@christang/keel 5.105.1 → 5.107.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
@@ -663,6 +663,36 @@ This changes only what Keel *recommends*. No gate, the write guard, and completi
663
663
  exactly as they would without it, and `keel context --change <paused>` still selects it — you asked
664
664
  for it by name. Keel never pauses a change on its own.
665
665
 
666
+ ## Changes another worktree owns
667
+
668
+ When several sessions share a repository, each in its own worktree, a change in progress elsewhere
669
+ does not decide your session's status (#241). `keel context` infers only over the changes that
670
+ belong to this worktree, and lists the rest as context: `Change X (blocked) belongs to worktree Y on
671
+ branch B; it does not set this session's status.` A change belongs elsewhere when its
672
+ `.openspec.yaml` names another chat role as its owner,
673
+
674
+ ```yaml
675
+ keel:
676
+ owner: verify
677
+ ```
678
+
679
+ or, with no owner named, when another worktree's branch has commits touching it beyond the default
680
+ branch and yours has none. Only committed history counts; uncommitted files never decide it. `keel
681
+ context --change <name>` still selects any change by name.
682
+
683
+ A session that never owns a change — review, verification, a coordinator — can be declared
684
+ read-only by its chat role (#246):
685
+
686
+ ```yaml
687
+ read_only_roles:
688
+ - review
689
+ ```
690
+
691
+ In a worktree bound to a listed role, `keel context` reports one `idle` line naming the role and
692
+ lists no candidates, and the SessionStart and post-compaction note say no change is selected
693
+ instead of asking the session to pick one. `keel context --change` and `keel/HANDOFF.md` still work
694
+ as usual.
695
+
666
696
  ## External model CLIs
667
697
 
668
698
  A session can hand work to an external model CLI — codex, DeepSeek Harness's `dsh`, or one you
@@ -726,7 +756,7 @@ Without a known default branch, no issue range is inferred.
726
756
 
727
757
  ## Group chat between sessions
728
758
 
729
- Sessions working the same repository — a Claude Code session, a Codex session, an unattended runner, and you — share a work group with `keel chat`. Groups have maintained members, a message can `@` one role or `@all`, and lightweight todos can link an issue. A record can supersede its author's earlier one (`--supersedes <id>`), and the earlier one then leaves everyone's unread; unread lists newest first. A record posted with `--ack` asks the roles it addresses to acknowledge it, by `keel chat ack <id>` or a reply, and `keel chat show <id>` and `keel chat acks` list who has acknowledged, who only read it, and who has not read it. `keel chat summary --since <time>` digests what changed in the groups you can read — per sender, the message count, todos opened with whether they are still open, todos closed, superseded records folded into their successors, and acknowledgements still waiting — without a model and without marking anything read. Each member has its own unread state, and history is kept. 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.
759
+ Sessions working the same repository — a Claude Code session, a Codex session, an unattended runner, and you — share a work group with `keel chat`. Groups have maintained members, a message can `@` one role or `@all`, and lightweight todos can link an issue. A record can supersede its author's earlier one (`--supersedes <id>`), and the earlier one then leaves everyone's unread; unread lists newest first. A record posted with `--ack` asks the roles it addresses to acknowledge it, by `keel chat ack <id>` or a reply, and `keel chat show <id>` and `keel chat acks` list who has acknowledged, who only read it, and who has not read it. `keel chat summary --since <time>` digests what changed in the groups you can read — per sender, the message count, todos opened with whether they are still open, todos closed, superseded records folded into their successors, and acknowledgements still waiting — without a model and without marking anything read. Each member has its own unread state, and history is kept. A session's chat role is its identity: address other sessions by role, never by the host's session title, which Keel cannot see; `keel context` and the session projection name the role bound to the worktree, and remind a worktree with none when others here have one (#245). 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.
730
760
 
731
761
  ## Commands
732
762
 
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.105.1 -->
1
+ <!-- keel:start version=5.107.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.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.105.1",
3
+ "version": "5.107.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.105.1",
9
+ "version": "5.107.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.105.1",
5
+ "version": "5.107.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.105.1",
3
+ "version": "5.107.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.105.1",
3
+ "version": "5.107.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",
@@ -627,10 +627,17 @@ function main() {
627
627
  for (const reason of reasons) {
628
628
  lines.push(`- reason: ${String(reason).slice(0, MAX_REASON_LENGTH)}`);
629
629
  }
630
- lines.push(
631
- "- next: run `keel context` and select an owner explicitly; this hook "
632
- + "does not guess among candidates."
633
- );
630
+ if (context.readOnly && context.readOnly.role) {
631
+ lines.push(
632
+ `- next: none — read-only session (role ${context.readOnly.role}); `
633
+ + "no change is selected."
634
+ );
635
+ } else {
636
+ lines.push(
637
+ "- next: run `keel context` and select an owner explicitly; this hook "
638
+ + "does not guess among candidates."
639
+ );
640
+ }
634
641
  }
635
642
  const drift = versionReport(
636
643
  cwd,
@@ -646,6 +653,15 @@ function main() {
646
653
  lines.push(`- ${drift}`);
647
654
  human.splice(human.length - 1, 0, drift[0].toUpperCase() + drift.slice(1));
648
655
  }
656
+ // The role other sessions address this one by (#245).
657
+ if (context.role) {
658
+ lines.push(`- chat role: ${context.role} (other sessions address this one by it).`);
659
+ } else if (context.roleReminder) {
660
+ lines.push(
661
+ "- chat role: none bound here while other worktrees have one; bind one "
662
+ + "with `keel chat role --set <name>`."
663
+ );
664
+ }
649
665
  const pointer = precedentPointer(cwd);
650
666
  if (pointer) lines.push(`- ${pointer}`);
651
667
  // A note from the previous shift (shift-without-role D3), on every host.
@@ -47,8 +47,8 @@ REQUIRED_SCRIPTS = [
47
47
  "scripts/validate_plugin.py",
48
48
  ]
49
49
 
50
- PACKAGE_VERSION = "5.105.1"
51
- PROTOCOL_VERSION = "5.105.1"
50
+ PACKAGE_VERSION = "5.107.0"
51
+ PROTOCOL_VERSION = "5.107.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
@@ -8520,6 +8520,210 @@ def validate_cli_scenario() -> int:
8520
8520
  return 0
8521
8521
 
8522
8522
 
8523
+ def per_worktree_change(repo: Path, name: str, *, blocked: bool = False, owner: str | None = None) -> None:
8524
+ """An actionable change; `blocked` drops its evidence-first Reason so it cannot compile."""
8525
+ tasks = task_capsule_compact_fixture()
8526
+ if blocked:
8527
+ tasks = "".join(line for line in tasks.splitlines(keepends=True) if "- Reason:" not in line)
8528
+ write_text(repo / f"openspec/changes/{name}/proposal.md", f"## Why\n\n{name}.\n\n## What Changes\n\n- {name}.\n")
8529
+ write_text(repo / f"openspec/changes/{name}/tasks.md", tasks)
8530
+ if owner:
8531
+ write_text(repo / f"openspec/changes/{name}/.openspec.yaml", f"schema: spec-driven\nkeel:\n owner: {owner}\n")
8532
+
8533
+
8534
+ def validate_context_per_worktree_scenario() -> int:
8535
+ """Issue #241: a change that belongs to another worktree is context here.
8536
+
8537
+ Ownership is the change's `owner:` role first, then committed branch
8538
+ history beyond the default branch; a change belonging elsewhere is listed
8539
+ and does not set this session's status. Explicit selection still reaches it.
8540
+ """
8541
+ label = "context-per-worktree:"
8542
+ with tempfile.TemporaryDirectory(prefix="keel-context-worktree-") as raw:
8543
+ base = Path(raw)
8544
+ main = mailbox_repository(base / "main")
8545
+ per_worktree_change(main, "broken", blocked=True)
8546
+ per_worktree_change(main, "owned", owner="verify")
8547
+ subprocess.run(["git", "add", "-A"], cwd=main, check=True, capture_output=True)
8548
+ subprocess.run(["git", "commit", "-q", "-m", "changes"], cwd=main, check=True, capture_output=True)
8549
+ rtl = chat_worktree(main, base / "rtl")
8550
+ verify = chat_worktree(main, base / "verify")
8551
+ review = chat_worktree(main, base / "review")
8552
+ env = chat_environment()
8553
+ for cwd, role in ((rtl, "rtl"), (verify, "verify"), (review, "review")):
8554
+ run_keel(cwd, "chat", "role", "--set", role, env=env)
8555
+ (rtl / "openspec/changes/broken/proposal.md").write_text("## Why\n\nbroken, edited on rtl.\n\n## What Changes\n\n- broken.\n", encoding="utf-8")
8556
+ subprocess.run(["git", "commit", "-q", "-am", "edit broken"], cwd=rtl, check=True, capture_output=True)
8557
+
8558
+ def context(cwd: Path, *args: str) -> dict:
8559
+ result = run_keel(cwd, "context", "--json", *args, env=env)
8560
+ try:
8561
+ return json.loads(result.stdout)
8562
+ except json.JSONDecodeError:
8563
+ return {"error": (result.stdout or result.stderr).strip()}
8564
+
8565
+ here = context(review)
8566
+ if here.get("status") != "idle":
8567
+ report(f"{label} review is {here.get('status')!r}, not idle: {here}")
8568
+ return 1
8569
+ elsewhere = {e.get("change"): e for e in here.get("elsewhere", [])}
8570
+ broken = elsewhere.get("broken", {})
8571
+ if broken.get("status") != "blocked":
8572
+ report(f"{label} review does not list broken as blocked: {here.get('elsewhere')!r}")
8573
+ return 1
8574
+ if broken.get("worktree") != str(rtl.resolve()):
8575
+ report(f"{label} review does not place broken in worktree rtl: {here.get('elsewhere')!r}")
8576
+ return 1
8577
+ if elsewhere.get("owned", {}).get("owner") != "verify":
8578
+ report(f"{label} review does not list owned as belonging to verify: {here.get('elsewhere')!r}")
8579
+ return 1
8580
+
8581
+ theirs = context(rtl)
8582
+ if theirs.get("status") != "blocked":
8583
+ report(f"{label} rtl is {theirs.get('status')!r}, not blocked by its own change: {theirs}")
8584
+ return 1
8585
+ if [e.get("change") for e in theirs.get("elsewhere", [])] != ["owned"]:
8586
+ report(f"{label} rtl does not list only owned as elsewhere: {theirs.get('elsewhere')!r}")
8587
+ return 1
8588
+
8589
+ owner = context(verify)
8590
+ if (owner.get("selection") or {}).get("change") != "owned":
8591
+ report(f"{label} verify does not select its owned change: {owner}")
8592
+ return 1
8593
+ if owner.get("status") != "ready":
8594
+ report(f"{label} verify's owned change is {owner.get('status')!r}, not ready: {owner}")
8595
+ return 1
8596
+
8597
+ explicit = context(review, "--change", "broken")
8598
+ if (explicit.get("selection") or {}).get("change") != "broken" and explicit.get("status") != "blocked":
8599
+ report(f"{label} explicit selection in review did not reach broken: {explicit}")
8600
+ return 1
8601
+ report("context-per-worktree scenario passed.")
8602
+ return 0
8603
+
8604
+
8605
+ def validate_session_role_identity_scenario() -> int:
8606
+ """Issue #245: the chat role is the session's identity.
8607
+
8608
+ `keel context` carries the bound role and the SessionStart projection
8609
+ names it; an unbound worktree among bound ones is reminded; a repository
8610
+ with no roles is unchanged.
8611
+ """
8612
+ label = "session-role-identity:"
8613
+ with tempfile.TemporaryDirectory(prefix="keel-role-identity-") as raw:
8614
+ base = Path(raw)
8615
+ repo = mailbox_repository(base / "repo")
8616
+ plain = mailbox_repository(base / "plain")
8617
+ # The SessionStart hook projects only where OpenSpec is present.
8618
+ for root in (repo, plain):
8619
+ write_text(root / "openspec/specs/.keep", "")
8620
+ subprocess.run(["git", "add", "-A"], cwd=root, check=True, capture_output=True)
8621
+ subprocess.run(["git", "commit", "-q", "-m", "openspec"], cwd=root, check=True, capture_output=True)
8622
+ rtl = chat_worktree(repo, base / "rtl")
8623
+ loose = chat_worktree(repo, base / "loose")
8624
+ env = chat_environment()
8625
+ run_keel(rtl, "chat", "role", "--set", "rtl", env=env)
8626
+
8627
+ def both(cwd: Path) -> tuple[dict, str]:
8628
+ context = json.loads(run_keel(cwd, "context", "--json", env=env).stdout)
8629
+ session = run_session_start_hook(
8630
+ cwd, {"hook_event_name": "SessionStart", "source": "startup", "cwd": str(cwd)},
8631
+ keel_cli=f'node "{ROOT / "bin" / "keel.js"}"',
8632
+ )
8633
+ return context, session_start_context(session) or ""
8634
+
8635
+ context, note = both(rtl)
8636
+ if context.get("role") != "rtl":
8637
+ report(f"{label} rtl's context carries role {context.get('role')!r}, not 'rtl'.")
8638
+ return 1
8639
+ if "chat role: rtl" not in note:
8640
+ report(f"{label} rtl's projection does not name its role: {note!r}")
8641
+ return 1
8642
+
8643
+ context, note = both(loose)
8644
+ if context.get("role") is not None:
8645
+ report(f"{label} the unbound worktree carries role {context.get('role')!r}.")
8646
+ return 1
8647
+ if not any("keel chat role --set" in w for w in context.get("warnings", [])):
8648
+ report(f"{label} the unbound worktree is not reminded: {context.get('warnings')!r}")
8649
+ return 1
8650
+ if "keel chat role --set" not in note:
8651
+ report(f"{label} the unbound worktree's projection carries no reminder: {note!r}")
8652
+ return 1
8653
+
8654
+ context, note = both(plain)
8655
+ if "role" not in context:
8656
+ report(f"{label} a role-less repository's context has no role field: {context}")
8657
+ return 1
8658
+ if context.get("role") is not None:
8659
+ report(f"{label} a role-less repository carries role {context.get('role')!r}.")
8660
+ return 1
8661
+ if any("keel chat role --set" in w for w in context.get("warnings", [])):
8662
+ report(f"{label} a role-less repository is warned: {context.get('warnings')!r}")
8663
+ return 1
8664
+ if "chat role:" in note:
8665
+ report(f"{label} a role-less repository's projection has a role line: {note!r}")
8666
+ return 1
8667
+ report("session-role-identity scenario passed.")
8668
+ return 0
8669
+
8670
+
8671
+ def validate_read_only_role_scenario() -> int:
8672
+ """Issue #246: a role listed in `read_only_roles:` infers nothing.
8673
+
8674
+ `keel context` reports one idle line naming the role, the session note
8675
+ stops asking to select an owner, a malformed entry is reported, and
8676
+ explicit selection still works.
8677
+ """
8678
+ label = "read-only-role:"
8679
+ with tempfile.TemporaryDirectory(prefix="keel-read-only-") as raw:
8680
+ repo = mailbox_repository(Path(raw) / "repo")
8681
+ per_worktree_change(repo, "first")
8682
+ per_worktree_change(repo, "second")
8683
+ write_authorize_config(repo, "read_only_roles:\n - review\n - Not A Role\n")
8684
+ env = chat_environment()
8685
+ run_keel(repo, "chat", "role", "--set", "review", env=env)
8686
+ result = run_keel(repo, "context", "--json", env=env)
8687
+ try:
8688
+ context = json.loads(result.stdout)
8689
+ except json.JSONDecodeError:
8690
+ report(f"{label} keel context printed no JSON: {result.stdout} {result.stderr}")
8691
+ return 1
8692
+ if context.get("status") != "idle":
8693
+ report(f"{label} a read-only role is {context.get('status')!r}, not idle: {context}")
8694
+ return 1
8695
+ reasons = context.get("reasons", [])
8696
+ if len(reasons) != 1:
8697
+ report(f"{label} the read-only result has {len(reasons)} reasons, not one: {reasons!r}")
8698
+ return 1
8699
+ if "review" not in reasons[0]:
8700
+ report(f"{label} the read-only reason does not name review: {reasons!r}")
8701
+ return 1
8702
+ if (context.get("readOnly") or {}).get("role") != "review":
8703
+ report(f"{label} the result carries no readOnly naming review: {context.get('readOnly')!r}")
8704
+ return 1
8705
+ if not any("Not A Role" in warning for warning in context.get("warnings", [])):
8706
+ report(f"{label} the malformed entry is not reported: {context.get('warnings')!r}")
8707
+ return 1
8708
+ session = run_session_start_hook(
8709
+ repo, {"hook_event_name": "SessionStart", "source": "compact", "cwd": str(repo)},
8710
+ keel_cli=f'node "{ROOT / "bin" / "keel.js"}"',
8711
+ )
8712
+ note = session_start_context(session) or ""
8713
+ if "read-only session (role review)" not in note:
8714
+ report(f"{label} the compaction note does not name the read-only session: {note!r}")
8715
+ return 1
8716
+ if "select an owner" in note:
8717
+ report(f"{label} the compaction note still asks a read-only session to select an owner: {note!r}")
8718
+ return 1
8719
+ explicit = json.loads(run_keel(repo, "context", "--json", "--change", "first", env=env).stdout)
8720
+ if (explicit.get("selection") or {}).get("change") != "first":
8721
+ report(f"{label} explicit selection in a read-only session did not select first: {explicit}")
8722
+ return 1
8723
+ report("read-only-role scenario passed.")
8724
+ return 0
8725
+
8726
+
8523
8727
  def validate_stateless_continuity_scenario() -> int:
8524
8728
  with tempfile.TemporaryDirectory(prefix="keel-context-") as raw_tmp:
8525
8729
  root = Path(raw_tmp)
@@ -37996,6 +38200,9 @@ def validate_external_agent_exit_status_scenario() -> int:
37996
38200
 
37997
38201
  SCENARIOS: tuple = (
37998
38202
  ("stateless-continuity", validate_stateless_continuity_scenario),
38203
+ ("context-per-worktree", validate_context_per_worktree_scenario),
38204
+ ("read-only-role", validate_read_only_role_scenario),
38205
+ ("session-role-identity", validate_session_role_identity_scenario),
37999
38206
  ("core-gates", validate_core_gates_scenario),
38000
38207
  ("scope-rename-attribution", validate_scope_rename_attribution_scenario),
38001
38208
  ("target-capability-adapters", validate_target_capability_adapters_scenario),
@@ -123,6 +123,7 @@ const CONFIG_DECLARATIONS = [
123
123
  "executor_tier",
124
124
  "merge",
125
125
  "external_agents",
126
+ "read_only_roles",
126
127
  ];
127
128
 
128
129
  const CONFIG_RELATIVE_PATH = path.join("keel", "config.yaml");
@@ -803,7 +804,31 @@ function triageIssue(repo, labels, issue = null) {
803
804
  };
804
805
  }
805
806
 
807
+ // `read_only_roles:` — the chat roles whose sessions own no change (#246): a
808
+ // review, verification, or coordinating session. `keel context` reports one
809
+ // idle line for them instead of candidates. An entry that is not a role name
810
+ // is reported and ignored, so it never quietly makes some session read-only.
811
+ const ROLE_NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,31}$/;
812
+
813
+ function readReadOnlyRoles(repo) {
814
+ const roles = [];
815
+ const unreadable = [];
816
+ for (const entry of configList(repo, "read_only_roles")) {
817
+ if (ROLE_NAME_PATTERN.test(entry)) {
818
+ if (!roles.includes(entry)) roles.push(entry);
819
+ } else {
820
+ unreadable.push(entry);
821
+ }
822
+ }
823
+ const message = unreadable.length
824
+ ? `keel/config.yaml read_only_roles lists ${unreadable.map((e) => `\`${e}\``).join(", ")}, `
825
+ + "which is not a chat role name (lowercase letters, digits, and hyphens); it is ignored."
826
+ : null;
827
+ return { roles, unreadable, message };
828
+ }
829
+
806
830
  module.exports = {
831
+ readReadOnlyRoles,
807
832
  readExternalAgents,
808
833
  CONFIG_RELATIVE_PATH,
809
834
  DELEGATION_TIERS,
@@ -17,6 +17,7 @@ const {
17
17
  fullModePathsUnreadableMessage,
18
18
  readExecutorTier,
19
19
  readMergeDeclaration,
20
+ readReadOnlyRoles,
20
21
  } = require("./config");
21
22
  const { isKeelSourceRepo } = require("./capabilities");
22
23
 
@@ -314,11 +315,14 @@ function activeChanges(repo) {
314
315
  // A declaration that cannot be read leaves the change available and is
315
316
  // reported. The alternative failure — a change silently dropped from inference
316
317
  // because its config had a typo — is this defect pointed the other way.
317
- function pauseDeclaration(repo, change) {
318
+ // The entries of a change's top-level `keel:` block, an empty map when it has
319
+ // none, or `{ unreadable }` when the file cannot be read.
320
+ function keelBlock(repo, change) {
318
321
  const configPath = path.join(
319
322
  repo, "openspec", "changes", change, ".openspec.yaml"
320
323
  );
321
- if (!fs.existsSync(configPath)) return null;
324
+ const entries = new Map();
325
+ if (!fs.existsSync(configPath)) return entries;
322
326
  let content;
323
327
  try {
324
328
  content = fs.readFileSync(configPath, "utf8");
@@ -329,12 +333,17 @@ function pauseDeclaration(repo, change) {
329
333
  // starts with whitespace. Simpler and safer than a lookahead for the next
330
334
  // top-level key, which has to spell "end of input" as well.
331
335
  const block = content.match(/^keel:[ \t]*\r?\n((?:[ \t]+\S[^\n]*\r?\n?)*)/m);
332
- if (!block) return null;
333
- const entries = new Map();
336
+ if (!block) return entries;
334
337
  for (const line of block[1].split(/\r?\n/)) {
335
338
  const match = line.match(/^\s+([A-Za-z_][A-Za-z0-9_-]*)\s*:\s*(.*)$/);
336
339
  if (match) entries.set(match[1].toLowerCase(), parseScalar(match[2]));
337
340
  }
341
+ return entries;
342
+ }
343
+
344
+ function pauseDeclaration(repo, change) {
345
+ const entries = keelBlock(repo, change);
346
+ if (!(entries instanceof Map)) return entries;
338
347
  if (!entries.has("status")) return null;
339
348
  const status = String(entries.get("status") || "").toLowerCase();
340
349
  if (status !== "paused") {
@@ -356,8 +365,115 @@ function pauseNote(change, declaration) {
356
365
  );
357
366
  }
358
367
 
368
+ // Whose a change is (#241). A change declaring `owner: <role>` belongs to the
369
+ // worktree bound to that role (D1). With none, it belongs to another worktree
370
+ // whose branch has commits touching it beyond the default branch while this
371
+ // worktree's HEAD has none (D2) — committed history only, never dirty state.
372
+ // Returns null when the change belongs here.
373
+ function gitOutput(cwd, args) {
374
+ const result = spawnSync("git", args, {
375
+ cwd, encoding: "utf8", env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" },
376
+ });
377
+ return result.status === 0 ? String(result.stdout || "").trim() : null;
378
+ }
379
+
380
+ function ownershipFacts(repo) {
381
+ let role = null;
382
+ try {
383
+ const store = require("./chat/store");
384
+ role = store.currentRole(store.locate(repo));
385
+ } catch {
386
+ role = null;
387
+ }
388
+ const facts = { role, base: null, worktrees: [], here: null };
389
+ const top = gitOutput(repo, ["rev-parse", "--show-toplevel"]);
390
+ if (!top) return facts;
391
+ facts.here = fs.realpathSync(top);
392
+ const remote = gitOutput(repo, ["symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"]);
393
+ if (remote) facts.base = remote.replace(/^refs\/remotes\//, "");
394
+ else {
395
+ facts.base = ["main", "master"].find(
396
+ (branch) => gitOutput(repo, ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`]) !== null
397
+ ) || null;
398
+ }
399
+ const listed = gitOutput(repo, ["worktree", "list", "--porcelain"]) || "";
400
+ let row = null;
401
+ for (const line of listed.split("\n")) {
402
+ if (line.startsWith("worktree ")) {
403
+ row = { path: line.slice(9), branch: null };
404
+ facts.worktrees.push(row);
405
+ } else if (row && line.startsWith("branch ")) {
406
+ row.branch = line.slice(7).replace(/^refs\/heads\//, "");
407
+ }
408
+ }
409
+ return facts;
410
+ }
411
+
412
+ function commitsTouching(repo, base, ref, change) {
413
+ const count = gitOutput(repo, ["rev-list", "--count", `${base}..${ref}`, "--", `openspec/changes/${change}`]);
414
+ return count === null ? 0 : Number(count);
415
+ }
416
+
417
+ function belongsElsewhere(repo, change, facts) {
418
+ const entries = keelBlock(repo, change);
419
+ const owner = entries instanceof Map ? entries.get("owner") : null;
420
+ if (owner) return owner === facts.role ? null : { owner: String(owner) };
421
+ if (!facts.base || !facts.here) return null;
422
+ if (commitsTouching(repo, facts.base, "HEAD", change) > 0) return null;
423
+ for (const worktree of facts.worktrees) {
424
+ let real = worktree.path;
425
+ try {
426
+ real = fs.realpathSync(worktree.path);
427
+ } catch {
428
+ continue;
429
+ }
430
+ if (real === facts.here || !worktree.branch) continue;
431
+ if (commitsTouching(repo, facts.base, worktree.branch, change) > 0) {
432
+ return { worktree: real, branch: worktree.branch };
433
+ }
434
+ }
435
+ return null;
436
+ }
437
+
438
+ function elsewhereLine(entry) {
439
+ const where = entry.owner
440
+ ? `role ${entry.owner}`
441
+ : `worktree ${entry.worktree} on branch ${entry.branch}`;
442
+ return `Change ${entry.change} (${entry.status}) belongs to ${where}; it does not set this session's status.`;
443
+ }
444
+
445
+ // Inference over the changes that belong here, with the rest attached as
446
+ // context (#241 D3).
359
447
  function inferContext(repo) {
360
448
  const changes = activeChanges(repo);
449
+ if (changes.length === 0) return inferOwnContext(repo, changes);
450
+ const facts = ownershipFacts(repo);
451
+ const own = [];
452
+ const elsewhere = [];
453
+ for (const change of changes) {
454
+ const placed = belongsElsewhere(repo, change, facts);
455
+ if (!placed) {
456
+ own.push(change);
457
+ continue;
458
+ }
459
+ const compiled = selectionForChange(repo, change, "inferred");
460
+ elsewhere.push({ change, status: compiled.storageOnly ? "storage-only" : compiled.status, ...placed });
461
+ }
462
+ if (!elsewhere.length) return inferOwnContext(repo, changes);
463
+ const lines = elsewhere.map(elsewhereLine);
464
+ let context;
465
+ if (own.length === 0) {
466
+ context = result("idle", null, "none", [], ["No active OpenSpec change belongs to this worktree.", ...lines]);
467
+ } else {
468
+ context = inferOwnContext(repo, own);
469
+ if (context.status === "idle") context.reasons.push(...lines);
470
+ else context.warnings.push(...lines);
471
+ }
472
+ context.elsewhere = elsewhere;
473
+ return context;
474
+ }
475
+
476
+ function inferOwnContext(repo, changes) {
361
477
  if (changes.length === 0) {
362
478
  return result(
363
479
  "idle",
@@ -661,13 +777,60 @@ function gitWarnings(repo) {
661
777
  : [];
662
778
  }
663
779
 
780
+ // A session whose bound chat role is listed in `read_only_roles:` owns no
781
+ // change, so it gets one idle line instead of candidates (#246 D4).
782
+ function readOnlyContext(repo, readOnly) {
783
+ if (!readOnly.roles.length) return null;
784
+ let role = null;
785
+ try {
786
+ const store = require("./chat/store");
787
+ role = store.currentRole(store.locate(repo));
788
+ } catch {
789
+ role = null;
790
+ }
791
+ if (!role || !readOnly.roles.includes(role)) return null;
792
+ const context = result("idle", null, "none", [], [
793
+ `Read-only session: role ${role} is listed in keel/config.yaml read_only_roles, so no change is selected.`,
794
+ ]);
795
+ context.readOnly = { role };
796
+ return context;
797
+ }
798
+
664
799
  function resolveContext(repo, options) {
665
800
  let context;
801
+ const readOnly = readReadOnlyRoles(repo);
666
802
  if (options.change) {
667
803
  context = resolveExplicit(repo, options.change, options.task);
668
804
  } else {
669
805
  const handoff = readHandoff(repo);
670
- context = handoff ? resolveHandoff(repo, handoff) : inferContext(repo);
806
+ context = handoff
807
+ ? resolveHandoff(repo, handoff)
808
+ : readOnlyContext(repo, readOnly) || inferContext(repo);
809
+ }
810
+ if (readOnly.message) context.warnings.push(readOnly.message);
811
+ // The chat role is the session's identity (#245): other sessions address it
812
+ // by role, and Keel cannot see the host's session title. A worktree with no
813
+ // role while others here have one is reminded; a repository that uses no
814
+ // roles hears nothing.
815
+ context.role = null;
816
+ try {
817
+ const store = require("./chat/store");
818
+ const where = store.locate(repo);
819
+ context.role = store.currentRole(where);
820
+ if (!context.role) {
821
+ const bound = Object.entries(store.readJsonFile(path.join(where.root, "roles.json")))
822
+ .filter(([worktree, role]) => worktree !== where.worktree && role);
823
+ if (bound.length) {
824
+ context.warnings.push(
825
+ "This worktree has no chat role while other worktrees here have one; "
826
+ + "sessions address each other by role. Bind one with "
827
+ + "`keel chat role --set <name>`."
828
+ );
829
+ context.roleReminder = true;
830
+ }
831
+ }
832
+ } catch {
833
+ context.role = null;
671
834
  }
672
835
  context.warnings.push(...gitWarnings(repo));
673
836
  // A broken `authorize:` declaration is otherwise reported only by