@christang/keel 5.95.0 → 5.95.2

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.95.0 -->
1
+ <!-- keel:start version=5.95.2 -->
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.95.0",
3
+ "version": "5.95.2",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.95.0",
9
+ "version": "5.95.2",
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.95.0",
5
+ "version": "5.95.2",
6
6
  "license": "MIT",
7
7
  "repository": {
8
8
  "type": "git",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keel",
3
- "version": "5.95.0",
3
+ "version": "5.95.2",
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.95.0",
3
+ "version": "5.95.2",
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.95.0"
51
- PROTOCOL_VERSION = "5.95.0"
50
+ PACKAGE_VERSION = "5.95.2"
51
+ PROTOCOL_VERSION = "5.95.2"
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
@@ -3810,7 +3810,7 @@ def validate_chat_slack_format_scenario() -> int:
3810
3810
  chat_slack_config(rtl, {"soc": "CSOC"})
3811
3811
  benv = chat_bridge_environment(env, base / "home", slack)
3812
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"
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\n这是**重点**内容"
3814
3814
  record_id = chat_json(run_keel(rtl, "chat", "post", "soc", body, "--json", env=benv)).get("id", "")
3815
3815
  once = run_keel(rtl, "chat", "bridge", "run", "--once", env=benv)
3816
3816
  if once.returncode != 0:
@@ -3824,6 +3824,10 @@ def validate_chat_slack_format_scenario() -> int:
3824
3824
  if needle not in sent:
3825
3825
  report(f"{label} the posted text lacks {needle!r}: {sent!r}")
3826
3826
  return 1
3827
+ # Slack needs a boundary beside a marker, and CJK text is not one.
3828
+ if "这是\u200b*重点*\u200b内容" not in sent:
3829
+ report(f"{label} bold beside CJK text carries no zero-width boundary: {sent!r}")
3830
+ return 1
3827
3831
  if "**must**" in sent:
3828
3832
  report(f"{label} Markdown bold reached Slack untranslated: {sent!r}")
3829
3833
  return 1
@@ -4091,6 +4095,122 @@ def validate_chat_bridge_lifecycle_scenario() -> int:
4091
4095
  return 0
4092
4096
 
4093
4097
 
4098
+ def validate_chat_bridge_start_race_scenario() -> int:
4099
+ """Issue #226: start, stop, install, and status follow launchd's state.
4100
+
4101
+ A stateful launchctl double behaves like launchd after a bootout: the
4102
+ unload is still in progress, so the next bootstraps fail with `5:
4103
+ Input/output error`. `start` must retry until the service loads, fail
4104
+ naming launchctl's output when it never does, and `status` must not
4105
+ report a launchd-started bridge running from a stale status file.
4106
+ """
4107
+ label = "chat-bridge-start-race:"
4108
+ if chat_bridge_node_missing("chat-bridge-start-race"):
4109
+ return 3
4110
+ with tempfile.TemporaryDirectory(prefix="keel-chat-race-") as raw:
4111
+ base = Path(raw)
4112
+ rtl, _verify, env = chat_scratch_group(base)
4113
+ state = base / "launchd"
4114
+ state.mkdir()
4115
+ calls = base / "launchctl.log"
4116
+ launchctl = base / "launchctl"
4117
+ write_text(
4118
+ launchctl,
4119
+ "#!/bin/sh\n"
4120
+ f'S="{state}"\n'
4121
+ f'echo "$@" >> "{calls}"\n'
4122
+ 'case "$1" in\n'
4123
+ " bootout)\n"
4124
+ ' rm -f "$S/loaded"; echo 2 > "$S/fails"; exit 0 ;;\n'
4125
+ " bootstrap)\n"
4126
+ ' if [ -f "$S/forever" ]; then echo "Bootstrap failed: 5: Input/output error" >&2; exit 5; fi\n'
4127
+ ' n=$(cat "$S/fails" 2>/dev/null || echo 0)\n'
4128
+ ' if [ "$n" -gt 0 ]; then echo $((n - 1)) > "$S/fails"; echo "Bootstrap failed: 5: Input/output error" >&2; exit 5; fi\n'
4129
+ ' if [ -f "$S/loaded" ]; then echo "Bootstrap failed: 5: Input/output error" >&2; exit 5; fi\n'
4130
+ ' touch "$S/loaded"; exit 0 ;;\n'
4131
+ " print)\n"
4132
+ ' if [ -f "$S/loaded" ]; then printf "gui/501/dev.keel.chat-bridge = {\\n\\tstate = running\\n\\tpid = 4242\\n}\\n"; exit 0; fi\n'
4133
+ ' echo "Could not find service \\"dev.keel.chat-bridge\\" in domain for user gui: 501" >&2; exit 113 ;;\n'
4134
+ "esac\n"
4135
+ "exit 0\n",
4136
+ )
4137
+ launchctl.chmod(0o755)
4138
+ home = base / "home"
4139
+ lenv = {
4140
+ **env,
4141
+ "KEEL_HOME": str(home),
4142
+ "KEEL_CHAT_LAUNCHCTL": str(launchctl),
4143
+ "KEEL_CHAT_LAUNCH_AGENTS_DIR": str(base / "LaunchAgents"),
4144
+ "KEEL_CHAT_LAUNCHCTL_WAIT_MS": "8000",
4145
+ }
4146
+
4147
+ installed = run_keel(rtl, "chat", "bridge", "install", env=lenv)
4148
+ if installed.returncode != 0:
4149
+ report(f"{label} install failed although the unload finishes: {installed.stderr.strip()}")
4150
+ return 1
4151
+ if not (state / "loaded").exists():
4152
+ report(f"{label} install returned without the agent loaded: {calls.read_text(encoding='utf-8')!r}")
4153
+ return 1
4154
+ stopped = run_keel(rtl, "chat", "bridge", "stop", env=lenv)
4155
+ if stopped.returncode != 0 or (state / "loaded").exists():
4156
+ report(f"{label} stop did not unload the agent: {stopped.stderr.strip()}")
4157
+ return 1
4158
+ write_text(calls, "")
4159
+ started = run_keel(rtl, "chat", "bridge", "start", env=lenv)
4160
+ bootstraps = [line for line in calls.read_text(encoding="utf-8").splitlines() if line.startswith("bootstrap")]
4161
+ if started.returncode != 0:
4162
+ report(f"{label} start after stop failed instead of waiting for the unload: {started.stderr.strip()}")
4163
+ return 1
4164
+ if len(bootstraps) != 3:
4165
+ report(f"{label} start asked launchctl to bootstrap {len(bootstraps)} times, not 3: {bootstraps!r}")
4166
+ return 1
4167
+ if not (state / "loaded").exists():
4168
+ report(f"{label} start reported success with the agent not loaded.")
4169
+ return 1
4170
+
4171
+ run_keel(rtl, "chat", "bridge", "stop", env=lenv)
4172
+ (state / "forever").touch()
4173
+ failed = run_keel(rtl, "chat", "bridge", "start", env={**lenv, "KEEL_CHAT_LAUNCHCTL_WAIT_MS": "1500"})
4174
+ if failed.returncode == 0:
4175
+ report(f"{label} start reported success although every bootstrap failed: {failed.stdout.strip()}")
4176
+ return 1
4177
+ if "5: Input/output error" not in failed.stderr:
4178
+ report(f"{label} the failed start does not name launchctl's output: {failed.stderr.strip()}")
4179
+ return 1
4180
+ (state / "forever").unlink()
4181
+
4182
+ holder = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])
4183
+ try:
4184
+ status_file = home / "chat" / "bridge" / "status.json"
4185
+ status_file.parent.mkdir(parents=True, exist_ok=True)
4186
+ stale = {"pid": holder.pid, "connected": True, "projects": [], "launchd": True}
4187
+
4188
+ def running(record: dict) -> object:
4189
+ write_text(status_file, json.dumps(record))
4190
+ return chat_json(run_keel(rtl, "chat", "bridge", "status", "--json", env=lenv)).get("running")
4191
+
4192
+ if running(stale) is not False:
4193
+ report(f"{label} status reports a launchd bridge running while launchd has unloaded it.")
4194
+ return 1
4195
+ (state / "loaded").touch()
4196
+ if running(stale) is not False:
4197
+ report(f"{label} status reports running from a status file whose pid launchd does not run.")
4198
+ return 1
4199
+ manual = {key: value for key, value in stale.items() if key != "launchd"}
4200
+ if running(manual) is not True:
4201
+ report(f"{label} status no longer reports a bridge run by hand from its live pid.")
4202
+ return 1
4203
+ finally:
4204
+ holder.kill()
4205
+ holder.wait()
4206
+
4207
+ if "chat-bridge-start-race" not in {name for name, _ in SCENARIOS}:
4208
+ report(f"{label} scenario is not registered.")
4209
+ return 1
4210
+ report("chat-bridge-start-race scenario passed.")
4211
+ return 0
4212
+
4213
+
4094
4214
  def validate_chat_archive_scenario() -> int:
