@christang/keel 5.116.0 → 5.117.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
@@ -825,7 +825,10 @@ prints the task — id, a cron from `every:`, the model, and a self-contained pr
825
825
  `keel patrol --since-last --notify` against the coordinator's worktree by path. Keel creates
826
826
  nothing; the session's model installs it with the host's own scheduled-task tool, since a host keeps
827
827
  the schedule itself. With `host_task:` declared, the reminder asks only to confirm the task is still
828
- enabled.
828
+ enabled. Create the task from a session whose folder is bound to no role: a host task starts its runs
829
+ in the folder it was created from. A run that starts in a role's worktree anyway is recognized by its
830
+ first prompt (`<scheduled-task …`), and Keel then restores that role's presence and ignores the
831
+ session, so it neither marks the role offline nor fires a `keel shift ready --wake` (#300).
829
832
 
830
833
  ## Commands
831
834
 
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.116.0 -->
1
+ <!-- keel:start version=5.117.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.116.0",
3
+ "version": "5.117.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.116.0",
9
+ "version": "5.117.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.116.0",
5
+ "version": "5.117.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.116.0",
3
+ "version": "5.117.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.116.0",
3
+ "version": "5.117.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.116.0"
51
- PROTOCOL_VERSION = "5.116.0"
50
+ PACKAGE_VERSION = "5.117.0"
51
+ PROTOCOL_VERSION = "5.117.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
@@ -5845,7 +5845,7 @@ def validate_shift_self_wake_scenario() -> int:
5845
5845
  with tempfile.TemporaryDirectory(prefix="keel-shift-wake-") as raw:
5846
5846
  base = Path(raw)
5847
5847
  rtl, verify, env, _ = shift_scratch(base)
5848
- env = {**env, "KEEL_SHIFT_WAKE_POLL_MS": "100", "KEEL_SHIFT_WAKE_TIMEOUT_MS": "20000"}
5848
+ env = {**env, "KEEL_SHIFT_WAKE_POLL_MS": "100", "KEEL_SHIFT_WAKE_SETTLE_MS": "500", "KEEL_SHIFT_WAKE_TIMEOUT_MS": "20000"}
5849
5849
  loose = chat_worktree(rtl, base / "loose")
5850
5850
  subprocess.run(["git", "push", "-q", "-u", "origin", "HEAD"], cwd=loose, check=True, capture_output=True)
5851
5851
 
@@ -5898,6 +5898,77 @@ def validate_shift_self_wake_scenario() -> int:
5898
5898
  return 0
5899
5899
 
5900
5900
 
5901
+ def validate_host_run_session_scenario() -> int:
5902
+ """Issue #300: a scheduled run started in a role's worktree is not that role.
5903
+
5904
+ Its first prompt, starting `<scheduled-task`, restores the presence its
5905
+ SessionStart replaced; its hooks then write and inject nothing, its end
5906
+ changes nothing, and it never fires `ready --wake`. An ordinary clear
5907
+ still wakes the role once, after the wake settles.
5908
+ """
5909
+ label = "host-run-session:"
5910
+ with tempfile.TemporaryDirectory(prefix="keel-host-run-") as raw:
5911
+ base = Path(raw)
5912
+ rtl, verify, env, _ = shift_scratch(base)
5913
+ env = {**env, "KEEL_SHIFT_WAKE_POLL_MS": "100", "KEEL_SHIFT_WAKE_SETTLE_MS": "1500", "KEEL_SHIFT_WAKE_TIMEOUT_MS": "30000"}
5914
+ presence = mailbox_common_dir(rtl) / "keel-chat" / "presence" / "verify.json"
5915
+
5916
+ def hook(event: str, payload: dict) -> subprocess.CompletedProcess[str]:
5917
+ return subprocess.run(
5918
+ ["node", str(ROOT / "bin" / "keel.js"), "chat", "hook", event],
5919
+ cwd=verify, env=env, text=True, capture_output=True, check=False,
5920
+ input=json.dumps({"cwd": str(verify), **payload}),
5921
+ )
5922
+
5923
+ def wakes() -> list[str]:
5924
+ return chat_records_with(rtl, "dm-keel-shift--verify", "keel shift resume")
5925
+
5926
+ def current() -> str:
5927
+ return presence.read_text(encoding="utf-8") if presence.exists() else ""
5928
+
5929
+ hook("session-start", {"hook_event_name": "SessionStart", "source": "startup", "session_id": "s1"})
5930
+ hook("user-prompt-submit", {"hook_event_name": "UserPromptSubmit", "session_id": "s1", "prompt": "hello"})
5931
+ armed = run_keel(verify, "shift", "ready", "--wake", "verify note", env=env)
5932
+ if armed.returncode != 0:
5933
+ report(f"{label} ready --wake failed: {armed.stderr}")
5934
+ return 1
5935
+ run_keel(rtl, "chat", "post", "soc", "@verify something to read", env=env)
5936
+ before = current()
5937
+ hook("session-start", {"hook_event_name": "SessionStart", "source": "startup", "session_id": "run1"})
5938
+ prompted = hook("user-prompt-submit", {"hook_event_name": "UserPromptSubmit", "session_id": "run1",
5939
+ "prompt": '<scheduled-task name="patrol">\nrun the patrol'})
5940
+ if current() != before:
5941
+ report(f"{label} the host run's presence was not restored:\nbefore {before}\nafter {current()}")
5942
+ return 1
5943
+ if prompted.stdout.strip():
5944
+ report(f"{label} the host run's prompt hook injected output: {prompted.stdout!r}")
5945
+ return 1
5946
+ time.sleep(3)
5947
+ if wakes():
5948
+ report(f"{label} the host run's start fired the wake.")
5949
+ return 1
5950
+ hook("session-end", {"hook_event_name": "SessionEnd", "session_id": "run1"})
5951
+ if current() != before:
5952
+ report(f"{label} the host run's end changed presence:\nbefore {before}\nafter {current()}")
5953
+ return 1
5954
+ hook("session-start", {"hook_event_name": "SessionStart", "source": "clear", "session_id": "s2"})
5955
+ hook("user-prompt-submit", {"hook_event_name": "UserPromptSubmit", "session_id": "s2", "prompt": "carry on"})
5956
+ deadline = time.time() + 6
5957
+ while time.time() < deadline and not wakes():
5958
+ time.sleep(0.1)
5959
+ if len(wakes()) != 1:
5960
+ report(f"{label} expected one wake after the clear start, found {len(wakes())}.")
5961
+ return 1
5962
+ task_config = "patrol:\n role: verify\n every: 30m\n"
5963
+ write_text(verify / "keel" / "config.yaml", task_config)
5964
+ task = run_keel(verify, "patrol", "task", env=env)
5965
+ if "bound to no role" not in task.stdout:
5966
+ report(f"{label} keel patrol task does not say to create the task from a folder bound to no role: {task.stdout!r} {task.stderr!r}")
5967
+ return 1
5968
+ report("host-run-session scenario passed.")
5969
+ return 0
5970
+
5971
+
5901
5972
  def validate_shift_coordinator_last_scenario() -> int:
5902
5973
  """Issue #289: the coordinator starts the others before its own shift ends.
5903
5974
 
@@ -39577,6 +39648,7 @@ SCENARIOS: tuple = (
39577
39648
  ("shift-coordinator-last", validate_shift_coordinator_last_scenario),
39578
39649
  ("shift-self", validate_shift_self_scenario),
39579
39650
  ("shift-self-wake", validate_shift_self_wake_scenario),
39651
+ ("host-run-session", validate_host_run_session_scenario),
39580
39652
  ("shift-without-role", validate_shift_without_role_scenario),
39581
39653
  ("resource-lock", validate_resource_lock_scenario),
39582
39654
  ("chat-supersedes", validate_chat_supersedes_scenario),
@@ -170,6 +170,47 @@ const HOST_EVENTS = {
170
170
  // wake signal and must mean only "something addressed to you arrived".
171
171
  const MAIL_POINTER = "Direct messages can also be read with the 5.83 `keel mail read`.";
172
172
 
173
+ // --- host-run sessions (#300) ---------------------------------------------------------
174
+ //
175
+ // A host scheduled task starts its runs in the folder it was created from, so a
176
+ // run can start in a role's worktree. Its SessionStart fires before its prompt
177
+ // exists, so the hook keeps the presence it replaces per session id (D1), and
178
+ // the first prompt decides: one starting `<scheduled-task` marks the session a
179
+ // host run and restores that presence (D2); a host run then writes nothing (D3).
180
+
181
+ const HOST_RUN_MARKER = "<scheduled-task";
182
+
183
+ function sessionFile(where, payload) {
184
+ const id = typeof payload.session_id === "string" ? payload.session_id : "";
185
+ return /^[A-Za-z0-9._-]{1,128}$/.test(id) ? path.join(where.root, "sessions", `${id}.json`) : null;
186
+ }
187
+
188
+ function rememberSession(where, role, file) {
189
+ if (!file) return;
190
+ const previous = fs.existsSync(presenceFile(where, role)) ? store.readJsonFile(presenceFile(where, role)) : null;
191
+ try {
192
+ store.writeJsonAtomic(where, file, { role, previous, decided: false, host_run: false });
193
+ } catch {
194
+ // Like presence, a convenience: never fail the hook.
195
+ }
196
+ }
197
+
198
+ // Returns true when this prompt marked the session a host run.
199
+ function decideSession(where, file, session, prompt) {
200
+ const hostRun = String(prompt || "").trimStart().startsWith(HOST_RUN_MARKER);
201
+ try {
202
+ store.writeJsonAtomic(where, file, { ...session, decided: true, host_run: hostRun });
203
+ if (hostRun) {
204
+ const target = presenceFile(where, session.role);
205
+ if (session.previous) store.writeJsonAtomic(where, target, session.previous);
206
+ else fs.rmSync(target, { force: true });
207
+ }
208
+ } catch {
209
+ // Presence stays as the SessionStart left it.
210
+ }
211
+ return hostRun;
212
+ }
213
+
173
214
  function hook(event, input, { mail = false } = {}) {
174
215
  if (!(event in HOST_EVENTS)) return { code: 0 };
175
216
  let payload = {};
@@ -194,10 +235,18 @@ function hook(event, input, { mail = false } = {}) {
194
235
  return { code: 0, stdout: `${JSON.stringify({ hookSpecificOutput: { hookEventName: "SessionStart", watchPaths: [watched] } })}\n` };
195
236
  }
196
237
  if (!where || !role) return { code: 0 };
238
+ const file = sessionFile(where, payload);
239
+ const session = file && fs.existsSync(file) ? store.readJsonFile(file) : null;
240
+ if (event === "session-end" && file) fs.rmSync(file, { force: true });
241
+ if (session && session.host_run) return { code: 0 };
242
+ if (event === "user-prompt-submit" && session && session.role === role && !session.decided) {
243
+ if (decideSession(where, file, session, payload.prompt)) return { code: 0 };
244
+ }
197
245
  if (event === "session-end") {
198
246
  touchPresence(where, role, "offline");
199
247
  return { code: 0 };
200
248
  }
249
+ if (event === "session-start") rememberSession(where, role, file);
201
250
  const started = event === "session-start" ? { source: typeof payload.source === "string" ? payload.source : null } : null;
202
251
  touchPresence(where, role, "online", mail ? null : "claude-code", started);
203
252
  const chatText = noticeText(where, role);
@@ -243,7 +243,7 @@ function hostTask(where) {
243
243
  const prompt = [
244
244
  `You run the Keel patrol for chat role ${role} of the repository at ${worktree}. Do exactly the steps below and nothing else.`,
245
245
  "",
246
- `Do not change into that directory: run every command with the paths given, so this session does not act as ${role} (Keel's session hooks follow the working directory). `
246
+ "Run every command with the paths given. "
247
247
  + "Do not edit files, commit, push, close or comment on issues, or message anyone yourself: `keel patrol` sends the coordinator what changed.",
248
248
  "",
249
249
  `1. Run \`git -C ${at} fetch -q origin\`. If it fails, keep its error and continue.`,
@@ -269,6 +269,8 @@ function renderTask(task) {
269
269
  `task id: ${task.taskId}`,
270
270
  `schedule: ${task.cronExpression ? `${task.cronExpression} (from every: ${task.every}; hosts may add jitter)` : task.cronNote}`,
271
271
  `model: ${task.model || "no model is declared: choose a small model; Keel names none"}`,
272
+ "Create it from a session whose folder is bound to no role: a host task starts its runs in the folder it was created from, "
273
+ + "and Keel recognizes such a run only once its prompt arrives (#300).",
272
274
  `description: ${task.description}`,
273
275
  "prompt:",
274
276
  task.prompt,
package/src/core/shift.js CHANGED
@@ -427,12 +427,14 @@ function armWake(where, role, since) {
427
427
  return child.pid;
428
428
  }
429
429
 
430
- // The role's current session started after `since`, from a clear or a fresh start.
430
+ // The role's current session start, when it is after `since` from a clear or a
431
+ // fresh start; null otherwise.
431
432
  function startedSince(where, role, since) {
432
433
  const { presenceFile } = require("./chat/notice");
433
434
  const presence = store.readJsonFile(presenceFile(where, role));
434
435
  const started = Date.parse(presence.session_started || "");
435
- return !Number.isNaN(started) && started >= since && WAKE_SOURCES.has(presence.session_source);
436
+ const qualifies = !Number.isNaN(started) && started >= since && WAKE_SOURCES.has(presence.session_source);
437
+ return qualifies ? presence.session_started : null;
436
438
  }
437
439
 
438
440
  function writeWake(where, role) {
@@ -448,11 +450,18 @@ function writeWake(where, role) {
448
450
 
449
451
  function waitForWake(where, role, since) {
450
452
  const poll = envMs("KEEL_SHIFT_WAKE_POLL_MS", 5000);
453
+ const settle = envMs("KEEL_SHIFT_WAKE_SETTLE_MS", 15000);
451
454
  const deadline = Date.now() + envMs("KEEL_SHIFT_WAKE_TIMEOUT_MS", 2 * 60 * 60 * 1000);
455
+ // A qualifying start must stay unchanged for `settle` (#300 D4): a host
456
+ // run's start is reverted once its first prompt shows what it is.
457
+ let pending = null;
452
458
  const tick = () => {
453
459
  // A note resumed by hand needs no wake; give up after the time limit.
454
460
  if (!fs.existsSync(notePath(where, role)) || Date.now() > deadline) return;
455
- if (startedSince(where, role, since)) {
461
+ const started = startedSince(where, role, since);
462
+ if (!started) pending = null;
463
+ else if (!pending || pending.value !== started) pending = { value: started, at: Date.now() };
464
+ else if (Date.now() - pending.at >= settle) {
456
465
  writeWake(where, role);
457
466
  return;
458
467
  }