@izhimu/pi-caveman 0.2.0 → 0.4.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.
Files changed (55) hide show
  1. package/CHANGELOG.md +68 -0
  2. package/README.md +60 -74
  3. package/extensions/caveman.ts +452 -346
  4. package/package.json +37 -6
  5. package/skills/caveman/README.md +68 -48
  6. package/skills/caveman/SKILL.md +57 -56
  7. package/skills/megacave/README.md +11 -0
  8. package/skills/megacave/SKILL.md +65 -0
  9. package/skills/ultracave/README.md +13 -0
  10. package/skills/ultracave/SKILL.md +63 -0
  11. package/skills/cavecrew/README.md +0 -61
  12. package/skills/cavecrew/SKILL.md +0 -82
  13. package/skills/caveman-commit/README.md +0 -44
  14. package/skills/caveman-commit/SKILL.md +0 -65
  15. package/skills/caveman-compress/README.md +0 -163
  16. package/skills/caveman-compress/SECURITY.md +0 -31
  17. package/skills/caveman-compress/SKILL.md +0 -111
  18. package/skills/caveman-compress/scripts/__init__.py +0 -9
  19. package/skills/caveman-compress/scripts/__main__.py +0 -3
  20. package/skills/caveman-compress/scripts/benchmark.py +0 -80
  21. package/skills/caveman-compress/scripts/cli.py +0 -85
  22. package/skills/caveman-compress/scripts/compress.py +0 -414
  23. package/skills/caveman-compress/scripts/detect.py +0 -139
  24. package/skills/caveman-compress/scripts/validate.py +0 -221
  25. package/skills/caveman-discover/SKILL.md +0 -118
  26. package/skills/caveman-evidence-review/SKILL.md +0 -144
  27. package/skills/caveman-explore/SKILL.md +0 -42
  28. package/skills/caveman-explore/package.json +0 -12
  29. package/skills/caveman-explore/tests/skill-file.test.mjs +0 -44
  30. package/skills/caveman-help/README.md +0 -38
  31. package/skills/caveman-help/SKILL.md +0 -63
  32. package/skills/caveman-learn/CLAUDE.md +0 -32
  33. package/skills/caveman-learn/README.md +0 -29
  34. package/skills/caveman-learn/SKILL.md +0 -69
  35. package/skills/caveman-learn/package.json +0 -12
  36. package/skills/caveman-learn/tests/skill-file.test.mjs +0 -44
  37. package/skills/caveman-manage/SKILL.md +0 -114
  38. package/skills/caveman-optimize/SKILL.md +0 -114
  39. package/skills/caveman-review/README.md +0 -33
  40. package/skills/caveman-review/SKILL.md +0 -55
  41. package/skills/caveman-setup/SKILL.md +0 -224
  42. package/skills/caveman-stats/README.md +0 -36
  43. package/skills/caveman-stats/SKILL.md +0 -12
  44. package/skills/investigate-first/SKILL.md +0 -16
  45. package/skills/investigate-first/agents/openai.yaml +0 -4
  46. package/skills/lean-build/SKILL.md +0 -18
  47. package/skills/lean-build/agents/openai.yaml +0 -4
  48. package/skills/migration/SKILL.md +0 -17
  49. package/skills/migration/agents/openai.yaml +0 -4
  50. package/skills/safe-refactor/SKILL.md +0 -16
  51. package/skills/safe-refactor/agents/openai.yaml +0 -4
  52. package/skills/surgical-patch/SKILL.md +0 -16
  53. package/skills/surgical-patch/agents/openai.yaml +0 -4
  54. package/skills/verify-and-stop/SKILL.md +0 -16
  55. package/skills/verify-and-stop/agents/openai.yaml +0 -4
@@ -1,9 +1,9 @@
1
- // pi-caveman — pi extension
1
+ // pi-caveman — pi & oh-my-pi extension
2
2
  //
3
- // Caveman mode for pi: auto-activates per session, /caveman commands,
4
- // per-turn reinforcement injection, status bar integration.
3
+ // Caveman mode for pi & oh-my-pi: auto-activates per session, /caveman commands,
4
+ // per-turn reinforcement injection.
5
5
  //
6
- // Flag file: ~/.pi/.caveman-active
6
+ // Flag file: ~/.pi/.caveman-active or ~/.omp/.caveman-active
7
7
  // Config: ~/.config/caveman/config.json or CAVEMAN_DEFAULT_MODE env
8
8
  // Upstream: https://github.com/JuliusBrussee/caveman
9
9
 
@@ -20,21 +20,27 @@ import { fileURLToPath } from "node:url";
20
20
  const __filename = fileURLToPath(import.meta.url);
21
21
  const __dirname = dirname(__filename);
22
22
 
23
- // ── Constants ───────────────────────────────────────────────────────────────
23
+ // ── Constants & Canonical Mode Mapping ─────────────────────────────────────
24
24
 
25
- const VALID_MODES = [
26
- "lite", "full", "ultra",
27
- "wenyan-lite", "wenyan", "wenyan-full", "wenyan-ultra",
28
- "commit", "review", "compress",
29
- ] as const;
25
+ export const VALID_MODES = ["caveman", "ultracave", "megacave"] as const;
26
+ export type Mode = (typeof VALID_MODES)[number];
30
27
 
