@christang/keel 5.227.0 → 5.229.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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keel",
3
- "version": "5.227.0",
3
+ "version": "5.229.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
@@ -117,9 +117,12 @@ release that changes the hook definitions needs that review again.
117
117
  Bind a mailbox role with `keel mail role --set codex-maint`; trusted hooks announce
118
118
  unread mail at session start and the next user input without marking it read.
119
119
  If receiving hooks are unavailable, use `keel mail list` and `keel mail read`
120
- explicitly. Codex does not wake itself while idle; `keel chat wake add` in its worktree
121
- starts a turn when something addressed to it arrives (#203). Native write-guard
122
- enforcement remains unverified.
120
+ explicitly. For a team owned by Keel, use `keel codex start --role <role> --repo <worktree>`
121
+ with a reachable Codex app-server endpoint (`--socket <path>` selects one explicitly).
122
+ `keel codex drain` and `keel tick` deliver addressed records to those managed roles;
123
+ `keel codex handover` retains a note and creates a successor only after the role is idle.
124
+ Existing desktop chats are not adopted. Native write-guard enforcement and compaction
125
+ remain manual until the current installation is behaviorally verified.
123
126
  See the [Codex acceptance record](docs/codex-validation.md) for versions, runtime
124
127
  evidence, limitations and the clean-consumer Full-mode check.
125
128
 
@@ -222,7 +225,7 @@ because a permission granted in conversation does not survive a context reset. D
222
225
  `keel/config.yaml` instead:
223
226
 
224
227
  ```yaml
225
- 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>], push-tag:<tag glob>[@<role>]
228
+ 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>], push-tag:<tag glob>[@<role>], device-sync
226
229
  - commit
227
230
  - push
228
231
  ```
@@ -232,7 +235,7 @@ names `keel/config.yaml` as that entry's source so an inherited authorization is
232
235
  for one the task decided. A task that authors its own boundary keeps it.
233
236
 
234
237
  The ordinals below count names, not the forms in that comment: `push` and `push:<branch glob>` are
235
- one name, so the vocabulary is fifteen names long and `continuation` is the fifth.
238
+ one name, so the vocabulary is sixteen names long and `continuation` is the fifth.
236
239
 
237
240
  `continuation`, the fifth name, is accepted and changes nothing. Moving from a durably complete
238
241
  task to the next unchecked task of the same change, inside a change whose `tasks.md` you approved,
@@ -286,6 +289,12 @@ role; the grant never asks. It changes nothing else: `--tags`, `--mirror`, `--fo
286
289
  repository that declares only `push-tag:` limits tags and leaves branch pushes alone, and a bare
287
290
  `push` beside it is allowed because it widens no branch.
288
291
 
292
+ `device-sync`, the sixteenth, lets Keel's own commands push the branch-lock refs under
293
+ `refs/keel/lock/` — acquiring, renewing, releasing, taking over and breaking a branch lock (#526) —
294
+ and nothing else. It is bare because a lock ref lives in this repository's own remote. A work
295
+ branch Keel pushes still needs `push` or a matching `push:<glob>`, and a `push-protected` branch is
296
+ never pushed by Keel. Without it every command that would push a lock ref exits 3 naming it.
297
+
289
298
  Every scoped entry — `push:`, `issue:`, `issue-close:`, `cleanup:`, `chat-reply:`,
290
299
  `push-protected:` and `push-tag:` — may end in `@<role>`, or a role pattern such as `@kaiwu-design-*`, where `*`
291
300
  matches any run of role characters (#378). Such an entry reaches only a session whose chat role
@@ -343,7 +352,7 @@ Three things the declaration is not:
343
352
  anything.
344
353
  - **Not a trigger.** It removes a confirmation, not the step that reaches the action. Nothing
345
354
  schedules itself, and no next task is selected for you.
346
- - **Not open-ended.** The fifteen names above are the whole vocabulary. An unrecognized entry is
355
+ - **Not open-ended.** The sixteen names above are the whole vocabulary. An unrecognized entry is
347
356
  reported with the accepted names and the declaration authorizes nothing until you fix it — a
348
357
  typo never becomes a silent grant.
349
358
 
@@ -853,7 +862,7 @@ the brief, so `egress_deny` guards what is handed over, not what it can open.
853
862
 
854
863
  ## Shared resource leases
855
864
 
856
- Sessions coordinate shared resources across worktrees through bounded leases. Other holders are refused and recorded as waiters; when a holder releases a lease, or a lease is found to have expired, the waiters are told through direct chat messages. A lease enforces nothing on Git or the filesystem. The shift check reports those its worktree still holds. See [docs/resource-lock.md](docs/resource-lock.md).
865
+ Sessions coordinate shared resources across worktrees through bounded leases. Other holders are refused and recorded as waiters; when a holder releases a lease, or a lease is found to have expired, the waiters are told through direct chat messages. A lease enforces nothing on Git or the filesystem. The shift check reports those its worktree still holds. Across machines, `keel lock acquire --branch <b>` keeps a branch's lease as the ref `refs/keel/lock/<b>` on its remote, updated only by a push without force, so of two devices that are never online together exactly one holds the branch; an expired lease is taken over with a warning of the gap, a live one only with `--break "<reason>"`, and `keel lock release --branch <b>` first confirms the branch is pushed. Keel pushes lock refs only under `authorize: device-sync`, and with `--push` the branch itself only where `push` allows it (#526). See [docs/resource-lock.md](docs/resource-lock.md).
857
866
 
858
867
  ## Worktree overview
859
868
 
@@ -873,6 +882,28 @@ each worktree's `issues` remains a sorted array of numbers. With `--issues`,
873
882
  `issueUpdates` adds `{number, updatedAt}` entries, with null for an absent time.
874
883
  Without a known default branch, no issue range is inferred.
875
884
 
885
+ ## What exists only on this machine
886
+
887
+ `keel sync status [--repo <path>] [--verify] [--remote <name>] [--json]` lists, for the whole repository from any of
888
+ its worktrees, what a session on another machine could not get by cloning (#526): each
889
+ local branch whose tip no remote-tracking ref contains, with its unpushed commit count
890
+ or that it has no remote counterpart; each worktree with uncommitted or untracked paths,
891
+ a detached head on no remote, or a local-only branch checked out; and every stash entry.
892
+ A branch merged into a remote branch is on the remote. It reads local refs only, never
893
+ fetches, and writes nothing; the output names when the remote-tracking refs were last
894
+ fetched. Exit 0 when nothing is only on this machine, 1 when something is, 2 for an
895
+ operational error. The same report runs from `/` with `--repo`.
896
+
897
+ Each local-only item carries its fix — `git push [-u] <remote> <branch>`, or commit then
898
+ push — and says which `authorize:` entry covers it (`commit`, `push` or a matching
899
+ `push:<glob>`) or which to declare; the report runs none of them. A local
900
+ `origin/<branch>` can lie after a push the remote hung up on, so `--verify` asks the
901
+ remote itself: one `git ls-remote` per remote (each branch's upstream remote, else
902
+ `origin`, or `--remote <name>`), time-limited and never prompting, and marks each local
903
+ branch `same`, `remote-behind`, `remote-ahead`, `diverged`, `unknown-to-local` (the
904
+ remote's sha is not in this clone) or `not-on-remote`. A lookup that fails is
905
+ `cannot verify` with git's error and counts like local-only work; `remote-ahead` does not.
906
+
876
907
  ## Group chat between sessions
877
908
 
878
909
  Sessions working the same repository — a Claude Code session, a Codex session, an unattended runner, and you — share a work group with `keel chat`. Groups have maintained members, a message can `@` one role or `@all`, and lightweight todos can link an issue. A record can supersede its author's earlier one (`--supersedes <id>`), and the earlier one then leaves everyone's unread; unread lists newest first. A record posted with `--ack` asks the roles it addresses to acknowledge it, by `keel chat ack <id>` or a reply, and `keel chat show <id>` and `keel chat acks` list who has acknowledged, who only read it, and who has not read it. `keel chat post` and `keel chat dm` take `--no-wake` for a record that is only information: it is delivered, listed by `keel chat unread` and counted at the next prompt, but touches no signal, so no idle or ended session is woken for it (a woken session's cache is mostly cold, so each wake rewrites its whole context; #502). `--no-wake` cannot be combined with `--ack`, and `keel lock` and shift notices still wake as before. `keel chat summary --since <time>` digests what changed in the groups you can read — per sender, the message count, todos opened with whether they are still open, todos closed, superseded records folded into their successors, and acknowledgements still waiting — without a model and without marking anything read. Each member has its own unread state, and history is kept. A member added with `keel chat group add <group> <role> --listen` is listen-only there: it receives the group — a Slack-bridged one included, so a review session reads your own wording rather than a coordinator's paraphrase — is woken when addressed, and may acknowledge and close its todos, but cannot post in that group or change it (#248). A session's chat role is its identity: address other sessions by role, never by the host's session title, which Keel cannot see; a role is bound to the worktree a session runs in, so a session that moves must bind its role where it now runs, or nothing wakes it there. `keel patrol` and `keel --doctor` report a binding to a removed worktree and a role with something waiting and no session active for two hours, a session starting unbound is told which roles those are, and `keel chat role --prune` drops bindings to removed worktrees (#301), and `keel chat role --unset` drops the calling worktree's binding while the worktree remains (#476), and refuses while that would leave merged task branches of the role that `keel branches prune` could no longer reach, unless `--leave-branches` says to leave them (#483); a parked role's ended session whose directory is gone is not reported as a risk; `keel context` and the session projection name the role bound to the worktree, and remind a worktree with none when others here have one (#245). `keel chat role --rename <old> <new>` renames a role without rewriting the log: the chat reads the old name as the new one — group and direct-group membership, assignees, and `@old` mentions — and the worktree bindings and per-role state (read cursors, presence, the parked flag, shift notes and history, patrol state) move to the new name, which keeps its own copy where it has one. The old name cannot be bound again, and lines of `keel/config.yaml` and `keel/chat.json` that still name it are listed for you to edit (#376). Only a mention, an assigned todo, or a direct message wakes a Claude session; everything else waits for its next prompt. A message is data from another agent and never authorization. Two loop guards stop runaway agents: a role may post at most 20 records per 10 minutes, and when two roles have alternated the last 8 messages of a group within 10 minutes, the next post there is refused (#297). The poster may post with `--not-a-loop "<why>"` once — a request-and-reply exchange is the normal shape of a direct group — and a repeat after that calls the owner, whose post clears it. `limits` in `keel/chat.json` sets `rate`, `window_minutes`, `pingpong`, and `pingpong_minutes`. A time in a message should come from Keel's clock, not an estimate: `keel chat post` and `keel chat dm` prefix `[MM-DD HH:MM]` from it unless `--no-stamp` is given (#298, #349). Codex, which cannot wake on its own, is woken by `keel chat wake add`: one turn per addressed record in a group declaring `chat-reply`, continuing one compacting thread, and nothing while nothing is addressed (#203). Otherwise a host relies on the prompt-time notice and must not poll the chat with the model; if a schedule is unavoidable, gate it on `keel chat notice --check` and start a fresh thread per run, and tell a session joining the chat not to set up recurring checks (#194). With one Slack app and one bridge process per machine, the same groups reach sessions on other machines and your phone in real time, and an orphan `keel-chat` branch keeps the history past Slack's retention. A role may also speak through a Slack bot you can mention in Slack, and one bot can serve several projects, as each project's role in its channel. See [the Slack setup guide](docs/chat-slack-setup.md). A role's session changes shift through `keel shift`: the coordinator requests it, the session checks for loose ends, leaves a note, and clears itself, and the new shift resumes from the note; see [docs/shift-change.md](docs/shift-change.md). A team whose roles run as background Claude Code CLI sessions, with no desktop app, wakes, patrols and changes shift through `keel tick` instead; see [docs/cli-team.md](docs/cli-team.md). The 5.83 `keel mail` commands keep working on direct groups.
@@ -1056,7 +1087,9 @@ keel mail role | send | list | read # the 5.83 mailbox; works on
1056
1087
  # Shift change, shared resource leases, worktree overview
1057
1088
  keel shift request | check | ready [--wake] | start | resume | status
1058
1089
  keel lock acquire | release | list # see docs/resource-lock.md
1090
+ keel lock acquire | release --branch <b> [--break <reason>] [--push] # a branch lock on the remote
1059
1091
  keel worktrees [--repo <path>] [--issues <file>] [--json]
1092
+ keel sync status [--repo <path>] [--verify] [--remote <name>] [--json] # what exists only on this machine
1060
1093
 
1061
1094
  # Unattended triage — may this issue start work without asking?
1062
1095
  # Keel never fetches the issue; pass what gh returned. At least one of the two.
package/README.zh-CN.md CHANGED
@@ -130,6 +130,12 @@ rm -rf "$tmp_dir"
130
130
  ```
131
131
  </details>
132
132
 
133
+ Keel 托管的 Codex 团队通过 `keel codex start --role <role> --repo <worktree>` 创建角色,
134
+ `--socket <path>` 指定可连接的 app-server 套接字。`keel codex drain` 和 `keel tick`
135
+ 只投递发给该角色的记录;`keel codex handover` 在角色空闲后保留交接说明并创建后继。
136
+ 现有桌面聊天不会被自动接管。原生写入拦截和压缩后的重新注入仍需当前安装的实际验证,能力报告保持 manual。
137
+ 详见 [Codex 验收记录](docs/codex-validation.md) 和 [CLI 团队说明](docs/cli-team.zh-CN.md)。
138
+
133
139
  ## 怎么用
134
140
 
135
141
  在项目根目录,先设置一次:
@@ -190,7 +196,7 @@ Keel: add-user-auth#2.1 — next: task-start. Disposable projection; OpenSpec an
190
196
  改为在 `keel/config.yaml` 里一次性声明:
191
197
 
192
198
  ```yaml
193
- 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>], push-tag:<tag glob>[@<role>]
199
+ 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>], push-tag:<tag glob>[@<role>], device-sync
194
200
  - commit
195
201
  - push
196
202
  ```
@@ -198,7 +204,7 @@ authorize: # accepted names: commit, push, push:<branch glob>[@<role>],
198
204
  没有自己写 `Autonomy boundary:` 的 task 会继承这份声明,编译出的 capsule 会把 `keel/config.yaml`
199
205
  标为该条目的来源,这样继承来的授权永远不会被误当成 task 自己做的决定。自己写了边界的 task 保留自己的边界。
200
206
 
201
- 下文的序数按名字计,不按上面注释里的写法计:`push` 和 `push:<branch glob>` 是同一个名字,所以词汇共 15 个名字,
207
+ 下文的序数按名字计,不按上面注释里的写法计:`push` 和 `push:<branch glob>` 是同一个名字,所以词汇共 16 个名字,
202
208
  `continuation` 是第五个。
203
209
 
204
210
  `continuation`(第五个名字)会被接受,但什么都不改变。在你批准过 `tasks.md` 的同一个 change 里,
@@ -238,6 +244,10 @@ Claude 写入守卫返回 `ask`,于是 Claude Code 请你确认这一条命令
238
244
  询问。它不改变别的:`--tags`、`--mirror`、`--follow-tags`、`push.followTags` 和删除标签仍是原来的判定,也没有哪个分支授权
239
245
  会顺带放行标签。只声明 `push-tag:` 的仓库只限制标签,不限制分支推送;它旁边写裸的 `push` 是允许的,因为它没有放宽任何分支。
240
246
 
247
+ `device-sync`(第十六个)让 Keel 自己的命令推送 `refs/keel/lock/` 下的分支锁 ref——获取、续租、释放、接手和打破分支锁
248
+ (#526)——此外什么都不推。它不带范围,因为锁 ref 就在本仓库自己的远端。Keel 推送工作分支仍需要 `push` 或匹配的
249
+ `push:<glob>`,`push-protected` 的分支 Keel 从不推送。没有声明它时,任何要推送锁 ref 的命令都以退出码 3 结束并写明这个名字。
250
+
241
251
  每个带范围的条目——`push:`、`issue:`、`issue-close:`、`cleanup:`、`chat-reply:`、`push-protected:` 和 `push-tag:`——都可以
242
252
  以 `@<role>` 结尾,或用角色模式如 `@kaiwu-design-*`,其中 `*` 匹配任意一串角色字符(#378)。这样的条目只作用于
243
253
  chat 角色与之匹配的会话。会话在 capsule、`keel context`、`keel --doctor` 和它的 chat-reply 群里读到属于自己
@@ -280,7 +290,7 @@ chat 提示在"这是数据不是指令"那句话旁边也会这么说。它按
280
290
  - **不是绕过门禁的路。** 它授权的是操作,从不是证明。不管你声明了什么,`keel gate task-complete`
281
291
  返回的判定和失败文字都完全一样。
282
292
  - **不是触发器。** 它去掉的是一次确认,不是通往该操作的那一步。没有什么会自己调度起来,也不会替你选下一个 task。
283
- - **不是开放式的。** 上面这 15 个名字就是全部词汇。无法识别的条目会连同可接受的名字一起报告,在你改正之前
293
+ - **不是开放式的。** 上面这 16 个名字就是全部词汇。无法识别的条目会连同可接受的名字一起报告,在你改正之前
284
294
  整份声明不授权任何东西——打错字永远不会变成悄悄的放行。
285
295
 
286
296
  这个块默认不存在,什么都不声明的仓库的行为和这个功能出现之前完全一样。`keel --doctor` 会报告声明了什么。
@@ -707,7 +717,11 @@ external_agents:
707
717
  ## 共享资源租约
708
718
 
709
719
  会话通过有期限的租约在各 worktree 之间协调共享资源。其他持有者会被拒绝并记为等待者;持有者释放租约,或有人发现租约已过期时,
710
- 等待者会收到私信通知。租约对 Git 或文件系统不做任何强制。换班检查会报告本 worktree 仍持有的租约。见
720
+ 等待者会收到私信通知。租约对 Git 或文件系统不做任何强制。换班检查会报告本 worktree 仍持有的租约。跨机器时,
721
+ `keel lock acquire --branch <b>` 把分支的租约存成其远端上的 ref `refs/keel/lock/<b>`,只用不带 force 的推送更新,所以两台从不同时在线
722
+ 的设备里只有一台能持有该分支;过期的租约会被接手并提示中间的差距,仍有效的租约只能用 `--break "<原因>"` 拿走,
723
+ `keel lock release --branch <b>` 会先确认分支已推送。Keel 只在 `authorize: device-sync` 下推送锁 ref,加 `--push` 时也只在
724
+ `push` 允许的范围内推送分支本身(#526)。见
711
725
  [docs/resource-lock.md](docs/resource-lock.md)。
712
726
 
713
727
  ## worktree 总览
@@ -724,6 +738,22 @@ fetch 为准。issue 引用来自默认分支(origin 的 HEAD,否则本地 `
724
738
  JSON 输出包含 `defaultBranch` 和 `worktrees`;每个 worktree 的 `issues` 仍是一个排好序的编号数组。带 `--issues`
725
739
  时,`issueUpdates` 会加上 `{number, updatedAt}` 条目,没有时间的记为 null。默认分支未知时,不推断 issue 范围。
726
740
 
741
+
742
+ ## 只在本机的工作
743
+
744
+ `keel sync status [--repo <path>] [--verify] [--remote <name>] [--json]` 在仓库的任意一个 worktree 里都能运行,列出整个仓库里另一台机器 clone
745
+ 下来也拿不到的东西(#526):提交不在任何远端跟踪分支里的本地分支(附未推送的提交数,或说明远端没有对应分支);
746
+ 有未提交或未跟踪文件、游离 HEAD 不在远端、或检出了只在本机的分支的 worktree;以及每一条 stash。已合并进远端分支的
747
+ 分支算在远端。它只读本地 refs,从不 fetch,也不写任何东西;输出会写明远端跟踪分支最后一次 fetch 的时间。没有只在本机
748
+ 的东西时退出 0,有时退出 1,操作错误退出 2。从 `/` 加 `--repo` 运行,结果相同。
749
+
750
+ 每一项都附带修复命令(`git push [-u] <remote> <branch>`,或先提交再推送),并说明是哪条 `authorize:`
751
+ 授权覆盖了它(`commit`、`push` 或匹配的 `push:<glob>`),没有覆盖时说明该声明哪一条;报告本身不执行任何命令。
752
+ 推送中途被远端挂断后,本地的 `origin/<branch>` 可能是错的,所以 `--verify` 直接问远端:每个远端运行一次
753
+ `git ls-remote`(分支上游的远端,否则 `origin`,或 `--remote <name>` 指定的),有超时、从不弹出凭据提示,
754
+ 并把每个本地分支标记为 `same`、`remote-behind`、`remote-ahead`、`diverged`、`unknown-to-local`(远端的 sha 不在
755
+ 本 clone 里)或 `not-on-remote`。查询失败记为 `cannot verify` 并附 git 的报错,按只在本机的工作计入退出码;
756
+ `remote-ahead` 不计入。
727
757
  ## 会话之间的群聊
728
758
 
729
759
  在同一个仓库里干活的各个会话——Claude Code 会话、Codex 会话、无人值守的执行器,还有你——用 `keel chat` 共享一个工作群。群有维护中的成员名单,一条消息可以 `@` 某个角色或 `@all`,轻量待办可以关联 issue。一条记录可以取代同一作者之前的记录(`--supersedes <id>`),被取代的那条随即从所有人的未读里消失;未读按新到旧排列。用 `--ack` 发出的记录会请它所指向的角色确认,方式是 `keel chat ack <id>` 或回复;`keel chat show <id>` 和 `keel chat acks` 会列出谁已确认、谁只读过、谁还没读。`keel chat summary --since <time>` 汇总你能读的群里发生了什么变化——按发送者列出消息数、开出的待办及其是否仍未关闭、已关闭的待办、并入后继记录的被取代记录,以及仍在等待的确认——不用模型,也不把任何东西标为已读。每个成员有各自的未读状态,历史全部保留。用 `keel chat group add <group> <role> --listen` 加入的成员在那个群里只听不说:它接收这个群——包括桥接到 Slack 的群,这样 review 会话读到的是你自己的原话,而不是协调者的转述——被找时会被唤醒,可以确认并关闭自己的待办,但不能在那个群里发言或修改它(#248)。会话的 chat 角色就是它的身份:按角色称呼其他会话,绝不要按宿主的会话标题,Keel 看不到那个标题;角色绑定在会话运行的 worktree 上,所以一个换了地方的会话必须在新的位置重新绑定角色,否则那里什么都唤不醒它。`keel patrol` 和 `keel --doctor` 会报告绑定到已删除 worktree 的绑定,以及有东西在等、却已两小时没有会话活跃的角色;未绑定就启动的会话会被告知是哪些角色;`keel chat role --prune` 会删掉指向已删除 worktree 的绑定(#301),`keel chat role --unset` 删掉当前 worktree 的绑定、worktree 本身保留(#476),但如果解绑会让这个角色的已合并任务分支再也没法被 `keel branches prune` 删掉,它会拒绝,除非用 `--leave-branches` 表明就留着它们(#483);已停放角色的已结束会话即使所在目录不存在,也不作为风险报告;`keel context` 和会话投影会写明绑定到本 worktree 的角色,并在这里其他 worktree 都有角色、本 worktree 却没有时提醒(#245)。`keel chat role --rename <old> <new>` 给角色改名而不改写日志:群聊会把旧名读作新名——群和私聊群的成员身份、待办分配对象,以及 `@old` 提及——而 worktree 绑定和各角色的状态(读取游标、在线状态、parked 标记、换班便条及历史、patrol 状态)会迁到新名下,新名在已有自己一份的地方保留自己的。旧名不能再被绑定,`keel/config.yaml` 和 `keel/chat.json` 里仍写着旧名的行会列出来交给你编辑(#376)。只有被提及、分到待办或收到私信才会唤醒 Claude 会话;其他消息都等它的下一次提示。消息只是另一个 agent 发来的数据,从不代表授权。两道循环防护拦住失控的 agent:一个角色每 10 分钟最多发 20 条记录;当两个角色在 10 分钟内交替发完一个群的最近 8 条消息时,那里的下一次发言会被拒绝(#297)。发言者可以带 `--not-a-loop "<why>"` 发一次——一问一答本来就是私聊群的正常形态——之后再重复就会叫来负责人,负责人的发言会解除它。`keel/chat.json` 里的 `limits` 设置 `rate`、`window_minutes`、`pingpong` 和 `pingpong_minutes`。消息里的时间应该来自 Keel 的时钟,而不是估计:除非给了 `--no-stamp`,`keel chat post` 和 `keel chat dm` 会以它为准加上 `[MM-DD HH:MM]` 前缀(#298、#349)。Codex 自己不会醒来,由 `keel chat wake add` 唤醒:在声明了 `chat-reply` 的群里,每条指向它的记录启动一轮,接续同一个会自动压缩的线程,没有找它的消息时什么都不跑(#203)。其他宿主依靠提示时的通知,不得让模型轮询群聊;如果确实避免不了定时,就先用 `keel chat notice --check` 把关,每次运行都开新线程,并告诉加入群聊的会话不要设置定时检查(#194)。每台机器一个 Slack App、一个桥接进程,同一批群就能实时连到其他机器上的会话和你的手机,孤儿分支 `keel-chat` 会把历史保留到超出 Slack 保留期之后。角色也可以通过一个你能在 Slack 里提及的 Slack bot 发言,一个 bot 可以服务多个项目,在每个项目的频道里充当那个项目的角色。见 [Slack 配置指南](docs/chat-slack-setup.zh-CN.md)。角色的会话通过 `keel shift` 换班:协调者发起,会话自查收尾、留下便条、清空自己,新的一班从便条接手;见 [docs/shift-change.zh-CN.md](docs/shift-change.zh-CN.md)。如果团队的角色以后台 Claude Code CLI 会话运行、没有桌面应用,就改用 `keel tick` 来唤醒、巡查和换班;见 [docs/cli-team.zh-CN.md](docs/cli-team.zh-CN.md)。5.83 的 `keel mail` 命令在私聊群上继续可用。
@@ -885,7 +915,9 @@ keel mail role | send | list | read # 5.83 的邮箱;在私聊
885
915
  # 换班、共享资源租约、worktree 总览
886
916
  keel shift request | check | ready [--wake] | start | resume | status
887
917
  keel lock acquire | release | list # 见 docs/resource-lock.md
918
+ keel lock acquire | release --branch <b> [--break <reason>] [--push] # 远端上的分支锁
888
919
  keel worktrees [--repo <path>] [--issues <file>] [--json]
920
+ keel sync status [--repo <path>] [--verify] [--remote <name>] [--json] # 只在本机的工作
889
921
 
890
922
  # 无人值守 triage —— 这个 issue 能否不经询问就开工?
891
923
  # Keel 从不获取 issue;传入 gh 返回的内容。两个参数至少给一个。
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.227.0 -->
1
+ <!-- keel:start version=5.229.0 -->
2
2
  ## Keel Bootstrap
3
3
 
4
4
  - Start every session with `keel context`; OpenSpec artifacts and Git are the durable authority, and memory or transcripts may only inform.
package/bin/keel.js CHANGED
@@ -103,8 +103,11 @@ Usage:
103
103
  keel branches prune [repo] [--role <role>] [--json] (delete them, local and remote, under authorize: delete-branch:merged; exit 3 without it)
104
104
  keel shift request|check|ready|start|resume|status ... (a role's shift change; see keel shift --help)
105
105
  keel lock acquire|release|list ... (shared resource leases; see keel lock --help)
106
+ keel lock acquire|release --branch <b> [--break <reason>] [--push] (a branch lock kept on the remote; device-sync)
106
107
  keel worktrees [--repo <path>] [--issues <file>] [--json] (read-only worktree overview)
108
+ keel sync status [--repo <path>] [--verify] [--remote <name>] [--json] (what exists only on this machine; fetches nothing, --verify asks the remote its sha)
107
109
  keel patrol [--issues <file>] [--idle <dur>] [--since-last [--notify]] [--nudge] [--json] [--repo <path>] (the coordinator's patrol; keel patrol task prints its schedule)
110
+ keel codex status|start|deliver|handover|drain [--repo <path>] [--role <role>] [--socket <path>] [--json] (managed Codex roles; explicit host identity)
108
111
  keel tick [--repo <path>] [--json] (one model-free step for a host scheduler; keel tick task prints the job)
109
112
  keel openspec [args...]
110
113
  keel --init [repo] [--target claude|codex|opencode|dsh] [--dry-run] [--force-template-update]
@@ -2538,6 +2541,7 @@ function runDoctor(options) {
2538
2541
  printTickIssueChecks(repo);
2539
2542
  printTickHeartbeat(repo);
2540
2543
  printMergedBranches(repo);
2544
+ printSyncDoctor(repo);
2541
2545
  printLaunchdJobs();
2542
2546
 
2543
2547
  return authorizationOk ? checkStatus : 1;
@@ -2617,6 +2621,37 @@ function printTickHeartbeat(repo) {
2617
2621
  if (beat.state) printDoctorLine("tick", beat.state === "ok" ? "ok" : "problem", beat.text);
2618
2622
  }
2619
2623
 
2624
+ // `sync:` (#526 D11, D21): the declaration as read; the branch locks this
2625
+ // device holds are added by the lock itself.
2626
+ function printSyncDoctor(repo) {
2627
+ const declared = require("../src/core/config").readSyncDeclaration(repo);
2628
+ if (declared.message) {
2629
+ printDoctorLine("sync", "unreadable", declared.message);
2630
+ return;
2631
+ }
2632
+ if (!declared.declared) {
2633
+ printDoctorLine("sync", "not declared", "no branch lock at the sync points; `keel sync status` still lists what is only on this machine");
2634
+ return;
2635
+ }
2636
+ printDoctorLine("sync", "declared", `lock: ${declared.lock}, ttl ${declared.ttl}`);
2637
+ const store = require("../src/core/chat/store");
2638
+ const where = store.locate(repo);
2639
+ if (!where) return;
2640
+ const lock = require("../src/core/lock");
2641
+ const device = lock.existingDeviceId(where);
2642
+ const heartbeat = require("../src/core/tick").heartbeat(where);
2643
+ const renewal = heartbeat.at ? `tick (${heartbeat.text}); prompt hook on Claude when due`
2644
+ : "prompt hook on Claude when due; tick has no recorded run here";
2645
+ printDoctorLine("sync device", "ok", `${device || "no device id yet"}; renewal: ${renewal}`);
2646
+ for (const held of lock.branchLocks(where, repo).filter((row) => row.state === "held" && row.device === device)) {
2647
+ const renewed = spawnSync("git", ["log", "-1", "--format=%cI", held.sha], {
2648
+ cwd: repo, encoding: "utf8", env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" },
2649
+ });
2650
+ printDoctorLine("sync lock", lock.liveFor(held, Date.now(), 0) ? "held" : "expired",
2651
+ `${held.branch} by ${held.holder}, expires ${held.expires}, last renewal ${String(renewed.stdout || "unknown").trim()}`);
2652
+ }
2653
+ }
2654
+
2620
2655
  function printMergedBranches(repo) {
2621
2656
  let where = null;
2622
2657
  try {
@@ -3345,6 +3380,10 @@ function runAction(options) {
3345
3380
  }
3346
3381
 
3347
3382
  function main() {
3383
+ if (process.argv[2] === "codex") {
3384
+ require("../src/core/codex-host").run(process.argv.slice(3)).then(code => { process.exitCode = code; });
3385
+ return 0;
3386
+ }
3348
3387
  // `keel mail` parses its own arguments: it is host-neutral messaging between
3349
3388
  // sessions (#180), sharing no option with the gate and projection commands.
3350
3389
  if (process.argv[2] === "mail") {
@@ -3372,6 +3411,10 @@ function main() {
3372
3411
  if (process.argv[2] === "feedback") {
3373
3412
  return require("../src/core/feedback").runFeedback(process.argv.slice(3));
3374
3413
  }
3414
+ // `keel sync` likewise: what exists only on this machine (#526).
3415
+ if (process.argv[2] === "sync") {
3416
+ return require("../src/core/sync").runSync(process.argv.slice(3));
3417
+ }
3375
3418
  if (process.argv[2] === "worktrees") {
3376
3419
  return require("../src/core/worktrees").runWorktrees(process.argv.slice(3));
3377
3420
  }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.227.0",
3
+ "version": "5.229.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.227.0",
9
+ "version": "5.229.0",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@fission-ai/openspec": "^1.4.1"
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@christang/keel",
3
3
  "displayName": "Keel",
4
4
  "description": "Keel OpenSpec execution discipline CLI for Claude Code, Codex, and OpenCode.",
5
- "version": "5.227.0",
5
+ "version": "5.229.0",
6
6
  "license": "MIT",
7
7
  "repository": {
8
8
  "type": "git",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keel",
3
- "version": "5.227.0",
3
+ "version": "5.229.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.227.0",
3
+ "version": "5.229.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",
@@ -19,7 +19,7 @@
19
19
  ],
20
20
  "PreToolUse": [
21
21
  {
22
- "matcher": "Edit|Write|NotebookEdit",
22
+ "matcher": "apply_patch|Edit|Write|NotebookEdit|Bash",
23
23
  "hooks": [
24
24
  {
25
25
  "type": "command",
@@ -43,7 +43,10 @@ function readStdin() {
43
43
  }
44
44
  }
45
45
 
46
+ let denied = false;
47
+
46
48
  function deny(reason) {
49
+ denied = true;
47
50
  process.stdout.write(
48
51
  `${JSON.stringify({
49
52
  hookSpecificOutput: {
@@ -571,6 +574,48 @@ function pushTargets(push) {
571
574
  return { targets, tagTargets, tags };
572
575
  }
573
576
 
577
+ // This hook also ships without src/core; read the same small sync declaration
578
+ // and lock trailers locally, without contacting the remote or creating an id.
579
+ function syncLockEnabled(top) {
580
+ let text;
581
+ try { text = fs.readFileSync(path.join(top, "keel", "config.yaml"), "utf8"); } catch { return false; }
582
+ let inside = false;
583
+ const values = {};
584
+ for (const raw of text.split(/\r?\n/)) {
585
+ const line = raw.replace(/\s+#.*$/, "");
586
+ if (!line.trim() || /^\s*#/.test(line)) continue;
587
+ if (!inside) {
588
+ if (/^sync\s*:\s*$/.test(line)) inside = true;
589
+ continue;
590
+ }
591
+ if (!/^\s/.test(line)) break;
592
+ const entry = line.match(/^\s+(lock|ttl)\s*:\s*(\S+)\s*$/);
593
+ if (!entry) return false;
594
+ values[entry[1]] = entry[2];
595
+ }
596
+ const ttl = (values.ttl || "30m").match(/^(\d+)([mh])$/);
597
+ if (!ttl) return false;
598
+ const seconds = Number(ttl[1]) * (ttl[2] === "h" ? 3600 : 60);
599
+ return values.lock === "true" && seconds >= 300 && seconds <= 86400;
600
+ }
601
+
602
+ function foreignBranchHolder(top, branch) {
603
+ const message = gitOut(top, ["log", "-1", "--format=%B", `refs/keel/lock/${branch}`]);
604
+ if (!message) return null;
605
+ const fields = {};
606
+ for (const line of message.split("\n")) {
607
+ const match = line.match(/^([A-Za-z-]+): (.*)$/);
608
+ if (match && !(match[1] in fields)) fields[match[1]] = match[2];
609
+ }
610
+ if (fields["keel-lock"] !== "held" || !(Date.parse(fields.Expires) + 5 * 60000 >= Date.now())) return null;
611
+ let device = process.env.KEEL_DEVICE;
612
+ if (!device || !/^[A-Za-z0-9._-]{1,64}$/.test(device)) {
613
+ const common = gitOut(top, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
614
+ try { device = JSON.parse(fs.readFileSync(path.join(common, "keel-chat", "device.json"), "utf8")).id; } catch { device = null; }
615
+ }
616
+ return fields.Device && fields.Device === device ? null : fields.Holder || "unknown holder";
617
+ }
618
+
574
619
  function checkPushes(event) {
575
620
  const command = event.tool_input && typeof event.tool_input.command === "string"
576
621
  ? event.tool_input.command : "";
@@ -582,6 +627,19 @@ function checkPushes(event) {
582
627
  const top = gitOut(push.dir || cwd, ["rev-parse", "--show-toplevel"]);
583
628
  if (!top) continue;
584
629
  const { globs, protectedEntries, tagEntries } = readPushGlobs(top);
630
+ const syncLock = syncLockEnabled(top);
631
+ if (syncLock) {
632
+ const targets = pushTargets(push);
633
+ if (!targets.undetermined && !targets.form) {
634
+ for (const branch of targets.targets || []) {
635
+ const holder = foreignBranchHolder(top, branch);
636
+ if (holder) {
637
+ deny(`Keel push guard: branch ${branch} is held by ${holder}; run \`keel lock acquire --branch ${branch}\` before pushing.`);
638
+ return 0;
639
+ }
640
+ }
641
+ }
642
+ }
585
643
  if (!globs.length && !protectedEntries.length && !tagEntries.length) continue;
586
644
  // Branches are limited by `push:` and `push-protected:` alone: a repository
587
645
  // declaring only tag grants leaves branch pushes alone (#499 D4).
@@ -707,8 +765,8 @@ function checkPushes(event) {
707
765
  return 0;
708
766
  }
709
767
 
710
- function main() {
711
- const input = readStdin();
768
+ function main(suppliedEvent = null) {
769
+ const input = suppliedEvent ? JSON.stringify(suppliedEvent) : readStdin();
712
770
  let event = {};
713
771
  try {
714
772
  event = JSON.parse(input || "{}");
@@ -726,6 +784,23 @@ function main() {
726
784
  if (handed !== null) return handed;
727
785
  }
728
786
 
787
+ if (event.tool_name === "apply_patch") {
788
+ const patch = typeof event.tool_input === "string" ? event.tool_input
789
+ : event.tool_input && (event.tool_input.command || event.tool_input.patch || event.tool_input.input);
790
+ const targets = typeof patch === "string"
791
+ ? [...patch.matchAll(/^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+)$/gm)].map(match => match[1].trim())
792
+ : [];
793
+ if (!targets.length && fs.existsSync(path.join(repo, "keel", "guard.json"))) {
794
+ deny("Keel write guard: native patch paths could not be inspected; file edits fail closed.");
795
+ return 0;
796
+ }
797
+ for (const file of targets) {
798
+ main({...event, tool_name: "Edit", tool_input: {file_path: file}});
799
+ if (denied) break;
800
+ }
801
+ return 0;
802
+ }
803
+
729
804
  if (event.tool_name === "Bash") return checkPushes(event);
730
805
 
731
806
  const pathField = FILE_EDIT_TOOLS.get(event.tool_name);
@@ -607,6 +607,13 @@ function main() {
607
607
  + `(${context.selection.source}); next action: `
608
608
  + `${context.nextAction ? context.nextAction.kind : "unknown"}.`
609
609
  );
610
+ // Under `sync: lock: true` the task waits for the branch lock (#526 D15):
611
+ // the command that takes it comes first, with the reason it is needed.
612
+ if (context.nextAction && ["lock-acquire", "shift-resume"].includes(context.nextAction.kind)
613
+ && context.nextAction.command) {
614
+ const why = (context.reasons || []).find((reason) => /branch lock|no lock/.test(String(reason)));
615
+ lines.push(`- first run \`${context.nextAction.command}\`${why ? `: ${String(why).slice(0, MAX_REASON_LENGTH)}` : "."}`);
616
+ }
610
617
  if (reinject) {
611
618
  const recorded = recordedContract(cwd, context.selection);
612
619
  if (recorded) {
@@ -122,6 +122,8 @@ function sweepVersionMarkers(dir, oldVersion, newVersion, touched) {
122
122
  const relative = path.relative(ROOT, full);
123
123
  if (MARKER_SKIP_PREFIXES.some((prefix) => relative.startsWith(prefix))) continue;
124
124
  if (entry.isDirectory()) {
125
+ // A linked worktree or nested clone owns its own release markers.
126
+ if (fs.existsSync(path.join(full, ".git"))) continue;
125
127
  sweepVersionMarkers(full, oldVersion, newVersion, touched);
126
128
  continue;
127
129
  }
@@ -0,0 +1,102 @@
1
+ 'use strict';
2
+ const {test}=require('node:test');
3
+ const assert=require('node:assert/strict');
4
+ const http=require('node:http');
5
+ const crypto=require('node:crypto');
6
+ const os=require('node:os');
7
+ const path=require('node:path');
8
+ const fs=require('node:fs');
9
+ const {spawn}=require('node:child_process');
10
+ const cli=path.resolve(__dirname,'../bin/keel.js');
11
+ function run(args,action="status"){return new Promise(resolve=>{const p=spawn(process.execPath,action==='tick'?[cli,'tick',...args]:[cli,'codex',action,...args]);let out='',err='';p.stdout.on('data',b=>out+=b);p.stderr.on('data',b=>err+=b);p.on('close',code=>resolve({code,out,err}));});}
12
+ test('managed CLI lifecycle, mailbox scheduling and frame boundaries',async()=>{
13
+ const dir=fs.mkdtempSync(path.join(os.tmpdir(),'keel-host-'));const sock=path.join(dir,'host.sock');const requests=[];const peers=[];let active=true,serial=0,uncertain=false,invalidHost=false,injectNotice=false;
14
+ const server=http.createServer();server.on('upgrade',(req,s)=>{peers.push(s);s.write('HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: '+crypto.createHash('sha1').update(req.headers['sec-websocket-key']+'258EAFA5-E914-47DA-95CA-C5AB0DC85B11').digest('base64')+'\r\n\r\n');let initialized=false;let buf=Buffer.alloc(0);s.on('data',chunk=>{buf=Buffer.concat([buf,chunk]);while(buf.length>=6){let n=buf[1]&127,off=2;if(n===126){if(buf.length<8)return;n=buf.readUInt16BE(2);off=4;}else if(n===127){if(buf.length<14)return;n=Number(buf.readBigUInt64BE(2));off=10;}if(buf.length<off+4+n)return;const mask=buf.subarray(off,off+4);const data=Buffer.from(buf.subarray(off+4,off+4+n));buf=buf.subarray(off+4+n);for(let i=0;i<data.length;i++)data[i]^=mask[i%4];const x=JSON.parse(data);requests.push(x.method);if(x.method==='initialized'){initialized=true;continue;}if(!x.id)continue;if(x.method!=='initialize'&&!initialized){s.destroy();return;}const result=x.method==='initialize'?(invalidHost?{}:{userAgent:'test-host'}):x.method==='turn/start'?{turn:uncertain?{}:{id:'turn-fixture'}}:{thread:{id:x.method==='thread/start'?`fixture-thread-${++serial}`:(x.params.threadId||'fixture-thread'),status:{type:active?'active':'idle'},cwd:dir}};const b=Buffer.from(JSON.stringify({id:x.id,result}));const h=b.length<126?Buffer.from([129,b.length]):Buffer.from([129,126,b.length>>8,b.length&255]);const split=Math.floor(b.length/2);const frame=(op,body)=>Buffer.concat([body.length<126?Buffer.from([op,body.length]):Buffer.from([op,126,body.length>>8,body.length&255]),body]);if(injectNotice){const notice=Buffer.from(JSON.stringify({id:x.id,method:'server/notice',params:{}}));s.write(frame(129,notice));}s.write(Buffer.concat([frame(1,b.subarray(0,split)),frame(128,b.subarray(split))]));}});});
15
+ await new Promise(r=>server.listen(sock,r));
16
+ try{const x=await run(['--socket',sock,'--thread','fixture-thread','--json']);assert.equal(x.code,0,x.err);assert.equal(JSON.parse(x.out).thread.status.type,'active');assert.deepEqual(requests.filter(x=>x!=='initialized'),['initialize','thread/read']);
17
+ active=false;const {spawnSync}=require('node:child_process');spawnSync('git',['init','-q',dir]);
18
+ const reserved=await run(['--socket',sock,'--repo',dir,'--role','keel','--json'],'start');assert.notEqual(reserved.code,0);assert.equal(serial,0,'reserved role must be rejected before thread/start');
19
+ fs.mkdirSync(path.join(dir,'.git/keel-chat'),{recursive:true});fs.writeFileSync(path.join(dir,'.git/keel-chat/renames.json'),JSON.stringify({'old-role':'new-role'}));const renamed=await run(['--socket',sock,'--repo',dir,'--role','old-role'],'start');assert.notEqual(renamed.code,0);assert.match(renamed.err,/renamed/);assert.equal(serial,0);
20
+ const started=await run(['--socket',sock,'--repo',dir,'--role','test-role','--json'],'start');assert.equal(started.code,0,started.err);
21
+ assert.equal(JSON.parse(started.out).role,'test-role');
22
+ const again=await run(['--socket',sock,'--repo',dir,'--role','test-role'],'start');assert.notEqual(again.code,0);assert.match(again.err,/already|exists/);
23
+ const own=await run(['--repo',dir,'--role','test-role','--json']);assert.equal(own.code,0,own.err);
24
+ assert.equal(requests.filter(x=>x==='thread/start').length,1);
25
+ const message=['--repo',dir,'--role','test-role','--record','fixture-record','--text','Run keel chat unread','--json'];
26
+ const sent=await run(message,'deliver');assert.equal(sent.code,0,sent.err);
27
+ const duplicate=await run(message,'deliver');assert.equal(duplicate.code,0,duplicate.err);assert.equal(requests.filter(x=>x==='turn/start').length,1);
28
+ active=true;const waiting=await run(['--repo',dir,'--role','test-role','--note','finish fixture','--json'],'handover');assert.equal(waiting.code,0,waiting.err);assert.equal(JSON.parse(waiting.out).state,'waiting');assert.equal(serial,1);
29
+ active=false;const handed=await run(['--repo',dir,'--role','test-role','--note','finish fixture','--json'],'handover');assert.equal(handed.code,0,handed.err);assert.equal(serial,2);
30
+ const store=require('../src/core/chat/store');const where=store.requireLocation(dir);
31
+ store.createGroup(where,'owner','team',['test-role']);
32
+ store.writeRecord(where,{group:'team',kind:'message',from:'owner',mentions:['test-role'],text:'addressed fixture'});
33
+ store.writeRecord(where,{group:'team',kind:'message',from:'owner',mentions:['test-role'],no_wake:true,text:'do not wake'});
34
+ const beforeDrain=requests.filter(x=>x==='turn/start').length;
35
+ const drained=await run(['--repo',dir,'--json'],'drain');assert.equal(drained.code,0,drained.err);assert.equal(requests.filter(x=>x==='turn/start').length,beforeDrain+1);
36
+ const drainedAgain=await run(['--repo',dir,'--json'],'drain');assert.equal(drainedAgain.code,0,drainedAgain.err);assert.equal(requests.filter(x=>x==='turn/start').length,beforeDrain+1);
37
+ const beforeTick=requests.filter(x=>x==='turn/start').length;
38
+ store.writeRecord(where,{group:'team',kind:'message',from:'owner',mentions:['test-role'],text:'tick addressed fixture'});
39
+ const ticked=await run(['--repo',dir,'--json'],'tick');assert.equal(ticked.code,0,ticked.err);assert.ok(JSON.parse(ticked.out).codex.some(x=>x.state==='delivered'));assert.equal(requests.filter(x=>x==='turn/start').length,beforeTick+1);
40
+ uncertain=true;const failedMessage=['--repo',dir,'--role','test-role','--record','uncertain-record','--text','read pending','--json'];const failed=await run(failedMessage,'deliver');assert.notEqual(failed.code,0);const retried=await run(failedMessage,'deliver');assert.notEqual(retried.code,0);assert.match(retried.err,/unknown/);assert.equal(requests.filter(x=>x==='turn/start').length,4);
41
+ const lock=path.join(dir,'.git/keel-chat/codex-roles/test-role.json.lock');fs.writeFileSync(lock,'owned by another process');const locked=await run(message,'deliver');assert.notEqual(locked.code,0);assert.equal(fs.readFileSync(lock,'utf8'),'owned by another process');fs.unlinkSync(lock);
42
+ const registry=JSON.parse(fs.readFileSync(path.join(dir,'.git/keel-chat/codex-roles/test-role.json')));assert.equal(registry.history.length,1);assert.equal(registry.history[0].note,'finish fixture');
43
+
44
+ uncertain=false;const large=await run(['--repo',dir,'--role','test-role','--record','large-record','--text','x'.repeat(70000),'--json'],'deliver');assert.equal(large.code,0,large.err);
45
+ const raceBefore=requests.filter(x=>x==='turn/start').length;const raceArgs=['--repo',dir,'--role','test-role','--record','concurrent-record','--text','concurrent fixture','--json'];const raced=await Promise.all([run(raceArgs,'deliver'),run(raceArgs,'deliver')]);assert.ok(raced.some(x=>x.code===0));assert.equal(requests.filter(x=>x==='turn/start').length,raceBefore+1);
46
+ injectNotice=true;const notified=await run(['--socket',sock,'--json']);assert.equal(notified.code,0,notified.err);assert.equal(JSON.parse(notified.out).host.userAgent,'test-host');injectNotice=false;
47
+ invalidHost=true;const malformed=await run(['--socket',sock,'--json']);assert.notEqual(malformed.code,0);assert.match(malformed.err,/identity/i);invalidHost=false;
48
+ const bad=await run(['--socket',path.join(dir,'missing'),'--timeout','100']);assert.notEqual(bad.code,0);assert.match(bad.err,/connect|ENOENT/i);}finally{peers.forEach(s=>s.destroy());await new Promise(r=>server.close(r));fs.rmSync(dir,{recursive:true,force:true});}
49
+ });
50
+ test('silent endpoint fails before the deadline',async()=>{
51
+ const dir=fs.mkdtempSync(path.join(os.tmpdir(),'keel-silent-')),sock=path.join(dir,'host.sock');const server=http.createServer();const peers=[];server.on('connection',s=>peers.push(s));await new Promise(r=>server.listen(sock,r));
52
+ try{const before=Date.now();const x=await run(['--socket',sock,'--timeout','100']);assert.notEqual(x.code,0);assert.match(x.err,/timeout/);assert.ok(Date.now()-before<3000);}finally{peers.forEach(s=>s.destroy());await new Promise(r=>server.close(r));fs.rmSync(dir,{recursive:true,force:true});}
53
+ });
54
+
55
+ test('native patch guard checks every source and move destination', () => {
56
+ const {spawnSync} = require('node:child_process');
57
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'keel-native-guard-'));
58
+ const hook = path.resolve(__dirname, '../plugins/keel/scripts/pretooluse-guard.js');
59
+ try {
60
+ fs.mkdirSync(path.join(dir, 'keel'));
61
+ fs.mkdirSync(path.join(dir, 'openspec/changes/fixture'), {recursive: true});
62
+ fs.writeFileSync(path.join(dir, 'openspec/changes/fixture/tasks.md'), '- [ ] 1.1 fixture\n');
63
+ fs.writeFileSync(path.join(dir, 'keel/guard.json'), JSON.stringify({schema:'keel-write-guard/v1',change:'fixture',task:'1.1',touch:['allowed.txt'],authority:[{path:'openspec/changes/fixture/tasks.md',sha256:'0'.repeat(64)}]}));
64
+ const check = patch => {
65
+ const r = spawnSync(process.execPath, [hook], {cwd:dir,encoding:'utf8',input:JSON.stringify({cwd:dir,tool_name:'apply_patch',tool_input:{command:patch}})});
66
+ assert.equal(r.status,0,r.stderr);
67
+ return r.stdout ? JSON.parse(r.stdout).hookSpecificOutput : null;
68
+ };
69
+ assert.equal(check('*** Begin Patch\n*** Add File: forbidden.txt\n+bad\n*** End Patch').permissionDecision,'deny');
70
+ assert.equal(check('*** Begin Patch\n*** Update File: allowed.txt\n*** Move to: forbidden.txt\n@@\n-old\n+new\n*** End Patch').permissionDecision,'deny');
71
+ assert.equal(check('*** Begin Patch\n*** Add File: allowed.txt\n+ok\n*** End Patch'),null);
72
+ const config=JSON.parse(fs.readFileSync(path.resolve(__dirname,'../plugins/keel/hooks/codex.json')));
73
+ assert.ok(config.hooks.PreToolUse.some(group=>new RegExp(group.matcher).test('Bash')));
74
+ } finally {fs.rmSync(dir,{recursive:true,force:true});}
75
+ });
76
+
77
+ test('public capability and help distinguish managed host from native enforcement', () => {
78
+ const {spawnSync}=require('node:child_process');
79
+ const result=spawnSync(process.execPath,[cli,'capabilities','--target','codex','--json'],{encoding:'utf8'});
80
+ assert.equal(result.status,0,result.stderr);
81
+ const capabilities=JSON.parse(result.stdout);
82
+ assert.equal(capabilities.host.managedRoles.level,'manual');
83
+ assert.match(capabilities.host.managedRoles.evidence,/explicit.*endpoint/);
84
+ assert.equal(capabilities.guard.enforcement.level,'manual');
85
+ assert.equal(capabilities.compaction.postCompactReinjection.level,'manual');
86
+ const help=spawnSync(process.execPath,[cli,'--help'],{encoding:'utf8'});
87
+ assert.match(help.stdout,/keel codex status\|start\|deliver\|handover\|drain/);
88
+ });
89
+
90
+ test('tick renders managed host failures without starting a replacement', async () => {
91
+ const {spawnSync}=require('node:child_process');
92
+ const dir=fs.mkdtempSync(path.join(os.tmpdir(),'keel-codex-tick-'));
93
+ try {
94
+ spawnSync('git',['init','-q',dir]);
95
+ const store=require('../src/core/chat/store'),where=store.requireLocation(dir);
96
+ fs.mkdirSync(path.join(where.root,'codex-roles'),{recursive:true});
97
+ fs.writeFileSync(path.join(where.root,'codex-roles/bad-role.json'),JSON.stringify({state:'creation-pending',role:'bad-role'}));
98
+ const result=await run(['--repo',dir],'tick');
99
+ assert.equal(result.code,0,result.err);
100
+ assert.match(result.out,/Codex bad-role.*unverified/);
101
+ } finally {fs.rmSync(dir,{recursive:true,force:true});}
102
+ });