@christang/keel 5.99.6 → 5.100.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 CHANGED
@@ -685,6 +685,10 @@ 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
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. 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.
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.99.6 -->
1
+ <!-- keel:start version=5.100.0 -->
2
2
  ## Keel Bootstrap
3
3
 
4
4
  - Start every session with `keel context`; OpenSpec artifacts and Git are the only durable authority — never native memory, goals, or transcripts.
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));
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.99.6",
3
+ "version": "5.100.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.99.6",
9
+ "version": "5.100.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.99.6",
5
+ "version": "5.100.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.99.6",
3
+ "version": "5.100.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.99.6",
3
+ "version": "5.100.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.99.6"
51
- PROTOCOL_VERSION = "5.99.6"
50
+ PACKAGE_VERSION = "5.100.0"
51
+ PROTOCOL_VERSION = "5.100.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
@@ -4457,6 +4457,261 @@ def validate_collected_feedback_is_recorded_scenario() -> int:
4457
4457
  return 0
4458
4458
 
4459
4459
 
4460
+ def validate_resource_lock_scenario() -> int:
4461
+ """Bounded exclusive leases, shared by worktrees, through the real CLI."""
4462
+ label = "resource-lock:"
4463
+ with tempfile.TemporaryDirectory(prefix="keel-resource-lock-") as raw:
4464
+ a, b, env = chat_scratch_group(Path(raw))
4465
+ for tree, role in ((a, "integ"), (b, "sweep")):
4466
+ bound = run_keel(tree, "chat", "role", "--set", role, env=env)
4467
+ if bound.returncode != 0:
4468
+ report(f"{label} could not bind {role}: {bound.stderr}")
4469
+ return 1
4470
+ locks = mailbox_common_dir(a) / "keel-chat" / "locks"
4471
+ lease_file = locks / "main-checkout.json"
4472
+
4473
+ def lock(tree: Path, *args: str) -> subprocess.CompletedProcess[str]:
4474
+ return run_keel(tree, "lock", *args, env=env)
4475
+
4476
+ def leases() -> list[dict]:
4477
+ result = lock(b, "list", "--json")
4478
+ if result.returncode != 0:
4479
+ report(f"{label} list --json failed: {result.stderr}")
4480
+ return [{}]
4481
+ try:
4482
+ return json.loads(result.stdout)["leases"]
4483
+ except (ValueError, KeyError, TypeError):
4484
+ report(f"{label} list --json lacks lease data: {result.stdout}")
4485
+ return [{}]
4486
+
4487
+ malformed = [
4488
+ (("acquire", "main-checkout", "--note", "x"), "--for"),
4489
+ (("acquire", "main-checkout", "--for", "5x", "--note", "x"), "5x"),
4490
+ (("acquire", "main-checkout", "--for", "1h"), "--note"),
4491
+ (("acquire", "../x", "--for", "1h", "--note", "x"), "../x"),
4492
+ (("acquire", "main-checkout", "--for", "0s", "--note", "x"), "0s"),
4493
+ (("acquire", "main-checkout", "--for", "1h", "--note", " "), "--note"),
4494
+ (("acquire", "x" * 65, "--for", "1h", "--note", "x"), "resource"),
4495
+ (("acquire", "main-checkout", "--for", "9" * 30 + "d", "--note", "x"), "duration"),
4496
+ ]
4497
+ for args, needle in malformed:
4498
+ refused = lock(a, *args)
4499
+ if refused.returncode == 0:
4500
+ report(f"{label} malformed acquire succeeded: {args}")
4501
+ return 1
4502
+ if needle not in refused.stdout + refused.stderr:
4503
+ report(f"{label} malformed acquire does not name {needle!r}: {refused.stderr}")
4504
+ return 1
4505
+ if leases():
4506
+ report(f"{label} malformed acquire recorded a lease: {args}")
4507
+ return 1
4508
+
4509
+ acquired = lock(a, "acquire", "main-checkout", "--for", "2h", "--note", "integration run")
4510
+ if acquired.returncode != 0:
4511
+ report(f"{label} acquire failed: {acquired.stderr}")
4512
+ return 1
4513
+ if "enforces nothing" not in acquired.stdout:
4514
+ report(f"{label} acquire does not say the lease enforces nothing: {acquired.stdout}")
4515
+ return 1
4516
+ rows = leases()
4517
+ if len(rows) != 1:
4518
+ report(f"{label} acquire did not record exactly one lease: {rows}")
4519
+ return 1
4520
+ first = rows[0]
4521
+ for key, expected in (("resource", "main-checkout"), ("holder", "integ"), ("role", "integ"), ("worktree", str(a.resolve())), ("note", "integration run")):
4522
+ if first.get(key) != expected:
4523
+ report(f"{label} acquired {key} differs: {first}")
4524
+ return 1
4525
+ for key in ("acquired", "expires"):
4526
+ if not first.get(key):
4527
+ report(f"{label} lease lacks {key}: {first}")
4528
+ return 1
4529
+ datetime.fromisoformat(first[key])
4530
+ listed = lock(b, "list")
4531
+ if listed.returncode != 0:
4532
+ report(f"{label} other-worktree list failed: {listed.stderr}")
4533
+ return 1
4534
+ for needle in ("main-checkout", "integ", first["expires"], "integration run", str(a.resolve())):
4535
+ if needle not in listed.stdout:
4536
+ report(f"{label} other-worktree list lacks {needle!r}: {listed.stdout}")
4537
+ return 1
4538
+ for attempt in range(2):
4539
+ refused = lock(b, "acquire", "main-checkout", "--for", "1h", "--note", "formal sweep")
4540
+ if refused.returncode != 1:
4541
+ report(f"{label} held acquire attempt {attempt} exited {refused.returncode}")
4542
+ return 1
4543
+ for needle in ("integ", first["expires"], "integration run", str(a.resolve())):
4544
+ if needle not in refused.stdout + refused.stderr:
4545
+ report(f"{label} held acquire omits {needle!r}: {refused.stderr}")
4546
+ return 1
4547
+ waiting = leases()[0]
4548
+ if [w.get("holder") for w in waiting.get("waiters", [])] != ["sweep"]:
4549
+ report(f"{label} waiter is absent or duplicated: {waiting}")
4550
+ return 1
4551
+ renewed = lock(a, "acquire", "main-checkout", "--for", "3h", "--note", "integration, extended")
4552
+ if renewed.returncode != 0:
4553
+ report(f"{label} renewal failed: {renewed.stderr}")
4554
+ return 1
4555
+ extended = leases()[0]
4556
+ if datetime.fromisoformat(extended["expires"]) <= datetime.fromisoformat(first["expires"]):
4557
+ report(f"{label} renewal did not extend expiry: {extended}")
4558
+ return 1
4559
+ if extended.get("note") != "integration, extended":
4560
+ report(f"{label} renewal did not update note: {extended}")
4561
+ return 1
4562
+ if extended.get("acquired") != first["acquired"]:
4563
+ report(f"{label} renewal replaced acquisition time: {extended}")
4564
+ return 1
4565
+ if extended.get("waiters") != waiting["waiters"]:
4566
+ report(f"{label} renewal lost waiters: {extended}")
4567
+ return 1
4568
+ refused = lock(b, "release", "main-checkout")
4569
+ if refused.returncode != 1:
4570
+ report(f"{label} waiter release exited {refused.returncode}")
4571
+ return 1
4572
+ if "integ" not in refused.stdout + refused.stderr:
4573
+ report(f"{label} waiter release does not name integ: {refused.stderr}")
4574
+ return 1
4575
+ if not lease_file.exists():
4576
+ report(f"{label} waiter release removed the lease")
4577
+ return 1
4578
+ released = lock(a, "release", "main-checkout")
4579
+ if released.returncode != 0:
4580
+ report(f"{label} holder release failed: {released.stderr}")
4581
+ return 1
4582
+ if leases():
4583
+ report(f"{label} holder release left a lease listed")
4584
+ return 1
4585
+ messages = chat_records_with(a, "dm-integ--sweep", "lock main-checkout released by integ")
4586
+ if len(messages) != 1:
4587
+ report(f"{label} release did not post exactly one direct message: {messages}")
4588
+ return 1
4589
+ reacquired = lock(a, "acquire", "main-checkout", "--for", "2h", "--note", "integration run")
4590
+ if reacquired.returncode != 0:
4591
+ report(f"{label} expiry fixture acquire failed: {reacquired.stderr}")
4592
+ return 1
4593
+ queued = lock(b, "acquire", "main-checkout", "--for", "1h", "--note", "formal sweep")
4594
+ if queued.returncode != 1:
4595
+ report(f"{label} expiry fixture waiter was not refused: {queued.stdout} {queued.stderr}")
4596
+ return 1
4597
+ expired = json.loads(lease_file.read_text())
4598
+ expired["expires"] = "2000-01-01T00:00:00+00:00"
4599
+ lease_file.write_text(json.dumps(expired))
4600
+ if leases():
4601
+ report(f"{label} expiry left a lease listed")
4602
+ return 1
4603
+ if lease_file.exists():
4604
+ report(f"{label} expiry left the lease file")
4605
+ return 1
4606
+ again = lock(b, "list")
4607
+ if again.returncode != 0:
4608
+ report(f"{label} second expiry list failed: {again.stderr}")
4609
+ return 1
4610
+ messages = chat_records_with(a, "dm-integ--sweep", "lock main-checkout expired at")
4611
+ if len(messages) != 1:
4612
+ report(f"{label} expiry did not post exactly once to integ: {messages}")
4613
+ return 1
4614
+ if "from: sweep" not in messages[0]:
4615
+ report(f"{label} expiry message is not from sweep: {messages[0]}")
4616
+ return 1
4617
+ if chat_records_with(b, "dm-sweep--sweep", "lock main-checkout expired at"):
4618
+ report(f"{label} expiry posted a direct message from sweep to itself")
4619
+ return 1
4620
+ reclaimed = lock(b, "acquire", "main-checkout", "--for", "1h", "--note", "formal sweep")
4621
+ if reclaimed.returncode != 0:
4622
+ report(f"{label} sweep could not acquire after expiry: {reclaimed.stderr}")
4623
+ return 1
4624
+ released = lock(b, "release", "main-checkout")
4625
+ if released.returncode != 0:
4626
+ report(f"{label} sweep release after expiry failed: {released.stderr}")
4627
+ return 1
4628
+
4629
+ # Simultaneous public commands: a lease must have exactly one winner.
4630
+ command = ["node", str(ROOT / "bin" / "keel.js"), "lock", "acquire", "race", "--for", "1h", "--note", "race"]
4631
+ racers = [subprocess.Popen(command, cwd=tree, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) for tree in (a, b)]
4632
+ outputs = [p.communicate(timeout=30) for p in racers]
4633
+ if sorted(p.returncode for p in racers) != [0, 1]:
4634
+ report(f"{label} racing acquires lack exactly one winner: {outputs}")
4635
+ return 1
4636
+ rows = leases()
4637
+ if len(rows) != 1:
4638
+ report(f"{label} race recorded other than one lease: {rows}")
4639
+ return 1
4640
+ winner = a if racers[0].returncode == 0 else b
4641
+ if rows[0].get("worktree") != str(winner.resolve()):
4642
+ report(f"{label} race lease does not belong to the winner: {rows}")
4643
+ return 1
4644
+ if len(rows[0].get("waiters", [])) != 1:
4645
+ report(f"{label} racing loser was not recorded as a waiter: {rows}")
4646
+ return 1
4647
+ released = lock(winner, "release", "race")
4648
+ if released.returncode != 0:
4649
+ report(f"{label} race winner could not release: {released.stderr}")
4650
+ return 1
4651
+
4652
+ # A mutex left by a crashed command is stale after 30 seconds.
4653
+ mutex = locks / ".mutation"
4654
+ mutex.mkdir(parents=True, exist_ok=True)
4655
+ os.utime(mutex, (time.time() - 120, time.time() - 120))
4656
+ unstuck = lock(a, "list")
4657
+ if unstuck.returncode != 0:
4658
+ report(f"{label} a stale mutex blocked keel lock list: {unstuck.stderr}")
4659
+ return 1
4660
+ if mutex.exists():
4661
+ report(f"{label} a stale mutex was left in place after keel lock list.")
4662
+ return 1
4663
+
4664
+ # No role: worktree identity, --repo, read-only shift and printed expiry.
4665
+ c = chat_worktree(a, Path(raw) / "unbound")
4666
+ acquired = lock(a, "acquire", "cpu-1", "--for", "1h", "--note", "slot", "--repo", str(c))
4667
+ if acquired.returncode != 0:
4668
+ report(f"{label} unbound --repo acquire failed: {acquired.stderr}")
4669
+ return 1
4670
+ row = leases()[0]
4671
+ if not row.get("holder", "").startswith("worktree:unbound-"):
4672
+ report(f"{label} unbound lease lacks worktree identity: {row}")
4673
+ return 1
4674
+ if row.get("role") is not None:
4675
+ report(f"{label} unbound lease has a chat role: {row}")
4676
+ return 1
4677
+ file = locks / "cpu-1.json"
4678
+ row["expires"] = "2000-01-01T00:00:00+00:00"
4679
+ file.write_text(json.dumps(row))
4680
+ before = file.read_bytes()
4681
+ checked = run_keel(c, "shift", "check", "--json", env=env)
4682
+ if any(item["kind"] == "lock" for item in chat_json(checked).get("items", [])):
4683
+ report(f"{label} shift check reports an expired lease")
4684
+ return 1
4685
+ if file.read_bytes() != before:
4686
+ report(f"{label} shift check mutated the expired lease")
4687
+ return 1
4688
+ freed = lock(c, "list", "--json")
4689
+ if freed.returncode != 0:
4690
+ report(f"{label} unbound expiry command failed: {freed.stderr}")
4691
+ return 1
4692
+ if "cpu-1" not in freed.stderr:
4693
+ report(f"{label} unbound expiry was not printed beside JSON: {freed.stderr}")
4694
+ return 1
4695
+ if chat_json(freed).get("leases") != []:
4696
+ report(f"{label} unbound expiry list is not empty JSON: {freed.stdout}")
4697
+ return 1
4698
+ guide = ROOT / "docs" / "resource-lock.md"
4699
+ if not guide.exists():
4700
+ report(f"{label} docs/resource-lock.md is missing")
4701
+ return 1
4702
+ if "enforces nothing" not in guide.read_text():
4703
+ report(f"{label} guide does not say the lease enforces nothing")
4704
+ return 1
4705
+ if "docs/resource-lock.md" not in (ROOT / "README.md").read_text():
4706
+ report(f"{label} README does not link the guide")
4707
+ return 1
4708
+ if "resource-lock" not in {name for name, _ in SCENARIOS}:
4709
+ report(f"{label} scenario is not registered")
4710
+ return 1
4711
+ report("resource-lock scenario passed.")
4712
+ return 0
4713
+
4714
+
4460
4715
  def validate_shift_change_scenario() -> int:
4461
4716
  """Owner's decision of 2026-10-05: a role's session changes shift through Keel.
4462
4717
 
@@ -4516,6 +4771,16 @@ def validate_shift_change_scenario() -> int:
4516
4771
  subprocess.run(["git", "add", "pushed-not.txt"], cwd=verify, check=True)
4517
4772
  subprocess.run(["git", "commit", "-q", "-m", "local only"], cwd=verify, check=True)
4518
4773
  write_text(verify / "keel" / "guard.json", "{}\n")
4774
+ leased = run_keel(verify, "lock", "acquire", "main-checkout", "--for", "1h", "--note", "shift fixture", env=env)
4775
+ if leased.returncode != 0:
4776
+ report(f"{label} could not acquire the shift fixture lease: {leased.stderr}")
4777
+ return 1
4778
+ other_lease = run_keel(rtl, "lock", "acquire", "other-worktree", "--for", "1h", "--note", "other session", env=env)
4779
+ if other_lease.returncode != 0:
4780
+ report(f"{label} could not acquire the other worktree's lease: {other_lease.stderr}")
4781
+ return 1
4782
+ lease_file = common / "locks" / "main-checkout.json"
4783
+ lease_before = lease_file.read_bytes()
4519
4784
  # A Claude scratchpad of a session started in verify, and one of a
4520
4785
  # session started elsewhere (shift-temp-owner D1).
4521
4786
  scratch = Path(tempfile.gettempdir()) / f"claude-{os.getuid()}"
@@ -4535,7 +4800,18 @@ def validate_shift_change_scenario() -> int:
4535
4800
  report(f"{label} keel shift check exited {checked.returncode} with loose ends present.")
4536
4801
  return 1
4537
4802
  text = checked.stdout
4538
- for needle in ("scratch.txt", "local only", "guard.json", str(sleeper.pid), temp_tree.name, "Rerun the regression"):
4803
+ lock_items = [item for item in chat_json(checked).get("items", []) if item["kind"] == "lock"]
4804
+ if len(lock_items) != 1:
4805
+ report(f"{label} expected exactly one held-worktree lock item: {text}")
4806
+ return 1
4807
+ for needle in ("main-checkout", "verify", "shift fixture", json.loads(lease_before)["expires"]):
4808
+ if needle not in lock_items[0]["detail"]:
4809
+ report(f"{label} lock item omits {needle!r}: {lock_items}")
4810
+ return 1
4811
+ if lease_file.read_bytes() != lease_before:
4812
+ report(f"{label} shift check changed the live lease")
4813
+ return 1
4814
+ for needle in ("scratch.txt", "local only", "guard.json", str(sleeper.pid), temp_tree.name, "Rerun the regression", "main-checkout"):
4539
4815
  if needle not in text:
4540
4816
  report(f"{label} keel shift check does not name {needle!r}: {text.strip()[:600]}")
4541
4817
  return 1
@@ -4555,6 +4831,14 @@ def validate_shift_change_scenario() -> int:
4555
4831
 
4556
4832
  (verify / "scratch.txt").unlink()
4557
4833
  (verify / "keel" / "guard.json").unlink()
4834
+ released = run_keel(verify, "lock", "release", "main-checkout", env=env)
4835
+ if released.returncode != 0:
4836
+ report(f"{label} could not release the shift fixture lease: {released.stderr}")
4837
+ return 1
4838
+ after_release = shift(verify, "check", "--json")
4839
+ if any(item["kind"] == "lock" for item in chat_json(after_release).get("items", [])):
4840
+ report(f"{label} shift check retained a lock item after release: {after_release.stdout}")
4841
+ return 1
4558
4842
  subprocess.run(["git", "push", "-q"], cwd=verify, check=True, capture_output=True)
4559
4843
  subprocess.run(["git", "worktree", "remove", "--force", str(temp_tree)], cwd=verify, check=True)
4560
4844
  todo_id = next(r for r in chat_records_with(rtl, "soc", "Rerun the regression"))
@@ -37356,6 +37640,7 @@ SCENARIOS: tuple = (
37356
37640
  ("collected-feedback-is-recorded", validate_collected_feedback_is_recorded_scenario),
37357
37641
  ("shift-change", validate_shift_change_scenario),
37358
37642
  ("shift-without-role", validate_shift_without_role_scenario),
37643
+ ("resource-lock", validate_resource_lock_scenario),
37359
37644
  ("init-never-downgrades-openspec", validate_init_never_downgrades_openspec_scenario),
37360
37645
  ("native-plugin-marketplaces", validate_native_plugin_marketplaces_scenario),
37361
37646
  ("native-plugin-install-matrix", validate_native_plugin_install_matrix_scenario),
@@ -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
  }