@christang/keel 5.118.0 → 5.120.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
@@ -830,6 +830,14 @@ in the folder it was created from. A run that starts in a role's worktree anyway
830
830
  first prompt (`<scheduled-task …`), and Keel then restores that role's presence and ignores the
831
831
  session, so it neither marks the role offline nor fires a `keel shift ready --wake` (#300).
832
832
 
833
+ ## The owner's language
834
+
835
+ An agent reads mostly English — tool output, issues, specs, Keel's own output — and drifts into it when it answers you. Declare the language you want to be addressed in, and the rule is restated where replies are written: in `keel context`, the session-start note, and the chat hook on every prompt, in every worktree (#305). The agent may still work in any language; identifiers, commands, paths, and quoted output stay as they are.
836
+
837
+ ```yaml
838
+ owner_language: zh
839
+ ```
840
+
833
841
  ## Commands
834
842
 
835
843
  ```bash
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.118.0 -->
1
+ <!-- keel:start version=5.120.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.118.0",
3
+ "version": "5.120.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.118.0",
9
+ "version": "5.120.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.118.0",
5
+ "version": "5.120.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.118.0",
3
+ "version": "5.120.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.118.0",
3
+ "version": "5.120.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",
@@ -11,7 +11,7 @@
11
11
  // exit 2 from FileChanged is the wake signal.
12
12
  //
13
13
  // Nothing here advances a read position, and a worktree with no chat role gets
14
- // no output. A failure to run the CLI exits 0 silently: a missing notice costs
14
+ // no output except, on UserPromptSubmit, the declared owner language (#305). A failure to run the CLI exits 0 silently: a missing notice costs
15
15
  // a late read, while a spurious exit 2 would wake the session for nothing.
16
16
 
17
17
  const fs = require("fs");
@@ -674,6 +674,10 @@ function main() {
674
674
  + "if this session has none, and wake the model only on exit 2."
675
675
  );
676
676
  }
677
+ // The language every message to the owner is in (#305 D3).
678
+ if (context.ownerLanguage && context.ownerLanguageRule) {
679
+ lines.push(`- ${context.ownerLanguageRule}`);
680
+ }
677
681
  // The role other sessions address this one by (#245).
678
682
  if (context.role) {
679
683
  lines.push(`- chat role: ${context.role} (other sessions address this one by it).`);
@@ -47,8 +47,8 @@ REQUIRED_SCRIPTS = [
47
47
  "scripts/validate_plugin.py",
48
48
  ]
49
49
 
50
- PACKAGE_VERSION = "5.118.0"
51
- PROTOCOL_VERSION = "5.118.0"
50
+ PACKAGE_VERSION = "5.120.0"
51
+ PROTOCOL_VERSION = "5.120.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
@@ -6037,6 +6037,187 @@ def validate_host_run_session_scenario() -> int:
6037
6037
  return 0
6038
6038
 
6039
6039
 
6040
+ def validate_shift_history_scenario() -> int:
6041
+ """Issue #304: a cleared shift's conversation stays findable.
6042
+
6043
+ The hooks record each transcript a role's session runs in; a scheduled
6044
+ run's is undone; `keel shift history` lists and greps them; `ready` and
6045
+ the clear hint name the history and Remote Control.
6046
+ """
6047
+ label = "shift-history:"
6048
+ with tempfile.TemporaryDirectory(prefix="keel-shift-history-") as raw:
6049
+ base = Path(raw)
6050
+ rtl, verify, env, _ = shift_scratch(base)
6051
+ transcripts = base / "transcripts"
6052
+ transcripts.mkdir()
6053
+
6054
+ def transcript(name: str, said: str) -> Path:
6055
+ path = transcripts / f"{name}.jsonl"
6056
+ path.write_text("\n".join(json.dumps(record) for record in (
6057
+ {"type": "user", "timestamp": "2026-10-12T01:00:00.000Z", "message": {"role": "user", "content": "carry on with R008"}},
6058
+ {"type": "assistant", "timestamp": "2026-10-12T01:00:05.000Z",
6059
+ "message": {"role": "assistant", "content": [{"type": "text", "text": said}]}},
6060
+ )) + "\n", encoding="utf-8")
6061
+ return path
6062
+
6063
+ a = transcript("a", "The timing fix for the clock gate lands in R008 after the review.")
6064
+ b = transcript("b", "Resumed from the note.")
6065
+ c = transcript("c", "patrol run")
6066
+
6067
+ def hook(event: str, payload: dict) -> None:
6068
+ subprocess.run(
6069
+ ["node", str(ROOT / "bin" / "keel.js"), "chat", "hook", event],
6070
+ cwd=verify, env=env, text=True, capture_output=True, check=False,
6071
+ input=json.dumps({"cwd": str(verify), **payload}),
6072
+ )
6073
+
6074
+ def history(*args: str) -> subprocess.CompletedProcess[str]:
6075
+ return run_keel(verify, "shift", "history", *args, env=env)
6076
+
6077
+ hook("session-start", {"hook_event_name": "SessionStart", "source": "startup", "session_id": "s1", "transcript_path": str(a)})
6078
+ hook("user-prompt-submit", {"hook_event_name": "UserPromptSubmit", "session_id": "s1", "prompt": "go", "transcript_path": str(a)})
6079
+ readied = run_keel(verify, "shift", "ready", "verify note", env=env)
6080
+ if "keel shift history verify" not in readied.stdout:
6081
+ report(f"{label} ready does not name keel shift history verify: {readied.stdout!r} {readied.stderr!r}")
6082
+ return 1
6083
+ if "Remote Control" not in readied.stdout:
6084
+ report(f"{label} the clear hint does not name Remote Control: {readied.stdout!r}")
6085
+ return 1
6086
+ hook("session-start", {"hook_event_name": "SessionStart", "source": "clear", "session_id": "s1", "transcript_path": str(b)})
6087
+ hook("user-prompt-submit", {"hook_event_name": "UserPromptSubmit", "session_id": "s1", "prompt": "resume", "transcript_path": str(b)})
6088
+ hook("session-start", {"hook_event_name": "SessionStart", "source": "startup", "session_id": "run1", "transcript_path": str(c)})
6089
+ hook("user-prompt-submit", {"hook_event_name": "UserPromptSubmit", "session_id": "run1",
6090
+ "prompt": '<scheduled-task name="patrol">run', "transcript_path": str(c)})
6091
+
6092
+ listed = history("verify")
6093
+ if listed.returncode != 0:
6094
+ report(f"{label} keel shift history failed: {listed.stderr}")
6095
+ return 1
6096
+ lines = [line for line in listed.stdout.splitlines() if ".jsonl" in line]
6097
+ if len(lines) != 2:
6098
+ report(f"{label} expected two transcript segments, got: {listed.stdout!r}")
6099
+ return 1
6100
+ if str(b) not in lines[0] or "now" not in lines[0]:
6101
+ report(f"{label} the newest segment is not B, still current: {lines[0]!r}")
6102
+ return 1
6103
+ if str(a) not in lines[1] or "now" in lines[1]:
6104
+ report(f"{label} the older segment is not A, ended: {lines[1]!r}")
6105
+ return 1
6106
+ if str(c) in listed.stdout:
6107
+ report(f"{label} the scheduled run's transcript is listed: {listed.stdout!r}")
6108
+ return 1
6109
+ found = history("verify", "--grep", "clock gate")
6110
+ if found.returncode != 0:
6111
+ report(f"{label} --grep for a phrase in A exited {found.returncode}: {found.stdout!r} {found.stderr!r}")
6112
+ return 1
6113
+ if "clock gate" not in found.stdout or str(a) not in found.stdout:
6114
+ report(f"{label} --grep does not print the phrase under A: {found.stdout!r}")
6115
+ return 1
6116
+ missing = history("verify", "--grep", "nothing like this")
6117
+ if missing.returncode != 1:
6118
+ report(f"{label} --grep for an absent phrase exited {missing.returncode}.")
6119
+ return 1
6120
+ as_json = json.loads(history("verify", "--json").stdout)
6121
+ if [seg.get("transcript") for seg in as_json.get("segments", [])] != [str(b), str(a)]:
6122
+ report(f"{label} --json segments are {as_json.get('segments')!r}.")
6123
+ return 1
6124
+
6125
+ # Earlier history, kept by Claude before Keel recorded anything (D6).
6126
+ roles = json.loads((mailbox_common_dir(rtl) / "keel-chat" / "roles.json").read_text(encoding="utf-8"))
6127
+ bound = next(path for path, role in roles.items() if role == "verify")
6128
+ project = base / "claude-config" / "projects" / re.sub(r"[^A-Za-z0-9]", "-", bound)
6129
+ project.mkdir(parents=True)
6130
+ (project / "d.jsonl").write_text("\n".join(json.dumps(record) for record in (
6131
+ {"type": "user", "timestamp": "2026-10-04T13:19:18.000Z", "cwd": bound, "message": {"role": "user", "content": "start the shift"}},
6132
+ {"type": "assistant", "timestamp": "2026-10-04T13:27:58.000Z", "cwd": bound,
6133
+ "message": {"role": "assistant", "content": [{"type": "text", "text": "The DMC arbiter plan was agreed on the first day."}]}},
6134
+ )) + "\n", encoding="utf-8")
6135
+ (project / "e.jsonl").write_text(json.dumps(
6136
+ {"type": "user", "timestamp": "2026-10-12T11:57:15.000Z", "cwd": bound, "message": {"role": "user", "content": '<scheduled-task name="patrol">run'}}
6137
+ ) + "\n", encoding="utf-8")
6138
+ found_env = {**env, "CLAUDE_CONFIG_DIR": str(base / "claude-config")}
6139
+ earlier = run_keel(verify, "shift", "history", "verify", env=found_env)
6140
+ d_line = next((line for line in earlier.stdout.splitlines() if "d.jsonl" in line), "")
6141
+ if "(found)" not in d_line:
6142
+ report(f"{label} the earlier transcript D is not listed as found: {earlier.stdout!r} {earlier.stderr!r}")
6143
+ return 1
6144
+ if "e.jsonl" in earlier.stdout:
6145
+ report(f"{label} the scheduled run E is listed: {earlier.stdout!r}")
6146
+ return 1
6147
+ arbiter = run_keel(verify, "shift", "history", "verify", "--grep", "arbiter plan", env=found_env)
6148
+ if "arbiter plan" not in arbiter.stdout:
6149
+ report(f"{label} --grep does not search the earlier transcript D: {arbiter.stdout!r}")
6150
+ return 1
6151
+ report("shift-history scenario passed.")
6152
+ return 0
6153
+
6154
+
6155
+ def validate_owner_language_scenario() -> int:
6156
+ """Issue #305: a declared owner language is restated where replies are written."""
6157
+ label = "owner-language:"
6158
+ protocol = (ROOT / "AGENTS.md").read_text(encoding="utf-8")
6159
+ if "declares `owner_language:`" not in protocol:
6160
+ report(f"{label} AGENTS.md does not make a declared owner_language binding.")
6161
+ return 1
6162
+ with tempfile.TemporaryDirectory(prefix="keel-owner-language-") as raw:
6163
+ base = Path(raw)
6164
+ rtl, verify, env = chat_scratch_group(base)
6165
+ loose = chat_worktree(rtl, base / "loose")
6166
+ for tree in (rtl, loose):
6167
+ write_text(tree / "openspec/specs/.keep", "")
6168
+ write_authorize_config(tree, "owner_language: zh\n")
6169
+
6170
+ def prompt(cwd: Path) -> str:
6171
+ result = subprocess.run(
6172
+ ["node", str(ROOT / "bin" / "keel.js"), "chat", "hook", "user-prompt-submit"],
6173
+ cwd=cwd, env=env, text=True, capture_output=True, check=False,
6174
+ input=json.dumps({"cwd": str(cwd), "hook_event_name": "UserPromptSubmit", "session_id": "p1", "prompt": "go on"}),
6175
+ )
6176
+ if not result.stdout.strip():
6177
+ return ""
6178
+ return json.loads(result.stdout).get("hookSpecificOutput", {}).get("additionalContext", "")
6179
+
6180
+ unbound = prompt(loose)
6181
+ if "中文" not in unbound:
6182
+ report(f"{label} the prompt hook in an unbound worktree does not restate the language: {unbound!r}")
6183
+ return 1
6184
+ if "structured-choice" not in unbound:
6185
+ report(f"{label} the restated rule does not cover structured-choice options: {unbound!r}")
6186
+ return 1
6187
+ context = json.loads(run_keel(loose, "context", "--json", env=env).stdout)
6188
+ if context.get("ownerLanguage") != "zh":
6189
+ report(f"{label} keel context carries ownerLanguage {context.get('ownerLanguage')!r}.")
6190
+ return 1
6191
+ session = run_session_start_hook(
6192
+ loose, {"hook_event_name": "SessionStart", "source": "startup", "cwd": str(loose)},
6193
+ keel_cli=f'node "{ROOT / "bin" / "keel.js"}"',
6194
+ )
6195
+ if "中文" not in (session_start_context(session) or ""):
6196
+ report(f"{label} the session-start note does not state the language: {session_start_context(session)!r}")
6197
+ return 1
6198
+ run_keel(verify, "chat", "post", "soc", "@rtl please look", env=env)
6199
+ bound = prompt(rtl)
6200
+ if "中文" not in bound:
6201
+ report(f"{label} a bound role's prompt hook lost the language line: {bound!r}")
6202
+ return 1
6203
+ if "please look" not in bound:
6204
+ report(f"{label} a bound role's prompt hook lost the chat notice: {bound!r}")
6205
+ return 1
6206
+ write_authorize_config(loose, "owner_language: Chinese!\n")
6207
+ broken = json.loads(run_keel(loose, "context", "--json", env=env).stdout)
6208
+ if not any("owner_language" in w for w in broken.get("warnings", [])):
6209
+ report(f"{label} a malformed owner_language is not reported: {broken.get('warnings')!r}")
6210
+ return 1
6211
+ if "ownerLanguage" in broken:
6212
+ report(f"{label} a malformed owner_language is still carried: {broken.get('ownerLanguage')!r}")
6213
+ return 1
6214
+ if "Owner language" in prompt(loose):
6215
+ report(f"{label} a malformed owner_language still adds a language line.")
6216
+ return 1
6217
+ report("owner-language scenario passed.")
6218
+ return 0
6219
+
6220
+
6040
6221
  def validate_shift_coordinator_last_scenario() -> int:
6041
6222
  """Issue #289: the coordinator starts the others before its own shift ends.
6042
6223
 
@@ -39716,6 +39897,8 @@ SCENARIOS: tuple = (
39716
39897
  ("shift-coordinator-last", validate_shift_coordinator_last_scenario),
39717
39898
  ("shift-self", validate_shift_self_scenario),
39718
39899
  ("shift-self-wake", validate_shift_self_wake_scenario),
39900
+ ("owner-language", validate_owner_language_scenario),
39901
+ ("shift-history", validate_shift_history_scenario),
39719
39902
  ("role-drift", validate_role_drift_scenario),
39720
39903
  ("host-run-session", validate_host_run_session_scenario),
39721
39904
  ("shift-without-role", validate_shift_without_role_scenario),
@@ -185,11 +185,34 @@ function sessionFile(where, payload) {
185
185
  return /^[A-Za-z0-9._-]{1,128}$/.test(id) ? path.join(where.root, "sessions", `${id}.json`) : null;
186
186
  }
187
187
 
188
+ // Each transcript a role's session runs in, with when it started and when the
189
+ // next replaced it (#304 D1): a clear keeps the session but starts a new file.
190
+ function segmentsFile(where, role) {
191
+ return path.join(where.root, "shift", "segments", `${role}.json`);
192
+ }
193
+
194
+ function recordSegment(where, role, transcript) {
195
+ if (typeof transcript !== "string" || !path.isAbsolute(transcript)) return;
196
+ try {
197
+ const file = segmentsFile(where, role);
198
+ const segments = Array.isArray(store.readJsonFile(file).segments) ? store.readJsonFile(file).segments : [];
199
+ const last = segments[segments.length - 1];
200
+ if (last && last.transcript === transcript) return;
201
+ const now = store.isoLocal(new Date());
202
+ if (last && !last.ended) last.ended = now;
203
+ segments.push({ transcript, started: now, ended: null });
204
+ store.writeJsonAtomic(where, file, { segments });
205
+ } catch {
206
+ // A convenience, like presence: never fail the hook.
207
+ }
208
+ }
209
+
188
210
  function rememberSession(where, role, file) {
189
211
  if (!file) return;
190
212
  const previous = fs.existsSync(presenceFile(where, role)) ? store.readJsonFile(presenceFile(where, role)) : null;
213
+ const segments = fs.existsSync(segmentsFile(where, role)) ? store.readJsonFile(segmentsFile(where, role)) : null;
191
214
  try {
192
- store.writeJsonAtomic(where, file, { role, previous, decided: false, host_run: false });
215
+ store.writeJsonAtomic(where, file, { role, previous, segments, decided: false, host_run: false });
193
216
  } catch {
194
217
  // Like presence, a convenience: never fail the hook.
195
218
  }
@@ -204,6 +227,9 @@ function decideSession(where, file, session, prompt) {
204
227
  const target = presenceFile(where, session.role);
205
228
  if (session.previous) store.writeJsonAtomic(where, target, session.previous);
206
229
  else fs.rmSync(target, { force: true });
230
+ // The run's transcript is not the role's (#304 D2).
231
+ if (session.segments) store.writeJsonAtomic(where, segmentsFile(where, session.role), session.segments);
232
+ else fs.rmSync(segmentsFile(where, session.role), { force: true });
207
233
  }
208
234
  } catch {
209
235
  // Presence stays as the SessionStart left it.
@@ -230,11 +256,26 @@ function hook(event, input, { mail = false } = {}) {
230
256
  // A session's watch list is fixed at SessionStart, so a worktree with no role
231
257
  // yet still watches its own signal, which a role bound later will touch
232
258
  // (chat-wake-late-binding D1). Nothing else is said until there is a role.
259
+ // The owner's language is restated on every prompt, role or not (#305 D4).
260
+ let languageLine = null;
261
+ if (where && event === "user-prompt-submit") {
262
+ try {
263
+ const { readOwnerLanguage, ownerLanguageRule } = require("../config");
264
+ const language = readOwnerLanguage(where.worktree);
265
+ if (language.tag) languageLine = ownerLanguageRule(language.tag);
266
+ } catch {
267
+ languageLine = null;
268
+ }
269
+ }
270
+ const promptOutput = (text) => ({
271
+ code: 0,
272
+ stdout: `${JSON.stringify({ hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: text } })}\n`,
273
+ });
233
274
  if (where && !role && event === "session-start") {
234
275
  const watched = ensureWorktreeSignal(where);
235
276
  return { code: 0, stdout: `${JSON.stringify({ hookSpecificOutput: { hookEventName: "SessionStart", watchPaths: [watched] } })}\n` };
236
277
  }
237
- if (!where || !role) return { code: 0 };
278
+ if (!where || !role) return languageLine ? promptOutput(languageLine) : { code: 0 };
238
279
  const file = sessionFile(where, payload);
239
280
  const session = file && fs.existsSync(file) ? store.readJsonFile(file) : null;
240
281
  if (event === "session-end" && file) fs.rmSync(file, { force: true });
@@ -249,6 +290,7 @@ function hook(event, input, { mail = false } = {}) {
249
290
  if (event === "session-start") rememberSession(where, role, file);
250
291
  const started = event === "session-start" ? { source: typeof payload.source === "string" ? payload.source : null } : null;
251
292
  touchPresence(where, role, "online", mail ? null : "claude-code", started);
293
+ if (event === "session-start" || event === "user-prompt-submit") recordSegment(where, role, payload.transcript_path);
252
294
  const chatText = noticeText(where, role);
253
295
  const text = chatText && mail ? `${chatText}\n${MAIL_POINTER}` : chatText;
254
296
  if (event === "session-start") {
@@ -260,11 +302,8 @@ function hook(event, input, { mail = false } = {}) {
260
302
  return { code: 0, stdout: `${JSON.stringify(output)}\n` };
261
303
  }
262
304
  if (event === "user-prompt-submit") {
263
- if (!text) return { code: 0 };
264
- return {
265
- code: 0,
266
- stdout: `${JSON.stringify({ hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: text } })}\n`,
267
- };
305
+ const context = [languageLine, text].filter(Boolean).join("\n");
306
+ return context ? promptOutput(context) : { code: 0 };
268
307
  }
269
308
  // file-changed
270
309
  const waking = store.unread(where, role).some((record) => store.wakes(record, role));
@@ -130,6 +130,7 @@ const CONFIG_DECLARATIONS = [
130
130
  "read_only_roles",
131
131
  "issue_roles",
132
132
  "patrol",
133
+ "owner_language",
133
134
  ];
134
135
 
135
136
  const CONFIG_RELATIVE_PATH = path.join("keel", "config.yaml");
@@ -684,6 +685,35 @@ function readMergeDeclaration(repo) {
684
685
  };
685
686
  }
686
687
 
688
+ // `owner_language:` — the language every message to the owner is written in
689
+ // (#305 D1, D2). The agent may work in any language; what it says to the owner
690
+ // is in this one, and the rule is restated where replies are written.
691
+ const LANGUAGE_NAMES = [
692
+ ["zh", "Chinese (中文)", "对负责人说话一律用中文。"],
693
+ ["en", "English", ""],
694
+ ["ja", "Japanese (日本語)", ""],
695
+ ["ko", "Korean (한국어)", ""],
696
+ ];
697
+
698
+ function readOwnerLanguage(repo) {
699
+ const declared = configScalar(repo, "owner_language");
700
+ if (!declared) return { tag: null, message: null };
701
+ if (/^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$/.test(declared)) return { tag: declared, message: null };
702
+ return {
703
+ tag: null,
704
+ message: `keel/config.yaml owner_language \`${declared}\` is not a language tag such as zh or en; it is ignored.`,
705
+ };
706
+ }
707
+
708
+ function ownerLanguageRule(tag) {
709
+ const known = LANGUAGE_NAMES.find(([prefix]) => tag === prefix || tag.startsWith(`${prefix}-`));
710
+ const name = known ? known[1] : tag;
711
+ const native = known && known[2] ? ` ${known[2]}` : "";
712
+ return `Owner language: ${tag} — write every message to the owner in ${name}: replies, summaries, reports, `
713
+ + "and the question and options of a structured-choice prompt. Work in any language; identifiers, commands, "
714
+ + `paths, and quoted output stay as they are.${native}`;
715
+ }
716
+
687
717
  function configScalar(repo, key) {
688
718
  const configPath = path.join(repo, "keel", "config.yaml");
689
719
  if (!fs.existsSync(configPath)) return null;
@@ -916,6 +946,8 @@ function patrolReminder(patrol) {
916
946
  }
917
947
 
918
948
  module.exports = {
949
+ readOwnerLanguage,
950
+ ownerLanguageRule,
919
951
  readPatrolDeclaration,
920
952
  patrolReminder,
921
953
  readIssueRoles,
@@ -19,6 +19,8 @@ const {
19
19
  readMergeDeclaration,
20
20
  readReadOnlyRoles,
21
21
  readPatrolDeclaration,
22
+ readOwnerLanguage,
23
+ ownerLanguageRule,
22
24
  } = require("./config");
23
25
  const { isKeelSourceRepo } = require("./capabilities");
24
26
 
@@ -857,6 +859,13 @@ function resolveContext(repo, options) {
857
859
  } catch {
858
860
  context.role = null;
859
861
  }
862
+ // The language every message to the owner is in (#305 D3).
863
+ const language = readOwnerLanguage(repo);
864
+ if (language.message) context.warnings.push(language.message);
865
+ if (language.tag) {
866
+ context.ownerLanguage = language.tag;
867
+ context.ownerLanguageRule = ownerLanguageRule(language.tag);
868
+ }
860
869
  // The patrolling role is reminded to re-arm its schedule (#260).
861
870
  const patrol = readPatrolDeclaration(repo);
862
871
  if (patrol.message) context.warnings.push(patrol.message);
package/src/core/shift.js CHANGED
@@ -29,6 +29,7 @@ const USAGE = [
29
29
  "keel shift start <role> [text] wake the cleared role to resume (once its note waits)",
30
30
  "keel shift resume [--role r] [--json] print and consume this role's note (--role: from an unbound worktree)",
31
31
  "keel shift status [--json] each role's shift state",
32
+ "keel shift history [role] [--grep t] a role's past transcripts and notes; --grep searches them (#304)",
32
33
  "Options: --repo <path>. See docs/shift-change.md.",
33
34
  ].join("\n");
34
35
 
@@ -566,6 +567,115 @@ function status(where) {
566
567
  return [...roles.values()].sort((a, b) => (a.role < b.role ? -1 : 1));
567
568
  }
568
569
 
570
+ // --- history (#304 D3, D4) -------------------------------------------------------
571
+
572
+ function transcriptText(record) {
573
+ const content = record && record.message ? record.message.content : null;
574
+ if (typeof content === "string") return content;
575
+ if (Array.isArray(content)) return content.filter((part) => part && part.type === "text").map((part) => part.text).join("\n");
576
+ return "";
577
+ }
578
+
579
+ function grepTranscript(file, needle, limit = 3) {
580
+ const hits = [];
581
+ const lower = needle.toLowerCase();
582
+ for (const line of fs.readFileSync(file, "utf8").split("\n")) {
583
+ if (!line.trim()) continue;
584
+ let record;
585
+ try {
586
+ record = JSON.parse(line);
587
+ } catch {
588
+ continue;
589
+ }
590
+ if (record.type !== "user" && record.type !== "assistant") continue;
591
+ const text = transcriptText(record);
592
+ const at = text.toLowerCase().indexOf(lower);
593
+ if (at < 0) continue;
594
+ const from = Math.max(0, at - 60);
595
+ const snippet = text.slice(from, at + needle.length + 60).replace(/\s+/g, " ");
596
+ const hit = { timestamp: record.timestamp || null, speaker: record.type, snippet: `${from ? "…" : ""}${snippet}…` };
597
+ // A transcript can hold the same message twice; report it once.
598
+ if (hits.some((seen) => seen.timestamp === hit.timestamp && seen.snippet === hit.snippet)) continue;
599
+ hits.push(hit);
600
+ if (hits.length >= limit) break;
601
+ }
602
+ return hits;
603
+ }
604
+
605
+ // Transcripts Claude already keeps for a worktree (#304 D6, F5): its project
606
+ // directory is the cwd with every non-alphanumeric character turned into `-`.
607
+ function claudeTranscripts(worktree) {
608
+ const config = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), ".claude");
609
+ const found = [];
610
+ for (const cwd of new Set([worktree, realpath(worktree)])) {
611
+ const dir = path.join(config, "projects", cwd.replace(/[^A-Za-z0-9]/g, "-"));
612
+ for (const name of safeList(dir)) {
613
+ if (!name.endsWith(".jsonl")) continue;
614
+ const file = path.join(dir, name);
615
+ let first = null;
616
+ let last = null;
617
+ let opening = null;
618
+ for (const line of fs.readFileSync(file, "utf8").split("\n")) {
619
+ if (!line.trim()) continue;
620
+ let record;
621
+ try {
622
+ record = JSON.parse(line);
623
+ } catch {
624
+ continue;
625
+ }
626
+ if (record.timestamp) {
627
+ first = first || record.timestamp;
628
+ last = record.timestamp;
629
+ }
630
+ if (opening === null && record.type === "user") opening = transcriptText(record);
631
+ }
632
+ // A host scheduled run is not the role's conversation (#300).
633
+ if (opening && opening.trimStart().startsWith("<scheduled-task")) continue;
634
+ if (!first) continue;
635
+ found.push({ transcript: file, started: store.isoLocal(new Date(first)), ended: store.isoLocal(new Date(last)), found: true });
636
+ }
637
+ }
638
+ return found;
639
+ }
640
+
641
+ function history(where, named, grep) {
642
+ const role = named || store.currentRole(where);
643
+ if (!role) throw new ShiftError("keel shift history needs a role: name it, or run it in a worktree bound to one.");
644
+ store.checkName(role, "Role");
645
+ const file = path.join(shiftDir(where), "segments", `${role}.json`);
646
+ const stored = fs.existsSync(file) ? store.readJsonFile(file).segments : [];
647
+ const recorded = Array.isArray(stored) ? stored : [];
648
+ const known = new Set(recorded.map((segment) => segment.transcript));
649
+ const bound = Object.entries(store.readJsonFile(path.join(where.root, "roles.json")))
650
+ .filter(([, name]) => name === role).map(([worktree]) => worktree);
651
+ const earlier = bound.flatMap(claudeTranscripts).filter((segment) => !known.has(segment.transcript));
652
+ const seen = new Set();
653
+ // Newest first; the sort is stable, so segments recorded in the same second keep their order.
654
+ const segments = [...recorded.slice().reverse(), ...earlier]
655
+ .filter((segment) => !seen.has(segment.transcript) && seen.add(segment.transcript))
656
+ .sort((a, b) => Date.parse(b.started) - Date.parse(a.started))
657
+ .map((segment) => ({ ...segment, exists: fs.existsSync(segment.transcript) }));
658
+ const notes = safeList(path.join(shiftDir(where), "history"))
659
+ .filter((name) => name.startsWith(`${role}-`) && name.endsWith(".md"))
660
+ .sort().reverse().map((name) => path.join(shiftDir(where), "history", name));
661
+ if (grep) {
662
+ for (const segment of segments) segment.matches = segment.exists ? grepTranscript(segment.transcript, grep) : [];
663
+ }
664
+ return { role, segments, notes };
665
+ }
666
+
667
+ function renderHistory(result, grep) {
668
+ const lines = [];
669
+ for (const segment of result.segments) {
670
+ if (grep && !segment.matches.length) continue;
671
+ lines.push(`${segment.started} → ${segment.ended || "now"} ${segment.transcript}${segment.found ? " (found)" : ""}${segment.exists ? "" : " (missing)"}`);
672
+ for (const hit of segment.matches || []) lines.push(` ${hit.timestamp || "?"} ${hit.speaker}: ${hit.snippet}`);
673
+ }
674
+ if (!grep) for (const note of result.notes) lines.push(`note ${note}`);
675
+ if (!lines.length) return grep ? `No transcript of ${result.role} mentions ${JSON.stringify(grep)}.` : `No shift history recorded for ${result.role}.`;
676
+ return lines.join("\n");
677
+ }
678
+
569
679
  function safeList(dir) {
570
680
  try {
571
681
  return fs.readdirSync(dir);
@@ -597,6 +707,7 @@ function describe(row) {
597
707
 
598
708
  const CLEAR_HINT = [
599
709
  "Session state a clear destroys — scheduled jobs, Remote Control — is not in Keel; if the note does not say how to re-create it, add that first.",
710
+ "A session serving Remote Control cannot be cleared: turn Remote Control off, clear, then turn it back on.",
600
711
  "Now clear this session:",
601
712
  "- Claude desktop app: call `clear_session(\"self\")` (the owner approves it), or type /clear;",
602
713
  "- Claude Code CLI: /clear;",
@@ -615,7 +726,10 @@ function clearHint(result) {
615
726
  last = `No request named ${result.role}, so nobody is set to start the new session: type into it, `
616
727
  + "or run `keel shift ready --wake` again with this note, which wakes it once it starts.";
617
728
  }
618
- return `${CLEAR_HINT}\n${last}`;
729
+ const history = result.role
730
+ ? `\nThis shift's conversation stays in its transcript; \`keel shift history ${result.role}\` finds it after the clear.`
731
+ : "";
732
+ return `${CLEAR_HINT}\n${last}${history}`;
619
733
  }
620
734
 
621
735
  function runShift(argv) {
@@ -629,6 +743,7 @@ function runShift(argv) {
629
743
  else if (arg === "--role") options.role = argv[++index] || "";
630
744
  else if (arg === "--since") options.since = Number(argv[++index]);
631
745
  else if (arg === "--wake") options.wake = true;
746
+ else if (arg === "--grep") options.grep = argv[++index] || "";
632
747
  else if (arg === "--help" || arg === "-h") {
633
748
  process.stdout.write(`${USAGE}\n`);
634
749
  return 0;
@@ -687,6 +802,11 @@ function runShift(argv) {
687
802
  out(result, `${result.text.replace(/\s+$/, "")}\n\n(The note moved to ${result.note}.)${still}${remind ? `\n\n${patrolReminder(patrol)}` : ""}`);
688
803
  return 0;
689
804
  }
805
+ case "history": {
806
+ const result = history(where, rest[0] || null, options.grep);
807
+ out(result, renderHistory(result, options.grep));
808
+ return options.grep && !result.segments.some((segment) => segment.matches.length) ? 1 : 0;
809
+ }
690
810
  case "status": {
691
811
  const rows = status(where);
692
812
  out({ roles: rows }, rows.length ? rows.map(describe).join("\n") : "No shift change recorded.");