hive-tasks 0.0.0-stage → 1.1.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 ADDED
@@ -0,0 +1,49 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses
5
+ [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [1.1.0] - 2026-12-03
8
+
9
+ ### Added
10
+
11
+ - Claim expiry: every claim records claimedUntil. A claimed card past that time is
12
+ reclaimable, so a crashed or starved agent is recovered without an operator.
13
+ - renew <id> [--ttl]: extend a claim without releasing it.
14
+ - done --verify: run the card acceptance command before finishing; the default stays
15
+ off, because a card is repository content and executing it is a code-execution path.
16
+ - resultCommit: done records the commit the work landed on (--sha or HEAD).
17
+ - tags, plus freeze semantics: while hive mode is freeze, ready returns only fix-tagged
18
+ cards, so the hotfix can run while the rest waits.
19
+ - plan --file: create a whole dependency tree in one tree write (one transaction).
20
+
21
+ ### Changed
22
+
23
+ - claim now sets claimedUntil alongside owner and attempt.
24
+
25
+ ### Tests
26
+
27
+ - 14 node:test scenarios: freeze filtering, claim expiry and reclaim, renew, acceptance
28
+ pass/fail, plan DAG creation, plus the earlier claim race and state machine cases.
29
+
30
+ ## [1.0.0] - 2026-12-03
31
+
32
+ ### Added
33
+
34
+ - Task cards in one git tree behind one ref (refs/hive/v1/tasks), updated with
35
+ compare-and-swap, so a claim has exactly one winner.
36
+ - State machine: pending, claimed, done, failed, blocked. ready is derived, never stored.
37
+ - Dependencies: after takes task ids; a card is ready only when all of them are done.
38
+ - Queue order: priority, then creation time. next returns the single best candidate.
39
+ - claim couples the card CAS with hive-consensus leases on the scope paths, with a
40
+ revert when a lease is refused.
41
+ - done releases the leases and can record a hive verdict note; fail keeps the attempt
42
+ counter; retry, block and unblock.
43
+ - Presence: claims update refs/hive/v1/board/<agent>, so hive board shows the work.
44
+ - Events in .hive/events.jsonl.
45
+ - SPEC.md and RFC-0001 (why one tree, why the queue is derived).
46
+ - 9 node:test scenarios, including two concurrent claims.
47
+
48
+ [1.1.0]: https://github.com/d86e/hive-tasks/releases/tag/v1.1.0
49
+ [1.0.0]: https://github.com/d86e/hive-tasks/releases/tag/v1.0.0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tommy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,140 @@
1
- # Temporary Holding Version
1
+ # hive-tasks
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **English** · [简体中文](README.zh-CN.md)
4
+
5
+ [![CI](https://github.com/d86e/hive-tasks/actions/workflows/ci.yml/badge.svg)](https://github.com/d86e/hive-tasks/actions/workflows/ci.yml)
6
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
7
+
8
+ **When several agents share a repository, "what is left to do, in what order, and who is doing it" lives in a chat prompt and dies with the session. hive-tasks makes it a query: every unit of work is a card in one git tree, behind one ref, with a state machine, dependencies and a role.**
9
+
10
+ ```
11
+ refs/hive/v1/tasks -> tree
12
+ auth-token-a1b2 -> blob (the card)
13
+ ```
14
+
15
+ No server, no database, no queue process. A claim is a compare-and-swap on that one ref, so exactly one agent wins, and the paths it touches are leased through [hive-consensus](https://github.com/d86e/hive-consensus) at the same time.
16
+
17
+ > ~700 lines, zero dependencies, git >= 2.40
18
+
19
+ **Built for**: agent teams that already coordinate with hive; a queen that hands out work; a dispatcher that needs a stable list instead of a conversation.
20
+
21
+ **Not built for**: single-agent projects; anyone who wants a scheduler (this package never starts an agent); work that has no shared repository.
22
+
23
+ ---
24
+
25
+ ## The problem
26
+
27
+ An agent crashes mid-run. Was task 4 done? Nobody knows. Another agent finishes a task and the queen's list is stale. Two agents pick up "the tests" because both read the same paragraph.
28
+
29
+ A card fixes that: it has an id, a state, an owner, an attempt count and a verdict. The answer to "what is left" is a command, not a memory.
30
+
31
+ ## Install
32
+
33
+ ```bash
34
+ npx hive-tasks init
35
+ npx hive-tasks add --title "auth takes an object" --role coder --scope src/auth.ts
36
+ ```
37
+
38
+ ## 60-second demo
39
+
40
+ ```bash
41
+ $ hive-tasks add --title "auth takes an object" --role coder --scope src/auth.ts
42
+ auth-takes-an-object-dea2 [pending] auth takes an object
43
+
44
+ $ hive-tasks ready
45
+ auth-takes-an-object-dea2 pending coder auth takes an object
46
+
47
+ $ hive-tasks claim auth-takes-an-object-dea2 --agent agent-A
48
+ auth-takes-an-object-dea2 [claimed] auth takes an object
49
+ role: coder owner: agent-A attempt: 1
50
+
51
+ $ hive-tasks claim auth-takes-an-object-dea2 --agent agent-B
52
+ hive-tasks: task auth-takes-an-object-dea2 is claimed # exit 2
53
+
54
+ $ hive-tasks add --title "token tests" --role tester --after auth-takes-an-object-dea2
55
+ $ hive-tasks ready
56
+ Nothing ready.
57
+
58
+ $ hive-tasks done auth-takes-an-object-dea2 --verdict pass
59
+ $ hive-tasks ready
60
+ token-tests-ba66 pending tester token tests
61
+ ```
62
+
63
+ ## Commands
64
+
65
+ | Command | Effect |
66
+ | --- | --- |
67
+ | add --title T [--role R] [--scope P] [--after ID] [--priority N] | create a card |
68
+ | list [--state S] [--role R] [--json] | every card |
69
+ | ready [--limit N] [--role R] [--json] | pending cards whose dependencies are done, ordered by priority then age |
70
+ | next [--role R] | the single best candidate |
71
+ | claim <id> --agent A [--ttl 5m] | card CAS, then hive leases on the scope |
72
+ | renew <id> [--ttl 5m] | extend a claim so a long run is not stolen |
73
+ | done <id> [--sha S] [--verdict pass\|fail] [--verify] | finish, release leases, record resultCommit; --verify runs the acceptance command first |
74
+ | plan --file plan.json | create a whole dependency tree in one transaction |
75
+ | fail <id> --reason R | failure is data: attempt stays |
76
+ | retry <id> | failed or blocked back to pending |
77
+ | block <id> --reason R / unblock <id> | park a card without losing it |
78
+
79
+ Exit codes: 0 done, 1 internal error, 2 refused (already claimed, wrong state, dependency missing, mode freeze, path busy).
80
+
81
+ ## How a claim works
82
+
83
+ 1. the card CAS moves pending -> claimed in the task tree (one winner);
84
+ 2. the scope paths are claimed as hive leases, all or nothing;
85
+ 3. if a lease is refused, the card is reverted to pending with a reason.
86
+
87
+ Reverting is another CAS we own, so a lost race never strands a lease. The card is the authority; the leases are the courtesy that keeps two agents out of the same file.
88
+
89
+ ## When an agent dies
90
+
91
+ Every claim carries claimedUntil (the --ttl, 5 minutes by default). Once it passes, the
92
+ card is **reclaimable**: the next agent that claims it takes over as if the card were
93
+ pending, incrementing attempt. No operator, no stale lock:
94
+
95
+ ~~~bash
96
+ $ hive-tasks claim slow-task-1a2b --agent agent-A --ttl 1s
97
+ $ # agent A dies here
98
+ $ sleep 2
99
+ $ hive-tasks claim slow-task-1a2b --agent agent-B # attempt 2, owner agent-B
100
+ ~~~
101
+
102
+ A long but healthy run calls renew to keep its claim.
103
+
104
+ ## Acceptance and freeze
105
+
106
+ A card may carry an acceptance command. It is **not** executed by default, because a card
107
+ is repository content and executing it would mean running code someone else pushed:
108
+
109
+ ~~~bash
110
+ $ hive-tasks add --title "auth takes an object" --acceptance "npm test -- auth"
111
+ $ hive-tasks done auth-takes-an-object-dea2 --verify # runs it, records resultCommit
112
+ $ hive-tasks done auth-takes-an-object-dea2 # records resultCommit only
113
+ ~~~
114
+
115
+ When hive mode is freeze, ready returns only cards tagged fix, so the hotfix can run while
116
+ the pipeline is red. Everything else waits.
117
+
118
+ ## Where it fits
119
+
120
+ | Project | Question |
121
+ | --- | --- |
122
+ | [merge-on-commit](https://github.com/d86e/merge-on-commit) | nobody lost their changes |
123
+ | [hive-consensus](https://github.com/d86e/hive-consensus) | who is doing what, may I touch this |
124
+ | hive-tasks | what is left, in which order, is it done |
125
+
126
+ ## Design
127
+
128
+ - [SPEC.md](SPEC.md): ref layout, card schema, state machine, claim algorithm, exit codes.
129
+ - [docs/RFC-0001-task-cards.md](docs/RFC-0001-task-cards.md): why one tree instead of one ref per task, and why the queue is derived.
130
+
131
+ ## Limits
132
+
133
+ - **Not a scheduler.** It never starts an agent; a dispatcher reads ready/next and spawns.
134
+ - **One ref means one writer at a time.** Claims serialize and retry; that is intended.
135
+ - **No per-card history.** Use .hive/events.jsonl, or turn on reflog for the one ref.
136
+ - **Single repository.** Cards do not cross repositories.
137
+
138
+ ## License
139
+
140
+ MIT
@@ -0,0 +1,136 @@
1
+ # hive-tasks
2
+
3
+ [English](README.md) · **简体中文**
4
+
5
+ [![CI](https://github.com/d86e/hive-tasks/actions/workflows/ci.yml/badge.svg)](https://github.com/d86e/hive-tasks/actions/workflows/ci.yml)
6
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
7
+
8
+ **多个 agent 共用一个仓库时,"还剩什么、什么顺序、谁在做"活在聊天记录里,会话一断就没了。hive-tasks 把它变成一次查询:每个工作单元都是一张卡,存在一棵 git 树、一个 ref 里,带状态机、依赖和角色。**
9
+
10
+ ```
11
+ refs/hive/v1/tasks -> 一棵树
12
+ auth-token-a1b2 -> blob(任务卡)
13
+ ```
14
+
15
+ 没有服务端、没有数据库、没有队列进程。认领就是对这个 ref 的一次 CAS,所以只有一个 agent 能赢;它要碰的路径同时在 [hive-consensus](https://github.com/d86e/hive-consensus) 里被租下。
16
+
17
+ > 约 700 行 · 零依赖 · git >= 2.40
18
+
19
+ **给谁用**:已经在用 hive 协调的 agent 团队;发任务的 queen;需要一个稳定列表而不是一段对话的调度器。
20
+
21
+ **不给谁用**:单 agent 项目;想要调度器的人(本包从不启动 agent);没有共享仓库的活。
22
+
23
+ ---
24
+
25
+ ## 问题
26
+
27
+ agent 跑到一半崩了。第 4 个任务做完了吗?没人知道。另一个 agent 完成了任务,queen 的清单已经过期。两个 agent 都读了同一段话,于是都去做"测试"。
28
+
29
+ 一张卡解决它:有 id、状态、owner、尝试次数和判定。"还剩什么"是一条命令,不是记忆。
30
+
31
+ ## 安装
32
+
33
+ ```bash
34
+ npx hive-tasks init
35
+ npx hive-tasks add --title "auth 改成对象入参" --role coder --scope src/auth.ts
36
+ ```
37
+
38
+ ## 60 秒体验
39
+
40
+ ```bash
41
+ $ hive-tasks add --title "auth 改成对象入参" --role coder --scope src/auth.ts
42
+ auth-takes-an-object-dea2 [pending] auth 改成对象入参
43
+
44
+ $ hive-tasks ready
45
+ auth-takes-an-object-dea2 pending coder auth 改成对象入参
46
+
47
+ $ hive-tasks claim auth-takes-an-object-dea2 --agent agent-A
48
+ auth-takes-an-object-dea2 [claimed] auth 改成对象入参
49
+ role: coder owner: agent-A attempt: 1
50
+
51
+ $ hive-tasks claim auth-takes-an-object-dea2 --agent agent-B
52
+ hive-tasks: task auth-takes-an-object-dea2 is claimed # 退出码 2
53
+
54
+ $ hive-tasks add --title "token 测试" --role tester --after auth-takes-an-object-dea2
55
+ $ hive-tasks ready
56
+ Nothing ready.
57
+
58
+ $ hive-tasks done auth-takes-an-object-dea2 --verdict pass
59
+ $ hive-tasks ready
60
+ token-tests-ba66 pending tester token 测试
61
+ ```
62
+
63
+ ## 命令
64
+
65
+ | 命令 | 效果 |
66
+ | --- | --- |
67
+ | add --title T [--role R] [--scope P] [--after ID] [--priority N] | 建卡 |
68
+ | list [--state S] [--role R] [--json] | 所有卡 |
69
+ | ready [--limit N] [--role R] [--json] | 依赖已完成的 pending 卡,按优先级、再按时间排序 |
70
+ | next [--role R] | 只给最优的那一张 |
71
+ | claim <id> --agent A [--ttl 5m] | 先卡片 CAS,再对 scope 拿 hive 租约 |
72
+ | renew <id> [--ttl 5m] | 续期认领,长任务不会被抢 |
73
+ | done <id> [--sha S] [--verdict pass\|fail] [--verify] | 完成、释放租约、记录 resultCommit;--verify 先跑验收命令 |
74
+ | plan --file plan.json | 一次事务创建整棵依赖树 |
75
+ | fail <id> --reason R | 失败是数据:attempt 保留 |
76
+ | retry <id> | failed 或 blocked 回到 pending |
77
+ | block <id> --reason R / unblock <id> | 挂起而不丢卡 |
78
+
79
+ 退出码:0 成功,1 内部错误,2 被拒(已被认领、状态不对、依赖缺失、模式 freeze、路径忙)。
80
+
81
+ ## claim 怎么走
82
+
83
+ 1. 卡片 CAS 把 pending 推到 claimed(唯一赢家);
84
+ 2. 对 scope 里的路径拿 hive 租约,要么全拿要么不拿;
85
+ 3. 租约被拒就把卡 CAS 回 pending 并记原因。
86
+
87
+ 回滚是我们自己持有的另一次 CAS,所以输掉竞争不会泄漏租约。**卡是权威,租约是礼貌**——它只是让两个 agent 不去碰同一个文件。
88
+
89
+ ## agent 中途死掉怎么办
90
+
91
+ 每次认领都带 claimedUntil(--ttl,默认 5 分钟)。时间一过,这张卡就是**可回收的**:下一个来认领的 agent 直接接管,attempt +1,不需要人工介入:
92
+
93
+ ~~~bash
94
+ $ hive-tasks claim slow-task-1a2b --agent agent-A --ttl 1s
95
+ $ # agent A 在这里崩溃
96
+ $ sleep 2
97
+ $ hive-tasks claim slow-task-1a2b --agent agent-B # attempt 2,owner agent-B
98
+ ~~~
99
+
100
+ 跑得久的健康任务用 renew 续期。
101
+
102
+ ## 验收与冻结
103
+
104
+ 卡片可以带一条验收命令。**默认不执行**——卡片是仓库内容,默认执行等于让别人 push 一段代码就能在你机器上跑:
105
+
106
+ ~~~bash
107
+ $ hive-tasks add --title "auth 改成对象入参" --acceptance "npm test -- auth"
108
+ $ hive-tasks done auth-takes-an-object-dea2 --verify # 执行验收,记录 resultCommit
109
+ $ hive-tasks done auth-takes-an-object-dea2 # 只记录 resultCommit
110
+ ~~~
111
+
112
+ hive 处于 freeze 模式时,ready 只返回带 fix 标签的卡,让热修能跑、其余等待。
113
+
114
+ ## 和另外两块的关系
115
+
116
+ | 项目 | 回答的问题 |
117
+ | --- | --- |
118
+ | [merge-on-commit](https://github.com/d86e/merge-on-commit) | 没有人的改动被丢掉 |
119
+ | [hive-consensus](https://github.com/d86e/hive-consensus) | 谁在干什么、我能不能碰这个 |
120
+ | hive-tasks | 还剩什么、什么顺序、做完了没有 |
121
+
122
+ ## 设计
123
+
124
+ - [SPEC.md](SPEC.md):ref 布局、卡片结构、状态机、claim 算法、退出码。
125
+ - [docs/RFC-0001-task-cards.md](docs/RFC-0001-task-cards.md):为什么用一棵树而不是每任务一个 ref,为什么队列是推导出来的。
126
+
127
+ ## 限制
128
+
129
+ - **不是调度器**:它从不启动 agent;调度器读 ready/next 再 spawn。
130
+ - **一个 ref 意味着单写者**:认领会串行并重试,这是刻意的。
131
+ - **没有逐卡历史**:用 .hive/events.jsonl,或给这一个 ref 打开 reflog。
132
+ - **单仓库**:卡片不跨仓库。
133
+
134
+ ## 许可
135
+
136
+ MIT
package/SPEC.md ADDED
@@ -0,0 +1,187 @@
1
+ # hive-tasks protocol (draft)
2
+
3
+ Status: draft, not implemented. Target: 1.0.0.
4
+
5
+ ## 1. Scope
6
+
7
+ hive-tasks stores work items for a team that coordinates through hive-consensus. It
8
+ defines:
9
+
10
+ - where a task lives (a git ref, same namespace family as hive);
11
+ - the task blob and its state machine;
12
+ - how a task is claimed, finished and failed, with compare-and-swap;
13
+ - what "ready" means, and the CLI surface a dispatcher consumes.
14
+
15
+ It does not start agents, split goals, run tests, or store patches.
16
+
17
+ ## 2. Namespace
18
+
19
+ The whole board is one git tree, behind one ref:
20
+
21
+ ```
22
+ refs/hive/v1/tasks -> tree
23
+ <id> -> blob (the task JSON)
24
+ ```
25
+
26
+ <id> is the tree entry name: a short slug, lowercase letters, digits and dashes, 4 to
27
+ 40 characters, generated from the title and a random suffix (for example
28
+ auth-token-a1b2). It is immutable once created.
29
+
30
+ Why a tree and not one ref per task:
31
+
32
+ - a mutation reads the tree, replaces one entry, writes a new tree and moves the ref
33
+ with compare-and-swap - one atomic operation, and several tasks can change at once;
34
+ - the number of refs stays at one, so for-each-ref and packed-refs do not grow with the
35
+ backlog;
36
+ - the board pushes and fetches as a single object.
37
+
38
+ The cost is that all task mutations serialize on one ref: two claims racing means one
39
+ wins and the other retries. For a work queue that is the behavior we want.
40
+
41
+ Implementation sketch (plumbing, no working tree involved):
42
+
43
+ ```bash
44
+ GIT_INDEX_FILE=tmp git read-tree refs/hive/v1/tasks # or an empty tree at first
45
+ GIT_INDEX_FILE=tmp git update-index --add --cacheinfo 100644,<blob>,<id>
46
+ GIT_INDEX_FILE=tmp git write-tree # new tree
47
+ git update-ref refs/hive/v1/tasks <new-tree> <old-tree>
48
+ ```
49
+
50
+ ## 3. Task blob
51
+
52
+ ```json
53
+ {
54
+ "v": 1,
55
+ "id": "auth-token-a1b2",
56
+ "title": "auth() takes an object",
57
+ "goal": "Change auth(token) to auth({ token }) and update call sites.",
58
+ "role": "coder",
59
+ "scope": ["src/auth.ts", "src/token.ts"],
60
+ "after": ["schema-migration-7c1d"],
61
+ "state": "pending",
62
+ "owner": null,
63
+ "attempt": 0,
64
+ "priority": 0,
65
+ "tags": [],
66
+ "acceptance": "",
67
+ "claimedUntil": null,
68
+ "resultCommit": null,
69
+ "verdict": null,
70
+ "createdBy": "queen",
71
+ "createdAt": "2026-12-03T15:00:00.000Z",
72
+ "updatedAt": "2026-12-03T15:00:00.000Z"
73
+ }
74
+ ```
75
+
76
+ | Field | Meaning |
77
+ | --- | --- |
78
+ | goal | what the worker should achieve; free text, no format |
79
+ | role | who may claim: a role name the team agrees on (coder, tester, reviewer, ...) |
80
+ | scope | paths the task is expected to touch; used to claim hive leases |
81
+ | after | ids that must be done before this becomes ready |
82
+ | state | see below |
83
+ | owner | agent id while claimed |
84
+ | attempt | incremented on every claim; used to stop retry loops |
85
+ | verdict | pass or fail, copied from the hive verdict when done |
86
+ | tags | free labels; "fix" is special (see mode) |
87
+ | acceptance | optional shell command; only run by done --verify |
88
+ | claimedUntil | expiry of the current claim; a claimed card past it is reclaimable |
89
+ | resultCommit | the commit recorded when the card was done |
90
+
91
+ ## 4. State machine
92
+
93
+ ```
94
+ (dependencies done)
95
+ pending ------------------------> ready
96
+ ^ | claim
97
+ | retry v
98
+ failed <--------- claimed ----> done
99
+ ^ |
100
+ +--- blocked <---+ (timeout, conflict, manual)
101
+ ```
102
+
103
+ - pending: exists, dependencies not satisfied (or no capacity to run it).
104
+ - ready: pending with every id in after in state done. Computed, never stored.
105
+ - claimed: a dispatcher claimed it; owner and attempt are set.
106
+ - done: owner finished and (optionally) a verdict was recorded.
107
+ - failed: the run failed; retry moves it back to pending with attempt preserved.
108
+ - blocked: cannot proceed (conflict, missing dependency, manual hold).
109
+
110
+ Stored states are pending, claimed, done, failed, blocked. ready is always computed.
111
+
112
+ A claimed card carries claimedUntil. Once that time passes the card is **reclaimable**:
113
+ claim may take it over exactly as if it were pending, incrementing attempt. This is how
114
+ a crashed or starved agent is recovered without an operator.
115
+
116
+ Every transition is a compare-and-swap on the task ref: read the blob, verify the
117
+ current state, write the new blob with the ref's current sha as the expected value.
118
+ Two claimants therefore cannot both win.
119
+
120
+ ## 5. Ready computation
121
+
122
+ A task is ready when:
123
+
124
+ 1. state is pending;
125
+ 2. every id in after exists and is done;
126
+ 3. hive mode is free, or the card is tagged "fix" (the fix must be able to run while the
127
+ pipeline is frozen).
128
+
129
+ A missing dependency id is a data error: report it, do not treat it as satisfied.
130
+
131
+ The queue is that set, sorted by priority (descending) and then createdAt (ascending).
132
+ There is no stored queue and no head pointer: ordering is a query over the task tree, so
133
+ it cannot drift from the cards. Two dispatchers that read the list at the same moment
134
+ see the same order; the claim CAS still gives exactly one winner per card.
135
+
136
+ ## 6. CLI
137
+
138
+ ```
139
+ hive-tasks add --title T --role coder --scope src/auth.ts [--scope ...] [--after ID]... [--goal G]
140
+ hive-tasks list [--json] [--state S] [--role R]
141
+ hive-tasks ready [--json] [--limit N] [--role R]
142
+ hive-tasks next [--role R] [--json] # the single best candidate, or null
143
+ hive-tasks show <id> [--json]
144
+ hive-tasks claim <id> --agent A [--ttl 5m]
145
+ hive-tasks done <id> [--sha S] [--verdict pass|fail]
146
+ hive-tasks fail <id> --reason R
147
+ hive-tasks retry <id>
148
+ hive-tasks block <id> --reason R
149
+ hive-tasks unblock <id>
150
+ ```
151
+
152
+ Exit codes: 0 success; 1 internal error; 2 refused (already claimed, wrong state,
153
+ dependency missing, mode freeze).
154
+
155
+ claim couples the card with the hive leases, card first:
156
+
157
+ 1. CAS the card from pending to claimed (this is what picks the single winner);
158
+ 2. claim every scope path as a hive lease, all or nothing;
159
+ 3. if a lease is refused, CAS the card back to pending with a reason and exit 2.
160
+
161
+ Card-first is deliberate: a lost card race costs nothing, while lease-first would leave
162
+ held leases behind when the card CAS loses. Reverting the card is another CAS we own, so
163
+ no state leaks.
164
+
165
+ done releases the leases and records the verdict. fail releases the leases and keeps the
166
+ attempt counter. retry accepts failed or blocked and returns the card to pending. block
167
+ accepts any state; unblock accepts blocked.
168
+
169
+ ## 7. Events
170
+
171
+ Each command appends one line to .hive/events.jsonl:
172
+
173
+ ```json
174
+ { "ts": "...", "actor": "worker-3", "kind": "task_claim", "task": "auth-token-a1b2", "attempt": 1 }
175
+ ```
176
+
177
+ kinds: task_add, task_claim, task_done, task_fail, task_retry, task_block, task_unblock.
178
+
179
+ ## 8. Requirements
180
+
181
+ - hive-consensus >= 1.2.0 (leases, board, mode, verdict, events).
182
+ - git >= 2.40.
183
+ - No network, no database, no daemon.
184
+
185
+ ## 9. Open questions
186
+
187
+ See docs/RFC-0001-task-cards.md section "Open questions".
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ import { run } from "../src/cli.js";
3
+
4
+ try {
5
+ run(process.argv.slice(2));
6
+ } catch (error) {
7
+ process.stderr.write("hive-tasks: " + (error && error.message ? error.message : String(error)) + "\n");
8
+ process.exit(1);
9
+ }
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "hive-tasks",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.1.0",
4
+ "description": "Task cards for agent teams: one git tree behind one ref, with a state machine, dependencies and hive leases.",
5
+ "type": "module",
6
+ "bin": {
7
+ "hive-tasks": "bin/hive-tasks.js"
8
+ },
9
+ "files": [
10
+ "bin",
11
+ "src",
12
+ "SPEC.md",
13
+ "README.md",
14
+ "README.zh-CN.md",
15
+ "LICENSE",
16
+ "CHANGELOG.md"
17
+ ],
18
+ "engines": {
19
+ "node": ">=20"
20
+ },
21
+ "scripts": {
22
+ "test": "node --test test/*.test.mjs",
23
+ "lint": "node scripts/lint.mjs"
24
+ },
25
+ "keywords": [
26
+ "git",
27
+ "agents",
28
+ "tasks",
29
+ "queue",
30
+ "coordination",
31
+ "multi-agent",
32
+ "ai-agents",
33
+ "git-refs"
34
+ ],
35
+ "license": "MIT",
36
+ "author": "Tommy <thf85@qq.com>",
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "git+https://github.com/d86e/hive-tasks.git"
40
+ },
41
+ "bugs": {
42
+ "url": "https://github.com/d86e/hive-tasks/issues"
43
+ },
44
+ "homepage": "https://github.com/d86e/hive-tasks#readme"
45
+ }
package/src/cli.js ADDED
@@ -0,0 +1,340 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { git, out } from "./git.js";
5
+ import { ensureState, repoInfo } from "./repo.js";
6
+ import { listRaw, mutate, readTask } from "./store.js";
7
+ import { create, isReady, isReclaimable, order, transition } from "./task.js";
8
+ import { addVerdict, claimLeases, parseTtl, readMode, releaseLeases, toKey } from "./lease.js";
9
+ import { append } from "./events.js";
10
+
11
+ const VERSION = JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
12
+
13
+ const USAGE = [
14
+ "hive-tasks " + VERSION,
15
+ "",
16
+ "USAGE",
17
+ " hive-tasks init create .hive/ and the AGENTS.md section",
18
+ " hive-tasks add --title T [--role R] [--scope P]... [--after ID]... [--tag T] [--priority N]",
19
+ " [--goal G] [--acceptance CMD]",
20
+ " hive-tasks list [--json] [--state S] [--role R]",
21
+ " hive-tasks show <id> [--json]",
22
+ " hive-tasks ready [--json] [--limit N] [--role R]",
23
+ " hive-tasks next [--role R] [--json] the single best candidate",
24
+ " hive-tasks claim <id> --agent A [--ttl 5m] card CAS, then hive leases",
25
+ " hive-tasks renew <id> [--ttl 5m] extend a claim",
26
+ " hive-tasks plan --file plan.json create a whole DAG in one transaction",
27
+ " hive-tasks done <id> [--sha S] [--verdict pass|fail] [--verify]",
28
+ " hive-tasks fail <id> --reason R",
29
+ " hive-tasks retry <id>",
30
+ " hive-tasks block <id> --reason R | unblock <id>",
31
+ "",
32
+ "ENVIRONMENT",
33
+ " HIVE_AGENT=name identity used for claims",
34
+ ].join("\n");
35
+
36
+ function fail(message, code = 1) {
37
+ process.stderr.write("hive-tasks: " + message + "\n");
38
+ process.exit(code);
39
+ }
40
+
41
+ function value(argv, index, flag) {
42
+ const next = argv[index + 1];
43
+ if (next === undefined) fail(flag + " needs a value", 2);
44
+ return next;
45
+ }
46
+
47
+ function parse(argv) {
48
+ const out = { args: [], scopes: [], after: [], tags: [], json: false, reason: null, agent: null, ttl: null, verdict: null, sha: null, state: null, role: null, limit: null, title: null, goal: null, priority: 0, force: false, acceptance: null, verify: false, file: null };
49
+ for (let i = 0; i < argv.length; i++) {
50
+ const arg = argv[i];
51
+ if (arg === "--json") out.json = true;
52
+ else if (arg === "--force") out.force = true;
53
+ else if (arg === "--scope") out.scopes.push(value(argv, i++, arg));
54
+ else if (arg === "--after") out.after.push(value(argv, i++, arg));
55
+ else if (arg === "--tag") out.tags.push(value(argv, i++, arg));
56
+ else if (arg === "--acceptance") out.acceptance = value(argv, i++, arg);
57
+ else if (arg === "--verify") out.verify = true;
58
+ else if (arg === "--file") out.file = value(argv, i++, arg);
59
+ else if (arg === "--reason") out.reason = value(argv, i++, arg);
60
+ else if (arg === "--agent") out.agent = value(argv, i++, arg);
61
+ else if (arg === "--ttl") out.ttl = value(argv, i++, arg);
62
+ else if (arg === "--verdict") out.verdict = value(argv, i++, arg);
63
+ else if (arg === "--sha") out.sha = value(argv, i++, arg);
64
+ else if (arg === "--state") out.state = value(argv, i++, arg);
65
+ else if (arg === "--role") out.role = value(argv, i++, arg);
66
+ else if (arg === "--limit") out.limit = Number(value(argv, i++, arg));
67
+ else if (arg === "--title") out.title = value(argv, i++, arg);
68
+ else if (arg === "--goal") out.goal = value(argv, i++, arg);
69
+ else if (arg === "--priority") out.priority = Number(value(argv, i++, arg));
70
+ else if (arg.startsWith("-")) fail("unknown option: " + arg, 2);
71
+ else out.args.push(arg);
72
+ }
73
+ return out;
74
+ }
75
+
76
+ function identity(repo, explicit) {
77
+ const name = explicit || process.env.HIVE_AGENT || git(["config", "--get", "hive.agent"], { cwd: repo.top, allowFail: true }).stdout.trim();
78
+ if (!name) fail("an identity is required (--agent, HIVE_AGENT, or git config hive.agent)", 2);
79
+ return name;
80
+ }
81
+
82
+ function board(repo) {
83
+ return listRaw(repo).map((entry) => entry.value);
84
+ }
85
+
86
+ function byId(tasks) {
87
+ return new Map(tasks.map((task) => [task.id, task]));
88
+ }
89
+
90
+ function readyList(repo, tasks, { role } = {}) {
91
+ const free = readMode(repo) === "free";
92
+ const map = byId(tasks);
93
+ return tasks
94
+ .filter((task) => (!role || task.role === role) && isReady(task, map, { modeFree: free }))
95
+ .sort(order);
96
+ }
97
+
98
+ function publishPresence(repo, { agent, task, state, files }) {
99
+ const key = toKey(agent);
100
+ const ref = "refs/hive/v1/board/" + key + "/__key__";
101
+ const value = { v: 1, agent, task: task ? task.id : "", state, files: files || [], updatedAt: new Date().toISOString(), host: "hive-tasks", pid: process.pid };
102
+ const blob = out(["hash-object", "-w", "--stdin"], { cwd: repo.top, input: JSON.stringify(value) });
103
+ const current = git(["rev-parse", "--verify", "--quiet", ref], { cwd: repo.top, allowFail: true }).stdout.trim();
104
+ git(["update-ref", ref, blob, current || "0".repeat(blob.length)], { cwd: repo.top, allowFail: true });
105
+ }
106
+
107
+ function printTask(task, json) {
108
+ if (json) return process.stdout.write(JSON.stringify(task, null, 2) + "\n");
109
+ const indent = " ";
110
+ process.stdout.write(task.id + " [" + task.state + "] " + task.title + "\n");
111
+ process.stdout.write(indent + "role: " + task.role + " owner: " + (task.owner || "-") + " attempt: " + task.attempt + "\n");
112
+ if (task.scope.length) process.stdout.write(indent + "scope: " + task.scope.join(", ") + "\n");
113
+ if (task.after.length) process.stdout.write(indent + "after: " + task.after.join(", ") + "\n");
114
+ if (task.goal) process.stdout.write(indent + "goal: " + task.goal + "\n");
115
+ }
116
+
117
+ function run(argv) {
118
+ const command = argv[0];
119
+ const options = parse(argv.slice(1));
120
+ const repo = repoInfo(process.cwd());
121
+
122
+ if (!command || command === "-h" || command === "--help" || command === "help") return process.stdout.write(USAGE + "\n");
123
+ if (command === "-V" || command === "--version" || command === "version") return process.stdout.write(VERSION + "\n");
124
+
125
+ if (command === "init") {
126
+ ensureState(repo);
127
+ const file = path.join(repo.top, "AGENTS.md");
128
+ const marker = "<!-- hive-tasks:start -->";
129
+ const snippet = [marker, "## Tasks (hive-tasks)", "", "- Look for work: hive-tasks ready", "- Take one: hive-tasks claim <id> --agent <name>", "- Finish: hive-tasks done <id>", "<!-- hive-tasks:end -->", ""].join("\n");
130
+ const current = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "";
131
+ if (!current.includes(marker)) fs.writeFileSync(file, current.replace(/\s*$/, "") + (current ? "\n\n" : "") + snippet);
132
+ process.stdout.write("initialised " + path.relative(repo.top, repo.stateDir) + "\n");
133
+ return;
134
+ }
135
+
136
+ if (command === "plan") {
137
+ const raw = options.file ? fs.readFileSync(options.file, "utf8") : fs.readFileSync(0, "utf8");
138
+ let plan;
139
+ try { plan = JSON.parse(raw); } catch { fail("plan is not valid JSON", 2); }
140
+ if (!Array.isArray(plan) || plan.length === 0) fail("plan must be a non-empty JSON array", 2);
141
+
142
+ const keys = new Map();
143
+ const drafts = plan.map((entry) => {
144
+ if (!entry || !entry.title) fail("every plan entry needs a title", 2);
145
+ const task = create({
146
+ title: entry.title,
147
+ goal: entry.goal,
148
+ role: entry.role,
149
+ scope: entry.scope || [],
150
+ after: [],
151
+ priority: entry.priority,
152
+ tags: entry.tags || [],
153
+ acceptance: entry.acceptance || "",
154
+ createdBy: options.agent || process.env.HIVE_AGENT || "planner",
155
+ });
156
+ if (entry.key) keys.set(entry.key, task.id);
157
+ return { entry, task };
158
+ });
159
+ for (const draft of drafts) {
160
+ draft.task.after = (draft.entry.after || []).map((dep) => keys.get(dep) || dep);
161
+ }
162
+
163
+ const result = mutate(repo, (tasks) => {
164
+ const known = new Set([...tasks.map((task) => task.id), ...drafts.map((draft) => draft.task.id)]);
165
+ for (const draft of drafts) {
166
+ for (const dep of draft.task.after) if (!known.has(dep)) throw new Error("unknown dependency: " + dep);
167
+ }
168
+ return [...tasks, ...drafts.map((draft) => draft.task)];
169
+ });
170
+ if (!result.ok) fail("could not write the task board");
171
+ append(repo, { actor: "planner", kind: "task_plan", count: drafts.length });
172
+ for (const draft of drafts) process.stdout.write(draft.task.id + " " + draft.task.title + "\n");
173
+ return;
174
+ }
175
+
176
+ if (command === "renew") {
177
+ const id = options.args[0];
178
+ if (!id) fail("renew needs a task id", 2);
179
+ const agent = identity(repo, options.agent);
180
+ const ttlMs = parseTtl(options.ttl);
181
+ const current = readTask(repo, id);
182
+ if (!current) fail("no such task: " + id, 2);
183
+ if (current.state !== "claimed" || current.owner !== agent) fail("task " + id + " is not claimed by " + agent, 2);
184
+ const result = mutate(repo, (tasks) => tasks.map((entry) => (entry.id === id ? { ...entry, claimedUntil: new Date(Date.now() + ttlMs).toISOString(), updatedAt: new Date().toISOString() } : entry)));
185
+ if (!result.ok) fail("could not renew " + id);
186
+ append(repo, { actor: agent, kind: "task_renew", task: id });
187
+ process.stdout.write(id + " renewed for " + Math.round(ttlMs / 1000) + "s\n");
188
+ return;
189
+ }
190
+
191
+ if (command === "add") {
192
+ if (!options.title) fail("--title is required", 2);
193
+ const task = create({
194
+ title: options.title,
195
+ goal: options.goal,
196
+ role: options.role,
197
+ scope: options.scopes,
198
+ after: options.after,
199
+ priority: options.priority,
200
+ tags: options.tags,
201
+ acceptance: options.acceptance || "",
202
+ createdBy: options.agent || process.env.HIVE_AGENT || "unknown",
203
+ });
204
+ const result = mutate(repo, (tasks) => {
205
+ const ids = byId(tasks);
206
+ for (const dep of task.after) if (!ids.has(dep)) throw new Error("unknown dependency: " + dep);
207
+ return [...tasks, task];
208
+ });
209
+ if (!result.ok) fail("could not write the task board (too much contention)");
210
+ append(repo, { actor: task.createdBy, kind: "task_add", task: task.id });
211
+ return printTask(task, options.json);
212
+ }
213
+
214
+ if (command === "list" || command === "ready") {
215
+ const tasks = board(repo);
216
+ const selected = command === "ready"
217
+ ? readyList(repo, tasks, { role: options.role })
218
+ : tasks
219
+ .filter((task) => (!options.state || task.state === options.state) && (!options.role || task.role === options.role))
220
+ .sort(order);
221
+ const limited = options.limit ? selected.slice(0, options.limit) : selected;
222
+ if (options.json) return process.stdout.write(JSON.stringify(limited, null, 2) + "\n");
223
+ if (limited.length === 0) return process.stdout.write(command === "ready" ? "Nothing ready.\n" : "No tasks.\n");
224
+ for (const task of limited) process.stdout.write(task.id.padEnd(34) + task.state.padEnd(9) + task.role.padEnd(11) + task.title + "\n");
225
+ return;
226
+ }
227
+
228
+ if (command === "next") {
229
+ const [first] = readyList(repo, board(repo), { role: options.role });
230
+ if (!first) {
231
+ if (options.json) process.stdout.write("null\n");
232
+ else process.stdout.write("Nothing ready.\n");
233
+ return;
234
+ }
235
+ return printTask(first, options.json);
236
+ }
237
+
238
+ if (command === "show") {
239
+ const id = options.args[0];
240
+ if (!id) fail("show needs a task id", 2);
241
+ const task = readTask(repo, id);
242
+ if (!task) fail("no such task: " + id, 2);
243
+ return printTask(task, options.json);
244
+ }
245
+
246
+ if (command === "claim") {
247
+ const id = options.args[0];
248
+ if (!id) fail("claim needs a task id", 2);
249
+ const agent = identity(repo, options.agent);
250
+ const ttlMs = parseTtl(options.ttl);
251
+
252
+ const preview = readTask(repo, id);
253
+ if (!preview) fail("no such task: " + id, 2);
254
+ if (readMode(repo) === "freeze" && !options.force && !(preview.tags || []).includes("fix")) {
255
+ fail("mode is freeze: only fix-tagged cards may be claimed (use --force to override)", 2);
256
+ }
257
+ const reclaim = isReclaimable(preview);
258
+ if (preview.state !== "pending" && !reclaim) fail("task " + id + " is " + preview.state, 2);
259
+ if (!isReady(preview, byId(board(repo)), { modeFree: true })) fail("task " + id + " is not ready (dependencies or mode)", 2);
260
+
261
+ let claimed = null;
262
+ try {
263
+ mutate(repo, (tasks) => {
264
+ const map = byId(tasks);
265
+ const task = map.get(id);
266
+ if (!task) throw new Error("no such task: " + id);
267
+ if (task.state !== "pending" && !isReclaimable(task)) throw new Error("task " + id + " is " + task.state);
268
+ if (!isReady(task, map, { modeFree: true })) throw new Error("task " + id + " is not ready (dependencies or mode)");
269
+ claimed = transition(task, "claimed", {
270
+ owner: agent,
271
+ attempt: (task.attempt || 0) + 1,
272
+ reason: null,
273
+ claimedUntil: new Date(Date.now() + ttlMs).toISOString(),
274
+ });
275
+ return tasks.map((entry) => (entry.id === id ? claimed : entry));
276
+ });
277
+ } catch (error) {
278
+ fail(error.message, 2);
279
+ }
280
+
281
+ if (!claimed) fail("could not claim " + id, 2);
282
+
283
+ const leases = claimLeases(repo, { paths: claimed.scope, agent, ttlMs, taskId: claimed.id });
284
+ if (leases.granted === false) {
285
+ const holder = leases.denied[0];
286
+ mutate(repo, (tasks) => tasks.map((entry) => (entry.id === id ? transition(entry, "pending", { owner: null, reason: "lease held by " + holder.agent }) : entry)));
287
+ const detail = holder ? " (" + holder.agent + " holds " + holder.key + ")" : "";
288
+ fail("could not claim " + id + ": path busy" + detail, 2);
289
+ }
290
+
291
+ publishPresence(repo, { agent, task: claimed, state: "working", files: claimed.scope });
292
+ append(repo, { actor: agent, kind: "task_claim", task: claimed.id, attempt: claimed.attempt });
293
+ return printTask(claimed, options.json);
294
+ }
295
+
296
+ if (command === "done" || command === "fail" || command === "retry" || command === "block" || command === "unblock") {
297
+ const id = options.args[0];
298
+ if (!id) fail(command + " needs a task id", 2);
299
+ const agent = options.agent || process.env.HIVE_AGENT || "unknown";
300
+ const current = readTask(repo, id);
301
+ if (!current) fail("no such task: " + id, 2);
302
+
303
+ if ((command === "done" || command === "fail") && current.state !== "claimed") fail("task " + id + " is " + current.state + ", not claimed", 2);
304
+ if (command === "retry" && current.state !== "failed" && current.state !== "blocked") fail("task " + id + " is " + current.state + ", not failed or blocked", 2);
305
+ if (command === "unblock" && current.state !== "blocked") fail("task " + id + " is " + current.state + ", not blocked", 2);
306
+
307
+ if (command === "done" && options.verify) {
308
+ if (!current.acceptance) fail("task " + id + " has no acceptance command", 2);
309
+ const run = spawnSync("sh", ["-c", current.acceptance], { cwd: repo.top, encoding: "utf8" });
310
+ if (run.stdout) process.stdout.write(run.stdout);
311
+ if (run.stderr) process.stderr.write(run.stderr);
312
+ if (run.status !== 0) fail("acceptance failed for " + id, 1);
313
+ }
314
+
315
+ const head = git(["rev-parse", "--verify", "--quiet", "HEAD"], { cwd: repo.top, allowFail: true }).stdout.trim();
316
+ const targetState = command === "done" ? "done" : command === "fail" ? "failed" : command === "block" ? "blocked" : "pending";
317
+ const patch = {
318
+ owner: null,
319
+ verdict: command === "done" ? (options.verdict || null) : current.verdict,
320
+ reason: options.reason || null,
321
+ resultCommit: command === "done" ? (options.sha || head || null) : current.resultCommit,
322
+ claimedUntil: null,
323
+ };
324
+
325
+ const result = mutate(repo, (tasks) => tasks.map((entry) => (entry.id === id ? transition(entry, targetState, patch) : entry)));
326
+ if (!result.ok) fail("could not update " + id);
327
+
328
+ if (current.state === "claimed") releaseLeases(repo, { paths: current.scope, agent: current.owner || agent });
329
+ if (command === "done" && options.verdict && options.sha) {
330
+ addVerdict(repo, { sha: options.sha, result: options.verdict });
331
+ }
332
+ publishPresence(repo, { agent, task: current, state: targetState === "done" ? "idle" : "working", files: [] });
333
+ append(repo, { actor: agent, kind: "task_" + command, task: id, reason: options.reason || undefined });
334
+ return printTask(readTask(repo, id), options.json);
335
+ }
336
+
337
+ fail("unknown command: " + command, 2);
338
+ }
339
+
340
+ export { run };
package/src/events.js ADDED
@@ -0,0 +1,12 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+
4
+ /** Append one event to .hive/events.jsonl. Best effort, never fatal. */
5
+ export function append(repo, event) {
6
+ try {
7
+ fs.mkdirSync(repo.stateDir, { recursive: true });
8
+ fs.appendFileSync(path.join(repo.stateDir, "events.jsonl"), JSON.stringify({ ts: new Date().toISOString(), ...event }) + "\n");
9
+ } catch {
10
+ // telemetry must not break a command
11
+ }
12
+ }
package/src/git.js ADDED
@@ -0,0 +1,26 @@
1
+ import { spawnSync } from "node:child_process";
2
+
3
+ /** Run git. Throws on spawn failure, or on a non-zero exit unless allowFail. */
4
+ export function git(args, { cwd, env, input, allowFail = false } = {}) {
5
+ const result = spawnSync("git", args, {
6
+ cwd,
7
+ env: env ? { ...process.env, ...env } : process.env,
8
+ input,
9
+ encoding: "utf8",
10
+ maxBuffer: 64 * 1024 * 1024,
11
+ });
12
+ if (result.error) throw result.error;
13
+ if (!allowFail && result.status !== 0) {
14
+ const detail = (result.stderr || result.stdout || "").trim();
15
+ throw new Error("git " + args.join(" ") + " failed (exit " + result.status + ")" + (detail ? ": " + detail : ""));
16
+ }
17
+ return result;
18
+ }
19
+
20
+ export function out(args, opts) {
21
+ return git(args, opts).stdout.trim();
22
+ }
23
+
24
+ export function ok(args, opts) {
25
+ return git(args, { ...opts, allowFail: true }).status === 0;
26
+ }
package/src/lease.js ADDED
@@ -0,0 +1,95 @@
1
+ import { git, out } from "./git.js";
2
+
3
+ export const NS = "refs/hive/v1";
4
+ export const KEY_LEAF = "__key__";
5
+ export const MODE_REF = NS + "/mode";
6
+ export const VERDICT_NOTES = "hive/verdict";
7
+
8
+ function encodeSegment(segment) {
9
+ let value = encodeURIComponent(segment);
10
+ if (value.startsWith(".")) value = "%2E" + value.slice(1);
11
+ if (/\.lock$/i.test(segment)) value = value.replace(/\.lock$/i, "%2Elock");
12
+ return value;
13
+ }
14
+
15
+ export function toKey(path) {
16
+ const parts = String(path).trim().split("/").filter((part) => part && part !== ".");
17
+ if (parts.length === 0 || parts.some((part) => part === "..")) throw new Error("invalid path: " + path);
18
+ return parts.map(encodeSegment).join("/");
19
+ }
20
+
21
+ export function leaseRef(key) {
22
+ return NS + "/lease/" + key + "/" + KEY_LEAF;
23
+ }
24
+
25
+ export function parseTtl(input) {
26
+ if (!input) return 5 * 60 * 1000;
27
+ const match = String(input).match(/^(\d+)([smh])?$/);
28
+ if (!match) throw new Error("invalid ttl: " + input);
29
+ return Number(match[1]) * ({ s: 1000, m: 60000, h: 3600000 }[match[2]] || 1000);
30
+ }
31
+
32
+ function readBlob(repo, ref) {
33
+ const rev = git(["rev-parse", "--verify", "--quiet", ref], { cwd: repo.top, allowFail: true });
34
+ if (rev.status !== 0) return null;
35
+ try { return JSON.parse(out(["cat-file", "blob", rev.stdout.trim()], { cwd: repo.top })); } catch { return null; }
36
+ }
37
+
38
+ export function readMode(repo) {
39
+ return (readBlob(repo, MODE_REF) || { mode: "free" }).mode;
40
+ }
41
+
42
+ /** Claim every scope path or none of them. An expired lease is taken over. */
43
+ export function claimLeases(repo, { paths, agent, ttlMs, taskId }) {
44
+ const keys = paths.map(toKey);
45
+ if (keys.length === 0) return { granted: true, denied: [] };
46
+
47
+ const now = Date.now();
48
+ const lines = ["start"];
49
+ const denied = [];
50
+
51
+ for (const key of keys) {
52
+ const ref = leaseRef(key);
53
+ const current = readBlob(repo, ref);
54
+ if (current && current.agent !== agent && Date.parse(current.expiresAt) > now) {
55
+ denied.push({ key, agent: current.agent, expiresAt: current.expiresAt });
56
+ continue;
57
+ }
58
+ const value = {
59
+ v: 1,
60
+ agent,
61
+ task: taskId || "",
62
+ key,
63
+ startedAt: new Date(now).toISOString(),
64
+ expiresAt: new Date(now + ttlMs).toISOString(),
65
+ };
66
+ const blob = out(["hash-object", "-w", "--stdin"], { cwd: repo.top, input: JSON.stringify(value) });
67
+ const currentSha = git(["rev-parse", "--verify", "--quiet", ref], { cwd: repo.top, allowFail: true }).stdout.trim();
68
+ lines.push("update " + ref + " " + blob + " " + (currentSha || "0".repeat(blob.length)));
69
+ }
70
+
71
+ if (denied.length > 0) return { granted: false, denied };
72
+
73
+ lines.push("prepare", "commit");
74
+ const result = git(["update-ref", "--stdin"], { cwd: repo.top, input: lines.join("\n") + "\n", allowFail: true });
75
+ return { granted: result.status === 0, denied: [], stderr: (result.stderr || "").trim() };
76
+ }
77
+
78
+ export function releaseLeases(repo, { paths, agent }) {
79
+ const released = [];
80
+ for (const key of paths.map(toKey)) {
81
+ const ref = leaseRef(key);
82
+ const current = readBlob(repo, ref);
83
+ if (!current || current.agent !== agent) continue;
84
+ const sha = out(["rev-parse", ref], { cwd: repo.top });
85
+ if (git(["update-ref", "-d", ref, sha], { cwd: repo.top, allowFail: true }).status === 0) released.push(key);
86
+ }
87
+ return released;
88
+ }
89
+
90
+ export function addVerdict(repo, { sha, result, note }) {
91
+ const target = sha ? out(["rev-parse", sha], { cwd: repo.top }) : out(["rev-parse", "HEAD"], { cwd: repo.top });
92
+ const text = result + (note ? ": " + note : "");
93
+ git(["notes", "--ref=" + VERDICT_NOTES, "add", "-f", "-m", text, target], { cwd: repo.top });
94
+ return { sha: target, text };
95
+ }
package/src/repo.js ADDED
@@ -0,0 +1,17 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { out } from "./git.js";
4
+
5
+ export function repoInfo(cwd = process.cwd()) {
6
+ const gitDir = out(["rev-parse", "--absolute-git-dir"], { cwd });
7
+ const top = out(["rev-parse", "--show-toplevel"], { cwd });
8
+ return { cwd, gitDir, top, stateDir: path.join(top, ".hive") };
9
+ }
10
+
11
+ export function ensureState(repo) {
12
+ fs.mkdirSync(path.join(repo.stateDir, "lessons"), { recursive: true });
13
+ }
14
+
15
+ export function relPath(repo, file) {
16
+ return path.relative(repo.top, path.resolve(repo.cwd, file)).split(path.sep).join("/");
17
+ }
package/src/store.js ADDED
@@ -0,0 +1,80 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { git, out } from "./git.js";
5
+
6
+ export const TASKS_REF = "refs/hive/v1/tasks";
7
+
8
+ export function refSha(repo) {
9
+ const result = git(["rev-parse", "--verify", "--quiet", TASKS_REF], { cwd: repo.top, allowFail: true });
10
+ return result.status === 0 ? result.stdout.trim() : null;
11
+ }
12
+
13
+ /** [{ id, value }] from the task tree. An absent ref is an empty board. */
14
+ export function listRaw(repo) {
15
+ const sha = refSha(repo);
16
+ if (!sha) return [];
17
+ const raw = git(["ls-tree", sha], { cwd: repo.top }).stdout.trim();
18
+ if (!raw) return [];
19
+ return raw.split("\n").map((line) => {
20
+ const tab = line.indexOf("\t");
21
+ const meta = line.slice(0, tab).split(/\s+/);
22
+ const id = line.slice(tab + 1);
23
+ const blob = git(["cat-file", "blob", meta[2]], { cwd: repo.top, allowFail: true }).stdout;
24
+ let value = null;
25
+ try { value = JSON.parse(blob); } catch { value = null; }
26
+ return { id, value };
27
+ }).filter((entry) => entry.value);
28
+ }
29
+
30
+ function hashBlob(repo, value) {
31
+ return out(["hash-object", "-w", "--stdin"], { cwd: repo.top, input: JSON.stringify(value) });
32
+ }
33
+
34
+ /**
35
+ * Replace the whole board with the given tasks, compare-and-swap on the ref.
36
+ * Returns false when the ref moved underneath us (caller retries).
37
+ */
38
+ function write(repo, tasks, expectedSha) {
39
+ const indexFile = path.join(repo.stateDir, "index-tasks-" + process.pid + "-" + crypto.randomBytes(4).toString("hex"));
40
+ const env = { GIT_INDEX_FILE: indexFile };
41
+ try {
42
+ fs.mkdirSync(repo.stateDir, { recursive: true });
43
+ if (expectedSha) git(["read-tree", expectedSha], { cwd: repo.top, env });
44
+ else git(["read-tree", "--empty"], { cwd: repo.top, env });
45
+
46
+ const keep = new Set(tasks.map((task) => task.id));
47
+ for (const entry of listRaw(repo)) {
48
+ if (!keep.has(entry.id)) git(["update-index", "--force-remove", entry.id], { cwd: repo.top, env });
49
+ }
50
+ for (const task of tasks) {
51
+ const blob = hashBlob(repo, task);
52
+ git(["update-index", "--add", "--cacheinfo", "100644," + blob + "," + task.id], { cwd: repo.top, env });
53
+ }
54
+ const tree = out(["write-tree"], { cwd: repo.top, env });
55
+ const update = git(["update-ref", TASKS_REF, tree, expectedSha || "0".repeat(tree.length)], {
56
+ cwd: repo.top,
57
+ allowFail: true,
58
+ });
59
+ return update.status === 0;
60
+ } finally {
61
+ fs.rmSync(indexFile, { force: true });
62
+ }
63
+ }
64
+
65
+ /** Read, mutate, write; retries when another writer wins the race. */
66
+ export function mutate(repo, fn) {
67
+ for (let attempt = 0; attempt < 8; attempt++) {
68
+ const expected = refSha(repo);
69
+ const tasks = listRaw(repo).map((entry) => entry.value);
70
+ const next = fn(tasks);
71
+ if (!next) return { ok: true, tasks };
72
+ if (write(repo, next, expected)) return { ok: true, tasks: next, attempt };
73
+ }
74
+ return { ok: false, tasks: [] };
75
+ }
76
+
77
+ export function readTask(repo, id) {
78
+ const found = listRaw(repo).find((entry) => entry.id === id);
79
+ return found ? found.value : null;
80
+ }
package/src/task.js ADDED
@@ -0,0 +1,82 @@
1
+ import crypto from "node:crypto";
2
+
3
+ export const STATES = ["pending", "claimed", "done", "failed", "blocked"];
4
+ export const ROLES = ["coder", "tester", "reviewer", "researcher", "planner", "worker"];
5
+
6
+ export function slug(title) {
7
+ const base = String(title)
8
+ .toLowerCase()
9
+ .replace(/[^a-z0-9]+/g, "-")
10
+ .replace(/^-+|-+$/g, "")
11
+ .slice(0, 32);
12
+ return base || "task";
13
+ }
14
+
15
+ export function newId(title) {
16
+ return slug(title) + "-" + crypto.randomBytes(2).toString("hex");
17
+ }
18
+
19
+ export function now() {
20
+ return new Date().toISOString();
21
+ }
22
+
23
+ export function create({ title, goal, role, scope, after, priority, createdBy, tags, acceptance }) {
24
+ if (!title || !title.trim()) throw new Error("title is required");
25
+ const time = now();
26
+ return {
27
+ v: 1,
28
+ id: newId(title),
29
+ title: title.trim(),
30
+ goal: goal || "",
31
+ role: role || "worker",
32
+ scope: scope || [],
33
+ after: after || [],
34
+ state: "pending",
35
+ owner: null,
36
+ attempt: 0,
37
+ priority: Number.isFinite(priority) ? priority : 0,
38
+ tags: tags || [],
39
+ acceptance: acceptance || "",
40
+ claimedUntil: null,
41
+ resultCommit: null,
42
+ verdict: null,
43
+ reason: null,
44
+ createdBy: createdBy || "unknown",
45
+ createdAt: time,
46
+ updatedAt: time,
47
+ };
48
+ }
49
+
50
+ /** A claimed card whose claim expired can be taken over by the next agent. */
51
+ export function isReclaimable(task, now = Date.now()) {
52
+ if (task.state !== "claimed") return false;
53
+ if (!task.claimedUntil) return false;
54
+ return Date.parse(task.claimedUntil) <= now;
55
+ }
56
+
57
+ function depsDone(task, byId) {
58
+ return (task.after || []).every((id) => byId.get(id) && byId.get(id).state === "done");
59
+ }
60
+
61
+ /**
62
+ * Ready = pending (or a reclaimable claim), dependencies done, and allowed by mode:
63
+ * in freeze only tags include "fix", because the fix itself must be able to run.
64
+ */
65
+ export function isReady(task, byId, { modeFree = true, now = Date.now() } = {}) {
66
+ const claimable = task.state === "pending" || isReclaimable(task, now);
67
+ if (!claimable) return false;
68
+ if (!depsDone(task, byId)) return false;
69
+ if (modeFree) return true;
70
+ return Array.isArray(task.tags) && task.tags.includes("fix");
71
+ }
72
+
73
+ /** Queue order: higher priority first, then oldest first. */
74
+ export function order(a, b) {
75
+ if ((b.priority || 0) !== (a.priority || 0)) return (b.priority || 0) - (a.priority || 0);
76
+ return a.createdAt < b.createdAt ? -1 : 1;
77
+ }
78
+
79
+ export function transition(task, next, patch = {}) {
80
+ if (!STATES.includes(next)) throw new Error("unknown state: " + next);
81
+ return { ...task, ...patch, state: next, updatedAt: now() };
82
+ }