31
- type Mode = (typeof VALID_MODES)[number];
32
-
33
- // Modes with independent skills — not caveman intensity levels
34
- const INDEPENDENT: Record<string, true> = {
35
- commit: true, review: true, compress: true,
28
+ export const LEGACY_MODE_MAP: Record<string, Mode> = {
29
+ "full": "caveman",
30
+ "lite": "caveman",
31
+ "ultra": "ultracave",
32
+ "wenyan": "megacave",
33
+ "wenyan-lite": "megacave",
34
+ "wenyan-full": "megacave",
35
+ "wenyan-ultra": "megacave",
36
36
  };
37
37
 
38
+ export function canonicalMode(raw: string): Mode | null {
39
+ const lower = raw.trim().toLowerCase();
40
+ if ((VALID_MODES as readonly string[]).includes(lower)) return lower as Mode;
41
+ return LEGACY_MODE_MAP[lower] ?? null;
42
+ }
43
+
38
44
  // ── Session stats ───────────────────────────────────────────────────────────
39
45
 
40
46
  interface SessionStats {
@@ -50,17 +56,23 @@ let sessionStats: SessionStats = {
50
56
 
51
57
  let sessionExplicitOff = false;
52
58
 
53
- const COMPRESSION_RATIOS: Record<string, number> = {
54
- 'full': 0.65,
55
- 'lite': 0.35,
56
- 'ultra': 0.75,
57
- 'wenyan': 0.80,
58
- 'wenyan-lite': 0.60,
59
- 'wenyan-ultra': 0.85,
59
+ export const COMPRESSION_RATIOS: Record<string, number> = {
60
+ caveman: 0.65,
61
+ ultracave: 0.75,
62
+ megacave: 0.80,
63
+ // legacy aliases for backwards compatibility
64
+ full: 0.65,
65
+ lite: 0.35,
66
+ ultra: 0.75,
67
+ wenyan: 0.80,
68
+ "wenyan-lite": 0.60,
69
+ "wenyan-full": 0.80,
70
+ "wenyan-ultra": 0.85,
60
71
  };
61
72
 
62
- function estimateSavings(outputTokens: number, mode: string) {
63
- const ratio = COMPRESSION_RATIOS[mode];
73
+ export function estimateSavings(outputTokens: number, mode: string) {
74
+ const canon = canonicalMode(mode) || mode;
75
+ const ratio = COMPRESSION_RATIOS[canon] ?? COMPRESSION_RATIOS[mode];
64
76
  if (!ratio) return null;
65
77
  const estWithout = Math.round(outputTokens / (1 - ratio));
66
78
  const estSaved = estWithout - outputTokens;
@@ -74,16 +86,13 @@ const RST = `${ESC}0m`;
74
86
  const DIM = `${ESC}2m`;
75
87
  const BOLD = `${ESC}1m`;
76
88
  const GREEN = `${ESC}32m`;
77
- const YELLOW = `${ESC}33m`;
78
- const RED = `${ESC}31m`;
79
89
  const CYAN = `${ESC}36m`;
80
90
  const GRAY = `${ESC}90m`;
81
91
 
82
- function modeColor(mode: string): string {
92
+ export function modeColor(mode: string): string {
83
93
  if (mode === "off") return GRAY;
84
- if (mode.startsWith("wenyan")) return CYAN;
85
- if (mode === "lite") return YELLOW;
86
- return GREEN; // full, ultra
94
+ if (mode === "megacave" || mode.startsWith("wenyan")) return CYAN;
95
+ return GREEN; // caveman, ultracave, full, ultra
87
96
  }
88
97
 
89
98
  function bar(pct: number, width = 20): string {
@@ -98,15 +107,27 @@ function truncatePath(p: string, max = 40): string {
98
107
  return "…" + sep + tail;
99
108
  }
100
109
 
101
- // ── Paths ───────────────────────────────────────────────────────────────────
110
+ // ── Paths & Host Resolution ─────────────────────────────────────────────────
111
+
112
+ export function resolveHostDir(): string {
113
+ const isOmp =
114
+ process.title === "omp" ||
115
+ Boolean(process.env.OMP_PROFILE) ||
116
+ process.env.PI_CONFIG_DIR === ".omp" ||
117
+ Boolean(process.env.OMP_AUTORESEARCH_DB_DIR) ||
118
+ (typeof process.argv[1] === "string" && process.argv[1].includes("@oh-my-pi"));
119
+ const dirName = isOmp ? "omp" : "pi";
120
+ const xdg = process.env.XDG_CONFIG_HOME;
121
+ return xdg ? join(xdg, dirName) : join(homedir(), `.${dirName}`);
122
+ }
102
123
 
103
- const xdg = process.env.XDG_CONFIG_HOME;
104
- const piDir = xdg ? join(xdg, "pi") : join(homedir(), ".pi");
105
- const flagPath = join(piDir, ".caveman-active");
124
+ export function getFlagPath(): string {
125
+ return join(resolveHostDir(), ".caveman-active");
126
+ }
106
127
 
107
128
  // ── Config resolution (mirrors caveman/src/hooks/caveman-config.js) ─────────
108
129
 
109
- function cavemanConfigDir(): string {
130
+ export function cavemanConfigDir(): string {
110
131
  const xdgHome = process.env.XDG_CONFIG_HOME;
111
132
  if (xdgHome) return join(xdgHome, "caveman");
112
133
  if (process.platform === "win32") {
@@ -118,7 +139,7 @@ function cavemanConfigDir(): string {
118
139
  return join(homedir(), ".config", "caveman");
119
140
  }
120
141
 
121
- function findRepoConfig(start: string): string | null {
142
+ export function findRepoConfig(start: string): string | null {
122
143
  let dir = start;
123
144
  for (let i = 0; i < 64; i++) {
124
145
  const a = join(dir, ".caveman", "config.json");
@@ -132,7 +153,7 @@ function findRepoConfig(start: string): string | null {
132
153
  return null;
133
154
  }
134
155
 
135
- function readConfigMode(configPath: string): string | null {
156
+ export function readConfigMode(configPath: string): string | null {
136
157
  try {
137
158
  const parsed = JSON.parse(readFileSync(configPath, "utf-8"));
138
159
  const m = parsed?.defaultMode;
@@ -142,16 +163,14 @@ function readConfigMode(configPath: string): string | null {
142
163
  }
143
164
  }
144
165
 
145
- function isValidMode(m: string): m is Mode {
146
- return (VALID_MODES as readonly string[]).includes(m);
147
- }
148
-
149
- function resolveDefault(): string {
166
+ export function resolveDefault(): Mode | "off" {
150
167
  // 1. Env var (short-circuits)
151
168
  const env = process.env.CAVEMAN_DEFAULT_MODE;
152
169
  if (env) {
153
170
  const lower = env.toLowerCase();
154
- if (isValidMode(lower) || lower === "off") return lower;
171
+ if (lower === "off") return "off";
172
+ const canon = canonicalMode(lower);
173
+ if (canon) return canon;
155
174
  }
156
175
  // 2. Repo-local config
157
176
  const repo = findRepoConfig(process.cwd());
@@ -159,7 +178,9 @@ function resolveDefault(): string {
159
178
  const m = readConfigMode(repo);
160
179
  if (m) {
161
180
  const lower = m.toLowerCase();
162
- if (isValidMode(lower) || lower === "off") return lower;
181
+ if (lower === "off") return "off";
182
+ const canon = canonicalMode(lower);
183
+ if (canon) return canon;
163
184
  }
164
185
  }
165
186
  // 3. User config
@@ -168,25 +189,44 @@ function resolveDefault(): string {
168
189
  const m = readConfigMode(user);
169
190
  if (m) {
170
191
  const lower = m.toLowerCase();
171
- if (isValidMode(lower) || lower === "off") return lower;
192
+ if (lower === "off") return "off";
193
+ const canon = canonicalMode(lower);
194
+ if (canon) return canon;
172
195
  }
173
196
  }
174
197
  // 4. Default
175
- return "full";
198
+ return "caveman";
176
199
  }
177
200
 
178
201
  // ── Flag I/O ────────────────────────────────────────────────────────────────
179
202
 
180
- function readFlag(): string | null {
203
+ export function readFlag(): Mode | null {
204
+ const flagPath = getFlagPath();
181
205
  try {
182
- const content = readFileSync(flagPath, "utf-8").trim();
183
- return isValidMode(content) ? content : null;
184
- } catch {
185
- return null;
186
- }
206
+ if (existsSync(flagPath)) {
207
+ const content = readFileSync(flagPath, "utf-8").trim();
208
+ return canonicalMode(content);
209
+ }
210
+ } catch {}
211
+
212
+ // Fallback: cross-host check if running under omp but flag written in ~/.pi (or vice versa)
213
+ try {
214
+ const xdg = process.env.XDG_CONFIG_HOME;
215
+ const fallbackDir = flagPath.includes(".omp")
216
+ ? (xdg ? join(xdg, "pi") : join(homedir(), ".pi"))
217
+ : (xdg ? join(xdg, "omp") : join(homedir(), ".omp"));
218
+ const fallbackPath = join(fallbackDir, ".caveman-active");
219
+ if (existsSync(fallbackPath)) {
220
+ const content = readFileSync(fallbackPath, "utf-8").trim();
221
+ return canonicalMode(content);
222
+ }
223
+ } catch {}
224
+
225
+ return null;
187
226
  }
188
227
 
189
- function writeFlag(mode: string): void {
228
+ export function writeFlag(mode: Mode): void {
229
+ const flagPath = getFlagPath();
190
230
  try {
191
231
  const dir = dirname(flagPath);
192
232
  if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
@@ -198,15 +238,24 @@ function writeFlag(mode: string): void {
198
238
  }
199
239
  }
200
240
 
201
- function deleteFlag(): void {
241
+ export function deleteFlag(): void {
242
+ const flagPath = getFlagPath();
202
243
  try { if (existsSync(flagPath)) unlinkSync(flagPath); } catch {}
244
+ try {
245
+ const xdg = process.env.XDG_CONFIG_HOME;
246
+ const fallbackDir = flagPath.includes(".omp")
247
+ ? (xdg ? join(xdg, "pi") : join(homedir(), ".pi"))
248
+ : (xdg ? join(xdg, "omp") : join(homedir(), ".omp"));
249
+ const fallbackPath = join(fallbackDir, ".caveman-active");
250
+ if (existsSync(fallbackPath)) unlinkSync(fallbackPath);
251
+ } catch {}
203
252
  }
204
253
 
205
- function logModeChange(newMode: string | null): void {
254
+ function logModeChange(newMode: Mode | null): void {
206
255
  try {
207
256
  const prev = readFlag();
208
257
  if (prev === newMode) return;
209
- const dir = dirname(flagPath);
258
+ const dir = dirname(getFlagPath());
210
259
  if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
211
260
  const entry = JSON.stringify({
212
261
  ts: new Date().toISOString(), mode: newMode, prev,
@@ -215,9 +264,21 @@ function logModeChange(newMode: string | null): void {
215
264
  } catch {}
216
265
  }
217
266
 
218
- // ── Mode switching ──────────────────────────────────────────────────────────
267
+ export function saveUserConfigMode(mode: string): void {
268
+ try {
269
+ const configDir = cavemanConfigDir();
270
+ const cfgPath = join(configDir, "config.json");
271
+ if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true });
272
+ let existing: Record<string, unknown> = {};
273
+ if (existsSync(cfgPath)) {
274
+ try { existing = JSON.parse(readFileSync(cfgPath, "utf-8")); } catch {}
275
+ }
276
+ existing.defaultMode = mode;
277
+ writeFileSync(cfgPath, JSON.stringify(existing, null, 2) + "\n", { mode: 0o600 });
278
+ } catch {}
279
+ }
219
280
 
220
- function applyMode(mode: string | "off"): void {
281
+ export function applyMode(mode: Mode | "off"): void {
221
282
  if (mode === "off") { logModeChange(null); deleteFlag(); }
222
283
  else { logModeChange(mode); writeFlag(mode); }
223
284
  }
@@ -225,158 +286,225 @@ function applyMode(mode: string | "off"): void {
225
286
  interface UI {
226
287
  hasUI: boolean;
227
288
  ui: {
228
- notify(msg: string, level: string): void;
289
+ notify(msg: string, level?: "info" | "warning" | "error"): void;
290
+ setStatus?(key: string, text: string | undefined): void;
229
291
  };
230
292
  }
231
293
 
232
294
  function notifyMode(ui: UI, mode: string): void {
233
295
  if (!ui.hasUI) return;
234
- const label = mode === "wenyan" ? "wenyan-full" : mode;
235
- ui.ui.notify(`caveman: ${label}`, "info");
296
+ ui.ui.notify(`caveman: ${mode}`, "info");
297
+ ui.ui.setStatus?.("caveman", undefined);
236
298
  }
237
299
 
238
300
  function clearStatus(ui: UI): void {
239
301
  if (!ui.hasUI) return;
302
+ ui.ui.setStatus?.("caveman", undefined);
240
303
  ui.ui.notify("caveman: off", "info");
241
304
  }
242
305
 
243
- // ── Mode parsing (mirrors caveman hooks/caveman-parse.js) ───────────────────
244
-
245
- function parseModeChange(promptRaw: string): string | "off" | null {
246
- let prompt = (promptRaw || "").trim();
247
- if (!prompt) return null;
306
+ // ── SKILL.md and Thesis loading (mirrors caveman 3.2.0) ─────────────────────
248
307
 
249
- prompt = prompt.toLowerCase().replace(/\s+/g, " ");
250
-
251
- // Natural-language deactivation (checked first)
252
- const wantsOff =
253
- /\b(stop|disable|deactivate|quit|exit|kill)\s+(the\s+)?caveman\b/.test(prompt) ||
254
- /\bcaveman(\s+mode)?\s+(off|stop|disabled?)\b/.test(prompt) ||
255
- /\bturn\s+off\s+(the\s+)?caveman\b/.test(prompt) ||
256
- /^(please\s+)?(go\s+|back\s+to\s+|switch\s+(back\s+)?to\s+|return\s+to\s+)?normal\s+mode\b/.test(prompt) ||
257
- (/\bnormal\s+mode\b/.test(prompt) && /\bcaveman\b/.test(prompt));
258
-
259
- if (wantsOff) return "off";
260
-
261
- // Natural-language activation (exclude questions)
262
- const isQuestion =
263
- /^(what|whats|what's|how|why|when|where|who|does|do|did|is|are|can|could|would|should|tell me|explain)\b/.test(prompt);
264
-
265
- if (!isQuestion) {
266
- if (
267
- /\b(activate|enable|start|turn on|use|switch to|want|give me)\b[^.]{0,40}\bcaveman\b/.test(prompt) ||
268
- /\btalk like\b[^.]{0,40}\bcaveman\b/.test(prompt) ||
269
- /\bcaveman\s+mode\s+(on|please|now)\b/.test(prompt) ||
270
- /^caveman(\s+mode)?\s*[.!]*$/.test(prompt) ||
271
- /\b(less tokens|fewer tokens|be brief|be terse|shorter answers)\b(?!\s+(in|for|on|about|when|during|with)\b)/.test(prompt)
272
- ) {
273
- const mode = resolveDefault();
274
- return mode !== "off" ? mode : null;
275
- }
308
+ export function findSkillPath(skillId: string): string | null {
309
+ const candidates = [
310
+ join(__dirname, "..", "skills", skillId, "SKILL.md"),
311
+ join(__dirname, "skills", skillId, "SKILL.md"),
312
+ ];
313
+ for (const candidate of candidates) {
314
+ if (existsSync(candidate)) return candidate;
276
315
  }
316
+ return null;
317
+ }
277
318
 
278
- // Slash-command (support bare and namespaced /caveman:<cmd>)
279
- if (prompt.startsWith("/caveman")) {
280
- const parts = prompt.split(/\s+/);
281
- const cmd = parts[0];
282
- const arg = parts[1] || "";
319
+ export function loadSkillContent(mode: Mode): string | null {
320
+ const skillPath = findSkillPath(mode);
321
+ if (!skillPath) return null;
322
+ try {
323
+ const raw = readFileSync(skillPath, "utf-8");
324
+ return raw.replace(/^---[\s\S]*?---\s*/, "");
325
+ } catch {
326
+ return null;
327
+ }
328
+ }
283
329
 
284
- if (cmd === "/caveman-commit" || cmd === "/caveman:caveman-commit") return "commit";
285
- if (cmd === "/caveman-review" || cmd === "/caveman:caveman-review") return "review";
286
- if (cmd === "/caveman-compress" || cmd === "/caveman:caveman-compress") return "compress";
330
+ export const FALLBACK_THESIS: Record<Mode, string> = {
331
+ caveman: "Respond terse like smart caveman. All technical substance stay. Only fluff die.",
332
+ ultracave: "Respond terse like smart caveman. All technical substance stay. Only fluff die. Then cut again.",
333
+ megacave: "以文言答。技術之實皆存,唯贅言去之。",
334
+ };
287
335
 
288
- if (cmd === "/caveman" || cmd === "/caveman:caveman") {
289
- if (!arg) {
290
- const mode = resolveDefault();
291
- return mode === "off" ? "off" : mode;
336
+ export function getThesisLine(mode: Mode): string {
337
+ const skillPath = findSkillPath(mode);
338
+ if (skillPath) {
339
+ try {
340
+ const raw = readFileSync(skillPath, "utf-8");
341
+ const body = raw.replace(/^---[\s\S]*?---\s*/, "");
342
+ const lines = body.split("\n");
343
+ const titleIndex = lines.findIndex((l) => l.trim().startsWith("# "));
344
+ if (titleIndex !== -1) {
345
+ for (let i = titleIndex + 1; i < lines.length; i++) {
346
+ const line = lines[i].trim();
347
+ if (line) return line;
348
+ }
292
349
  }
293
- if (arg === "off" || arg === "stop" || arg === "disable") return "off";
294
- if (arg === "wenyan-full") return "wenyan";
295
- if (isValidMode(arg) && !INDEPENDENT[arg]) return arg;
296
- return null; // unknown arg — don't silently overwrite
297
- }
350
+ } catch {}
298
351
  }
352
+ return FALLBACK_THESIS[mode] ?? FALLBACK_THESIS.caveman;
353
+ }
299
354
 
300
- return null;
355
+ export function reinforcementLine(mode: Mode): string {
356
+ const thesis = getThesisLine(mode);
357
+ return (
358
+ `CAVEMAN MODE ACTIVE (${mode}). ${thesis} ` +
359
+ "Answer only what was asked: no unrequested background, lists, examples, walkthroughs, or follow-up offers; " +
360
+ "give code, steps, or warnings when the task needs them. " +
361
+ "Security warnings, irreversible actions, multi-step order: normal prose. " +
362
+ "Technical terms, code, commands, paths, and errors stay exact."
363
+ );
301
364
  }
302
365
 
303
- // ── SKILL.md loading (mirrors caveman-activate.js) ──────────────────────────
366
+ // ── Mode parsing (mirrors caveman hooks/caveman-parse.js) ───────────────────
304
367
 
305
- // Resolve SKILL.md path — try relative to this extension file first, then skills dir
306
- const SKILL_CANDIDATES = [
307
- join(__dirname, "..", "skills", "caveman", "SKILL.md"),
308
- join(__dirname, "skills", "caveman", "SKILL.md"),
309
- ];
368
+ const QUOTED_SPAN_REGEX = /(["`])(?:(?!\1).)*\1/g;
310
369
 
311
- function findSkillPath(): string | null {
312
- for (const candidate of SKILL_CANDIDATES) {
313
- if (existsSync(candidate)) return candidate;
314
- }
315
- return null;
370
+ export function normalizeModeArg(arg: string): string {
371
+ return (arg || "").replace(/^[^a-z0-9]+/, "").replace(/[^a-z0-9-]+$/, "");
316
372
  }
317
373
 
318
- // Load and filter SKILL.md content for the active mode.
319
- // Mirrors caveman-activate.js: strips frontmatter, keeps only the active
320
- // level's table row and example lines.
321
- function loadFilteredSkillContent(mode: string): string | null {
322
- const skillPath = findSkillPath();
323
- if (!skillPath) return null;
374
+ export interface ModeResolution {
375
+ action: "set" | "clear" | "status" | "unresolved";
376
+ mode?: Mode;
377
+ }
324
378
 
325
- try {
326
- const raw = readFileSync(skillPath, "utf-8");
327
- // Strip YAML frontmatter
328
- const body = raw.replace(/^---[\s\S]*?---\s*/, "");
329
- const modeLabel = mode === "wenyan" ? "wenyan-full" : mode;
330
-
331
- // Filter: keep header rows + only the active level's row
332
- const filtered = body.split("\n").reduce<string[]>((acc, line) => {
333
- // Intensity table rows start with | **level** |
334
- const tableRowMatch = line.match(/^\|\s*\*\*(\S+?)\*\*\s*\|/);
335
- if (tableRowMatch) {
336
- if (tableRowMatch[1] === modeLabel) acc.push(line);
337
- return acc;
338
- }
339
- // Example lines start with "- level:"
340
- const exampleMatch = line.match(/^- (\S+?):\s/);
341
- if (exampleMatch) {
342
- if (exampleMatch[1] === modeLabel) acc.push(line);
343
- return acc;
344
- }
345
- acc.push(line);
346
- return acc;
347
- }, []);
379
+ export function resolveModeArg(rawArg: string, getDefault: () => Mode | "off"): ModeResolution {
380
+ const arg = normalizeModeArg(rawArg);
381
+ if (!arg) {
382
+ if (rawArg) return { action: "unresolved" };
383
+ const def = getDefault();
384
+ return def === "off" ? { action: "clear" } : { action: "set", mode: def };
385
+ }
386
+ if (arg === "off" || arg === "stop" || arg === "disable") return { action: "clear" };
387
+ if (arg === "status") return { action: "status" };
388
+ const canon = canonicalMode(arg);
389
+ if (canon) return { action: "set", mode: canon };
390
+ return { action: "unresolved" };
391
+ }
348
392
 
349
- return filtered.join("\n");
350
- } catch {
351
- return null;
393
+ // Whitelist gap between activation verb and "caveman" to prevent false positives
394
+ const ACTIVATION_VERBS = "(?:activate|enable|start|turn on|use|switch to|want|give me)";
395
+ const ACTIVATION_GAP = "(?:\\s+(?:the|to|into|on|in|please|now|it|me|my|this|that|mode))*";
396
+ const ACTIVATION_VERB_PHRASE = new RegExp(
397
+ "\\b" + ACTIVATION_VERBS + "\\b" + ACTIVATION_GAP + "\\s+caveman\\b"
398
+ );
399
+ const ACTIVATION_TALK_LIKE = /\btalk\s+like\s+(?:a\s+|an\s+|the\s+)?caveman\b/;
400
+
401
+ // Negation guard: "don't activate caveman" must not activate caveman
402
+ const NEGATOR = /\b(?:don['’]?t|do not|doesn['’]?t|does not|won['’]?t|will not|never|no need to|rather not)\b/;
403
+ const CLAUSE_BOUNDARY = /[.;!?,:—–]|\s-+\s|\bbut\b|\bthen\b/g;
404
+
405
+ export function negatedBefore(text: string, index: number): boolean {
406
+ CLAUSE_BOUNDARY.lastIndex = 0;
407
+ let clauseStart = 0;
408
+ let m: RegExpExecArray | null;
409
+ while ((m = CLAUSE_BOUNDARY.exec(text)) !== null) {
410
+ if (m.index >= index) break;
411
+ clauseStart = m.index + m[0].length;
352
412
  }
413
+ return NEGATOR.test(text.slice(clauseStart, index));
353
414
  }
354
415
 
355
- // ── Reinforcement line ──────────────────────────────────────────────────────
416
+ const BREVITY_TRIGGER = /\b(less tokens|fewer tokens|be brief|be terse|shorter answers)\b(?!\s+(in|for|on|about|when|during|with)\b)/;
417
+
418
+ const ACTIVATION_TRIGGERS: RegExp[] = [
419
+ ACTIVATION_VERB_PHRASE,
420
+ ACTIVATION_TALK_LIKE,
421
+ /\bcaveman\s+mode\s+(on|please|now)\b/,
422
+ /^caveman(\s+mode)?\s*[.!]*$/,
423
+ BREVITY_TRIGGER,
424
+ ].map((re) => new RegExp(re.source, re.flags.includes("g") ? re.flags : re.flags + "g"));
425
+
426
+ export function wantsActivation(text: string): boolean {
427
+ for (const re of ACTIVATION_TRIGGERS) {
428
+ re.lastIndex = 0;
429
+ let m: RegExpExecArray | null;
430
+ while ((m = re.exec(text)) !== null) {
431
+ if (!negatedBefore(text, m.index)) return true;
432
+ if (m.index === re.lastIndex) re.lastIndex++;
433
+ }
434
+ }
435
+ return false;
436
+ }
356
437
 
357
- function reinforcementLine(mode: string): string {
358
- const label = mode === "wenyan" ? "wenyan-full" : mode;
359
- const wenyanHint = mode.startsWith("wenyan")
360
- ? " MUST respond in 文言文 (classical Chinese). Use classical particles (之/乃/為/其), omit subjects, verbs precede objects."
361
- : "";
362
- return (
363
- `[CAVEMAN ACTIVE — intensity: ${label}.${wenyanHint} ` +
364
- "Respond terse like smart caveman. All technical substance stay. " +
365
- "Only fluff die. Fragments OK. Short synonyms. " +
366
- "No filler/hedging/pleasantries. Code unchanged. Technical terms exact.]"
367
- );
438
+ export function parseModeChange(promptRaw: string): Mode | "off" | null {
439
+ let prompt = (promptRaw || "").trim();
440
+ if (!prompt) return null;
441
+
442
+ const collapsed = prompt.toLowerCase().replace(/\s+/g, " ");
443
+ const naturalLanguage = !prompt.startsWith("/");
444
+ const nlPrompt = naturalLanguage ? collapsed.replace(QUOTED_SPAN_REGEX, " ") : "";
445
+
446
+ // Natural-language deactivation (checked first)
447
+ if (naturalLanguage) {
448
+ const wantsOff =
449
+ /\b(stop|disable|deactivate|quit|exit|kill)\s+(the\s+)?caveman\b/.test(nlPrompt) ||
450
+ /\bcaveman(\s+mode)?\s+(off|stop|disabled?)\b/.test(nlPrompt) ||
451
+ /\bturn\s+off\s+(the\s+)?caveman\b/.test(nlPrompt) ||
452
+ /^(please\s+)?(go\s+|back\s+to\s+|switch\s+(back\s+)?to\s+|return\s+to\s+)?normal\s+mode\b/.test(nlPrompt) ||
453
+ (/\bnormal\s+mode\b/.test(nlPrompt) && /\bcaveman\b/.test(nlPrompt));
454
+
455
+ if (wantsOff) return "off";
456
+
457
+ // Direct invocation keywords
458
+ const ultraIdx = nlPrompt.search(/\bultracave\b/);
459
+ if (ultraIdx !== -1 && !negatedBefore(nlPrompt, ultraIdx)) {
460
+ return "ultracave";
461
+ }
462
+ const megaIdx = nlPrompt.search(/\bmegacave\b/);
463
+ if (megaIdx !== -1 && !negatedBefore(nlPrompt, megaIdx)) {
464
+ return "megacave";
465
+ }
466
+
467
+ // Natural-language activation (exclude questions)
468
+ const isQuestion =
469
+ /^(what|whats|what's|how|why|when|where|who|does|do|did|is|are|can|could|would|should|tell me|explain)\b/.test(nlPrompt);
470
+
471
+ if (!isQuestion && wantsActivation(nlPrompt)) {
472
+ const def = resolveDefault();
473
+ return def !== "off" ? def : null;
474
+ }
475
+ }
476
+
477
+ // Slash commands
478
+ if (prompt.startsWith("/")) {
479
+ const parts = prompt.split(/\s+/);
480
+ const cmd = parts[0].toLowerCase();
481
+ const rawArg = parts[1] || "";
482
+
483
+ if (cmd === "/ultracave" || cmd === "/caveman:ultracave") {
484
+ return "ultracave";
485
+ }
486
+ if (cmd === "/megacave" || cmd === "/caveman:megacave") {
487
+ return "megacave";
488
+ }
489
+ if (cmd === "/caveman" || cmd === "/caveman:caveman") {
490
+ const res = resolveModeArg(rawArg, resolveDefault);
491
+ if (res.action === "set" && res.mode) return res.mode;
492
+ if (res.action === "clear") return "off";
493
+ return null;
494
+ }
495
+ }
496
+
497
+ return null;
368
498
  }
369
499
 
370
500
  // ── Argument completions ────────────────────────────────────────────────────
371
501
 
372
502
  const MODE_CHOICES = [
373
- { value: "lite", label: "lite", description: "no filler/hedging, keep articles" },
374
- { value: "full", label: "full", description: "drop articles, fragments OK (default)" },
375
- { value: "ultra", label: "ultra", description: "one word when one word enough" },
376
- { value: "wenyan-lite", label: "wenyan-lite", description: "semi-classical, keep grammar" },
377
- { value: "wenyan", label: "wenyan", description: "maximum classical terseness (文言文)" },
378
- { value: "wenyan-ultra",label: "wenyan-ultra", description: "extreme abbreviation, classical feel" },
379
- { value: "off", label: "off", description: "disabled" },
503
+ { value: "caveman", label: "caveman", description: "smart caveman voice (default)" },
504
+ { value: "ultracave", label: "ultracave", description: "maximum compression, grammar stripped" },
505
+ { value: "megacave", label: "megacave", description: "Classical Chinese (文言文)" },
506
+ { value: "status", label: "status", description: "show current mode and stats" },
507
+ { value: "off", label: "off", description: "disabled" },
380
508
  ];
381
509
 
382
510
  function getModeCompletions(prefix: string) {
@@ -387,15 +515,80 @@ function getModeCompletions(prefix: string) {
387
515
  return matches.length > 0 ? matches : null;
388
516
  }
389
517
 
518
+ // ── Status display ──────────────────────────────────────────────────────────
519
+
520
+ function displayStatus(
521
+ pi: ExtensionAPI,
522
+ ctx: { hasUI: boolean; ui: { notify(msg: string, level?: "info" | "warning" | "error"): void } },
523
+ ): void {
524
+ const active = readFlag();
525
+ const def = resolveDefault();
526
+ const configPath = join(cavemanConfigDir(), "config.json");
527
+ const repoConfig = findRepoConfig(process.cwd());
528
+ const mode = active || "off";
529
+
530
+ const mc = modeColor(mode);
531
+
532
+ const lines: string[] = [
533
+ `${BOLD}Caveman${RST}: ${mc}${mode}${RST}${def !== mode ? ` ${DIM}(default: ${def})${RST}` : ""}`,
534
+ "",
535
+ ` ${sessionStats.turns} turns ${DIM}│${RST} ${sessionStats.outputTokens.toLocaleString()} out ${DIM}│${RST} ${sessionStats.cacheReadTokens.toLocaleString()} cached ${DIM}│${RST} ${sessionStats.inputTokens.toLocaleString()} in`,
536
+ ];
537
+
538
+ const savings = estimateSavings(sessionStats.outputTokens, mode);
539
+ if (savings && savings.estSaved > 0) {
540
+ lines.push(
541
+ "",
542
+ ` saved ${GREEN}${savings.estSaved.toLocaleString()}${RST} tokens ${DIM}(~${savings.pct}%)${RST} ${GREEN}${bar(savings.pct)}${RST}`,
543
+ );
544
+ }
545
+
546
+ const configLines: string[] = [];
547
+ if (process.env.CAVEMAN_DEFAULT_MODE) {
548
+ configLines.push(` env ${DIM}CAVEMAN_DEFAULT_MODE=${process.env.CAVEMAN_DEFAULT_MODE}${RST}`);
549
+ }
550
+ if (existsSync(configPath)) configLines.push(` user ${DIM}${truncatePath(configPath)}${RST}`);
551
+ if (repoConfig) configLines.push(` repo ${DIM}${truncatePath(repoConfig)}${RST}`);
552
+ configLines.push(` flag ${DIM}${truncatePath(getFlagPath())}${RST}`);
553
+
554
+ if (configLines.length) {
555
+ lines.push("", ...configLines);
556
+ }
557
+
558
+ const msg = lines.join("\n");
559
+ if (ctx.hasUI) ctx.ui.notify(msg, "info");
560
+ pi.sendMessage({
561
+ content: msg,
562
+ attribution: "user",
563
+ }, { triggerTurn: false });
564
+ }
565
+
390
566
  // ── Extension factory ───────────────────────────────────────────────────────
391
567
 
392
568
  export default function cavemanExtension(pi: ExtensionAPI) {
569
+ let lastInjectedMode: Mode | null = null;
570
+
393
571
  // ── session_start: auto-activate ──────────────────────────────────────
394
- pi.on("session_start", async (_event, ctx) => {
395
- sessionStats = { turns: 0, outputTokens: 0, cacheReadTokens: 0, inputTokens: 0 };
396
- sessionExplicitOff = false;
397
- const mode = resolveDefault();
398
- if (mode === "off") { deleteFlag(); return; }
572
+ pi.on("session_start", async (event, ctx) => {
573
+ const e = event as Record<string, unknown> | undefined;
574
+ const reason = e?.reason as string | undefined;
575
+ const isContinuation = reason === "resume" || reason === "reload" || reason === "fork";
576
+ if (!isContinuation) {
577
+ sessionStats = { turns: 0, outputTokens: 0, cacheReadTokens: 0, inputTokens: 0 };
578
+ sessionExplicitOff = false;
579
+ lastInjectedMode = null;
580
+ }
581
+
582
+ let mode = readFlag();
583
+ if (!mode && !sessionExplicitOff) {
584
+ const def = resolveDefault();
585
+ if (def !== "off") mode = def;
586
+ }
587
+ if (!mode || (mode as string) === "off") {
588
+ deleteFlag();
589
+ clearStatus(ctx);
590
+ return;
591
+ }
399
592
  applyMode(mode);
400
593
  notifyMode(ctx, mode);
401
594
  });
@@ -415,216 +608,123 @@ export default function cavemanExtension(pi: ExtensionAPI) {
415
608
 
416
609
  // ── /caveman command ──────────────────────────────────────────────────
417
610
  pi.registerCommand("caveman", {
418
- description: "Switch caveman mode (lite|full|ultra|wenyan|off)",
611
+ description: "Switch and persist caveman mode (caveman|ultracave|megacave|status|off)",
419
612
  getArgumentCompletions: (prefix) => getModeCompletions(prefix),
420
613
  handler: async (args, ctx) => {
421
- const arg = (args || "").trim().toLowerCase();
614
+ const rawArg = (args || "").trim();
422
615
 
423
- // No arg → activate default
424
- if (!arg) {
425
- const mode = resolveDefault();
426
- if (mode === "off") { deleteFlag(); return; }
616
+ // Bare /caveman -> activate default and persist
617
+ if (!rawArg) {
618
+ const def = resolveDefault();
619
+ const mode = def === "off" ? "caveman" : def;
620
+ sessionExplicitOff = false;
621
+ lastInjectedMode = null;
427
622
  applyMode(mode);
623
+ saveUserConfigMode(mode);
428
624
  notifyMode(ctx, mode);
429
625
  return;
430
626
  }
431
627
 
432
- // Off
433
- if (arg === "off" || arg === "stop" || arg === "disable") {
434
- sessionExplicitOff = true;
435
- applyMode("off");
436
- clearStatus(ctx);
628
+ const res = resolveModeArg(rawArg, resolveDefault);
629
+
630
+ if (res.action === "status") {
631
+ displayStatus(pi, ctx);
437
632
  return;
438
633
  }
439
634
 
440
- // Wenyan alias
441
- if (arg === "wenyan-full") {
442
- applyMode("wenyan");
443
- if (ctx.hasUI) {
444
- ctx.ui.notify("caveman: wenyan-full", "info");
445
- }
635
+ if (res.action === "set" && res.mode) {
636
+ sessionExplicitOff = false;
637
+ lastInjectedMode = null;
638
+ applyMode(res.mode);
639
+ saveUserConfigMode(res.mode);
640
+ notifyMode(ctx, res.mode);
446
641
  return;
447
642
  }
448
643
 
449
- // Valid mode
450
- if (isValidMode(arg) && !INDEPENDENT[arg]) {
451
- applyMode(arg);
452
- notifyMode(ctx, arg);
644
+ if (res.action === "clear") {
645
+ sessionExplicitOff = true;
646
+ lastInjectedMode = null;
647
+ applyMode("off");
648
+ saveUserConfigMode("off");
649
+ clearStatus(ctx);
453
650
  return;
454
651
  }
455
652
 
456
653
  // Unknown
457
654
  if (ctx.hasUI) {
458
655
  ctx.ui.notify(
459
- `unknown mode "${arg}". Use: lite|full|ultra|wenyan-lite|wenyan|wenyan-ultra|off`,
656
+ `unknown mode "${rawArg}". Use: caveman|ultracave|megacave|status|off`,
460
657
  "warning",
461
658
  );
462
659
  }
463
660
  },
464
661
  });
465
662
 
466
- // ── /caveman-status command ────────────────────────────────────────────
467
- pi.registerCommand("caveman-status", {
468
- description: "Show current caveman mode and config",
663
+ // ── /ultracave command ────────────────────────────────────────────────
664
+ pi.registerCommand("ultracave", {
665
+ description: "Switch to ultracave mode (maximum compression, fragments only)",
469
666
  handler: async (_args, ctx) => {
470
- const active = readFlag();
471
- const def = resolveDefault();
472
- const configPath = join(cavemanConfigDir(), "config.json");
473
- const repoConfig = findRepoConfig(process.cwd());
474
- const mode = active || "off";
475
-
476
- const mc = modeColor(mode);
477
- const modeLabel = mode === "wenyan" ? "wenyan-full" : mode;
478
- const defLabel = def === "wenyan" ? "wenyan-full" : def;
479
-
480
- const lines: string[] = [
481
- `${BOLD}Caveman${RST}: ${mc}${modeLabel}${RST}${def !== mode ? ` ${DIM}(default: ${defLabel})${RST}` : ""}`,
482
- "",
483
- ` ${sessionStats.turns} turns ${DIM}│${RST} ${sessionStats.outputTokens.toLocaleString()} out ${DIM}│${RST} ${sessionStats.cacheReadTokens.toLocaleString()} cached ${DIM}│${RST} ${sessionStats.inputTokens.toLocaleString()} in`,
484
- ];
485
-
486
- const savings = estimateSavings(sessionStats.outputTokens, mode);
487
- if (savings && savings.estSaved > 0) {
488
- lines.push(
489
- "",
490
- ` saved ${GREEN}${savings.estSaved.toLocaleString()}${RST} tokens ${DIM}(~${savings.pct}%)${RST} ${GREEN}${bar(savings.pct)}${RST}`,
491
- );
492
- }
493
-
494
- const configLines: string[] = [];
495
- if (process.env.CAVEMAN_DEFAULT_MODE) {
496
- configLines.push(` env ${DIM}CAVEMAN_DEFAULT_MODE=${process.env.CAVEMAN_DEFAULT_MODE}${RST}`);
497
- }
498
- if (existsSync(configPath)) configLines.push(` user ${DIM}${truncatePath(configPath)}${RST}`);
499
- if (repoConfig) configLines.push(` repo ${DIM}${truncatePath(repoConfig)}${RST}`);
500
- configLines.push(` flag ${DIM}${truncatePath(flagPath)}${RST}`);
501
-
502
- if (configLines.length) {
503
- lines.push("", ...configLines);
504
- }
505
-
506
- const msg = lines.join("\n");
507
- if (ctx.hasUI) ctx.ui.notify(msg, "info");
508
- pi.sendMessage({
509
- content: msg,
510
- attribution: "user",
511
- }, { triggerTurn: false });
667
+ sessionExplicitOff = false;
668
+ lastInjectedMode = null;
669
+ applyMode("ultracave");
670
+ saveUserConfigMode("ultracave");
671
+ notifyMode(ctx, "ultracave");
512
672
  },
513
673
  });
514
674
 
515
- // ── /caveman-config command ──────────────────────────────────────────
516
- const INTENSITY_MODES = ["lite", "full", "ultra", "wenyan-lite", "wenyan", "wenyan-ultra", "off"];
517
-
518
- pi.registerCommand("caveman-config", {
519
- description: "Set default caveman mode for new sessions",
520
- getArgumentCompletions: (prefix) => getModeCompletions(prefix),
521
- handler: async (args, ctx) => {
522
- const arg = (args || "").trim().toLowerCase();
523
-
524
- // No arg → show current config + available options
525
- if (!arg) {
526
- const def = resolveDefault();
527
- const configPath = join(cavemanConfigDir(), "config.json");
528
- const repoConfig = findRepoConfig(process.cwd());
529
-
530
- const lines: string[] = [
531
- `Current default: ${def}`,
532
- "",
533
- "Available modes:",
534
- " lite — no filler/hedging, keep articles + full sentences",
535
- " full — drop articles, fragments OK, short synonyms (default)",
536
- " ultra — one word when one word enough, no abbreviations",
537
- " wenyan-lite — semi-classical, keep grammar structure",
538
- " wenyan — maximum classical terseness (文言文)",
539
- " wenyan-ultra — extreme abbreviation, classical feel",
540
- " off — disabled by default",
541
- "",
542
- "Usage: /caveman-config <mode>",
543
- `Config file: ${configPath}`,
544
- ];
545
- if (process.env.CAVEMAN_DEFAULT_MODE) {
546
- lines.push(`Note: CAVEMAN_DEFAULT_MODE=${process.env.CAVEMAN_DEFAULT_MODE} overrides config file`);
547
- }
548
- if (repoConfig) {
549
- lines.push(`Note: repo config at ${repoConfig} overrides user config`);
550
- }
551
-
552
- const msg = lines.join("\n");
553
- if (ctx.hasUI) ctx.ui.notify(msg, "info");
554
- pi.sendMessage({
555
- customType: "caveman-config",
556
- content: msg,
557
- display: true,
558
- attribution: "user",
559
- }, { triggerTurn: false });
560
- return;
561
- }
562
-
563
- // Validate
564
- if (!isValidMode(arg) && arg !== "off") {
565
- if (ctx.hasUI) {
566
- ctx.ui.notify(
567
- `unknown mode "${arg}". Available: ${INTENSITY_MODES.join(", ")}`,
568
- "warning",
569
- );
570
- }
571
- return;
572
- }
573
-
574
- // Write to user config
575
- const configDir = cavemanConfigDir();
576
- const cfgPath = join(configDir, "config.json");
577
-
578
- try {
579
- if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true });
580
-
581
- let existing: Record<string, unknown> = {};
582
- if (existsSync(cfgPath)) {
583
- try { existing = JSON.parse(readFileSync(cfgPath, "utf-8")); } catch {}
584
- }
585
- existing.defaultMode = arg;
586
- writeFileSync(cfgPath, JSON.stringify(existing, null, 2) + "\n", { mode: 0o600 });
675
+ // ── /megacave command ─────────────────────────────────────────────────
676
+ pi.registerCommand("megacave", {
677
+ description: "Switch to megacave mode (Classical Chinese 文言文)",
678
+ handler: async (_args, ctx) => {
679
+ sessionExplicitOff = false;
680
+ lastInjectedMode = null;
681
+ applyMode("megacave");
682
+ saveUserConfigMode("megacave");
683
+ notifyMode(ctx, "megacave");
684
+ },
685
+ });
587
686
 
588
- const label = arg === "off" ? "off" : arg;
589
- if (ctx.hasUI) {
590
- ctx.ui.notify(`default mode set to: ${label}`, "info");
591
- ctx.ui.notify(`config: ${cfgPath}`, "info");
592
- }
593
- pi.sendMessage({
594
- customType: "caveman-config",
595
- content: `Default mode saved: ${label}\nConfig: ${cfgPath}\nEffective on next session.`,
596
- display: true,
597
- attribution: "user",
598
- }, { triggerTurn: false });
599
- } catch (e) {
600
- if (ctx.hasUI) ctx.ui.notify(`failed to write config: ${e}`, "error");
601
- }
687
+ // ── /caveman-status command ────────────────────────────────────────────
688
+ pi.registerCommand("caveman-status", {
689
+ description: "Show current caveman mode and config",
690
+ handler: async (_args, ctx) => {
691
+ displayStatus(pi, ctx);
602
692
  },
603
693
  });
604
694
 
605
695
  // ── before_agent_start: per-turn reinforcement ────────────────────────
606
- // Injects full SKILL.md content (filtered to active mode) + reinforcement line.
607
- // Mirrors caveman-activate.js behavior: the model sees the complete ruleset
608
- // on every turn, not just a one-line reminder.
696
+ // Injects full SKILL.md content on activation / mode-switch.
697
+ // Subsequent continuing turns use a lightweight single-line reminder to preserve tokens & prompt cache.
609
698
  pi.on("before_agent_start", async (_event, _ctx) => {
610
699
  let active = readFlag();
611
- if (!active && !sessionExplicitOff) active = resolveDefault();
612
- if (!active || active === "off" || INDEPENDENT[active]) return null;
613
-
614
- const skillContent = loadFilteredSkillContent(active);
615
- const header = `CAVEMAN MODE ACTIVE — level: ${active === "wenyan" ? "wenyan-full" : active}\n\n`;
700
+ if (!active && !sessionExplicitOff) {
701
+ const def = resolveDefault();
702
+ if (def !== "off") active = def;
703
+ }
704
+ if (!active || (active as string) === "off") {
705
+ lastInjectedMode = null;
706
+ return null;
707
+ }
616
708
 
617
- // If SKILL.md found, inject full filtered content; fall back to reinforcement line
618
- const content = skillContent
619
- ? header + skillContent
620
- : reinforcementLine(active);
709
+ const modeChanged = active !== lastInjectedMode;
710
+ lastInjectedMode = active;
711
+
712
+ let content: string;
713
+ if (modeChanged) {
714
+ const skillContent = loadSkillContent(active);
715
+ const header = `CAVEMAN MODE ACTIVE — mode: ${active}\n\n`;
716
+ content = skillContent
717
+ ? header + skillContent
718
+ : reinforcementLine(active);
719
+ } else {
720
+ content = reinforcementLine(active);
721
+ }
621
722
 
622
723
  return {
623
724
  message: {
624
725
  customType: "caveman-reinforcement",
625
726
  content,
626
727
  display: false,
627
- attribution: "system",
628
728
  },
629
729
  };
630
730
  });
@@ -636,9 +736,15 @@ export default function cavemanExtension(pi: ExtensionAPI) {
636
736
  if (typeof text !== "string") return;
637
737
  const change = parseModeChange(text);
638
738
  if (change) {
639
- if (change === "off") sessionExplicitOff = true;
739
+ if (change === "off") {
740
+ sessionExplicitOff = true;
741
+ lastInjectedMode = null;
742
+ } else {
743
+ sessionExplicitOff = false;
744
+ lastInjectedMode = null;
745
+ }
640
746
  applyMode(change);
747
+ saveUserConfigMode(change);
641
748
  }
642
749
  });
643
-
644
750
  }