@haposoft/cafekit 0.16.0 → 0.16.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 (66) hide show
  1. package/README.md +5 -3
  2. package/bin/__tests__/codex-hooks.test.js +125 -0
  3. package/bin/__tests__/codex-native.test.js +95 -0
  4. package/bin/__tests__/develop-contract.test.js +43 -1
  5. package/bin/__tests__/grok-envelope.test.js +271 -0
  6. package/bin/__tests__/grok-platform.test.js +133 -0
  7. package/bin/__tests__/hook-payload.test.js +194 -0
  8. package/bin/__tests__/omp-bridge.test.js +168 -0
  9. package/bin/__tests__/omp-hooks.test.js +178 -0
  10. package/bin/__tests__/omp-runtime.test.js +150 -0
  11. package/bin/__tests__/orca-session.test.js +225 -0
  12. package/bin/__tests__/orca-skill.test.js +210 -0
  13. package/bin/__tests__/package-inventory.test.js +1 -0
  14. package/bin/__tests__/runtime-dir.test.js +158 -0
  15. package/bin/__tests__/runtime-schema.test.js +5 -3
  16. package/bin/__tests__/specs-v2-execution-closeout.test.js +28 -1
  17. package/bin/install.js +5 -5
  18. package/bin/lib/context.js +50 -3
  19. package/bin/lib/i18n.js +3 -30
  20. package/bin/phases/codex-hooks.js +90 -17
  21. package/bin/phases/copy-payload.js +7 -0
  22. package/bin/phases/omp-runtime.js +140 -0
  23. package/bin/phases/root-config.js +3 -0
  24. package/bin/phases/select-platform.js +22 -1
  25. package/bin/phases/summary.js +0 -4
  26. package/package.json +1 -1
  27. package/src/claude/hooks/__tests__/semantic-review-authority.test.js +2 -0
  28. package/src/claude/hooks/__tests__/spec-gate.test.js +338 -0
  29. package/src/claude/hooks/__tests__/state.test.js +2 -0
  30. package/src/claude/hooks/agent.cjs +12 -7
  31. package/src/claude/hooks/completion-authority.cjs +10 -4
  32. package/src/claude/hooks/docs-sync.cjs +2 -1
  33. package/src/claude/hooks/inspect-block.cjs +27 -7
  34. package/src/claude/hooks/lib/config.cjs +5 -2
  35. package/src/claude/hooks/lib/counter.cjs +7 -5
  36. package/src/claude/hooks/lib/hook-payload.cjs +160 -0
  37. package/src/claude/hooks/lib/hook-state-dir.cjs +2 -2
  38. package/src/claude/hooks/lib/runtime-dir.cjs +49 -0
  39. package/src/claude/hooks/precompact.cjs +2 -1
  40. package/src/claude/hooks/privacy-block.cjs +4 -2
  41. package/src/claude/hooks/rules.cjs +4 -2
  42. package/src/claude/hooks/secret-output-guardrail.cjs +2 -1
  43. package/src/claude/hooks/semantic-review-authority.cjs +6 -4
  44. package/src/claude/hooks/session.cjs +16 -8
  45. package/src/claude/hooks/spec-gate.cjs +18 -8
  46. package/src/claude/hooks/spec-state.cjs +9 -5
  47. package/src/claude/hooks/state.cjs +6 -4
  48. package/src/claude/hooks/task-scaffold-guard.cjs +29 -8
  49. package/src/claude/hooks/usage.cjs +5 -4
  50. package/src/claude/migration-manifest.json +3 -0
  51. package/src/claude/rules/skill-domain-routing.md +1 -0
  52. package/src/claude/rules/state-sync.md +7 -1
  53. package/src/claude/rules/workflow.md +2 -0
  54. package/src/claude/scripts/provenance.cjs +11 -4
  55. package/src/claude/scripts/spec-receipt.cjs +65 -4
  56. package/src/claude/skills/orca/SKILL.md +51 -0
  57. package/src/claude/skills/specs/SKILL.md +10 -11
  58. package/src/codex/hooks/session.cjs +6 -1
  59. package/src/codex/hooks/spec-state.cjs +1 -1
  60. package/src/codex/hooks.json +18 -18
  61. package/src/codex/rules/state-sync.md +7 -1
  62. package/src/omp/extensions/cafekit-bridge.mjs +233 -0
  63. package/src/omp/hooks/privacy-block.cjs +250 -0
  64. package/src/omp/runtime.json +33 -0
  65. package/bin/lib/rtk-run.js +0 -28
  66. package/bin/phases/setup-rtk.js +0 -159
