@christang/keel 5.99.6 → 5.101.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/README.md +5 -1
- package/assets/bootstrap/AGENTS.md +1 -1
- package/bin/keel.js +4 -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/validate_plugin.py +382 -3
- package/src/core/chat/bridge.js +14 -0
- package/src/core/chat/cli.js +6 -4
- package/src/core/chat/notice.js +2 -1
- package/src/core/chat/store.js +40 -2
- package/src/core/chat/view.js +6 -0
- package/src/core/lock.js +231 -0
- package/src/core/shift.js +6 -1
package/README.md
CHANGED
|
@@ -685,9 +685,13 @@ are machine facts: `~/.keel/agents.json` adds an agent or overrides a field, suc
|
|
|
685
685
|
`{"agents": {"dsh": {"executable": "/path/to/dsh"}}}`. Keel cannot see what an agent reads beyond
|
|
686
686
|
the brief, so `egress_deny` guards what is handed over, not what it can open.
|
|
687
687
|
|
|
688
|
+
## Shared resource leases
|
|
689
|
+
|
|
690
|
+
Sessions coordinate shared resources across worktrees through bounded leases. Other holders are refused and recorded as waiters; release and noticed expiry tell them 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).
|
|
691
|
+
|
|
688
692
|
## Group chat between sessions
|
|
689
693
|
|
|
690
|
-
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. Each member has its own unread state, and history is kept. 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. 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). The 5.83 `keel mail` commands keep working on direct groups.
|
|
694
|
+
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. Each member has its own unread state, and history is kept. 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. 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). The 5.83 `keel mail` commands keep working on direct groups.
|
|
691
695
|
|
|
692
696
|
## Commands
|
|
693
697
|
|
package/bin/keel.js
CHANGED
|
@@ -107,6 +107,7 @@ Usage:
|
|
|
107
107
|
keel triage [repo] [--labels <l1,l2>] [--issue <n>] [--json]
|
|
108
108
|
keel agents [name] [--repo path] [--json] (external model CLIs, read on demand; Keel launches none)
|
|
109
109
|
keel shift request|check|ready|start|resume|status ... (a role's shift change; see keel shift --help)
|
|
110
|
+
keel lock acquire|release|list ... (shared resource leases; see keel lock --help)
|
|
110
111
|
keel openspec [args...]
|
|
111
112
|
keel --init [repo] [--target claude|codex|opencode] [--dry-run] [--force-template-update]
|
|
112
113
|
keel --install [repo] [--target claude|codex|opencode] [--dry-run] [--force-template-update] [--with-git-hooks]
|
|
@@ -2854,6 +2855,9 @@ function main() {
|
|
|
2854
2855
|
if (process.argv[2] === "shift") {
|
|
2855
2856
|
return require("../src/core/shift").runShift(process.argv.slice(3));
|
|
2856
2857
|
}
|
|
2858
|
+
if (process.argv[2] === "lock") {
|
|
2859
|
+
return require("../src/core/lock").runLock(process.argv.slice(3));
|
|
2860
|
+
}
|
|
2857
2861
|
// `keel agents` likewise: the external model CLI catalog (#219).
|
|
2858
2862
|
if (process.argv[2] === "agents") {
|
|
2859
2863
|
return require("../src/core/agents").runAgents(process.argv.slice(3));
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@christang/keel",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.101.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.101.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.101.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.101.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",
|
|
@@ -47,8 +47,8 @@ REQUIRED_SCRIPTS = [
|
|
|
47
47
|
"scripts/validate_plugin.py",
|
|
48
48
|
]
|
|
49
49
|
|
|
50
|
-
PACKAGE_VERSION = "5.
|
|
51
|
-
PROTOCOL_VERSION = "5.
|
|
50
|
+
PACKAGE_VERSION = "5.101.0"
|
|
51
|
+
PROTOCOL_VERSION = "5.101.0"
|
|
52
52
|
LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
|
|
53
53
|
OPENSPEC_SCHEMA_NAME = "keel-spec-driven"
|
|
54
54
|
# Mirrors KEEL_PACKAGE_NAME in scripts/install_to_repo.py, one of the two
|
|
@@ -2442,6 +2442,85 @@ def chat_scratch_group(base: Path) -> tuple[Path, Path, dict[str, str]]:
|
|
|
2442
2442
|
return rtl, verify, env
|
|
2443
2443
|
|
|
2444
2444
|
|
|
2445
|
+
def validate_chat_supersedes_scenario() -> int:
|
|
2446
|
+
"""Issue #252: a record supersedes its author's earlier one.
|
|
2447
|
+
|
|
2448
|
+
A superseded record leaves unread, so it neither wakes nor is listed; a
|
|
2449
|
+
group view marks both records; and unread and the notice list newest first.
|
|
2450
|
+
"""
|
|
2451
|
+
label = "chat-supersedes:"
|
|
2452
|
+
with tempfile.TemporaryDirectory(prefix="keel-chat-supersedes-") as raw:
|
|
2453
|
+
base = Path(raw)
|
|
2454
|
+
rtl, verify, env = chat_scratch_group(base)
|
|
2455
|
+
|
|
2456
|
+
def chat(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
|
|
2457
|
+
return run_keel(cwd, "chat", *args, env=env)
|
|
2458
|
+
|
|
2459
|
+
def posted_id(result: subprocess.CompletedProcess[str]) -> str:
|
|
2460
|
+
return chat_json(result).get("id", "")
|
|
2461
|
+
|
|
2462
|
+
first = posted_id(chat(rtl, "post", "soc", "@verify verify owns integration", "--json"))
|
|
2463
|
+
second_run = chat(rtl, "post", "soc", "@verify design owns integration", "--supersedes", first, "--json")
|
|
2464
|
+
second = posted_id(second_run)
|
|
2465
|
+
if not first or not second:
|
|
2466
|
+
report(f"{label} the posts did not return ids: {second_run.stdout} {second_run.stderr}")
|
|
2467
|
+
return 1
|
|
2468
|
+
unread = [r.get("id") for r in chat_json(chat(verify, "unread", "--json")).get("unread", [])]
|
|
2469
|
+
if unread != [second]:
|
|
2470
|
+
report(f"{label} verify's unread is {unread!r}, not only the superseding record {second}.")
|
|
2471
|
+
return 1
|
|
2472
|
+
notice = chat_json(chat(verify, "notice", "--json")).get("notice", "")
|
|
2473
|
+
if first in notice:
|
|
2474
|
+
report(f"{label} the wake notice still lists the superseded record {first}: {notice!r}")
|
|
2475
|
+
return 1
|
|
2476
|
+
if second not in notice:
|
|
2477
|
+
report(f"{label} the wake notice does not list the superseding record {second}: {notice!r}")
|
|
2478
|
+
return 1
|
|
2479
|
+
view = chat(rtl, "soc", "--peek").stdout
|
|
2480
|
+
if f"(superseded by {second})" not in view:
|
|
2481
|
+
report(f"{label} the group view does not mark {first} superseded by {second}: {view!r}")
|
|
2482
|
+
return 1
|
|
2483
|
+
if f"(supersedes {first})" not in view:
|
|
2484
|
+
report(f"{label} the group view does not mark {second} as superseding {first}: {view!r}")
|
|
2485
|
+
return 1
|
|
2486
|
+
|
|
2487
|
+
refusals = []
|
|
2488
|
+
other = posted_id(chat(verify, "post", "soc", "verify's own note", "--json"))
|
|
2489
|
+
refusals.append(("another author's record", chat(rtl, "post", "soc", "x", "--supersedes", other), "verify"))
|
|
2490
|
+
refusals.append(("an already superseded record", chat(rtl, "post", "soc", "x", "--supersedes", first), second))
|
|
2491
|
+
gone = posted_id(chat(rtl, "post", "soc", "to retract", "--json"))
|
|
2492
|
+
chat(rtl, "retract", gone)
|
|
2493
|
+
refusals.append(("a retracted record", chat(rtl, "post", "soc", "x", "--supersedes", gone), "retracted"))
|
|
2494
|
+
chat(rtl, "group", "create", "ops", "--member", "verify")
|
|
2495
|
+
elsewhere = posted_id(chat(rtl, "post", "ops", "ops note", "--json"))
|
|
2496
|
+
refusals.append(("a record in another group", chat(rtl, "post", "soc", "x", "--supersedes", elsewhere), "ops"))
|
|
2497
|
+
for what, result, needle in refusals:
|
|
2498
|
+
if result.returncode == 0:
|
|
2499
|
+
report(f"{label} superseding {what} was accepted: {result.stdout}")
|
|
2500
|
+
return 1
|
|
2501
|
+
if needle not in result.stderr:
|
|
2502
|
+
report(f"{label} superseding {what} was refused without naming {needle!r}: {result.stderr}")
|
|
2503
|
+
return 1
|
|
2504
|
+
|
|
2505
|
+
chat(verify, "read")
|
|
2506
|
+
ordered = [posted_id(chat(rtl, "post", "soc", f"@verify step {n}", "--json")) for n in (1, 2, 3)]
|
|
2507
|
+
listed = [r.get("id") for r in chat_json(chat(verify, "unread", "--json")).get("unread", [])]
|
|
2508
|
+
if listed != list(reversed(ordered)):
|
|
2509
|
+
report(f"{label} unread is not newest first: {listed!r}, posted {ordered!r}.")
|
|
2510
|
+
return 1
|
|
2511
|
+
notice = chat_json(chat(verify, "notice", "--json")).get("notice", "")
|
|
2512
|
+
positions = [notice.find(i) for i in reversed(ordered)]
|
|
2513
|
+
if -1 in positions:
|
|
2514
|
+
report(f"{label} the wake notice does not list all three posts: {notice!r}")
|
|
2515
|
+
return 1
|
|
2516
|
+
if positions != sorted(positions):
|
|
2517
|
+
report(f"{label} the wake notice is not newest first: {notice!r}")
|
|
2518
|
+
return 1
|
|
2519
|
+
|
|
2520
|
+
report("chat-supersedes scenario passed.")
|
|
2521
|
+
return 0
|
|
2522
|
+
|
|
2523
|
+
|
|
2445
2524
|
def validate_chat_records_scenario() -> int:
|
|
2446
2525
|
"""Issue #187: todos, edits, retractions, search, and local-time display.
|
|
2447
2526
|
|
|
@@ -3112,6 +3191,8 @@ def validate_chat_bridge_outbound_scenario() -> int:
|
|
|
3112
3191
|
chat(rtl, "edit", root_id, "Clock fix is in (v2)")
|
|
3113
3192
|
gone_id = chat_json(chat(rtl, "post", "soc", "wrong group", "--json")).get("id", "")
|
|
3114
3193
|
chat(rtl, "retract", gone_id)
|
|
3194
|
+
old_rule_id = chat_json(chat(rtl, "post", "soc", "verify owns integration", "--json")).get("id", "")
|
|
3195
|
+
new_rule_id = chat_json(chat(rtl, "post", "soc", "design owns integration", "--supersedes", old_rule_id, "--json")).get("id", "")
|
|
3115
3196
|
slack.rate_limit("chat.postMessage", 1)
|
|
3116
3197
|
|
|
3117
3198
|
started = time.time()
|
|
@@ -3195,6 +3276,18 @@ def validate_chat_bridge_outbound_scenario() -> int:
|
|
|
3195
3276
|
if not any(c["params"].get("ts") == gone_ts for c in slack.calls_to("chat.delete")):
|
|
3196
3277
|
report(f"{label} the retraction did not call chat.delete.")
|
|
3197
3278
|
return 1
|
|
3279
|
+
# Issue #252: a superseded record's Slack copy says so.
|
|
3280
|
+
if not new_rule_id:
|
|
3281
|
+
report(f"{label} the superseding post returned no id.")
|
|
3282
|
+
return 1
|
|
3283
|
+
old_rule_ts = next(m["ts"] for m in slack.messages["CSOC"] if (m.get("metadata") or {}).get("event_payload", {}).get("id") == old_rule_id)
|
|
3284
|
+
marked = [c for c in slack.calls_to("chat.update") if c["params"].get("ts") == old_rule_ts]
|
|
3285
|
+
if not marked:
|
|
3286
|
+
report(f"{label} the superseded record's Slack message was never updated.")
|
|
3287
|
+
return 1
|
|
3288
|
+
if not marked[-1]["params"].get("text", "").startswith(f"(superseded by {new_rule_id})"):
|
|
3289
|
+
report(f"{label} the superseded Slack message does not open with its successor: {marked[-1]['params'].get('text')!r}")
|
|
3290
|
+
return 1
|
|
3198
3291
|
|
|
3199
3292
|
before = len(slack.calls_to("chat.postMessage"))
|
|
3200
3293
|
# launchd starts the bridge in `/`, outside every repository, so the
|
|
@@ -4457,6 +4550,261 @@ def validate_collected_feedback_is_recorded_scenario() -> int:
|
|
|
4457
4550
|
return 0
|
|
4458
4551
|
|
|
4459
4552
|
|
|
4553
|
+
def validate_resource_lock_scenario() -> int:
|
|
4554
|
+
"""Bounded exclusive leases, shared by worktrees, through the real CLI."""
|
|
4555
|
+
label = "resource-lock:"
|
|
4556
|
+
with tempfile.TemporaryDirectory(prefix="keel-resource-lock-") as raw:
|
|
4557
|
+
a, b, env = chat_scratch_group(Path(raw))
|
|
4558
|
+
for tree, role in ((a, "integ"), (b, "sweep")):
|
|
4559
|
+
bound = run_keel(tree, "chat", "role", "--set", role, env=env)
|
|
4560
|
+
if bound.returncode != 0:
|
|
4561
|
+
report(f"{label} could not bind {role}: {bound.stderr}")
|
|
4562
|
+
return 1
|
|
4563
|
+
locks = mailbox_common_dir(a) / "keel-chat" / "locks"
|
|
4564
|
+
lease_file = locks / "main-checkout.json"
|
|
4565
|
+
|
|
4566
|
+
def lock(tree: Path, *args: str) -> subprocess.CompletedProcess[str]:
|
|
4567
|
+
return run_keel(tree, "lock", *args, env=env)
|
|
4568
|
+
|
|
4569
|
+
def leases() -> list[dict]:
|
|
4570
|
+
result = lock(b, "list", "--json")
|
|
4571
|
+
if result.returncode != 0:
|
|
4572
|
+
report(f"{label} list --json failed: {result.stderr}")
|
|
4573
|
+
return [{}]
|
|
4574
|
+
try:
|
|
4575
|
+
return json.loads(result.stdout)["leases"]
|
|
4576
|
+
except (ValueError, KeyError, TypeError):
|
|
4577
|
+
report(f"{label} list --json lacks lease data: {result.stdout}")
|
|
4578
|
+
return [{}]
|
|
4579
|
+
|
|
4580
|
+
malformed = [
|
|
4581
|
+
(("acquire", "main-checkout", "--note", "x"), "--for"),
|
|
4582
|
+
(("acquire", "main-checkout", "--for", "5x", "--note", "x"), "5x"),
|
|
4583
|
+
(("acquire", "main-checkout", "--for", "1h"), "--note"),
|
|
4584
|
+
(("acquire", "../x", "--for", "1h", "--note", "x"), "../x"),
|
|
4585
|
+
(("acquire", "main-checkout", "--for", "0s", "--note", "x"), "0s"),
|
|
4586
|
+
(("acquire", "main-checkout", "--for", "1h", "--note", " "), "--note"),
|
|
4587
|
+
(("acquire", "x" * 65, "--for", "1h", "--note", "x"), "resource"),
|
|
4588
|
+
(("acquire", "main-checkout", "--for", "9" * 30 + "d", "--note", "x"), "duration"),
|
|
4589
|
+
]
|
|
4590
|
+
for args, needle in malformed:
|
|
4591
|
+
refused = lock(a, *args)
|
|
4592
|
+
if refused.returncode == 0:
|
|
4593
|
+
report(f"{label} malformed acquire succeeded: {args}")
|
|
4594
|
+
return 1
|
|
4595
|
+
if needle not in refused.stdout + refused.stderr:
|
|
4596
|
+
report(f"{label} malformed acquire does not name {needle!r}: {refused.stderr}")
|
|
4597
|
+
return 1
|
|
4598
|
+
if leases():
|
|
4599
|
+
report(f"{label} malformed acquire recorded a lease: {args}")
|
|
4600
|
+
return 1
|
|
4601
|
+
|
|
4602
|
+
acquired = lock(a, "acquire", "main-checkout", "--for", "2h", "--note", "integration run")
|
|
4603
|
+
if acquired.returncode != 0:
|
|
4604
|
+
report(f"{label} acquire failed: {acquired.stderr}")
|
|
4605
|
+
return 1
|
|
4606
|
+
if "enforces nothing" not in acquired.stdout:
|
|
4607
|
+
report(f"{label} acquire does not say the lease enforces nothing: {acquired.stdout}")
|
|
4608
|
+
return 1
|
|
4609
|
+
rows = leases()
|
|
4610
|
+
if len(rows) != 1:
|
|
4611
|
+
report(f"{label} acquire did not record exactly one lease: {rows}")
|
|
4612
|
+
return 1
|
|
4613
|
+
first = rows[0]
|
|
4614
|
+
for key, expected in (("resource", "main-checkout"), ("holder", "integ"), ("role", "integ"), ("worktree", str(a.resolve())), ("note", "integration run")):
|
|
4615
|
+
if first.get(key) != expected:
|
|
4616
|
+
report(f"{label} acquired {key} differs: {first}")
|
|
4617
|
+
return 1
|
|
4618
|
+
for key in ("acquired", "expires"):
|
|
4619
|
+
if not first.get(key):
|
|
4620
|
+
report(f"{label} lease lacks {key}: {first}")
|
|
4621
|
+
return 1
|
|
4622
|
+
datetime.fromisoformat(first[key])
|
|
4623
|
+
listed = lock(b, "list")
|
|
4624
|
+
if listed.returncode != 0:
|
|
4625
|
+
report(f"{label} other-worktree list failed: {listed.stderr}")
|
|
4626
|
+
return 1
|
|
4627
|
+
for needle in ("main-checkout", "integ", first["expires"], "integration run", str(a.resolve())):
|
|
4628
|
+
if needle not in listed.stdout:
|
|
4629
|
+
report(f"{label} other-worktree list lacks {needle!r}: {listed.stdout}")
|
|
4630
|
+
return 1
|
|
4631
|
+
for attempt in range(2):
|
|
4632
|
+
refused = lock(b, "acquire", "main-checkout", "--for", "1h", "--note", "formal sweep")
|
|
4633
|
+
if refused.returncode != 1:
|
|
4634
|
+
report(f"{label} held acquire attempt {attempt} exited {refused.returncode}")
|
|
4635
|
+
return 1
|
|
4636
|
+
for needle in ("integ", first["expires"], "integration run", str(a.resolve())):
|
|
4637
|
+
if needle not in refused.stdout + refused.stderr:
|
|
4638
|
+
report(f"{label} held acquire omits {needle!r}: {refused.stderr}")
|
|
4639
|
+
return 1
|
|
4640
|
+
waiting = leases()[0]
|
|
4641
|
+
if [w.get("holder") for w in waiting.get("waiters", [])] != ["sweep"]:
|
|
4642
|
+
report(f"{label} waiter is absent or duplicated: {waiting}")
|
|
4643
|
+
return 1
|
|
4644
|
+
renewed = lock(a, "acquire", "main-checkout", "--for", "3h", "--note", "integration, extended")
|
|
4645
|
+
if renewed.returncode != 0:
|
|
4646
|
+
report(f"{label} renewal failed: {renewed.stderr}")
|
|
4647
|
+
return 1
|
|
4648
|
+
extended = leases()[0]
|
|
4649
|
+
if datetime.fromisoformat(extended["expires"]) <= datetime.fromisoformat(first["expires"]):
|
|
4650
|
+
report(f"{label} renewal did not extend expiry: {extended}")
|
|
4651
|
+
return 1
|
|
4652
|
+
if extended.get("note") != "integration, extended":
|
|
4653
|
+
report(f"{label} renewal did not update note: {extended}")
|
|
4654
|
+
return 1
|
|
4655
|
+
if extended.get("acquired") != first["acquired"]:
|
|
4656
|
+
report(f"{label} renewal replaced acquisition time: {extended}")
|
|
4657
|
+
return 1
|
|
4658
|
+
if extended.get("waiters") != waiting["waiters"]:
|
|
4659
|
+
report(f"{label} renewal lost waiters: {extended}")
|
|
4660
|
+
return 1
|
|
4661
|
+
refused = lock(b, "release", "main-checkout")
|
|
4662
|
+
if refused.returncode != 1:
|
|
4663
|
+
report(f"{label} waiter release exited {refused.returncode}")
|
|
4664
|
+
return 1
|
|
4665
|
+
if "integ" not in refused.stdout + refused.stderr:
|
|
4666
|
+
report(f"{label} waiter release does not name integ: {refused.stderr}")
|
|
4667
|
+
return 1
|
|
4668
|
+
if not lease_file.exists():
|
|
4669
|
+
report(f"{label} waiter release removed the lease")
|
|
4670
|
+
return 1
|
|
4671
|
+
released = lock(a, "release", "main-checkout")
|
|
4672
|
+
if released.returncode != 0:
|
|
4673
|
+
report(f"{label} holder release failed: {released.stderr}")
|
|
4674
|
+
return 1
|
|
4675
|
+
if leases():
|
|
4676
|
+
report(f"{label} holder release left a lease listed")
|
|
4677
|
+
return 1
|
|
4678
|
+
messages = chat_records_with(a, "dm-integ--sweep", "lock main-checkout released by integ")
|
|
4679
|
+
if len(messages) != 1:
|
|
4680
|
+
report(f"{label} release did not post exactly one direct message: {messages}")
|
|
4681
|
+
return 1
|
|
4682
|
+
reacquired = lock(a, "acquire", "main-checkout", "--for", "2h", "--note", "integration run")
|
|
4683
|
+
if reacquired.returncode != 0:
|
|
4684
|
+
report(f"{label} expiry fixture acquire failed: {reacquired.stderr}")
|
|
4685
|
+
return 1
|
|
4686
|
+
queued = lock(b, "acquire", "main-checkout", "--for", "1h", "--note", "formal sweep")
|
|
4687
|
+
if queued.returncode != 1:
|
|
4688
|
+
report(f"{label} expiry fixture waiter was not refused: {queued.stdout} {queued.stderr}")
|
|
4689
|
+
return 1
|
|
4690
|
+
expired = json.loads(lease_file.read_text())
|
|
4691
|
+
expired["expires"] = "2000-01-01T00:00:00+00:00"
|
|
4692
|
+
lease_file.write_text(json.dumps(expired))
|
|
4693
|
+
if leases():
|
|
4694
|
+
report(f"{label} expiry left a lease listed")
|
|
4695
|
+
return 1
|
|
4696
|
+
if lease_file.exists():
|
|
4697
|
+
report(f"{label} expiry left the lease file")
|
|
4698
|
+
return 1
|
|
4699
|
+
again = lock(b, "list")
|
|
4700
|
+
if again.returncode != 0:
|
|
4701
|
+
report(f"{label} second expiry list failed: {again.stderr}")
|
|
4702
|
+
return 1
|
|
4703
|
+
messages = chat_records_with(a, "dm-integ--sweep", "lock main-checkout expired at")
|
|
4704
|
+
if len(messages) != 1:
|
|
4705
|
+
report(f"{label} expiry did not post exactly once to integ: {messages}")
|
|
4706
|
+
return 1
|
|
4707
|
+
if "from: sweep" not in messages[0]:
|
|
4708
|
+
report(f"{label} expiry message is not from sweep: {messages[0]}")
|
|
4709
|
+
return 1
|
|
4710
|
+
if chat_records_with(b, "dm-sweep--sweep", "lock main-checkout expired at"):
|
|
4711
|
+
report(f"{label} expiry posted a direct message from sweep to itself")
|
|
4712
|
+
return 1
|
|
4713
|
+
reclaimed = lock(b, "acquire", "main-checkout", "--for", "1h", "--note", "formal sweep")
|
|
4714
|
+
if reclaimed.returncode != 0:
|
|
4715
|
+
report(f"{label} sweep could not acquire after expiry: {reclaimed.stderr}")
|
|
4716
|
+
return 1
|
|
4717
|
+
released = lock(b, "release", "main-checkout")
|
|
4718
|
+
if released.returncode != 0:
|
|
4719
|
+
report(f"{label} sweep release after expiry failed: {released.stderr}")
|
|
4720
|
+
return 1
|
|
4721
|
+
|
|
4722
|
+
# Simultaneous public commands: a lease must have exactly one winner.
|
|
4723
|
+
command = ["node", str(ROOT / "bin" / "keel.js"), "lock", "acquire", "race", "--for", "1h", "--note", "race"]
|
|
4724
|
+
racers = [subprocess.Popen(command, cwd=tree, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) for tree in (a, b)]
|
|
4725
|
+
outputs = [p.communicate(timeout=30) for p in racers]
|
|
4726
|
+
if sorted(p.returncode for p in racers) != [0, 1]:
|
|
4727
|
+
report(f"{label} racing acquires lack exactly one winner: {outputs}")
|
|
4728
|
+
return 1
|
|
4729
|
+
rows = leases()
|
|
4730
|
+
if len(rows) != 1:
|
|
4731
|
+
report(f"{label} race recorded other than one lease: {rows}")
|
|
4732
|
+
return 1
|
|
4733
|
+
winner = a if racers[0].returncode == 0 else b
|
|
4734
|
+
if rows[0].get("worktree") != str(winner.resolve()):
|
|
4735
|
+
report(f"{label} race lease does not belong to the winner: {rows}")
|
|
4736
|
+
return 1
|
|
4737
|
+
if len(rows[0].get("waiters", [])) != 1:
|
|
4738
|
+
report(f"{label} racing loser was not recorded as a waiter: {rows}")
|
|
4739
|
+
return 1
|
|
4740
|
+
released = lock(winner, "release", "race")
|
|
4741
|
+
if released.returncode != 0:
|
|
4742
|
+
report(f"{label} race winner could not release: {released.stderr}")
|
|
4743
|
+
return 1
|
|
4744
|
+
|
|
4745
|
+
# A mutex left by a crashed command is stale after 30 seconds.
|
|
4746
|
+
mutex = locks / ".mutation"
|
|
4747
|
+
mutex.mkdir(parents=True, exist_ok=True)
|
|
4748
|
+
os.utime(mutex, (time.time() - 120, time.time() - 120))
|
|
4749
|
+
unstuck = lock(a, "list")
|
|
4750
|
+
if unstuck.returncode != 0:
|
|
4751
|
+
report(f"{label} a stale mutex blocked keel lock list: {unstuck.stderr}")
|
|
4752
|
+
return 1
|
|
4753
|
+
if mutex.exists():
|
|
4754
|
+
report(f"{label} a stale mutex was left in place after keel lock list.")
|
|
4755
|
+
return 1
|
|
4756
|
+
|
|
4757
|
+
# No role: worktree identity, --repo, read-only shift and printed expiry.
|
|
4758
|
+
c = chat_worktree(a, Path(raw) / "unbound")
|
|
4759
|
+
acquired = lock(a, "acquire", "cpu-1", "--for", "1h", "--note", "slot", "--repo", str(c))
|
|
4760
|
+
if acquired.returncode != 0:
|
|
4761
|
+
report(f"{label} unbound --repo acquire failed: {acquired.stderr}")
|
|
4762
|
+
return 1
|
|
4763
|
+
row = leases()[0]
|
|
4764
|
+
if not row.get("holder", "").startswith("worktree:unbound-"):
|
|
4765
|
+
report(f"{label} unbound lease lacks worktree identity: {row}")
|
|
4766
|
+
return 1
|
|
4767
|
+
if row.get("role") is not None:
|
|
4768
|
+
report(f"{label} unbound lease has a chat role: {row}")
|
|
4769
|
+
return 1
|
|
4770
|
+
file = locks / "cpu-1.json"
|
|
4771
|
+
row["expires"] = "2000-01-01T00:00:00+00:00"
|
|
4772
|
+
file.write_text(json.dumps(row))
|
|
4773
|
+
before = file.read_bytes()
|
|
4774
|
+
checked = run_keel(c, "shift", "check", "--json", env=env)
|
|
4775
|
+
if any(item["kind"] == "lock" for item in chat_json(checked).get("items", [])):
|
|
4776
|
+
report(f"{label} shift check reports an expired lease")
|
|
4777
|
+
return 1
|
|
4778
|
+
if file.read_bytes() != before:
|
|
4779
|
+
report(f"{label} shift check mutated the expired lease")
|
|
4780
|
+
return 1
|
|
4781
|
+
freed = lock(c, "list", "--json")
|
|
4782
|
+
if freed.returncode != 0:
|
|
4783
|
+
report(f"{label} unbound expiry command failed: {freed.stderr}")
|
|
4784
|
+
return 1
|
|
4785
|
+
if "cpu-1" not in freed.stderr:
|
|
4786
|
+
report(f"{label} unbound expiry was not printed beside JSON: {freed.stderr}")
|
|
4787
|
+
return 1
|
|
4788
|
+
if chat_json(freed).get("leases") != []:
|
|
4789
|
+
report(f"{label} unbound expiry list is not empty JSON: {freed.stdout}")
|
|
4790
|
+
return 1
|
|
4791
|
+
guide = ROOT / "docs" / "resource-lock.md"
|
|
4792
|
+
if not guide.exists():
|
|
4793
|
+
report(f"{label} docs/resource-lock.md is missing")
|
|
4794
|
+
return 1
|
|
4795
|
+
if "enforces nothing" not in guide.read_text():
|
|
4796
|
+
report(f"{label} guide does not say the lease enforces nothing")
|
|
4797
|
+
return 1
|
|
4798
|
+
if "docs/resource-lock.md" not in (ROOT / "README.md").read_text():
|
|
4799
|
+
report(f"{label} README does not link the guide")
|
|
4800
|
+
return 1
|
|
4801
|
+
if "resource-lock" not in {name for name, _ in SCENARIOS}:
|
|
4802
|
+
report(f"{label} scenario is not registered")
|
|
4803
|
+
return 1
|
|
4804
|
+
report("resource-lock scenario passed.")
|
|
4805
|
+
return 0
|
|
4806
|
+
|
|
4807
|
+
|
|
4460
4808
|
def validate_shift_change_scenario() -> int:
|
|
4461
4809
|
"""Owner's decision of 2026-10-05: a role's session changes shift through Keel.
|
|
4462
4810
|
|
|
@@ -4516,6 +4864,16 @@ def validate_shift_change_scenario() -> int:
|
|
|
4516
4864
|
subprocess.run(["git", "add", "pushed-not.txt"], cwd=verify, check=True)
|
|
4517
4865
|
subprocess.run(["git", "commit", "-q", "-m", "local only"], cwd=verify, check=True)
|
|
4518
4866
|
write_text(verify / "keel" / "guard.json", "{}\n")
|
|
4867
|
+
leased = run_keel(verify, "lock", "acquire", "main-checkout", "--for", "1h", "--note", "shift fixture", env=env)
|
|
4868
|
+
if leased.returncode != 0:
|
|
4869
|
+
report(f"{label} could not acquire the shift fixture lease: {leased.stderr}")
|
|
4870
|
+
return 1
|
|
4871
|
+
other_lease = run_keel(rtl, "lock", "acquire", "other-worktree", "--for", "1h", "--note", "other session", env=env)
|
|
4872
|
+
if other_lease.returncode != 0:
|
|
4873
|
+
report(f"{label} could not acquire the other worktree's lease: {other_lease.stderr}")
|
|
4874
|
+
return 1
|
|
4875
|
+
lease_file = common / "locks" / "main-checkout.json"
|
|
4876
|
+
lease_before = lease_file.read_bytes()
|
|
4519
4877
|
# A Claude scratchpad of a session started in verify, and one of a
|
|
4520
4878
|
# session started elsewhere (shift-temp-owner D1).
|
|
4521
4879
|
scratch = Path(tempfile.gettempdir()) / f"claude-{os.getuid()}"
|
|
@@ -4535,7 +4893,18 @@ def validate_shift_change_scenario() -> int:
|
|
|
4535
4893
|
report(f"{label} keel shift check exited {checked.returncode} with loose ends present.")
|
|
4536
4894
|
return 1
|
|
4537
4895
|
text = checked.stdout
|
|
4538
|
-
for
|
|
4896
|
+
lock_items = [item for item in chat_json(checked).get("items", []) if item["kind"] == "lock"]
|
|
4897
|
+
if len(lock_items) != 1:
|
|
4898
|
+
report(f"{label} expected exactly one held-worktree lock item: {text}")
|
|
4899
|
+
return 1
|
|
4900
|
+
for needle in ("main-checkout", "verify", "shift fixture", json.loads(lease_before)["expires"]):
|
|
4901
|
+
if needle not in lock_items[0]["detail"]:
|
|
4902
|
+
report(f"{label} lock item omits {needle!r}: {lock_items}")
|
|
4903
|
+
return 1
|
|
4904
|
+
if lease_file.read_bytes() != lease_before:
|
|
4905
|
+
report(f"{label} shift check changed the live lease")
|
|
4906
|
+
return 1
|
|
4907
|
+
for needle in ("scratch.txt", "local only", "guard.json", str(sleeper.pid), temp_tree.name, "Rerun the regression", "main-checkout"):
|
|
4539
4908
|
if needle not in text:
|
|
4540
4909
|
report(f"{label} keel shift check does not name {needle!r}: {text.strip()[:600]}")
|
|
4541
4910
|
return 1
|
|
@@ -4555,6 +4924,14 @@ def validate_shift_change_scenario() -> int:
|
|
|
4555
4924
|
|
|
4556
4925
|
(verify / "scratch.txt").unlink()
|
|
4557
4926
|
(verify / "keel" / "guard.json").unlink()
|
|
4927
|
+
released = run_keel(verify, "lock", "release", "main-checkout", env=env)
|
|
4928
|
+
if released.returncode != 0:
|
|
4929
|
+
report(f"{label} could not release the shift fixture lease: {released.stderr}")
|
|
4930
|
+
return 1
|
|
4931
|
+
after_release = shift(verify, "check", "--json")
|
|
4932
|
+
if any(item["kind"] == "lock" for item in chat_json(after_release).get("items", [])):
|
|
4933
|
+
report(f"{label} shift check retained a lock item after release: {after_release.stdout}")
|
|
4934
|
+
return 1
|
|
4558
4935
|
subprocess.run(["git", "push", "-q"], cwd=verify, check=True, capture_output=True)
|
|
4559
4936
|
subprocess.run(["git", "worktree", "remove", "--force", str(temp_tree)], cwd=verify, check=True)
|
|
4560
4937
|
todo_id = next(r for r in chat_records_with(rtl, "soc", "Rerun the regression"))
|
|
@@ -37356,6 +37733,8 @@ SCENARIOS: tuple = (
|
|
|
37356
37733
|
("collected-feedback-is-recorded", validate_collected_feedback_is_recorded_scenario),
|
|
37357
37734
|
("shift-change", validate_shift_change_scenario),
|
|
37358
37735
|
("shift-without-role", validate_shift_without_role_scenario),
|
|
37736
|
+
("resource-lock", validate_resource_lock_scenario),
|
|
37737
|
+
("chat-supersedes", validate_chat_supersedes_scenario),
|
|
37359
37738
|
("init-never-downgrades-openspec", validate_init_never_downgrades_openspec_scenario),
|
|
37360
37739
|
("native-plugin-marketplaces", validate_native_plugin_marketplaces_scenario),
|
|
37361
37740
|
("native-plugin-install-matrix", validate_native_plugin_install_matrix_scenario),
|
package/src/core/chat/bridge.js
CHANGED
|
@@ -256,6 +256,7 @@ async function postRecord(ctx, project, record, channel, direct = null) {
|
|
|
256
256
|
const sent = await call("chat.postMessage", params, direct.token);
|
|
257
257
|
writePosted(where, record.id, { channel, ts: sent.ts, thread_ts: params.thread_ts || null, as: direct.role, direct: true });
|
|
258
258
|
rememberTs(project, channel, sent.ts, record.id);
|
|
259
|
+
await markSuperseded(ctx, project, record, call);
|
|
259
260
|
return;
|
|
260
261
|
}
|
|
261
262
|
const app = roleApp(ctx, project, record.from);
|
|
@@ -281,6 +282,7 @@ async function postRecord(ctx, project, record, channel, direct = null) {
|
|
|
281
282
|
if (as) posted.as = as;
|
|
282
283
|
writePosted(where, record.id, posted);
|
|
283
284
|
rememberTs(project, channel, response.ts, record.id);
|
|
285
|
+
await markSuperseded(ctx, project, record, call);
|
|
284
286
|
// Another project on this machine that maps the same channel gets the
|
|
285
287
|
// record now, without waiting for Slack to echo it back (D16).
|
|
286
288
|
for (const other of ctx.projects) {
|
|
@@ -289,6 +291,18 @@ async function postRecord(ctx, project, record, channel, direct = null) {
|
|
|
289
291
|
}
|
|
290
292
|
}
|
|
291
293
|
|
|
294
|
+
// A record that supersedes another (#252 D5) also marks the earlier Slack
|
|
295
|
+
// message, with the token of the app that posted it, as an edit does.
|
|
296
|
+
async function markSuperseded(ctx, project, record, call) {
|
|
297
|
+
if (!record.supersedes) return;
|
|
298
|
+
const target = readPosted(project.where, record.supersedes);
|
|
299
|
+
if (!target || !target.ts) return;
|
|
300
|
+
const original = store.findRecord(project.where, record.supersedes) || {};
|
|
301
|
+
const poster = target.as ? roleApp(ctx, project, target.as) : null;
|
|
302
|
+
const text = `(superseded by ${record.id}) ${slackText(project, original, bodyText(original))}`;
|
|
303
|
+
await call("chat.update", { channel: target.channel, ts: target.ts, text }, poster ? poster.token : ctx.token);
|
|
304
|
+
}
|
|
305
|
+
|
|
292
306
|
// Every record that originated on this machine, in a mapped group, and not yet
|
|
293
307
|
// posted, in id order. The queue is derived, so it survives any restart.
|
|
294
308
|
function pendingOutbound(project) {
|
package/src/core/chat/cli.js
CHANGED
|
@@ -20,7 +20,7 @@ const USAGE = [
|
|
|
20
20
|
"keel chat group add|remove <group> <role>",
|
|
21
21
|
"keel chat group archive <group>",
|
|
22
22
|
"keel chat group list [--all] [--json] (also: keel chat list)",
|
|
23
|
-
"keel chat post <group> <text...> [--reply-to <id>] [--json] (also: keel chat <group> <text...>)",
|
|
23
|
+
"keel chat post <group> <text...> [--reply-to <id>] [--supersedes <id>] [--json] (also: keel chat <group> <text...>)",
|
|
24
24
|
"keel chat dm <role> <text...> [--json]",
|
|
25
25
|
"keel chat <group> [--since <90s|15m|2h|3d|date>] [--follow] [--peek] [--json] (view; advances your read position unless --peek)",
|
|
26
26
|
"keel chat unread [--json]",
|
|
@@ -53,6 +53,7 @@ const VALUED = {
|
|
|
53
53
|
"--set": "set",
|
|
54
54
|
"--alias": "alias",
|
|
55
55
|
"--reply-to": "replyTo",
|
|
56
|
+
"--supersedes": "supersedes",
|
|
56
57
|
"--repo": "repo",
|
|
57
58
|
"--assignee": "assignee",
|
|
58
59
|
"--issue": "issue",
|
|
@@ -259,7 +260,7 @@ function dispatch(where, options) {
|
|
|
259
260
|
case "post": {
|
|
260
261
|
const [group, ...words] = rest;
|
|
261
262
|
if (!group) throw new ChatError("keel chat post needs a group.");
|
|
262
|
-
postResult(where, store.post(where, { group, text: textFrom(words), replyTo: options.replyTo }), options.json);
|
|
263
|
+
postResult(where, store.post(where, { group, text: textFrom(words), replyTo: options.replyTo, supersedes: options.supersedes }), options.json);
|
|
263
264
|
return 0;
|
|
264
265
|
}
|
|
265
266
|
case "dm": {
|
|
@@ -270,7 +271,8 @@ function dispatch(where, options) {
|
|
|
270
271
|
}
|
|
271
272
|
case "unread": {
|
|
272
273
|
const role = store.requireRole(where);
|
|
273
|
-
|
|
274
|
+
// Newest first (#252 D3): the latest word is the one to read first.
|
|
275
|
+
const records = store.unread(where, role).reverse();
|
|
274
276
|
if (options.json) out(JSON.stringify({ role, unread: records.map(publicRecord) }));
|
|
275
277
|
else out(records.length ? records.map((r) => `${r.group} ${formatLine(r)}`).join("\n") : `keel chat: nothing unread for role \`${role}\`.`);
|
|
276
278
|
return 0;
|
|
@@ -363,7 +365,7 @@ function dispatch(where, options) {
|
|
|
363
365
|
default: {
|
|
364
366
|
// `keel chat <group>` views; `keel chat <group> <text...>` posts.
|
|
365
367
|
if (rest.length) {
|
|
366
|
-
postResult(where, store.post(where, { group: command, text: rest.join(" "), replyTo: options.replyTo }), options.json);
|
|
368
|
+
postResult(where, store.post(where, { group: command, text: rest.join(" "), replyTo: options.replyTo, supersedes: options.supersedes }), options.json);
|
|
367
369
|
return 0;
|
|
368
370
|
}
|
|
369
371
|
return runView(where, command, options);
|
package/src/core/chat/notice.js
CHANGED
|
@@ -26,7 +26,8 @@ function firstLine(text) {
|
|
|
26
26
|
}
|
|
27
27
|
|
|
28
28
|
function noticeText(where, role, now = Date.now()) {
|
|
29
|
-
|
|
29
|
+
// Newest first (#252 D3).
|
|
30
|
+
const records = store.unread(where, role).reverse();
|
|
30
31
|
if (!records.length) return "";
|
|
31
32
|
const waking = records.filter((record) => store.wakes(record, role));
|
|
32
33
|
const others = new Map();
|
package/src/core/chat/store.js
CHANGED
|
@@ -40,7 +40,7 @@ const DATA_NOTICE =
|
|
|
40
40
|
const READABLE_KINDS = new Set(["message", "todo", "system"]);
|
|
41
41
|
const LIST_FIELDS = new Set(["mentions", "refs"]);
|
|
42
42
|
const FIELD_ORDER = [
|
|
43
|
-
"id", "group", "kind", "from", "created", "mentions", "reply_to",
|
|
43
|
+
"id", "group", "kind", "from", "created", "mentions", "reply_to", "supersedes",
|
|
44
44
|
"assignee", "issue", "target", "refs", "origin", "slack_channel", "slack_ts",
|
|
45
45
|
];
|
|
46
46
|
|
|
@@ -559,12 +559,14 @@ function post(where, options) {
|
|
|
559
559
|
if (options.replyTo) {
|
|
560
560
|
parent = findRecord(where, options.replyTo);
|
|
561
561
|
}
|
|
562
|
+
if (options.supersedes) checkSupersedes(where, from, group, records, options.supersedes);
|
|
562
563
|
const record = writeRecord(where, {
|
|
563
564
|
group,
|
|
564
565
|
kind: options.kind || "message",
|
|
565
566
|
from,
|
|
566
567
|
mentions,
|
|
567
568
|
reply_to: options.replyTo || null,
|
|
569
|
+
supersedes: options.supersedes || null,
|
|
568
570
|
assignee: options.assignee || null,
|
|
569
571
|
issue: options.issue || null,
|
|
570
572
|
refs: options.refs || [],
|
|
@@ -582,6 +584,40 @@ function post(where, options) {
|
|
|
582
584
|
|
|
583
585
|
const DONE_REPLY = /^\s*(done\b|✅)/i;
|
|
584
586
|
|
|
587
|
+
// A record supersedes only its author's current version of a message or todo
|
|
588
|
+
// in the same group (#252 D1), so the chain stays linear and readable.
|
|
589
|
+
function checkSupersedes(where, from, group, records, id) {
|
|
590
|
+
const target = findRecord(where, id);
|
|
591
|
+
if (!target) throw new ChatError(`No record ${id} to supersede.`);
|
|
592
|
+
if (target.group !== group) {
|
|
593
|
+
throw new ChatError(`Record ${id} is in group ${target.group}, not ${group}; a record supersedes only one in its own group.`);
|
|
594
|
+
}
|
|
595
|
+
if (!["message", "todo"].includes(target.kind)) {
|
|
596
|
+
throw new ChatError(`Record ${id} is a ${target.kind}; only a message or todo can be superseded.`);
|
|
597
|
+
}
|
|
598
|
+
if (target.from !== from) {
|
|
599
|
+
throw new ChatError(`Record ${id} was written by ${target.from}; only its author may supersede it.`);
|
|
600
|
+
}
|
|
601
|
+
if (records.some((record) => record.kind === "retract" && record.target === id)) {
|
|
602
|
+
throw new ChatError(`Record ${id} was retracted; post a new record instead.`);
|
|
603
|
+
}
|
|
604
|
+
const successor = records.find((record) => record.supersedes === id);
|
|
605
|
+
if (successor) {
|
|
606
|
+
throw new ChatError(`Record ${id} is already superseded by ${successor.id}; supersede ${successor.id} instead.`);
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
// Ids a later record of the same author supersedes, in one group's log.
|
|
611
|
+
function supersededIds(records) {
|
|
612
|
+
const byId = new Map(records.map((record) => [record.id, record]));
|
|
613
|
+
const ids = new Set();
|
|
614
|
+
for (const record of records) {
|
|
615
|
+
const target = record.supersedes && byId.get(record.supersedes);
|
|
616
|
+
if (target && target.from === record.from) ids.add(target.id);
|
|
617
|
+
}
|
|
618
|
+
return ids;
|
|
619
|
+
}
|
|
620
|
+
|
|
585
621
|
function isDone(where, todo) {
|
|
586
622
|
return readLog(where, todo.group).some((record) => record.kind === "done" && record.target === todo.id);
|
|
587
623
|
}
|
|
@@ -727,8 +763,10 @@ function unread(where, role) {
|
|
|
727
763
|
const state = groupState(records);
|
|
728
764
|
if (!state.exists || state.archived || !canAct(state, role)) continue;
|
|
729
765
|
const cursor = readCursor(where, role, group);
|
|
766
|
+
// A superseded record is no one's to act on (#252 D2), read or not.
|
|
767
|
+
const superseded = supersededIds(records);
|
|
730
768
|
for (const record of records) {
|
|
731
|
-
if (record.id > cursor && readable(record) && record.from !== role) result.push(record);
|
|
769
|
+
if (record.id > cursor && readable(record) && record.from !== role && !superseded.has(record.id)) result.push(record);
|
|
732
770
|
}
|
|
733
771
|
}
|
|
734
772
|
return result;
|
package/src/core/chat/view.js
CHANGED
|
@@ -63,6 +63,10 @@ function displayRecords(records) {
|
|
|
63
63
|
continue;
|
|
64
64
|
}
|
|
65
65
|
const copy = { ...record };
|
|
66
|
+
if (copy.supersedes) {
|
|
67
|
+
const old = byId.get(copy.supersedes);
|
|
68
|
+
if (old && old.from === copy.from) old.superseded_by = copy.id;
|
|
69
|
+
}
|
|
66
70
|
if (copy.kind === "done") {
|
|
67
71
|
const todo = byId.get(copy.target);
|
|
68
72
|
if (todo) todo.done = true;
|
|
@@ -79,6 +83,8 @@ function markers(record) {
|
|
|
79
83
|
parts.push(`[todo → ${record.assignee || "?"}${record.issue ? ` ${record.issue}` : ""}${record.done ? ", done" : ""}]`);
|
|
80
84
|
}
|
|
81
85
|
if (record.reply_to) parts.push(`↳ ${record.reply_to}`);
|
|
86
|
+
if (record.superseded_by) parts.push(`(superseded by ${record.superseded_by})`);
|
|
87
|
+
if (record.supersedes) parts.push(`(supersedes ${record.supersedes})`);
|
|
82
88
|
// A mention the text already spells out is not repeated; one written as an
|
|
83
89
|
// alias (`@cb`) still shows the role it resolved to (#196).
|
|
84
90
|
const text = String(record.text || "").toLowerCase();
|
package/src/core/lock.js
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
// Resource-lock D1-D6: cooperative leases in the git common chat store.
|
|
4
|
+
// These records never guard Git operations or access to the named resource.
|
|
5
|
+
const fs = require("fs");
|
|
6
|
+
const path = require("path");
|
|
7
|
+
const crypto = require("crypto");
|
|
8
|
+
const store = require("./chat/store");
|
|
9
|
+
|
|
10
|
+
const RESOURCE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
11
|
+
const USAGE = [
|
|
12
|
+
"keel lock acquire <resource> --for <n>s|m|h|d --note <why> acquire or renew",
|
|
13
|
+
"keel lock release <resource> holder only",
|
|
14
|
+
"keel lock list [--json] live leases",
|
|
15
|
+
"Options: --repo <path>, --json. See docs/resource-lock.md.",
|
|
16
|
+
"A lease enforces nothing on Git or the filesystem.",
|
|
17
|
+
].join("\n");
|
|
18
|
+
|
|
19
|
+
class LockError extends Error {}
|
|
20
|
+
|
|
21
|
+
function lockDir(where) {
|
|
22
|
+
return path.join(where.root, "locks");
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function identity(where) {
|
|
26
|
+
const role = store.currentRole(where);
|
|
27
|
+
const id = crypto.createHash("sha256").update(where.worktree).digest("hex").slice(0, 8);
|
|
28
|
+
return { holder: role || "worktree:" + path.basename(where.worktree) + "-" + id, role: role || null, worktree: where.worktree };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function checkResource(resource) {
|
|
32
|
+
if (!RESOURCE.test(resource || "")) {
|
|
33
|
+
throw new LockError("Invalid resource " + JSON.stringify(resource) + ': use 1–64 letters, digits, ".", "_" or "-", starting with a letter or digit.');
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function expiry(duration, now) {
|
|
38
|
+
const match = String(duration || "").match(/^(\d+)([smhd])$/);
|
|
39
|
+
const amount = match ? Number(match[1]) : 0;
|
|
40
|
+
const unit = match ? { s: 1000, m: 60000, h: 3600000, d: 86400000 }[match[2]] : 0;
|
|
41
|
+
const date = new Date(now.getTime() + amount * unit);
|
|
42
|
+
if (!match || !Number.isSafeInteger(amount) || amount <= 0 || !Number.isFinite(date.getTime()) || date.getFullYear() > 9999) {
|
|
43
|
+
throw new LockError("Invalid --for duration " + JSON.stringify(duration) + ": use a positive integer followed by s, m, h or d.");
|
|
44
|
+
}
|
|
45
|
+
return store.isoLocal(date);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function readLeases(where) {
|
|
49
|
+
let files;
|
|
50
|
+
try {
|
|
51
|
+
files = fs.readdirSync(lockDir(where));
|
|
52
|
+
} catch (error) {
|
|
53
|
+
if (error.code === "ENOENT") return [];
|
|
54
|
+
throw error;
|
|
55
|
+
}
|
|
56
|
+
const leases = [];
|
|
57
|
+
for (const name of files.sort()) {
|
|
58
|
+
if (!name.endsWith(".json")) continue;
|
|
59
|
+
const file = path.join(lockDir(where), name);
|
|
60
|
+
let lease;
|
|
61
|
+
try {
|
|
62
|
+
lease = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
63
|
+
} catch (error) {
|
|
64
|
+
if (error.code === "ENOENT") continue; // Concurrent release.
|
|
65
|
+
throw new LockError("Cannot read lease " + file + ": " + error.message);
|
|
66
|
+
}
|
|
67
|
+
if (!lease || !RESOURCE.test(lease.resource || "") || name !== lease.resource + ".json"
|
|
68
|
+
|| typeof lease.holder !== "string" || typeof lease.worktree !== "string"
|
|
69
|
+
|| !Number.isFinite(Date.parse(lease.expires)) || !Array.isArray(lease.waiters)) {
|
|
70
|
+
throw new LockError("Malformed lease " + file + ".");
|
|
71
|
+
}
|
|
72
|
+
leases.push(lease);
|
|
73
|
+
}
|
|
74
|
+
return leases;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Pure read for shift check: never reap expiry or post chat records.
|
|
78
|
+
function liveLeases(where, now = Date.now()) {
|
|
79
|
+
return readLeases(where).filter((lease) => Date.parse(lease.expires) > now);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function describe(lease) {
|
|
83
|
+
return lease.resource + ": held by " + lease.holder + " (" + lease.worktree + "), expires " + lease.expires + ": " + lease.note;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// Serialize read/modify/write and expiry notifications across worktrees.
|
|
87
|
+
// The lease itself still uses exclusive creation. A bounded wait fails closed
|
|
88
|
+
// rather than deleting another command's mutex or stealing a lease.
|
|
89
|
+
function withMutation(where, action) {
|
|
90
|
+
fs.mkdirSync(lockDir(where), { recursive: true });
|
|
91
|
+
const mutex = path.join(lockDir(where), ".mutation");
|
|
92
|
+
const deadline = Date.now() + 5000;
|
|
93
|
+
while (true) {
|
|
94
|
+
try {
|
|
95
|
+
fs.mkdirSync(mutex);
|
|
96
|
+
break;
|
|
97
|
+
} catch (error) {
|
|
98
|
+
if (error.code !== "EEXIST") throw error;
|
|
99
|
+
// A mutex left by a crashed command would block every later one; no
|
|
100
|
+
// command holds it for more than a moment, so one older than 30s is stale.
|
|
101
|
+
try {
|
|
102
|
+
if (Date.now() - fs.statSync(mutex).mtimeMs > 30000) {
|
|
103
|
+
fs.rmdirSync(mutex);
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
} catch {
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
if (Date.now() >= deadline) throw new LockError("Lease store busy at " + mutex + "; retry after the other lock command finishes.");
|
|
110
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
try {
|
|
114
|
+
return action();
|
|
115
|
+
} finally {
|
|
116
|
+
fs.rmdirSync(mutex);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// Posts from the running worktree's role to every other role among the
|
|
121
|
+
// targets. The running role is not messaged: it is the one reading the output.
|
|
122
|
+
function notify(where, targets, text) {
|
|
123
|
+
const from = store.currentRole(where);
|
|
124
|
+
if (!from) return;
|
|
125
|
+
for (const role of new Set(targets.map((target) => target.role).filter(Boolean))) {
|
|
126
|
+
if (role !== from) store.directPost(where, role, text);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// Every freed lease is printed, whether or not anyone was messaged (D4).
|
|
131
|
+
function reap(where) {
|
|
132
|
+
const freed = [];
|
|
133
|
+
for (const lease of readLeases(where)) {
|
|
134
|
+
if (Date.parse(lease.expires) > Date.now()) continue;
|
|
135
|
+
const text = "lock " + lease.resource + " expired at " + lease.expires + " (held by " + lease.holder + ": " + lease.note + ")";
|
|
136
|
+
notify(where, [lease, ...lease.waiters], text);
|
|
137
|
+
freed.push(text);
|
|
138
|
+
fs.unlinkSync(path.join(lockDir(where), lease.resource + ".json"));
|
|
139
|
+
}
|
|
140
|
+
return freed;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function acquire(where, resource, expires, note) {
|
|
144
|
+
const who = identity(where);
|
|
145
|
+
const file = path.join(lockDir(where), resource + ".json");
|
|
146
|
+
const existing = readLeases(where).find((lease) => lease.resource === resource);
|
|
147
|
+
if (existing) {
|
|
148
|
+
if (existing.holder !== who.holder) {
|
|
149
|
+
if (!existing.waiters.some((waiter) => waiter.holder === who.holder)) {
|
|
150
|
+
existing.waiters.push(who);
|
|
151
|
+
store.writeJsonAtomic(where, file, existing);
|
|
152
|
+
}
|
|
153
|
+
throw new LockError(describe(existing));
|
|
154
|
+
}
|
|
155
|
+
const renewed = { ...existing, expires, note };
|
|
156
|
+
store.writeJsonAtomic(where, file, renewed);
|
|
157
|
+
return renewed;
|
|
158
|
+
}
|
|
159
|
+
const lease = { resource, ...who, acquired: store.isoLocal(new Date()), expires, note, waiters: [] };
|
|
160
|
+
fs.writeFileSync(file, JSON.stringify(lease, null, 2) + "\n", { flag: "wx" });
|
|
161
|
+
return lease;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function release(where, resource) {
|
|
165
|
+
const lease = readLeases(where).find((row) => row.resource === resource);
|
|
166
|
+
if (!lease) throw new LockError("No live lease for " + resource + ".");
|
|
167
|
+
if (lease.holder !== identity(where).holder) throw new LockError("Only " + lease.holder + " can release " + resource + " (" + lease.worktree + ").");
|
|
168
|
+
notify(where, lease.waiters, "lock " + resource + " released by " + lease.holder);
|
|
169
|
+
fs.unlinkSync(path.join(lockDir(where), resource + ".json"));
|
|
170
|
+
return lease;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function runLock(argv) {
|
|
174
|
+
const options = { repo: process.cwd(), json: false, positionals: [], duration: null, note: null };
|
|
175
|
+
try {
|
|
176
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
177
|
+
const arg = argv[index];
|
|
178
|
+
if (arg === "--json") options.json = true;
|
|
179
|
+
else if (arg === "--help" || arg === "-h") {
|
|
180
|
+
process.stdout.write(USAGE + "\n");
|
|
181
|
+
return 0;
|
|
182
|
+
} else if (["--repo", "--for", "--note"].includes(arg)) {
|
|
183
|
+
const value = argv[++index];
|
|
184
|
+
if (!value || value.startsWith("--")) throw new LockError(arg + " needs a value.");
|
|
185
|
+
options[{ "--repo": "repo", "--for": "duration", "--note": "note" }[arg]] = value;
|
|
186
|
+
} else if (arg.startsWith("-")) throw new LockError("Unknown option " + arg + ".");
|
|
187
|
+
else options.positionals.push(arg);
|
|
188
|
+
}
|
|
189
|
+
const [action, resource, ...extra] = options.positionals;
|
|
190
|
+
if (!["acquire", "release", "list"].includes(action)) {
|
|
191
|
+
process.stderr.write((action ? "keel lock: unknown action " + action + "\n" : "") + USAGE + "\n");
|
|
192
|
+
return 2;
|
|
193
|
+
}
|
|
194
|
+
const where = store.requireLocation(options.repo);
|
|
195
|
+
return withMutation(where, () => {
|
|
196
|
+
for (const text of reap(where)) {
|
|
197
|
+
// Keep --json parseable, including when a command is later refused.
|
|
198
|
+
(options.json ? process.stderr : process.stdout).write(text + "\n");
|
|
199
|
+
}
|
|
200
|
+
if (extra.length || (action === "list" && resource)) throw new LockError("Unexpected argument for " + action + ".");
|
|
201
|
+
if (action !== "acquire" && (options.duration !== null || options.note !== null)) throw new LockError("--for and --note are only valid for acquire.");
|
|
202
|
+
const out = (data, text) => process.stdout.write((options.json ? JSON.stringify(data, null, 2) : text) + "\n");
|
|
203
|
+
if (action === "list") {
|
|
204
|
+
const leases = liveLeases(where);
|
|
205
|
+
out({ leases }, leases.length ? leases.map(describe).join("\n") : "No live leases.");
|
|
206
|
+
} else {
|
|
207
|
+
checkResource(resource);
|
|
208
|
+
if (action === "release") {
|
|
209
|
+
const lease = release(where, resource);
|
|
210
|
+
out({ released: lease }, "lock " + resource + " released by " + lease.holder);
|
|
211
|
+
} else {
|
|
212
|
+
if (options.duration === null) throw new LockError("acquire requires --for <duration>.");
|
|
213
|
+
if (!options.note || !options.note.trim()) throw new LockError("acquire requires a non-empty --note <why>.");
|
|
214
|
+
const expires = expiry(options.duration, new Date());
|
|
215
|
+
const lease = acquire(where, resource, expires, options.note.trim());
|
|
216
|
+
const notice = "The lease enforces nothing on Git or the filesystem.";
|
|
217
|
+
out({ lease, notice }, describe(lease) + "\n" + notice);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
return 0;
|
|
221
|
+
});
|
|
222
|
+
} catch (error) {
|
|
223
|
+
if (error instanceof LockError || error instanceof store.ChatError) {
|
|
224
|
+
process.stderr.write("keel lock: " + error.message + "\n");
|
|
225
|
+
return 1;
|
|
226
|
+
}
|
|
227
|
+
throw error;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
module.exports = { LockError, liveLeases, describe, runLock };
|
package/src/core/shift.js
CHANGED
|
@@ -16,6 +16,7 @@ const os = require("os");
|
|
|
16
16
|
const path = require("path");
|
|
17
17
|
const { spawnSync } = require("child_process");
|
|
18
18
|
const store = require("./chat/store");
|
|
19
|
+
const locks = require("./lock");
|
|
19
20
|
|
|
20
21
|
const REF = "keel-shift";
|
|
21
22
|
const USAGE = [
|
|
@@ -195,6 +196,10 @@ function check(where, role) {
|
|
|
195
196
|
for (const tree of temporary.own) items.push({ kind: "temporary-worktree", detail: tree });
|
|
196
197
|
for (const tree of temporary.other) notes.push(`temporary worktree of another session, or of unknown owner, not counted: ${tree}`);
|
|
197
198
|
|
|
199
|
+
for (const lease of locks.liveLeases(where)) {
|
|
200
|
+
if (lease.worktree === where.worktree) items.push({ kind: "lock", detail: locks.describe(lease) });
|
|
201
|
+
}
|
|
202
|
+
|
|
198
203
|
if (role) {
|
|
199
204
|
for (const todo of store.openTodos(where, { assignee: role })) {
|
|
200
205
|
if (isShift(todo)) continue;
|
|
@@ -466,7 +471,7 @@ function runShift(argv) {
|
|
|
466
471
|
return 2;
|
|
467
472
|
}
|
|
468
473
|
} catch (error) {
|
|
469
|
-
if (error instanceof ShiftError || error instanceof store.ChatError) {
|
|
474
|
+
if (error instanceof ShiftError || error instanceof store.ChatError || error instanceof locks.LockError) {
|
|
470
475
|
process.stderr.write(`keel shift: ${error.message}\n`);
|
|
471
476
|
return 1;
|
|
472
477
|
}
|