@christang/keel 5.203.0 → 5.204.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/.claude-plugin/plugin.json +1 -1
- package/README.md +12 -4
- package/README.zh-CN.md +12 -4
- package/assets/bootstrap/AGENTS.md +1 -1
- package/bin/keel.js +36 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/plugins/keel/.claude-plugin/plugin.json +1 -1
- package/plugins/keel/.codex-plugin/plugin.json +1 -1
- package/scripts/validation/common.py +2 -2
- package/scripts/validation/docs.py +4 -3
- package/scripts/validation/registry.py +3 -0
- package/scripts/validation/shift.py +192 -0
- package/src/core/branches.js +258 -0
- package/src/core/config.js +36 -1
- package/src/core/shift.js +19 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "keel",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.204.0",
|
|
4
4
|
"description": "Keel OpenSpec execution discipline: stateless continuity, task capsules, deterministic gates, and expectation alignment for Codex and Claude Code.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "TanglmChris",
|
package/README.md
CHANGED
|
@@ -219,7 +219,7 @@ because a permission granted in conversation does not survive a context reset. D
|
|
|
219
219
|
`keel/config.yaml` instead:
|
|
220
220
|
|
|
221
221
|
```yaml
|
|
222
|
-
authorize: # accepted names: commit, push, push:<branch glob>[@<role>], release, archive, continuation, issue:<owner>/<repo>[@<role>], protocol-refresh, chat-reply:<group>[@<role>], issue-close:<owner>/<repo>[@<role>], cleanup:scratch[@<role>], push-protected:<branch glob>[@<role>], shift-restore, self-shift
|
|
222
|
+
authorize: # accepted names: commit, push, push:<branch glob>[@<role>], release, archive, continuation, issue:<owner>/<repo>[@<role>], protocol-refresh, chat-reply:<group>[@<role>], issue-close:<owner>/<repo>[@<role>], cleanup:scratch[@<role>], push-protected:<branch glob>[@<role>], shift-restore, self-shift, delete-branch:merged[@<role>]
|
|
223
223
|
- commit
|
|
224
224
|
- push
|
|
225
225
|
```
|
|
@@ -229,7 +229,7 @@ names `keel/config.yaml` as that entry's source so an inherited authorization is
|
|
|
229
229
|
for one the task decided. A task that authors its own boundary keeps it.
|
|
230
230
|
|
|
231
231
|
The ordinals below count names, not the forms in that comment: `push` and `push:<branch glob>` are
|
|
232
|
-
one name, so the vocabulary is
|
|
232
|
+
one name, so the vocabulary is fourteen names long and `continuation` is the fifth.
|
|
233
233
|
|
|
234
234
|
`continuation`, the fifth name, is accepted and changes nothing. Moving from a durably complete
|
|
235
235
|
task to the next unchecked task of the same change, inside a change whose `tasks.md` you approved,
|
|
@@ -243,7 +243,7 @@ nothing until corrected — fail-closed, never a silent grant.
|
|
|
243
243
|
|
|
244
244
|
`issue:<owner>/<repo>`, the sixth name, names the resource it reaches, and it is refused without
|
|
245
245
|
one; `chat-reply:<group>`, the eighth, `issue-close:<owner>/<repo>` and `cleanup:scratch`, the ninth
|
|
246
|
-
and tenth,
|
|
246
|
+
and tenth, `push-protected:<branch glob>`, the eleventh, and `delete-branch:merged`, the fourteenth, are the others that do. The other names, `push` included, act on the checkout the declaration sits in, so each is already bounded by the repository you declared it in. The credentials that open an issue are not:
|
|
247
247
|
`gh` is account-wide, so a bare `issue` would reach every repository your account can touch —
|
|
248
248
|
silently the widest entry in the file, and wider than `push`. Naming the repository keeps the
|
|
249
249
|
grant the size of what it says. Keel carries that scope to `keel --doctor` and to the compiled
|
|
@@ -303,6 +303,10 @@ scope.
|
|
|
303
303
|
scratchpad, after checking that they are merged and that no process is using them. It never covers
|
|
304
304
|
a branch or another session's files, and like the tracker scopes it is carried, not enforced.
|
|
305
305
|
|
|
306
|
+
`delete-branch:merged` (#469) lets `keel branches prune` delete the role's task branches that are
|
|
307
|
+
merged into a trunk, checked out nowhere, and checked out before in a worktree bound to the role,
|
|
308
|
+
local and remote, recording each with its sha before it goes. Without it, `prune` lists them and exits 3.
|
|
309
|
+
|
|
306
310
|
`protocol-refresh`, the seventh name, covers the one piece of a release that a plugin update cannot
|
|
307
311
|
carry: the managed protocol block in this repository's `AGENTS.md`, which moves only when
|
|
308
312
|
`keel --install` runs here. When `keel context` reports that block as older than the running Keel,
|
|
@@ -327,7 +331,7 @@ Three things the declaration is not:
|
|
|
327
331
|
anything.
|
|
328
332
|
- **Not a trigger.** It removes a confirmation, not the step that reaches the action. Nothing
|
|
329
333
|
schedules itself, and no next task is selected for you.
|
|
330
|
-
- **Not open-ended.** The
|
|
334
|
+
- **Not open-ended.** The fourteen names above are the whole vocabulary. An unrecognized entry is
|
|
331
335
|
reported with the accepted names and the declaration authorizes nothing until you fix it — a
|
|
332
336
|
typo never becomes a silent grant.
|
|
333
337
|
|
|
@@ -1035,6 +1039,10 @@ keel tick [--json] | keel tick task # one step; print the launchd
|
|
|
1035
1039
|
keel agents [name] [--json]
|
|
1036
1040
|
keel agents brief <name> --mode helper|implementation --dir <path> --out <file>
|
|
1037
1041
|
|
|
1042
|
+
# A role's merged task branches: listed with their sha; fetches and deletes nothing
|
|
1043
|
+
keel branches [repo] [--role <role>] [--json]
|
|
1044
|
+
keel branches prune [repo] [--role <role>] [--json] # deletes them under authorize: delete-branch:merged
|
|
1045
|
+
|
|
1038
1046
|
# Install / maintenance
|
|
1039
1047
|
keel --init [--target <t>] [--dry-run] [--force-template-update]
|
|
1040
1048
|
keel --install [--target <t>] [--dry-run] [--force-template-update] [--with-git-hooks]
|
package/README.zh-CN.md
CHANGED
|
@@ -187,7 +187,7 @@ Keel: add-user-auth#2.1 — next: task-start. Disposable projection; OpenSpec an
|
|
|
187
187
|
改为在 `keel/config.yaml` 里一次性声明:
|
|
188
188
|
|
|
189
189
|
```yaml
|
|
190
|
-
authorize: # accepted names: commit, push, push:<branch glob>[@<role>], release, archive, continuation, issue:<owner>/<repo>[@<role>], protocol-refresh, chat-reply:<group>[@<role>], issue-close:<owner>/<repo>[@<role>], cleanup:scratch[@<role>], push-protected:<branch glob>[@<role>], shift-restore, self-shift
|
|
190
|
+
authorize: # accepted names: commit, push, push:<branch glob>[@<role>], release, archive, continuation, issue:<owner>/<repo>[@<role>], protocol-refresh, chat-reply:<group>[@<role>], issue-close:<owner>/<repo>[@<role>], cleanup:scratch[@<role>], push-protected:<branch glob>[@<role>], shift-restore, self-shift, delete-branch:merged[@<role>]
|
|
191
191
|
- commit
|
|
192
192
|
- push
|
|
193
193
|
```
|
|
@@ -195,7 +195,7 @@ authorize: # accepted names: commit, push, push:<branch glob>[@<role>],
|
|
|
195
195
|
没有自己写 `Autonomy boundary:` 的 task 会继承这份声明,编译出的 capsule 会把 `keel/config.yaml`
|
|
196
196
|
标为该条目的来源,这样继承来的授权永远不会被误当成 task 自己做的决定。自己写了边界的 task 保留自己的边界。
|
|
197
197
|
|
|
198
|
-
下文的序数按名字计,不按上面注释里的写法计:`push` 和 `push:<branch glob>` 是同一个名字,所以词汇共
|
|
198
|
+
下文的序数按名字计,不按上面注释里的写法计:`push` 和 `push:<branch glob>` 是同一个名字,所以词汇共 14 个名字,
|
|
199
199
|
`continuation` 是第五个。
|
|
200
200
|
|
|
201
201
|
`continuation`(第五个名字)会被接受,但什么都不改变。在你批准过 `tasks.md` 的同一个 change 里,
|
|
@@ -206,7 +206,7 @@ authorize: # accepted names: commit, push, push:<branch glob>[@<role>],
|
|
|
206
206
|
任何东西——失败即关闭,绝不会悄悄放行。
|
|
207
207
|
|
|
208
208
|
`issue:<owner>/<repo>`(第六个名字)要写明它能触及的资源,不写就被拒绝;`chat-reply:<group>`(第八个)、
|
|
209
|
-
`issue-close:<owner>/<repo>` 和 `cleanup:scratch
|
|
209
|
+
`issue-close:<owner>/<repo>` 和 `cleanup:scratch`(第九、第十个),`push-protected:<branch glob>`(第十一个),以及 `delete-branch:merged`(第十四个)
|
|
210
210
|
也同样要写。其余名字作用于声明所在的 checkout,所以天然被限定在你声明它的那个仓库里。开 issue 用的凭据却不是:
|
|
211
211
|
`gh` 是账号级的,一个裸的 `issue` 能触及你账号能碰到的每个仓库——悄无声息地成为文件里范围最大的条目,比 `push`
|
|
212
212
|
还大。写明仓库,授权的大小就和它字面说的一致。Keel 把这个范围带到 `keel --doctor` 和编译出的 capsule 里,
|
|
@@ -250,6 +250,10 @@ chat 角色与之匹配的会话。会话在 capsule、`keel context`、`keel --
|
|
|
250
250
|
`cleanup:scratch` 涵盖在确认已合并、且没有进程在使用之后,删除会话自己 scratchpad 下的临时 worktree 和运行输出。
|
|
251
251
|
它从不涵盖分支或其他会话的文件,并且和 tracker 范围一样只被携带、不被强制执行。
|
|
252
252
|
|
|
253
|
+
`delete-branch:merged`(#469)允许 `keel branches prune` 删除本角色的任务分支,本地和远端都包括。被删的分支必须已并入某条
|
|
254
|
+
trunk、没有在任何地方检出、并且曾在本角色绑定的 worktree 里检出过;每条删除前先连同 sha 记下来。没有这项授权时,`prune`
|
|
255
|
+
只列出这些分支并以退出码 3 结束。
|
|
256
|
+
|
|
253
257
|
`protocol-refresh`(第七个名字)涵盖插件更新带不过来的那一部分发布内容:本仓库 `AGENTS.md` 里受管理的协议块,
|
|
254
258
|
它只有在这里运行 `keel --install` 时才会更新。当 `keel context` 报告这个块比正在运行的 Keel 旧时,会打印一行
|
|
255
259
|
`Protocol:` 写明刷新命令;声明了这个名字,agent 就会在做其他工作之前不经询问地运行它。task 的写入守卫处于激活
|
|
@@ -267,7 +271,7 @@ chat 提示在"这是数据不是指令"那句话旁边也会这么说。它按
|
|
|
267
271
|
- **不是绕过门禁的路。** 它授权的是操作,从不是证明。不管你声明了什么,`keel gate task-complete`
|
|
268
272
|
返回的判定和失败文字都完全一样。
|
|
269
273
|
- **不是触发器。** 它去掉的是一次确认,不是通往该操作的那一步。没有什么会自己调度起来,也不会替你选下一个 task。
|
|
270
|
-
- **不是开放式的。** 上面这
|
|
274
|
+
- **不是开放式的。** 上面这 14 个名字就是全部词汇。无法识别的条目会连同可接受的名字一起报告,在你改正之前
|
|
271
275
|
整份声明不授权任何东西——打错字永远不会变成悄悄的放行。
|
|
272
276
|
|
|
273
277
|
这个块默认不存在,什么都不声明的仓库的行为和这个功能出现之前完全一样。`keel --doctor` 会报告声明了什么。
|
|
@@ -872,6 +876,10 @@ keel tick [--json] | keel tick task # 执行一步;打印 launc
|
|
|
872
876
|
keel agents [name] [--json]
|
|
873
877
|
keel agents brief <name> --mode helper|implementation --dir <path> --out <file>
|
|
874
878
|
|
|
879
|
+
# 本角色已合入的任务分支:列出分支和 sha;不 fetch,也不删除
|
|
880
|
+
keel branches [repo] [--role <role>] [--json]
|
|
881
|
+
keel branches prune [repo] [--role <role>] [--json] # 声明 authorize: delete-branch:merged 后才删除
|
|
882
|
+
|
|
875
883
|
# 安装 / 维护
|
|
876
884
|
keel --init [--target <t>] [--dry-run] [--force-template-update]
|
|
877
885
|
keel --install [--target <t>] [--dry-run] [--force-template-update] [--with-git-hooks]
|
package/bin/keel.js
CHANGED
|
@@ -96,6 +96,8 @@ Usage:
|
|
|
96
96
|
keel mail role|send|list|read|hook [repo] ... (cross-host mailbox; see keel mail help)
|
|
97
97
|
keel triage [repo] [--labels <l1,l2>] [--issue <n>] [--json]
|
|
98
98
|
keel agents [name] [--repo path] [--json] (external model CLIs, read on demand; Keel launches none)
|
|
99
|
+
keel branches [repo] [--role <role>] [--json] (a role's merged task branches, with their sha; fetches and deletes nothing)
|
|
100
|
+
keel branches prune [repo] [--role <role>] [--json] (delete them, local and remote, under authorize: delete-branch:merged; exit 3 without it)
|
|
99
101
|
keel shift request|check|ready|start|resume|status ... (a role's shift change; see keel shift --help)
|
|
100
102
|
keel lock acquire|release|list ... (shared resource leases; see keel lock --help)
|
|
101
103
|
keel worktrees [--repo <path>] [--issues <file>] [--json] (read-only worktree overview)
|
|
@@ -2494,6 +2496,7 @@ function runDoctor(options) {
|
|
|
2494
2496
|
printFastPrePushSurface(repo);
|
|
2495
2497
|
printSourceRepoCliResolution(repo);
|
|
2496
2498
|
printChatRoleDrift(repo);
|
|
2499
|
+
printMergedBranches(repo);
|
|
2497
2500
|
printLaunchdJobs();
|
|
2498
2501
|
|
|
2499
2502
|
return authorizationOk ? checkStatus : 1;
|
|
@@ -2518,6 +2521,35 @@ function printLaunchdJobs() {
|
|
|
2518
2521
|
if (!gone.length) printDoctorLine("launchd", "ok", `${jobs.length} dev.keel job${jobs.length === 1 ? "" : "s"}, each naming a node that exists`);
|
|
2519
2522
|
}
|
|
2520
2523
|
|
|
2524
|
+
// Each role's merged, unused task branches (#469 D5): a count pointing at
|
|
2525
|
+
// `keel branches`, never a deletion.
|
|
2526
|
+
function printMergedBranches(repo) {
|
|
2527
|
+
let where = null;
|
|
2528
|
+
try {
|
|
2529
|
+
where = require("../src/core/chat/store").locate(repo);
|
|
2530
|
+
} catch {
|
|
2531
|
+
where = null;
|
|
2532
|
+
}
|
|
2533
|
+
if (!where || !fs.existsSync(path.join(where.root, "roles.json"))) return;
|
|
2534
|
+
const branches = require("../src/core/branches");
|
|
2535
|
+
const roles = [...new Set(Object.values(JSON.parse(fs.readFileSync(path.join(where.root, "roles.json"), "utf8"))).filter(Boolean))].sort();
|
|
2536
|
+
const counts = [];
|
|
2537
|
+
for (const role of roles) {
|
|
2538
|
+
let names = [];
|
|
2539
|
+
try {
|
|
2540
|
+
names = [...new Set(branches.merged(where, role).branches.map((b) => b.branch))];
|
|
2541
|
+
} catch {
|
|
2542
|
+
continue;
|
|
2543
|
+
}
|
|
2544
|
+
if (names.length) counts.push(`${role} ${names.length}`);
|
|
2545
|
+
}
|
|
2546
|
+
if (!counts.length) {
|
|
2547
|
+
printDoctorLine("branches", "ok", "no role has a merged task branch left");
|
|
2548
|
+
return;
|
|
2549
|
+
}
|
|
2550
|
+
printDoctorLine("branches", "merged", `${counts.join(", ")} merged task branch(es) may be deleted; \`keel branches --role <role>\` lists them`);
|
|
2551
|
+
}
|
|
2552
|
+
|
|
2521
2553
|
function printChatRoleDrift(repo) {
|
|
2522
2554
|
let where = null;
|
|
2523
2555
|
try {
|
|
@@ -3232,6 +3264,10 @@ function main() {
|
|
|
3232
3264
|
if (process.argv[2] === "agents") {
|
|
3233
3265
|
return require("../src/core/agents").runAgents(process.argv.slice(3));
|
|
3234
3266
|
}
|
|
3267
|
+
// `keel branches` likewise: a role's merged task branches (#469).
|
|
3268
|
+
if (process.argv[2] === "branches") {
|
|
3269
|
+
return require("../src/core/branches").runBranches(process.argv.slice(3));
|
|
3270
|
+
}
|
|
3235
3271
|
// `keel docx` was Markdown with SVG to Word (#405). It is retired (#464 D3),
|
|
3236
3272
|
// and the word stays known so a caller learns where the export went.
|
|
3237
3273
|
if (process.argv[2] === "docx") {
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@christang/keel",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.204.0",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@christang/keel",
|
|
9
|
-
"version": "5.
|
|
9
|
+
"version": "5.204.0",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@fission-ai/openspec": "^1.4.1"
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "keel",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.204.0",
|
|
4
4
|
"description": "Keel OpenSpec execution discipline: stateless continuity, task capsules, deterministic gates, and expectation alignment for Codex and Claude Code.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "TanglmChris",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "keel",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.204.0",
|
|
4
4
|
"description": "Keel OpenSpec execution discipline: stateless continuity, task capsules, deterministic gates, and expectation alignment for Codex and Claude Code.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "TanglmChris",
|
|
@@ -35,10 +35,10 @@ os.environ["KEEL_UPDATE_CLAUDE"] = str(Path(tempfile.gettempdir()) / "keel-suite
|
|
|
35
35
|
os.environ["KEEL_UPDATE_CODEX"] = str(Path(tempfile.gettempdir()) / "keel-suite-has-no-codex")
|
|
36
36
|
|
|
37
37
|
|
|
38
|
-
PACKAGE_VERSION = "5.
|
|
38
|
+
PACKAGE_VERSION = "5.204.0"
|
|
39
39
|
|
|
40
40
|
|
|
41
|
-
PROTOCOL_VERSION = "5.
|
|
41
|
+
PROTOCOL_VERSION = "5.204.0"
|
|
42
42
|
|
|
43
43
|
|
|
44
44
|
LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
|
|
@@ -612,7 +612,8 @@ def validate_verification_layering_docs_scenario() -> int:
|
|
|
612
612
|
ACCEPTED_AUTHORIZE_NAMES = (
|
|
613
613
|
"commit, push, push:<branch glob>[@<role>], release, archive, continuation, "
|
|
614
614
|
"issue:<owner>/<repo>[@<role>], protocol-refresh, chat-reply:<group>[@<role>], "
|
|
615
|
-
"issue-close:<owner>/<repo>[@<role>], cleanup:scratch[@<role>], push-protected:<branch glob>[@<role>], shift-restore, self-shift"
|
|
615
|
+
"issue-close:<owner>/<repo>[@<role>], cleanup:scratch[@<role>], push-protected:<branch glob>[@<role>], shift-restore, self-shift, "
|
|
616
|
+
"delete-branch:merged[@<role>]"
|
|
616
617
|
)
|
|
617
618
|
|
|
618
619
|
|
|
@@ -640,7 +641,7 @@ def validate_continuation_docs_scenario() -> int:
|
|
|
640
641
|
# to spell all of it: a reader copies from the list they are shown.
|
|
641
642
|
for needle in (
|
|
642
643
|
f"accepted names: {ACCEPTED_AUTHORIZE_NAMES}",
|
|
643
|
-
"The
|
|
644
|
+
"The fourteen names above are the whole vocabulary.",
|
|
644
645
|
"`protocol-refresh`, the seventh name",
|
|
645
646
|
):
|
|
646
647
|
if needle not in readme:
|
|
@@ -648,7 +649,7 @@ def validate_continuation_docs_scenario() -> int:
|
|
|
648
649
|
return 1
|
|
649
650
|
|
|
650
651
|
config_text = (ROOT / "keel/config.yaml").read_text(encoding="utf-8")
|
|
651
|
-
if "commit, push, push:<branch glob>[@<role>],\n# release, archive, continuation, issue:<owner>/<repo>[@<role>], protocol-refresh,\n# chat-reply:<group>[@<role>], issue-close:<owner>/<repo>[@<role>], cleanup:scratch[@<role>],\n# push-protected:<branch glob>[@<role>], shift-restore, self-shift" not in config_text:
|
|
652
|
+
if "commit, push, push:<branch glob>[@<role>],\n# release, archive, continuation, issue:<owner>/<repo>[@<role>], protocol-refresh,\n# chat-reply:<group>[@<role>], issue-close:<owner>/<repo>[@<role>], cleanup:scratch[@<role>],\n# push-protected:<branch glob>[@<role>], shift-restore, self-shift,\n# delete-branch:merged[@<role>]" not in config_text:
|
|
652
653
|
report(
|
|
653
654
|
f"{label}: keel/config.yaml's comment lacks: protocol-refresh in the "
|
|
654
655
|
"seven-name vocabulary."
|
|
@@ -435,6 +435,9 @@ SCENARIOS: tuple = (
|
|
|
435
435
|
("shift-resume-checks-commits", shift.validate_shift_resume_checks_commits_scenario),
|
|
436
436
|
("shift-resume-skips-session-ids", shift.validate_shift_resume_skips_session_ids_scenario),
|
|
437
437
|
("shift-resume-names-merged-branch", shift.validate_shift_resume_names_merged_branch_scenario),
|
|
438
|
+
("branches-lists-merged", shift.validate_branches_lists_merged_scenario),
|
|
439
|
+
("branches-prune-under-authorization", shift.validate_branches_prune_under_authorization_scenario),
|
|
440
|
+
("branches-pointed-out", shift.validate_branches_pointed_out_scenario),
|
|
438
441
|
("shift-keeps-transcripts", shift.validate_shift_keeps_transcripts_scenario),
|
|
439
442
|
("shift-keeps-found-transcripts", shift.validate_shift_keeps_found_transcripts_scenario),
|
|
440
443
|
("role-drift", shift.validate_role_drift_scenario),
|
|
@@ -5255,3 +5255,195 @@ def validate_memory_rule_reaches_every_repo_scenario() -> int:
|
|
|
5255
5255
|
return 1
|
|
5256
5256
|
report(f"{label.rstrip(':')} scenario passed.")
|
|
5257
5257
|
return 0
|
|
5258
|
+
|
|
5259
|
+
|
|
5260
|
+
def branches_scratch(base: Path) -> tuple[Path, Path, dict, Path]:
|
|
5261
|
+
"""Issue #469's branch shapes, each pushed to a bare remote.
|
|
5262
|
+
|
|
5263
|
+
verify's worktree checks out `done-a` (merged into main), `done-b` (merged
|
|
5264
|
+
only into the declared trunk `integ`), `wip` (not merged), `kept` (merged,
|
|
5265
|
+
kept by declaration) and `busy` (merged, checked out in another worktree);
|
|
5266
|
+
rtl's alone checks out `rtl-done` (merged). verify ends on its own branch.
|
|
5267
|
+
"""
|
|
5268
|
+
rtl, verify, env, remote = shift_scratch(base)
|
|
5269
|
+
|
|
5270
|
+
def git(cwd: Path, *args: str) -> str:
|
|
5271
|
+
return subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True).stdout.strip()
|
|
5272
|
+
|
|
5273
|
+
def branch(cwd: Path, name: str, home: str) -> None:
|
|
5274
|
+
git(cwd, "switch", "-q", "-c", name, "main")
|
|
5275
|
+
write_text(cwd / f"{name}.txt", f"{name}\n")
|
|
5276
|
+
git(cwd, "add", f"{name}.txt")
|
|
5277
|
+
git(cwd, "commit", "-q", "-m", name)
|
|
5278
|
+
git(cwd, "push", "-q", "-u", "origin", name)
|
|
5279
|
+
git(cwd, "switch", "-q", home)
|
|
5280
|
+
|
|
5281
|
+
write_text(verify / "keel" / "config.yaml", "branches:\n trunk:\n - integ\n keep:\n - kept\n")
|
|
5282
|
+
git(verify, "add", "keel/config.yaml")
|
|
5283
|
+
git(verify, "commit", "-q", "-m", "declare trunks")
|
|
5284
|
+
git(verify, "push", "-q", "origin", "HEAD")
|
|
5285
|
+
for name in ("done-a", "done-b", "wip", "kept", "busy"):
|
|
5286
|
+
branch(verify, name, "verify")
|
|
5287
|
+
branch(rtl, "rtl-done", "main")
|
|
5288
|
+
for name in ("done-a", "kept", "busy", "rtl-done"):
|
|
5289
|
+
git(rtl, "merge", "-q", "--no-ff", "--no-edit", name)
|
|
5290
|
+
git(rtl, "push", "-q", "origin", "main")
|
|
5291
|
+
git(rtl, "push", "-q", "origin", "done-b:refs/heads/integ")
|
|
5292
|
+
git(rtl, "fetch", "-q", "origin")
|
|
5293
|
+
git(rtl, "worktree", "add", "-q", str(base / "busy-tree"), "busy")
|
|
5294
|
+
return rtl, verify, env, remote
|
|
5295
|
+
|
|
5296
|
+
|
|
5297
|
+
def all_refs(cwd: Path) -> str:
|
|
5298
|
+
return subprocess.run(["git", "for-each-ref", "--format=%(refname) %(objectname)"], cwd=cwd,
|
|
5299
|
+
check=True, capture_output=True, text=True).stdout
|
|
5300
|
+
|
|
5301
|
+
|
|
5302
|
+
def validate_branches_lists_merged_scenario() -> int:
|
|
5303
|
+
"""Issue #469: a role's merged task branches are listed, with their sha, and nothing is touched.
|
|
5304
|
+
|
|
5305
|
+
kaiwu-ip's branches piled up to 110 on 2026-10-19 because nothing told a
|
|
5306
|
+
session which of its branches were merged and unused. `keel branches`
|
|
5307
|
+
lists exactly those, on both sides, and fetches and deletes nothing.
|
|
5308
|
+
"""
|
|
5309
|
+
label = "branches-lists-merged:"
|
|
5310
|
+
with tempfile.TemporaryDirectory(prefix="keel-branches-469-") as raw:
|
|
5311
|
+
base = Path(raw)
|
|
5312
|
+
_rtl, verify, env, _remote = branches_scratch(base)
|
|
5313
|
+
before = all_refs(verify)
|
|
5314
|
+
listed = run_keel(verify, "branches", "--json", env=env)
|
|
5315
|
+
if listed.returncode != 0:
|
|
5316
|
+
report(f"{label} keel branches exited {listed.returncode}: {listed.stderr!r}")
|
|
5317
|
+
return 1
|
|
5318
|
+
try:
|
|
5319
|
+
result = json.loads(listed.stdout)
|
|
5320
|
+
except json.JSONDecodeError:
|
|
5321
|
+
report(f"{label} keel branches --json printed no JSON: {listed.stdout!r}")
|
|
5322
|
+
return 1
|
|
5323
|
+
got = sorted((b["side"], b["branch"]) for b in result.get("branches", []))
|
|
5324
|
+
want = sorted((side, name) for side in ("local", "remote") for name in ("done-a", "done-b"))
|
|
5325
|
+
if got != want:
|
|
5326
|
+
report(f"{label} keel branches lists {got!r}, not {want!r}.")
|
|
5327
|
+
return 1
|
|
5328
|
+
for b in result["branches"]:
|
|
5329
|
+
if not re.fullmatch(r"[0-9a-f]{40}", b.get("sha", "")):
|
|
5330
|
+
report(f"{label} {b['side']} {b['branch']} carries no sha: {b!r}")
|
|
5331
|
+
return 1
|
|
5332
|
+
trunks = {b["branch"]: b["trunk"] for b in result["branches"]}
|
|
5333
|
+
if trunks.get("done-a") != "origin/main" or trunks.get("done-b") != "origin/integ":
|
|
5334
|
+
report(f"{label} the trunks named are {trunks!r}, not done-a in origin/main and done-b in origin/integ.")
|
|
5335
|
+
return 1
|
|
5336
|
+
if all_refs(verify) != before:
|
|
5337
|
+
report(f"{label} keel branches changed a ref.")
|
|
5338
|
+
return 1
|
|
5339
|
+
if label.rstrip(":") not in {name for name, _ in registry.SCENARIOS}:
|
|
5340
|
+
report(f"{label} the scenario registry does not include it.")
|
|
5341
|
+
return 1
|
|
5342
|
+
report(f"{label.rstrip(':')} scenario passed.")
|
|
5343
|
+
return 0
|
|
5344
|
+
|
|
5345
|
+
|
|
5346
|
+
def validate_branches_prune_under_authorization_scenario() -> int:
|
|
5347
|
+
"""Issue #469: merged task branches are deleted only under `delete-branch:merged`, with a record.
|
|
5348
|
+
|
|
5349
|
+
Without the declaration nothing is deleted and the command says which one
|
|
5350
|
+
would allow it. With it, the role's merged, unused branches go on both
|
|
5351
|
+
sides, each recorded with its sha first, and the printed command restores one.
|
|
5352
|
+
"""
|
|
5353
|
+
label = "branches-prune-under-authorization:"
|
|
5354
|
+
with tempfile.TemporaryDirectory(prefix="keel-branches-469p-") as raw:
|
|
5355
|
+
base = Path(raw)
|
|
5356
|
+
rtl, verify, env, remote = branches_scratch(base)
|
|
5357
|
+
|
|
5358
|
+
def heads(where: Path, prefix: str) -> set[str]:
|
|
5359
|
+
listed = subprocess.run(["git", "for-each-ref", "--format=%(refname)", prefix], cwd=where,
|
|
5360
|
+
check=True, capture_output=True, text=True).stdout.split()
|
|
5361
|
+
return {ref[len(prefix):] for ref in listed}
|
|
5362
|
+
|
|
5363
|
+
local_before, remote_before = heads(verify, "refs/heads/"), heads(remote, "refs/heads/")
|
|
5364
|
+
refused = run_keel(verify, "branches", "prune", env=env)
|
|
5365
|
+
if refused.returncode != 3:
|
|
5366
|
+
report(f"{label} keel branches prune without delete-branch:merged exited {refused.returncode}, not 3: {refused.stdout!r} {refused.stderr!r}")
|
|
5367
|
+
return 1
|
|
5368
|
+
if "delete-branch:merged" not in refused.stdout:
|
|
5369
|
+
report(f"{label} the refusal does not name delete-branch:merged: {refused.stdout!r}")
|
|
5370
|
+
return 1
|
|
5371
|
+
if heads(verify, "refs/heads/") != local_before or heads(remote, "refs/heads/") != remote_before:
|
|
5372
|
+
report(f"{label} a branch was deleted without the declaration.")
|
|
5373
|
+
return 1
|
|
5374
|
+
|
|
5375
|
+
config = verify / "keel" / "config.yaml"
|
|
5376
|
+
config.write_text(config.read_text(encoding="utf-8") + "authorize:\n - delete-branch:merged\n", encoding="utf-8")
|
|
5377
|
+
sha = subprocess.run(["git", "rev-parse", "done-a"], cwd=verify, check=True, capture_output=True, text=True).stdout.strip()
|
|
5378
|
+
pruned = run_keel(verify, "branches", "prune", env=env)
|
|
5379
|
+
if pruned.returncode != 0:
|
|
5380
|
+
report(f"{label} keel branches prune with the declaration exited {pruned.returncode}: {pruned.stdout!r} {pruned.stderr!r}")
|
|
5381
|
+
return 1
|
|
5382
|
+
gone = {"done-a", "done-b"}
|
|
5383
|
+
if heads(verify, "refs/heads/") != local_before - gone:
|
|
5384
|
+
report(f"{label} the local branches left are {sorted(heads(verify, 'refs/heads/'))!r}, not all but done-a and done-b.")
|
|
5385
|
+
return 1
|
|
5386
|
+
if heads(remote, "refs/heads/") != remote_before - gone:
|
|
5387
|
+
report(f"{label} the remote branches left are {sorted(heads(remote, 'refs/heads/'))!r}, not all but done-a and done-b.")
|
|
5388
|
+
return 1
|
|
5389
|
+
ledger = mailbox_common_dir(rtl) / "keel-chat" / "branches" / "deleted.jsonl"
|
|
5390
|
+
lines = [json.loads(line) for line in ledger.read_text(encoding="utf-8").splitlines()] if ledger.is_file() else []
|
|
5391
|
+
if sorted((l["side"], l["branch"]) for l in lines) != sorted((s, n) for s in ("local", "remote") for n in gone):
|
|
5392
|
+
report(f"{label} the record holds {lines!r}, not one line per deletion.")
|
|
5393
|
+
return 1
|
|
5394
|
+
if not any(l["branch"] == "done-a" and l["side"] == "local" and l["sha"] == sha for l in lines):
|
|
5395
|
+
report(f"{label} the record does not hold done-a's sha {sha}: {lines!r}")
|
|
5396
|
+
return 1
|
|
5397
|
+
restore = next((line.split("restore: ", 1)[1] for line in pruned.stdout.splitlines()
|
|
5398
|
+
if line.startswith("Deleted local done-a") and "restore: " in line), "")
|
|
5399
|
+
if restore != f"git branch done-a {sha}":
|
|
5400
|
+
report(f"{label} the restore command printed for done-a is {restore!r}: {pruned.stdout!r}")
|
|
5401
|
+
return 1
|
|
5402
|
+
subprocess.run(restore.split(), cwd=verify, check=True, capture_output=True)
|
|
5403
|
+
back = subprocess.run(["git", "rev-parse", "done-a"], cwd=verify, check=True, capture_output=True, text=True).stdout.strip()
|
|
5404
|
+
if back != sha:
|
|
5405
|
+
report(f"{label} the restore command recreated done-a at {back}, not {sha}.")
|
|
5406
|
+
return 1
|
|
5407
|
+
if label.rstrip(":") not in {name for name, _ in registry.SCENARIOS}:
|
|
5408
|
+
report(f"{label} the scenario registry does not include it.")
|
|
5409
|
+
return 1
|
|
5410
|
+
report(f"{label.rstrip(':')} scenario passed.")
|
|
5411
|
+
return 0
|
|
5412
|
+
|
|
5413
|
+
|
|
5414
|
+
def validate_branches_pointed_out_scenario() -> int:
|
|
5415
|
+
"""Issue #469: the shift check and the doctor point at merged branches, and delete none.
|
|
5416
|
+
|
|
5417
|
+
A session learns its merged branches where it already looks — the shift
|
|
5418
|
+
check and `keel --doctor` — without either one failing over them or
|
|
5419
|
+
touching a ref.
|
|
5420
|
+
"""
|
|
5421
|
+
label = "branches-pointed-out:"
|
|
5422
|
+
with tempfile.TemporaryDirectory(prefix="keel-branches-469c-") as raw:
|
|
5423
|
+
base = Path(raw)
|
|
5424
|
+
_rtl, verify, env, _remote = branches_scratch(base)
|
|
5425
|
+
before = all_refs(verify)
|
|
5426
|
+
checked = run_keel(verify, "shift", "check", env=env)
|
|
5427
|
+
if checked.returncode != 0:
|
|
5428
|
+
report(f"{label} keel shift check exited {checked.returncode} with nothing loose: {checked.stdout!r}")
|
|
5429
|
+
return 1
|
|
5430
|
+
pointer = next((line for line in checked.stdout.splitlines() if "keel branches" in line), "")
|
|
5431
|
+
if not pointer:
|
|
5432
|
+
report(f"{label} keel shift check does not name `keel branches`: {checked.stdout!r}")
|
|
5433
|
+
return 1
|
|
5434
|
+
if not re.search(r"(?<!\d)2(?!\d)", pointer):
|
|
5435
|
+
report(f"{label} the shift check's pointer does not count verify's 2 merged branches: {pointer!r}")
|
|
5436
|
+
return 1
|
|
5437
|
+
doctor = run_keel(verify, "--doctor", env=env).stdout
|
|
5438
|
+
line = next((l for l in doctor.splitlines() if l.strip().startswith("branches")), "")
|
|
5439
|
+
if "verify" not in line:
|
|
5440
|
+
report(f"{label} keel --doctor has no branches line naming verify: {line!r}")
|
|
5441
|
+
return 1
|
|
5442
|
+
if all_refs(verify) != before:
|
|
5443
|
+
report(f"{label} the shift check or the doctor changed a ref.")
|
|
5444
|
+
return 1
|
|
5445
|
+
if label.rstrip(":") not in {name for name, _ in registry.SCENARIOS}:
|
|
5446
|
+
report(f"{label} the scenario registry does not include it.")
|
|
5447
|
+
return 1
|
|
5448
|
+
report(f"{label.rstrip(':')} scenario passed.")
|
|
5449
|
+
return 0
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
// A role's merged task branches (#469): listed with their sha and the trunk
|
|
4
|
+
// that contains them, deleted only under `delete-branch:merged`, with a record
|
|
5
|
+
// that restores each one. Keel lists without fetching; prune fetches first,
|
|
6
|
+
// because it acts on what it finds.
|
|
7
|
+
|
|
8
|
+
const fs = require("fs");
|
|
9
|
+
const path = require("path");
|
|
10
|
+
const { spawnSync } = require("child_process");
|
|
11
|
+
|
|
12
|
+
const REMOTE = "origin";
|
|
13
|
+
|
|
14
|
+
class BranchesError extends Error {
|
|
15
|
+
constructor(message, code = 1) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.code = code;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function git(cwd, args) {
|
|
22
|
+
const result = spawnSync("git", args, { cwd, encoding: "utf8" });
|
|
23
|
+
return { ok: result.status === 0, out: String(result.stdout || "").replace(/\s+$/, ""), err: String(result.stderr || "").trim() };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function realpath(file) {
|
|
27
|
+
try {
|
|
28
|
+
return fs.realpathSync(file);
|
|
29
|
+
} catch {
|
|
30
|
+
return path.resolve(file);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// `*` within a `/` segment and `**` across them, as Touch globs read (D2 e).
|
|
35
|
+
function globRegExp(glob) {
|
|
36
|
+
let source = "";
|
|
37
|
+
for (let i = 0; i < glob.length; i += 1) {
|
|
38
|
+
if (glob[i] === "*" && glob[i + 1] === "*") {
|
|
39
|
+
source += ".*";
|
|
40
|
+
i += 1;
|
|
41
|
+
} else if (glob[i] === "*") {
|
|
42
|
+
source += "[^/]*";
|
|
43
|
+
} else {
|
|
44
|
+
source += glob[i].replace(/[.+?^${}()|[\]\\]/g, "\\$&");
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return new RegExp(`^${source}$`);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const { readBranchesDeclaration } = require("./config");
|
|
51
|
+
|
|
52
|
+
function remoteDefault(cwd) {
|
|
53
|
+
const head = git(cwd, ["symbolic-ref", "--quiet", "--short", `refs/remotes/${REMOTE}/HEAD`]);
|
|
54
|
+
if (head.ok && head.out) return head.out.slice(REMOTE.length + 1);
|
|
55
|
+
for (const name of ["main", "master"]) {
|
|
56
|
+
if (git(cwd, ["rev-parse", "--verify", "--quiet", `refs/remotes/${REMOTE}/${name}`]).ok) return name;
|
|
57
|
+
}
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// The trunks as remote-tracking refs, and the declared ones that have none.
|
|
62
|
+
function trunks(cwd, declared) {
|
|
63
|
+
const names = [...new Set([remoteDefault(cwd), ...declared.trunk].filter(Boolean))];
|
|
64
|
+
const found = [];
|
|
65
|
+
const missing = [];
|
|
66
|
+
for (const name of names) {
|
|
67
|
+
const ref = `refs/remotes/${REMOTE}/${name}`;
|
|
68
|
+
if (git(cwd, ["rev-parse", "--verify", "--quiet", ref]).ok) found.push({ name, ref });
|
|
69
|
+
else missing.push(name);
|
|
70
|
+
}
|
|
71
|
+
return { found, missing };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function refs(cwd, prefix) {
|
|
75
|
+
const listed = git(cwd, ["for-each-ref", "--format=%(refname)\t%(objectname)", prefix]);
|
|
76
|
+
return listed.out.split("\n").filter(Boolean).map((line) => {
|
|
77
|
+
const [ref, sha] = line.split("\t");
|
|
78
|
+
return { ref, sha };
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function checkedOut(cwd) {
|
|
83
|
+
const listed = git(cwd, ["worktree", "list", "--porcelain"]);
|
|
84
|
+
return new Set(listed.out.split("\n").filter((line) => line.startsWith("branch refs/heads/"))
|
|
85
|
+
.map((line) => line.slice("branch refs/heads/".length)));
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Branches a worktree bound to the role has checked out, from its own HEAD
|
|
89
|
+
// reflog (D2 d, F1).
|
|
90
|
+
function owned(where, role) {
|
|
91
|
+
const roles = JSON.parse(fs.readFileSync(path.join(where.root, "roles.json"), "utf8"));
|
|
92
|
+
const names = new Set();
|
|
93
|
+
for (const [worktree, name] of Object.entries(roles)) {
|
|
94
|
+
if (name !== role || !fs.existsSync(worktree)) continue;
|
|
95
|
+
const reflog = git(worktree, ["reflog", "show", "--format=%gs", "HEAD"]);
|
|
96
|
+
for (const line of reflog.out.split("\n")) {
|
|
97
|
+
const moved = line.match(/^checkout: moving from (\S+) to (\S+)$/);
|
|
98
|
+
if (moved) {
|
|
99
|
+
names.add(moved[1]);
|
|
100
|
+
names.add(moved[2]);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return names;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function lastFetch(cwd) {
|
|
108
|
+
const file = git(cwd, ["rev-parse", "--git-path", "FETCH_HEAD"]);
|
|
109
|
+
if (!file.ok) return null;
|
|
110
|
+
try {
|
|
111
|
+
return fs.statSync(path.resolve(cwd, file.out)).mtime.toISOString();
|
|
112
|
+
} catch {
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// The role's qualifying branches on each side (D2).
|
|
118
|
+
function merged(where, role) {
|
|
119
|
+
const cwd = where.worktree;
|
|
120
|
+
const declared = readBranchesDeclaration(cwd);
|
|
121
|
+
const { found, missing } = trunks(cwd, declared);
|
|
122
|
+
const trunkNames = new Set([...found.map((t) => t.name), ...missing]);
|
|
123
|
+
const busy = checkedOut(cwd);
|
|
124
|
+
const mine = owned(where, role);
|
|
125
|
+
const kept = declared.keep.map(globRegExp);
|
|
126
|
+
const containing = (sha) => found.find((trunk) => git(cwd, ["merge-base", "--is-ancestor", sha, trunk.ref]).ok);
|
|
127
|
+
const branches = [];
|
|
128
|
+
const sides = [
|
|
129
|
+
{ side: "local", prefix: "refs/heads/", list: refs(cwd, "refs/heads/") },
|
|
130
|
+
{ side: "remote", prefix: `refs/remotes/${REMOTE}/`, list: refs(cwd, `refs/remotes/${REMOTE}/`) },
|
|
131
|
+
];
|
|
132
|
+
for (const { side, prefix, list } of sides) {
|
|
133
|
+
for (const { ref, sha } of list) {
|
|
134
|
+
const name = ref.slice(prefix.length);
|
|
135
|
+
if (name === "HEAD" || trunkNames.has(name) || !mine.has(name) || kept.some((re) => re.test(name))) continue;
|
|
136
|
+
if (side === "local" && busy.has(name)) continue;
|
|
137
|
+
if (side === "remote" && busy.has(name)) continue;
|
|
138
|
+
const trunk = containing(sha);
|
|
139
|
+
if (trunk) branches.push({ side, branch: name, sha, trunk: `${REMOTE}/${trunk.name}` });
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return {
|
|
143
|
+
role,
|
|
144
|
+
trunks: found.map((t) => `${REMOTE}/${t.name}`),
|
|
145
|
+
missingTrunks: missing,
|
|
146
|
+
branches,
|
|
147
|
+
fetched: lastFetch(cwd),
|
|
148
|
+
message: declared.message,
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function describe(result) {
|
|
153
|
+
const lines = [];
|
|
154
|
+
if (result.message) lines.push(result.message);
|
|
155
|
+
for (const name of result.missingTrunks) lines.push(`Trunk ${name} has no ${REMOTE}/${name} here, so nothing is judged against it.`);
|
|
156
|
+
if (!result.branches.length) {
|
|
157
|
+
lines.push(`No merged task branch of ${result.role} to delete (trunks: ${result.trunks.join(", ") || "none"}; refs as last fetched ${result.fetched || "never"}).`);
|
|
158
|
+
return lines.join("\n");
|
|
159
|
+
}
|
|
160
|
+
lines.push(`Merged task branches of ${result.role} (trunks: ${result.trunks.join(", ")}; refs as last fetched ${result.fetched || "never"}):`);
|
|
161
|
+
for (const b of result.branches) lines.push(`- ${b.side === "remote" ? `${REMOTE}/` : ""}${b.branch} ${b.sha.slice(0, 12)} (in ${b.trunk})`);
|
|
162
|
+
return lines.join("\n");
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// Delete the role's merged task branches (D4), only under
|
|
166
|
+
// `delete-branch:merged`. Each deletion is recorded before it happens, so a
|
|
167
|
+
// mistaken one is restored from the record's sha.
|
|
168
|
+
function prune(where, role, authorized) {
|
|
169
|
+
const cwd = where.worktree;
|
|
170
|
+
if (!authorized) return { ...merged(where, role), refused: "delete-branch:merged", deleted: [], failed: [] };
|
|
171
|
+
const fetched = git(cwd, ["fetch", "--prune", "--quiet", REMOTE]);
|
|
172
|
+
if (!fetched.ok) throw new BranchesError(`git fetch --prune ${REMOTE} failed, so nothing was deleted: ${fetched.err}`);
|
|
173
|
+
const result = merged(where, role);
|
|
174
|
+
const ledger = path.join(where.root, "branches", "deleted.jsonl");
|
|
175
|
+
fs.mkdirSync(path.dirname(ledger), { recursive: true });
|
|
176
|
+
const deleted = [];
|
|
177
|
+
const failed = [];
|
|
178
|
+
for (const b of result.branches) {
|
|
179
|
+
fs.appendFileSync(ledger, `${JSON.stringify({ at: new Date().toISOString(), role, side: b.side, branch: b.branch, sha: b.sha })}\n`);
|
|
180
|
+
const done = b.side === "local"
|
|
181
|
+
? git(cwd, ["branch", "-D", b.branch])
|
|
182
|
+
: git(cwd, ["push", "--quiet", REMOTE, "--delete", b.branch]);
|
|
183
|
+
const restore = b.side === "local" ? `git branch ${b.branch} ${b.sha}` : `git push ${REMOTE} ${b.sha}:refs/heads/${b.branch}`;
|
|
184
|
+
if (done.ok) deleted.push({ ...b, restore });
|
|
185
|
+
else failed.push({ ...b, error: done.err || "failed" });
|
|
186
|
+
}
|
|
187
|
+
return { ...result, refused: null, deleted, failed, ledger };
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function describePrune(result) {
|
|
191
|
+
if (result.refused) {
|
|
192
|
+
return `${describe(result)}\nNothing was deleted: keel/config.yaml does not declare \`${result.refused}\` under authorize:, which is what lets \`keel branches prune\` delete them.`;
|
|
193
|
+
}
|
|
194
|
+
const lines = [];
|
|
195
|
+
if (!result.deleted.length && !result.failed.length) lines.push(`No merged task branch of ${result.role} to delete.`);
|
|
196
|
+
for (const b of result.deleted) lines.push(`Deleted ${b.side} ${b.branch} ${b.sha.slice(0, 12)} (in ${b.trunk}); restore: ${b.restore}`);
|
|
197
|
+
for (const b of result.failed) lines.push(`Could not delete ${b.side} ${b.branch}: ${b.error}`);
|
|
198
|
+
if (result.deleted.length) lines.push(`Recorded in ${result.ledger}.`);
|
|
199
|
+
return lines.join("\n");
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
const USAGE = [
|
|
203
|
+
"keel branches [repo] [--role <role>] [--json] a role's merged task branches, with their sha; fetches and deletes nothing",
|
|
204
|
+
"keel branches prune [repo] [--role <role>] [--json] delete them, under authorize: delete-branch:merged, recording each first",
|
|
205
|
+
].join("\n");
|
|
206
|
+
|
|
207
|
+
function parse(argv) {
|
|
208
|
+
const options = { json: false, role: null, positionals: [], help: false, unknown: null };
|
|
209
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
210
|
+
const arg = argv[i];
|
|
211
|
+
if (arg === "--json") options.json = true;
|
|
212
|
+
else if (arg === "--role") options.role = argv[++i] || null;
|
|
213
|
+
else if (arg === "--repo") options.positionals.push(argv[++i]);
|
|
214
|
+
else if (arg === "--help" || arg === "-h") options.help = true;
|
|
215
|
+
else if (arg.startsWith("-")) options.unknown = arg;
|
|
216
|
+
else options.positionals.push(arg);
|
|
217
|
+
}
|
|
218
|
+
return options;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function runBranches(argv) {
|
|
222
|
+
const options = parse(argv);
|
|
223
|
+
if (options.help) {
|
|
224
|
+
process.stdout.write(`${USAGE}\n`);
|
|
225
|
+
return 0;
|
|
226
|
+
}
|
|
227
|
+
if (options.unknown) {
|
|
228
|
+
process.stderr.write(`keel branches: unknown option ${options.unknown}\n${USAGE}\n`);
|
|
229
|
+
return 2;
|
|
230
|
+
}
|
|
231
|
+
const pruning = options.positionals[0] === "prune";
|
|
232
|
+
if (pruning) options.positionals.shift();
|
|
233
|
+
const store = require("./chat/store");
|
|
234
|
+
try {
|
|
235
|
+
const where = store.requireLocation(path.resolve(options.positionals[0] || process.cwd()));
|
|
236
|
+
const role = options.role || store.currentRole(where);
|
|
237
|
+
if (!role) throw new BranchesError("This worktree is bound to no role; name one with --role.", 2);
|
|
238
|
+
if (!pruning) {
|
|
239
|
+
const result = merged(where, role);
|
|
240
|
+
process.stdout.write(options.json ? `${JSON.stringify(result)}\n` : `${describe(result)}\n`);
|
|
241
|
+
return 0;
|
|
242
|
+
}
|
|
243
|
+
const { readStandingAuthorization } = require("./config");
|
|
244
|
+
const authorized = readStandingAuthorization(where.worktree, { role }).scopes.get("delete-branch") === "merged";
|
|
245
|
+
const result = prune(where, role, authorized);
|
|
246
|
+
process.stdout.write(options.json ? `${JSON.stringify(result)}\n` : `${describePrune(result)}\n`);
|
|
247
|
+
if (result.refused) return 3;
|
|
248
|
+
return result.failed.length ? 1 : 0;
|
|
249
|
+
} catch (error) {
|
|
250
|
+
if (error instanceof BranchesError || error instanceof store.ChatError) {
|
|
251
|
+
process.stderr.write(`keel branches: ${error.message}\n`);
|
|
252
|
+
return error.code || 1;
|
|
253
|
+
}
|
|
254
|
+
throw error;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
module.exports = { BranchesError, readBranchesDeclaration, merged, describe, prune, runBranches, globRegExp, REMOTE, USAGE };
|
package/src/core/config.js
CHANGED
|
@@ -40,6 +40,10 @@ const STANDING_AUTHORIZATION_ACTIONS = [
|
|
|
40
40
|
// and the clear (#319; Remote Control stays on since #324). Never the
|
|
41
41
|
// decision to change shift.
|
|
42
42
|
"self-shift",
|
|
43
|
+
// Deleting the role's task branches merged into a trunk, local and remote,
|
|
44
|
+
// through `keel branches prune` (#469). Its one scope, `merged`, says which
|
|
45
|
+
// branches it reaches; each deletion is recorded with its sha first.
|
|
46
|
+
"delete-branch",
|
|
43
47
|
];
|
|
44
48
|
|
|
45
49
|
// The actions whose credential reaches further than the checkout the
|
|
@@ -49,7 +53,7 @@ const STANDING_AUTHORIZATION_ACTIONS = [
|
|
|
49
53
|
// actions are declared with the resource they may reach and refused bare —
|
|
50
54
|
// accepting the bare form as a convenience would make the narrow form optional
|
|
51
55
|
// and the wide one the default, which is the decision inverted.
|
|
52
|
-
const SCOPED_AUTHORIZATION_ACTIONS = new Set(["issue", "chat-reply", "issue-close", "cleanup", "push-protected"]);
|
|
56
|
+
const SCOPED_AUTHORIZATION_ACTIONS = new Set(["issue", "chat-reply", "issue-close", "cleanup", "push-protected", "delete-branch"]);
|
|
53
57
|
|
|
54
58
|
// Actions whose scope narrows them but is not required (#257). A bare `push`
|
|
55
59
|
// keeps the meaning it always had; `push:<branch glob>` limits it to matching
|
|
@@ -70,6 +74,7 @@ const AUTHORIZATION_SCOPES = {
|
|
|
70
74
|
"chat-reply": { form: "<group>", pattern: /^(?:[a-z0-9][a-z0-9-]{0,31}|dm-[a-z0-9][a-z0-9-]{0,31}--[a-z0-9][a-z0-9-]{0,31})$/ },
|
|
71
75
|
"issue-close": { form: "<owner>/<repo>", pattern: AUTHORIZATION_SCOPE_PATTERN },
|
|
72
76
|
cleanup: { form: "scratch", pattern: /^scratch$/ },
|
|
77
|
+
"delete-branch": { form: "merged", pattern: /^merged$/ },
|
|
73
78
|
// Branch-name characters and `*`; `*` matches within one `/` segment and
|
|
74
79
|
// `**` across them, as Touch globs do.
|
|
75
80
|
push: { form: "<branch glob>", pattern: /^[A-Za-z0-9._/*-]+$/ },
|
|
@@ -167,6 +172,7 @@ const CONFIG_DECLARATIONS = [
|
|
|
167
172
|
"issue_roles",
|
|
168
173
|
"patrol",
|
|
169
174
|
"shift",
|
|
175
|
+
"branches",
|
|
170
176
|
"owner_language",
|
|
171
177
|
];
|
|
172
178
|
|
|
@@ -1099,6 +1105,34 @@ function readShiftDeclaration(repo) {
|
|
|
1099
1105
|
return { permissionMode, keepOldSessions, message: messages.length ? messages.join(" ") : null };
|
|
1100
1106
|
}
|
|
1101
1107
|
|
|
1108
|
+
// `branches:` (#469 D1, D7): `trunk:` names the branches beyond the remote
|
|
1109
|
+
// default that count as merged into, and `keep:` the branch globs never to
|
|
1110
|
+
// delete. A line Keel cannot read is named rather than skipped.
|
|
1111
|
+
function readBranchesDeclaration(repo) {
|
|
1112
|
+
const block = configBlockLines(repo, "branches");
|
|
1113
|
+
const declared = { trunk: [], keep: [], message: null };
|
|
1114
|
+
if (!block) return declared;
|
|
1115
|
+
if (block.inline) {
|
|
1116
|
+
declared.message = "keel/config.yaml `branches:` is written inline; give `trunk:` and `keep:` as indented lists.";
|
|
1117
|
+
return declared;
|
|
1118
|
+
}
|
|
1119
|
+
let current = null;
|
|
1120
|
+
for (const line of block.lines) {
|
|
1121
|
+
const key = line.match(/^\s+(trunk|keep)\s*:\s*$/);
|
|
1122
|
+
if (key) {
|
|
1123
|
+
current = key[1];
|
|
1124
|
+
continue;
|
|
1125
|
+
}
|
|
1126
|
+
const item = line.match(/^\s+-\s*(\S+)\s*$/);
|
|
1127
|
+
if (item && current) {
|
|
1128
|
+
declared[current].push(item[1]);
|
|
1129
|
+
continue;
|
|
1130
|
+
}
|
|
1131
|
+
declared.message = `keel/config.yaml \`branches:\` has a line Keel cannot read: \`${line.trim()}\`; it lists only \`trunk:\` and \`keep:\` entries.`;
|
|
1132
|
+
}
|
|
1133
|
+
return declared;
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1102
1136
|
function durationSeconds(value) {
|
|
1103
1137
|
const match = String(value || "").match(/^(\d+)([smhd])$/);
|
|
1104
1138
|
return match ? Number(match[1]) * { s: 1, m: 60, h: 3600, d: 86400 }[match[2]] : null;
|
|
@@ -1123,6 +1157,7 @@ module.exports = {
|
|
|
1123
1157
|
readPatrolDeclaration,
|
|
1124
1158
|
readPatrolDeclarations,
|
|
1125
1159
|
readShiftDeclaration,
|
|
1160
|
+
readBranchesDeclaration,
|
|
1126
1161
|
durationSeconds,
|
|
1127
1162
|
patrolReminder,
|
|
1128
1163
|
readIssueRoles,
|
package/src/core/shift.js
CHANGED
|
@@ -240,9 +240,26 @@ function check(where, role) {
|
|
|
240
240
|
// recheck: a reminder, never an item that holds the shift (#416 D5).
|
|
241
241
|
notes.push("memory: before the hand-off note, recheck what this session wrote to memory — keep only what the next session "
|
|
242
242
|
+ "would get wrong without it and the repository cannot answer, and remove what this shift made untrue");
|
|
243
|
+
// A pointer, never a loose item and never a deletion (#469 D5).
|
|
244
|
+
const merged = role ? mergedBranchNote(where, role) : null;
|
|
245
|
+
if (merged) notes.push(merged);
|
|
243
246
|
return { ready: items.length === 0, worktree: where.worktree, role: role || null, items, notes };
|
|
244
247
|
}
|
|
245
248
|
|
|
249
|
+
// How many of the role's task branches are merged and unused, pointing at
|
|
250
|
+
// `keel branches` (#469 D5); null when none or when they cannot be read.
|
|
251
|
+
function mergedBranchNote(where, role) {
|
|
252
|
+
let names = [];
|
|
253
|
+
try {
|
|
254
|
+
names = [...new Set(require("./branches").merged(where, role).branches.map((b) => b.branch))].sort();
|
|
255
|
+
} catch {
|
|
256
|
+
return null;
|
|
257
|
+
}
|
|
258
|
+
if (!names.length) return null;
|
|
259
|
+
return `merged branches: ${names.length} of ${role}'s task branches are merged into a trunk and checked out nowhere `
|
|
260
|
+
+ `(${names.join(", ")}); \`keel branches\` lists them, and \`keel branches prune\` deletes them under delete-branch:merged`;
|
|
261
|
+
}
|
|
262
|
+
|
|
246
263
|
// The UTC millisecond a chat record id was written at (`20261012T093944609Z-…`).
|
|
247
264
|
function idTime(id) {
|
|
248
265
|
const m = String(id || "").match(/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(\d{3})Z/);
|
|
@@ -1575,7 +1592,8 @@ function runShift(argv) {
|
|
|
1575
1592
|
const merged = result.merged_branch;
|
|
1576
1593
|
const stale = merged
|
|
1577
1594
|
? `\n\nThis worktree is on ${merged.branch ? `\`${merged.branch}\`` : "a detached HEAD"}, already in ${merged.base} and `
|
|
1578
|
-
+ `${merged.behind} commit${merged.behind === 1 ? "" : "s"} behind it: start new work from ${merged.base}
|
|
1595
|
+
+ `${merged.behind} commit${merged.behind === 1 ? "" : "s"} behind it: start new work from ${merged.base}. `
|
|
1596
|
+
+ "`keel branches` lists this role's merged task branches, which `keel branches prune` deletes under delete-branch:merged."
|
|
1579
1597
|
: "";
|
|
1580
1598
|
const removed = (result.removed || []).length
|
|
1581
1599
|
? `\n\nRemoved old sessions from claude agents: ${result.removed.join(", ")}; \`keel shift history ${result.role} --show <id>\` prints each.`
|