@christang/keel 5.115.0 → 5.116.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
@@ -770,7 +770,7 @@ Without a known default branch, no issue range is inferred.
770
770
 
771
771
  ## Group chat between sessions
772
772
 
773
- 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 member added with `keel chat group add <group> <role> --listen` is listen-only there: it receives the group — a Slack-bridged one included, so a review session reads your own wording rather than a coordinator's paraphrase — is woken when addressed, and may acknowledge and close its todos, but cannot post in that group or change it (#248). 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.
773
+ 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 member added with `keel chat group add <group> <role> --listen` is listen-only there: it receives the group — a Slack-bridged one included, so a review session reads your own wording rather than a coordinator's paraphrase — is woken when addressed, and may acknowledge and close its todos, but cannot post in that group or change it (#248). 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. Two loop guards stop runaway agents: a role may post at most 20 records per 10 minutes, and when two roles have alternated the last 8 messages of a group within 10 minutes, the next post there is refused (#297). The poster may post with `--not-a-loop "<why>"` once — a request-and-reply exchange is the normal shape of a direct group — and a repeat after that calls the owner, whose post clears it. `limits` in `keel/chat.json` sets `rate`, `window_minutes`, `pingpong`, and `pingpong_minutes`. A time in a message should come from Keel's clock, not an estimate: `keel chat post` and `keel chat dm` take `--stamp`, which prefixes `[MM-DD HH:MM]` (#298). 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.
774
774
 
775
775
  ## Coordinator patrol
776
776
 
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.115.0 -->
1
+ <!-- keel:start version=5.116.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.115.0",
3
+ "version": "5.116.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.115.0",
9
+ "version": "5.116.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.115.0",
5
+ "version": "5.116.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.115.0",
3
+ "version": "5.116.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.115.0",
3
+ "version": "5.116.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.115.0"
51
- PROTOCOL_VERSION = "5.115.0"
50
+ PACKAGE_VERSION = "5.116.0"
51
+ PROTOCOL_VERSION = "5.116.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
@@ -2583,6 +2583,45 @@ def chat_logs_snapshot(repo: Path) -> dict:
2583
2583
  return {str(p): p.read_bytes() for p in groups.rglob("*") if p.is_file()}
2584
2584
 
2585
2585
 
2586
+ def validate_chat_stamp_help_scenario() -> int:
2587
+ """Issue #298: `--stamp` writes Keel's time; `keel chat --help` is not an error."""
2588
+ label = "chat-stamp-help:"
2589
+ with tempfile.TemporaryDirectory(prefix="keel-chat-stamp-") as raw:
2590
+ base = Path(raw)
2591
+ rtl, _verify, env = chat_scratch_group(base)
2592
+
2593
+ def stamped(group: str, *args: str) -> str | None:
2594
+ posted = run_keel(rtl, "chat", *args, env=env)
2595
+ if posted.returncode != 0:
2596
+ return f"{' '.join(args)} failed: {posted.stderr.strip()}"
2597
+ record = sorted(chat_log(rtl, group).glob("*.md"))[-1].read_text(encoding="utf-8")
2598
+ created = re.search(r"^created: \d{4}-(\d{2})-(\d{2})T(\d{2}):(\d{2})", record, re.M)
2599
+ if not created:
2600
+ return f"the record has no created time:\n{record}"
2601
+ month, day, hour, minute = created.groups()
2602
+ want = f"[{month}-{day} {hour}:{minute}] "
2603
+ body = record.split("\n---\n", 1)[1].strip()
2604
+ if not body.startswith(want):
2605
+ return f"{' '.join(args)} stored {body!r}, not text starting with {want!r}"
2606
+ return None
2607
+
2608
+ for group, args in (("soc", ("post", "soc", "--stamp", "R008 done")), ("dm-rtl--verify", ("dm", "verify", "--stamp", "x"))):
2609
+ problem = stamped(group, *args)
2610
+ if problem:
2611
+ report(f"{label} {problem}")
2612
+ return 1
2613
+ for flag in ("--help", "-h"):
2614
+ helped = run_keel(rtl, "chat", flag, env=env)
2615
+ if helped.returncode != 0:
2616
+ report(f"{label} keel chat {flag} exited {helped.returncode}: {helped.stderr.strip()}")
2617
+ return 1
2618
+ if "Usage:" not in helped.stdout:
2619
+ report(f"{label} keel chat {flag} printed no usage: {helped.stdout!r}")
2620
+ return 1
2621
+ report("chat-stamp-help scenario passed.")
2622
+ return 0
2623
+
2624
+
2586
2625
  def validate_patrol_rearm_scenario() -> int:
2587
2626
  """Issue #260: the patrolling role is reminded to re-arm its schedule.
2588
2627
 
@@ -3506,27 +3545,64 @@ def validate_chat_loop_guards_scenario() -> int:
3506
3545
  extra = {"KEEL_CHAT_ROLE": role} if role else {}
3507
3546
  return run_keel(cwd, "chat", *args, env={**env, **extra})
3508
3547
 
3509
- for index in range(8):
3510
- cwd = rtl if index % 2 == 0 else verify
3511
- turn = chat(cwd, "post", "soc", f"round {index}")
3512
- if turn.returncode != 0:
3513
- report(f"{label} alternating post {index} was refused before the threshold: {turn.stderr.strip()}")
3514
- return 1
3548
+ # Enough rate for the ping-pong rounds below; the rate limit is checked with lint.
3549
+ for tree in (rtl, verify):
3550
+ write_text(tree / "keel" / "chat.json", json.dumps({"limits": {"rate": 100}}) + "\n")
3551
+
3552
+ def alternate(group: str, start: int, poster=None) -> str | None:
3553
+ post = poster or (lambda cwd, text: chat(cwd, "post", group, text))
3554
+ for index in range(start, start + 8):
3555
+ cwd = rtl if index % 2 == 0 else verify
3556
+ turn = post(cwd, f"round {index}")
3557
+ if turn.returncode != 0:
3558
+ return f"alternating post {index} in {group} was refused before the threshold: {turn.stderr.strip()}"
3559
+ return None
3560
+
3561
+ def systems(group: str) -> list[str]:
3562
+ return [p.read_text(encoding="utf-8") for p in chat_log(rtl, group).glob("*.md") if "kind: system" in p.read_text(encoding="utf-8")]
3563
+
3564
+ problem = alternate("soc", 0)
3565
+ if problem:
3566
+ report(f"{label} {problem}")
3567
+ return 1
3515
3568
  ninth = chat(rtl, "post", "soc", "round 8")
3516
3569
  if ninth.returncode == 0:
3517
- report(f"{label} a ninth alternating post was accepted.")
3570
+ report(f"{label} a ninth quick alternating post was accepted.")
3518
3571
  return 1
3519
3572
  if "loop guard" not in ninth.stderr:
3520
3573
  report(f"{label} the ping-pong refusal does not name the loop guard: {ninth.stderr.strip()}")
3521
3574
  return 1
3522
- chat(verify, "post", "soc", "round 8 again")
3523
- records = [p.read_text(encoding="utf-8") for p in chat_log(rtl, "soc").glob("*.md")]
3524
- system = [r for r in records if "kind: system" in r]
3525
- if len(system) != 1:
3526
- report(f"{label} expected one system record after two refused posts, found {len(system)}.")
3575
+ if "--not-a-loop" not in ninth.stderr:
3576
+ report(f"{label} the first refusal does not name --not-a-loop: {ninth.stderr.strip()}")
3577
+ return 1
3578
+ if systems("soc"):
3579
+ report(f"{label} the first trip already called the owner.")
3527
3580
  return 1
3528
- if " - owner" not in system[0]:
3529
- report(f"{label} the system record does not mention owner:\n{system[0]}")
3581
+ overridden = chat(rtl, "post", "soc", "--not-a-loop", "new assignment", "R009 next")
3582
+ if overridden.returncode != 0:
3583
+ report(f"{label} a --not-a-loop post was refused: {overridden.stderr.strip()}")
3584
+ return 1
3585
+ if not chat_records_with(rtl, "soc", "not_a_loop: new assignment"):
3586
+ report(f"{label} the override's reason is not recorded on the post.")
3587
+ return 1
3588
+ problem = alternate("soc", 9)
3589
+ if problem:
3590
+ report(f"{label} after the override, {problem}")
3591
+ return 1
3592
+ again = chat(rtl, "post", "soc", "round 17")
3593
+ if again.returncode == 0:
3594
+ report(f"{label} a quick alternating post after the override run was accepted.")
3595
+ return 1
3596
+ chat(verify, "post", "soc", "round 17 again")
3597
+ if len(systems("soc")) != 1:
3598
+ report(f"{label} expected one system record after the repeat trip, found {len(systems('soc'))}.")
3599
+ return 1
3600
+ if " - owner" not in systems("soc")[0]:
3601
+ report(f"{label} the system record does not mention owner:\n{systems('soc')[0]}")
3602
+ return 1
3603
+ refused_override = chat(rtl, "post", "soc", "--not-a-loop", "really", "x")
3604
+ if refused_override.returncode == 0:
3605
+ report(f"{label} an override was accepted after the owner was called.")
3530
3606
  return 1
3531
3607
  owner = chat(rtl, "post", "soc", "Stop and summarize, please.", role="owner")
3532
3608
  if owner.returncode != 0:
@@ -3537,6 +3613,36 @@ def validate_chat_loop_guards_scenario() -> int:
3537
3613
  report(f"{label} rtl could not post after the owner did: {resumed.stderr.strip()}")
3538
3614
  return 1
3539
3615
 
3616
+ direct = lambda cwd, text: chat(cwd, "dm", "verify" if cwd == rtl else "rtl", text)
3617
+ for step in (lambda: alternate("dm-rtl--verify", 0, direct),
3618
+ lambda: None if chat(rtl, "dm", "verify", "--not-a-loop", "work", "x").returncode == 0 else "the direct override was refused",
3619
+ lambda: alternate("dm-rtl--verify", 1, direct)):
3620
+ problem = step()
3621
+ if problem:
3622
+ report(f"{label} in the direct group, {problem}")
3623
+ return 1
3624
+ escalated = chat(verify, "dm", "rtl", "one more")
3625
+ if escalated.returncode == 0:
3626
+ report(f"{label} the repeat trip in the direct group was accepted.")
3627
+ return 1
3628
+ if "another member" in escalated.stderr:
3629
+ report(f"{label} the direct group's refusal names another member: {escalated.stderr.strip()}")
3630
+ return 1
3631
+
3632
+ run_keel(rtl, "chat", "group", "create", "slow", "--member", "verify", env=env)
3633
+ problem = alternate("slow", 0)
3634
+ if problem:
3635
+ report(f"{label} {problem}")
3636
+ return 1
3637
+ hours_ago = (datetime.now().astimezone() - timedelta(hours=3)).isoformat(timespec="seconds")
3638
+ for record in chat_log(rtl, "slow").glob("*.md"):
3639
+ text = record.read_text(encoding="utf-8")
3640
+ record.write_text(re.sub(r"^created: .*$", f"created: {hours_ago}", text, count=1, flags=re.M), encoding="utf-8")
3641
+ slow = chat(rtl, "post", "slow", "a new piece of work, hours later")
3642
+ if slow.returncode != 0:
3643
+ report(f"{label} a post after a slow exchange was refused: {slow.stderr.strip()}")
3644
+ return 1
3645
+
3540
3646
  write_text(lint / "keel" / "chat.json", json.dumps({"limits": {"rate": 3, "window_minutes": 10}}) + "\n")
3541
3647
  for index in range(3):
3542
3648
  within = chat(lint, "post", "soc", f"lint note {index}")
@@ -39141,6 +39247,10 @@ SCENARIOS: tuple = (
39141
39247
  "chat-loop-guards",
39142
39248
  validate_chat_loop_guards_scenario,
39143
39249
  ),
39250
+ (
39251
+ "chat-stamp-help",
39252
+ validate_chat_stamp_help_scenario,
39253
+ ),
39144
39254
  (
39145
39255
  "chat-human-view",
39146
39256
  validate_chat_human_view_scenario,
@@ -20,13 +20,13 @@ const USAGE = [
20
20
  "keel chat group add|remove <group> <role> [--listen] (--listen: receives the group, may ack and close its todos, does not post)",
21
21
  "keel chat group archive <group>",
22
22
  "keel chat group list [--all] [--json] (also: keel chat list)",
23
- "keel chat post <group> <text...> [--reply-to <id>] [--supersedes <id>] [--ack] [--json] (also: keel chat <group> <text...>)",
23
+ "keel chat post <group> <text...> [--reply-to <id>] [--supersedes <id>] [--ack] [--stamp] [--not-a-loop <why>] [--json] (also: keel chat <group> <text...>)",
24
24
  "keel chat ack <id> acknowledge a record that asks (a reply also counts)",
25
25
  "keel chat acks [--mine] [--json] records still waiting on an acknowledgement",
26
26
  "keel chat summary --since <90s|15m|2h|3d|date> [--group <group>] [--json] (what changed, per group and sender; reads without marking read)",
27
27
  "keel chat wait <group> --commit <sha> [--remote <name>] [note...] (or --issue <n> --closed: what this role waits for; keel patrol tells it when it holds)",
28
28
  "keel chat waits [--json] waits not yet met",
29
- "keel chat dm <role> <text...> [--json]",
29
+ "keel chat dm <role> <text...> [--stamp] [--not-a-loop <why>] [--json]",
30
30
  "keel chat <group> [--since <90s|15m|2h|3d|date>] [--follow] [--peek] [--json] (view; advances your read position unless --peek)",
31
31
  "keel chat unread [--json]",
32
32
  "keel chat read [<group>] [--json]",
@@ -59,6 +59,7 @@ const VALUED = {
59
59
  "--alias": "alias",
60
60
  "--reply-to": "replyTo",
61
61
  "--supersedes": "supersedes",
62
+ "--not-a-loop": "notALoop",
62
63
  "--repo": "repo",
63
64
  "--assignee": "assignee",
64
65
  "--issue": "issue",
@@ -73,10 +74,10 @@ const VALUED = {
73
74
  "--compact-at": "compactAt",
74
75
  };
75
76
  const REPEATED = { "--member": "members" };
76
- const SWITCHES = { "--json": "json", "--peek": "peek", "--all": "all", "--mine": "mine", "--follow": "follow", "--once": "once", "--mail": "mail", "--check": "check", "--ack": "ack", "--listen": "listen", "--closed": "closed" };
77
+ const SWITCHES = { "--json": "json", "--peek": "peek", "--all": "all", "--mine": "mine", "--follow": "follow", "--once": "once", "--mail": "mail", "--check": "check", "--ack": "ack", "--listen": "listen", "--closed": "closed", "--stamp": "stamp", "--help": "help", "-h": "help" };
77
78
 
78
79
  function parseChatArgs(argv) {
79
- const options = { positionals: [], members: [], json: false, peek: false, all: false, mine: false, follow: false, once: false, mail: false, check: false, ack: false, listen: false, closed: false };
80
+ const options = { positionals: [], members: [], json: false, peek: false, all: false, mine: false, follow: false, once: false, mail: false, check: false, ack: false, listen: false, closed: false, stamp: false, help: false };
80
81
  for (const key of Object.values(VALUED)) options[key] = null;
81
82
  for (let index = 0; index < argv.length; index += 1) {
82
83
  const arg = argv[index];
@@ -114,6 +115,13 @@ function parseChatArgs(argv) {
114
115
  return options;
115
116
  }
116
117
 
118
+ // `--stamp` (#298 D3): the time comes from Keel's clock, never the author's estimate.
119
+ function stamped(text, options) {
120
+ if (!options.stamp || !String(text || "").trim()) return text;
121
+ const now = store.isoLocal(new Date());
122
+ return `[${now.slice(5, 10)} ${now.slice(11, 16)}] ${text}`;
123
+ }
124
+
117
125
  function out(text) {
118
126
  process.stdout.write(text.endsWith("\n") ? text : `${text}\n`);
119
127
  }
@@ -296,7 +304,7 @@ function dispatch(where, options) {
296
304
  case "post": {
297
305
  const [group, ...words] = rest;
298
306
  if (!group) throw new ChatError("keel chat post needs a group.");
299
- postResult(where, store.post(where, { group, text: textFrom(words), replyTo: options.replyTo, supersedes: options.supersedes, ack: options.ack }), options.json);
307
+ postResult(where, store.post(where, { group, text: stamped(textFrom(words), options), replyTo: options.replyTo, supersedes: options.supersedes, ack: options.ack, notALoop: options.notALoop }), options.json);
300
308
  return 0;
301
309
  }
302
310
  case "ack": {
@@ -345,7 +353,7 @@ function dispatch(where, options) {
345
353
  case "dm": {
346
354
  const [target, ...words] = rest;
347
355
  if (!target) throw new ChatError("keel chat dm needs a role.");
348
- postResult(where, store.directPost(where, target, textFrom(words)), options.json);
356
+ postResult(where, store.directPost(where, target, stamped(textFrom(words), options), { notALoop: options.notALoop }), options.json);
349
357
  return 0;
350
358
  }
351
359
  case "unread": {
@@ -602,7 +610,7 @@ function runChat(argv) {
602
610
  try {
603
611
  const options = parseChatArgs(argv);
604
612
  const cwd = path.resolve(options.repo || process.cwd());
605
- if (!options.positionals.length || options.positionals[0] === "help") {
613
+ if (!options.positionals.length || options.positionals[0] === "help" || options.help) {
606
614
  out(`Usage:\n ${USAGE.join("\n ")}`);
607
615
  return 0;
608
616
  }
@@ -8,15 +8,20 @@
8
8
  // records per `limits.window_minutes` across the project
9
9
  // (default 20 per 10).
10
10
  // ping-pong when the last `limits.pingpong` messages of a group (default 8)
11
- // alternate between the same two roles other than `owner`, the
12
- // next post there by either is refused, and Keel calls the owner
13
- // with one `system` record. Any other member's post clears it.
11
+ // since its latest override alternate between the same two
12
+ // roles other than `owner`, and the first of them is within
13
+ // `limits.pingpong_minutes` (default 10), the next post there by
14
+ // either is refused (#297 D1). A first refusal only names
15
+ // `--not-a-loop "<why>"`, which lets the poster through once;
16
+ // a repeat after an override calls the owner with one `system`
17
+ // record (D2). The owner's post clears it, or in a group of more
18
+ // than two, any other member's.
14
19
  //
15
20
  // Both refuse by name, so an agent reading its error knows what stopped it.
16
21
 
17
22
  const { loadChatConfig } = require("./config");
18
23
 
19
- const DEFAULTS = { rate: 20, window_minutes: 10, pingpong: 8 };
24
+ const DEFAULTS = { rate: 20, window_minutes: 10, pingpong: 8, pingpong_minutes: 10 };
20
25
  const SYSTEM_SENDER = "keel";
21
26
 
22
27
  function positiveInteger(value, fallback) {
@@ -30,13 +35,19 @@ function limitsFor(where) {
30
35
  rate: positiveInteger(limits.rate, DEFAULTS.rate),
31
36
  window_minutes: positiveInteger(limits.window_minutes, DEFAULTS.window_minutes),
32
37
  pingpong: positiveInteger(limits.pingpong, DEFAULTS.pingpong),
38
+ pingpong_minutes: positiveInteger(limits.pingpong_minutes, DEFAULTS.pingpong_minutes),
33
39
  };
34
40
  }
35
41
 
36
- // The two roles a group's recent messages alternate between, or null.
37
- function pingPongPair(records, length) {
38
- const messages = records.filter((record) => record.kind === "message").slice(-length);
42
+ // The two roles a group's recent messages alternate between, or null: only
43
+ // messages after the latest override count, and only a run whose first
44
+ // message is within `minutes` of now (#297 D1).
45
+ function pingPongPair(records, length, minutes) {
46
+ const override = records.map((record) => Boolean(record.not_a_loop)).lastIndexOf(true);
47
+ const messages = records.slice(override + 1).filter((record) => record.kind === "message").slice(-length);
39
48
  if (messages.length < length) return null;
49
+ const first = Date.parse(messages[0].created || "");
50
+ if (Number.isNaN(first) || Date.now() - first > minutes * 60 * 1000) return null;
40
51
  const pair = [messages[0].from, messages[1].from];
41
52
  if (pair[0] === pair[1] || pair.includes("owner")) return null;
42
53
  for (let index = 0; index < messages.length; index += 1) {
@@ -57,12 +68,34 @@ function postedSince(store, where, role, since) {
57
68
  return count;
58
69
  }
59
70
 
60
- // Throws the store's error when `role` may not post to `group` now.
61
- function checkPost(store, where, role, group, records) {
62
- if (role === "owner") return;
71
+ // Escalated once the group's latest override or call to the owner has not
72
+ // been followed by an owner message (#297 D2).
73
+ function escalated(records) {
74
+ for (let index = records.length - 1; index >= 0; index -= 1) {
75
+ const record = records[index];
76
+ if (record.from === "owner" && record.kind === "message") return false;
77
+ if (record.not_a_loop || (record.kind === "system" && record.from === SYSTEM_SENDER)) return true;
78
+ }
79
+ return false;
80
+ }
81
+
82
+ // Throws the store's error when `role` may not post to `group` now. Returns
83
+ // whether `notALoop` let the post through, so the caller records the reason.
84
+ function checkPost(store, where, role, group, records, notALoop = null) {
85
+ if (role === "owner") return { overridden: false };
63
86
  const limits = limitsFor(where);
64
- const pair = pingPongPair(records, limits.pingpong);
65
- if (pair && pair.includes(role)) {
87
+ const pair = pingPongPair(records, limits.pingpong, limits.pingpong_minutes);
88
+ let overridden = false;
89
+ if (pair && pair.includes(role) && !escalated(records)) {
90
+ if (!notALoop) {
91
+ throw new store.ChatError(
92
+ `The loop guard stopped this post: ${pair[0]} and ${pair[1]} have alternated the last ${limits.pingpong} `
93
+ + `messages in ${group} within ${limits.pingpong_minutes} minutes. If this is ordinary request and reply, `
94
+ + "post again with `--not-a-loop \"<why>\"`; if it trips again, the owner is called."
95
+ );
96
+ }
97
+ overridden = true;
98
+ } else if (pair && pair.includes(role)) {
66
99
  const last = records[records.length - 1];
67
100
  if (!(last && last.kind === "system" && last.from === SYSTEM_SENDER)) {
68
101
  store.writeRecord(where, {
@@ -74,9 +107,10 @@ function checkPost(store, where, role, group, records) {
74
107
  + "the loop guard holds their next posts here until someone else posts.",
75
108
  });
76
109
  }
110
+ const clears = store.isDirect(group) ? "a post by the owner clears it" : "a post by the owner or another member clears it";
77
111
  throw new store.ChatError(
78
112
  `The loop guard stopped this post: ${pair[0]} and ${pair[1]} have alternated the last ${limits.pingpong} `
79
- + `messages in ${group}. The owner has been called; any other member's post clears it.`
113
+ + `messages in ${group} again after an override. The owner has been called; ${clears}, and --not-a-loop no longer applies.`
80
114
  );
81
115
  }
82
116
  const since = Date.now() - limits.window_minutes * 60 * 1000;
@@ -87,6 +121,7 @@ function checkPost(store, where, role, group, records) {
87
121
  + `minutes, the limit set by limits.rate in keel/chat.json (default ${DEFAULTS.rate}).`
88
122
  );
89
123
  }
124
+ return { overridden };
90
125
  }
91
126
 
92
127
  module.exports = {
@@ -41,7 +41,7 @@ const READABLE_KINDS = new Set(["message", "todo", "system"]);
41
41
  const LIST_FIELDS = new Set(["mentions", "refs"]);
42
42
  const FIELD_ORDER = [
43
43
  "id", "group", "kind", "from", "created", "mentions", "reply_to", "supersedes", "ack",
44
- "assignee", "issue", "target", "access", "condition", "refs", "origin", "slack_channel", "slack_ts",
44
+ "assignee", "issue", "target", "access", "condition", "not_a_loop", "refs", "origin", "slack_channel", "slack_ts",
45
45
  ];
46
46
 
47
47
  // A group may not take a name `keel chat <group>` would read as a subcommand.
@@ -568,7 +568,7 @@ function post(where, options) {
568
568
  requireSpeaker(group, state, from);
569
569
  const mentions = resolveMentions(where, group, state, text);
570
570
  // Loaded here rather than at the top: the guards read the store's own API.
571
- require("./guards").checkPost(module.exports, where, from, group, records);
571
+ const guard = require("./guards").checkPost(module.exports, where, from, group, records, options.notALoop || null);
572
572
  if (options.replyTo) {
573
573
  const parent = findRecord(where, options.replyTo);
574
574
  if (!parent || parent.group !== group) {
@@ -597,6 +597,7 @@ function post(where, options) {
597
597
  assignee: options.assignee || null,
598
598
  issue: options.issue || null,
599
599
  refs: options.refs || [],
600
+ not_a_loop: guard.overridden ? String(options.notALoop) : null,
600
601
  text: text.replace(/\s+$/, ""),
601
602
  });
602
603
  // A reply that opens with `done` or ✅ closes the todo it answers (D6).
@@ -804,7 +805,7 @@ function directPost(where, target, text, extra = {}) {
804
805
  if (!groupState(readLog(where, group)).exists) {
805
806
  createGroup(where, from, group, [target], { direct: true });
806
807
  }
807
- return post(where, { group, text, replyTo: extra.replyTo || null, refs: extra.refs || [] });
808
+ return post(where, { group, text, replyTo: extra.replyTo || null, refs: extra.refs || [], notALoop: extra.notALoop || null });
808
809
  }
809
810
 
810
811
  // --- waits (#260) ---------------------------------------------------------------
@@ -1014,6 +1015,7 @@ module.exports = {
1014
1015
  directPost,
1015
1016
  findRecord,
1016
1017
  groupState,
1018
+ isDirect,
1017
1019
  isoLocal,
1018
1020
  listGroups,
1019
1021
  listGroupNames,