@christang/keel 5.159.0 → 5.161.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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keel",
3
- "version": "5.159.0",
3
+ "version": "5.161.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",
package/README.md CHANGED
@@ -210,7 +210,7 @@ because a permission granted in conversation does not survive a context reset. D
210
210
  `keel/config.yaml` instead:
211
211
 
212
212
  ```yaml
213
- authorize: # accepted names: commit, push, push:<branch glob>, release, archive, continuation, issue:<owner>/<repo>, protocol-refresh, chat-reply:<group>, issue-close:<owner>/<repo>, cleanup:scratch, push-protected:<branch glob>[@<role>], shift-restore, self-shift
213
+ authorize: # accepted names: commit, push, push:<branch glob>[@<role>], release, archive, continuation, issue:<owner>/<repo>[@<role>], protocol-refresh, chat-reply:<group>[@<role>], issue-close:<owner>/<repo>[@<role>], cleanup:scratch[@<role>], push-protected:<branch glob>[@<role>], shift-restore, self-shift
214
214
  - commit
215
215
  - push
216
216
  ```
@@ -262,6 +262,17 @@ refused. A permission mode that cannot be relied on to ask, `bypassPermissions`
262
262
  refused too. Declaring it turns the push check on by itself, and a bare `push` beside it is
263
263
  refused.
264
264
 