4095
4215
  """Issue #187: chat history is archived to an orphan branch, never exposed.
4096
4216
 
@@ -36245,6 +36365,10 @@ SCENARIOS: tuple = (
36245
36365
  "chat-bridge-lifecycle",
36246
36366
  validate_chat_bridge_lifecycle_scenario,
36247
36367
  ),
36368
+ (
36369
+ "chat-bridge-start-race",
36370
+ validate_chat_bridge_start_race_scenario,
36371
+ ),
36248
36372
  (
36249
36373
  "chat-role-apps",
36250
36374
  validate_chat_role_apps_scenario,
@@ -726,6 +726,8 @@ function machineName() {
726
726
  function writeStatus(ctx) {
727
727
  const status = {
728
728
  pid: process.pid,
729
+ // launchd names the agent it started in XPC_SERVICE_NAME (D4).
730
+ launchd: process.env.XPC_SERVICE_NAME === lifecycle.LABEL,
729
731
  machine: machineName(),
730
732
  connected: Boolean(ctx.connected),
731
733
  projects: ctx.projects.map((project) => project.where.worktree),
@@ -813,6 +815,12 @@ function readStatus() {
813
815
  } catch {
814
816
  running = false;
815
817
  }
818
+ // A status file a launchd-started bridge wrote is current only while
819
+ // launchd still runs that pid (D4); a bridge run by hand has only its pid.
820
+ if (running && status.launchd && lifecycle.installed()) {
821
+ const state = lifecycle.loadedState();
822
+ if (state && (!state.loaded || (state.pid && state.pid !== status.pid))) running = false;
823
+ }
816
824
  return { ...status, running, connected: running && Boolean(status.connected) };
817
825
  }
818
826
 
@@ -444,8 +444,7 @@ function runBridge(where, rest, options) {
444
444
  out(`Removed ${lifecycle.uninstall()}; the bridge no longer runs on this machine.`);
445
445
  return 0;
446
446
  case "start":
447
- lifecycle.start();
448
- out("Started the bridge.");
447
+ out(lifecycle.start() ? "Started the bridge." : "The bridge is already loaded; launchd keeps it running.");
449
448
  return 0;
450
449
  case "stop":
451
450
  lifecycle.stop();
@@ -165,6 +165,57 @@ function domain() {
165
165
  return `gui/${typeof process.getuid === "function" ? process.getuid() : 0}`;
166
166
  }
167
167
 
168
+ // launchd's view of the agent (bridge-start-race D1): loaded with its state
169
+ // and pid, unloaded, or null when launchctl gives no answer to read — a
170
+ // system without it, or a test double that prints nothing.
171
+ function loadedState() {
172
+ const result = launchctl(["print", `${domain()}/${LABEL}`]);
173
+ const state = result.output.match(/^\s*state = (\S+)/m);
174
+ if (result.ok && state) {
175
+ const pid = result.output.match(/^\s*pid = (\d+)/m);
176
+ return { loaded: true, state: state[1], pid: pid ? Number(pid[1]) : null };
177
+ }
178
+ if (!result.ok && /could not find service/i.test(result.output)) return { loaded: false };
179
+ return null;
180
+ }
181
+
182
+ function waitLimit() {
183
+ const ms = Number(process.env.KEEL_CHAT_LAUNCHCTL_WAIT_MS);
184
+ return Number.isFinite(ms) && ms >= 0 ? ms : 10000;
185
+ }
186
+
187
+ function sleep(ms) {
188
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
189
+ }
190
+
191
+ // `bootout` returns before launchd has removed the service (F1); waits,
192
+ // bounded, until it reports the service gone or gives no answer.
193
+ function bootout() {
194
+ launchctl(["bootout", `${domain()}/${LABEL}`]);
195
+ const deadline = Date.now() + waitLimit();
196
+ for (;;) {
197
+ const state = loadedState();
198
+ if (!state || !state.loaded || Date.now() >= deadline) return;
199
+ sleep(250);
200
+ }
201
+ }
202
+
203
+ // Loads the agent, retrying while a previous unload is still in progress
204
+ // (D2); any other failure, or one that outlasts the wait, is reported with
205
+ // launchctl's own words.
206
+ function bootstrap(what) {
207
+ const deadline = Date.now() + waitLimit();
208
+ for (;;) {
209
+ const loaded = launchctl(["bootstrap", domain(), plistPath()]);
210
+ if (loaded.ok) return;
211
+ const busy = /already|in progress|5:/i.test(loaded.output);
212
+ if (!busy || Date.now() >= deadline) {
213
+ throw new ChatError(`launchctl could not ${what}: ${loaded.output}`);
214
+ }
215
+ sleep(500);
216
+ }
217
+ }
218
+
168
219
  function install() {
169
220
  if (process.platform !== "darwin" && !process.env.KEEL_CHAT_LAUNCHCTL) {
170
221
  throw new ChatError("keel chat bridge install sets up a macOS LaunchAgent; on this system run `keel chat bridge run` under your own service manager.");
@@ -172,14 +223,13 @@ function install() {
172
223
  fs.mkdirSync(agentsDir(), { recursive: true });
173
224
  fs.mkdirSync(bridgeDir(), { recursive: true });
174
225
  fs.writeFileSync(plistPath(), plistText());
175
- launchctl(["bootout", `${domain()}/${LABEL}`]);
176
- const loaded = launchctl(["bootstrap", domain(), plistPath()]);
177
- if (!loaded.ok) throw new ChatError(`launchctl could not load ${plistPath()}: ${loaded.output}`);
226
+ bootout();
227
+ bootstrap(`load ${plistPath()}`);
178
228
  return plistPath();
179
229
  }
180
230
 
181
231
  function uninstall() {
182
- launchctl(["bootout", `${domain()}/${LABEL}`]);
232
+ bootout();
183
233
  try {
184
234
  fs.rmSync(plistPath());
185
235
  } catch {
@@ -188,19 +238,21 @@ function uninstall() {
188
238
  return plistPath();
189
239
  }
190
240
 
241
+ // Returns false when launchd already has the agent loaded, and so keeps it
242
+ // running, and nothing was done.
191
243
  function start() {
192
244
  if (!installed()) throw new ChatError("The bridge is not installed: run `keel chat bridge install` first.");
193
245
  resume();
194
- const loaded = launchctl(["bootstrap", domain(), plistPath()]);
195
- if (!loaded.ok && !/already|in progress|5:/i.test(loaded.output)) {
196
- throw new ChatError(`launchctl could not start the bridge: ${loaded.output}`);
197
- }
246
+ const state = loadedState();
247
+ if (state && state.loaded) return false;
248
+ bootstrap("start the bridge");
249
+ return true;
198
250
  }
199
251
 
200
252
  // Unloads the agent: it stays stopped until `start`, or until the next login
201
253
  // loads it again.
202
254
  function stop() {
203
- launchctl(["bootout", `${domain()}/${LABEL}`]);
255
+ bootout();
204
256
  }
205
257
 
206
258
  module.exports = {
@@ -210,6 +262,7 @@ module.exports = {
210
262
  bridgeDir,
211
263
  install,
212
264
  installed,
265
+ loadedState,
213
266
  missingTokens,
214
267
  pause,
215
268
  pausedUntil,
@@ -11,6 +11,11 @@ const FENCE = /```[\s\S]*?```/g;
11
11
  const SPAN = /`[^`\n]*`/g;
12
12
  // A placeholder for a bold marker, so a later italic pass cannot read it.
13
13
  const BOLD = "\u0001";
14
+ // Slack renders `*x*` only between word boundaries, and CJK text or
15
+ // full-width punctuation right beside a marker is not one: a zero-width space
16
+ // on each side of every marker pair supplies the boundary, checked against
17
+ // real Slack on 2026-10-05 (#187). Inbound text drops them again.
18
+ const ZWSP = "\u200b";
14
19
 
15
20
  // Calls `prose` on the text outside code and `code` on the code itself.
16
21
  function byCode(text, prose, code) {
@@ -47,13 +52,13 @@ function proseToSlack(text) {
47
52
  .replace(/^#{1,6}[ \t]+(.+?)[ \t]*#*[ \t]*$/gm, `${BOLD}$1${BOLD}`)
48
53
  .replace(/\*\*(?!\s)([^\n]+?)\*\*/g, `${BOLD}$1${BOLD}`)
49
54
  .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("*");
55
+ .replace(/(^|[^\w*])\*(?![\s*])([^*\n]+?)\*(?![\w*])/g, `$1${ZWSP}_$2_${ZWSP}`)
56
+ .replace(/~~(?!\s)([^\n]+?)~~/g, `${ZWSP}~$1~${ZWSP}`)
57
+ .replace(new RegExp(`${BOLD}([^${BOLD}]+)${BOLD}`, "g"), `${ZWSP}*$1*${ZWSP}`);
53
58
  }
54
59
 
55
60
  function proseFromSlack(text) {
56
- return unescape(text
61
+ return unescape(text.split(ZWSP).join("")
57
62
  .replace(/<((?:https?:\/\/|mailto:)[^|>\s]+)\|([^>]+)>/g, "[$2]($1)")
58
63
  .replace(/<((?:https?:\/\/|mailto:)[^|>\s]+)>/g, "$1")
59
64
  .replace(/(^|[^\w*])\*(?![\s*])([^*\n]+?)\*(?![\w*])/g, `$1${BOLD}${BOLD}$2${BOLD}${BOLD}`)