@christang/keel 5.94.0 → 5.95.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,4 +1,4 @@
1
- <!-- keel:start version=5.94.0 -->
1
+ <!-- keel:start version=5.95.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.94.0",
3
+ "version": "5.95.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.94.0",
9
+ "version": "5.95.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.94.0",
5
+ "version": "5.95.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.94.0",
3
+ "version": "5.95.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.94.0",
3
+ "version": "5.95.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.94.0"
51
- PROTOCOL_VERSION = "5.94.0"
50
+ PACKAGE_VERSION = "5.95.0"
51
+ PROTOCOL_VERSION = "5.95.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
@@ -2663,15 +2663,43 @@ def validate_chat_claude_hooks_scenario() -> int:
2663
2663
  if not script.is_file():
2664
2664
  report(f"{label} {script.relative_to(ROOT)} does not exist.")
2665
2665
  return 1
2666
+ late_watch: list[str] = []
2666
2667
  for cwd in (unbound, plain):
2667
2668
  for event, host_event in events:
2668
2669
  quiet = hook(cwd, event, host_event)
2669
2670
  if quiet.returncode != 0:
2670
2671
  report(f"{label} {event} exited {quiet.returncode} in {cwd.name}, which has no role.")
2671
2672
  return 1
2673
+ if cwd == unbound and event == "session-start":
2674
+ # A session may start before its worktree's role is bound;
2675
+ # it still watches the worktree's signal, and nothing else.
2676
+ output = chat_json(quiet).get("hookSpecificOutput", {})
2677
+ watched = output.get("watchPaths") or []
2678
+ if len(watched) != 1:
2679
+ report(f"{label} session-start in a worktree with no role does not watch exactly one path: {quiet.stdout.strip()!r}")
2680
+ return 1
2681
+ if "/signal/worktree/" not in watched[0]:
2682
+ report(f"{label} session-start in a worktree with no role watches something other than the worktree signal: {watched!r}")
2683
+ return 1
2684
+ if output.get("additionalContext"):
2685
+ report(f"{label} session-start in a worktree with no role printed notice text: {quiet.stdout.strip()!r}")
2686
+ return 1
2687
+ late_watch = watched
2688
+ continue
2672
2689
  if quiet.stdout.strip() or quiet.stderr.strip():
2673
2690
  report(f"{label} {event} wrote output in {cwd.name}, which has no role: {(quiet.stdout + quiet.stderr).strip()!r}")
2674
2691
  return 1
2692
+ chat(unbound, "role", "--set", "late")
2693
+ chat(unbound, "group", "create", "side", "--member", "poster")
2694
+ run_keel(unbound, "chat", "post", "side", "@late please look", env={**env, "KEEL_CHAT_ROLE": "poster"})
2695
+ late_signal = Path(late_watch[0])
2696
+ if not late_signal.exists() or not late_signal.stat().st_size:
2697
+ report(f"{label} a mention of a role bound after session start did not touch the worktree signal that session watches.")
2698
+ return 1
2699
+ late_wake = hook(unbound, "file-changed", "FileChanged")
2700
+ if late_wake.returncode != 2:
2701
+ report(f"{label} file-changed exited {late_wake.returncode} for a role bound after session start, not 2.")
2702
+ return 1
2675
2703
 
2676
2704
  signal = mailbox_common_dir(rtl) / "keel-chat" / "signal" / "verify"
2677
2705
 
@@ -2717,8 +2745,12 @@ def validate_chat_claude_hooks_scenario() -> int:
2717
2745
  if mention_id not in start_output.get("additionalContext", ""):
2718
2746
  report(f"{label} the session-start notice does not name the mention: {start.stdout.strip()} {start.stderr.strip()}")
2719
2747
  return 1
