@lornatang/dsh-caveman 0.1.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/CHANGELOG.md +16 -0
- package/LICENSE +202 -0
- package/LICENSE-MIT +21 -0
- package/NOTICE +51 -0
- package/README.md +218 -0
- package/README.zh.md +218 -0
- package/cordis.patch.yml +3 -0
- package/examples/caveman-anthropic.patch.yml +14 -0
- package/examples/caveman-auto.patch.yml +15 -0
- package/lib/attribution.js +24 -0
- package/lib/blocks.js +80 -0
- package/lib/cavecrew-git.js +83 -0
- package/lib/cavecrew.js +67 -0
- package/lib/compression.js +434 -0
- package/lib/index.js +127 -0
- package/lib/memory.js +35 -0
- package/lib/mode.js +71 -0
- package/lib/native.js +357 -0
- package/lib/runtime.js +199 -0
- package/lib/skills.js +75 -0
- package/lib/stats.js +189 -0
- package/lib/types/attribution.d.ts +8 -0
- package/lib/types/blocks.d.ts +12 -0
- package/lib/types/cavecrew-git.d.ts +5 -0
- package/lib/types/cavecrew.d.ts +10 -0
- package/lib/types/compression.d.ts +50 -0
- package/lib/types/index.d.ts +30 -0
- package/lib/types/memory.d.ts +3 -0
- package/lib/types/mode.d.ts +33 -0
- package/lib/types/native.d.ts +43 -0
- package/lib/types/runtime.d.ts +23 -0
- package/lib/types/skills.d.ts +3 -0
- package/lib/types/stats.d.ts +6 -0
- package/package.json +129 -0
- package/presets/cavecrew.patch.yml +54 -0
- package/scripts/benchmark.mjs +79 -0
- package/scripts/caveman-cli.mjs +30 -0
- package/scripts/learn-binary.mjs +82 -0
- package/scripts/learn-checksums.json +29 -0
- package/vendor/caveman/LICENSE +202 -0
- package/vendor/caveman/LICENSE-MIT +21 -0
- package/vendor/caveman/NOTICE +49 -0
- package/vendor/caveman/agents/cavecrew-builder.md +46 -0
- package/vendor/caveman/agents/cavecrew-investigator.md +56 -0
- package/vendor/caveman/agents/cavecrew-reviewer.md +47 -0
- package/vendor/caveman/skills/activation-rule.mjs +43 -0
- package/vendor/caveman/skills/cavecrew/README.md +67 -0
- package/vendor/caveman/skills/cavecrew/SKILL.md +78 -0
- package/vendor/caveman/skills/caveman/README.md +68 -0
- package/vendor/caveman/skills/caveman/SKILL.md +89 -0
- package/vendor/caveman/skills/caveman-commit/README.md +44 -0
- package/vendor/caveman/skills/caveman-commit/SKILL.md +63 -0
- package/vendor/caveman/skills/caveman-compress/README.md +262 -0
- package/vendor/caveman/skills/caveman-compress/SECURITY.md +55 -0
- package/vendor/caveman/skills/caveman-compress/SKILL.md +114 -0
- package/vendor/caveman/skills/caveman-compress/scripts/__init__.py +9 -0
- package/vendor/caveman/skills/caveman-compress/scripts/__main__.py +3 -0
- package/vendor/caveman/skills/caveman-compress/scripts/benchmark.py +80 -0
- package/vendor/caveman/skills/caveman-compress/scripts/cli.py +94 -0
- package/vendor/caveman/skills/caveman-compress/scripts/compress.py +1331 -0
- package/vendor/caveman/skills/caveman-compress/scripts/detect.py +192 -0
- package/vendor/caveman/skills/caveman-compress/scripts/validate.py +440 -0
- package/vendor/caveman/skills/caveman-discover/SKILL.md +115 -0
- package/vendor/caveman/skills/caveman-evidence-review/SKILL.md +142 -0
- package/vendor/caveman/skills/caveman-explore/SKILL.md +42 -0
- package/vendor/caveman/skills/caveman-explore/package.json +12 -0
- package/vendor/caveman/skills/caveman-explore/tests/skill-file.test.mjs +44 -0
- package/vendor/caveman/skills/caveman-help/README.md +39 -0
- package/vendor/caveman/skills/caveman-help/SKILL.md +62 -0
- package/vendor/caveman/skills/caveman-learn/CLAUDE.md +32 -0
- package/vendor/caveman/skills/caveman-learn/README.md +38 -0
- package/vendor/caveman/skills/caveman-learn/SKILL.md +185 -0
- package/vendor/caveman/skills/caveman-learn/package.json +12 -0
- package/vendor/caveman/skills/caveman-learn/tests/index.js +1 -0
- package/vendor/caveman/skills/caveman-learn/tests/skill-file.test.mjs +54 -0
- package/vendor/caveman/skills/caveman-manage/SKILL.md +112 -0
- package/vendor/caveman/skills/caveman-optimize/SKILL.md +111 -0
- package/vendor/caveman/skills/caveman-review/README.md +33 -0
- package/vendor/caveman/skills/caveman-review/SKILL.md +53 -0
- package/vendor/caveman/skills/caveman-setup/SKILL.md +222 -0
- package/vendor/caveman/skills/caveman-stats/README.md +48 -0
- package/vendor/caveman/skills/caveman-stats/SKILL.md +17 -0
- package/vendor/caveman/skills/compile.mjs +298 -0
- package/vendor/caveman/skills/engine-mcp-tools.json +10 -0
- package/vendor/caveman/skills/generated/aider/pack.json +163 -0
- package/vendor/caveman/skills/generated/claude/pack.json +163 -0
- package/vendor/caveman/skills/generated/codex/pack.json +163 -0
- package/vendor/caveman/skills/generated/gemini/pack.json +163 -0
- package/vendor/caveman/skills/generated/hermes/pack.json +163 -0
- package/vendor/caveman/skills/generated/opencode/pack.json +163 -0
- package/vendor/caveman/skills/investigate-first/SKILL.md +16 -0
- package/vendor/caveman/skills/investigate-first/agents/openai.yaml +4 -0
- package/vendor/caveman/skills/lean-build/SKILL.md +18 -0
- package/vendor/caveman/skills/lean-build/agents/openai.yaml +4 -0
- package/vendor/caveman/skills/megacave/README.md +11 -0
- package/vendor/caveman/skills/megacave/SKILL.md +65 -0
- package/vendor/caveman/skills/migration/SKILL.md +17 -0
- package/vendor/caveman/skills/migration/agents/openai.yaml +4 -0
- package/vendor/caveman/skills/native/native-core.md +16 -0
- package/vendor/caveman/skills/registry.json +283 -0
- package/vendor/caveman/skills/safe-refactor/SKILL.md +16 -0
- package/vendor/caveman/skills/safe-refactor/agents/openai.yaml +4 -0
- package/vendor/caveman/skills/surgical-patch/SKILL.md +16 -0
- package/vendor/caveman/skills/surgical-patch/agents/openai.yaml +4 -0
- package/vendor/caveman/skills/ultracave/README.md +13 -0
- package/vendor/caveman/skills/ultracave/SKILL.md +63 -0
- package/vendor/caveman/skills/verbs-gate.mjs +213 -0
- package/vendor/caveman/skills/verify-and-stop/SKILL.md +16 -0
- package/vendor/caveman/skills/verify-and-stop/agents/openai.yaml +4 -0
- package/vendor/caveman/src/hooks/caveman-config.js +921 -0
- package/vendor/caveman/src/hooks/caveman-parse.js +342 -0
- package/vendor/caveman/src/hooks/package.json +3 -0
|
@@ -0,0 +1,921 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// caveman — shared configuration resolver
|
|
3
|
+
//
|
|
4
|
+
// KEEP THIS FILE LOADABLE WITHOUT THE MODULE LOADER. `src/plugins/opencode/
|
|
5
|
+
// plugin.js` cannot `require()` a file from disk (compiled Bun binary), so it
|
|
6
|
+
// reads this file's source and evaluates it through `new Function(...)` with a
|
|
7
|
+
// `createRequire` rooted at this file. Node built-ins (fs/path/os) resolve
|
|
8
|
+
// there; anything heavier does not. Consequence for mode-state work: keep it
|
|
9
|
+
// HERE. Parsing already lives in caveman-parse.js (#602) and is loaded the same
|
|
10
|
+
// way, so a second parser copy is no longer a risk — but a THIRD home for the
|
|
11
|
+
// state primitives would be, because opencode would keep its own drifting
|
|
12
|
+
// version of them (the drift #602 was created to end).
|
|
13
|
+
//
|
|
14
|
+
// Resolution order for default mode:
|
|
15
|
+
// 1. CAVEMAN_DEFAULT_MODE environment variable
|
|
16
|
+
// 2. Repo-local config (checked-in, per-project default):
|
|
17
|
+
// - <cwd>/.caveman/config.json
|
|
18
|
+
// - <cwd>/.caveman.json
|
|
19
|
+
// Walks up from process.cwd() to the nearest file that names a
|
|
20
|
+
// defaultMode (stops at filesystem root). A file without one — e.g. a
|
|
21
|
+
// .caveman/config.json holding only CLI settings — is skipped. Lets a
|
|
22
|
+
// team pin a project's default mode without polluting every
|
|
23
|
+
// contributor's user-level config or env.
|
|
24
|
+
// 3. User config file defaultMode field:
|
|
25
|
+
// - $XDG_CONFIG_HOME/caveman/config.json (any platform, if set; only file)
|
|
26
|
+
// - ~/.config/caveman/config.json (macOS / Linux fallback)
|
|
27
|
+
// - %APPDATA%\caveman\config.json, then ~/.config/caveman/config.json
|
|
28
|
+
// (Windows fallback; the docs give the ~/.config path everywhere)
|
|
29
|
+
// 4. 'caveman'
|
|
30
|
+
// Config files may carry a BOM, be UTF-16LE, or hold comments and trailing
|
|
31
|
+
// commas (see parseConfigFile).
|
|
32
|
+
//
|
|
33
|
+
// The per-turn reinforcement switch (`reinforce`, #1468) resolves through the
|
|
34
|
+
// same sources in the same order: CAVEMAN_REINFORCE → repo-local config →
|
|
35
|
+
// user config → on. See getReinforce.
|
|
36
|
+
|
|
37
|
+
const fs = require('fs');
|
|
38
|
+
const path = require('path');
|
|
39
|
+
const os = require('os');
|
|
40
|
+
|
|
41
|
+
// One stored id per skill: skills/caveman, skills/ultracave, skills/megacave,
|
|
42
|
+
// plus the one-shot modes and the durable off.
|
|
43
|
+
const VALID_MODES = [
|
|
44
|
+
'off', 'caveman', 'ultracave', 'megacave',
|
|
45
|
+
'commit', 'review', 'compress'
|
|
46
|
+
];
|
|
47
|
+
|
|
48
|
+
// Startup policy only: manual starts inactive, but explicit activation uses
|
|
49
|
+
// caveman. Keep it out of flag validation and the selectable modes.
|
|
50
|
+
const VALID_DEFAULT_MODES = [...VALID_MODES, 'manual'];
|
|
51
|
+
|
|
52
|
+
// The six intensity levels that preceded the three skills. Session files,
|
|
53
|
+
// .caveman-active mirrors, config files, env vars and mode-log rows written
|
|
54
|
+
// before the switch still hold these, so every read maps them forward and no
|
|
55
|
+
// write ever emits one.
|
|
56
|
+
const LEGACY_MODES = {
|
|
57
|
+
lite: 'caveman', full: 'caveman', ultra: 'ultracave',
|
|
58
|
+
wenyan: 'megacave', 'wenyan-lite': 'megacave',
|
|
59
|
+
'wenyan-full': 'megacave', 'wenyan-ultra': 'megacave',
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
// Stored/configured value → current mode id, or null when it is neither a
|
|
63
|
+
// mode nor a legacy level. The whitelist every read path goes through.
|
|
64
|
+
function canonicalMode(raw) {
|
|
65
|
+
if (typeof raw !== 'string') return null;
|
|
66
|
+
const m = raw.toLowerCase();
|
|
67
|
+
if (VALID_MODES.includes(m)) return m;
|
|
68
|
+
return Object.prototype.hasOwnProperty.call(LEGACY_MODES, m) ? LEGACY_MODES[m] : null;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Same, for default-mode sources, which also accept the 'manual' policy.
|
|
72
|
+
function canonicalDefaultMode(raw) {
|
|
73
|
+
if (typeof raw !== 'string') return null;
|
|
74
|
+
const m = raw.toLowerCase();
|
|
75
|
+
return VALID_DEFAULT_MODES.includes(m) ? m : canonicalMode(m);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Legacy machine-wide flag. Kept as a last-write-wins MIRROR of whichever
|
|
79
|
+
// session wrote most recently, because INSTALL.md tells users to `cat` it and
|
|
80
|
+
// src/hooks/README.md ships a third-party statusline snippet that reads it.
|
|
81
|
+
// It never receives the literal string 'off' — see writeSessionMode.
|
|
82
|
+
const FLAG_BASENAME = '.caveman-active';
|
|
83
|
+
const PREV_BASENAME = '.caveman-active.prev';
|
|
84
|
+
|
|
85
|
+
// Per-session state lives here, one small file per session id. Dot-prefixed to
|
|
86
|
+
// match the rest of the caveman namespace in $CLAUDE_CONFIG_DIR and to avoid
|
|
87
|
+
// colliding with Claude Code's own directories (projects/, hooks/, ...).
|
|
88
|
+
const SESSIONS_DIRNAME = '.caveman-sessions';
|
|
89
|
+
|
|
90
|
+
function getConfigDir() {
|
|
91
|
+
if (process.env.XDG_CONFIG_HOME) {
|
|
92
|
+
return path.join(process.env.XDG_CONFIG_HOME, 'caveman');
|
|
93
|
+
}
|
|
94
|
+
if (process.platform === 'win32') {
|
|
95
|
+
return path.join(
|
|
96
|
+
process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming'),
|
|
97
|
+
'caveman'
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
return path.join(os.homedir(), '.config', 'caveman');
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function getConfigPath() {
|
|
104
|
+
return path.join(getConfigDir(), 'config.json');
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// Walk up from `start` looking for a repo-local caveman config. Returns the
|
|
108
|
+
// absolute path of the first match, or null. Stops at the filesystem root.
|
|
109
|
+
// Candidates per dir (first wins): .caveman/config.json, .caveman.json.
|
|
110
|
+
// `accept(path)`, when given, must also return true for a file to match.
|
|
111
|
+
//
|
|
112
|
+
// Bounded to 64 levels to defend against symlink cycles on pathological mounts.
|
|
113
|
+
function findRepoConfigPath(start, accept) {
|
|
114
|
+
try {
|
|
115
|
+
let dir = path.resolve(start || process.cwd());
|
|
116
|
+
const candidates = ['.caveman/config.json', '.caveman.json'];
|
|
117
|
+
for (let i = 0; i < 64; i++) {
|
|
118
|
+
for (const rel of candidates) {
|
|
119
|
+
const p = path.join(dir, rel);
|
|
120
|
+
try {
|
|
121
|
+
const st = fs.lstatSync(p);
|
|
122
|
+
// Refuse symlinks — symmetric with safeWriteFlag/readFlag policy.
|
|
123
|
+
if (st.isSymbolicLink() || !st.isFile()) continue;
|
|
124
|
+
if (accept && !accept(p)) continue;
|
|
125
|
+
return p;
|
|
126
|
+
} catch (e) {
|
|
127
|
+
// not present, try next candidate
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
const parent = path.dirname(dir);
|
|
131
|
+
if (parent === dir) return null;
|
|
132
|
+
dir = parent;
|
|
133
|
+
}
|
|
134
|
+
} catch (e) {
|
|
135
|
+
// Defensive: any cwd / fs failure → no repo config
|
|
136
|
+
}
|
|
137
|
+
return null;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// Config files are hand-edited, often on Windows: PowerShell 5.1's `>` writes
|
|
141
|
+
// UTF-16LE with a BOM, `Set-Content -Encoding UTF8` a UTF-8 BOM, and people
|
|
142
|
+
// leave comments and trailing commas. Accept all of them — the JSONC
|
|
143
|
+
// tolerance installer/lib/settings.js gives settings.json — inlined because
|
|
144
|
+
// this file may load only node built-ins (see the top of this file).
|
|
145
|
+
function parseConfigFile(configPath) {
|
|
146
|
+
const buf = fs.readFileSync(configPath);
|
|
147
|
+
const text = (buf[0] === 0xff && buf[1] === 0xfe ? buf.toString('utf16le', 2) : buf.toString('utf8'))
|
|
148
|
+
.replace(/^\uFEFF/, '');
|
|
149
|
+
try {
|
|
150
|
+
return JSON.parse(text);
|
|
151
|
+
} catch (e) {
|
|
152
|
+
// Strings match first and are kept whole, so "//" or ",}" inside a value
|
|
153
|
+
// survives; outside strings, comments go and trailing commas go.
|
|
154
|
+
return JSON.parse(text
|
|
155
|
+
.replace(/("(?:[^"\\]|\\.)*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (m, s) => s || '')
|
|
156
|
+
.replace(/("(?:[^"\\]|\\.)*")|,(\s*[}\]])/g, (m, s, close) => s || close));
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function readModeFromConfigFile(configPath) {
|
|
161
|
+
try {
|
|
162
|
+
const config = parseConfigFile(configPath);
|
|
163
|
+
if (config && config.defaultMode) {
|
|
164
|
+
return canonicalDefaultMode(String(config.defaultMode));
|
|
165
|
+
}
|
|
166
|
+
} catch (e) {
|
|
167
|
+
// Missing / unreadable / invalid JSON → caller falls through
|
|
168
|
+
}
|
|
169
|
+
return null;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// One precedence for every setting: the env value, else the nearest repo
|
|
173
|
+
// config that names the setting, else the user config, else null. `readFile`
|
|
174
|
+
// returns null for a file that does not name it (missing, unreadable, invalid
|
|
175
|
+
// JSON, unrecognized value), so such a file never hides a farther one.
|
|
176
|
+
//
|
|
177
|
+
// startDir overrides the cwd the repo-config walk starts from (default
|
|
178
|
+
// process.cwd(), same as findRepoConfigPath's own fallback) — lets a caller
|
|
179
|
+
// resolve a setting for a directory other than its own process cwd (#634:
|
|
180
|
+
// the UserPromptSubmit hook's stdin carries the session's cwd, which can
|
|
181
|
+
// differ from the hook process's cwd). Every other resolution step is
|
|
182
|
+
// cwd-independent, so only the repo-config walk takes it.
|
|
183
|
+
function resolveSetting(envValue, readFile, startDir) {
|
|
184
|
+
// 1. Environment variable (highest priority)
|
|
185
|
+
if (envValue !== null) return envValue;
|
|
186
|
+
|
|
187
|
+
// 2. Repo-local config (checked-in, per-project). The first file that names
|
|
188
|
+
// the setting wins: .caveman/config.json is also the CLI's project
|
|
189
|
+
// overlay, and one without it must not hide a .caveman.json.
|
|
190
|
+
const repoConfigPath = findRepoConfigPath(startDir, (p) => readFile(p) !== null);
|
|
191
|
+
if (repoConfigPath) return readFile(repoConfigPath);
|
|
192
|
+
|
|
193
|
+
// 3. User config file. Windows also reads ~/.config/caveman/config.json,
|
|
194
|
+
// the path the docs give for every platform, after %APPDATA%.
|
|
195
|
+
const user = readFile(getConfigPath());
|
|
196
|
+
if (user !== null) return user;
|
|
197
|
+
if (process.platform === 'win32' && !process.env.XDG_CONFIG_HOME) {
|
|
198
|
+
return readFile(path.join(os.homedir(), '.config', 'caveman', 'config.json'));
|
|
199
|
+
}
|
|
200
|
+
return null;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function getDefaultMode(startDir) {
|
|
204
|
+
return resolveSetting(canonicalDefaultMode(process.env.CAVEMAN_DEFAULT_MODE),
|
|
205
|
+
readModeFromConfigFile, startDir) || 'caveman';
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// true/false, or null for anything else. Accepts a JSON boolean and the usual
|
|
209
|
+
// env spellings, so `"reinforce": "off"` and CAVEMAN_REINFORCE=0 both work.
|
|
210
|
+
function parseSwitch(raw) {
|
|
211
|
+
if (typeof raw === 'boolean') return raw;
|
|
212
|
+
if (typeof raw !== 'string') return null;
|
|
213
|
+
const v = raw.trim().toLowerCase();
|
|
214
|
+
if (v === '1' || v === 'true' || v === 'on' || v === 'yes') return true;
|
|
215
|
+
if (v === '0' || v === 'false' || v === 'off' || v === 'no') return false;
|
|
216
|
+
return null;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function readReinforceFromConfigFile(configPath) {
|
|
220
|
+
try {
|
|
221
|
+
const config = parseConfigFile(configPath);
|
|
222
|
+
return config && typeof config === 'object' ? parseSwitch(config.reinforce) : null;
|
|
223
|
+
} catch (e) {
|
|
224
|
+
return null;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// Whether the UserPromptSubmit hook adds its one-line per-turn reminder
|
|
229
|
+
// (#1468). Off keeps caveman itself on: SessionStart still injects the ruleset
|
|
230
|
+
// and a mid-session switch still injects the new mode's ruleset; only the
|
|
231
|
+
// repeat on every prompt goes. Same sources and order as getDefaultMode.
|
|
232
|
+
function getReinforce(startDir) {
|
|
233
|
+
const value = resolveSetting(parseSwitch(process.env.CAVEMAN_REINFORCE),
|
|
234
|
+
readReinforceFromConfigFile, startDir);
|
|
235
|
+
return value !== false;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// Symlink-safe flag file write.
|
|
239
|
+
// Uses O_NOFOLLOW where available, writes atomically via temp + rename with
|
|
240
|
+
// 0600 permissions. Protects against local attackers replacing the predictable
|
|
241
|
+
// flag path (~/.claude/.caveman-active) with a symlink to clobber other files.
|
|
242
|
+
//
|
|
243
|
+
// When the parent directory is itself a symlink (legitimate pattern: ~/.claude
|
|
244
|
+
// symlinked to another drive or shared config dir), resolves through to the
|
|
245
|
+
// real path and verifies ownership on Unix (uid match). This allows e.g.
|
|
246
|
+
// ln -s /opt/shared-claude-config ~/.claude
|
|
247
|
+
// while still refusing attacker-planted symlinks pointing to dirs owned by
|
|
248
|
+
// another user.
|
|
249
|
+
//
|
|
250
|
+
// On Windows, uid checks are unavailable — falls back to verifying the resolved
|
|
251
|
+
// path lives under the user's home directory.
|
|
252
|
+
//
|
|
253
|
+
// The flag file itself must never be a symlink (that's the actual clobber vector).
|
|
254
|
+
//
|
|
255
|
+
// Set CAVEMAN_DEBUG=1 to emit stderr diagnostics when flag writes are refused.
|
|
256
|
+
//
|
|
257
|
+
// Silent-fails on any filesystem error — the flag is best-effort.
|
|
258
|
+
// Blocking sleep with no child process and no busy-wait. Used only to space
|
|
259
|
+
// out rename retries under Windows lock contention.
|
|
260
|
+
function sleepMs(ms) {
|
|
261
|
+
try {
|
|
262
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
263
|
+
} catch (e) { /* SharedArrayBuffer unavailable — skip the backoff */ }
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function safeWriteFlag(flagPath, content) {
|
|
267
|
+
const debug = process.env.CAVEMAN_DEBUG === '1';
|
|
268
|
+
try {
|
|
269
|
+
const flagDir = path.dirname(flagPath);
|
|
270
|
+
fs.mkdirSync(flagDir, { recursive: true });
|
|
271
|
+
|
|
272
|
+
// When the parent directory is a symlink, resolve it and verify ownership.
|
|
273
|
+
// This allows legitimate symlinked ~/.claude dirs while still refusing
|
|
274
|
+
// attacker-planted symlinks pointing at dirs owned by another user.
|
|
275
|
+
let realFlagDir;
|
|
276
|
+
try {
|
|
277
|
+
const lstat = fs.lstatSync(flagDir);
|
|
278
|
+
if (lstat.isSymbolicLink()) {
|
|
279
|
+
realFlagDir = fs.realpathSync(flagDir);
|
|
280
|
+
const realStat = fs.statSync(realFlagDir);
|
|
281
|
+
if (!realStat.isDirectory()) {
|
|
282
|
+
if (debug) process.stderr.write(`[caveman] safeWriteFlag: symlink target ${realFlagDir} is not a directory\n`);
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
if (typeof process.getuid === 'function') {
|
|
286
|
+
if (realStat.uid !== process.getuid()) {
|
|
287
|
+
if (debug) process.stderr.write(`[caveman] safeWriteFlag: symlink target ${realFlagDir} owned by uid ${realStat.uid}, not current user ${process.getuid()}\n`);
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
} else {
|
|
291
|
+
// The home-prefix check used to live here, comparing the resolved
|
|
292
|
+
// symlink target against os.homedir(). That is the wrong proxy on
|
|
293
|
+
// win32: a directory junction (e.g. ~/.claude junctioned to another
|
|
294
|
+
// drive, the same "legitimate symlinked config dir" case this branch
|
|
295
|
+
// exists to allow) resolves to a realpath that does not start with
|
|
296
|
+
// the home directory, so the write was refused through the very
|
|
297
|
+
// junction this code's own comments say it should tolerate. Test
|
|
298
|
+
// what actually matters instead: can the current user write there.
|
|
299
|
+
try {
|
|
300
|
+
fs.accessSync(realFlagDir, fs.constants.W_OK);
|
|
301
|
+
} catch (e) {
|
|
302
|
+
if (debug) process.stderr.write(`[caveman] safeWriteFlag: symlink target ${realFlagDir} is not writable by current user\n`);
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
} else {
|
|
307
|
+
realFlagDir = flagDir;
|
|
308
|
+
}
|
|
309
|
+
} catch (e) {
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// The flag file itself must never be a symlink (that's the actual clobber vector).
|
|
314
|
+
const realFlagPath = path.join(realFlagDir, path.basename(flagPath));
|
|
315
|
+
try {
|
|
316
|
+
if (fs.lstatSync(realFlagPath).isSymbolicLink()) return;
|
|
317
|
+
} catch (e) {
|
|
318
|
+
if (e.code !== 'ENOENT') return;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
// tempPath is hoisted above the try so the finally below can always find
|
|
322
|
+
// it. On Windows, renameSync onto an existing target throws EPERM/EBUSY/
|
|
323
|
+
// EACCES/EEXIST when another process (statusline read, a concurrent
|
|
324
|
+
// session's hook) holds the file open without FILE_SHARE_DELETE —
|
|
325
|
+
// without the retry + guaranteed cleanup here, every such miss left an
|
|
326
|
+
// orphaned .caveman-active.<pid>.<ts> file behind (#511/#578/#657).
|
|
327
|
+
let tempPath;
|
|
328
|
+
try {
|
|
329
|
+
tempPath = path.join(realFlagDir, `.caveman-active.${process.pid}.${Date.now()}`);
|
|
330
|
+
const O_NOFOLLOW = typeof fs.constants.O_NOFOLLOW === 'number' ? fs.constants.O_NOFOLLOW : 0;
|
|
331
|
+
const flags = fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | O_NOFOLLOW;
|
|
332
|
+
let fd;
|
|
333
|
+
try {
|
|
334
|
+
fd = fs.openSync(tempPath, flags, 0o600);
|
|
335
|
+
fs.writeSync(fd, String(content));
|
|
336
|
+
try { fs.fchmodSync(fd, 0o600); } catch (e) { /* best-effort on Windows */ }
|
|
337
|
+
} finally {
|
|
338
|
+
if (fd !== undefined) fs.closeSync(fd);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// Retry brief lock contention a few times, backing off between attempts.
|
|
342
|
+
// Three synchronous attempts with no delay all complete inside a few
|
|
343
|
+
// microseconds, so whichever handle blocked the first (a statusline read,
|
|
344
|
+
// a concurrent session's hook, an AV scan) is still held for the other
|
|
345
|
+
// two — effectively one attempt with two extra syscalls. Sleep for real:
|
|
346
|
+
// Atomics.wait blocks this thread without pulling in a child process,
|
|
347
|
+
// which is what a hook budget can least afford.
|
|
348
|
+
let renamed = false;
|
|
349
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
350
|
+
try {
|
|
351
|
+
fs.renameSync(tempPath, realFlagPath);
|
|
352
|
+
renamed = true;
|
|
353
|
+
break;
|
|
354
|
+
} catch (e) {
|
|
355
|
+
const transient = e.code === 'EPERM' || e.code === 'EBUSY' ||
|
|
356
|
+
e.code === 'EACCES' || e.code === 'EEXIST';
|
|
357
|
+
if (!transient) throw e;
|
|
358
|
+
if (attempt < 2) sleepMs(10 * (attempt + 1));
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
if (!renamed && debug) {
|
|
362
|
+
process.stderr.write('[caveman] safeWriteFlag: rename contended after 3 attempts; flag not updated this write\n');
|
|
363
|
+
}
|
|
364
|
+
} finally {
|
|
365
|
+
if (tempPath) {
|
|
366
|
+
try {
|
|
367
|
+
fs.unlinkSync(tempPath);
|
|
368
|
+
} catch (error) {
|
|
369
|
+
if (debug && error.code !== 'ENOENT') {
|
|
370
|
+
process.stderr.write(`[caveman] safeWriteFlag: failed to remove temp flag ${tempPath}: ${error.message}\n`);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
} catch (e) {
|
|
376
|
+
// Silent fail — flag is best-effort
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
// Symlink-safe flag file delete. Symmetric with safeWriteFlag: resolves
|
|
381
|
+
// through a symlinked/junctioned parent the same way (ownership check on
|
|
382
|
+
// Unix, writable-parent check on win32) and refuses to touch a target that
|
|
383
|
+
// is itself a symlink, before unlinking. Without this, any caller that wants
|
|
384
|
+
// to clear the flag could delete straight through a junction that
|
|
385
|
+
// safeWriteFlag would refuse to write through in the first place — a
|
|
386
|
+
// write/delete asymmetry that lets the flag be destroyed but never
|
|
387
|
+
// recreated on that machine.
|
|
388
|
+
//
|
|
389
|
+
// Silent-fails on any filesystem error — the flag is best-effort.
|
|
390
|
+
function safeDeleteFlag(flagPath) {
|
|
391
|
+
const debug = process.env.CAVEMAN_DEBUG === '1';
|
|
392
|
+
try {
|
|
393
|
+
const flagDir = path.dirname(flagPath);
|
|
394
|
+
|
|
395
|
+
let realFlagDir;
|
|
396
|
+
try {
|
|
397
|
+
const lstat = fs.lstatSync(flagDir);
|
|
398
|
+
if (lstat.isSymbolicLink()) {
|
|
399
|
+
realFlagDir = fs.realpathSync(flagDir);
|
|
400
|
+
const realStat = fs.statSync(realFlagDir);
|
|
401
|
+
if (!realStat.isDirectory()) {
|
|
402
|
+
if (debug) process.stderr.write(`[caveman] safeDeleteFlag: symlink target ${realFlagDir} is not a directory\n`);
|
|
403
|
+
return;
|
|
404
|
+
}
|
|
405
|
+
if (typeof process.getuid === 'function') {
|
|
406
|
+
if (realStat.uid !== process.getuid()) {
|
|
407
|
+
if (debug) process.stderr.write(`[caveman] safeDeleteFlag: symlink target ${realFlagDir} owned by uid ${realStat.uid}, not current user ${process.getuid()}\n`);
|
|
408
|
+
return;
|
|
409
|
+
}
|
|
410
|
+
} else {
|
|
411
|
+
try {
|
|
412
|
+
fs.accessSync(realFlagDir, fs.constants.W_OK);
|
|
413
|
+
} catch (e) {
|
|
414
|
+
if (debug) process.stderr.write(`[caveman] safeDeleteFlag: symlink target ${realFlagDir} is not writable by current user\n`);
|
|
415
|
+
return;
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
} else {
|
|
419
|
+
realFlagDir = flagDir;
|
|
420
|
+
}
|
|
421
|
+
} catch (e) {
|
|
422
|
+
return;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
const realFlagPath = path.join(realFlagDir, path.basename(flagPath));
|
|
426
|
+
try {
|
|
427
|
+
if (fs.lstatSync(realFlagPath).isSymbolicLink()) return;
|
|
428
|
+
} catch (e) {
|
|
429
|
+
return;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
fs.unlinkSync(realFlagPath);
|
|
433
|
+
} catch (e) {
|
|
434
|
+
// Silent fail — flag is best-effort
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
// Symlink-safe, size-capped, whitelist-validated flag file read.
|
|
439
|
+
// Symmetric with safeWriteFlag: refuses symlinks at the target, caps the read,
|
|
440
|
+
// and rejects anything that isn't a known mode. Returns null on any anomaly.
|
|
441
|
+
//
|
|
442
|
+
// Without this, a local attacker with write access to ~/.claude/ could replace
|
|
443
|
+
// the flag with a symlink to ~/.ssh/id_rsa (or any user-readable secret). Every
|
|
444
|
+
// reader — statusline, per-turn reinforcement — would slurp that content and
|
|
445
|
+
// either echo it to the terminal or inject it into model context.
|
|
446
|
+
//
|
|
447
|
+
// MAX_FLAG_BYTES is a hard cap. The longest legitimate value is the legacy
|
|
448
|
+
// "wenyan-ultra" (12 bytes); 64 leaves slack without enabling exfil.
|
|
449
|
+
const MAX_FLAG_BYTES = 64;
|
|
450
|
+
|
|
451
|
+
function readFlag(flagPath) {
|
|
452
|
+
try {
|
|
453
|
+
let st;
|
|
454
|
+
try {
|
|
455
|
+
st = fs.lstatSync(flagPath);
|
|
456
|
+
} catch (e) {
|
|
457
|
+
return null;
|
|
458
|
+
}
|
|
459
|
+
if (st.isSymbolicLink() || !st.isFile()) return null;
|
|
460
|
+
if (st.size > MAX_FLAG_BYTES) return null;
|
|
461
|
+
|
|
462
|
+
const O_NOFOLLOW = typeof fs.constants.O_NOFOLLOW === 'number' ? fs.constants.O_NOFOLLOW : 0;
|
|
463
|
+
const flags = fs.constants.O_RDONLY | O_NOFOLLOW;
|
|
464
|
+
let fd;
|
|
465
|
+
let out;
|
|
466
|
+
try {
|
|
467
|
+
fd = fs.openSync(flagPath, flags);
|
|
468
|
+
const buf = Buffer.alloc(MAX_FLAG_BYTES);
|
|
469
|
+
const n = fs.readSync(fd, buf, 0, MAX_FLAG_BYTES, 0);
|
|
470
|
+
out = buf.slice(0, n).toString('utf8');
|
|
471
|
+
} finally {
|
|
472
|
+
if (fd !== undefined) fs.closeSync(fd);
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
// Legacy levels come back as their current id, so every caller of
|
|
476
|
+
// readFlag (and the session helpers built on it) sees only VALID_MODES.
|
|
477
|
+
return canonicalMode(out.trim());
|
|
478
|
+
} catch (e) {
|
|
479
|
+
return null;
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
// Symlink-safe append. Same parent-dir + symlink-target rules as safeWriteFlag,
|
|
484
|
+
// but opens with O_APPEND so concurrent writers from different sessions don't
|
|
485
|
+
// clobber each other. Used for the lifetime stats log
|
|
486
|
+
// ($CLAUDE_CONFIG_DIR/.caveman-history.jsonl).
|
|
487
|
+
//
|
|
488
|
+
// Silent-fails on any filesystem error.
|
|
489
|
+
function appendFlag(filePath, line) {
|
|
490
|
+
const debug = process.env.CAVEMAN_DEBUG === '1';
|
|
491
|
+
try {
|
|
492
|
+
const dir = path.dirname(filePath);
|
|
493
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
494
|
+
|
|
495
|
+
let realDir;
|
|
496
|
+
try {
|
|
497
|
+
const lstat = fs.lstatSync(dir);
|
|
498
|
+
if (lstat.isSymbolicLink()) {
|
|
499
|
+
realDir = fs.realpathSync(dir);
|
|
500
|
+
const realStat = fs.statSync(realDir);
|
|
501
|
+
if (!realStat.isDirectory()) return;
|
|
502
|
+
if (typeof process.getuid === 'function') {
|
|
503
|
+
if (realStat.uid !== process.getuid()) {
|
|
504
|
+
if (debug) process.stderr.write(`[caveman] appendFlag: symlink target ${realDir} owned by uid ${realStat.uid}\n`);
|
|
505
|
+
return;
|
|
506
|
+
}
|
|
507
|
+
} else {
|
|
508
|
+
// Same reasoning as safeWriteFlag's win32 branch: a directory
|
|
509
|
+
// junction resolves to a realpath with no home-directory prefix, so
|
|
510
|
+
// the old check refused the legitimate junctioned config dir it was
|
|
511
|
+
// meant to allow — and silently stopped the lifetime stats log from
|
|
512
|
+
// recording anything. Test what the guard actually cares about.
|
|
513
|
+
try {
|
|
514
|
+
fs.accessSync(realDir, fs.constants.W_OK);
|
|
515
|
+
} catch (e) {
|
|
516
|
+
if (debug) process.stderr.write(`[caveman] appendFlag: symlink target ${realDir} is not writable by current user\n`);
|
|
517
|
+
return;
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
} else {
|
|
521
|
+
realDir = dir;
|
|
522
|
+
}
|
|
523
|
+
} catch (e) {
|
|
524
|
+
return;
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
const realPath = path.join(realDir, path.basename(filePath));
|
|
528
|
+
try {
|
|
529
|
+
if (fs.lstatSync(realPath).isSymbolicLink()) return;
|
|
530
|
+
} catch (e) {
|
|
531
|
+
if (e.code !== 'ENOENT') return;
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
const O_NOFOLLOW = typeof fs.constants.O_NOFOLLOW === 'number' ? fs.constants.O_NOFOLLOW : 0;
|
|
535
|
+
const flags = fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_APPEND | O_NOFOLLOW;
|
|
536
|
+
let fd;
|
|
537
|
+
try {
|
|
538
|
+
fd = fs.openSync(realPath, flags, 0o600);
|
|
539
|
+
fs.writeSync(fd, String(line).replace(/\n$/, '') + '\n');
|
|
540
|
+
try { fs.fchmodSync(fd, 0o600); } catch (e) { /* best-effort on Windows */ }
|
|
541
|
+
} finally {
|
|
542
|
+
if (fd !== undefined) fs.closeSync(fd);
|
|
543
|
+
}
|
|
544
|
+
} catch (e) {
|
|
545
|
+
// Silent fail — history is best-effort
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
550
|
+
// Per-session mode state
|
|
551
|
+
//
|
|
552
|
+
// The mode is applied per session but used to be stored in ONE file per
|
|
553
|
+
// machine. That single fact caused four bugs: parallel sessions shared a mode,
|
|
554
|
+
// SessionStart re-derived the default and clobbered an explicit "stop caveman"
|
|
555
|
+
// after every auto-compaction, the statusline badge showed the same mode in
|
|
556
|
+
// every window, and "off" — expressed as file ABSENCE — could never survive a
|
|
557
|
+
// SessionStart.
|
|
558
|
+
//
|
|
559
|
+
// #691 fixed the compaction case for a mid-session LEVEL change by branching on
|
|
560
|
+
// the hook payload's `source`. It cannot fix the other three, because all of
|
|
561
|
+
// them are consequences of the storage shape rather than of when the hook
|
|
562
|
+
// re-derives: one file cannot hold two windows' modes, and an absent file
|
|
563
|
+
// cannot express "deliberately off" distinguishably from "never set".
|
|
564
|
+
//
|
|
565
|
+
// Storage: $CLAUDE_CONFIG_DIR/.caveman-sessions/<session_id>.mode (+ .prev),
|
|
566
|
+
// with the legacy flag kept as a compat mirror.
|
|
567
|
+
//
|
|
568
|
+
// Every function below accepts a sessionId that may be null or malformed and
|
|
569
|
+
// degrades to the previous machine-wide behavior in that case. That is the
|
|
570
|
+
// whole backward-compatibility story: the old code path IS the fallback
|
|
571
|
+
// branch, so a caller with no session id behaves exactly as it did before.
|
|
572
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
573
|
+
|
|
574
|
+
// A session id becomes part of a filesystem path, so it is a path-traversal
|
|
575
|
+
// vector. Whitelist the alphabet rather than blacklisting separators — same
|
|
576
|
+
// philosophy as VALID_MODES. Claude Code sends a UUID, but the regex stays
|
|
577
|
+
// deliberately broad so a future id format degrades to the legacy path instead
|
|
578
|
+
// of throwing. Length-capped so a hostile id cannot blow past filename limits.
|
|
579
|
+
const SESSION_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
|
|
580
|
+
|
|
581
|
+
function validateSessionId(id) {
|
|
582
|
+
if (typeof id !== 'string' || !SESSION_ID_RE.test(id)) return null;
|
|
583
|
+
return id;
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
function legacyFlagPath(claudeDir) {
|
|
587
|
+
return path.join(claudeDir, FLAG_BASENAME);
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
function sessionsDir(claudeDir) {
|
|
591
|
+
return path.join(claudeDir, SESSIONS_DIRNAME);
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
// Returns null for any id the whitelist rejects. The resolved-path containment
|
|
595
|
+
// check is redundant while SESSION_ID_RE holds, but it is cheap and it defends
|
|
596
|
+
// against a future edit loosening the regex — the same defense-in-depth style
|
|
597
|
+
// as the symlink checks in safeWriteFlag.
|
|
598
|
+
function sessionStatePath(claudeDir, sessionId, ext) {
|
|
599
|
+
const sid = validateSessionId(sessionId);
|
|
600
|
+
if (!sid) return null;
|
|
601
|
+
const dir = sessionsDir(claudeDir);
|
|
602
|
+
const candidate = path.join(dir, sid + ext);
|
|
603
|
+
if (path.dirname(path.resolve(candidate)) !== path.resolve(dir)) return null;
|
|
604
|
+
return candidate;
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
function sessionActivePath(claudeDir, sessionId) {
|
|
608
|
+
return sessionStatePath(claudeDir, sessionId, '.mode');
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
function sessionPrevPath(claudeDir, sessionId) {
|
|
612
|
+
return sessionStatePath(claudeDir, sessionId, '.prev');
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
// Both "no file" and the literal 'off' mean caveman is off. Collapsing them to
|
|
616
|
+
// a single null is what implements the dual-read compat requirement: a missing
|
|
617
|
+
// file is the old spelling, a literal 'off' the new durable one.
|
|
618
|
+
function offToNull(mode) {
|
|
619
|
+
return (!mode || mode === 'off') ? null : mode;
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
// "What mode is in effect right now" — for every reader (per-turn
|
|
623
|
+
// reinforcement gate, ruleset re-emission, statusline, stats).
|
|
624
|
+
function resolveActiveMode(claudeDir, sessionId) {
|
|
625
|
+
const sessionPath = sessionActivePath(claudeDir, sessionId);
|
|
626
|
+
if (sessionPath) {
|
|
627
|
+
const stored = readFlag(sessionPath);
|
|
628
|
+
if (stored !== null) return offToNull(stored);
|
|
629
|
+
}
|
|
630
|
+
return offToNull(readFlag(legacyFlagPath(claudeDir)));
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
// "What is literally written for THIS session" — no legacy fallback, and 'off'
|
|
634
|
+
// comes back verbatim. Two callers need exactly this: recordModeChange (whose
|
|
635
|
+
// comparison against the shared mirror would diff against whatever some OTHER
|
|
636
|
+
// session wrote last and spam the log with phantom transitions) and the
|
|
637
|
+
// SessionStart continuation branch, which has to tell "this session chose off"
|
|
638
|
+
// apart from "this session has no state yet".
|
|
639
|
+
function readSessionModeRaw(claudeDir, sessionId) {
|
|
640
|
+
const sessionPath = sessionActivePath(claudeDir, sessionId);
|
|
641
|
+
if (!sessionPath) return readFlag(legacyFlagPath(claudeDir));
|
|
642
|
+
return readFlag(sessionPath);
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
// Single writer for the active mode. Pass null (or 'off') to deactivate.
|
|
646
|
+
//
|
|
647
|
+
// The session file stores 'off' literally — that is what makes deactivation
|
|
648
|
+
// durable across SessionStart. The legacy mirror instead gets UNLINKED, and
|
|
649
|
+
// never holds the literal 'off', on purpose: 'off' is already in VALID_MODES,
|
|
650
|
+
// so an older caveman-mode-tracker.js reading it from the legacy path would
|
|
651
|
+
// clear its !INDEPENDENT_MODES check and inject "CAVEMAN MODE ACTIVE (off)",
|
|
652
|
+
// and an older caveman-statusline.sh would render [CAVEMAN:OFF] instead of
|
|
653
|
+
// staying silent. Mixed-version installs are real — plugin hooks and
|
|
654
|
+
// standalone hooks can both be registered, and settings.json holds a
|
|
655
|
+
// statusline path baked in at install time.
|
|
656
|
+
function writeSessionMode(claudeDir, sessionId, modeOrNull) {
|
|
657
|
+
const canonical = modeOrNull ? canonicalMode(modeOrNull) : 'off';
|
|
658
|
+
if (!canonical) return;
|
|
659
|
+
|
|
660
|
+
const sessionPath = sessionActivePath(claudeDir, sessionId);
|
|
661
|
+
if (sessionPath) safeWriteFlag(sessionPath, canonical);
|
|
662
|
+
|
|
663
|
+
const legacy = legacyFlagPath(claudeDir);
|
|
664
|
+
if (canonical === 'off') {
|
|
665
|
+
safeDeleteFlag(legacy);
|
|
666
|
+
} else {
|
|
667
|
+
safeWriteFlag(legacy, canonical);
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
// Displaced-prose-mode memory for one-shot independent modes (#599), scoped to
|
|
672
|
+
// the session. Without the scoping, two windows each running /caveman-commit
|
|
673
|
+
// would overwrite each other's "where to return to".
|
|
674
|
+
//
|
|
675
|
+
// Unlike the active mode, prev is stored in EXACTLY ONE place — the session
|
|
676
|
+
// file when there is a valid session id, the legacy file otherwise. It is not
|
|
677
|
+
// mirrored, and the read/clear helpers must not cross that line either.
|
|
678
|
+
//
|
|
679
|
+
// Falling back to the legacy prev whenever a session simply has none of its own
|
|
680
|
+
// is a real bug, not a convenience: a session where caveman was never on saves
|
|
681
|
+
// no prev (there is nothing to displace), so after /caveman-commit it would
|
|
682
|
+
// restore from whatever stale machine-wide prev another context left behind and
|
|
683
|
+
// switch itself on at that mode. Symmetrically, clearing must not reach across
|
|
684
|
+
// and delete machine-wide state on behalf of one session.
|
|
685
|
+
function writeSessionPrev(claudeDir, sessionId, mode) {
|
|
686
|
+
const canonical = canonicalMode(mode);
|
|
687
|
+
if (!canonical) return;
|
|
688
|
+
const p = sessionPrevPath(claudeDir, sessionId) || path.join(claudeDir, PREV_BASENAME);
|
|
689
|
+
safeWriteFlag(p, canonical);
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
function readSessionPrev(claudeDir, sessionId) {
|
|
693
|
+
const p = sessionPrevPath(claudeDir, sessionId);
|
|
694
|
+
if (p) return readFlag(p);
|
|
695
|
+
return readFlag(path.join(claudeDir, PREV_BASENAME));
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
function clearSessionPrev(claudeDir, sessionId) {
|
|
699
|
+
const p = sessionPrevPath(claudeDir, sessionId);
|
|
700
|
+
if (p) {
|
|
701
|
+
safeDeleteFlag(p);
|
|
702
|
+
return;
|
|
703
|
+
}
|
|
704
|
+
safeDeleteFlag(path.join(claudeDir, PREV_BASENAME));
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
// Sweep stale per-session files. Called from SessionStart on a genuinely new
|
|
708
|
+
// session only — not on every compaction, which is frequent in a long session
|
|
709
|
+
// and would spend the 5s hook budget on directory walks.
|
|
710
|
+
//
|
|
711
|
+
// maxDeletes caps the first sweep on a machine that already accumulated many
|
|
712
|
+
// sessions. TTL is overridable via env so tests need not fake two weeks.
|
|
713
|
+
const SESSION_TTL_MS = 14 * 24 * 60 * 60 * 1000;
|
|
714
|
+
|
|
715
|
+
function gcSessionStore(claudeDir, opts) {
|
|
716
|
+
const options = opts || {};
|
|
717
|
+
const envTtl = Number(process.env.CAVEMAN_SESSION_TTL_MS);
|
|
718
|
+
const maxAgeMs = options.maxAgeMs
|
|
719
|
+
|| (Number.isFinite(envTtl) && envTtl > 0 ? envTtl : SESSION_TTL_MS);
|
|
720
|
+
const maxDeletes = options.maxDeletes || 500;
|
|
721
|
+
|
|
722
|
+
try {
|
|
723
|
+
const dir = sessionsDir(claudeDir);
|
|
724
|
+
const entries = fs.readdirSync(dir);
|
|
725
|
+
const cutoff = Date.now() - maxAgeMs;
|
|
726
|
+
let deleted = 0;
|
|
727
|
+
for (const name of entries) {
|
|
728
|
+
if (deleted >= maxDeletes) break;
|
|
729
|
+
const p = path.join(dir, name);
|
|
730
|
+
try {
|
|
731
|
+
const st = fs.lstatSync(p);
|
|
732
|
+
// Refuse symlinks rather than following them into someone else's file.
|
|
733
|
+
if (st.isSymbolicLink() || !st.isFile()) continue;
|
|
734
|
+
if (st.mtimeMs < cutoff) { fs.unlinkSync(p); deleted++; }
|
|
735
|
+
} catch (e) { /* vanished or unreadable — skip */ }
|
|
736
|
+
}
|
|
737
|
+
return deleted;
|
|
738
|
+
} catch (e) {
|
|
739
|
+
// Missing directory (fresh install) or any fs failure — nothing to do.
|
|
740
|
+
return 0;
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
// Mode-transition log (#601). Whenever the active mode actually changes,
|
|
745
|
+
// append {ts, mode, prev, session_id} to
|
|
746
|
+
// $CLAUDE_CONFIG_DIR/.caveman-mode-log.jsonl so caveman-stats can attribute
|
|
747
|
+
// output tokens to the mode that was active when each message was generated,
|
|
748
|
+
// instead of whatever mode the flag holds at stats time. mode/prev are a
|
|
749
|
+
// VALID_MODES string or null (null = caveman off). prev lets stats attribute
|
|
750
|
+
// messages that predate the first logged transition of a session. No-op when
|
|
751
|
+
// the mode is unchanged; best-effort like all flag IO.
|
|
752
|
+
//
|
|
753
|
+
// session_id is omitted (not null) when unknown, so JSON.stringify drops the
|
|
754
|
+
// key and readers written before this field existed see the old shape.
|
|
755
|
+
const MODE_LOG_BASENAME = '.caveman-mode-log.jsonl';
|
|
756
|
+
|
|
757
|
+
// Normalizing through offToNull before comparing matters here: without it a
|
|
758
|
+
// durable-off write looks like a transition from 'off' to null and lands a
|
|
759
|
+
// phantom entry in the log — and attributing output tokens to a mode named
|
|
760
|
+
// 'off' would be meaningless besides.
|
|
761
|
+
function recordModeChange(claudeDir, newMode, sessionId) {
|
|
762
|
+
try {
|
|
763
|
+
if (newMode && !canonicalMode(newMode)) return; // not a mode: log nothing
|
|
764
|
+
const current = offToNull(readSessionModeRaw(claudeDir, sessionId));
|
|
765
|
+
const next = offToNull(canonicalMode(newMode));
|
|
766
|
+
if (current === next) return;
|
|
767
|
+
const entry = { ts: Date.now(), mode: next, prev: current };
|
|
768
|
+
const sid = validateSessionId(sessionId);
|
|
769
|
+
if (sid) entry.session_id = sid;
|
|
770
|
+
appendFlag(path.join(claudeDir, MODE_LOG_BASENAME), JSON.stringify(entry));
|
|
771
|
+
} catch (e) {
|
|
772
|
+
// Silent fail — the log is best-effort
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
// Symlink-safe history read. Returns lines (untrimmed) or empty array on any
|
|
777
|
+
// anomaly. Caller is responsible for parsing JSON. Does NOT enforce a size cap
|
|
778
|
+
// the way readFlag does — history is expected to grow with use.
|
|
779
|
+
function readHistory(filePath) {
|
|
780
|
+
try {
|
|
781
|
+
const st = fs.lstatSync(filePath);
|
|
782
|
+
if (st.isSymbolicLink() || !st.isFile()) return [];
|
|
783
|
+
const O_NOFOLLOW = typeof fs.constants.O_NOFOLLOW === 'number' ? fs.constants.O_NOFOLLOW : 0;
|
|
784
|
+
const flags = fs.constants.O_RDONLY | O_NOFOLLOW;
|
|
785
|
+
let fd;
|
|
786
|
+
let raw;
|
|
787
|
+
try {
|
|
788
|
+
fd = fs.openSync(filePath, flags);
|
|
789
|
+
raw = fs.readFileSync(fd, 'utf8');
|
|
790
|
+
} finally {
|
|
791
|
+
if (fd !== undefined) fs.closeSync(fd);
|
|
792
|
+
}
|
|
793
|
+
return raw.split('\n').filter(line => line.trim());
|
|
794
|
+
} catch (e) {
|
|
795
|
+
return [];
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
// ---------------------------------------------------------------------------
|
|
800
|
+
// Caveman ruleset — skills/<mode>/SKILL.md, whole body
|
|
801
|
+
//
|
|
802
|
+
// Each prose mode is its own skill, so the stored id IS the skill id and the
|
|
803
|
+
// body needs no per-level filtering. caveman-activate.js injects it at
|
|
804
|
+
// SessionStart; caveman-mode-tracker.js re-injects it when the user switches
|
|
805
|
+
// mode mid-session (#975) and reads its thesis line for per-turn
|
|
806
|
+
// reinforcement.
|
|
807
|
+
//
|
|
808
|
+
// It lives here rather than in a new `caveman-ruleset.js` sibling for the reason
|
|
809
|
+
// the "Keep mode-state logic in caveman-config.js" rule gives: the hook file set
|
|
810
|
+
// is pinned in three places (checksums.sha256, verify_repo.py, the install
|
|
811
|
+
// lists) and src/plugins/opencode/plugin.js can only evaluate files it knows by
|
|
812
|
+
// name, so a second shared sibling is a standing drift risk. This module is
|
|
813
|
+
// already the one file every loader resolves.
|
|
814
|
+
|
|
815
|
+
const SKILL_MODES = ['caveman', 'ultracave', 'megacave'];
|
|
816
|
+
|
|
817
|
+
// Used when no SKILL.md resolves (standalone hook install without skills dir).
|
|
818
|
+
// Each is the first line under the skill's `# <id>` heading.
|
|
819
|
+
const FALLBACK_THESIS = {
|
|
820
|
+
caveman: 'Respond terse like smart caveman. All technical substance stay. Only fluff die.',
|
|
821
|
+
ultracave: 'Respond terse like smart caveman. All technical substance stay. Only fluff die. Then cut again.',
|
|
822
|
+
megacave: '以文言答。技術之實皆存,唯贅言去之。',
|
|
823
|
+
};
|
|
824
|
+
|
|
825
|
+
// Candidate locations, tried in order (#587/#589 — the old single '..' path
|
|
826
|
+
// resolved to <plugin_root>/src/skills/, which does not exist, so plugin
|
|
827
|
+
// installs silently used the stale fallback ruleset):
|
|
828
|
+
// 1. $CLAUDE_PLUGIN_ROOT/skills/<id>/SKILL.md — Claude Code sets
|
|
829
|
+
// CLAUDE_PLUGIN_ROOT when invoking plugin hooks; authoritative when present.
|
|
830
|
+
// 2. ../../skills/<id>/SKILL.md — hook at <plugin_root>/src/hooks/
|
|
831
|
+
// (plugin.json layout) or a repo checkout.
|
|
832
|
+
// 3. ../skills/<id>/SKILL.md — standalone install with hooks at
|
|
833
|
+
// $CLAUDE_CONFIG_DIR/hooks/ and the skill at $CLAUDE_CONFIG_DIR/skills/<id>/.
|
|
834
|
+
// skillId becomes a path segment: callers pass a SKILL_MODES id only.
|
|
835
|
+
function skillPathCandidates(hookDir, skillId) {
|
|
836
|
+
const dir = hookDir || __dirname;
|
|
837
|
+
const id = skillId || 'caveman';
|
|
838
|
+
const candidates = [];
|
|
839
|
+
if (process.env.CLAUDE_PLUGIN_ROOT) {
|
|
840
|
+
candidates.push(path.join(process.env.CLAUDE_PLUGIN_ROOT, 'skills', id, 'SKILL.md'));
|
|
841
|
+
}
|
|
842
|
+
candidates.push(
|
|
843
|
+
path.join(dir, '..', '..', 'skills', id, 'SKILL.md'),
|
|
844
|
+
path.join(dir, '..', 'skills', id, 'SKILL.md')
|
|
845
|
+
);
|
|
846
|
+
return candidates;
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
// The mode's SKILL.md body with YAML frontmatter stripped, or null when the
|
|
850
|
+
// mode has no skill file (off, one-shot modes) or none resolves — callers
|
|
851
|
+
// then use fallbackRuleset() below.
|
|
852
|
+
function loadRuleset(mode, hookDir) {
|
|
853
|
+
const id = canonicalMode(mode);
|
|
854
|
+
if (!SKILL_MODES.includes(id)) return null;
|
|
855
|
+
for (const candidate of skillPathCandidates(hookDir, id)) {
|
|
856
|
+
try {
|
|
857
|
+
return fs.readFileSync(candidate, 'utf8').replace(/^---[\s\S]*?---\s*/, '');
|
|
858
|
+
} catch (e) { /* try next candidate */ }
|
|
859
|
+
}
|
|
860
|
+
return null;
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
// First non-empty line after the skill's `# <id>` heading — the one-sentence
|
|
864
|
+
// statement of the mode, used for per-turn reinforcement.
|
|
865
|
+
function thesisLine(mode, hookDir) {
|
|
866
|
+
const id = canonicalMode(mode);
|
|
867
|
+
if (!SKILL_MODES.includes(id)) return null;
|
|
868
|
+
const lines = (loadRuleset(id, hookDir) || '').split(/\r?\n/);
|
|
869
|
+
const heading = lines.findIndex((line) => line.trim() === '# ' + id);
|
|
870
|
+
const line = heading === -1 ? null : lines.slice(heading + 1).find((l) => l.trim());
|
|
871
|
+
return line ? line.trim() : FALLBACK_THESIS[id];
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
// The ruleset body when no SKILL.md resolves (standalone hook install without
|
|
875
|
+
// skills dir): the caveman thesis plus the nine rule headlines of
|
|
876
|
+
// skills/caveman, then the mode's own thesis for ultracave/megacave. Rule 8
|
|
877
|
+
// keeps its "never switch" sentence: a headline alone lost the #812 language
|
|
878
|
+
// rule for every fallback-install user. megacave answers in 文言 by design, so
|
|
879
|
+
// it gets its own rule 8 instead of one its thesis contradicts. Shared so a
|
|
880
|
+
// mid-session switch on that install carries the same rules SessionStart did.
|
|
881
|
+
function fallbackRuleset(mode, hookDir) {
|
|
882
|
+
const id = canonicalMode(mode) || mode;
|
|
883
|
+
const modeThesis = id !== 'caveman' ? thesisLine(id, hookDir) : null;
|
|
884
|
+
return 'Respond terse like smart caveman. All technical substance stay. Only fluff die.\n\n' +
|
|
885
|
+
'1. Answer first.\n' +
|
|
886
|
+
'2. Kill ceremony.\n' +
|
|
887
|
+
'3. Short word.\n' +
|
|
888
|
+
'4. Articles optional, meaning never.\n' +
|
|
889
|
+
'5. One idea per sentence.\n' +
|
|
890
|
+
'6. Payload verbatim.\n' +
|
|
891
|
+
'7. Tool runs: bounded status.\n' +
|
|
892
|
+
(id === 'megacave'
|
|
893
|
+
? '8. Prose in 文言. Code, commands, paths, errors in their original script.\n'
|
|
894
|
+
: "8. User's language. Compress the style, not the language. Never switch because of quoted text.\n") +
|
|
895
|
+
'9. Never perform caveman.\n\n' +
|
|
896
|
+
'Plain prose for security warnings, irreversible actions, and anything persisted outside chat (code, commits, PRs, docs).' +
|
|
897
|
+
(modeThesis ? '\n\n' + modeThesis : '');
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
// The banner both loaders put above the ruleset, so the label the model reads
|
|
901
|
+
// cannot drift between SessionStart and a mid-session switch.
|
|
902
|
+
function rulesetBanner(mode) {
|
|
903
|
+
return 'CAVEMAN MODE ACTIVE — mode: ' + (canonicalMode(mode) || mode);
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
module.exports = {
|
|
907
|
+
getDefaultMode, getReinforce, getConfigDir, getConfigPath, findRepoConfigPath, VALID_MODES,
|
|
908
|
+
parseConfigFile,
|
|
909
|
+
canonicalMode,
|
|
910
|
+
safeWriteFlag, safeDeleteFlag, readFlag, appendFlag, readHistory,
|
|
911
|
+
recordModeChange, MODE_LOG_BASENAME,
|
|
912
|
+
// Per-session state
|
|
913
|
+
SESSIONS_DIRNAME, FLAG_BASENAME, PREV_BASENAME,
|
|
914
|
+
validateSessionId, legacyFlagPath, sessionsDir,
|
|
915
|
+
sessionActivePath, sessionPrevPath,
|
|
916
|
+
resolveActiveMode, readSessionModeRaw, writeSessionMode,
|
|
917
|
+
writeSessionPrev, readSessionPrev, clearSessionPrev,
|
|
918
|
+
gcSessionStore,
|
|
919
|
+
// Ruleset injection
|
|
920
|
+
skillPathCandidates, loadRuleset, thesisLine, rulesetBanner, fallbackRuleset,
|
|
921
|
+
};
|