@@ -0,0 +1,160 @@
1
+ /**
2
+ * Copyright (c) 2026 Haposoft. MIT License.
3
+ *
4
+ * Hook payload normalization.
5
+ *
6
+ * The gate hooks were written against Claude Code's stdin envelope: snake_case keys and
7
+ * capitalised tool names. Two other hosts run the very same scripts with a different
8
+ * spelling. Grok CLI loads `.claude/settings.json` through its Claude-compatibility layer
9
+ * but sends camelCase keys (`toolName`, `stopHookActive`) and its own tool names
10
+ * (`run_terminal_command`, `read_file`, `search_replace`). Oh My Pi's bridge sends
11
+ * Claude-shaped keys with lowercase tool names (`bash`, `read`).
12
+ *
13
+ * A hook that reads `data.tool_name` on a grok payload gets `undefined`, extracts no
14
+ * paths, and allows the call: the gate looks installed and is open. This module is the
15
+ * one place that reconciles those spellings, so every hook keeps a single code path.
16
+ *
17
+ * Two rules earn their keep:
18
+ *
19
+ * 1. The tool name is aliased by VALUE, under any key. omp already sends `tool_name`,
20
+ * so a key-only translation would silently skip its lowercase names.
21
+ * 2. Every name that can reach a `Bash` matcher must map to `Bash`. Grok expands
22
+ * matchers by alias, so a shell call can arrive under a name the hook does not
23
+ * recognise; an unmapped name skips the command scan and a secret-bearing command
24
+ * is never examined.
25
+ *
26
+ * The reader is total: it never throws. Callers include two fail-closed hooks whose final
27
+ * catch emits a block, so an exception here would block the Stop gate on Claude too.
28
+ */
29
+
30
+ 'use strict';
31
+
32
+ /** Grok's event values are snake_case; the hooks compare against Claude's PascalCase. */
33
+ const EVENT_NAMES = Object.freeze({
34
+ pre_tool_use: 'PreToolUse',
35
+ post_tool_use: 'PostToolUse',
36
+ post_tool_use_failure: 'PostToolUseFailure',
37
+ permission_denied: 'PermissionDenied',
38
+ user_prompt_submit: 'UserPromptSubmit',
39
+ session_start: 'SessionStart',
40
+ session_end: 'SessionEnd',
41
+ stop: 'Stop',
42
+ stop_failure: 'StopFailure',
43
+ stop_cancelled: 'StopCancelled',
44
+ subagent_start: 'SubagentStart',
45
+ subagent_stop: 'SubagentStop',
46
+ pre_compact: 'PreCompact',
47
+ post_compact: 'PostCompact',
48
+ notification: 'Notification',
49
+ });
50
+
51
+ /**
52
+ * Foreign tool names to the Claude names the rules were authored against.
53
+ *
54
+ * Grok's registry and matcher aliases come first, then omp's lowercase registry. Where
55
+ * both hosts use a spelling (`write`, `grep`) they agree on the destination. `write` is
56
+ * grok's file-creating tool and maps to `Write`, while `search_replace` edits an existing
57
+ * file and maps to `Edit`; conflating them would make the scaffold guard reject ordinary
58
+ * edits. `delete_file` maps to `Write` so a delete is gated like any other file write.
59
+ */
60
+ const TOOL_ALIASES = Object.freeze({
61
+ // grok — every spelling that reaches a Bash matcher
62
+ run_terminal_command: 'Bash',
63
+ run_terminal_cmd: 'Bash',
64
+ PowerShell: 'Bash',
65
+ // grok — file and search tools
66
+ read_file: 'Read',
67
+ hashline_read: 'Read',
68
+ search_replace: 'Edit',
69
+ hashline_edit: 'Edit',
70
+ write: 'Write',
71
+ delete_file: 'Write',
72
+ grep: 'Grep',
73
+ grep_search: 'Grep',
74
+ hashline_grep: 'Grep',
75
+ list_dir: 'Glob',
76
+ web_search: 'WebSearch',
77
+ web_fetch: 'WebFetch',
78
+ spawn_subagent: 'Task',
79
+ todo_write: 'TodoWrite',
80
+ // omp — lowercase registry
81
+ bash: 'Bash',
82
+ read: 'Read',
83
+ edit: 'Edit',
84
+ glob: 'Glob',
85
+ find: 'Glob',
86
+ ls: 'Glob',
87
+ webfetch: 'WebFetch',
88
+ websearch: 'WebSearch',
89
+ });
90
+
91
+ /**
92
+ * Camel-cased foreign key to the snake_case key the hooks read.
93
+ *
94
+ * `transcriptPath` is deliberately absent: grok stores sessions in its own format, and
95
+ * mapping it would make `state.cjs` stream a file it cannot parse. The last three pairs
96
+ * cover fields whose grok spelling is unverified, so both spellings are accepted.
97
+ */
98
+ const KEY_ALIASES = Object.freeze({
99
+ hookEventName: 'hook_event_name',
100
+ sessionId: 'session_id',
101
+ stopHookActive: 'stop_hook_active',
102
+ lastAssistantMessage: 'last_assistant_message',
103
+ toolName: 'tool_name',
104
+ toolInput: 'tool_input',
105
+ toolUseId: 'tool_use_id',
106
+ toolResult: 'tool_response',
107
+ subagentType: 'agent_type',
108
+ subagentId: 'agent_id',
109
+ permissionMode: 'permission_mode',
110
+ workspaceRoot: 'workspace_root',
111
+ userPrompt: 'prompt',
112
+ startSource: 'source',
113
+ compactTrigger: 'trigger',
114
+ });
115
+
116
+ const owns = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
117
+
118
+ /** The Claude name for a foreign tool, or the input unchanged when unknown. */
119
+ function normalizeToolName(name) {
120
+ if (typeof name !== 'string' || name === '') return name;
121
+ return owns(TOOL_ALIASES, name) ? TOOL_ALIASES[name] : name;
122
+ }
123
+
124
+ /** The Claude name for an event value, or the input unchanged (already PascalCase). */
125
+ function normalizeEventName(value) {
126
+ if (typeof value !== 'string' || value === '') return value;
127
+ return owns(EVENT_NAMES, value) ? EVENT_NAMES[value] : value;
128
+ }
129
+
130
+ /**
131
+ * A hook payload in the shape the gate scripts read, whatever host sent it.
132
+ *
133
+ * Anything that is not a plain object is returned as-is rather than coerced, so a caller
134
+ * that already guards on shape keeps its own behaviour. The input is never mutated.
135
+ */
136
+ function normalizeHookPayload(payload) {
137
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return payload;
138
+
139
+ const out = { ...payload };
140
+
141
+ // A snake_case key already present wins: the host that sent it meant it.
142
+ for (const [foreign, native] of Object.entries(KEY_ALIASES)) {
143
+ if (owns(out, foreign) && !owns(out, native)) out[native] = out[foreign];
144
+ }
145
+
146
+ if (owns(out, 'hook_event_name')) out.hook_event_name = normalizeEventName(out.hook_event_name);
147
+ // By value, under whichever key carried it — omp sends `tool_name` with a lowercase value.
148
+ if (owns(out, 'tool_name')) out.tool_name = normalizeToolName(out.tool_name);
149
+
150
+ // grok's `read_file` carries its argument as `path`; the hooks read `file_path`.
151
+ const input = out.tool_input;
152
+ if (input && typeof input === 'object' && !Array.isArray(input)
153
+ && owns(input, 'path') && !owns(input, 'file_path')) {
154
+ out.tool_input = { ...input, file_path: input.path };
155
+ }
156
+
157
+ return out;
158
+ }
159
+
160
+ module.exports = { normalizeHookPayload, normalizeToolName, TOOL_ALIASES, KEY_ALIASES, EVENT_NAMES };
@@ -5,7 +5,7 @@
5
5
  * gate/tollgate caches.
