@christang/keel 5.101.0 → 5.102.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 +18 -0
- 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 +171 -2
- package/src/core/worktrees.js +166 -0
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.
|
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));
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@christang/keel",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.102.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.102.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.102.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.102.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.102.0"
|
|
51
|
+
PROTOCOL_VERSION = "5.102.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
|
|
@@ -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:"
|
|
@@ -37735,6 +37903,7 @@ SCENARIOS: tuple = (
|
|
|
37735
37903
|
("shift-without-role", validate_shift_without_role_scenario),
|
|
37736
37904
|
("resource-lock", validate_resource_lock_scenario),
|
|
37737
37905
|
("chat-supersedes", validate_chat_supersedes_scenario),
|
|
37906
|
+
("worktree-overview", validate_worktree_overview_scenario),
|
|
37738
37907
|
("init-never-downgrades-openspec", validate_init_never_downgrades_openspec_scenario),
|
|
37739
37908
|
("native-plugin-marketplaces", validate_native_plugin_marketplaces_scenario),
|
|
37740
37909
|
("native-plugin-install-matrix", validate_native_plugin_install_matrix_scenario),
|
|
@@ -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 };
|