265
+ Every scoped entry — `push:`, `issue:`, `issue-close:`, `cleanup:`, `chat-reply:` and
266
+ `push-protected:` — may end in `@<role>`, or a role pattern such as `@kaiwu-design-*`, where `*`
267
+ matches any run of role characters (#378). Such an entry reaches only a session whose chat role
268
+ matches. A session reads the grants for its own role in the capsule, `keel context`,
269
+ `keel --doctor` and its chat-reply groups, and `keel --doctor` lists, for each bound role, the
270
+ scoped entries that reach it. On push, the Claude write guard allows a branch only through an
271
+ entry for the session's role, and refuses a branch another role's entry covers by naming that role.
272
+ The check stays on for every session while any push entry is declared, so a role that no entry
273
+ names is limited, not unlimited. The tracker, chat and scratchpad scopes stay carried rather than
274
+ enforced: the role decides only which session reads them.
275
+
265
276
  `shift-restore` (#319) covers the two things a session started by a shift change on the Claude
266
277
  desktop app must do right after `keel shift resume`: turn its own Remote Control back on if it came
267
278
  back off, and rename itself back to its working title. A clear there keeps no title. Without the declaration, the woken
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.159.0 -->
1
+ <!-- keel:start version=5.161.0 -->
2
2
  ## Keel Bootstrap
3
3
 
4
4
  - Start every session with `keel context`; OpenSpec artifacts and Git are the only durable authority — never native memory, goals, or transcripts.
package/bin/keel.js CHANGED
@@ -48,6 +48,7 @@ const {
48
48
  STANDING_AUTHORIZATION_ACTIONS,
49
49
  readPrecedentStore,
50
50
  readStandingAuthorization,
51
+ roleMatches,
51
52
  readFullModePaths,
52
53
  readExecutorTier,
53
54
  readMergeDeclaration,
@@ -2378,7 +2379,7 @@ function gitConfigHooksPath(repo) {
2378
2379
 
2379
2380
  function printStandingAuthorizationSurface(repo) {
2380
2381
  process.stdout.write("\nStanding authorization:\n");
2381
- const { declared, scopes, unknown, message } = readStandingAuthorization(repo);
2382
+ const { declared, scopes, unknown, message, otherRoles, entries, role } = readStandingAuthorization(repo);
2382
2383
  if (unknown.length > 0) {
2383
2384
  printDoctorLine("authorize", "failed", message);
2384
2385
  return false;
@@ -2386,9 +2387,10 @@ function printStandingAuthorizationSurface(repo) {
2386
2387
  printDoctorLine(
2387
2388
  "authorize",
2388
2389
  declared.length > 0 ? "ok" : "none",
2389
- declared.length > 0
2390
+ (declared.length > 0
2390
2391
  ? `declared in keel/config.yaml: ${declared.join(", ")}`
2391
- : "undeclared; every action stays hard-stop"
2392
+ : "undeclared; every action stays hard-stop")
2393
+ + (otherRoles.length ? `; for other roles than ${role || "this unbound session"}: ${otherRoles.join(", ")}` : "")
2392
2394
  );
2393
2395
  for (const action of STANDING_AUTHORIZATION_ACTIONS) {
2394
2396
  // Keyed on the action, never on the declared string. A scoped entry is
@@ -2431,6 +2433,21 @@ function printStandingAuthorizationSurface(repo) {
2431
2433
  + "asked, and a mode that cannot ask (bypassPermissions, dontAsk) is refused"
2432
2434
  );
2433
2435
  }
2436
+ // Per bound role, the scoped entries that reach it (#378 D4).
2437
+ if (entries.some((entry) => entry.role)) {
2438
+ let bound = [];
2439
+ try {
2440
+ const store = require("../src/core/chat/store");
2441
+ const where = store.locate(repo);
2442
+ if (where) bound = [...new Set(Object.values(store.readRoles(where.root)).map((name) => store.canonicalRole(where.root, name)))].sort();
2443
+ } catch {
2444
+ bound = [];
2445
+ }
2446
+ for (const name of bound) {
2447
+ const reach = entries.filter((entry) => entry.scope !== null && (!entry.role || roleMatches(entry.role, name))).map((entry) => entry.entry);
2448
+ printDoctorLine("roles", name, reach.length ? reach.join(", ") : "no scoped grant");
2449
+ }
2450
+ }
2434
2451
  if (scopes.get("push")) {
2435
2452
  printDoctorLine(
2436
2453
  "push scope",
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.159.0",
3
+ "version": "5.161.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.159.0",
9
+ "version": "5.161.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.159.0",
5
+ "version": "5.161.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.159.0",
3
+ "version": "5.161.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.159.0",
3
+ "version": "5.161.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",
@@ -187,7 +187,8 @@ function gitOut(cwd, args) {
187
187
  return result.status === 0 ? String(result.stdout || "").trim() : null;
188
188
  }
189
189
 
190
- // `push:` globs and `push-protected:` entries ({ glob, role }) of `authorize:`.
190
+ // `push:` and `push-protected:` entries ({ glob, role }) of `authorize:`; a
191
+ // role pattern after `@` limits either to matching sessions (#378).
191
192
  function readPushGlobs(top) {
192
193
  let text = "";
193
194
  try {
@@ -207,8 +208,8 @@ function readPushGlobs(top) {
207
208
  if (!inBlock) continue;
208
209
  if (!/^\s/.test(line)) break;
209
210
  const bare = line.replace(/\s+#.*$/, "");
210
- const entry = bare.match(/^\s+-\s*push:(\S+)\s*$/);
211
- if (entry) globs.push(entry[1]);
211
+ const entry = bare.match(/^\s+-\s*push:([^@\s]+)(?:@(\S+))?\s*$/);
212
+ if (entry) globs.push({ glob: entry[1], role: entry[2] || null });
212
213
  const guarded = bare.match(/^\s+-\s*push-protected:([^@\s]+)(?:@(\S+))?\s*$/);
213
214
  if (guarded) protectedEntries.push({ glob: guarded[1], role: guarded[2] || null });
214
215
  }
@@ -225,13 +226,29 @@ function sessionRole(top) {
225
226
  const common = gitOut(top, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
226
227
  if (!common) return null;
227
228
  try {
228
- const roles = JSON.parse(fs.readFileSync(path.join(fs.realpathSync(common), "keel-chat", "roles.json"), "utf8"));
229
- return roles[fs.realpathSync(top)] || null;
229
+ const root = path.join(fs.realpathSync(common), "keel-chat");
230
+ const roles = JSON.parse(fs.readFileSync(path.join(root, "roles.json"), "utf8"));
231
+ let role = roles[fs.realpathSync(top)] || null;
232
+ // A renamed role reads as its new name (#376).
233
+ let renames = {};
234
+ try {
235
+ renames = JSON.parse(fs.readFileSync(path.join(root, "renames.json"), "utf8")) || {};
236
+ } catch {
237
+ renames = {};
238
+ }
239
+ for (let hops = 0; role && renames[role] && hops < 32; hops += 1) role = renames[role];
240
+ return role;
230
241
  } catch {
231
242
  return null;
232
243
  }
233
244
  }
234
245
 
246
+ // A role pattern: chat-role characters, `*` matching any run of them (#378).
247
+ function roleMatches(pattern, role) {
248
+ if (!role) return false;
249
+ return new RegExp(`^${String(pattern).split("*").join("[a-z0-9-]*")}$`).test(role);
250
+ }
251
+
235
252
  // Modes in which the host cannot be relied on to ask (#280 D3, F2).
236
253
  const MODES_THAT_CANNOT_ASK = new Set(["bypassPermissions", "dontAsk"]);
237
254
 
@@ -533,7 +550,7 @@ function checkPushes(event) {
533
550
  const { globs, protectedEntries } = readPushGlobs(top);
534
551
  if (!globs.length && !protectedEntries.length) continue;
535
552
  const declared = [
536
- ...globs.map((glob) => `\`push:${glob}\``),
553
+ ...globs.map((e) => `\`push:${e.glob}${e.role ? `@${e.role}` : ""}\``),
537
554
  ...protectedEntries.map((e) => `\`push-protected:${e.glob}${e.role ? `@${e.role}` : ""}\``),
538
555
  ].join(", ");
539
556
  const result = pushTargets(push);
@@ -556,19 +573,30 @@ function checkPushes(event) {
556
573
  return 0;
557
574
  }
558
575
  if (result.tags) carriesTags = true;
576
+ let role;
577
+ const roleOf = () => (role === undefined ? (role = sessionRole(top)) : role);
578
+ const mine = (e) => !e.role || roleMatches(e.role, roleOf());
559
579
  const unlisted = result.tags
560
580
  ? result.targets
561
- : result.targets.filter((branch) => !globs.some((glob) => globPattern(glob).test(branch)));
581
+ : result.targets.filter((branch) => !globs.some((e) => mine(e) && globPattern(e.glob).test(branch)));
562
582
  const outside = [];
563
583
  for (const branch of unlisted) {
564
584
  const entry = protectedEntries.find((e) => globPattern(e.glob).test(branch));
565
585
  if (!entry) {
586
+ // Another role's grant (#378): name who may push it.
587
+ const theirs = globs.filter((e) => e.role && globPattern(e.glob).test(branch)).map((e) => e.role);
588
+ if (theirs.length && !result.tags) {
589
+ deny(
590
+ `Keel push guard: \`${branch}\` may be pushed by role ${theirs.join(" or ")} (keel/config.yaml), and this `
591
+ + `session is ${roleOf() ? `role ${roleOf()}` : "bound to no chat role"}.`
592
+ );
593
+ return 0;
594
+ }
566
595
  outside.push(branch);
567
596
  continue;
568
597
  }
569
598
  if (entry.role) {
570
- const role = sessionRole(top);
571
- if (role !== entry.role) {
599
+ if (!roleMatches(entry.role, roleOf())) {
572
600
  deny(
573
601
  `Keel push guard: \`${branch}\` is protected for role ${entry.role}, and this `
574
602
  + `session is ${role ? `role ${role}` : "bound to no chat role"}; only an ${entry.role} `
@@ -49,8 +49,8 @@ REQUIRED_SCRIPTS = [
49
49
  "scripts/validate_plugin.py",
50
50
  ]
51
51
 
52
- PACKAGE_VERSION = "5.159.0"
53
- PROTOCOL_VERSION = "5.159.0"
52
+ PACKAGE_VERSION = "5.161.0"
53
+ PROTOCOL_VERSION = "5.161.0"
54
54
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
55
55
  OPENSPEC_SCHEMA_NAME = "keel-spec-driven"
56
56
  # Mirrors KEEL_PACKAGE_NAME in scripts/install_to_repo.py, one of the two
@@ -2675,6 +2675,8 @@ def validate_chat_role_rename_scenario() -> int:
2675
2675
  run_keel(rtl2, "chat", "post", "soc", "first", env=env2)
2676
2676
  run_keel(verify2, "chat", "read", env=env2)
2677
2677
  run_keel(rtl2, "chat", "group", "add", "soc", "check", env=env2)
2678
+ # kaiwu-ip's order: the new name joined, then the old one was removed.
2679
+ run_keel(rtl2, "chat", "group", "remove", "soc", "verify", env=env2)
2678
2680
  run_keel(rtl2, "chat", "post", "soc", "second", env=env2)
2679
2681
  run_keel(verify2, "chat", "role", "--set", "check", env=env2)
2680
2682
  run_keel(verify2, "chat", "read", env=env2)
@@ -2682,6 +2684,10 @@ def validate_chat_role_rename_scenario() -> int:
2682
2684
  if merged.returncode != 0:
2683
2685
  report(f"{label} keel chat role --rename was refused onto an existing role: {merged.stdout!r} {merged.stderr!r}")
2684
2686
  return 1
2687
+ groups2 = json.loads(run_keel(verify2, "chat", "group", "list", "--json", env=env2).stdout)["groups"]
2688
+ if "check" not in next((g["members"] for g in groups2 if g["name"] == "soc"), []):
2689
+ report(f"{label} the old name's leave after the new one joined removed check from soc: {groups2!r}")
2690
+ return 1
2685
2691
  left = json.loads(run_keel(verify2, "chat", "unread", "--json", env=env2).stdout)
2686
2692
  if "second" in json.dumps(left):
2687
2693
  report(f"{label} check's later cursor was not kept: {left!r}")
@@ -30935,9 +30941,9 @@ def validate_continuation_authorization_scenario() -> int:
30935
30941
 
30936
30942
 
30937
30943
  ACCEPTED_AUTHORIZE_NAMES = (
30938
- "commit, push, push:<branch glob>, release, archive, continuation, "
30939
- "issue:<owner>/<repo>, protocol-refresh, chat-reply:<group>, "
30940
- "issue-close:<owner>/<repo>, cleanup:scratch, push-protected:<branch glob>[@<role>], shift-restore, self-shift"
30944
+ "commit, push, push:<branch glob>[@<role>], release, archive, continuation, "
30945
+ "issue:<owner>/<repo>[@<role>], protocol-refresh, chat-reply:<group>[@<role>], "
30946
+ "issue-close:<owner>/<repo>[@<role>], cleanup:scratch[@<role>], push-protected:<branch glob>[@<role>], shift-restore, self-shift"
30941
30947
  )
30942
30948
 
30943
30949
 
@@ -30999,7 +31005,7 @@ def validate_continuation_docs_scenario() -> int:
30999
31005
  return 1
31000
31006
 
31001
31007
  config_text = (ROOT / "keel/config.yaml").read_text(encoding="utf-8")
31002
- if "commit, push, push:<branch glob>,\n# release, archive, continuation, issue:<owner>/<repo>, protocol-refresh,\n# chat-reply:<group>, issue-close:<owner>/<repo>, cleanup:scratch,\n# push-protected:<branch glob>[@<role>], shift-restore, self-shift" not in config_text:
31008
+ if "commit, push, push:<branch glob>[@<role>],\n# release, archive, continuation, issue:<owner>/<repo>[@<role>], protocol-refresh,\n# chat-reply:<group>[@<role>], issue-close:<owner>/<repo>[@<role>], cleanup:scratch[@<role>],\n# push-protected:<branch glob>[@<role>], shift-restore, self-shift" not in config_text:
31003
31009
  report(
31004
31010
  f"{label}: keel/config.yaml's comment lacks: protocol-refresh in the "
31005
31011
  "seven-name vocabulary."
@@ -33464,6 +33470,101 @@ def validate_push_branch_guard_scenario() -> int:
33464
33470
  return 0
33465
33471
 
33466
33472
 
33473
+ def validate_authorize_role_scoped_scenario() -> int:
33474
+ """Issue #378: a scoped grant may name the roles it applies to.
33475
+
33476
+ kaiwu-ip split its standing authorization by capability, one session per
33477
+ capability, and could only write the split as comments: every scoped grant
33478
+ but `push-protected` applied to every session. `@<role pattern>` limits an
33479
+ entry to matching roles; the push guard stays on for a role no entry names.
33480
+ """
33481
+ label = "authorize-role-scoped:"
33482
+ with tempfile.TemporaryDirectory(prefix="keel-authorize-378-") as raw:
33483
+ base = Path(raw)
33484
+ repo = mailbox_repository(base / "repo")
33485
+ rtl = chat_worktree(repo, base / "rtl")
33486
+ verify = chat_worktree(repo, base / "verify")
33487
+ env = chat_environment()
33488
+ run_keel(rtl, "chat", "role", "--set", "rtl", env=env)
33489
+ run_keel(verify, "chat", "role", "--set", "verify", env=env)
33490
+ entries = ["commit", "push:design-*@rtl", "push:review-*@ver*", "issue:acme/widgets@rtl",
33491
+ "chat-reply:soc@verify", "push-protected:main@rt*"]
33492
+ for cwd in (rtl, verify):
33493
+ write_authorize_config(cwd, "authorize:\n" + "".join(f" - {e}\n" for e in entries))
33494
+
33495
+ def line(stdout: str, name: str) -> str:
33496
+ return next((l for l in stdout.splitlines() if l.strip().startswith(f"{name}:")), "")
33497
+
33498
+ for cwd, role, granted, withheld in ((rtl, "rtl", "issue", "chat-reply"), (verify, "verify", "chat-reply", "issue")):
33499
+ doctor = run_keel(cwd, "--doctor", env=env)
33500
+ if not line(doctor.stdout, granted):
33501
+ report(f"{label} {role}'s doctor has no {granted} line: {doctor.stdout}")
33502
+ return 1
33503
+ if "not authorized" in line(doctor.stdout, granted):
33504
+ report(f"{label} {role}'s doctor does not report {granted} authorized: {doctor.stdout}")
33505
+ return 1
33506
+ if "not authorized" not in line(doctor.stdout, withheld):
33507
+ report(f"{label} {role}'s doctor reports {withheld}, another role's grant: {line(doctor.stdout, withheld)!r}")
33508
+ return 1
33509
+ roles = [l for l in doctor.stdout.splitlines() if l.startswith("roles:")]
33510
+ if not any("rtl" in l and "issue:acme/widgets@rtl" in l for l in roles):
33511
+ report(f"{label} {role}'s doctor lists no roles line for rtl's grants: {roles!r}")
33512
+ return 1
33513
+ if not any("verify" in l and "chat-reply:soc@verify" in l for l in roles):
33514
+ report(f"{label} {role}'s doctor lists no roles line for verify's grants: {roles!r}")
33515
+ return 1
33516
+
33517
+ hook_env = {k: v for k, v in os.environ.items() if k not in ("KEEL_CHAT_ROLE", "KEEL_MAIL_ROLE")}
33518
+ hook_env["CLAUDE_PLUGIN_ROOT"] = str(ROOT / PLUGIN_ROOT)
33519
+
33520
+ def decide(cwd: Path, command: str, role: str | None = None) -> dict:
33521
+ event = {"tool_name": "Bash", "tool_input": {"command": command}, "cwd": str(cwd), "permission_mode": "default"}
33522
+ run_env = {**hook_env, **({"KEEL_CHAT_ROLE": role} if role else {})}
33523
+ result = subprocess.run(
33524
+ ["node", str(ROOT / PLUGIN_ROOT / "scripts/pretooluse-guard.js")],
33525
+ cwd=cwd, env=run_env, input=json.dumps(event), text=True, capture_output=True, check=False,
33526
+ )
33527
+ return pretooluse_decision(result) or {"permissionDecision": "pass"}
33528
+
33529
+ if decide(rtl, "git push origin design-x").get("permissionDecision") != "pass":
33530
+ report(f"{label} rtl's own design branch was not allowed: {decide(rtl, 'git push origin design-x')!r}")
33531
+ return 1
33532
+ other = decide(verify, "git push origin design-x")
33533
+ if other.get("permissionDecision") != "deny":
33534
+ report(f"{label} verify pushing rtl's design branch was {other!r}, not deny.")
33535
+ return 1
33536
+ if "rtl" not in other.get("permissionDecisionReason", ""):
33537
+ report(f"{label} the refusal does not name the role that may push it: {other!r}")
33538
+ return 1
33539
+ if decide(verify, "git push origin review-x").get("permissionDecision") != "pass":
33540
+ report(f"{label} verify's review branch, granted by the ver* pattern, was not allowed.")
33541
+ return 1
33542
+ unnamed = decide(verify, "git push origin design-x", role="spec")
33543
+ if unnamed.get("permissionDecision") != "deny":
33544
+ report(f"{label} a role no entry names was left unlimited: {unnamed!r}")
33545
+ return 1
33546
+ if decide(rtl, "git push origin HEAD:main").get("permissionDecision") != "ask":
33547
+ report(f"{label} rtl, matching main@rt*, was not asked about main.")
33548
+ return 1
33549
+ if decide(verify, "git push origin HEAD:main").get("permissionDecision") != "deny":
33550
+ report(f"{label} verify's push to main@rt* was not refused.")
33551
+ return 1
33552
+
33553
+ write_authorize_config(rtl, "authorize:\n - issue:acme/widgets@Not A Role\n")
33554
+ bad = run_keel(rtl, "--doctor", env=env)
33555
+ if bad.returncode == 0:
33556
+ report(f"{label} a malformed role pattern was accepted: {bad.stdout}")
33557
+ return 1
33558
+ if "issue:acme/widgets@Not A Role" not in bad.stdout:
33559
+ report(f"{label} the refusal does not name the entry: {bad.stdout}")
33560
+ return 1
33561
+ if "authorize-role-scoped" not in {name for name, _ in SCENARIOS}:
33562
+ report(f"{label} scenario is not registered.")
33563
+ return 1
33564
+ report("authorize-role-scoped scenario passed.")
33565
+ return 0
33566
+
33567
+
33467
33568
  def validate_push_protected_guard_scenario() -> int:
33468
33569
  """Issue #280: a protected push is asked, never stored, and role-limited.
33469
33570
 
@@ -42643,6 +42744,7 @@ SCENARIOS: tuple = (
42643
42744
  ("push-guard-redirects", validate_push_guard_redirects_scenario),
42644
42745
  ("push-guard-follow-tags", validate_push_guard_follow_tags_scenario),
42645
42746
  ("push-protected-guard", validate_push_protected_guard_scenario),
42747
+ ("authorize-role-scoped", validate_authorize_role_scoped_scenario),
42646
42748
  ("touch-guard-record-layer", validate_touch_guard_record_layer_scenario),
42647
42749
  ("repo-action-mode", validate_repo_action_mode_scenario),
42648
42750
  ("runner-skip-accounting", validate_runner_skip_accounting_scenario),
@@ -218,7 +218,9 @@ function mapRecord(record, renames) {
218
218
  record.from = map(record.from);
219
219
  if (record.assignee) record.assignee = map(record.assignee);
220
220
  if (Array.isArray(record.mentions)) record.mentions = [...new Set(record.mentions.map(map))];
221
- if ((record.kind === "join" || record.kind === "leave") && record.target) record.target = map(record.target);
221
+ // A join or leave keeps the name it was written for; `member` is the role
222
+ // it now means, applied once membership is computed (groupState).
223
+ if ((record.kind === "join" || record.kind === "leave") && record.target) record.member = map(record.target);
222
224
  if (record.group && isDirect(record.group)) record.direct = [...new Set(directMembers(record.group).map(map))];
223
225
  return record;
224
226
  }
@@ -457,7 +459,16 @@ function groupState(records) {
457
459
  }
458
460
  if (record.kind === "archive") archived = true;
459
461
  }
460
- return { members, listeners, archived, exists: records.length > 0 };
462
+ // Renamed names (#376): membership is computed under the names the records
463
+ // were written for, so an old name's leave after the new name joined does
464
+ // not remove the new one; the result is then read through the renames. A
465
+ // merged role is listen-only only when every name it merges was.
466
+ const meant = new Map(records.filter((r) => r.member).map((r) => [r.target, r.member]));
467
+ if (!meant.size) return { members, listeners, archived, exists: records.length > 0 };
468
+ const as = (name) => meant.get(name) || name;
469
+ const mapped = new Set([...members].map(as));
470
+ const speaking = new Set([...members].filter((name) => !listeners.has(name)).map(as));
471
+ return { members: mapped, listeners: new Set([...mapped].filter((name) => !speaking.has(name))), archived, exists: records.length > 0 };
461
472
  }
462
473
 
463
474
  function isDirect(group) {
@@ -71,17 +71,27 @@ const AUTHORIZATION_SCOPES = {
71
71
  // Branch-name characters and `*`; `*` matches within one `/` segment and
72
72
  // `**` across them, as Touch globs do.
73
73
  push: { form: "<branch glob>", pattern: /^[A-Za-z0-9._/*-]+$/ },
74
- "push-protected": { form: "<branch glob>[@<role>]", pattern: /^[A-Za-z0-9._/*-]+(?:@[a-z0-9][a-z0-9-]{0,31})?$/ },
74
+ "push-protected": { form: "<branch glob>", pattern: /^[A-Za-z0-9._/*-]+$/ },
75
75
  };
76
76
 
77
+ // `@<role pattern>` after any scope (#378): chat-role characters and `*`,
78
+ // which matches any run of them. Only a session of a matching role reads it.
79
+ const AUTHORIZATION_ROLE_PATTERN = /^[a-z0-9*][a-z0-9*-]{0,31}$/;
80
+
81
+ function roleMatches(pattern, role) {
82
+ if (!role) return false;
83
+ // The pattern is checked to hold only `[a-z0-9-]` and `*`, so each part is a literal.
84
+ return new RegExp(`^${String(pattern).split("*").join("[a-z0-9-]*")}$`).test(role);
85
+ }
86
+
77
87
  // How the accepted names are spelled back to an author: the scoped ones carry
78
88
  // their form, so the list is copyable rather than a name the next message
79
89
  // refuses.
80
90
  const STANDING_AUTHORIZATION_ACCEPTED_FORMS = STANDING_AUTHORIZATION_ACTIONS.flatMap(
81
91
  (action) => {
82
- if (SCOPED_AUTHORIZATION_ACTIONS.has(action)) return [`${action}:${AUTHORIZATION_SCOPES[action].form}`];
92
+ if (SCOPED_AUTHORIZATION_ACTIONS.has(action)) return [`${action}:${AUTHORIZATION_SCOPES[action].form}[@<role>]`];
83
93
  if (OPTIONALLY_SCOPED_AUTHORIZATION_ACTIONS.has(action)) {
84
- return [action, `${action}:${AUTHORIZATION_SCOPES[action].form}`];
94
+ return [action, `${action}:${AUTHORIZATION_SCOPES[action].form}[@<role>]`];
85
95
  }
86
96
  return [action];
87
97
  }
@@ -105,10 +115,35 @@ function classifyAuthorizationEntry(entry) {
105
115
  return { ok: true, entry, action, scope: null };
106
116
  }
107
117
  if (scope === null) return { ok: false, entry, action, reason: "missing-scope" };
108
- if (!AUTHORIZATION_SCOPES[action].pattern.test(scope)) {
118
+ const at = scope.lastIndexOf("@");
119
+ const bare = at === -1 ? scope : scope.slice(0, at);
120
+ const role = at === -1 ? null : scope.slice(at + 1);
121
+ if (!AUTHORIZATION_SCOPES[action].pattern.test(bare)) {
109
122
  return { ok: false, entry, action, reason: "malformed-scope" };
110
123
  }
111
- return { ok: true, entry, action, scope };
124
+ if (role !== null && !AUTHORIZATION_ROLE_PATTERN.test(role)) {
125
+ return { ok: false, entry, action, reason: "malformed-role" };
126
+ }
127
+ // `push-protected` keeps its role in the scope it prints, as before (#280).
128
+ return { ok: true, entry, action, scope: action === "push-protected" ? scope : bare, role };
129
+ }
130
+
131
+ // The chat role of the session reading the declaration (#378 D2): the
132
+ // override, else the worktree's binding, read through any rename.
133
+ function sessionChatRole(repo) {
134
+ for (const variable of ["KEEL_CHAT_ROLE", "KEEL_MAIL_ROLE"]) {
135
+ const value = (process.env[variable] || "").trim();
136
+ if (value) return value;
137
+ }
138
+ try {
139
+ const store = require("./chat/store");
140
+ const where = store.locate(repo);
141
+ if (!where) return null;
142
+ const bound = store.readRoles(where.root)[where.worktree];
143
+ return bound ? store.canonicalRole(where.root, bound) : null;
144
+ } catch {
145
+ return null;
146
+ }
112
147
  }
113
148
 
114
149
  // The closed vocabulary of capability tiers a repository may declare for a
@@ -301,6 +336,13 @@ function standingAuthorizationUnknownMessage(unknown, problems = []) {
301
336
  // names are ... issue" beside "unrecognized action: issue" would contradict
302
337
  // itself. Name what is missing instead, and why this one name carries it.
303
338
  for (const problem of problems) {
339
+ if (problem.reason === "malformed-role") {
340
+ notes.push(
341
+ `\`${problem.entry}\` ends in a role pattern that is not chat-role characters — `
342
+ + "lowercase letters, digits, and hyphens — with `*` matching any run of them."
343
+ );
344
+ continue;
345
+ }
304
346
  if (problem.reason === "mixed-push") {
305
347
  notes.push(
306
348
  `\`push\` and ${problem.scoped.map((entry) => `\`${entry}\``).join(", ")} are `
@@ -365,7 +407,12 @@ function standingAuthorizationUnknownMessage(unknown, problems = []) {
365
407
  return notes.length === 0 ? base : `${base} ${notes.join(" ")}`;
366
408
  }
367
409
 
368
- function readStandingAuthorization(repo) {
410
+ function readStandingAuthorization(repo, options = {}) {
411
+ const role = Object.prototype.hasOwnProperty.call(options, "role") ? options.role : sessionChatRole(repo);
412
+ // Entries for other roles (#378 D2): read, checked, and left out of what
413
+ // this session is granted; `push-protected` prints its own role instead.
414
+ const otherRoles = [];
415
+ const entries = [];
369
416
  const declared = [];
370
417
  const unknown = [];
371
418
  const problems = [];
@@ -379,6 +426,11 @@ function readStandingAuthorization(repo) {
379
426
  for (const entry of configList(repo, "authorize")) {
380
427
  const classified = classifyAuthorizationEntry(entry);
381
428
  if (classified.ok) {
429
+ entries.push(classified);
430
+ if (classified.role && classified.action !== "push-protected" && !roleMatches(classified.role, role)) {
431
+ otherRoles.push(entry);
432
+ continue;
433
+ }
382
434
  declared.push(entry);
383
435
  if (!scopes.has(classified.action)) scopes.set(classified.action, classified.scope);
384
436
  if (classified.action === "chat-reply" && !chatReplyGroups.includes(classified.scope)) {
@@ -403,11 +455,12 @@ function readStandingAuthorization(repo) {
403
455
  protectedPushes.push(classified.scope);
404
456
  }
405
457
  }
406
- if ((pushGlobs.length || protectedPushes.length) && declared.includes("push")) {
458
+ const anyScopedPush = entries.some((e) => (e.action === "push" && e.scope !== null) || e.action === "push-protected");
459
+ if (anyScopedPush && declared.includes("push")) {
407
460
  unknown.push("push");
408
461
  problems.push({
409
462
  reason: "mixed-push", entry: "push", action: "push",
410
- scoped: [...pushGlobs.map((glob) => `push:${glob}`), ...protectedPushes.map((scope) => `push-protected:${scope}`)],
463
+ scoped: entries.filter((e) => (e.action === "push" && e.scope !== null) || e.action === "push-protected").map((e) => e.entry),
411
464
  });
412
465
  }
413
466
  if (unknown.length > 0) {
@@ -417,6 +470,9 @@ function readStandingAuthorization(repo) {
417
470
  chatReplyGroups: [],
418
471
  pushGlobs: [],
419
472
  protectedPushes: [],
473
+ otherRoles: [],
474
+ entries: [],
475
+ role,
420
476
  unknown,
421
477
  message: standingAuthorizationUnknownMessage(unknown, problems),
422
478
  };
@@ -424,7 +480,7 @@ function readStandingAuthorization(repo) {
424
480
  if (chatReplyGroups.length) scopes.set("chat-reply", chatReplyGroups.join(", "));
425
481
  if (pushGlobs.length) scopes.set("push", pushGlobs.join(", "));
426
482
  if (protectedPushes.length) scopes.set("push-protected", protectedPushes.join(", "));
427
- return { declared, scopes, chatReplyGroups, pushGlobs, protectedPushes, unknown, message: null };
483
+ return { declared, scopes, chatReplyGroups, pushGlobs, protectedPushes, otherRoles, entries, role, unknown, message: null };
428
484
  }
429
485
 
430
486
  // `full_mode_paths:` — the paths whose change always routes Full, whatever the
@@ -1018,6 +1074,7 @@ module.exports = {
1018
1074
  executorTierUnreadableMessage,
1019
1075
  readPrecedentStore,
1020
1076
  readStandingAuthorization,
1077
+ roleMatches,
1021
1078
  readTriagePolicy,
1022
1079
  triageIssue,
1023
1080
  };