@haposoft/cafekit 0.18.0 → 0.18.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/README.md +12 -1
  2. package/bin/__tests__/claude-settings.test.js +123 -0
  3. package/bin/__tests__/codex-ask-guard.test.js +123 -0
  4. package/bin/__tests__/codex-ask-projection.test.js +51 -0
  5. package/bin/__tests__/codex-hooks-ownership.test.js +80 -1
  6. package/bin/__tests__/codex-hooks.test.js +938 -237
  7. package/bin/__tests__/codex-native-hook-boundaries.test.js +136 -0
  8. package/bin/__tests__/codex-native.test.js +222 -149
  9. package/bin/__tests__/codex-projection-parity.test.js +314 -0
  10. package/bin/__tests__/codex-quiet-hooks.test.js +170 -0
  11. package/bin/__tests__/codex-research-projection.test.js +70 -0
  12. package/bin/__tests__/codex-specs-projection.test.js +76 -0
  13. package/bin/__tests__/develop-contract.test.js +102 -1362
  14. package/bin/__tests__/docs-sync-on-demand.test.js +25 -20
  15. package/bin/__tests__/inspect-paths.test.js +183 -0
  16. package/bin/__tests__/installer-safety.test.js +335 -0
  17. package/bin/__tests__/legacy-authority-decoupled.test.js +14 -19
  18. package/bin/__tests__/legacy-hooks-retired.test.js +18 -8
  19. package/bin/__tests__/omp-bridge.test.js +66 -12
  20. package/bin/__tests__/omp-hooks.test.js +11 -5
  21. package/bin/__tests__/orca-session.test.js +7 -0
  22. package/bin/__tests__/package-inventory.test.js +1 -395
  23. package/bin/__tests__/privacy-paths.test.js +317 -0
  24. package/bin/__tests__/spec-narrowing.test.js +30 -134
  25. package/bin/__tests__/specs-v2-execution-closeout.test.js +0 -372
  26. package/bin/__tests__/test-runtime-dependency-closure.cjs +1 -2
  27. package/bin/__tests__/usage-hook-retired.test.js +5 -3
  28. package/bin/__tests__/validator-grounding.test.js +17 -2929
  29. package/bin/install.js +25 -0
  30. package/bin/lib/codex-install.js +134 -12
  31. package/bin/lib/context.js +1 -1
  32. package/bin/lib/managed-writer.js +2 -3
  33. package/bin/phases/claude-runtime.js +91 -25
  34. package/bin/phases/claude-settings.js +22 -1
  35. package/bin/phases/codex-hooks.js +96 -33
  36. package/bin/phases/codex-runtime.js +45 -49
  37. package/bin/phases/copy-payload.js +11 -28
  38. package/bin/phases/omp-runtime.js +6 -3
  39. package/package.json +2 -3
  40. package/src/claude/CLAUDE.md +4 -0
  41. package/src/claude/agents/code-auditor.md +9 -6
  42. package/src/claude/agents/debugger.md +3 -9
  43. package/src/claude/agents/docs-keeper.md +4 -7
  44. package/src/claude/agents/git-ops.md +2 -4
  45. package/src/claude/agents/implementer.md +6 -7
  46. package/src/claude/agents/inspector.md +2 -0
  47. package/src/claude/agents/project-manager.md +2 -2
  48. package/src/claude/agents/spec-maker.md +4 -4
  49. package/src/claude/agents/test-runner.md +8 -11
  50. package/src/claude/agents/ui-ux-designer.md +0 -1
  51. package/src/claude/gitignore +3 -0
  52. package/src/claude/hooks/__tests__/installed-root.test.js +111 -0
  53. package/src/claude/hooks/__tests__/precompact.test.js +206 -10
  54. package/src/claude/hooks/__tests__/privacy-block.test.js +27 -0
  55. package/src/claude/hooks/__tests__/session-writeenv.test.js +25 -0
  56. package/src/claude/hooks/__tests__/spec-gate.test.js +311 -340
  57. package/src/claude/hooks/__tests__/spec-state-touched.test.js +230 -8
  58. package/src/claude/hooks/__tests__/state.test.js +207 -7
  59. package/src/claude/hooks/__tests__/update-check.test.js +88 -0
  60. package/src/claude/hooks/agent.cjs +7 -6
  61. package/src/claude/hooks/inspect-block.cjs +15 -63
  62. package/src/claude/hooks/lib/inspect-paths.cjs +304 -0
  63. package/src/claude/hooks/lib/parser.cjs +1 -1
  64. package/src/claude/hooks/lib/privacy-command-analysis.cjs +191 -17
  65. package/src/claude/hooks/lib/privacy-paths.cjs +313 -0
  66. package/src/claude/hooks/lib/project-root.cjs +15 -0
  67. package/src/claude/hooks/lib/rules-reservation.cjs +36 -0
  68. package/src/claude/hooks/lib/spec-touch.cjs +67 -0
  69. package/src/claude/hooks/lib/update-check.cjs +77 -0
  70. package/src/claude/hooks/precompact.cjs +8 -15
  71. package/src/claude/hooks/privacy-block.cjs +23 -205
  72. package/src/claude/hooks/rules.cjs +6 -28
  73. package/src/claude/hooks/session.cjs +34 -117
  74. package/src/claude/hooks/spec-gate.cjs +17 -89
  75. package/src/claude/hooks/spec-state.cjs +89 -96
  76. package/src/claude/hooks/state.cjs +96 -51
  77. package/src/claude/migration-manifest.json +20 -8
  78. package/src/claude/output-styles/coding-level-0-eli5.md +9 -9
  79. package/src/claude/output-styles/coding-level-1-junior.md +3 -3
  80. package/src/claude/output-styles/coding-level-2-mid.md +3 -3
  81. package/src/claude/output-styles/coding-level-3-senior.md +2 -2
  82. package/src/claude/output-styles/coding-level-4-lead.md +5 -5
  83. package/src/claude/output-styles/coding-level-5-god.md +6 -6
  84. package/src/claude/rules/ai-dev-rules.md +1 -2
  85. package/src/claude/rules/hook-protocols.md +1 -1
  86. package/src/claude/rules/workflow.md +1 -1
  87. package/src/claude/runtime.json +0 -3
  88. package/src/claude/scripts/generate-skill-catalog.cjs +2 -2
  89. package/src/claude/scripts/provenance.cjs +14 -0
  90. package/src/claude/scripts/spec-receipt.cjs +0 -114
  91. package/src/claude/scripts/spec-resolver.cjs +41 -457
  92. package/src/claude/scripts/workflow-policy.cjs +3 -1801
  93. package/src/claude/settings/settings.json +1 -1
  94. package/src/claude/skills/agent-browser/SKILL.md +1 -1
  95. package/src/claude/skills/ai-multimodal/scripts/check_setup.py +8 -68
  96. package/src/claude/skills/ai-multimodal/scripts/gemini_batch_process.py +6 -28
  97. package/src/claude/skills/chrome-devtools/SKILL.md +14 -31
  98. package/src/claude/skills/code-review/SKILL.md +25 -108
  99. package/src/claude/skills/code-review/references/spec-compliance-review.md +4 -7
  100. package/src/claude/skills/develop/SKILL.md +22 -70
  101. package/src/claude/skills/develop/references/subagent-patterns.md +0 -6
  102. package/src/claude/skills/git/SKILL.md +1 -1
  103. package/src/claude/skills/git/references/worktree-blueprint.md +1 -1
  104. package/src/claude/skills/research/SKILL.md +24 -55
  105. package/src/claude/skills/sync/SKILL.md +12 -34
  106. package/src/claude/skills/sync/references/rebind-and-audit.md +2 -2
  107. package/src/claude/skills/test/SKILL.md +39 -123
  108. package/src/claude/skills/test/references/execution-strategy.md +11 -22
  109. package/src/claude/skills/ui-ux/SKILL.md +1 -1
  110. package/src/claude/skills/ui-ux-pro-max/SKILL.md +24 -79
  111. package/src/claude/skills/web-testing/SKILL.md +2 -20
  112. package/src/codex/AGENTS.md +8 -0
  113. package/src/codex/hooks/ask-guard.cjs +54 -0
  114. package/src/codex/hooks/inspect-block.cjs +11 -7
  115. package/src/codex/hooks/lib/inspect-paths.cjs +1 -199
  116. package/src/codex/hooks/lib/privacy-paths.cjs +1 -0
  117. package/src/codex/hooks/lib/privacy-state.cjs +98 -16
  118. package/src/codex/hooks/lib/rules-reservation.cjs +38 -0
  119. package/src/codex/hooks/lib/secret-keywords.cjs +1 -0
  120. package/src/codex/hooks/lib/spec-receipt.cjs +2 -30
  121. package/src/codex/hooks/lib/spec-session-touch.cjs +100 -0
  122. package/src/codex/hooks/lib/spec-touch.cjs +3 -0
  123. package/src/codex/hooks/lib/spec-utils.cjs +6 -45
  124. package/src/codex/hooks/lib/update-check.cjs +1 -0
  125. package/src/codex/hooks/precompact.cjs +39 -0
  126. package/src/codex/hooks/privacy-approval.cjs +28 -17
  127. package/src/codex/hooks/privacy-block.cjs +9 -215
  128. package/src/codex/hooks/rules.cjs +4 -30
  129. package/src/codex/hooks/secret-output-guardrail.cjs +1 -1
  130. package/src/codex/hooks/session.cjs +47 -11
  131. package/src/codex/hooks/spec-gate.cjs +32 -74
  132. package/src/codex/hooks/spec-state.cjs +68 -46
  133. package/src/codex/hooks/state.cjs +25 -4
  134. package/src/codex/hooks.json +39 -7
  135. package/src/codex/rules/hook-protocols.md +13 -6
  136. package/src/common/AGENTS.md +4 -10
  137. package/src/omp/extensions/cafekit-bridge.mjs +12 -4
  138. package/src/omp/hooks/privacy-block.cjs +24 -206
  139. package/bin/__tests__/change-firewall.semantic-firewall.test.js +0 -2133
  140. package/bin/__tests__/finalizer-pass-gate.semantic-firewall.test.js +0 -342
  141. package/bin/__tests__/release-preflight.semantic-firewall.test.js +0 -586
  142. package/bin/__tests__/review-receipt-c2.semantic-firewall.test.js +0 -378
  143. package/bin/__tests__/specs-v2-policy-and-scaffold.test.js +0 -665
  144. package/bin/__tests__/specs-v2-validator-grounder-contract.test.js +0 -1132
  145. package/src/claude/hooks/lib/context.cjs +0 -527
  146. package/src/claude/hooks/lib/detect.cjs +0 -474
  147. package/src/claude/scripts/change-firewall.cjs +0 -1748
  148. package/src/claude/scripts/spec-authoring-digest.cjs +0 -151
  149. package/src/claude/scripts/spec-authoring-validation.cjs +0 -126
  150. package/src/claude/scripts/spec-final-state.cjs +0 -290
  151. package/src/claude/scripts/spec-ground.cjs +0 -650
  152. package/src/claude/scripts/spec-readiness.cjs +0 -425
  153. package/src/claude/scripts/spec-scaffold.cjs +0 -2317
  154. package/src/claude/scripts/spec-semantic-model.cjs +0 -396
  155. package/src/claude/scripts/validate-spec-output.cjs +0 -3914
  156. package/src/claude/skills/code-review/references/verification-gate.md +0 -41
  157. package/src/claude/skills/specs/templates/design.md +0 -82
  158. package/src/claude/skills/specs/templates/requirements-init.md +0 -8
  159. package/src/claude/skills/specs/templates/requirements.md +0 -42
  160. package/src/claude/skills/specs/templates/spec-state.json +0 -56
  161. package/src/claude/skills/specs/templates/task.md +0 -47
  162. package/src/codex/rules/state-sync.md +0 -60
