@christang/keel 5.105.0 → 5.106.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
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.105.0 -->
1
+ <!-- keel:start version=5.106.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.0",
3
+ "version": "5.106.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.105.0",
9
+ "version": "5.106.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.0",
5
+ "version": "5.106.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.0",
3
+ "version": "5.106.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.0",
3
+ "version": "5.106.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",
@@ -190,7 +190,7 @@ function readPushGlobs(top) {
190
190
  }
191
191
  if (!inBlock) continue;
192
192
  if (!/^\s/.test(line)) break;
193
- const entry = line.match(/^\s+-\s*push:(\S+)\s*$/);
193
+ const entry = line.replace(/\s+#.*$/, "").match(/^\s+-\s*push:(\S+)\s*$/);
194
194
  if (entry) globs.push(entry[1]);
195
195
  }
196
196
  return globs;
@@ -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,
@@ -47,8 +47,8 @@ REQUIRED_SCRIPTS = [
47
47
  "scripts/validate_plugin.py",
48
48
  ]
49
49
 
50
- PACKAGE_VERSION = "5.105.0"
51
- PROTOCOL_VERSION = "5.105.0"
50
+ PACKAGE_VERSION = "5.106.0"
51
+ PROTOCOL_VERSION = "5.106.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,144 @@ 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_read_only_role_scenario() -> int:
8606
+ """Issue #246: a role listed in `read_only_roles:` infers nothing.
8607
+
8608
+ `keel context` reports one idle line naming the role, the session note
8609
+ stops asking to select an owner, a malformed entry is reported, and
8610
+ explicit selection still works.
8611
+ """
8612
+ label = "read-only-role:"
8613
+ with tempfile.TemporaryDirectory(prefix="keel-read-only-") as raw:
8614
+ repo = mailbox_repository(Path(raw) / "repo")
8615
+ per_worktree_change(repo, "first")
8616
+ per_worktree_change(repo, "second")
8617
+ write_authorize_config(repo, "read_only_roles:\n - review\n - Not A Role\n")
8618
+ env = chat_environment()
8619
+ run_keel(repo, "chat", "role", "--set", "review", env=env)
8620
+ result = run_keel(repo, "context", "--json", env=env)
8621
+ try:
8622
+ context = json.loads(result.stdout)
8623
+ except json.JSONDecodeError:
8624
+ report(f"{label} keel context printed no JSON: {result.stdout} {result.stderr}")
8625
+ return 1
8626
+ if context.get("status") != "idle":
8627
+ report(f"{label} a read-only role is {context.get('status')!r}, not idle: {context}")
8628
+ return 1
8629
+ reasons = context.get("reasons", [])
8630
+ if len(reasons) != 1:
8631
+ report(f"{label} the read-only result has {len(reasons)} reasons, not one: {reasons!r}")
8632
+ return 1
8633
+ if "review" not in reasons[0]:
8634
+ report(f"{label} the read-only reason does not name review: {reasons!r}")
8635
+ return 1
8636
+ if (context.get("readOnly") or {}).get("role") != "review":
8637
+ report(f"{label} the result carries no readOnly naming review: {context.get('readOnly')!r}")
8638
+ return 1
8639
+ if not any("Not A Role" in warning for warning in context.get("warnings", [])):
8640
+ report(f"{label} the malformed entry is not reported: {context.get('warnings')!r}")
8641
+ return 1
8642
+ session = run_session_start_hook(
8643
+ repo, {"hook_event_name": "SessionStart", "source": "compact", "cwd": str(repo)},
8644
+ keel_cli=f'node "{ROOT / "bin" / "keel.js"}"',
8645
+ )
8646
+ note = session_start_context(session) or ""
8647
+ if "read-only session (role review)" not in note:
8648
+ report(f"{label} the compaction note does not name the read-only session: {note!r}")
8649
+ return 1
8650
+ if "select an owner" in note:
8651
+ report(f"{label} the compaction note still asks a read-only session to select an owner: {note!r}")
8652
+ return 1
8653
+ explicit = json.loads(run_keel(repo, "context", "--json", "--change", "first", env=env).stdout)
8654
+ if (explicit.get("selection") or {}).get("change") != "first":
8655
+ report(f"{label} explicit selection in a read-only session did not select first: {explicit}")
8656
+ return 1
8657
+ report("read-only-role scenario passed.")
8658
+ return 0
8659
+
8660
+
8523
8661
  def validate_stateless_continuity_scenario() -> int:
8524
8662
  with tempfile.TemporaryDirectory(prefix="keel-context-") as raw_tmp:
8525
8663
  root = Path(raw_tmp)
@@ -24084,6 +24222,52 @@ def write_authorize_config(repo: Path, body: str) -> None:
24084
24222
  (repo / "keel" / "config.yaml").write_text(body, encoding="utf-8")
24085
24223
 
24086
24224
 