2720
- if start_output.get("watchPaths") != [str(signal)]:
2721
- report(f"{label} session-start watchPaths is {start_output.get('watchPaths')!r}, not [{str(signal)!r}].")
2748
+ watch = start_output.get("watchPaths") or []
2749
+ if watch[:1] != [str(signal)]:
2750
+ report(f"{label} session-start does not watch the role's signal first: {watch!r}, not starting with {str(signal)!r}.")
2751
+ return 1
2752
+ if [path for path in watch[1:] if "/signal/worktree/" in path] != watch[1:2] or len(watch) != 2:
2753
+ report(f"{label} session-start does not also watch exactly the worktree signal: {watch!r}.")
2722
2754
  return 1
2723
2755
 
2724
2756
  before_dm = signal_size()
@@ -3760,6 +3792,72 @@ def validate_chat_shared_bots_scenario() -> int:
3760
3792
  return 0
3761
3793
 
3762
3794
 
3795
+ def validate_chat_slack_format_scenario() -> int:
3796
+ """Issue #187: Markdown shows as formatting in Slack, and back.
3797
+
3798
+ A record's Markdown is posted as Slack mrkdwn — bold, italic, headings,
3799
+ bullets, links, escaped `&<>` — with code left alone and the local record
3800
+ unchanged; a person's mrkdwn arrives in the store as Markdown; and the
3801
+ setup guides tell sessions they may format with Markdown.
3802
+ """
3803
+ label = "chat-slack-format:"
3804
+ if chat_bridge_node_missing("chat-slack-format"):
3805
+ return 3
3806
+ FakeSlack = fake_slack_class()
3807
+ with tempfile.TemporaryDirectory(prefix="keel-chat-format-") as raw, FakeSlack() as slack:
3808
+ base = Path(raw)
3809
+ rtl, _verify, env = chat_scratch_group(base)
3810
+ chat_slack_config(rtl, {"soc": "CSOC"})
3811
+ benv = chat_bridge_environment(env, base / "home", slack)
3812
+ run_keel(rtl, "chat", "bridge", "add", env=benv)
3813
+ body = "# Plan\n**must** land *soon*\n- item\nsee [spec](https://example.com/s) and `a**b`\n```\n**raw**\n```\nx<y&z"
3814
+ record_id = chat_json(run_keel(rtl, "chat", "post", "soc", body, "--json", env=benv)).get("id", "")
3815
+ once = run_keel(rtl, "chat", "bridge", "run", "--once", env=benv)
3816
+ if once.returncode != 0:
3817
+ report(f"{label} bridge run --once failed: {once.stderr.strip()}")
3818
+ return 1
3819
+ sent = next((c["params"].get("text", "") for c in slack.calls_to("chat.postMessage") if slack_payload(c).get("id") == record_id), None)
3820
+ if sent is None:
3821
+ report(f"{label} the record was never posted.")
3822
+ return 1
3823
+ for needle in ("*Plan*", "*must*", "_soon_", "• item", "<https://example.com/s|spec>", "`a**b`", "```\n**raw**\n```", "x&lt;y&amp;z"):
3824
+ if needle not in sent:
3825
+ report(f"{label} the posted text lacks {needle!r}: {sent!r}")
3826
+ return 1
3827
+ if "**must**" in sent:
3828
+ report(f"{label} Markdown bold reached Slack untranslated: {sent!r}")
3829
+ return 1
3830
+ if body not in (chat_log(rtl, "soc") / f"{record_id}.md").read_text(encoding="utf-8"):
3831
+ report(f"{label} translation changed the local record.")
3832
+ return 1
3833
+
3834
+ bridge = start_chat_bridge(rtl, benv)
3835
+ try:
3836
+ if not slack.wait_for(lambda: slack.sockets, 10):
3837
+ report(f"{label} the bridge never connected: {stop_chat_bridge(bridge).strip()}")
3838
+ return 1
3839
+ slack.push(slack_event("CSOC", user="UOWNER", text="*urgent* _today_ ~old~ see <https://example.com|this> a &lt; b", ts="1800000001.000100"))
3840
+ if not slack.wait_for(lambda: chat_records_with(rtl, "soc", "today")):
3841
+ report(f"{label} the owner's formatted message was not imported.")
3842
+ return 1
3843
+ stored = chat_records_with(rtl, "soc", "today")[0]
3844
+ if "**urgent** *today* ~~old~~ see [this](https://example.com) a < b" not in stored:
3845
+ report(f"{label} the owner's mrkdwn was not stored as Markdown:\n{stored}")
3846
+ return 1
3847
+ finally:
3848
+ stop_chat_bridge(bridge)
3849
+
3850
+ for relative, needle in (("docs/chat-slack-setup.md", "format with ordinary Markdown"), ("docs/chat-slack-setup.zh-CN.md", "用普通的 Markdown")):
3851
+ if needle not in (ROOT / relative).read_text(encoding="utf-8"):
3852
+ report(f"{label} {relative} does not say {needle!r}.")
3853
+ return 1
3854
+ if "chat-slack-format" not in {name for name, _ in SCENARIOS}:
3855
+ report(f"{label} scenario is not registered.")
3856
+ return 1
3857
+ report("chat-slack-format scenario passed.")
3858
+ return 0
3859
+
3860
+
3763
3861
  def validate_chat_role_apps_are_documented_scenario() -> int:
3764
3862
  """Issue #187: the setup guides and READMEs describe shared bots.
3765
3863
 
@@ -36163,6 +36261,10 @@ SCENARIOS: tuple = (
36163
36261
  "chat-shared-bots",
36164
36262
  validate_chat_shared_bots_scenario,
36165
36263
  ),
36264
+ (
36265
+ "chat-slack-format",
36266
+ validate_chat_slack_format_scenario,
36267
+ ),
36166
36268
  (
36167
36269
  "chat-archive",
36168
36270
  validate_chat_archive_scenario,
@@ -20,6 +20,7 @@ const path = require("path");
20
20
  const store = require("./store");
21
21
  const { slackSettings } = require("./config");
22
22
  const { redact } = require("./redact");
23
+ const mrkdwn = require("./mrkdwn");
23
24
  const slack = require("./slack");
24
25
  const lifecycle = require("./lifecycle");
25
26
 
@@ -167,10 +168,11 @@ function bodyText(record) {
167
168
  }
168
169
  }
169
170
 
170
- // Redact, then cut, then address: the cut must not split a `[redacted]`, and
171
- // the owner mention must survive the cut.
171
+ // Redact, translate, cut, then address: the cut must not split a
172
+ // `[redacted]`, and neither the cut pointer nor the owner mention is Markdown
173
+ // to translate (chat-slack-format D1).
172
174
  function slackText(project, record, text) {
173
- let result = redact(text);
175
+ let result = mrkdwn.toSlack(redact(text));
174
176
  if (result.length > TEXT_LIMIT) {
175
177
  result = `${result.slice(0, TEXT_LIMIT)}… (cut; full text: \`keel chat show ${record.id}\`)`;
176
178
  }
@@ -395,7 +397,7 @@ function unwrapText(project, text, kind) {
395
397
  if (project.settings.owner) result = result.replace(new RegExp(`^<@${project.settings.owner}> `), "");
396
398
  result = result.replace(/^↳ reply to \S+\n/, "");
397
399
  if (kind === "todo") result = result.replace(/^☐ todo → [^:]*: /, "");
398
- return result;
400
+ return mrkdwn.fromSlack(result);
399
401
  }
400
402
 
401
403
  function importKeelRecord(ctx, project, channel, payload, message) {
@@ -473,6 +475,7 @@ function humanText(project, event) {
473
475
  const role = project.settings.members[user] || project.settings.bots[user];
474
476
  return role ? `@${role}` : match;
475
477
  });
478
+ text = mrkdwn.fromSlack(text);
476
479
  for (const file of event.files || []) {
477
480
  const link = file.permalink || file.url_private || "";
478
481
  text += `${text ? "\n" : ""}📎 ${file.name || file.title || "file"}${link ? `: ${link}` : ""}`;
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+
3
+ // Formatting between the store's Markdown and Slack's mrkdwn (issue #187,
4
+ // chat-slack-format D2, D3). Sessions write Markdown; Slack renders its own
5
+ // dialect, so the bridge translates on the way out and back on the way in.
6
+ // Code spans and fenced blocks are escaped but otherwise left alone in both
7
+ // directions. The round trip keeps meaning, not the exact markers: a heading
8
+ // comes back as a bold line and a bullet as a `•` line.
9
+
10
+ const FENCE = /```[\s\S]*?```/g;
11
+ const SPAN = /`[^`\n]*`/g;
12
+ // A placeholder for a bold marker, so a later italic pass cannot read it.
13
+ const BOLD = "\u0001";
14
+
15
+ // Calls `prose` on the text outside code and `code` on the code itself.
16
+ function byCode(text, prose, code) {
17
+ const outside = (part) => {
18
+ let result = "";
19
+ let last = 0;
20
+ for (const match of part.matchAll(SPAN)) {
21
+ result += prose(part.slice(last, match.index)) + code(match[0]);
22
+ last = match.index + match[0].length;
23
+ }
24
+ return result + prose(part.slice(last));
25
+ };
26
+ let result = "";
27
+ let last = 0;
28
+ for (const match of text.matchAll(FENCE)) {
29
+ result += outside(text.slice(last, match.index)) + code(match[0]);
30
+ last = match.index + match[0].length;
31
+ }
32
+ return result + outside(text.slice(last));
33
+ }
34
+
35
+ function escape(text) {
36
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
37
+ }
38
+
39
+ function unescape(text) {
40
+ return text.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
41
+ }
42
+
43
+ function proseToSlack(text) {
44
+ return escape(text)
45
+ .replace(/\[([^\]\n]+)\]\((https?:\/\/[^)\s]+|mailto:[^)\s]+)\)/g, (match, label, url) => `<${url}|${label}>`)
46
+ .replace(/^(\s*)[-*+][ \t]+/gm, "$1• ")
47
+ .replace(/^#{1,6}[ \t]+(.+?)[ \t]*#*[ \t]*$/gm, `${BOLD}$1${BOLD}`)
48
+ .replace(/\*\*(?!\s)([^\n]+?)\*\*/g, `${BOLD}$1${BOLD}`)
49
+ .replace(/__(?!\s)([^\n]+?)__/g, `${BOLD}$1${BOLD}`)
50
+ .replace(/(^|[^\w*])\*(?![\s*])([^*\n]+?)\*(?![\w*])/g, "$1_$2_")
51
+ .replace(/~~(?!\s)([^\n]+?)~~/g, "~$1~")
52
+ .split(BOLD).join("*");
53
+ }
54
+
55
+ function proseFromSlack(text) {
56
+ return unescape(text
57
+ .replace(/<((?:https?:\/\/|mailto:)[^|>\s]+)\|([^>]+)>/g, "[$2]($1)")
58
+ .replace(/<((?:https?:\/\/|mailto:)[^|>\s]+)>/g, "$1")
59
+ .replace(/(^|[^\w*])\*(?![\s*])([^*\n]+?)\*(?![\w*])/g, `$1${BOLD}${BOLD}$2${BOLD}${BOLD}`)
60
+ .replace(/(^|[^\w_])_(?![\s_])([^_\n]+?)_(?![\w_])/g, "$1*$2*")
61
+ .replace(/(^|[^\w~])~(?![\s~])([^~\n]+?)~(?![\w~])/g, "$1~~$2~~")
62
+ .split(BOLD).join("*"));
63
+ }
64
+
65
+ function toSlack(text) {
66
+ return byCode(String(text || ""), proseToSlack, escape);
67
+ }
68
+
69
+ function fromSlack(text) {
70
+ return byCode(String(text || ""), proseFromSlack, unescape);
71
+ }
72
+
73
+ module.exports = { fromSlack, toSlack };
@@ -114,6 +114,13 @@ function ensureSignal(where, role) {
114
114
  return signal;
115
115
  }
116
116
 
117
+ function ensureWorktreeSignal(where) {
118
+ const signal = store.worktreeSignalPath(where.root, where.worktree);
119
+ fs.mkdirSync(path.dirname(signal), { recursive: true });
120
+ if (!fs.existsSync(signal)) fs.writeFileSync(signal, "");
121
+ return signal;
122
+ }
123
+
117
124
  // For a Slack-enabled project, whether this machine's bridge is carrying the
118
125
  // chat, so a session does not assume the owner's phone can reach it (D18).
119
126
  function bridgeLine(where) {
@@ -161,6 +168,13 @@ function hook(event, input, { mail = false } = {}) {
161
168
  } catch {
162
169
  role = null;
163
170
  }
171
+ // A session's watch list is fixed at SessionStart, so a worktree with no role
172
+ // yet still watches its own signal, which a role bound later will touch
173
+ // (chat-wake-late-binding D1). Nothing else is said until there is a role.
174
+ if (where && !role && event === "session-start") {
175
+ const watched = ensureWorktreeSignal(where);
176
+ return { code: 0, stdout: `${JSON.stringify({ hookSpecificOutput: { hookEventName: "SessionStart", watchPaths: [watched] } })}\n` };
177
+ }
164
178
  if (!where || !role) return { code: 0 };
165
179
  if (event === "session-end") {
166
180
  touchPresence(where, role, "offline");
@@ -171,7 +185,7 @@ function hook(event, input, { mail = false } = {}) {
171
185
  const text = chatText && mail ? `${chatText}\n${MAIL_POINTER}` : chatText;
172
186
  if (event === "session-start") {
173
187
  const output = {
174
- hookSpecificOutput: { hookEventName: "SessionStart", watchPaths: [ensureSignal(where, role)] },
188
+ hookSpecificOutput: { hookEventName: "SessionStart", watchPaths: [ensureSignal(where, role), ensureWorktreeSignal(where)] },
175
189
  };
176
190
  const context = [bridgeLine(where), text].filter(Boolean).join("\n");
177
191
  if (context) output.hookSpecificOutput.additionalContext = context;
@@ -345,14 +345,31 @@ function writeRecord(where, fields, date = new Date()) {
345
345
  writeAtomic(where.root, target, renderRecord(record));
346
346
  refreshTranscript(where, record.group);
347
347
  // After the rename, so a host woken by the signal always finds the record.
348
- for (const role of signalTargets(record)) {
349
- const signal = path.join(where.root, "signal", role);
350
- fs.mkdirSync(path.dirname(signal), { recursive: true });
351
- fs.appendFileSync(signal, `${record.id}\n`);
348
+ // Each worktree bound to a woken role gets its own signal too, which a
349
+ // session watches from its start whether or not a role was bound yet
350
+ // (chat-wake-late-binding D2).
351
+ const targets = signalTargets(record);
352
+ const bound = targets.length ? readRoles(where.root) : {};
353
+ for (const role of targets) {
354
+ const signals = [path.join(where.root, "signal", role)];
355
+ for (const [worktree, name] of Object.entries(bound)) {
356
+ if (name === role) signals.push(worktreeSignalPath(where.root, worktree));
357
+ }
358
+ for (const signal of signals) {
359
+ fs.mkdirSync(path.dirname(signal), { recursive: true });
360
+ fs.appendFileSync(signal, `${record.id}\n`);
361
+ }
352
362
  }
353
363
  return record;
354
364
  }
355
365
 
366
+ // A worktree's own signal file: the first 16 hex digits of the SHA-256 of its
367
+ // path, so it names the worktree whatever role it later binds.
368
+ function worktreeSignalPath(root, worktree) {
369
+ const id = require("crypto").createHash("sha256").update(worktree).digest("hex").slice(0, 16);
370
+ return path.join(root, "signal", "worktree", id);
371
+ }
372
+
356
373
  // The transcript is derived and local (D1): regenerated whole after each
357
374
  // write, and never a source of anything. A failure to write it fails nothing.
358
375
  function refreshTranscript(where, group) {
@@ -737,6 +754,7 @@ function readGroups(where, role, group) {
737
754
 
738
755
  module.exports = {
739
756
  checkName,
757
+ worktreeSignalPath,
740
758
  ALL,
741
759
  ChatError,
742
760
  DATA_NOTICE,