hive-tasks 1.6.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,29 @@ All notable changes to this project are documented here. The format follows
4
4
  [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses
5
5
  [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## [1.7.0] - 2026-12-04
8
+
9
+ ### Changed
10
+
11
+ - claim is announcement-only. A card claim always succeeds; the scope paths are
12
+ announced on the hive-consensus lease board instead of being taken as exclusive
13
+ leases. The latest announcer per key wins, and a live announcement by another agent
14
+ is reported as an overlap in the claim event and in `--json`, never as a refusal.
15
+ - done, fail, retry, reopen and rm --force release the announcements the claim owns; a
16
+ release only deletes the blob this claim still wrote, so a newer announcer survives.
17
+ - Two agents may claim two cards whose scope overlaps, which is what the queue needs;
18
+ merge-on-commit reconciles the edits at commit time.
19
+
20
+ ### Removed
21
+
22
+ - The `path busy` refusal and the card-revert branch behind it.
23
+
24
+ ### Tests
25
+
26
+ - 43 node:test scenarios: the original 41 unchanged, plus two cards on one scope claimed
27
+ by different agents (both claimed, both visible on the hive board, overlap reported)
28
+ and release ownership for a superseded announcement.
29
+
7
30
  ## [1.6.0] - 2026-12-04
8
31
 
9
32
  ### Changed
@@ -27,6 +50,10 @@ All notable changes to this project are documented here. The format follows
27
50
  cards, ready excluding failed cards, stats counting only the four states, and the
28
51
  removal of block/unblock as commands.
29
52
 
53
+ ### Published
54
+
55
+ - npm: `hive-tasks@1.6.0` on 2026-12-04.
56
+
30
57
  ## [1.5.0] - 2026-12-04
31
58
 
32
59
  ### Added
package/README.md CHANGED
@@ -12,7 +12,7 @@ refs/hive/v1/tasks -> tree
12
12
  auth-token-a1b2 -> blob (the card)
13
13
  ```
14
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.
15
+ No server, no database, no queue process. A claim is a compare-and-swap on that one ref, so exactly one agent wins a card; the paths it touches are announced on the [hive-consensus](https://github.com/d86e/hive-consensus) board, where overlaps are visible information rather than a refusal.
16
16
 
17
17
  > ~1,400 lines, zero dependencies, git >= 2.40
18
18
 
@@ -69,16 +69,16 @@ token-tests-ba66 pending tester token tests
69
69
  | show <id> [--json] | one card, its stage chain, and the resolved role source |
70
70
  | ready [--limit N] [--role R] [--json] | pending cards whose dependencies are done, ordered by priority then age |
71
71
  | next [--role R] | the single best candidate |
72
- | claim <id> --agent A [--ttl 5m] | card CAS, then hive leases on the scope |
72
+ | claim <id> --agent A [--ttl 5m] | card CAS, then announce the scope paths on the hive-consensus board |
73
73
  | renew <id> [--ttl 5m] | extend a claim so a long run is not stolen |
74
- | done <id> [--sha S] [--verdict pass\|fail] [--verify] | finish, release leases, record resultCommit; on a staged card it opens the next stage; --verify runs the current stage acceptance first |
74
+ | done <id> [--sha S] [--verdict pass\|fail] [--verify] | finish, release the claim's announcements, record resultCommit; on a staged card it opens the next stage; --verify runs the current stage acceptance first |
75
75
  | plan --file plan.json | create a whole dependency tree in one transaction |
76
76
  | fail <id> --reason R | failure is data: attempt stays; a stage with a done onFail target rewinds instead |
77
77
  | retry <id> [--stage KEY] | failed back to pending (or reset a chain to KEY) |
78
- | 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 leases; a staged card resets to KEY (default the first stage) |
79
- | rm <id> [--force] [--json] | delete a pending/failed/done card; a claimed card is refused (exit 2) unless --force, which releases its leases first |
78
+ | 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 card resets to KEY (default the first stage) |
79
+ | rm <id> [--force] [--json] | delete a pending/failed/done card; a claimed card is refused (exit 2) unless --force, which releases its announcements first |
80
80
 
81
- Exit codes: 0 done, 1 internal error, 2 refused (already claimed, wrong state, dependency missing, mode freeze, path busy).
81
+ Exit codes: 0 done, 1 internal error, 2 refused (already claimed, wrong state, dependency missing, mode freeze).
82
82
 
83
83
  ## Resource keys
84
84
 
@@ -90,8 +90,9 @@ hive-tasks add --title "run the dev server" --scope src/web --scope resource:por
90
90
  hive-tasks add --title "migrate" --scope resource:db:dev
91
91
  ~~~
92
92
 
93
- Two cards that name the same resource cannot be claimed at the same time, which is the
94
- same guarantee files get. Nothing else is required: no daemon watches ports.
93
+ Two cards that name the same resource can be claimed at the same time: the claim
94
+ announces the key and reports an existing live announcement as an overlap. Nothing else
95
+ is required: no daemon watches ports, and no claim is refused because of one.
95
96
 
96
97
  ## Stats
97
98
 
@@ -104,11 +105,15 @@ Counts by state and role, plus the oldest pending card.
104
105
 
105
106
  ## How a claim works
106
107
 
107
- 1. the card CAS moves pending -> claimed in the task tree (one winner);
108
- 2. the scope paths are claimed as hive leases, all or nothing;
109
- 3. if a lease is refused, the card is reverted to pending with a reason.
108
+ 1. the card CAS moves pending -> claimed in the task tree (one winner per card);
109
+ 2. every scope path is announced on the hive-consensus lease board; the latest
110
+ announcement wins and a live announcement by another agent is reported as an
111
+ overlap;
112
+ 3. done, fail, retry, reopen and rm --force release the announcements their claim owns.
110
113
 
111
- 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.
114
+ Announcements never refuse a card: two agents may hold two cards whose scope overlaps,
115
+ which is exactly what the queue must allow. merge-on-commit reconciles the two edits at
116
+ commit time; the card is the authority, the announcement is visibility for the board.
112
117
 
113
118
  ## When an agent dies
114
119
 
@@ -135,11 +140,11 @@ stale-card-1a2b deleted [pending] stale card
135
140
 
136
141
  $ hive-tasks rm working-card-9f8e
137
142
  hive-tasks: task working-card-9f8e is claimed by agent-A; release or reopen it first, or use --force # exit 2
138
- $ hive-tasks rm working-card-9f8e --force # releases the claim's leases, then deletes
143
+ $ hive-tasks rm working-card-9f8e --force # releases the claim's announcements, then deletes
139
144
  ~~~
140
145
 
141
146
  pending, failed and done cards are deletable. A claimed card is protected on
142
- purpose: delete it with --force, which releases exactly that claim's hive leases first, so
147
+ purpose: delete it with --force, which releases exactly that claim's announcements first, so
143
148
  no lease is stranded. An unknown id is exit 2, and a second delete reports "no such task"
144
149
  instead of pretending to succeed.
145
150
 
package/README.zh-CN.md CHANGED
@@ -12,7 +12,7 @@ refs/hive/v1/tasks -> 一棵树
12
12
  auth-token-a1b2 -> blob(任务卡)
13
13
  ```
14
14
 
15
- 没有服务端、没有数据库、没有队列进程。认领就是对这个 ref 的一次 CAS,所以只有一个 agent 能赢;它要碰的路径同时在 [hive-consensus](https://github.com/d86e/hive-consensus) 里被租下。
15
+ 没有服务端、没有数据库、没有队列进程。认领就是对这个 ref 的一次 CAS,所以一张卡只有一个 agent 能赢;它要碰的路径会公告到 [hive-consensus](https://github.com/d86e/hive-consensus) 的看板上,重叠只是可见的信息,不会拒绝任何认领。
16
16
 
17
17
  > 约 1,400 行 · 零依赖 · git >= 2.40
18
18
 
@@ -69,16 +69,16 @@ token-tests-ba66 pending tester token 测试
69
69
  | show <id> [--json] | 单张卡、它的阶段链,以及解析到的角色来源 |
70
70
  | ready [--limit N] [--role R] [--json] | 依赖已完成的 pending 卡,按优先级、再按时间排序 |
71
71
  | next [--role R] | 只给最优的那一张 |
72
- | claim <id> --agent A [--ttl 5m] | 先卡片 CAS,再对 scope 拿 hive 租约 |
72
+ | claim <id> --agent A [--ttl 5m] | 先卡片 CAS,再把 scope 路径公告到 hive-consensus 看板 |
73
73
  | renew <id> [--ttl 5m] | 续期认领,长任务不会被抢 |
74
- | done <id> [--sha S] [--verdict pass\|fail] [--verify] | 完成、释放租约、记录 resultCommit;带阶段的卡会打开下一阶段;--verify 先跑当前阶段的验收 |
74
+ | done <id> [--sha S] [--verdict pass\|fail] [--verify] | 完成、释放认领的公告、记录 resultCommit;带阶段的卡会打开下一阶段;--verify 先跑当前阶段的验收 |
75
75
  | plan --file plan.json | 一次事务创建整棵依赖树 |
76
76
  | fail <id> --reason R | 失败是数据:attempt 保留;阶段有已 done 的 onFail 目标时改为回退 |
77
77
  | retry <id> [--stage KEY] | failed 回到 pending(或把链复位到 KEY) |
78
- | reopen <id> [--reason R] [--agent A] [--stage KEY] | 任何状态回到 pending;清 owner、认领、结果与判定,attempt + 1;释放认领时的租约;带阶段的卡复位到 KEY(默认第一阶段) |
79
- | rm <id> [--force] [--json] | 删除 pending/failed/done 的卡;claimed 的卡默认拒绝(退出码 2),加 --force 会先释放租约再删 |
78
+ | reopen <id> [--reason R] [--agent A] [--stage KEY] | 任何状态回到 pending;清 owner、认领、结果与判定,attempt + 1;释放认领时的公告;带阶段的卡复位到 KEY(默认第一阶段) |
79
+ | rm <id> [--force] [--json] | 删除 pending/failed/done 的卡;claimed 的卡默认拒绝(退出码 2),加 --force 会先释放公告再删 |
80
80
 
81
- 退出码:0 成功,1 内部错误,2 被拒(已被认领、状态不对、依赖缺失、模式 freeze、路径忙)。
81
+ 退出码:0 成功,1 内部错误,2 被拒(已被认领、状态不对、依赖缺失、模式 freeze)。
82
82
 
83
83
  ## 资源 key
84
84
 
@@ -89,7 +89,7 @@ hive-tasks add --title "起 dev server" --scope src/web --scope resource:port:30
89
89
  hive-tasks add --title "跑迁移" --scope resource:db:dev
90
90
  ~~~
91
91
 
92
- 两张卡写了同一个资源,就不可能同时被认领——和文件拿到的是同一种保证。不需要额外的东西:没有守护进程去盯端口。
92
+ 两张卡写了同一个资源,可以同时被认领:后一次认领会公告这个 key,并把人家的存活公告作为 overlap 返回。不需要额外的东西:没有守护进程去盯端口,也没有认领会因此被拒。
93
93
 
94
94
  ## 统计
95
95
 
@@ -102,11 +102,11 @@ hive-tasks stats --json
102
102
 
103
103
  ## claim 怎么走
104
104
 
105
- 1. 卡片 CAS 把 pending 推到 claimed(唯一赢家);
106
- 2. 对 scope 里的路径拿 hive 租约,要么全拿要么不拿;
107
- 3. 租约被拒就把卡 CAS 回 pending 并记原因。
105
+ 1. 卡片 CAS 把 pending 推到 claimed(一张卡唯一赢家);
106
+ 2. scope 里每个路径都公告到 hive-consensus 的租约看板:后来者覆盖公告,别人的存活公告作为 overlap 返回;
107
+ 3. done、fail、retry、reopen 和 rm --force 释放这次认领自己写的公告。
108
108
 
109
- 回滚是我们自己持有的另一次 CAS,所以输掉竞争不会泄漏租约。**卡是权威,租约是礼貌**——它只是让两个 agent 不去碰同一个文件。
109
+ 公告永远不拒绝认领:两个 agent 可以同时持有 scope 重叠的两张卡,队列本来就该允许这种情况。真正撞车的改动由 merge-on-commit 在提交时合并;**卡是权威,公告是看板上的可见性**。
110
110
 
111
111
  ## agent 中途死掉怎么办
112
112
 
package/SPEC.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # hive-tasks protocol
2
2
 
3
- Status: implemented, 1.6.0. Protocol version v1 (card blobs keep `v: 1`).
3
+ Status: implemented, 1.7.0. Protocol version v1 (card blobs keep `v: 1`).
4
4
 
5
5
  ## 1. Scope
6
6
 
@@ -85,7 +85,7 @@ Implementation sketch (plumbing, no working tree involved):
85
85
  | --- | --- |
86
86
  | goal | what the worker should achieve; free text, no format |
87
87
  | role | who may claim: a role name the team agrees on (coder, tester, reviewer, ...). For a staged card it is the fallback/display role; routing uses the stage role |
88
- | scope | paths or resource keys the task expects to touch; used for hive leases. A resource key is any stable string such as resource:port:3000 |
88
+ | scope | paths or resource keys the task expects to touch; announced on the hive-consensus lease board, where a live overlap is information, never a refusal. A resource key is any stable string such as resource:port:3000 |
89
89
  | after | ids that must be done before this becomes ready |
90
90
  | state | see below |
91
91
  | owner | agent id while claimed |
@@ -145,30 +145,30 @@ Once a non-final stage is done the card returns to pending while the next stage
145
145
  card back to pending, clears owner, claimedUntil, resultCommit and verdict, keeps attempt
146
146
  and increments it, records reason (default "reopened") and writes a reopen event.
147
147
  Reopening a pending card is a no-op (exit 0) and does not change attempt. Reopening a
148
- claimed card releases its hive leases, so no orphan lease is left behind. On a staged
148
+ claimed card releases its announcements, so no orphan announcement is left behind. On a staged
149
149
  card reopen always resets the chain (default first stage, --stage KEY selects another),
150
150
  including a card that is currently pending.
151
151
 
152
152
  `rm` is the only destructive command: it removes the card's blob from the task tree in
153
153
  one CAS. pending, failed and done cards are deletable. A claimed card is refused
154
154
  (exit 2, with a hint to release or reopen it) unless --force is given; --force releases
155
- exactly that claim's hive leases and then deletes the card, so a forced delete cannot
156
- strand a lease. Deleting a card is not idempotent: an unknown id is exit 2, and a second
155
+ exactly that claim's announcements and then deletes the card, so a forced delete cannot
156
+ strand an announcement. Deleting a card is not idempotent: an unknown id is exit 2, and a second
157
157
  `rm` of the same id reports "no such task". Cards that named the deleted id in `after`
158
158
  now have a missing dependency, which the ready computation reports as a data error.
159
159
 
160
160
  | From | Command | To | Effect |
161
161
  | --- | --- | --- | --- |
162
162
  | pending | claim | claimed | CAS winner; attempt + 1 |
163
- | claimed | done | done | releases leases; records resultCommit and verdict |
164
- | claimed | fail | failed | releases leases; attempt kept |
165
- | claimed | reopen | pending | releases leases; attempt + 1 |
163
+ | claimed | done | done | releases the claim's announcements; records resultCommit and verdict |
164
+ | claimed | fail | failed | releases the claim's announcements; attempt kept |
165
+ | claimed | reopen | pending | releases the claim's announcements; attempt + 1 |
166
166
  | done | reopen | pending | attempt + 1; clears resultCommit and verdict |
167
167
  | failed | retry | pending | attempt kept |
168
168
  | failed | reopen | pending | attempt + 1 |
169
169
  | pending | reopen | pending | no-op (exit 0) |
170
170
  | pending/failed/done | rm | deleted | removes the blob in one CAS |
171
- | claimed | rm --force | deleted | releases the claim's leases, then removes the blob |
171
+ | claimed | rm --force | deleted | releases the claim's announcements, then removes the blob |
172
172
 
173
173
  - pending: exists, dependencies not satisfied (or no capacity to run it).
174
174
  - ready: pending with every id in after in state done. Computed, never stored.
@@ -219,7 +219,7 @@ Rules:
219
219
  (or when a claim expired, in which case the stage is reclaimed like any claim).
220
220
  done and fail accept only a claimed current stage.
221
221
  2. **Advance, do not release.** done marks the current stage done, opens the next stage
222
- (pending, owner cleared, leases released) and keeps the card pending. The last stage
222
+ (pending, owner cleared, announcements released) and keeps the card pending. The last stage
223
223
  finishes the card (state done, stageState done). done returns `nextStage` (null when
224
224
  the chain is complete).
225
225
  3. **Fail stops or rewinds.** fail marks the current stage failed. If the stage has
@@ -237,13 +237,13 @@ Rules:
237
237
 
238
238
  | Card / stageState | Command | Result | Effect |
239
239
  | --- | --- | --- | --- |
240
- | pending / pending | claim | claimed / claimed | owner, leases, attempt + 1; stage state claimed |
241
- | claimed / claimed | done (more stages) | pending / pending at next | stage done, next pending, owner cleared, leases released; nextStage returned |
240
+ | pending / pending | claim | claimed / claimed | owner, announcements, attempt + 1; stage state claimed |
241
+ | claimed / claimed | done (more stages) | pending / pending at next | stage done, next pending, owner cleared, announcements released; nextStage returned |
242
242
  | claimed / claimed | done (last stage) | done / done | stage done; card done; resultCommit/verdict recorded |
243
243
  | claimed / claimed | fail, onFail target done | pending / pending at target | stage failed; target..end pending; attempt + 1; card ready again |
244
244
  | claimed / claimed | fail, no usable onFail | failed / failed | whole card failed; stage failed |
245
245
  | failed / failed | retry [--stage KEY] | pending / pending at KEY | KEY..end reset to pending, attempt kept |
246
- | any / any | reopen [--stage KEY] | pending / pending at KEY | KEY..end reset (default first), attempt + 1, leases released |
246
+ | any / any | reopen [--stage KEY] | pending / pending at KEY | KEY..end reset (default first), attempt + 1, announcements released |
247
247
 
248
248
  ## 5. Ready computation
249
249
 
@@ -290,24 +290,29 @@ per-stage acceptance in one shot. The two flags are mutually exclusive.
290
290
  Exit codes: 0 success; 1 internal error; 2 refused (already claimed, wrong state,
291
291
  dependency missing, mode freeze, invalid stage chain).
292
292
 
293
- claim couples the card with the hive leases, card first:
293
+ claim couples the card with the hive-consensus announcement board, card first:
294
294
 
295
295
  1. CAS the card from pending to claimed (this is what picks the single winner);
296
- 2. claim every scope path as a hive lease, all or nothing;
297
- 3. if a lease is refused, CAS the card back to pending with a reason and exit 2.
298
-
299
- Card-first is deliberate: a lost card race costs nothing, while lease-first would leave
300
- held leases behind when the card CAS loses. Reverting the card is another CAS we own, so
301
- no state leaks. A staged card reverts its stageState to pending together with the card.
302
-
303
- done releases the leases and records the verdict (or opens the next stage). fail releases
304
- the leases and keeps the attempt counter. retry accepts failed cards and returns the card
305
- to pending (or resets the chain to a stage). reopen accepts every stored state, returns
306
- the card to pending and releases a claimed card's leases (section 4). add --review-of
307
- links a review card to its upstream (section 4.1). rm deletes pending, failed and done
308
- cards, and refuses a
309
- claimed card (exit 2) unless --force, which releases the claim's leases first; it prints
310
- the deleted card (with `deleted: true`) under --json.
296
+ 2. announce every scope path (refs/hive/v1/lease/<key>/__key__). The claim always
297
+ succeeds: the latest announcement wins, and a live announcement by another agent is
298
+ returned as an overlap (in the claim event and in --json) and is otherwise ignored;
299
+ 3. done, fail, retry, reopen and rm --force release the announcements the claim owns.
300
+
301
+ Announcements are advisory and never refuse a claim: two agents may hold two cards whose
302
+ scope overlaps, and merge-on-commit reconciles the two edits at commit time. The card is
303
+ the authority; the announcement is the board's visibility. An announcement blob is
304
+ {"v": 1, "agent", "task", "key", "startedAt", "expiresAt"}; release is a
305
+ compare-and-delete of the announcement the caller still owns, so a newer announcer's blob
306
+ is never deleted by an older claim.
307
+
308
+ done releases the announcements and records the verdict (or opens the next stage). fail
309
+ releases the announcements and keeps the attempt counter. retry accepts failed cards and
310
+ returns the card to pending (or resets the chain to a stage). reopen accepts every stored
311
+ state, returns the card to pending and releases a claimed card's announcements
312
+ (section 4). add --review-of links a review card to its upstream (section 4.1). rm
313
+ deletes pending, failed and done cards, and refuses a claimed card (exit 2) unless
314
+ --force, which releases the claim's announcements first; it prints the deleted card
315
+ (with `deleted: true`) under --json.
311
316
 
312
317
  ## 7. Role resolution (dispatchers)
313
318
 
@@ -371,7 +376,7 @@ Stage events are additional lines next to the task event:
371
376
 
372
377
  ## 9. Requirements
373
378
 
374
- - hive-consensus >= 1.2.0 (leases, board, mode, verdict, events).
379
+ - hive-consensus >= 1.5.0 (announcement board, board, mode, verdict, events).
375
380
  - git >= 2.40.
376
381
  - No network, no database, no daemon.
377
382
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hive-tasks",
3
- "version": "1.6.0",
3
+ "version": "1.7.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
@@ -37,7 +37,7 @@ const USAGE = [
37
37
  " hive-tasks show <id> [--json] card plus the resolved role source",
38
38
  " hive-tasks ready [--json] [--limit N] [--role R]",
39
39
  " hive-tasks next [--role R] [--json] the single best candidate",
40
- " hive-tasks claim <id> --agent A [--ttl 5m] card CAS, then hive leases",
40
+ " hive-tasks claim <id> --agent A [--ttl 5m] card CAS, then announce scope paths",
41
41
  " hive-tasks renew <id> [--ttl 5m] extend a claim",
42
42
  " hive-tasks plan --file plan.json create a whole DAG in one transaction",
43
43
  " hive-tasks done <id> [--sha S] [--verdict pass|fail] [--verify]",
@@ -309,7 +309,7 @@ function run(argv) {
309
309
  return printTask(readTask(repo, id), options.json);
310
310
  }
311
311
 
312
- // A claimed card may still hold hive leases; release exactly the claim we reset.
312
+ // A claimed card may still hold announcements; release exactly the claim we reset.
313
313
  if (previous.state === "claimed") releaseLeases(repo, { paths: previous.scope, agent: previous.owner || agent });
314
314
  append(repo, { actor: agent, kind: "reopen", task: id, from: previous.state, reason, attempt: reopened.attempt, stage: isStaged(reopened) ? reopened.stage : undefined });
315
315
  return printTask(reopened, options.json);
@@ -344,7 +344,7 @@ function run(argv) {
344
344
  fail(error.message, 2);
345
345
  }
346
346
 
347
- // --force deletes a claimed card only after releasing exactly the leases
347
+ // --force deletes a claimed card only after releasing exactly the announcements
348
348
  // that claim holds, so a forced delete cannot strand them.
349
349
  if (deleted.state === "claimed") releaseLeases(repo, { paths: deleted.scope, agent: deleted.owner || agent });
350
350
  append(repo, { actor: agent, kind: "task_delete", task: id, id, state: deleted.state });
@@ -476,20 +476,21 @@ function run(argv) {
476
476
 
477
477
  if (!claimed) fail("could not claim " + id, 2);
478
478
 
479
- const leases = claimLeases(repo, { paths: claimed.scope, agent, ttlMs, taskId: claimed.id });
480
- if (leases.granted === false) {
481
- const holder = leases.denied[0];
482
- mutate(repo, (tasks) => tasks.map((entry) => {
483
- if (entry.id !== id) return entry;
484
- return transition(entry, "pending", { owner: null, claimedUntil: null, reason: "lease held by " + (holder ? holder.agent : "another agent"), ...stageStatePatch(entry, "pending") });
485
- }));
486
- const detail = holder ? " (" + holder.agent + " holds " + holder.key + ")" : "";
487
- fail("could not claim " + id + ": path busy" + detail, 2);
488
- }
489
-
479
+ // Announcements are information, never a gate: the card claim already
480
+ // succeeded, and a live announcement by someone else is reported as an
481
+ // overlap instead of reverting the card.
482
+ const announcements = claimLeases(repo, { paths: claimed.scope, agent, ttlMs, taskId: claimed.id });
490
483
  publishPresence(repo, { agent, task: claimed, state: "working", files: claimed.scope });
491
- append(repo, { actor: agent, kind: "task_claim", task: claimed.id, attempt: claimed.attempt, stage: isStaged(claimed) ? claimed.stage : undefined });
492
- return printTask(claimed, options.json);
484
+ append(repo, {
485
+ actor: agent,
486
+ kind: "task_claim",
487
+ task: claimed.id,
488
+ attempt: claimed.attempt,
489
+ stage: isStaged(claimed) ? claimed.stage : undefined,
490
+ ...(announcements.overlaps.length > 0 ? { overlaps: announcements.overlaps } : {}),
491
+ });
492
+ const extra = announcements.overlaps.length > 0 ? { overlaps: announcements.overlaps } : {};
493
+ return printTask(claimed, options.json, extra);
493
494
  }
494
495
 
495
496
  if (command === "done" || command === "fail" || command === "retry") {
package/src/lease.js CHANGED
@@ -39,40 +39,93 @@ export function readMode(repo) {
39
39
  return (readBlob(repo, MODE_REF) || { mode: "free" }).mode;
40
40
  }
41
41
 
42
- /** Claim every scope path or none of them. An expired lease is taken over. */
42
+ /** One consistent observation of a lease ref: its sha and parsed blob. */
43
+ function readEntry(repo, ref) {
44
+ const rev = git(["rev-parse", "--verify", "--quiet", ref], { cwd: repo.top, allowFail: true });
45
+ if (rev.status !== 0) return { sha: null, value: null };
46
+ const sha = rev.stdout.trim();
47
+ try {
48
+ return { sha, value: JSON.parse(out(["cat-file", "blob", sha], { cwd: repo.top })) };
49
+ } catch {
50
+ return { sha, value: null };
51
+ }
52
+ }
53
+
54
+ /** Write one announcement with no compare-and-swap: the last announcer wins. */
55
+ function replaceAnnouncement(repo, ref, value) {
56
+ const blob = out(["hash-object", "-w", "--stdin"], { cwd: repo.top, input: JSON.stringify(value) });
57
+ return git(["update-ref", ref, blob], { cwd: repo.top, allowFail: true }).status === 0;
58
+ }
59
+
60
+ /**
61
+ * Announce every scope path. Announcements never fail and never block a claim.
62
+ *
63
+ * The consensus layer is a shared announcement board: the latest announcer per
64
+ * key wins, and a live announcement by another agent is reported as an overlap
65
+ * (information) instead of refusing the card. merge-on-commit reconciles two
66
+ * agents writing the same file at commit time.
67
+ *
68
+ * Returns { granted: true, keys, overlaps: [{ key, agent, task, expiresAt }] }.
69
+ */
43
70
  export function claimLeases(repo, { paths, agent, ttlMs, taskId }) {
44
- const keys = paths.map(toKey);
45
- if (keys.length === 0) return { granted: true, denied: [] };
71
+ const keys = [];
72
+ for (const path of paths) {
73
+ const key = toKey(path);
74
+ if (!keys.includes(key)) keys.push(key);
75
+ }
76
+ if (keys.length === 0) return { granted: true, keys, overlaps: [] };
46
77
 
47
- const now = Date.now();
48
- const lines = ["start"];
49
- const denied = [];
78
+ let overlaps = [];
79
+ for (let attempt = 0; attempt < 8; attempt++) {
80
+ const now = Date.now();
81
+ const entries = new Map();
82
+ overlaps = [];
83
+ for (const key of keys) {
84
+ const entry = readEntry(repo, leaseRef(key));
85
+ entries.set(key, entry);
86
+ const current = entry.value;
87
+ if (
88
+ current &&
89
+ Date.parse(current.expiresAt) > now &&
90
+ (current.agent !== agent || (current.task || "") !== (taskId || ""))
91
+ ) {
92
+ overlaps.push({ key, agent: current.agent, task: current.task || "", expiresAt: current.expiresAt });
93
+ }
94
+ }
50
95
 
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;
96
+ const lines = ["start"];
97
+ for (const key of keys) {
98
+ const entry = entries.get(key);
99
+ const value = {
100
+ v: 1,
101
+ agent,
102
+ task: taskId || "",
103
+ key,
104
+ startedAt: new Date(now).toISOString(),
105
+ expiresAt: new Date(now + ttlMs).toISOString(),
106
+ };
107
+ const blob = out(["hash-object", "-w", "--stdin"], { cwd: repo.top, input: JSON.stringify(value) });
108
+ lines.push("update " + leaseRef(key) + " " + blob + " " + (entry.sha || "0".repeat(blob.length)));
57
109
  }
58
- const value = {
110
+ lines.push("prepare", "commit");
111
+ const result = git(["update-ref", "--stdin"], { cwd: repo.top, input: lines.join("\n") + "\n", allowFail: true });
112
+ if (result.status === 0) return { granted: true, keys, overlaps };
113
+ }
114
+
115
+ // Announcements are advisory: after repeated contention the last write wins
116
+ // instead of turning an announcement into a failure.
117
+ const now = Date.now();
118
+ for (const key of keys) {
119
+ replaceAnnouncement(repo, leaseRef(key), {
59
120
  v: 1,
60
121
  agent,
61
122
  task: taskId || "",
62
123
  key,
63
124
  startedAt: new Date(now).toISOString(),
64
125
  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)));
126
+ });
69
127
  }
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() };
128
+ return { granted: true, keys, overlaps };
76
129
  }
77
130
 
78
131
  export function releaseLeases(repo, { paths, agent }) {