@@ -0,0 +1,36 @@
1
+ 'use strict';
2
+
3
+ const crypto = require('crypto');
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+ const { hookStateDir } = require('./hook-state-dir.cjs');
7
+
8
+ function reservationFile(sessionId) {
9
+ if (!sessionId) return null;
10
+ const key = crypto.createHash('sha256').update(String(sessionId)).digest('hex');
11
+ return path.join(hookStateDir(), `rules-${key}.json`);
12
+ }
13
+
14
+ /** Reserve one injection slot per session. Returns null on reservation errors. */
15
+ function reserveSession(sessionId) {
16
+ try {
17
+ const file = reservationFile(sessionId);
18
+ if (!file) return null;
19
+ fs.mkdirSync(path.dirname(file), { recursive: true });
20
+ fs.writeFileSync(file, JSON.stringify({ sessionId: String(sessionId) }), {
21
+ encoding: 'utf8', flag: 'wx', mode: 0o600,
22
+ });
23
+ return true;
24
+ } catch (error) {
25
+ return error.code === 'EEXIST' ? false : null;
26
+ }
27
+ }
28
+
29
+ function clearSessionReservation(sessionId) {
30
+ try {
31
+ const file = reservationFile(sessionId);
32
+ if (file) fs.rmSync(file, { force: true });
33
+ } catch { /* fail-open */ }
34
+ }
35
+
36
+ module.exports = { reserveSession, clearSessionReservation };
@@ -0,0 +1,67 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+
6
+ // Deleted/new paths still resolve through their deepest existing ancestor. This also
7
+ // prevents an innocent lexical prefix from hiding a symlink outside the specs root.
8
+ function canonicalTarget(value) {
9
+ const missing = [];
10
+ let current = path.resolve(value);
11
+ while (true) {
12
+ try { return path.join(fs.realpathSync(current), ...missing); } catch (error) {
13
+ if (error.code !== 'ENOENT') return null;
14
+ const parent = path.dirname(current);
15
+ if (parent === current) return null;
16
+ missing.unshift(path.basename(current));
17
+ current = parent;
18
+ }
19
+ }
20
+ }
21
+
22
+ function packetAt(value, specsRoot, cwd) {
23
+ if (typeof value !== 'string' || !value.trim()) return null;
24
+ const root = canonicalTarget(specsRoot);
25
+ const target = canonicalTarget(path.resolve(cwd, value));
26
+ if (!root || !target) return null;
27
+ const rel = path.relative(root, target);
28
+ if (!rel || path.isAbsolute(rel) || rel === '..' || rel.startsWith(`..${path.sep}`)) return null;
29
+ const segments = rel.split(path.sep);
30
+ return segments[0] === '_shared' ? null : segments[0];
31
+ }
32
+
33
+ function namedPackets(prompt, names, specsRoot, projectRoot) {
34
+ if (typeof prompt !== 'string') return [];
35
+ const escape = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
36
+ const prefix = path.relative(projectRoot, specsRoot).split(path.sep).join('/');
37
+ const named = names.filter((name) => {
38
+ const n = escape(name);
39
+ const absolute = specsRoot.split(path.sep).join('/');
40
+ return new RegExp(`(^|[^\\w])${escape(absolute)}/${n}(?![\\w-])`).test(prompt)
41
+ || new RegExp(`(^|[^\\w/-])${escape(prefix)}/${n}(?![\\w-])`).test(prompt)
42
+ || new RegExp(`(?:\\$cf-[\\w-]+|/cf:[\\w-]+)\\s+(?:${escape(prefix)}/)?${n}(?![\\w-])`).test(prompt)
43
+ || (/[-_0-9]/.test(name) && new RegExp(`(^|[^\\w/-])${n}(?![\\w-])`).test(prompt));
44
+ });
45
+ // Absolute prompt references may use another realpath alias (notably /var on macOS).
46
+ const paths = [...prompt.matchAll(/(?:^|[\s"'`])((?:\/|[A-Za-z]:[\\/])[^\s"'`]+)/g)].map((match) => match[1]);
47
+ for (const match of prompt.matchAll(/["']([^"']+)["']/g)) {
48
+ if (path.isAbsolute(match[1])) paths.push(match[1]);
49
+ }
50
+ for (const value of paths) {
51
+ const name = packetAt(value, specsRoot, projectRoot);
52
+ if (names.includes(name)) named.push(name);
53
+ }
54
+ return [...new Set(named)];
55
+ }
56
+
57
+ function explicitFailure(payload) {
58
+ const failed = (value) => {
59
+ if (!value || typeof value !== 'object') return false;
60
+ if (value.success === false || value.is_error === true || value.isError === true
61
+ || value.ok === false || value.error || ['error', 'failed', 'failure'].includes(value.status)) return true;
62
+ return ['exit_code', 'exitCode'].some((key) => value[key] !== undefined && value[key] !== 0);
63
+ };
64
+ return payload.success === false || failed(payload.tool_response);
65
+ }
66
+
67
+ module.exports = { canonicalTarget, packetAt, namedPackets, explicitFailure };
@@ -0,0 +1,77 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const VERSION = /^\d+\.\d+\.\d+$/;
6
+ const CACHE_TTL = 12 * 60 * 60 * 1000;
7
+
8
+ function fetchLatestVersion() {
9
+ try {
10
+ const https = require('https');
11
+ return new Promise((resolve) => {
12
+ const req = https.get(
13
+ 'https://registry.npmjs.org/@haposoft/cafekit/latest',
14
+ { timeout: 3000, headers: { Accept: 'application/json' } },
15
+ (res) => {
16
+ let body = '';
17
+ res.on('error', () => resolve(null));
18
+ res.on('aborted', () => resolve(null));
19
+ res.on('data', (chunk) => { body += chunk; });
20
+ res.on('end', () => {
21
+ try { resolve(JSON.parse(body).version || null); } catch { resolve(null); }
22
+ });
23
+ }
24
+ );
25
+ req.on('error', () => resolve(null));
26
+ req.on('timeout', () => { req.destroy(); resolve(null); });
27
+ });
28
+ } catch { return Promise.resolve(null); }
29
+ }
30
+
31
+ function isNewer(a, b) {
32
+ const n = (v) => String(v).split('.').map((x) => parseInt(x, 10) || 0);
33
+ const [aN, bN] = [n(a), n(b)];
34
+ for (let i = 0; i < 3; i++) {
35
+ if (bN[i] > aN[i]) return true;
36
+ if (bN[i] < aN[i]) return false;
37
+ }
38
+ return false;
39
+ }
40
+
41
+ function getInstalledVersion(runtimeDirectory) {
42
+ try {
43
+ const meta = JSON.parse(fs.readFileSync(path.join(runtimeDirectory, 'cafekit.json'), 'utf8'));
44
+ return typeof meta.version === 'string' ? meta.version : null;
45
+ } catch { return null; }
46
+ }
47
+
48
+ function noticeFor(installed, latest) {
49
+ return isNewer(installed, latest)
50
+ ? `\n⚡ CafeKit update available: ${installed} → ${latest}\n Run: npx @haposoft/cafekit\n`
51
+ : '';
52
+ }
53
+
54
+ async function checkCafeKitUpdate(runtimeDirectory, fetchVersion = fetchLatestVersion) {
55
+ const installed = getInstalledVersion(runtimeDirectory);
56
+ if (!installed) return '';
57
+ const cachePath = path.join(runtimeDirectory, '.cafekit-update-cache.json');
58
+ const now = Date.now();
59
+ try {
60
+ const cache = JSON.parse(fs.readFileSync(cachePath, 'utf8'));
61
+ if (typeof cache.ts === 'number' && Number.isFinite(cache.ts) && cache.ts <= now
62
+ && now - cache.ts < CACHE_TTL && typeof cache.latest === 'string' && VERSION.test(cache.latest)) {
63
+ return noticeFor(installed, cache.latest);
64
+ }
65
+ } catch {
66
+ // Missing, corrupt or legacy cache requires a fresh version fetch.
67
+ }
68
+ let latest;
69
+ try { latest = await fetchVersion(); } catch { return ''; }
70
+ if (typeof latest !== 'string' || !VERSION.test(latest)) return '';
71
+ try {
72
+ fs.writeFileSync(cachePath, JSON.stringify({ ts: Date.now(), latest }), 'utf8');
73
+ } catch { /* cache persistence is optional */ }
74
+ return noticeFor(installed, latest);
75
+ }
76
+
77
+ module.exports = { fetchLatestVersion, isNewer, getInstalledVersion, checkCafeKitUpdate };
@@ -23,27 +23,16 @@
23
23
 
24
24
  const fs = require('fs');
25
25
  const path = require('path');
26
+ const crypto = require('crypto');
26
27
  const { spawnSync } = require('child_process');
27
28
 
28
- const RECOVERY_FILE = 'compact-recovery.json';
29
-
30
29
  function gitLine(root, args) {
31
- const result = spawnSync('git', ['-C', root, ...args], { encoding: 'utf8' });
30
+ const result = spawnSync('git', ['-C', root, ...args], { encoding: 'utf8', timeout: 3000 });
32
31
  if (result.error || result.status !== 0) return null;
33
32
  const value = String(result.stdout || '').trim();
34
33
  return value === '' ? null : value;
35
34
  }
36
35
 
37
- function projectRoot(payload) {
38
- const configured = typeof process.env.CLAUDE_PROJECT_DIR === 'string' ? process.env.CLAUDE_PROJECT_DIR.trim() : '';
39
- const candidates = [configured, typeof payload.cwd === 'string' ? payload.cwd.trim() : '', process.cwd()];
40
- for (const candidate of candidates) {
41
- if (!candidate) continue;
42
- try { return fs.realpathSync(path.resolve(candidate)); } catch { /* next */ }
43
- }
44
- return process.cwd();
45
- }
46
-
47
36
  /** The one task the packet currently says is in flight, if any. */
48
37
  function activeTask(root) {
49
38
  try {
@@ -72,13 +61,16 @@ try {
72
61
  const { normalizeHookPayload } = require('./lib/hook-payload.cjs');
73
62
  const payload = stdin ? normalizeHookPayload(JSON.parse(stdin)) : {};
74
63
  if (!payload || typeof payload !== 'object' || Array.isArray(payload)) process.exit(0);
64
+ const sessionId = payload.session_id;
65
+ if (typeof sessionId !== 'string' || !sessionId.trim()) process.exit(0);
75
66
 
67
+ const { projectRoot } = require('./lib/project-root.cjs');
76
68
  const root = projectRoot(payload);
77
69
  const status = gitLine(root, ['status', '--porcelain']);
78
70
  const record = {
79
71
  captured_at: new Date().toISOString(),
80
72
  trigger: typeof payload.trigger === 'string' ? payload.trigger : null,
81
- session_id: typeof payload.session_id === 'string' ? payload.session_id : null,
73
+ session_id: sessionId,
82
74
  project_root: root,
83
75
  branch: gitLine(root, ['rev-parse', '--abbrev-ref', 'HEAD']),
84
76
  head: gitLine(root, ['rev-parse', '--short', 'HEAD']),
@@ -88,7 +80,8 @@ try {
88
80
 
89
81
  const dir = require('./lib/hook-state-dir.cjs').hookStateDir();
90
82
  fs.mkdirSync(dir, { recursive: true });
91
- const target = path.join(dir, RECOVERY_FILE);
83
+ const key = crypto.createHash('sha256').update(sessionId).digest('hex');
84
+ const target = path.join(dir, `compact-recovery-${key}.json`);
92
85
  const temp = `${target}.${process.pid}.tmp`;
93
86
  fs.writeFileSync(temp, `${JSON.stringify(record, null, 2)}\n`);
94
87
  fs.renameSync(temp, target);
@@ -14,32 +14,22 @@
14
14
  * Exit: 0 (the JSON hook output carries the permission decision)
15
15
  */
16
16
 
17
- try {
18
- const fs = require('fs');
19
- const path = require('path');
20
- const { commandAccess } = require('./lib/privacy-command-analysis.cjs');
17
+ const EVALUATION_FAILURE = 'Sensitive access could not be evaluated safely.';
21
18
 
22
- const RESTRICTED_PATTERNS = [
23
- /^\.env(?:[.\[*?{]|$)/i,
24
- /^credentials/i,
25
- /secrets?\.(ya?ml|json)$/i,
26
- /\.pem$/i,
27
- /\.key$/i,
28
- /\.p12$/i,
29
- /\.pfx$/i,
30
- /^id_(rsa|ed25519|ecdsa|dsa)$/i,
31
- /\.netrc$/i,
32
- /\.pgpass$/i,
33
- /kubeconfig/i,
34
- /\.keystore$/i,
35
- /\.jks$/i,
36
- /auth\.json$/i,
37
- /token(s)?\.json$/i
38
- ];
19
+ function askForPermission(reason) {
20
+ process.stdout.write(JSON.stringify({
21
+ hookSpecificOutput: {
22
+ hookEventName: 'PreToolUse',
23
+ permissionDecision: 'ask',
24
+ permissionDecisionReason: reason
25
+ }
26
+ }) + '\n');
27
+ }
39
28
 
40
- const ALLOWED_EXEMPTIONS = [
41
- /\.env\.(example|sample|template|test)$/i
42
- ];
29
+ try {
30
+ const fs = require('fs');
31
+ const { sensitivePaths, displayNames } = require('./lib/privacy-paths.cjs');
32
+ const { projectRoot: resolveProjectRoot } = require('./lib/project-root.cjs');
43
33
 
44
34
  const { runtimeDirName, runtimeDir, runtimePath } = require('./lib/runtime-dir.cjs');
45
35
  function readRuntime(cwd) {
@@ -51,199 +41,27 @@ try {
51
41
  }
52
42
  }
53
43
 
54
- function isSafe(filePath) {
55
- const base = path.basename(filePath);
56
- return ALLOWED_EXEMPTIONS.some((rule) => rule.test(base) || rule.test(filePath));
57
- }
58
-
59
- function isSensitive(filePath) {
60
- const base = path.basename(filePath);
61
- return RESTRICTED_PATTERNS.some((rule) => rule.test(base) || rule.test(filePath));
62
- }
63
-
64
- /**
65
- * Resolve a symlink to its real target so a harmless-looking name that points
66
- * at a sensitive file cannot slip through the basename check. Returns null
67
- * when the path cannot be resolved (missing file, broken link) — fail-open to
68
- * the original-path check in that case. See isSymlinkToSensitive for dangling handling.
69
- */
70
- function resolveTarget(filePath, cwd) {
71
- try {
72
- const requested = path.isAbsolute(filePath) ? filePath : path.resolve(cwd, filePath);
73
- return fs.realpathSync(requested);
74
- } catch {
75
- return null;
76
- }
77
- }
78
-
79
- /**
80
- * When realpath fails, check whether the requested path is a symlink (or chain)
81
- * whose lexical target is sensitive. Dangling link to protected target -> true (fail-closed ask);
82
- * dangling benign link or link to allowed example/template -> false (allow).
83
- * Limit hops to avoid loops; malformed/looping -> fail closed.
84
- * TOCTOU note: check and use are not atomic; target could be swapped between this check and the actual read.
85
- * This is a best-effort guardrail, not an arbitrary-shell security boundary. For strong isolation use OS sandbox.
86
- */
87
- function isSymlinkToSensitive(filePath, cwd) {
88
- try {
89
- const requested = path.isAbsolute(filePath) ? filePath : path.resolve(cwd, filePath);
90
- let current = requested;
91
- let hops = 0;
92
- const MAX_HOPS = 8;
93
- while (hops < MAX_HOPS) {
94
- let stat;
95
- try {
96
- stat = fs.lstatSync(current);
97
- } catch {
98
- return false;
99
- }
100
- if (!stat.isSymbolicLink()) return false;
101
- let linkTarget;
102
- try {
103
- linkTarget = fs.readlinkSync(current);
104
- } catch {
105
- return true;
106
- }
107
- if (isSensitive(linkTarget) && !isSafe(linkTarget)) return true;
108
- if (isSafe(linkTarget)) return false;
109
- const next = path.isAbsolute(linkTarget) ? linkTarget : path.resolve(path.dirname(current), linkTarget);
110
- if (next === current) return true;
111
- try {
112
- const real = fs.realpathSync(next);
113
- if (isSensitive(real) && !isSafe(real)) return true;
114
- if (isSafe(real)) return false;
115
- return false;
116
- } catch {
117
- current = next;
118
- hops += 1;
119
- continue;
120
- }
121
- }
122
- return true;
123
- } catch {
124
- return true;
125
- }
126
- }
127
-
128
- function extractBashPaths(command) {
129
- // The analyzer parses the command and returns the operands of every reading
130
- // command it recognises, nested shells and `find -exec` included. Treating
131
- // every unresolved expansion as sensitive, as this did before, asked on
132
- // `cat $FILE`, `wc -l *.cjs` and `cat ~/.zshrc` alike. Noise is what trains
133
- // people to click through the prompt that matters.
134
- // A heredoc whose delimiter is quoted (<<'BODY') is inert: the shell
135
- // expands nothing inside it, so no word in the body is ever read. The
136
- // analyzer has no notion of heredocs and parses the body as shell, so prose
137
- // that quotes a command -- a PR body carrying `cat .env` in backticks --
138
- // came back as a real command substitution. Blank those bodies out first.
139
- // An unquoted delimiter (<<BODY) does expand, so it is left to the
140
- // analyzer.
141
- const scrubbed = String(command).replace(
142
- /(<<-?[ \t]*)(['"])([A-Za-z_]\w*)\2[^\n]*\n[\s\S]*?\n[ \t]*\3\b/g,
143
- '$1$2$3$2'
144
- );
145
-
146
- const paths = new Set(commandAccess(scrubbed).paths);
147
-
148
- // Two shapes the analyzer cannot return. It drops any word carrying an
149
- // expansion, so `~/.ssh/id_rsa` and `certs/*.pem` still have to be matched
150
- // by name. And it only walks commands it recognises, so an unknown tool
151
- // handed a secret through a file-shaped option, such as
152
- // `docker compose --env-file .env`, is invisible to it.
153
- const FILE_OPTION = /^--?[\w-]*(?:file|config|key|cert|identity)$/i;
154
- const tokens = scrubbed.split(/[\s|;&<>"'()`]+/);
155
- for (let index = 0; index < tokens.length; index += 1) {
156
- const token = tokens[index];
157
- const shaped = /^~|[*?[{]/.test(token);
158
- const optionFed = index > 0 && FILE_OPTION.test(tokens[index - 1]);
159
- if (!shaped && !optionFed) continue;
160
- const value = token.replace(/^~/, '').replace(/^["'()`]+|["'(),]+$/g, '');
161
- if (value && isSensitive(value) && !isSafe(value)) paths.add(value);
162
- }
163
-
164
- return [...paths];
165
- }
166
-
167
- function extractPaths(toolName, input) {
168
- const paths = [];
169
- if (!input) return paths;
170
-
171
- for (const key of ['file_path', 'path']) {
172
- if (typeof input[key] === 'string' && input[key].trim()) {
173
- paths.push(input[key].trim());
174
- }
175
- }
176
-
177
- for (const key of ['paths', 'search_paths']) {
178
- if (Array.isArray(input[key])) {
179
- paths.push(...input[key].filter(Boolean));
180
- }
181
- }
182
-
183
- if (toolName === 'Bash' && typeof input.command === 'string') {
184
- paths.push(...extractBashPaths(input.command));
185
- }
186
-
187
- return paths.filter(Boolean);
188
- }
189
-
190
- function askForPermission(filePath) {
191
- const basename = path.basename(filePath);
192
- process.stdout.write(JSON.stringify({
193
- hookSpecificOutput: {
194
- hookEventName: 'PreToolUse',
195
- permissionDecision: 'ask',
196
- permissionDecisionReason: `Sensitive file access requires approval: ${basename}`
197
- }
198
- }) + '\n');
199
- }
200
-
201
44
  const stdin = fs.readFileSync(0, 'utf8').trim();
202
- if (!stdin) process.exit(0);
45
+ if (!stdin) {
46
+ askForPermission(EVALUATION_FAILURE);
47
+ process.exit(0);
48
+ }
203
49
 
204
50
  const { normalizeHookPayload } = require('./lib/hook-payload.cjs');
205
51
  const data = normalizeHookPayload(JSON.parse(stdin));
206
52
  const toolName = data.tool_name || '';
207
53
  const toolInput = data.tool_input || {};
208
54
  const cwd = typeof data.cwd === 'string' && data.cwd.trim() ? data.cwd : process.cwd();
209
- const runtime = readRuntime(cwd);
55
+ const projectRoot = resolveProjectRoot(data);
56
+ const runtime = readRuntime(projectRoot);
210
57
 
211
58
  if (runtime.privacyBlock === false) process.exit(0);
212
59
 
213
- const paths = extractPaths(toolName, toolInput);
214
- if (!paths.length) process.exit(0);
215
-
216
- for (const filePath of paths) {
217
- const target = resolveTarget(filePath, cwd);
218
-
219
- // The real target is authoritative: an exempt-looking alias must not hide
220
- // a sensitive target, while a real .env.example target remains safe.
221
- if (target) {
222
- if (isSensitive(target) && !isSafe(target)) {
223
- askForPermission(filePath);
224
- process.exit(0);
225
- }
226
- if (isSafe(target)) continue;
227
- } else {
228
- if (isSymlinkToSensitive(filePath, cwd)) {
229
- askForPermission(filePath);
230
- process.exit(0);
231
- }
232
- }
233
-
234
- if (isSafe(filePath) || !isSensitive(filePath)) continue;
235
- askForPermission(filePath);
236
- process.exit(0);
237
- }
60
+ const paths = sensitivePaths(toolName, toolInput, cwd);
61
+ if (paths.length) askForPermission(`Sensitive file access requires approval: ${displayNames(paths)}`);
238
62
 
239
63
  process.exit(0);
240
64
  } catch (_) {
241
- process.stdout.write(JSON.stringify({
242
- hookSpecificOutput: {
243
- hookEventName: 'PreToolUse',
244
- permissionDecision: 'ask',
245
- permissionDecisionReason: 'Sensitive access could not be evaluated safely.'
246
- }
247
- }) + '\n');
65
+ askForPermission(EVALUATION_FAILURE);
248
66
  process.exit(0);
249
67
  }
@@ -11,12 +11,12 @@
11
11
  */
12
12
 
13
13
  try {
14
- const crypto = require('crypto');
15
14
  const fs = require('fs');
16
- const os = require('os');
17
15
  const path = require('path');
18
16
 
19
17
  const { runtimeDirName, runtimeDir, runtimePath } = require('./lib/runtime-dir.cjs');
18
+ const { projectRoot } = require('./lib/project-root.cjs');
19
+ const { reserveSession } = require('./lib/rules-reservation.cjs');
20
20
  function readRuntime(cwd) {
21
21
  try {
22
22
  const p = runtimePath(cwd, 'runtime.json');
@@ -24,26 +24,6 @@ try {
24
24
  } catch { return null; }
25
25
  }
26
26
 
27
- /** Reserve one injection slot per session. Returns null on reservation errors. */
28
- function reserveSession(sessionId) {
29
- if (!sessionId) return null;
30
- try {
31
- const key = crypto.createHash('sha256')
32
- .update(String(sessionId))
33
- .digest('hex')
34
- .slice(0, 16);
35
- const file = path.join(os.tmpdir(), `cafekit-rules-${key}.json`);
36
- fs.writeFileSync(file, JSON.stringify({ sessionId: String(sessionId) }), {
37
- encoding: 'utf8',
38
- flag: 'wx',
39
- mode: 0o600
40
- });
41
- return true;
42
- } catch (error) {
43
- return error.code === 'EEXIST' ? false : null;
44
- }
45
- }
46
-
47
27
  // ── Main ──────────────────────────────────────────────────────────────────
48
28
 
49
29
  const stdin = fs.readFileSync(0, 'utf8').trim();
@@ -52,22 +32,20 @@ try {
52
32
  const { normalizeHookPayload } = require('./lib/hook-payload.cjs');
53
33
  const payload = normalizeHookPayload(JSON.parse(stdin));
54
34
  const sessionId = payload.session_id || null;
55
- const payloadCwd = typeof payload.cwd === 'string' ? payload.cwd.trim() : '';
56
- const cwd = payloadCwd || process.env.PROJECT_ROOT || process.cwd();
35
+ const root = projectRoot(payload);
36
+ const runtime = readRuntime(root);
37
+ if (runtime === null) process.exit(0);
57
38
 
58
39
  // No session identity or reservation means no injection. Fail open.
59
40
  if (reserveSession(sessionId) !== true) process.exit(0);
60
41
 
61
- const runtime = readRuntime(cwd);
62
- if (runtime === null) process.exit(0);
63
-
64
42
  // Language
65
43
  const thinkLang = runtime.locale?.thinkingLanguage || '';
66
44
  const respondLang = runtime.locale?.responseLanguage || '';
67
45
  const effectThink = thinkLang || (respondLang ? 'en' : '');
68
46
 
69
47
  // Paths
70
- const baseDir = cwd;
48
+ const baseDir = root;
71
49
  const plansPath = path.join(baseDir, runtime.paths?.plans || 'plans');
72
50
  const docsPath = path.join(baseDir, runtime.paths?.docs || 'docs');
73
51
  const specsPath = path.join(baseDir, runtime.paths?.specs || 'specs');