24225
+ def validate_authorize_block_reads_every_line_scenario() -> int:
24226
+ """Issue #275: no line of `authorize:` is dropped silently.
24227
+
24228
+ An item with a space used to end the block, dropping it and every later
24229
+ entry while doctor said ok; a trailing comment dropped its item too.
24230
+ """
24231
+ label = "authorize-block-reads-every-line:"
24232
+ with tempfile.TemporaryDirectory(prefix="keel-authorize-275-") as raw_tmp:
24233
+ root = Path(raw_tmp)
24234
+ spaced = root / "spaced"
24235
+ spaced.mkdir()
24236
+ write_authorize_config(spaced, "authorize:\n - commit\n - push:main branch\n - release\n")
24237
+ doctor = run_keel(spaced, "--doctor")
24238
+ if doctor.returncode == 0:
24239
+ report(f"{label} an item with a space was not refused: {doctor.stdout}")
24240
+ return 1
24241
+ if "push:main branch" not in doctor.stdout + doctor.stderr:
24242
+ report(f"{label} the refusal does not name `push:main branch`: {doctor.stdout}")
24243
+ return 1
24244
+ if "commit: authorized" in doctor.stdout:
24245
+ report(f"{label} the entries beside the refused one stayed authorized.")
24246
+ return 1
24247
+
24248
+ commented = root / "commented"
24249
+ subprocess.run(["git", "init", "-q", "-b", "main", str(commented)], check=True, capture_output=True)
24250
+ write_authorize_config(
24251
+ commented,
24252
+ "authorize:\n - commit # owner, 2026-10-11\n - push:claude/* # sessions push their own branches\n",
24253
+ )
24254
+ out = run_keel(commented, "--doctor").stdout
24255
+ if "commit: authorized" not in out:
24256
+ report(f"{label} a trailing comment dropped `commit`: {out}")
24257
+ return 1
24258
+ push_line = next((l for l in out.splitlines() if l.strip().startswith("push:")), "")
24259
+ if "claude/*" not in push_line or "#" in push_line:
24260
+ report(f"{label} the push line does not read the glob without its comment: {push_line!r}")
24261
+ return 1
24262
+ event = {"tool_name": "Bash", "tool_input": {"command": "git push origin HEAD:main"}, "cwd": str(commented)}
24263
+ decision = pretooluse_decision(run_pretooluse_guard_hook(commented, event))
24264
+ if not decision or decision.get("permissionDecision") != "deny":
24265
+ report(f"{label} the push guard did not read a commented glob: {decision!r}")
24266
+ return 1
24267
+ report("authorize-block-reads-every-line scenario passed.")
24268
+ return 0
24269
+
24270
+
24087
24271
  def validate_authorize_push_close_cleanup_scenario() -> int:
24088
24272
  """Issue #257: `push:<glob>`, `issue-close:<owner>/<repo>`, `cleanup:scratch`.
24089
24273
 
@@ -37950,6 +38134,8 @@ def validate_external_agent_exit_status_scenario() -> int:
37950
38134
 
37951
38135
  SCENARIOS: tuple = (
37952
38136
  ("stateless-continuity", validate_stateless_continuity_scenario),
38137
+ ("context-per-worktree", validate_context_per_worktree_scenario),
38138
+ ("read-only-role", validate_read_only_role_scenario),
37953
38139
  ("core-gates", validate_core_gates_scenario),
37954
38140
  ("scope-rename-attribution", validate_scope_rename_attribution_scenario),
37955
38141
  ("target-capability-adapters", validate_target_capability_adapters_scenario),
@@ -38147,6 +38333,7 @@ SCENARIOS: tuple = (
38147
38333
  validate_standing_authorization_declaration_scenario,
38148
38334
  ),
38149
38335
  ("authorize-push-close-cleanup", validate_authorize_push_close_cleanup_scenario),
38336
+ ("authorize-block-reads-every-line", validate_authorize_block_reads_every_line_scenario),
38150
38337
  (
38151
38338
  "standing-authorization-sync-confusion",
38152
38339
  validate_standing_authorization_sync_confusion_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");
@@ -144,11 +145,14 @@ function configList(repo, key) {
144
145
  }
145
146
  if (!inBlock) continue;
146
147
  if (line.trim() === "") continue;
147
- const entry = line.match(/^\s+-\s*(\S+)\s*$/);
148
- // Anything that is not a list item closes the block; the next top-level
149
- // key belongs to the rest of the file.
150
- if (!entry) break;
151
- entries.push(entry[1]);
148
+ // Only a line at column zero closes the block: the next top-level key
149
+ // belongs to the rest of the file. Every indented line is an entry, read
150
+ // whole, so one Keel cannot use is refused by name rather than ending the
151
+ // block and dropping itself and everything after it unseen (#275).
152
+ if (!/^\s/.test(line)) break;
153
+ const text = line.replace(/\s+#.*$/, "").trim();
154
+ const entry = text.replace(/^-\s*/, "");
155
+ if (entry) entries.push(entry);
152
156
  }
153
157
  return entries;
154
158
  }
@@ -800,7 +804,31 @@ function triageIssue(repo, labels, issue = null) {
800
804
  };
801
805
  }
802
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
+
803
830
  module.exports = {
831
+ readReadOnlyRoles,
804
832
  readExternalAgents,
805
833
  CONFIG_RELATIVE_PATH,
806
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,14 +777,37 @@ 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);
671
809
  }
810
+ if (readOnly.message) context.warnings.push(readOnly.message);
672
811
  context.warnings.push(...gitWarnings(repo));
673
812
  // A broken `authorize:` declaration is otherwise reported only by
674
813
  // `keel --doctor`, an explicitly-invoked diagnostic — surfaced here too so a