@christang/keel 5.101.0 → 5.102.1

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
@@ -689,6 +689,24 @@ the brief, so `egress_deny` guards what is handed over, not what it can open.
689
689
 
690
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
691
 
692
+ ## Worktree overview
693
+
694
+ `keel worktrees [--repo <path>] [--issues <file>] [--json]` lists every worktree's
695
+ branch or detached head, upstream and ahead/behind counts, last commit, dirty path
696
+ count, bound chat role and presence, and referenced issues. Locked, prunable, and
697
+ missing worktrees remain visible. It reads local state without writing to the
698
+ repository or chat store, and never fetches: ahead/behind is as of the last fetch.
699
+ Issue references come from commit subjects and bodies outside the default branch
700
+ (origin's HEAD, otherwise local `main`, then `master`), which the text output names.
701
+
702
+ Pass issue times explicitly using `--issues issues.json`, with a JSON array such as
703
+ `[{"number":12,"updatedAt":"2026-10-05T08:00:00Z"}]` (the format of
704
+ `gh issue list --json number,updatedAt`). An unreadable or malformed file is refused
705
+ with exit 1 and its filename. JSON output contains `defaultBranch` and `worktrees`;
706
+ each worktree's `issues` remains a sorted array of numbers. With `--issues`,
707
+ `issueUpdates` adds `{number, updatedAt}` entries, with null for an absent time.
708
+ Without a known default branch, no issue range is inferred.
709
+
692
710
  ## Group chat between sessions
693
711
 
694
712
  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.
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.101.0 -->
1
+ <!-- keel:start version=5.102.1 -->
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
@@ -108,6 +108,7 @@ Usage:
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
110
  keel lock acquire|release|list ... (shared resource leases; see keel lock --help)
111
+ keel worktrees [--repo <path>] [--issues <file>] [--json] (read-only worktree overview)
111
112
  keel openspec [args...]
112
113
  keel --init [repo] [--target claude|codex|opencode] [--dry-run] [--force-template-update]
113
114
  keel --install [repo] [--target claude|codex|opencode] [--dry-run] [--force-template-update] [--with-git-hooks]
@@ -2858,6 +2859,9 @@ function main() {
2858
2859
  if (process.argv[2] === "lock") {
2859
2860
  return require("../src/core/lock").runLock(process.argv.slice(3));
2860
2861
  }
2862
+ if (process.argv[2] === "worktrees") {
2863
+ return require("../src/core/worktrees").runWorktrees(process.argv.slice(3));
2864
+ }
2861
2865
  // `keel agents` likewise: the external model CLI catalog (#219).
2862
2866
  if (process.argv[2] === "agents") {
2863
2867
  return require("../src/core/agents").runAgents(process.argv.slice(3));
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.101.0",
3
+ "version": "5.102.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.101.0",
9
+ "version": "5.102.1",
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.101.0",
5
+ "version": "5.102.1",
6
6
  "license": "MIT",
7
7
  "repository": {
8
8
  "type": "git",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keel",
3
- "version": "5.101.0",
3
+ "version": "5.102.1",
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.101.0",
3
+ "version": "5.102.1",
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.101.0"
51
- PROTOCOL_VERSION = "5.101.0"
50
+ PACKAGE_VERSION = "5.102.1"
51
+ PROTOCOL_VERSION = "5.102.1"
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
@@ -4550,6 +4550,174 @@ def validate_collected_feedback_is_recorded_scenario() -> int:
4550
4550
  return 0
4551
4551
 
4552
4552
 
4553
+ def validate_worktree_overview_scenario() -> int:
4554
+ """Read every worktree through the CLI without fetching or changing chat."""
4555
+ label = "worktree-overview:"
4556
+ with tempfile.TemporaryDirectory(prefix="keel-worktree-overview-") as raw:
4557
+ base = Path(raw).resolve()
4558
+ repo, remote = base / "repo", base / "remote.git"
4559
+ repo.mkdir()
4560
+ env = os.environ.copy()
4561
+ env.pop("KEEL_CHAT_ROLE", None)
4562
+ env.pop("KEEL_MAIL_ROLE", None)
4563
+
4564
+ def git(*args: str, cwd: Path = repo) -> str:
4565
+ return subprocess.run(
4566
+ ["git", *args], cwd=cwd, env=env, check=True,
4567
+ capture_output=True, text=True,
4568
+ ).stdout.strip()
4569
+
4570
+ git("init", "-q", "-b", "main")
4571
+ git("config", "user.email", "test@example.invalid")
4572
+ git("config", "user.name", "Worktree test")
4573
+ (repo / "seed").write_text("base\n", encoding="utf-8")
4574
+ git("add", "seed")
4575
+ git("commit", "-qm", "base #99")
4576
+ git("init", "--bare", "-q", str(remote))
4577
+ git("remote", "add", "origin", str(remote))
4578
+ git("push", "-qu", "origin", "main")
4579
+ git("symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main")
4580
+ a, b, gone = base / "a", base / "b", base / "gone"
4581
+ git("worktree", "add", "-qb", "feature", str(a), "main")
4582
+ git("branch", "--set-upstream-to=origin/main", "feature")
4583
+ (a / "feature").write_text("feature\n", encoding="utf-8")
4584
+ git("add", "feature", cwd=a)
4585
+ git("commit", "-qm", "feature #12", "-m", "References #12 again", cwd=a)
4586
+ git("worktree", "add", "-q", "--detach", str(b), "main")
4587
+ (b / "uncommitted").write_text("dirty\n", encoding="utf-8")
4588
+ git("worktree", "add", "-q", "--detach", str(gone), "main")
4589
+ git("worktree", "lock", "--reason", "test lock", str(a))
4590
+ shutil.rmtree(gone)
4591
+ bound = run_keel(a, "chat", "role", "--set", "pm", env=env)
4592
+ if bound.returncode != 0:
4593
+ report(f"{label} could not bind pm: {bound.stderr}")
4594
+ return 1
4595
+ chat = Path(git("rev-parse", "--path-format=absolute", "--git-common-dir")) / "keel-chat"
4596
+ stamp = datetime.now(timezone.utc).isoformat()
4597
+ write_text(chat / "presence" / "pm.json", json.dumps({"state": "online", "last_active": stamp}))
4598
+
4599
+ def snapshot() -> dict[str, bytes]:
4600
+ return {str(file.relative_to(chat)): file.read_bytes()
4601
+ for file in chat.rglob("*") if file.is_file()}
4602
+
4603
+ before = snapshot()
4604
+ repository_before = {str(file.relative_to(repo)): file.read_bytes()
4605
+ for file in repo.rglob("*") if file.is_file()}
4606
+
4607
+ def overview(*args: str) -> subprocess.CompletedProcess[str]:
4608
+ # An override for the invoking session must not bind every worktree.
4609
+ return run_keel(b, "worktrees", "--repo", str(repo), *args,
4610
+ env={**env, "KEEL_CHAT_ROLE": "caller"})
4611
+
4612
+ result = overview("--json")
4613
+ if result.returncode != 0:
4614
+ report(f"{label} --json failed: {result.stderr}")
4615
+ return 1
4616
+ try:
4617
+ payload = json.loads(result.stdout)
4618
+ rows = {row["path"]: row for row in payload["worktrees"]}
4619
+ except (ValueError, KeyError, TypeError):
4620
+ report(f"{label} --json lacks worktree data: {result.stdout}")
4621
+ return 1
4622
+ if set(rows) != {str(repo), str(a), str(b), str(gone)}:
4623
+ report(f"{label} did not list every worktree: {rows}")
4624
+ return 1
4625
+ for tree, expected in (
4626
+ (a, {"branch": "feature", "ahead": 1, "behind": 0, "issues": [12],
4627
+ "role": "pm", "upstream": "origin/main", "dirty": 0,
4628
+ "locked": "test lock", "prunable": None}),
4629
+ (b, {"branch": None, "dirty": 1, "role": None, "presence": None,
4630
+ "ahead": None, "behind": None, "upstream": None, "issues": []}),
4631
+ (gone, {"missing": True}),
4632
+ ):
4633
+ for key, value in expected.items():
4634
+ if rows[str(tree)].get(key) != value:
4635
+ report(f"{label} {tree.name}'s {key} differs: {rows[str(tree)]}")
4636
+ return 1
4637
+ if rows[str(a)].get("presence") != {"state": "online", "last_active": stamp}:
4638
+ report(f"{label} a's presence differs: {rows[str(a)]}")
4639
+ return 1
4640
+ for tree in (repo, a, b):
4641
+ row = rows[str(tree)]
4642
+ if row.get("head") != git("rev-parse", "--short", "HEAD", cwd=tree):
4643
+ report(f"{label} {tree.name}'s short head differs: {row}")
4644
+ return 1
4645
+ expected_commit = {"subject": git("log", "-1", "--format=%s", cwd=tree),
4646
+ "time": git("log", "-1", "--format=%cI", cwd=tree)}
4647
+ if row.get("lastCommit") != expected_commit:
4648
+ report(f"{label} {tree.name}'s last commit differs: {row}")
4649
+ return 1
4650
+ if not rows[str(gone)].get("prunable"):
4651
+ report(f"{label} missing worktree lacks Git's prunable marker: {rows[str(gone)]}")
4652
+ return 1
4653
+ text = overview()
4654
+ if text.returncode != 0:
4655
+ report(f"{label} text output failed: {text.stderr}")
4656
+ return 1
4657
+ for needle in ("main", "as of the last fetch", str(a), str(b), str(gone), "missing"):
4658
+ if needle not in text.stdout:
4659
+ report(f"{label} text output lacks {needle!r}: {text.stdout}")
4660
+ return 1
4661
+ issues = base / "issues.json"
4662
+ updated = "2026-10-05T08:00:00Z"
4663
+ write_text(issues, json.dumps([{"number": 12, "updatedAt": updated}]))
4664
+ timed = overview("--issues", str(issues), "--json")
4665
+ if timed.returncode != 0:
4666
+ report(f"{label} passed issues file failed: {timed.stderr}")
4667
+ return 1
4668
+ timed_rows = {row["path"]: row for row in json.loads(timed.stdout)["worktrees"]}
4669
+ if timed_rows[str(a)].get("issueUpdates") != [{"number": 12, "updatedAt": updated}]:
4670
+ report(f"{label} issue 12 does not carry the passed updatedAt: {timed.stdout}")
4671
+ return 1
4672
+ timed_text = overview("--issues", str(issues))
4673
+ if updated not in timed_text.stdout:
4674
+ report(f"{label} text output lacks issue 12's passed time: {timed_text.stdout}")
4675
+ return 1
4676
+ write_text(issues, "[]")
4677
+ absent = overview("--issues", str(issues), "--json")
4678
+ if absent.returncode != 0:
4679
+ report(f"{label} empty issue array failed: {absent.stderr}")
4680
+ return 1
4681
+ absent_rows = {row["path"]: row for row in json.loads(absent.stdout)["worktrees"]}
4682
+ if absent_rows[str(a)].get("issueUpdates") != [{"number": 12, "updatedAt": None}]:
4683
+ report(f"{label} absent issue time is not null: {absent.stdout}")
4684
+ return 1
4685
+ bad = base / "bad.json"
4686
+ for content in ("not JSON", "{}", '[{"number": 12}]'):
4687
+ write_text(bad, content)
4688
+ refused = overview("--issues", str(bad))
4689
+ if refused.returncode != 1:
4690
+ report(f"{label} malformed --issues did not exit 1: {refused.returncode}")
4691
+ return 1
4692
+ if str(bad) not in refused.stderr:
4693
+ report(f"{label} malformed --issues does not name the file: {refused.stderr}")
4694
+ return 1
4695
+ if refused.stdout:
4696
+ report(f"{label} malformed --issues printed partial output: {refused.stdout}")
4697
+ return 1
4698
+ missing = base / "missing.json"
4699
+ refused = overview("--issues", str(missing))
4700
+ if refused.returncode != 1:
4701
+ report(f"{label} missing --issues did not exit 1: {refused.returncode}")
4702
+ return 1
4703
+ if str(missing) not in refused.stderr:
4704
+ report(f"{label} missing --issues does not name the file: {refused.stderr}")
4705
+ return 1
4706
+ if refused.stdout:
4707
+ report(f"{label} missing --issues printed partial output: {refused.stdout}")
4708
+ return 1
4709
+ if snapshot() != before:
4710
+ report(f"{label} the chat store's files changed")
4711
+ return 1
4712
+ repository_after = {str(file.relative_to(repo)): file.read_bytes()
4713
+ for file in repo.rglob("*") if file.is_file()}
4714
+ if repository_after != repository_before:
4715
+ report(f"{label} the repository's files changed (including Git indexes and refs)")
4716
+ return 1
4717
+ report(f"{label} scenario passed")
4718
+ return 0
4719
+
4720
+
4553
4721
  def validate_resource_lock_scenario() -> int:
4554
4722
  """Bounded exclusive leases, shared by worktrees, through the real CLI."""
4555
4723
  label = "resource-lock:"
@@ -11884,6 +12052,93 @@ def validate_inline_code_is_concrete_scenario() -> int:
11884
12052
  return 0
11885
12053
 
11886
12054
 
12055
+ def validate_marker_words_in_capitals_scenario() -> int:
12056
+ """Issue #271: a marker word reads as a slot only in capitals.
12057
+
12058
+ `task-complete` refused Evidence reading "post and todo" because the
12059
+ unfilled-slot test matched its marker words in any case, so the name of a
12060
+ `keel chat` record kind read as an unfilled slot. Lowercase prose is
12061
+ concrete; `TODO`, `PLACEHOLDER` and `<value>` outside inline code are not.
12062
+ """
12063
+ def start(repo: Path, change: str, m1: str):
12064
+ write_text(
12065
+ repo / f"openspec/changes/{change}/tasks.md",
12066
+ task_capsule_compact_fixture().replace(
12067
+ " - M1: node test.js\n", f" - M1: {m1}\n"
12068
+ ),
12069
+ )
12070
+ return run_keel(
12071
+ repo, "gate", "task-start", "--change", change, "--task", "1.1", "--json"
12072
+ )
12073
+
12074
+ with tempfile.TemporaryDirectory(prefix="keel-marker-words-") as raw_tmp:
12075
+ repo = Path(raw_tmp)
12076
+ prose = start(repo, "prose", "node test.js lists each todo and its placeholder text")
12077
+ if prose.returncode != 0:
12078
+ report(
12079
+ "marker-words-in-capitals: a check naming a todo and a "
12080
+ "placeholder in lowercase prose was judged unfilled."
12081
+ )
12082
+ report((prose.stdout or prose.stderr).strip())
12083
+ return 1
12084
+
12085
+ # The reporter's shape: Evidence written after the task started.
12086
+ write_text(
12087
+ repo / "openspec/changes/evidence/tasks.md", task_capsule_compact_fixture()
12088
+ )
12089
+ if not record_contract_anchor(repo, "evidence"):
12090
+ report("marker-words-in-capitals: the fixture could not record its anchor.")
12091
+ return 1
12092
+ path = repo / "openspec/changes/evidence/tasks.md"
12093
+ path.write_text(
12094
+ path.read_text(encoding="utf-8").replace(
12095
+ " - M1: pending\n",
12096
+ " - M1: pass. With `--ack` on post and todo, the record is acknowledged.\n",
12097
+ ),
12098
+ encoding="utf-8",
12099
+ )
12100
+ completed = run_keel(
12101
+ repo, "gate", "task-complete", "--change", "evidence", "--task", "1.1", "--json"
12102
+ )
12103
+ slots = [
12104
+ problem.get("message", "")
12105
+ for problem in json.loads(completed.stdout).get("problems", [])
12106
+ if "unfilled" in problem.get("message", "")
12107
+ ]
12108
+ if slots:
12109
+ report(
12110
+ "marker-words-in-capitals: Evidence reading 'post and todo' was "
12111
+ f"refused as an unfilled slot: {slots}"
12112
+ )
12113
+ return 1
12114
+
12115
+ for change, m1, token in (
12116
+ ("todo", "node test.js TODO", "TODO"),
12117
+ ("upper", "node test.js PLACEHOLDER", "PLACEHOLDER"),
12118
+ ("angle", "node test.js <value>", "<value>"),
12119
+ ):
12120
+ result = start(repo, change, m1)
12121
+ problems = json.loads(result.stdout).get("problems", [])
12122
+ named = [
12123
+ problem
12124
+ for problem in problems
12125
+ if problem.get("code") == "non-concrete-verify"
12126
+ and f"`{token}`" in problem.get("message", "")
12127
+ ]
12128
+ if not named:
12129
+ report(
12130
+ f"marker-words-in-capitals: a bare {token} was not reported "
12131
+ "as non-concrete-verify naming it."
12132
+ )
12133
+ report(result.stdout.strip())
12134
+ return 1
12135
+ if "marker-words-in-capitals" not in {name for name, _ in SCENARIOS}:
12136
+ report("marker-words-in-capitals: the scenario registry does not include it.")
12137
+ return 1
12138
+ report("marker-words-in-capitals scenario passed.")
12139
+ return 0
12140
+
12141
+
11887
12142
  def validate_covers_separator_collision_scenario() -> int:
11888
12143
  """Issue #7 example 2: a requirement name containing the hierarchy separator.
11889
12144
 
@@ -37609,6 +37864,7 @@ SCENARIOS: tuple = (
37609
37864
  validate_non_concrete_verify_diagnostic_scenario,
37610
37865
  ),
37611
37866
  ("inline-code-is-concrete", validate_inline_code_is_concrete_scenario),
37867
+ ("marker-words-in-capitals", validate_marker_words_in_capitals_scenario),
37612
37868
  ("covers-separator-collision", validate_covers_separator_collision_scenario),
37613
37869
  (
37614
37870
  "unresolved-covers-names-what-failed",
@@ -37735,6 +37991,7 @@ SCENARIOS: tuple = (
37735
37991
  ("shift-without-role", validate_shift_without_role_scenario),
37736
37992
  ("resource-lock", validate_resource_lock_scenario),
37737
37993
  ("chat-supersedes", validate_chat_supersedes_scenario),
37994
+ ("worktree-overview", validate_worktree_overview_scenario),
37738
37995
  ("init-never-downgrades-openspec", validate_init_never_downgrades_openspec_scenario),
37739
37996
  ("native-plugin-marketplaces", validate_native_plugin_marketplaces_scenario),
37740
37997
  ("native-plugin-install-matrix", validate_native_plugin_install_matrix_scenario),
@@ -26,7 +26,10 @@ const SUPPORTED_MODES = new Set([
26
26
  // rather than merely tolerated.
27
27
  const NO_WRITE_MODES = new Set(["diagnose-only", "repo-action"]);
28
28
 
29
- const UNFILLED_TOKEN = /(<[^>]+>|\bTODO\b|\bTBD\b|\bplaceholder\b)/i;
29
+ // Marker words count only in capitals, the form people write to mark something
30
+ // unfinished. In lowercase they are prose — "a todo", "the placeholder text" —
31
+ // and matching them in any case refused concrete Evidence (issue #271).
32
+ const UNFILLED_TOKEN = /(<[^>]+>|\bTODO\b|\bTBD\b|\bPLACEHOLDER\b)/;
30
33
 
31
34
  function normalizeFieldText(value) {
32
35
  return String(value || "")
@@ -726,8 +729,8 @@ function requiredFieldProblems(task) {
726
729
  `Verify contains the unfilled token \`${token}\`; compact v4 `
727
730
  + "detection requires a concrete Verify. Replace or remove that "
728
731
  + "token — the expanded v3 fields are not required. Angle "
729
- + "brackets, TODO, TBD, and the word placeholder all read as "
730
- + "unfilled, including inside prose.",
732
+ + "brackets, and TODO, TBD, or PLACEHOLDER written in capitals, "
733
+ + "read as unfilled, including inside prose.",
731
734
  },
732
735
  ];
733
736
  }
@@ -0,0 +1,166 @@
1
+ "use strict";
2
+
3
+ // Worktree-overview D1-D5: local Git and chat reads only. In particular,
4
+ // status must not refresh the index, and role overrides belong to the caller,
5
+ // not to every worktree it is inspecting.
6
+ const fs = require("fs");
7
+ const path = require("path");
8
+ const { spawnSync } = require("child_process");
9
+ const store = require("./chat/store");
10
+ const notice = require("./chat/notice");
11
+
12
+ const USAGE = "keel worktrees [--repo <path>] [--issues <file>] [--json]";
13
+ class WorktreesError extends Error {}
14
+
15
+ function git(cwd, args, optional = false) {
16
+ const result = spawnSync("git", args, {
17
+ cwd, encoding: "utf8", maxBuffer: 16 * 1024 * 1024,
18
+ env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" },
19
+ });
20
+ if (result.status !== 0) {
21
+ if (optional) return null;
22
+ throw new WorktreesError(`git ${args.join(" ")} in ${cwd}: ${result.error ? result.error.message : String(result.stderr || "failed").trim()}`);
23
+ }
24
+ return String(result.stdout || "").replace(/\n$/, "");
25
+ }
26
+
27
+ // NUL delimiters preserve spaces, quotes and newlines in worktree paths.
28
+ function listWorktrees(repo) {
29
+ const rows = [];
30
+ let row = null;
31
+ for (const field of git(repo, ["worktree", "list", "--porcelain", "-z"]).split("\0")) {
32
+ if (field.startsWith("worktree ")) {
33
+ row = { path: field.slice(9), branch: null, head: null, locked: null, prunable: null };
34
+ rows.push(row);
35
+ } else if (row) {
36
+ if (field.startsWith("HEAD ")) row.head = field.slice(5);
37
+ else if (field.startsWith("branch ")) row.branch = field.slice(7).replace(/^refs\/heads\//, "");
38
+ else if (field === "locked") row.locked = true;
39
+ else if (field.startsWith("locked ")) row.locked = field.slice(7);
40
+ else if (field === "prunable") row.prunable = true;
41
+ else if (field.startsWith("prunable ")) row.prunable = field.slice(9);
42
+ }
43
+ }
44
+ return rows;
45
+ }
46
+
47
+ function defaultBranch(repo) {
48
+ const remote = git(repo, ["symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"], true);
49
+ if (remote) return remote.replace(/^refs\/remotes\//, "");
50
+ for (const branch of ["main", "master"]) {
51
+ if (git(repo, ["show-ref", "--verify", `refs/heads/${branch}`], true) !== null) return branch;
52
+ }
53
+ return null;
54
+ }
55
+
56
+ function readIssues(file) {
57
+ if (file === null) return null;
58
+ try {
59
+ const rows = JSON.parse(fs.readFileSync(file, "utf8"));
60
+ if (!Array.isArray(rows)) throw new Error("expected a JSON array of objects with number and updatedAt");
61
+ const times = new Map();
62
+ for (const row of rows) {
63
+ if (!row || !Number.isSafeInteger(row.number) || row.number <= 0
64
+ || !(typeof row.updatedAt === "string" || row.updatedAt === null)) {
65
+ throw new Error("expected each issue to have a positive integer number and updatedAt (string or null)");
66
+ }
67
+ times.set(row.number, row.updatedAt);
68
+ }
69
+ return times;
70
+ } catch (error) {
71
+ throw new WorktreesError(`Cannot read --issues ${file}: ${error.message}`);
72
+ }
73
+ }
74
+
75
+ function inspect(where, row, base, roles, times) {
76
+ if (!fs.existsSync(row.path)) {
77
+ return { path: row.path, missing: true, locked: row.locked, prunable: row.prunable };
78
+ }
79
+ const head = git(row.path, ["rev-parse", "--short", "HEAD"], true);
80
+ const upstream = row.branch
81
+ ? git(row.path, ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"], true)
82
+ : null;
83
+ let ahead = null;
84
+ let behind = null;
85
+ if (upstream) {
86
+ const counts = git(row.path, ["rev-list", "--left-right", "--count", `${upstream}...HEAD`]).trim().split(/\s+/).map(Number);
87
+ [behind, ahead] = counts;
88
+ }
89
+ let lastCommit = null;
90
+ if (head) {
91
+ const last = git(row.path, ["log", "-1", "--format=%s%x00%cI", "HEAD"]).split("\0");
92
+ lastCommit = { subject: last[0], time: last[1] };
93
+ }
94
+ const dirty = git(row.path, ["status", "--porcelain"]).split("\n").filter(Boolean).length;
95
+ const bound = roles[fs.realpathSync(row.path)];
96
+ const role = typeof bound === "string" && new RegExp(store.NAME_PATTERN_TEXT).test(bound) ? bound : null;
97
+ const subjects = head && base ? git(row.path, ["log", "--format=%s%n%b", `${base}..HEAD`, "--"]) : "";
98
+ const issues = [...new Set([...subjects.matchAll(/#(\d+)/g)].map((match) => Number(match[1])))]
99
+ .filter((number) => Number.isSafeInteger(number) && number > 0).sort((a, b) => a - b);
100
+ const result = {
101
+ ...row, head, missing: false, upstream, ahead, behind, lastCommit, dirty,
102
+ role, presence: role ? notice.presenceOf(where, role) : null, issues,
103
+ };
104
+ if (times) result.issueUpdates = issues.map((number) => ({ number, updatedAt: times.get(number) ?? null }));
105
+ return result;
106
+ }
107
+
108
+ function render(result) {
109
+ const lines = [
110
+ `keel worktrees: default branch ${result.defaultBranch || "unknown (no origin/HEAD, main or master)"}`,
111
+ "Ahead/behind counts are as of the last fetch; Keel does not fetch.",
112
+ ];
113
+ for (const row of result.worktrees) {
114
+ const markers = [row.locked ? `locked${row.locked === true ? "" : `: ${row.locked}`}` : null,
115
+ row.prunable ? `prunable${row.prunable === true ? "" : `: ${row.prunable}`}` : null].filter(Boolean);
116
+ lines.push(`${row.path}${markers.length ? ` (${markers.join("; ")})` : ""}`);
117
+ if (row.missing) {
118
+ lines.push(" missing");
119
+ continue;
120
+ }
121
+ lines.push(` ${row.branch || "detached"} ${row.head || "(no commits)"}; ${row.upstream ? `upstream ${row.upstream}, ahead ${row.ahead}, behind ${row.behind}` : "no upstream"}; dirty ${row.dirty}`);
122
+ if (row.lastCommit) lines.push(` last commit: ${row.lastCommit.subject} (${row.lastCommit.time})`);
123
+ lines.push(` role: ${row.role ? `${row.role}, ${row.presence.state}, last active ${row.presence.last_active || "unknown"}` : "none"}`);
124
+ const updates = new Map((row.issueUpdates || []).map((issue) => [issue.number, issue.updatedAt]));
125
+ lines.push(` issues: ${row.issues.length ? row.issues.map((number) => `#${number}${row.issueUpdates ? ` (updatedAt: ${updates.get(number) || "unknown"})` : ""}`).join(", ") : "none"}`);
126
+ }
127
+ return lines.join("\n");
128
+ }
129
+
130
+ function runWorktrees(argv) {
131
+ const options = { repo: process.cwd(), issues: null, json: false };
132
+ try {
133
+ for (let index = 0; index < argv.length; index += 1) {
134
+ const arg = argv[index];
135
+ if (arg === "--json") options.json = true;
136
+ else if (arg === "--help" || arg === "-h") {
137
+ process.stdout.write(`${USAGE}\nIssue times come only from --issues (a JSON array with number and updatedAt).\n`);
138
+ return 0;
139
+ } else if (arg === "--repo" || arg === "--issues") {
140
+ const value = argv[++index];
141
+ if (!value || value.startsWith("--")) throw new WorktreesError(`${arg} needs a value.`);
142
+ options[arg === "--repo" ? "repo" : "issues"] = value;
143
+ } else throw new WorktreesError(`Unknown argument ${arg}. ${USAGE}`);
144
+ }
145
+ // Refuse a bad file before collecting or printing any repository state.
146
+ const times = readIssues(options.issues);
147
+ const where = store.locate(options.repo);
148
+ if (!where) throw new WorktreesError(`Not a git repository: ${options.repo}`);
149
+ const base = defaultBranch(where.worktree);
150
+ const roles = store.readJsonFile(path.join(where.root, "roles.json"));
151
+ const result = {
152
+ defaultBranch: base,
153
+ worktrees: listWorktrees(where.worktree).map((row) => inspect(where, row, base, roles, times)),
154
+ };
155
+ process.stdout.write(`${options.json ? JSON.stringify(result, null, 2) : render(result)}\n`);
156
+ return 0;
157
+ } catch (error) {
158
+ if (error instanceof WorktreesError) {
159
+ process.stderr.write(`keel worktrees: ${error.message}\n`);
160
+ return 1;
161
+ }
162
+ throw error;
163
+ }
164
+ }
165
+
166
+ module.exports = { WorktreesError, runWorktrees };