6
6
  *
7
7
  * Hooks run from two places. In an installed project they live in
8
- * `.claude/hooks/`, whose `.logs/` is gitignored, so writing beside the hook is
8
+ * `<runtime-dir>/hooks/`, whose `.logs/` is gitignored, so writing beside the hook is
9
9
  * correct. During this package's tests they run straight from
10
10
  * `packages/spec/src/claude/hooks/`, where the same write lands inside the
11
11
  * source tree as an untracked directory. That changes the worktree digest the
@@ -32,7 +32,7 @@ function isSourceTree(dir) {
32
32
  /** Absolute directory for hook-generated state; create it before writing. */
33
33
  function hookStateDir() {
34
34
  return isSourceTree(HOOKS_DIR)
35
- ? path.join(os.tmpdir(), 'cafekit-hook-logs', 'claude')
35
+ ? path.join(os.tmpdir(), 'cafekit-hook-logs', require('./runtime-dir.cjs').runtimeDirName().slice(1))
36
36
  : path.join(HOOKS_DIR, '.logs');
37
37
  }
38
38
 
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Copyright (c) 2026 Haposoft. MIT License.
3
+ *
4
+ * Runtime-directory derivation for the gate hooks.
5
+ *
6
+ * The hooks used to hardcode `.claude` in every project-runtime path, so a copy installed
7
+ * under `.omp/hooks/` or `.codex/hooks/` read another platform's config, never matched
8
+ * installed-root detection, and wrote session state into a directory that did not exist.
9
+ * This module ships in `hooks/lib/`, so the runtime root is always two levels up from
10
+ * here and its basename is the answer: `.claude`, `.codex`, or `.omp`.
11
+ *
12
+ * In the source tree the same files live at `packages/spec/src/<platform>/hooks/lib/`, so
13
+ * the basename is the undotted platform name; it is mapped to its dotted form so tests
14
+ * that run hooks from source see the same directory an install would. A dotted basename
15
+ * always wins over the source-tree check, because an install can legitimately sit under a
16
+ * path that happens to contain `/packages/spec/src/`.
17
+ *
18
+ * Anything else yields `.claude`, which is exactly the behaviour every caller had before
19
+ * this module existed. There is deliberately no "derived" flag: nobody would read it.
20
+ *
21
+ * The source-tree marker is inlined rather than required from `hook-state-dir.cjs` so a
22
+ * fixture that copies a hook by hand needs to copy only this one library.
23
+ */
24
+
25
+ const path = require('path');
26
+
27
+ const SOURCE_MARKER = `${path.sep}packages${path.sep}spec${path.sep}src${path.sep}`;
28
+ const HOOKS_DIR = path.resolve(__dirname, '..');
29
+ const RUNTIME_ROOT = path.resolve(HOOKS_DIR, '..');
30
+
31
+ /** `.claude`, `.codex`, `.omp`, or whatever dotted folder this hook tree is installed under. */
32
+ function runtimeDirName() {
33
+ const base = path.basename(RUNTIME_ROOT);
34
+ if (base.startsWith('.')) return base;
35
+ if (HOOKS_DIR.includes(SOURCE_MARKER)) return `.${base}`;
36
+ return '.claude';
37
+ }
38
+
39
+ /** Absolute runtime directory for a project, e.g. `<cwd>/.omp`. */
40
+ function runtimeDir(cwd) {
41
+ return path.join(cwd, runtimeDirName());
42
+ }
43
+
44
+ /** Absolute path under the runtime directory, e.g. `runtimePath(cwd, 'runtime.json')`. */
45
+ function runtimePath(cwd, ...segments) {
46
+ return path.join(runtimeDir(cwd), ...segments);
47
+ }
48
+
49
+ module.exports = { runtimeDirName, runtimeDir, runtimePath };
@@ -69,7 +69,8 @@ function activeTask(root) {
69
69
 
70
70
  try {
71
71
  const stdin = fs.readFileSync(0, 'utf8').trim();
72
- const payload = stdin ? JSON.parse(stdin) : {};
72
+ const { normalizeHookPayload } = require('./lib/hook-payload.cjs');
73
+ const payload = stdin ? normalizeHookPayload(JSON.parse(stdin)) : {};
73
74
  if (!payload || typeof payload !== 'object' || Array.isArray(payload)) process.exit(0);
74
75
 
75
76
  const root = projectRoot(payload);
@@ -41,9 +41,10 @@ try {
41
41
  /\.env\.(example|sample|template|test)$/i
42
42
  ];
43
43
 
44
+ const { runtimeDirName, runtimeDir, runtimePath } = require('./lib/runtime-dir.cjs');
44
45
  function readRuntime(cwd) {
45
46
  try {
46
- const file = path.join(cwd, '.claude', 'runtime.json');
47
+ const file = runtimePath(cwd, 'runtime.json');
47
48
  return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : {};
48
49
  } catch {
49
50
  return {};
@@ -200,7 +201,8 @@ try {
200
201
  const stdin = fs.readFileSync(0, 'utf8').trim();
201
202
  if (!stdin) process.exit(0);
202
203
 
203
- const data = JSON.parse(stdin);
204
+ const { normalizeHookPayload } = require('./lib/hook-payload.cjs');
205
+ const data = normalizeHookPayload(JSON.parse(stdin));
204
206
  const toolName = data.tool_name || '';
205
207
  const toolInput = data.tool_input || {};
206
208
  const cwd = typeof data.cwd === 'string' && data.cwd.trim() ? data.cwd : process.cwd();
@@ -16,9 +16,10 @@ try {
16
16
  const os = require('os');
17
17
  const path = require('path');
18
18
 
19
+ const { runtimeDirName, runtimeDir, runtimePath } = require('./lib/runtime-dir.cjs');
19
20
  function readRuntime(cwd) {
20
21
  try {
21
- const p = path.join(cwd, '.claude', 'runtime.json');
22
+ const p = runtimePath(cwd, 'runtime.json');
22
23
  return fs.existsSync(p) ? JSON.parse(fs.readFileSync(p, 'utf8')) : null;
23
24
  } catch { return null; }
24
25
  }
@@ -48,7 +49,8 @@ try {
48
49
  const stdin = fs.readFileSync(0, 'utf8').trim();
49
50
  if (!stdin) process.exit(0);
50
51
 
51
- const payload = JSON.parse(stdin);
52
+ const { normalizeHookPayload } = require('./lib/hook-payload.cjs');
53
+ const payload = normalizeHookPayload(JSON.parse(stdin));
52
54
  const sessionId = payload.session_id || null;
53
55
  const payloadCwd = typeof payload.cwd === 'string' ? payload.cwd.trim() : '';
54
56
  const cwd = payloadCwd || process.env.PROJECT_ROOT || process.cwd();
@@ -24,7 +24,8 @@ try {
24
24
  const stdin = fs.readFileSync(0, 'utf8').trim();
25
25
  if (!stdin) process.exit(0);
26
26
 
27
- const payload = JSON.parse(stdin);
27
+ const { normalizeHookPayload } = require('./lib/hook-payload.cjs');
28
+ const payload = normalizeHookPayload(JSON.parse(stdin));
28
29
  const prompt = String(payload.prompt || payload.user_prompt || '');
29
30
  if (!containsSecretKeyword(prompt)) process.exit(0);
30
31
 
@@ -3,6 +3,7 @@
3
3
 
4
4
  const fs = require('fs');
5
5
  const path = require('path');
6
+ const { runtimeDirName, runtimeDir, runtimePath } = require('./lib/runtime-dir.cjs');
6
7
  const { spawnSync } = require('child_process');
7
8
  const STATE = require('./completion-authority-state.cjs');
8
9
  const PATH_SAFETY = require('./lib/runtime-path-safety.cjs');
@@ -28,7 +29,7 @@ function inside(root, target) {
28
29
 
29
30
  function projectRoot(payload = {}) {
30
31
  const installedRoot = path.resolve(__dirname, '..', '..');
31
- if (fs.existsSync(path.join(installedRoot, '.claude', 'hooks', path.basename(__filename)))) {
32
+ if (fs.existsSync(runtimePath(installedRoot, 'hooks', path.basename(__filename)))) {
32
33
  try { return STATE.canonicalProjectRoot(installedRoot); } catch {}
33
34
  }
34
35
  for (const candidate of [process.env.CLAUDE_PROJECT_DIR, process.env.PROJECT_ROOT]) {
@@ -70,7 +71,7 @@ function parseClaim(message) {
70
71
  }
71
72
 
72
73
  function validatorFor(root) {
73
- const installedRoot = path.join(root, '.claude');
74
+ const installedRoot = runtimeDir(root);
74
75
  const installedHook = path.join(installedRoot, 'hooks', path.basename(__filename));
75
76
  if (fs.existsSync(installedHook)) {
76
77
  const canonicalHook = PATH_SAFETY.canonicalRegularFile(root, installedHook, 'installed semantic hook');
@@ -82,7 +83,7 @@ function validatorFor(root) {
82
83
 
83
84
  const sourceRuntime = path.resolve(__dirname, '..');
84
85
  const sourceRoot = path.resolve(sourceRuntime, '..');
85
- if (path.basename(sourceRuntime) !== 'claude' || path.basename(sourceRoot) !== 'src') {
86
+ if (`.${path.basename(sourceRuntime)}` !== runtimeDirName() || path.basename(sourceRoot) !== 'src') {
86
87
  throw new Error('semantic validator runtime root is not recognized');
87
88
  }
88
89
  const validator = path.join(sourceRuntime, 'scripts', 'validate-spec-output.cjs');
@@ -143,7 +144,8 @@ function verifyAttestation(root, specFile, featureName, semanticDigest) {
143
144
  if (require.main === module) {
144
145
  try {
145
146
  const raw = fs.readFileSync(0, 'utf8').trim();
146
- if (raw) recordFromSubagentStop(JSON.parse(raw));
147
+ const { normalizeHookPayload } = require('./lib/hook-payload.cjs');
148
+ if (raw) recordFromSubagentStop(normalizeHookPayload(JSON.parse(raw)));
147
149
  } catch (error) {
148
150
  process.stderr.write(`CafeKit semantic review SubagentStop claim rejected: ${error.message}\n`);
149
151
  }
@@ -14,6 +14,7 @@
14
14
  try {
15
15
  const fs = require('fs');
16
16
  const path = require('path');
17
+ const { runtimeDirName, runtimeDir, runtimePath } = require('./lib/runtime-dir.cjs');
17
18
  const os = require('os');
18
19
  const { execSync } = require('child_process');
19
20
 
@@ -49,16 +50,16 @@ try {
49
50
  }
50
51
 
51
52
  const installedRoot = path.resolve(__dirname, '..', '..');
52
- const installedHook = path.join(installedRoot, '.claude', 'hooks', path.basename(__filename));
53
+ const installedHook = runtimePath(installedRoot, 'hooks', path.basename(__filename));
53
54
  if (fs.existsSync(installedHook)) return installedRoot;
54
55
 
55
56
  try { return fs.realpathSync(process.cwd()); } catch { return path.resolve(process.cwd()); }
56
57
  }
57
58
 
58
- /** Read .claude/runtime.json config */
59
+ /** Read <runtime>/runtime.json config */
59
60
  function readRuntime(cwd) {
60
61
  try {
61
- const p = path.join(cwd, '.claude', 'runtime.json');
62
+ const p = runtimePath(cwd, 'runtime.json');
62
63
  return fs.existsSync(p) ? JSON.parse(fs.readFileSync(p, 'utf8')) : {};
63
64
  } catch { return {}; }
64
65
  }
@@ -143,12 +144,12 @@ try {
143
144
  }
144
145
 
145
146
  /**
146
- * Read the installed CafeKit version from .claude/cafekit.json.
147
+ * Read the installed CafeKit version from <runtime>/cafekit.json.
147
148
  * Returns null if not found.
148
149
  */
149
150
  function getInstalledVersion(cwd) {
150
151
  try {
151
- const p = path.join(cwd, '.claude', 'cafekit.json');
152
+ const p = runtimePath(cwd, 'cafekit.json');
152
153
  if (!fs.existsSync(p)) return null;
153
154
  const meta = JSON.parse(fs.readFileSync(p, 'utf8'));
154
155
  return typeof meta.version === 'string' ? meta.version : null;
@@ -158,14 +159,14 @@ try {
158
159
  /**
159
160
  * Check for a newer CafeKit version and return an update notice string,
160
161
  * or an empty string if already up to date or check fails.
161
- * Result is cached in .claude/.cafekit-update-cache.json for 12 hours.
162
+ * Result is cached in <runtime>/.cafekit-update-cache.json for 12 hours.
162
163
  */
163
164
  async function checkCafeKitUpdate(cwd) {
164
165
  const installed = getInstalledVersion(cwd);
165
166
  if (!installed) return '';
166
167
 
167
168
  const CACHE_TTL = 12 * 60 * 60 * 1000; // 12 hours
168
- const cachePath = path.join(cwd, '.claude', '.cafekit-update-cache.json');
169
+ const cachePath = runtimePath(cwd, '.cafekit-update-cache.json');
169
170
 
170
171
  // Return cached result if still fresh.
171
172
  try {
@@ -195,7 +196,8 @@ try {
195
196
 
196
197
  (async () => {
197
198
  const stdin = fs.readFileSync(0, 'utf8').trim();
198
- const payload = stdin ? JSON.parse(stdin) : {};
199
+ const { normalizeHookPayload } = require('./lib/hook-payload.cjs');
200
+ const payload = stdin ? normalizeHookPayload(JSON.parse(stdin)) : {};
199
201
  const source = payload.source || 'unknown';
200
202
  const envFile = process.env.CLAUDE_ENV_FILE;
201
203
  const cwd = projectRoot();
@@ -252,6 +254,12 @@ try {
252
254
  if (packageManager) parts.push(`PM: ${packageManager}`);
253
255
  if (framework) parts.push(`Framework: ${framework}`);
254
256
  if (gitBranch) parts.push(`Branch: ${gitBranch}`);
257
+ // Orca (onorca.dev) sets this in every pane; it is a presence marker, not a secret.
258
+ // ORCA_AGENT_HOOK_TOKEN and ORCA_AGENT_LAUNCH_TOKEN live in the same environment and
259
+ // must never be read or printed here.
260
+ if (typeof process.env.ORCA_PANE_KEY === 'string' && process.env.ORCA_PANE_KEY !== '') {
261
+ parts.push('Orca: pane');
262
+ }
255
263
 
256
264
  console.log(`Session ${source}. ${parts.length ? parts.join(' | ') : 'No project info detected.'}${updateNotice}`);
257
265
 
@@ -15,6 +15,7 @@
15
15
 
16
16
  const fs = require('fs');
17
17
  const path = require('path');
18
+ const { runtimeDirName, runtimeDir, runtimePath } = require('./lib/runtime-dir.cjs');
18
19
 
19
20
  function projectRoot(payload = {}) {
20
21
  const configured = typeof process.env.CLAUDE_PROJECT_DIR === 'string'
@@ -25,7 +26,7 @@ function projectRoot(payload = {}) {
25
26
  }
26
27
 
27
28
  const installedRoot = path.resolve(__dirname, '..', '..');
28
- const installedHook = path.join(installedRoot, '.claude', 'hooks', path.basename(__filename));
29
+ const installedHook = runtimePath(installedRoot, 'hooks', path.basename(__filename));
29
30
  if (fs.existsSync(installedHook)) return installedRoot;
30
31
 
31
32
  const sourceFixture = typeof process.env.PROJECT_ROOT === 'string'
@@ -78,8 +79,13 @@ try {
78
79
  throw new Error('hook payload must be a JSON object');
79
80
  }
80
81
 
81
- // Never re-block a continuation caused by our own block (infinite-loop guard).
82
- if (payload.stop_hook_active === true) process.exit(0);
82
+ // Never re-block a continuation caused by our own block (infinite-loop guard). Grok
83
+ // spells this `stopHookActive`; both are accepted here rather than through the payload
84
+ // reader, because the catch at the end of this file answers a block, so a reader that
85
+ // threw above the guard would block every completion instead of only a foreign one.
86
+ // The rest of this hook is already host-neutral: sessionIdentity() accepts sessionId
87
+ // and sessionID, the resolver reads camelCase targets, and projectRoot reads cwd.
88
+ if (payload.stop_hook_active === true || payload.stopHookActive === true) process.exit(0);
83
89
 
84
90
  let POLICY;
85
91
  let RESOLVER;
@@ -108,7 +114,7 @@ try {
108
114
  // Missing/malformed runtime.json keeps the gate ON (fail-closed, valve 3 style).
109
115
  let runtime = {};
110
116
  try {
111
- const rp = path.join(cwd, '.claude', 'runtime.json');
117
+ const rp = runtimePath(cwd, 'runtime.json');
112
118
  if (fs.existsSync(rp)) runtime = JSON.parse(fs.readFileSync(rp, 'utf8'));
113
119
  } catch { /* gate stays on */ }
114
120
  // Active-spec discovery via shared resolver — explicit target if present, else fail on ambiguity.
@@ -225,10 +231,14 @@ try {
225
231
  process.exit(0);
226
232
  }
227
233
 
228
- // Cache hardening: every Stop revalidates the canonical receipt for
229
- // every task currently marked done, so a cached PASS cannot hide later
230
- // mutations (deletion, placeholder, changed Verification/Command/Exit/
231
- // Base/Head, stale provenance). Cache is an optimization, not truth.
234
+ // Cache hardening: every Stop re-reads and re-checks the receipt of every
235
+ // task currently marked done, so a cached PASS cannot hide later mutations
236
+ // (deletion, placeholder, changed Verification/Command/Exit, missing
237
+ // output, edited artifact bytes). Base/Head are compared against the live
238
+ // runtime only while the task file differs from its committed bytes or the
239
+ // tree outside the specs root is dirty; a committed, unchanged receipt on a
240
+ // clean tree is checked on structure alone. Cache is an optimization, not
241
+ // truth.
232
242
  const featureCache = cacheExists ? (cache[featureName] || {}) : {};
233
243
  const allDoneTasks = Object.keys(taskRegistry).filter((tp) =>
234
244
  (taskRegistry[tp]?.status || 'pending') === 'done'
@@ -13,6 +13,7 @@
13
13
 
14
14
  const fs = require('fs');
15
15
  const path = require('path');
16
+ const { runtimeDirName, runtimeDir, runtimePath } = require('./lib/runtime-dir.cjs');
16
17
 
17
18
  function logCrash(error) {
18
19
  try {
@@ -49,7 +50,8 @@ try {
49
50
  const stdin = fs.readFileSync(0, 'utf8').trim();
50
51
  if (!stdin) process.exit(0);
51
52
 
52
- const payload = JSON.parse(stdin);
53
+ const { normalizeHookPayload } = require('./lib/hook-payload.cjs');
54
+ const payload = normalizeHookPayload(JSON.parse(stdin));
53
55
  const cwd = payload.cwd || process.cwd();
54
56
 
55
57
  let POLICY;
@@ -69,7 +71,7 @@ try {
69
71
  // Read runtime configuration if exists
70
72
  let runtime = {};
71
73
  try {
72
- const p = path.join(cwd, '.claude', 'runtime.json');
74
+ const p = runtimePath(cwd, 'runtime.json');
73
75
  if (fs.existsSync(p)) runtime = JSON.parse(fs.readFileSync(p, 'utf8'));
74
76
  } catch { /* ignore */ }
75
77
 
@@ -77,7 +79,9 @@ try {
77
79
  // (The Stop completion gate has its own toggle: spec.completion_gate.)
78
80
  if (runtime.spec && runtime.spec.tollgate === false) process.exit(0);
79
81
 
80
- const baseDir = process.env.PROJECT_ROOT || cwd;
82
+ // Same rule as spec-gate: an installed hook trusts its own location over the environment.
83
+ const installedRoot = path.basename(path.resolve(__dirname, '..')).startsWith('.') ? path.resolve(__dirname, '..', '..') : null;
84
+ const baseDir = installedRoot || process.env.PROJECT_ROOT || cwd;
81
85
  const explicitFeature = payload.featureName || payload.feature || payload.explicitFeature || null;
82
86
  const explicitPath = payload.specPath || payload.spec_path || payload.featurePath || null;
83
87
  const resolveWorkflow = typeof RESOLVER.resolveWorkflowCandidate === 'function'
@@ -222,11 +226,11 @@ try {
222
226
  lines.push('- Migration required: add `Specs-Contract: process-first-ready-v1` after the plan title before tasks can enter Next.');
223
227
  }
224
228
  lines.push('- Sync each flat task `Status:` only after verified work; task proof belongs in that task\'s inline `## Receipt`.');
225
- lines.push(`- Workflow source: \`specs/${featureName}/plan.md\`; Stop revalidates every task currently marked done.`);
229
+ lines.push(`- Workflow source: \`specs/${featureName}/plan.md\`; Stop re-checks every done receipt, binding Base/Head to the runtime until the task file is committed, unchanged, and the tree outside the specs root is clean.`);
226
230
  } else {
227
231
  lines.push('- Sync `spec.json` + task Markdown status after verified work; task proof belongs in `receipts/<task-basename>.md`.');
228
232
  lines.push(`- Create \`feature-receipt.md\` once after final integration proof${featureReceiptPresent ? ' (present)' : ' (not required before closeout)'}.`);
229
- lines.push(`- Validate with \`node .claude/scripts/validate-spec-output.cjs specs/${featureName}\`; hooks revalidate receipt bytes but never grant approval.`);
233
+ lines.push(`- Validate with \`node ${runtimeDirName()}/scripts/validate-spec-output.cjs specs/${featureName}\`; hooks revalidate receipt bytes but never grant approval.`);
230
234
  }
231
235
  lines.push('');
232
236
 
@@ -12,7 +12,7 @@
12
12
  * Stop → persist full session state and archive
13
13
  * SubagentStop → append agent completion note to current state
14
14
  *
15
- * Storage: .claude/session-state/latest.md (+ archive/)
15
+ * Storage: <runtime>/session-state/latest.md (+ archive/)
16
16
  * Exit: 0 always (fail-open)
17
17
  */
18
18
 
@@ -23,6 +23,7 @@ try {
23
23
  const crypto = require('crypto');
24
24
  const { execSync } = require('child_process');
25
25
  const { parseTranscript } = require('./lib/parser.cjs');
26
+ const { runtimeDirName, runtimeDir, runtimePath } = require('./lib/runtime-dir.cjs');
26
27
 
27
28
  const EXPIRY_DAYS = 7;
28
29
  const MAX_ARCHIVES = 5;
@@ -32,8 +33,8 @@ try {
32
33
 
33
34
  function stateDir(cwd) {
34
35
  try {
35
- const local = path.join(cwd, '.claude', 'session-state');
36
- if (fs.existsSync(path.join(cwd, '.claude'))) {
36
+ const local = runtimePath(cwd, 'session-state');
37
+ if (fs.existsSync(runtimeDir(cwd))) {
37
38
  if (!fs.existsSync(local)) fs.mkdirSync(local, { recursive: true });
38
39
  return local;
39
40
  }
@@ -224,7 +225,8 @@ try {
224
225
  const stdin = fs.readFileSync(0, 'utf8').trim();
225
226
  if (!stdin) process.exit(0);
226
227
 
227
- const data = JSON.parse(stdin);
228
+ const { normalizeHookPayload } = require('./lib/hook-payload.cjs');
229
+ const data = normalizeHookPayload(JSON.parse(stdin));
228
230
  const event = data.hook_event_name || '';
229
231
  const cwd = data.cwd || process.cwd();
230
232
  const dir = stateDir(cwd);
@@ -21,7 +21,7 @@
21
21
  * 1. fail-open when spec-scaffold.cjs is absent — you cannot force a tool that
22
22
  * is not installed, so a hook shipped without its script must not deadlock.
23
23
  * 2. actionable block message — prints the exact scaffold command to run.
24
- * 3. escape hatch — "spec": { "scaffold_guard": false } in .claude/runtime.json.
24
+ * 3. escape hatch — "spec": { "scaffold_guard": false } in <runtime>/runtime.json.
25
25
  *
26
26
  * Exit: 0 = allow, 2 = block.
27
27
  */
@@ -29,11 +29,33 @@
29
29
  try {
30
30
  const fs = require('fs');
31
31
  const path = require('path');
32
+ const { runtimeDirName, runtimeDir, runtimePath } = require('./lib/runtime-dir.cjs');
33
+
34
+ /**
35
+ * Deny the call with a reason every host can read.
36
+ *
37
+ * The reason is the JSON `permissionDecisionReason`, which Claude Code reads natively and
38
+ * grok honours "regardless of exit code"; the same text also goes to stderr, because on
39
+ * an exit-2 denial that is the channel Claude Code feeds back, and grok reads only the
40
+ * first stderr line. Exit 2 stays so a host that reads neither still blocks.
41
+ */
42
+ function denyWithReason(reason) {
43
+ process.stdout.write(JSON.stringify({
44
+ hookSpecificOutput: {
45
+ hookEventName: 'PreToolUse',
46
+ permissionDecision: 'deny',
47
+ permissionDecisionReason: reason
48
+ }
49
+ }) + '\n');
50
+ process.stderr.write(reason + '\n');
51
+ process.exit(2);
52
+ }
32
53
 
33
54
  const stdin = fs.readFileSync(0, 'utf8').trim();
34
55
  if (!stdin) process.exit(0);
35
56
 
36
- const data = JSON.parse(stdin);
57
+ const { normalizeHookPayload } = require('./lib/hook-payload.cjs');
58
+ const data = normalizeHookPayload(JSON.parse(stdin));
37
59
  const toolName = data.tool_name || '';
38
60
  const toolInput = data.tool_input || {};
39
61
  const cwd = data.cwd || process.cwd();
@@ -50,17 +72,17 @@ try {
50
72
  const isTaskFile = /(^|\/)specs\/[^/]+\/tasks\/task-[^/]+\.md$/.test(norm);
51
73
  if (!isTaskFile) process.exit(0);
52
74
 
53
- // Valve 3: explicit escape hatch via .claude/runtime.json (fail-closed: a
75
+ // Valve 3: explicit escape hatch via <runtime>/runtime.json (fail-closed: a
54
76
  // missing/broken runtime.json keeps the guard ON).
55
77
  let runtime = {};
56
78
  try {
57
- const rp = path.join(cwd, '.claude', 'runtime.json');
79
+ const rp = runtimePath(cwd, 'runtime.json');
58
80
  if (fs.existsSync(rp)) runtime = JSON.parse(fs.readFileSync(rp, 'utf8'));
59
81
  } catch { /* malformed runtime.json -> keep guard on */ }
60
82
  if (runtime.spec && runtime.spec.scaffold_guard === false) process.exit(0);
61
83
 
62
84
  // Valve 1: fail-open if the scaffold script is not installed next to this hook
63
- // (hook lives in .claude/hooks/, script in .claude/scripts/). Forcing a tool
85
+ // (hook lives in <runtime>/hooks/, script in <runtime>/scripts/). Forcing a tool
64
86
  // that does not exist would deadlock task creation.
65
87
  const scaffold = path.join(__dirname, '..', 'scripts', 'spec-scaffold.cjs');
66
88
  if (!fs.existsSync(scaffold)) process.exit(0);
@@ -71,14 +93,13 @@ try {
71
93
  // simply disables the guard itself. The hatch stays functional for humans.
72
94
  const m = norm.match(/(^|\/)specs\/([^/]+)\/tasks\//);
73
95
  const feature = m ? m[2] : '<feature>';
74
- console.log(
96
+ denyWithReason(
75
97
  `TASK SCAFFOLD REQUIRED: task files must be generated, not hand-written.\n` +
76
98
  `Blocked Write: ${filePath}\n\n` +
77
99
  `Generate the stub(s), then Edit-fill the {{...}} placeholders:\n` +
78
- ` node .claude/scripts/spec-scaffold.cjs ${feature} --tasks "R0-01-slug,R1-01-slug,..." --tasks-only\n` +
100
+ ` node ${runtimeDirName()}/scripts/spec-scaffold.cjs ${feature} --tasks "R0-01-slug,R1-01-slug,..." --tasks-only\n` +
79
101
  `Then use Edit (not Write) on each tasks/task-*.md stub.`
80
102
  );
81
- process.exit(2);
82
103
 
83
104
  } catch (e) {
84
105
  // Never let a hook crash block the user — log and fail-open.