mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-27 16:09:34 +01:00
Found with knip (exports, types, class members) and confirmed by a text search of src, test, scripts and packages before each removal. - Per-CLI get<Cli>NotFoundMessage() (nine of them) with their message constants: missingCliMessage() builds that text from the registry now. - Registry leftovers: renderCliCommand, asCliId, cliIds, isCliRunnable, createCliResolverForTest, profileExists, and two name lists that only repeated schema enums. - A task-description cache in Session that was written on every chunk of terminal output (one regex pass per line) and never read since the subagent watcher takes descriptions from transcripts. The cache module, its pattern and both parse methods go with it. - Session.parentAgentId / childAgentIds: never set by anything, so the two optional SessionState fields were never on the wire. - Unreferenced methods on TmuxManager (pipe-pane pair, syncMouseMode), RespawnController, StateStore.recoverFromBackup (load() already falls back to the .bak file), TeamWatcher, SseStreamManager and the AI checkers' getErrorVerdict. - updateCaseEnvVars: the settings.local.json env path that envOverrides replaced. - Re-exports in the utils, cli-registry, routes and prompts barrels that no importer used, and unused test helpers (MockStateStore, the mobile throttle helpers and others). Eight mobile tests imported the WebServer type from a path that does not exist (../src instead of ../../src); type-only, so nothing failed. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
1856 lines
88 KiB
TypeScript
1856 lines
88 KiB
TypeScript
/**
|
|
* @fileoverview Claude Code hooks configuration generator.
|
|
*
|
|
* Generates `.claude/settings.local.json` with hook definitions that POST
|
|
* to Codeman's `/api/hook-event` endpoint when Claude Code fires hooks.
|
|
* Uses `$CODEMAN_API_URL`, `$CODEMAN_SESSION_ID`, and `$CODEMAN_HOOK_SECRET_FILE`
|
|
* env vars (set on every managed session) so the config is static per case
|
|
* directory and free of secret values.
|
|
*
|
|
* Key exports:
|
|
* - `generateHooksConfig()` — returns hooks object for settings.local.json
|
|
* - `writeHooksConfig(casePath)` — writes hooks + env config to disk
|
|
* - `applyWorkspaceHooks(workspace, install?)` — the ONE install-vs-refresh decision
|
|
* point every claude-session create path routes through (see its doc comment)
|
|
* - `ensureCodemanHooks(casePath)` — safely installs/updates hooks for a managed case
|
|
*
|
|
* Hook events generated: `idle_prompt`, `permission_prompt`, `elicitation_dialog`,
|
|
* `elicitation_complete`, `elicitation_response`, `stop`, `teammate_idle`,
|
|
* `task_completed`
|
|
*
|
|
* Hook categories: `Notification` (5 matchers), `Stop` (1), `SubagentStop` (1),
|
|
* `TeammateIdle` (1), `TaskCompleted` (1), `PostToolUse` (1 self-contained
|
|
* background Bash rewake)
|
|
*
|
|
* @dependencies types (HookEventType), config/auth-config (HOOK_TIMEOUT_SECONDS)
|
|
* @consumedby web/server (session creation), session-cli-builder (env setup)
|
|
*
|
|
* @module hooks-config
|
|
*/
|
|
|
|
import { randomBytes } from 'node:crypto';
|
|
import { readFile, writeFile, mkdir, lstat, readdir, realpath, rename, unlink, rmdir, chmod } from 'node:fs/promises';
|
|
import { homedir } from 'node:os';
|
|
import { join, dirname } from 'node:path';
|
|
import { fileURLToPath } from 'node:url';
|
|
|
|
import type { HookEventType } from './types.js';
|
|
import type { AgentSkillDir, CliCapabilities } from './config/cli-registry/types.js';
|
|
import { HOOK_TIMEOUT_SECONDS } from './config/auth-config.js';
|
|
import { dataPath } from './config/instance.js';
|
|
import { readJsonConfig, SETTINGS_PATH } from './web/route-helpers.js';
|
|
import { isNearStalledPath, probePath } from './utils/index.js';
|
|
import { DEFAULT_KEEP_WARM_MAX_HOURS, type KeepWarmSettings } from './prompt-cache-keepwarm.js';
|
|
import { gitFetchSettingsFrom, type GitFetchSettings } from './git-fetch.js';
|
|
|
|
/**
|
|
* Existence check for a WRITER. Unlike the bounded read-side probe (`probePath`),
|
|
* which gives up after a timeout and answers "unknown", this waits for the real
|
|
* answer: only ENOENT reads as absent, anything else throws, so a
|
|
* stalled or unreadable workspace can never be mistaken for an empty one and
|
|
* have its settings recreated over the top. It is async, so a dead mount ties
|
|
* up a threadpool worker rather than the event loop.
|
|
*/
|
|
async function pathExistsForWrite(path: string): Promise<boolean> {
|
|
try {
|
|
await lstat(path);
|
|
return true;
|
|
} catch (err) {
|
|
if ((err as NodeJS.ErrnoException).code === 'ENOENT') return false;
|
|
throw err;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Probe a path a per-spawn helper is about to touch. An "unknown" that is NOT near a
|
|
* stalled probe (the bulk cap refused it, or the stat failed with something other
|
|
* than ENOENT) gets ONE more bounded probe past the bulk cap, so a healthy path still
|
|
* answers while unrelated mounts are dead. Whatever is still "unknown" after that
|
|
* must be skipped by the caller, never touched with an unbounded `lstat`/`readFile`:
|
|
* on a dead mount those never settle, and each would hold a threadpool worker the
|
|
* probe's ceiling does not count.
|
|
*/
|
|
async function probeBeforeTouching(path: string) {
|
|
const state = await probePath(path);
|
|
if (state !== 'unknown' || isNearStalledPath(path)) return state;
|
|
return probePath(path, { pastCap: true });
|
|
}
|
|
|
|
/**
|
|
* Whether a READ-side helper should leave `path` alone: it is definitely absent, or
|
|
* it did not answer (a mount that is not responding, a refused probe, an unreadable
|
|
* path). See `probeBeforeTouching` for why "unknown" is a skip.
|
|
*/
|
|
async function absentOrUnreachable(path: string): Promise<'absent' | 'unreachable' | false> {
|
|
const state = await probeBeforeTouching(path);
|
|
if (state === 'absent') return 'absent';
|
|
if (state === 'unknown') return 'unreachable';
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* Serializes read-modify-write access to a `settings.local.json` path. Every
|
|
* writer in this module (hooks, env, model, statusLine) shares this map, so
|
|
* concurrent updates to the SAME file — e.g. session-create writing hooks/model
|
|
* while an App-Settings toggle injects the statusLine into the same repo — can't
|
|
* lose each other's changes through interleaved read-then-write. Per-path chains
|
|
* are independent; the map self-prunes when a path's chain goes idle.
|
|
*
|
|
* The agent-skill injector keys the same map on its skill DIRECTORY, which can never
|
|
* collide with a settings-file path, so those writers serialize against each other too.
|
|
*/
|
|
const settingsWriteLocks = new Map<string, Promise<unknown>>();
|
|
/**
|
|
* Version-agnostic ownership prefix: every rewake script version embeds a marker
|
|
* starting with this, and `isCodemanHookHandler` matches on the prefix. That way a
|
|
* version bump replaces the old handler instead of duplicating it (matching on the
|
|
* full versioned marker would disown every older script).
|
|
*/
|
|
const BACKGROUND_WAKE_MARKER_PREFIX = 'CODEMAN_BACKGROUND_REWAKE_V';
|
|
/**
|
|
* Current script version. Bump the suffix whenever `generateBackgroundWakeScript`
|
|
* changes: `refreshStaleCodemanHooks` treats the absence of the CURRENT marker as
|
|
* stale, so healed cases pick up the new script on next launch.
|
|
*/
|
|
const BACKGROUND_WAKE_MARKER = `${BACKGROUND_WAKE_MARKER_PREFIX}3`;
|
|
const SUBAGENT_STOP_GUARD_MARKER_PREFIX = 'CODEMAN_SUBAGENT_STOP_GUARD_V';
|
|
const SUBAGENT_STOP_GUARD_MARKER = `${SUBAGENT_STOP_GUARD_MARKER_PREFIX}1`;
|
|
const BACKGROUND_WAKE_TIMEOUT_SECONDS = 6 * 60 * 60;
|
|
|
|
/**
|
|
* Inline Node helper for Claude Code's `asyncRewake` hook.
|
|
*
|
|
* A background Bash tool returns immediately with a task ID, then Claude writes
|
|
* its completion as a queue-operation in the top-level transcript. Subagent hooks
|
|
* receive their own transcript path even though their completion is parent-owned,
|
|
* so the helper watches both paths. Watching durable records avoids injecting
|
|
* terminal input (which could submit a user's draft).
|
|
* The helper is embedded in settings via `node -e`, so it has no script path
|
|
* that can go stale after an install or plugin-cache cleanup.
|
|
*
|
|
* Self-terminating: Claude Code enforces the hook timeout, but the helper does not
|
|
* rely on it. It exits on its own deadline (same budget) and when orphaned
|
|
* (`ppid === 1`), so a dead session cannot leave a poller stat-ing the transcript
|
|
* forever. The ppid check misses subreaper setups; the deadline is the backstop.
|
|
*/
|
|
export function generateBackgroundWakeScript(): string {
|
|
return [
|
|
"const fs = require('node:fs');",
|
|
"const path = require('node:path');",
|
|
`const ${BACKGROUND_WAKE_MARKER} = true;`,
|
|
`const deadline = Date.now() + ${BACKGROUND_WAKE_TIMEOUT_SECONDS} * 1000;`,
|
|
"const RESULT_BEGIN = '=== CODEMAN_RESULT_BEGIN ===';",
|
|
"const RESULT_END = '=== CODEMAN_RESULT_END ===';",
|
|
'const MAX_RESULT_CHARS = 65536;',
|
|
'let input = {};',
|
|
"try { input = JSON.parse(fs.readFileSync(0, 'utf8') || '{}'); } catch { process.exit(0); }",
|
|
'function findTaskId(value) {',
|
|
" const idKeys = new Set(['taskId', 'task_id', 'shellId', 'shell_id', 'backgroundTaskId', 'background_task_id']);",
|
|
' const stack = [value];',
|
|
' const seen = new Set();',
|
|
' while (stack.length > 0) {',
|
|
' const current = stack.pop();',
|
|
" if (!current || typeof current !== 'object' || seen.has(current)) continue;",
|
|
' seen.add(current);',
|
|
' for (const [key, nested] of Object.entries(current)) {',
|
|
" if (idKeys.has(key) && typeof nested === 'string' && /^[A-Za-z0-9_-]+$/.test(nested)) return nested;",
|
|
" if (nested && typeof nested === 'object') stack.push(nested);",
|
|
' }',
|
|
' }',
|
|
" const serialized = JSON.stringify(value ?? '');",
|
|
' const messageMatch = serialized.match(/Command running in background with ID:\\s*([A-Za-z0-9_-]+)/i);',
|
|
' if (messageMatch) return messageMatch[1];',
|
|
' const pathMatch = serialized.match(/[\\\\/]tasks[\\\\/]([A-Za-z0-9_-]+)\\.output/i);',
|
|
' return pathMatch ? pathMatch[1] : null;',
|
|
'}',
|
|
'const taskId = findTaskId(input.tool_response);',
|
|
"const transcriptPath = typeof input.transcript_path === 'string' ? input.transcript_path : '';",
|
|
'if (!taskId || !transcriptPath) process.exit(0);',
|
|
'const transcriptPaths = [transcriptPath];',
|
|
'const sessionDir = path.dirname(path.dirname(transcriptPath));',
|
|
"if (typeof input.agent_id === 'string' && path.basename(path.dirname(transcriptPath)) === 'subagents' &&",
|
|
" typeof input.session_id === 'string' && path.basename(sessionDir) === input.session_id) {",
|
|
" transcriptPaths.push(sessionDir + '.jsonl');",
|
|
'}',
|
|
'const transcripts = [...new Set(transcriptPaths)].map((transcript) => {',
|
|
' let position = 0;',
|
|
' try { position = Math.max(0, fs.statSync(transcript).size - 262144); } catch {}',
|
|
" return { path: transcript, position, carry: '' };",
|
|
'});',
|
|
'if (!transcripts.some((transcript) => fs.existsSync(transcript.path))) process.exit(0);',
|
|
'function readMarkedResult(outputPath) {',
|
|
" if (!outputPath || !path.isAbsolute(outputPath) || path.basename(outputPath) !== taskId + '.output') return '';",
|
|
" if (path.basename(path.dirname(outputPath)) !== 'tasks') return '';",
|
|
' try {',
|
|
' const size = fs.statSync(outputPath).size;',
|
|
' const length = Math.min(size, MAX_RESULT_CHARS * 2);',
|
|
' const buffer = Buffer.allocUnsafe(length);',
|
|
" const fd = fs.openSync(outputPath, 'r');",
|
|
' const bytes = fs.readSync(fd, buffer, 0, length, size - length);',
|
|
' fs.closeSync(fd);',
|
|
" const text = buffer.subarray(0, bytes).toString('utf8');",
|
|
' const begin = text.lastIndexOf(RESULT_BEGIN);',
|
|
' const end = text.indexOf(RESULT_END, begin + RESULT_BEGIN.length);',
|
|
" if (begin < 0 || end < 0) return '';",
|
|
' let result = text.slice(begin + RESULT_BEGIN.length, end).trim();',
|
|
" if (!result) return '';",
|
|
' if (result.length > MAX_RESULT_CHARS) {',
|
|
' const half = Math.floor(MAX_RESULT_CHARS / 2);',
|
|
" result = result.slice(0, half) + '\\n\\n[report truncated by Codeman]\\n\\n' + result.slice(-half);",
|
|
' }',
|
|
" return '\\n\\nCompleted task report:\\n<codeman-background-result>\\n' + result + '\\n</codeman-background-result>';",
|
|
" } catch { return ''; }",
|
|
'}',
|
|
'function inspect(text) {',
|
|
' for (const line of text.split(/\\r?\\n/)) {',
|
|
' if (!line.includes(taskId)) continue;',
|
|
' let entry;',
|
|
' try { entry = JSON.parse(line); } catch { continue; }',
|
|
" if (entry.type !== 'queue-operation' || entry.operation !== 'enqueue' || typeof entry.content !== 'string') continue;",
|
|
" if (!entry.content.includes('<task-id>' + taskId + '</task-id>')) continue;",
|
|
' const status = entry.content.match(/<status>(completed|failed|killed|error)<\\/status>/i);',
|
|
' if (!status) continue;',
|
|
' const output = entry.content.match(/<output-file>([^<]+)<\\/output-file>/i);',
|
|
" const outputPath = output ? output[1].trim() : '';",
|
|
" const location = outputPath ? ' Read ' + outputPath + ' and' : '';",
|
|
' const result = readMarkedResult(outputPath);',
|
|
" console.error('Background command ' + taskId + ' ' + status[1].toLowerCase() + '.' + location + ' continue the task.' + result);",
|
|
' process.exit(2);',
|
|
' }',
|
|
'}',
|
|
'function pollTranscript(transcript) {',
|
|
' try {',
|
|
' const size = fs.statSync(transcript.path).size;',
|
|
" if (size < transcript.position) { transcript.position = 0; transcript.carry = ''; }",
|
|
' if (size > transcript.position) {',
|
|
' const length = Math.min(size - transcript.position, 1048576);',
|
|
' const buffer = Buffer.allocUnsafe(length);',
|
|
" const fd = fs.openSync(transcript.path, 'r');",
|
|
' const bytes = fs.readSync(fd, buffer, 0, length, transcript.position);',
|
|
' fs.closeSync(fd);',
|
|
' transcript.position += bytes;',
|
|
" transcript.carry = (transcript.carry + buffer.subarray(0, bytes).toString('utf8')).slice(-262144);",
|
|
' inspect(transcript.carry);',
|
|
' }',
|
|
' } catch {}',
|
|
'}',
|
|
'function poll() {',
|
|
' if (Date.now() > deadline || process.ppid === 1) process.exit(0);',
|
|
' for (const transcript of transcripts) pollTranscript(transcript);',
|
|
' setTimeout(poll, 1000);',
|
|
'}',
|
|
'poll();',
|
|
].join('\n');
|
|
}
|
|
|
|
/**
|
|
* Keep a Claude subagent alive while its Monitor or background Bash work is live.
|
|
* Claude otherwise can publish the worker's last progress sentence as an Agent
|
|
* result when one watcher ends, even if other tracked tasks are still running.
|
|
*/
|
|
export function generateSubagentStopGuardScript(): string {
|
|
return [
|
|
"const fs = require('node:fs');",
|
|
`const ${SUBAGENT_STOP_GUARD_MARKER} = true;`,
|
|
'let input = {};',
|
|
"try { input = JSON.parse(fs.readFileSync(0, 'utf8') || '{}'); } catch { process.exit(0); }",
|
|
"const transcriptPath = typeof input.agent_transcript_path === 'string' ? input.agent_transcript_path : '';",
|
|
'if (!transcriptPath) process.exit(0);',
|
|
'let text;',
|
|
'try {',
|
|
' const size = fs.statSync(transcriptPath).size;',
|
|
' const length = Math.min(size, 16 * 1024 * 1024);',
|
|
' const buffer = Buffer.allocUnsafe(length);',
|
|
" const fd = fs.openSync(transcriptPath, 'r');",
|
|
' const bytes = fs.readSync(fd, buffer, 0, length, size - length);',
|
|
' fs.closeSync(fd);',
|
|
" text = buffer.subarray(0, bytes).toString('utf8');",
|
|
'} catch { process.exit(0); }',
|
|
'const launched = new Set();',
|
|
'const finished = new Set();',
|
|
'function inspectToolResult(value) {',
|
|
" const serialized = typeof value === 'string' ? value : JSON.stringify(value ?? '');",
|
|
' for (const match of serialized.matchAll(/Command running in background with ID:\\s*([A-Za-z0-9_-]+)/gi)) launched.add(match[1]);',
|
|
' for (const match of serialized.matchAll(/Monitor started \\(task ([A-Za-z0-9_-]+)/gi)) launched.add(match[1]);',
|
|
'}',
|
|
'function inspectNotifications(value) {',
|
|
" if (typeof value !== 'string' || !value.includes('<task-notification>')) return;",
|
|
' for (const match of value.matchAll(/<task-notification>([\\s\\S]*?)<\\/task-notification>/gi)) {',
|
|
' const body = match[1];',
|
|
' const id = body.match(/<task-id>([^<]+)<\\/task-id>/i);',
|
|
' const status = body.match(/<status>(completed|failed|killed|error)<\\/status>/i);',
|
|
' if (id && status) finished.add(id[1].trim());',
|
|
' }',
|
|
'}',
|
|
'for (const line of text.split(/\\r?\\n/)) {',
|
|
' let entry;',
|
|
' try { entry = JSON.parse(line); } catch { continue; }',
|
|
' const content = entry && entry.message ? entry.message.content : undefined;',
|
|
' if (Array.isArray(content)) {',
|
|
' for (const block of content) {',
|
|
" if (block && block.type === 'tool_result') inspectToolResult(block.content);",
|
|
" if (block && block.type === 'text') inspectNotifications(block.text);",
|
|
' }',
|
|
' } else {',
|
|
' inspectNotifications(content);',
|
|
' }',
|
|
' inspectNotifications(entry && entry.content);',
|
|
'}',
|
|
'function findLiveTasks(candidates) {',
|
|
' const live = new Set();',
|
|
" if (candidates.size === 0 || !fs.existsSync('/proc')) return live;",
|
|
' let processIds;',
|
|
" try { processIds = fs.readdirSync('/proc').filter((name) => /^\\d+$/.test(name)); } catch { return live; }",
|
|
' for (const processId of processIds) {',
|
|
" for (const descriptor of ['0', '1', '2']) {",
|
|
' let target;',
|
|
" try { target = fs.readlinkSync('/proc/' + processId + '/fd/' + descriptor); } catch { continue; }",
|
|
' const match = target.match(/[\\/]tasks[\\/]([A-Za-z0-9_-]+)\\.output(?: \\(deleted\\))?$/);',
|
|
' if (match && candidates.has(match[1])) live.add(match[1]);',
|
|
' }',
|
|
' if (live.size === candidates.size) break;',
|
|
' }',
|
|
' return live;',
|
|
'}',
|
|
'const unfinished = new Set([...launched].filter((taskId) => !finished.has(taskId)));',
|
|
'const active = [...findLiveTasks(unfinished)];',
|
|
'if (active.length === 0) process.exit(0);',
|
|
'const shown = active.slice(0, 8);',
|
|
"const suffix = active.length > shown.length ? ' and ' + (active.length - shown.length) + ' more' : '';",
|
|
'process.stdout.write(JSON.stringify({',
|
|
" decision: 'block',",
|
|
" reason: 'You still own active background work (' + shown.join(', ') + suffix + '). Do not return an intermediate progress message as your final report. Process the task notifications or keep actively polling until every task completes, then return one complete summary.',",
|
|
'}));',
|
|
].join('\n');
|
|
}
|
|
|
|
function withSettingsLock<T>(path: string, fn: () => Promise<T>): Promise<T> {
|
|
const prev = settingsWriteLocks.get(path) ?? Promise.resolve();
|
|
const run = prev.then(fn, fn); // run after the prior writer, regardless of its outcome
|
|
// Tail never rejects, so a failed write doesn't poison subsequent writers.
|
|
const tail = run.then(
|
|
() => {},
|
|
() => {}
|
|
);
|
|
settingsWriteLocks.set(path, tail);
|
|
void tail.then(() => {
|
|
if (settingsWriteLocks.get(path) === tail) settingsWriteLocks.delete(path);
|
|
});
|
|
return run;
|
|
}
|
|
|
|
/**
|
|
* Why writing into `<casePath>/.claude/settings.local.json` must NOT proceed,
|
|
* or null when it is safe.
|
|
*
|
|
* Case contents can be FOREIGN (a freshly cloned repository, an imported
|
|
* tree): `.claude` or the settings file itself can arrive as a symlink
|
|
* pointing anywhere on this machine, and `writeFile` follows links, so a
|
|
* scaffold write would land outside the case, up to and including replacing
|
|
* the user's own `~/.claude/settings.json` (#251 review). Any symlink in the
|
|
* chain, or a `.claude` that resolves outside the case, refuses the write.
|
|
* A missing `.claude` is fine (the writer creates it).
|
|
*/
|
|
export async function settingsWriteBlocker(casePath: string): Promise<string | null> {
|
|
const claudeDir = join(casePath, '.claude');
|
|
try {
|
|
const dirStat = await lstat(claudeDir).catch(() => null);
|
|
if (dirStat?.isSymbolicLink()) return 'its .claude is a symlink';
|
|
if (dirStat && !dirStat.isDirectory()) return 'its .claude is a file, not a directory';
|
|
if (dirStat && (await realpath(claudeDir)) !== join(await realpath(casePath), '.claude')) {
|
|
return 'its .claude directory resolves outside the case';
|
|
}
|
|
const settingsStat = await lstat(join(claudeDir, 'settings.local.json')).catch(() => null);
|
|
if (settingsStat?.isSymbolicLink()) return 'its .claude/settings.local.json is a symlink';
|
|
} catch (err) {
|
|
return `its .claude paths could not be verified (${String(err)})`;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* The ONE gate for writing `<casePath>/.claude/settings.local.json`.
|
|
*
|
|
* Serializes writers per path (withSettingsLock) and, INSIDE the lock, refuses
|
|
* the write when `settingsWriteBlocker` reports the target unsafe. Every
|
|
* settings writer in this module must go through here rather than calling
|
|
* `writeFile` on the settings path itself, so a repository-controlled symlink
|
|
* can never redirect ANY of them outside the case (#251 review: the guard
|
|
* originally covered only two writers, and applyStatusLineConfig was shown
|
|
* writing through a symlinked settings file). Refusal is a console.warn, not
|
|
* a throw: hooks/statusline degrade gracefully and the session still runs.
|
|
*/
|
|
async function withSafeSettingsWrite(
|
|
casePath: string,
|
|
purpose: string,
|
|
fn: (claudeDir: string, settingsPath: string) => Promise<void>
|
|
): Promise<void> {
|
|
const claudeDir = join(casePath, '.claude');
|
|
const settingsPath = join(claudeDir, 'settings.local.json');
|
|
await withSettingsLock(settingsPath, async () => {
|
|
const blocker = await settingsWriteBlocker(casePath);
|
|
if (blocker) {
|
|
console.warn(`[hooks-config] Refusing to write ${purpose} for ${casePath}: ${blocker}`);
|
|
return;
|
|
}
|
|
await fn(claudeDir, settingsPath);
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Generates the hooks section for .claude/settings.local.json
|
|
*
|
|
* The hook commands read stdin JSON from Claude Code (contains tool_name,
|
|
* tool_input, etc.) and forward it as the `data` field to Codeman's API.
|
|
* Env vars are resolved at runtime by the shell, so the config is static
|
|
* per case directory.
|
|
*/
|
|
export function generateHooksConfig(): { hooks: Record<string, unknown[]> } {
|
|
// Read Claude Code's stdin JSON and forward it as the data field.
|
|
// Falls back to empty object if stdin is unavailable or malformed.
|
|
// COD-54: present the per-instance hook secret so the bypass keeps working while
|
|
// a tunnel is running. The value is read from the secret file AT EXECUTION TIME
|
|
// (path via $CODEMAN_HOOK_SECRET_FILE, set in every managed session's env), so it
|
|
// never lands in this config and rotation needs no respawn. If the var/file is
|
|
// missing the header is empty — the middleware then allows the request only on
|
|
// the plain loopback bypass (tunnel down), same as pre-secret behavior.
|
|
const curlCmd = (event: HookEventType, options: { discardStdout?: boolean } = {}) =>
|
|
`HOOK_DATA=$(cat 2>/dev/null || echo '{}'); ` +
|
|
`printf '{"event":"${event}","sessionId":"%s","data":%s}' "$CODEMAN_SESSION_ID" "$HOOK_DATA" | ` +
|
|
// `-k`, same as the statusline exporter: CODEMAN_API_URL is loopback HTTPS with
|
|
// a self-signed cert on --https/tailscale installs. Without it curl exits 60,
|
|
// the `|| true` swallows it, and ALL SIX hook events die silently: respawn loses
|
|
// its definitive idle signals and the wait endpoints lose stop/blocked.
|
|
`curl -sk ${options.discardStdout ? '-o /dev/null ' : ''}-X POST "$CODEMAN_API_URL/api/hook-event" ` +
|
|
`-H 'Content-Type: application/json' ` +
|
|
`-H "X-Codeman-Hook-Secret: $(cat "$CODEMAN_HOOK_SECRET_FILE" 2>/dev/null)" ` +
|
|
`--data @- ` +
|
|
`2>/dev/null || true`;
|
|
|
|
// The same POST with stdout DISCARDED, via curl's own `-o`. UserPromptSubmit is
|
|
// one of the hook events whose stdout Claude Code injects into the model's
|
|
// context (the CLI's own hook reference: "Exit code 0 - stdout shown to
|
|
// Claude"), so an undiscarded curl pastes Codeman's `{"success":true,…}`
|
|
// envelope into the user's prompt on every single turn.
|
|
// ⚠️ It MUST be curl's flag, not a trailing redirect. `curlCmd` already ends
|
|
// `… 2>/dev/null || true`, and in `pipeline || true >/dev/null` the shell binds
|
|
// the redirection to `true` — which never runs on the success path — so the
|
|
// envelope still reaches stdout. Verified in dash and bash.
|
|
// ⚠️ The flag is opt-in so the other events' command text stays byte-identical:
|
|
// their stdout feeds the SSE stream harmlessly, and changing it would rewrite
|
|
// every workspace's settings file for no gain.
|
|
const curlCmdSilent = (event: HookEventType) => curlCmd(event, { discardStdout: true });
|
|
|
|
return {
|
|
hooks: {
|
|
Notification: [
|
|
{
|
|
matcher: 'idle_prompt',
|
|
hooks: [{ type: 'command', command: curlCmd('idle_prompt'), timeout: HOOK_TIMEOUT_SECONDS }],
|
|
},
|
|
{
|
|
matcher: 'permission_prompt',
|
|
hooks: [{ type: 'command', command: curlCmd('permission_prompt'), timeout: HOOK_TIMEOUT_SECONDS }],
|
|
},
|
|
{
|
|
matcher: 'elicitation_dialog',
|
|
hooks: [{ type: 'command', command: curlCmd('elicitation_dialog'), timeout: HOOK_TIMEOUT_SECONDS }],
|
|
},
|
|
// The two dialog-closed notifications resolve Approvals Inbox items the
|
|
// moment a question is answered IN the terminal (long before `stop`).
|
|
{
|
|
matcher: 'elicitation_complete',
|
|
hooks: [{ type: 'command', command: curlCmd('elicitation_complete'), timeout: HOOK_TIMEOUT_SECONDS }],
|
|
},
|
|
{
|
|
matcher: 'elicitation_response',
|
|
hooks: [{ type: 'command', command: curlCmd('elicitation_response'), timeout: HOOK_TIMEOUT_SECONDS }],
|
|
},
|
|
],
|
|
Stop: [
|
|
{
|
|
hooks: [{ type: 'command', command: curlCmd('stop'), timeout: HOOK_TIMEOUT_SECONDS }],
|
|
},
|
|
],
|
|
// The pane's LIVE conversation id, reported by the CLI process itself.
|
|
// Without it the response viewer has to guess which `<uuid>.jsonl` a pane
|
|
// is on after a `/clear`, and the only anchor it can guess from is an
|
|
// Enter that went THROUGH Codeman — so a user who attaches to tmux
|
|
// directly never gets one and stays pinned to the launch conversation.
|
|
UserPromptSubmit: [
|
|
{
|
|
hooks: [{ type: 'command', command: curlCmdSilent('prompt_submitted'), timeout: HOOK_TIMEOUT_SECONDS }],
|
|
},
|
|
],
|
|
SubagentStop: [
|
|
{
|
|
hooks: [
|
|
{
|
|
type: 'command',
|
|
command: 'node',
|
|
args: ['-e', generateSubagentStopGuardScript()],
|
|
timeout: HOOK_TIMEOUT_SECONDS,
|
|
},
|
|
],
|
|
},
|
|
],
|
|
TeammateIdle: [
|
|
{
|
|
hooks: [{ type: 'command', command: curlCmd('teammate_idle'), timeout: HOOK_TIMEOUT_SECONDS }],
|
|
},
|
|
],
|
|
TaskCompleted: [
|
|
{
|
|
hooks: [{ type: 'command', command: curlCmd('task_completed'), timeout: HOOK_TIMEOUT_SECONDS }],
|
|
},
|
|
],
|
|
PostToolUse: [
|
|
{
|
|
matcher: 'Bash',
|
|
hooks: [
|
|
{
|
|
type: 'command',
|
|
command: 'node',
|
|
args: ['-e', generateBackgroundWakeScript()],
|
|
asyncRewake: true,
|
|
timeout: BACKGROUND_WAKE_TIMEOUT_SECONDS,
|
|
},
|
|
],
|
|
},
|
|
],
|
|
},
|
|
};
|
|
}
|
|
|
|
function isCodemanHookHandler(value: unknown): boolean {
|
|
try {
|
|
const serialized = JSON.stringify(value);
|
|
// Prefixes, not versioned markers: older script versions must still be ours.
|
|
return (
|
|
serialized.includes('/api/hook-event') ||
|
|
serialized.includes(BACKGROUND_WAKE_MARKER_PREFIX) ||
|
|
serialized.includes(SUBAGENT_STOP_GUARD_MARKER_PREFIX)
|
|
);
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Replace only Codeman-owned command handlers while preserving user events,
|
|
* matcher entries, and sibling handlers in mixed entries.
|
|
*/
|
|
function mergeCodemanHooks(existingValue: unknown, generated: Record<string, unknown[]>): Record<string, unknown[]> {
|
|
const existing =
|
|
existingValue && typeof existingValue === 'object' && !Array.isArray(existingValue)
|
|
? (existingValue as Record<string, unknown>)
|
|
: {};
|
|
const merged: Record<string, unknown[]> = {};
|
|
|
|
for (const eventName of new Set([...Object.keys(existing), ...Object.keys(generated)])) {
|
|
const existingEntries = Array.isArray(existing[eventName]) ? (existing[eventName] as unknown[]) : [];
|
|
const generatedEntries = generated[eventName];
|
|
if (!generatedEntries) {
|
|
merged[eventName] = existingEntries;
|
|
continue;
|
|
}
|
|
|
|
const entries: unknown[] = [];
|
|
let insertedGenerated = false;
|
|
for (const entry of existingEntries) {
|
|
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
|
|
if (!isCodemanHookHandler(entry)) entries.push(entry);
|
|
continue;
|
|
}
|
|
|
|
const record = entry as Record<string, unknown>;
|
|
if (!Array.isArray(record.hooks)) {
|
|
if (isCodemanHookHandler(record)) {
|
|
if (!insertedGenerated) {
|
|
entries.push(...generatedEntries);
|
|
insertedGenerated = true;
|
|
}
|
|
} else {
|
|
entries.push(entry);
|
|
}
|
|
continue;
|
|
}
|
|
|
|
const retainedHandlers = record.hooks.filter((handler) => !isCodemanHookHandler(handler));
|
|
const removedCodemanHandler = retainedHandlers.length !== record.hooks.length;
|
|
if (removedCodemanHandler && !insertedGenerated) {
|
|
entries.push(...generatedEntries);
|
|
insertedGenerated = true;
|
|
}
|
|
if (retainedHandlers.length > 0 || !removedCodemanHandler) {
|
|
entries.push(retainedHandlers.length === record.hooks.length ? entry : { ...record, hooks: retainedHandlers });
|
|
}
|
|
}
|
|
|
|
if (!insertedGenerated) entries.push(...generatedEntries);
|
|
merged[eventName] = entries;
|
|
}
|
|
|
|
return merged;
|
|
}
|
|
|
|
/**
|
|
* Remove a subset of env keys from .claude/settings.local.json.env if present.
|
|
* Used during the disk→tmux-setenv migration: when the caller is actively setting
|
|
* a fresh value for a Codeman-managed key, any stale disk entry for THAT KEY is
|
|
* superseded and should be removed. Keys NOT in `keysToRemove` are left alone
|
|
* (they may be user-managed). No-op if the file/keys don't exist.
|
|
*/
|
|
export async function stripCaseEnvKeys(casePath: string, keysToRemove: readonly string[]): Promise<void> {
|
|
if (keysToRemove.length === 0) return;
|
|
|
|
await withSafeSettingsWrite(casePath, 'env-key removal', async (_claudeDir, settingsPath) => {
|
|
if (!(await pathExistsForWrite(settingsPath))) return;
|
|
|
|
let existing: Record<string, unknown>;
|
|
try {
|
|
existing = JSON.parse(await readFile(settingsPath, 'utf-8'));
|
|
} catch {
|
|
return; // Malformed — don't rewrite it
|
|
}
|
|
|
|
const env = existing.env as Record<string, string> | undefined;
|
|
if (!env) return;
|
|
|
|
let changed = false;
|
|
for (const key of keysToRemove) {
|
|
if (key in env) {
|
|
delete env[key];
|
|
changed = true;
|
|
}
|
|
}
|
|
if (!changed) return;
|
|
|
|
existing.env = env;
|
|
await writeFile(settingsPath, JSON.stringify(existing, null, 2) + '\n');
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Updates the `model` field in .claude/settings.local.json for the given case path.
|
|
* Pass a non-empty string to set, or empty/null to remove.
|
|
*/
|
|
export async function updateCaseModel(casePath: string, model: string | null): Promise<void> {
|
|
await withSafeSettingsWrite(casePath, 'model', async (claudeDir, settingsPath) => {
|
|
if (!(await pathExistsForWrite(claudeDir))) {
|
|
await mkdir(claudeDir, { recursive: true });
|
|
}
|
|
|
|
let existing: Record<string, unknown> = {};
|
|
try {
|
|
existing = JSON.parse(await readFile(settingsPath, 'utf-8'));
|
|
} catch {
|
|
existing = {};
|
|
}
|
|
|
|
if (model) {
|
|
existing.model = model;
|
|
} else {
|
|
delete existing.model;
|
|
}
|
|
|
|
await writeFile(settingsPath, JSON.stringify(existing, null, 2) + '\n');
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Writes hooks config to .claude/settings.local.json in the given case path.
|
|
* Merges with existing file content, only touching the `hooks` key.
|
|
* Refuses (with a console.warn, not a throw: hooks degrade to output-based
|
|
* idle detection) when `settingsWriteBlocker` reports the target unsafe.
|
|
*/
|
|
export async function writeHooksConfig(casePath: string): Promise<void> {
|
|
await withSafeSettingsWrite(casePath, 'hooks', async (claudeDir, settingsPath) => {
|
|
if (!(await pathExistsForWrite(claudeDir))) {
|
|
await mkdir(claudeDir, { recursive: true });
|
|
}
|
|
|
|
let existing: Record<string, unknown> = {};
|
|
try {
|
|
existing = JSON.parse(await readFile(settingsPath, 'utf-8'));
|
|
} catch {
|
|
// If file is malformed or doesn't exist, start fresh
|
|
existing = {};
|
|
}
|
|
|
|
const hooksConfig = generateHooksConfig();
|
|
const merged = {
|
|
...existing,
|
|
hooks: mergeCodemanHooks(existing.hooks, hooksConfig.hooks),
|
|
};
|
|
|
|
await writeFile(settingsPath, JSON.stringify(merged, null, 2) + '\n');
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Ensures a workspace Codeman is about to run Claude in has the current Codeman hooks.
|
|
*
|
|
* Unlike `refreshStaleCodemanHooks`, this may ADD Codeman handlers to a settings
|
|
* file that has none (a linked case, a cloned repo, any directory Codeman did not
|
|
* scaffold). It merges rather than replaces, so a user's own hook entries survive,
|
|
* and a malformed existing file is left untouched rather than replaced.
|
|
*
|
|
* ⚠️ That "may add" is a deliberate POLICY, adopted 2026-08-15 after the symptom it
|
|
* causes was reported: hooks were only ever written when Codeman CREATED a case
|
|
* directory, so every session in a linked case ran with no hooks at all and each
|
|
* hook-driven surface was silently dead there — an AskUserQuestion dialog blocking
|
|
* the pane while the tab and the phone overview both read a calm `idle`, no
|
|
* Approvals Inbox item, no push, no definitive `stop`/`idle_prompt` for respawn, and
|
|
* no `stop`/`blocked` for the agent wait endpoints. The cost of the policy is the
|
|
* other direction: a user who DELETES Codeman's hooks from a workspace gets them
|
|
* back on the next session create there, because nothing on disk distinguishes
|
|
* "removed on purpose" from "never had any".
|
|
*
|
|
* Called from both session-create paths (`POST /api/sessions`, `POST /api/quick-start`)
|
|
* for claude mode, and from `restoreMuxSessions()` so sessions that predate this heal
|
|
* on the next server start. Claude Code re-reads the file, so a session ALREADY running
|
|
* in the workspace picks the hooks up without a restart (verified live, 2026-08-15).
|
|
*/
|
|
export async function ensureCodemanHooks(casePath: string): Promise<void> {
|
|
await withSafeSettingsWrite(casePath, 'hooks (ensure)', async (claudeDir, settingsPath) => {
|
|
if (!(await pathExistsForWrite(claudeDir))) {
|
|
await mkdir(claudeDir, { recursive: true });
|
|
}
|
|
|
|
let existing: Record<string, unknown> = {};
|
|
try {
|
|
const parsed: unknown = JSON.parse(await readFile(settingsPath, 'utf-8'));
|
|
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return;
|
|
existing = parsed as Record<string, unknown>;
|
|
} catch (err) {
|
|
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') return;
|
|
}
|
|
|
|
const generated = generateHooksConfig();
|
|
const hooks = mergeCodemanHooks(existing.hooks, generated.hooks);
|
|
if (JSON.stringify(existing.hooks ?? {}) === JSON.stringify(hooks)) return;
|
|
|
|
await writeFile(settingsPath, JSON.stringify({ ...existing, hooks }, null, 2) + '\n');
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Self-heal a case's Codeman-owned hooks block.
|
|
*
|
|
* `writeHooksConfig` only runs when a case is first CREATED. Cases created before the
|
|
* X-Codeman-Hook-Secret header was added (COD-54, 2026-06-10) keep hook curls in their
|
|
* settings.local.json that POST to /api/hook-event WITHOUT the secret — which, once the
|
|
* gate requires it unconditionally (COD-91), silently 401 on a password-protected install.
|
|
* Older Codeman blocks also lack the current background Bash async-rewake hook or the
|
|
* SubagentStop guard. A further stale shape: hook curls without `-k`, which exit 60 on
|
|
* every --https/tailscale install (the cert is self-signed), swallowed by the hooks'
|
|
* own `|| true` — all six hook events die silently. Refresh any of these stale shapes
|
|
* on launch so existing cases heal.
|
|
*
|
|
* Deliberately surgical: regenerates ONLY when settings.local.json already contains
|
|
* Codeman's own hook curls (they target `/api/hook-event`) and they are stale. No-op
|
|
* when the file/hooks are absent (we never impose hooks on a user who removed them) or
|
|
* when the hooks aren't ours, so it is cheap enough to call on every Claude spawn.
|
|
*/
|
|
export async function refreshStaleCodemanHooks(casePath: string): Promise<void> {
|
|
if (await absentOrUnreachable(join(casePath, '.claude', 'settings.local.json'))) return;
|
|
await withSafeSettingsWrite(casePath, 'hooks (refresh)', async (_claudeDir, settingsPath) => {
|
|
let existing: Record<string, unknown>;
|
|
try {
|
|
existing = JSON.parse(await readFile(settingsPath, 'utf-8'));
|
|
} catch {
|
|
return; // malformed — leave it untouched (case-create owns the happy path)
|
|
}
|
|
const hooksJson = JSON.stringify(existing.hooks ?? null);
|
|
const isOurs = hooksJson.includes('/api/hook-event');
|
|
// The generated curl carries this header literal (see generateHooksConfig); its
|
|
// absence on our own hooks means they predate COD-54 and need regenerating.
|
|
const hasSecret = hooksJson.includes('X-Codeman-Hook-Secret');
|
|
const hasBackgroundWake = hooksJson.includes(BACKGROUND_WAKE_MARKER);
|
|
// The pre--k curl shape: `curl -sk -X POST` does not contain `curl -s -X POST`
|
|
// as a substring, so this cleanly identifies hook curls that die with exit 60
|
|
// on a self-signed HTTPS install.
|
|
const hasTlsFlaglessCurl = hooksJson.includes('curl -s -X POST');
|
|
const hasSubagentStopGuard = hooksJson.includes(SUBAGENT_STOP_GUARD_MARKER);
|
|
// Approvals Inbox needs the elicitation_complete/elicitation_response
|
|
// matchers; their absence marks a pre-inbox hooks block.
|
|
const hasElicitationComplete = hooksJson.includes('elicitation_complete');
|
|
// The UserPromptSubmit event is what gives a tmux-driven pane a first-hand
|
|
// conversation id; its absence marks a pre-prompt_submitted hooks block.
|
|
// ⚠️ No surrounding quotes: `hooksJson` is JSON.stringify'd, so the marker
|
|
// inside the command reads \"prompt_submitted\" and a quoted needle never
|
|
// matches — which would make this gate permanently false and rewrite every
|
|
// workspace's settings file on every Claude spawn. The sibling markers are
|
|
// quote-free for the same reason.
|
|
const hasPromptSubmit = hooksJson.includes('prompt_submitted');
|
|
if (
|
|
!isOurs ||
|
|
(hasSecret &&
|
|
hasBackgroundWake &&
|
|
hasSubagentStopGuard &&
|
|
hasElicitationComplete &&
|
|
hasPromptSubmit &&
|
|
!hasTlsFlaglessCurl)
|
|
)
|
|
return;
|
|
const generated = generateHooksConfig();
|
|
const merged = {
|
|
...existing,
|
|
hooks: mergeCodemanHooks(existing.hooks, generated.hooks),
|
|
};
|
|
await writeFile(settingsPath, JSON.stringify(merged, null, 2) + '\n');
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Hooks for the workspace a Claude session is about to run in. ONE decision point,
|
|
* shared by every claude-session create path — the interactive routes, quick-start,
|
|
* cron fires, legacy scheduled runs, the plan-orchestrator one-shots, and the boot
|
|
* recovery sweep — so the `workspaceHooksEnabled` setting cannot apply to some of
|
|
* them only.
|
|
*
|
|
* ON (the default): INSTALL Codeman's hooks block (`ensureCodemanHooks`), merging so
|
|
* a user's own hook entries and every other settings key survive. Hooks used to be
|
|
* written only when Codeman CREATED the case DIRECTORY, so a linked case or any
|
|
* pre-existing repo — where most sessions actually run — had none, and every
|
|
* hook-driven surface was silently dead there (full history on `ensureCodemanHooks`).
|
|
*
|
|
* OFF: the older, narrower behavior. A Codeman block that is already there is still
|
|
* refreshed when stale (COD-91: a pre-secret block 401s once the hook-secret gate
|
|
* went unconditional), but one is never added, so Codeman leaves the repo alone.
|
|
*
|
|
* `install` overrides the setting read: route handlers resolve it through their
|
|
* ConfigPort (`ctx.getWorkspaceHooksEnabled()`, which tests stub), and the boot sweep
|
|
* passes `true` after checking the setting once for its whole batch. Every other
|
|
* caller omits it and the synced setting is read from settings.json here — default ON
|
|
* when the key is absent or the file unreadable, matching the server's resolver.
|
|
*
|
|
* Callers gate on their own context (claude mode only; local — never a remote
|
|
* workingDir, which is a path on ANOTHER host, and never a docker case that opted
|
|
* out of hooks). The guards EVERY caller needs live here instead:
|
|
* - a workspace that does not exist is skipped — `ensureCodemanHooks` mkdir -p's,
|
|
* so a deleted repo whose tmux session survived would otherwise be resurrected
|
|
* as an empty directory tree holding only `.claude/settings.local.json`;
|
|
* - errors are swallowed — a session create must never fail on hooks.
|
|
*/
|
|
export async function applyWorkspaceHooks(workspace: string, install?: boolean): Promise<void> {
|
|
try {
|
|
// "absent" stays absent: the install below would mkdir -p a deleted repo back
|
|
// into being. "unknown" is skipped too, never asked again with an unbounded
|
|
// lstat (see probeBeforeTouching).
|
|
const state = await probeBeforeTouching(workspace);
|
|
if (state === 'absent') return;
|
|
if (state === 'unknown') {
|
|
console.warn(
|
|
`[hooks] ${workspace} is not responding or not readable (unreachable mount?); Codeman hooks not checked or installed`
|
|
);
|
|
return;
|
|
}
|
|
const shouldInstall = install ?? (await readWorkspaceHooksEnabled());
|
|
await (shouldInstall ? ensureCodemanHooks(workspace) : refreshStaleCodemanHooks(workspace));
|
|
} catch {
|
|
// Best-effort by contract (see doc comment): hooks degrade to output-based
|
|
// idle detection; the create goes ahead.
|
|
}
|
|
}
|
|
|
|
/**
|
|
* The synced `workspaceHooksEnabled` app setting, read straight from settings.json
|
|
* for callers that live outside the web layer (cron, scheduled runs, the plan
|
|
* orchestrator). Default ON: an absent key means a user who has never seen the
|
|
* setting, and OFF for them would mean no tab alerts, no Approvals Inbox and no
|
|
* respawn idle signals in every workspace Codeman did not scaffold itself.
|
|
*/
|
|
async function readWorkspaceHooksEnabled(): Promise<boolean> {
|
|
try {
|
|
const parsed = JSON.parse(await readFile(dataPath('settings.json'), 'utf-8')) as Record<string, unknown>;
|
|
return parsed.workspaceHooksEnabled !== false;
|
|
} catch {
|
|
return true;
|
|
}
|
|
}
|
|
|
|
/** Unique marker identifying Codeman's own statusLine command (vs a user's). */
|
|
const STATUSLINE_MARKER = '/api/status-telemetry';
|
|
|
|
/**
|
|
* The plan-usage statusLine exporter command. Mirrors the hook `curlCmd` pattern:
|
|
* reads Claude Code's statusline stdin JSON, POSTs `{sessionId,data}` to Codeman,
|
|
* and prints the response body (a compact "⟳ 5h 15% · 7d 34%" footer) back to
|
|
* stdout so the in-terminal statusline stays useful. Env vars resolve at runtime
|
|
* (present in every managed session via tmux setenv), so the config is static.
|
|
*/
|
|
export function generateStatusLineCommand(): string {
|
|
// `curl -sfk`: CODEMAN_API_URL is loopback HTTPS with a self-signed cert in the
|
|
// production setup; without -k curl returns 000 and the statusline shows
|
|
// nothing. -k is safe here (loopback only); -f keeps an HTTP error body off
|
|
// the statusline. On any failure it prints NOTHING: the old `|| echo codeman`
|
|
// is the bare word that a hand-run `claude` in a managed repo rendered, and
|
|
// that reads as a broken config (discussion #405).
|
|
return (
|
|
`INPUT=$(cat 2>/dev/null || echo '{}'); ` +
|
|
`printf '{"sessionId":"%s","data":%s}' "$CODEMAN_SESSION_ID" "$INPUT" | ` +
|
|
`curl -sfk -X POST "$CODEMAN_API_URL${STATUSLINE_MARKER}" ` +
|
|
`-H 'Content-Type: application/json' ` +
|
|
`-H "X-Codeman-Hook-Secret: $(cat "$CODEMAN_HOOK_SECRET_FILE" 2>/dev/null)" ` +
|
|
`--data @- 2>/dev/null || true`
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Add or remove Codeman's plan-usage statusLine exporter in
|
|
* `.claude/settings.local.json`. Only ever touches a statusLine that is OURS
|
|
* (command targets `/api/status-telemetry`), so a user's hand-authored
|
|
* statusLine is never removed OR overwritten — on both the enable and disable
|
|
* paths we bail out when an existing statusLine isn't ours. Callers gate on
|
|
* Claude mode. Merges, preserving all other keys (hooks, env, model).
|
|
*/
|
|
export async function applyStatusLineConfig(casePath: string, enabled: boolean): Promise<void> {
|
|
await withSafeSettingsWrite(casePath, 'statusLine', async (claudeDir, settingsPath) => {
|
|
let existing: Record<string, unknown> = {};
|
|
if (await pathExistsForWrite(settingsPath)) {
|
|
try {
|
|
existing = JSON.parse(await readFile(settingsPath, 'utf-8'));
|
|
} catch {
|
|
return; // Malformed — don't rewrite it
|
|
}
|
|
}
|
|
|
|
const current = existing.statusLine as { command?: unknown } | undefined;
|
|
const isOurs = !!current && typeof current.command === 'string' && current.command.includes(STATUSLINE_MARKER);
|
|
|
|
if (enabled) {
|
|
const desired = generateStatusLineCommand();
|
|
if (isOurs && current?.command === desired) return; // already current — skip rewrite
|
|
if (current && !isOurs) return; // user has their OWN statusLine — never clobber it
|
|
if (!(await pathExistsForWrite(claudeDir))) await mkdir(claudeDir, { recursive: true });
|
|
existing.statusLine = { type: 'command', command: desired }; // add, or update an out-of-date ours
|
|
} else {
|
|
if (!isOurs) return; // nothing of ours to remove (leave a user's own statusLine alone)
|
|
delete existing.statusLine;
|
|
}
|
|
|
|
await writeFile(settingsPath, JSON.stringify(existing, null, 2) + '\n');
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Version-agnostic marker embedded as a comment in the generated exporter
|
|
* SCRIPT (see ensureStatusLineExporterScript) — bump the numeric suffix
|
|
* whenever the script content changes so `ensureStatusLineExporterScript`'s
|
|
* content comparison rewrites stale copies on next use.
|
|
*/
|
|
const STATUSLINE_EXPORTER_SCRIPT_MARKER = 'CODEMAN_STATUSLINE_EXPORTER_V4';
|
|
|
|
function statusLineExporterScriptContent(): string {
|
|
// Where the telemetry POST runs depends on who owns the footer. When the pane's
|
|
// env carries CODEMAN_USER_STATUSLINE_CMD (set via tmux setenv by TmuxManager
|
|
// when findEffectiveUserStatusLineCommand found the user's own REAL statusLine —
|
|
// see that function's doc comment), the user's command owns the footer, so the
|
|
// POST runs in a BACKGROUND subshell with stdin/stdout/stderr all closed
|
|
// (`>/dev/null 2>&1 </dev/null &`) — closing stdout/stderr keeps it from adding
|
|
// latency or leaking into the visible statusline, and closing stdin too is what
|
|
// lets a host reading this script's own stdout to EOF (`sh script | cat`) see
|
|
// that EOF promptly: without it the backgrounded curl keeps the pipe's write end
|
|
// open until IT exits, so the reader blocks for however long curl takes (measured
|
|
// ~5s with a stand-in) instead of the ~9ms it takes once stdin is closed too.
|
|
// Absent a user statusline, NOTHING else will print the footer, so the POST runs
|
|
// in the FOREGROUND and ITS OWN stdout becomes the footer — `/api/status-telemetry`
|
|
// returns formatSessionStatusText(...) (model/tokens/context %) precisely so this
|
|
// can happen. If curl itself fails (refused/unreachable Codeman, or an HTTP
|
|
// error, which `-f` keeps off stdout) the footer is simply EMPTY (`|| true`):
|
|
// the old `|| echo codeman` rendered a bare brand word that reads as a broken
|
|
// config, the symptom discussion #405 opened with. `--max-time` bounds a
|
|
// HUNG (not just refused) Codeman so it cannot wedge the render indefinitely.
|
|
const post =
|
|
`printf '{"sessionId":"%s","data":%s}' "$CODEMAN_SESSION_ID" "$INPUT" | ` +
|
|
`curl -sfk --max-time 5 -X POST "$CODEMAN_API_URL${STATUSLINE_MARKER}" ` +
|
|
`-H 'Content-Type: application/json' ` +
|
|
`-H "X-Codeman-Hook-Secret: $(cat "$CODEMAN_HOOK_SECRET_FILE" 2>/dev/null)" ` +
|
|
`--data @-`;
|
|
return (
|
|
`#!/bin/sh\n` +
|
|
`# ${STATUSLINE_EXPORTER_SCRIPT_MARKER} — auto-generated by Codeman; safe to delete, regenerated on demand.\n` +
|
|
`INPUT=$(cat 2>/dev/null || echo '{}')\n` +
|
|
`if [ -n "$CODEMAN_USER_STATUSLINE_CMD" ]; then\n` +
|
|
` ( ${post} ) >/dev/null 2>&1 </dev/null &\n` +
|
|
` printf '%s' "$INPUT" | sh -c "$CODEMAN_USER_STATUSLINE_CMD"\n` +
|
|
`else\n` +
|
|
` ${post} 2>/dev/null || true\n` +
|
|
`fi\n`
|
|
);
|
|
}
|
|
|
|
async function readStatusLineCommandFromFile(settingsPath: string): Promise<string | undefined> {
|
|
if (await absentOrUnreachable(settingsPath)) return undefined;
|
|
try {
|
|
const parsed = JSON.parse(await readFile(settingsPath, 'utf-8'));
|
|
const current = parsed.statusLine as { command?: unknown } | undefined;
|
|
return current && typeof current.command === 'string' ? current.command : undefined;
|
|
} catch {
|
|
return undefined; // Malformed — treat as absent, same posture as applyStatusLineConfig.
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Walk Claude Code's OWN settings precedence for `workingDir` to find whatever
|
|
* statusLine command is ACTUALLY effective there right now: project-local
|
|
* `.claude/settings.local.json` > project-shared `.claude/settings.json` >
|
|
* the user's global `~/.claude/settings.json`. Returns undefined when none of
|
|
* the three configures one.
|
|
*
|
|
* A legacy Codeman-marked entry in the project's OWN settings.local.json
|
|
* (written by an older build's disk-based mechanism) is never treated as a
|
|
* real user command — resolveStatusLineCliCommand strips it before this ever
|
|
* runs, so ordinarily this function never even sees one; the marker check
|
|
* here is a second, defensive guard in case something else wrote a copy in
|
|
* between, and precedence simply continues to the next layer instead of
|
|
* stopping on it.
|
|
*/
|
|
export async function findEffectiveUserStatusLineCommand(workingDir: string): Promise<string | undefined> {
|
|
const projectLocal = await readStatusLineCommandFromFile(join(workingDir, '.claude', 'settings.local.json'));
|
|
if (projectLocal && !projectLocal.includes(STATUSLINE_MARKER)) return projectLocal;
|
|
|
|
const projectShared = await readStatusLineCommandFromFile(join(workingDir, '.claude', 'settings.json'));
|
|
if (projectShared) return projectShared;
|
|
|
|
return readStatusLineCommandFromFile(join(homedir(), '.claude', 'settings.json'));
|
|
}
|
|
|
|
/**
|
|
* Write (or refresh) the SHARED, single exporter script every claude session
|
|
* points its ephemeral --settings statusLine flag at, and return its absolute
|
|
* path. Idempotent: only rewrites when the marker-versioned content differs.
|
|
*
|
|
* This is the fix for a real bug found live 2026-08-31: the exporter's
|
|
* command string legitimately depends on `$CODEMAN_SESSION_ID`,
|
|
* `$CODEMAN_API_URL`, `$CODEMAN_HOOK_SECRET_FILE`, and its own internal
|
|
* `$INPUT` — all meant to be expanded ONLY when Claude Code itself finally
|
|
* executes the statusLine command, using the PANE's tmux-setenv'd
|
|
* environment. Passing that command as literal TEXT through
|
|
* `--settings '...'` routes it through this server's OWN spawn-time shell
|
|
* layers first (tmux respawn-pane's `bash -c "..."`, itself invoked via
|
|
* execSync's implicit `/bin/sh -c`) — and POSIX double quotes do NOT
|
|
* suppress `$` expansion, so those vars got expanded there and then, against
|
|
* the SERVER process's environment (where they are unset), producing a
|
|
* mangled curl call that posted malformed JSON and printed the server's raw
|
|
* error response as the statusline text itself. A bare file PATH has no `$`,
|
|
* quotes, or pipes for any of those intermediate shells to mangle — the
|
|
* script's own content (containing the real `$VAR`s) is never touched by a
|
|
* shell until Claude Code executes the file itself, at which point the
|
|
* pane's real environment is in scope. This mirrors the existing #208 fix in
|
|
* tmux-manager.ts (never embed a literal `$SHELL` meant for later
|
|
* expansion — resolve it, or in this case reference a file, instead).
|
|
*/
|
|
export async function ensureStatusLineExporterScript(): Promise<string> {
|
|
const scriptPath = dataPath('statusline-exporter.sh');
|
|
const desired = statusLineExporterScriptContent();
|
|
let current: string | null = null;
|
|
try {
|
|
current = await readFile(scriptPath, 'utf-8');
|
|
} catch {
|
|
// Doesn't exist yet.
|
|
}
|
|
if (current !== desired) {
|
|
// Temp file + rename: live sessions execute this script on every statusline
|
|
// render, and a truncate-then-write (plus a chmod AFTER the write) opened two
|
|
// windows in which Claude Code could run an empty or non-executable file.
|
|
// rename() swaps the complete, already-executable file in atomically.
|
|
// ⚠️ The temp name must be unique per CALL, not per millisecond: sessions created
|
|
// concurrently (spawn_workers, a multi-tab Run) refresh this together, a shared
|
|
// name let the first rename consume the others' temp file, and their ENOENT
|
|
// dropped those sessions from tmux to the direct-PTY fallback.
|
|
const tmpPath = `${scriptPath}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`;
|
|
await writeFile(tmpPath, desired);
|
|
await chmod(tmpPath, 0o755);
|
|
await rename(tmpPath, scriptPath);
|
|
}
|
|
return scriptPath;
|
|
}
|
|
|
|
/**
|
|
* Whether plan-usage telemetry collection is CURRENTLY wanted — read FRESH
|
|
* from the persisted `showPlanUsageLimits` setting on every call, never
|
|
* cached and never per-session. Reusing that setting rather than inventing a
|
|
* second persisted flag: it's the SAME boolean the App Settings chip checkbox
|
|
* already writes (see `planUsageChipEnabled()` in settings-ui.js).
|
|
*
|
|
* This is what lets the on/off decision survive a Codeman restart (there is
|
|
* no per-session state to lose — see the now-removed `Session._statusLineTelemetry`,
|
|
* which WAS such a per-session field and went stale on every restart) and
|
|
* apply uniformly across every claude session-creation path — interactive
|
|
* create, cron, the Ralph Loop API, quick-start — with none of them needing
|
|
* to thread a request-time flag through: they all already construct a
|
|
* session via TmuxManager.createSession/respawnPane, which reads this at
|
|
* spawn time.
|
|
*
|
|
* An ABSENT key means ON, mirroring readWorkspaceHooksEnabled() above: the
|
|
* client shows the chip and its checkbox as already on for a desktop that has
|
|
* never touched the setting (planUsageChipEnabled() in settings-ui.js), and
|
|
* the exporter only ever posts to THIS Codeman over loopback, so the honest
|
|
* default for an install that never said otherwise is the one the user can
|
|
* see. Resolving the default here, in the reader, is what lets
|
|
* `GET /api/settings` stay a plain read: a reconcile write there ran on every
|
|
* page load and could replace an unreadable settings.json with a one-key
|
|
* file. Only an explicit `false` (a save that flipped the chip off on some
|
|
* device) turns collection off.
|
|
*/
|
|
export async function readPlanUsageTelemetryEnabled(): Promise<boolean> {
|
|
const settings = await readJsonConfig<Record<string, unknown>>(SETTINGS_PATH, 'settings.json', {});
|
|
return settings.showPlanUsageLimits !== false;
|
|
}
|
|
|
|
/**
|
|
* Whether every Claude session is launched with `--name` set to its tab name
|
|
* (the `pinCliSessionName` setting). Read FRESH from settings.json at every
|
|
* claude create and respawn, like {@link readPlanUsageTelemetryEnabled}, so a
|
|
* toggle applies from the next spawn with no server restart. An ABSENT key
|
|
* means OFF: only a name the user chose is pinned, and Claude titles the
|
|
* placeholder- and auto-named conversations itself (see `Session.cliPinnedName`).
|
|
*/
|
|
export async function readPinCliSessionNameEnabled(): Promise<boolean> {
|
|
const settings = await readJsonConfig<Record<string, unknown>>(SETTINGS_PATH, 'settings.json', {});
|
|
return settings.pinCliSessionName === true;
|
|
}
|
|
|
|
/**
|
|
* The prompt-cache keep-warm's app-wide default (`promptCacheKeepWarm`, absent = OFF) and its
|
|
* cap (`promptCacheKeepWarmMaxHours`, hours after the last real prompt). Read FRESH like
|
|
* {@link readPinCliSessionNameEnabled} at every claude create and respawn, which decides the
|
|
* launch's `idleCompaction` opt-out.
|
|
*/
|
|
export async function readKeepWarmSettings(): Promise<KeepWarmSettings> {
|
|
return keepWarmSettingsFrom(await readJsonConfig<Record<string, unknown>>(SETTINGS_PATH, 'settings.json', {}));
|
|
}
|
|
|
|
/**
|
|
* The same two keys for the keep-warm service, which keeps what it reads until the next
|
|
* settings change. A missing file is the defaults, but any other read or parse failure rejects
|
|
* rather than falling back: settings.json is replaced atomically, so such a failure is a real
|
|
* read error or a file that does not parse (a hand edit), never a write in progress, and a
|
|
* fallback kept from it would hold keep-warm off until the next keep-warm settings change.
|
|
*/
|
|
export async function readKeepWarmSettingsOrThrow(): Promise<KeepWarmSettings> {
|
|
let text: string;
|
|
try {
|
|
text = await readFile(SETTINGS_PATH, 'utf-8');
|
|
} catch (err) {
|
|
if ((err as NodeJS.ErrnoException).code === 'ENOENT') return keepWarmSettingsFrom({});
|
|
throw err;
|
|
}
|
|
return keepWarmSettingsFrom(parseSettingsText(text));
|
|
}
|
|
|
|
/**
|
|
* The Git fetch interval's app-wide default (`gitFetchEnabled`, absent = OFF) and its cap
|
|
* (`gitFetchIntervalSeconds`, seconds between runs). Read FRESH on every tick by the scheduler, so a live
|
|
* toggle takes effect on the next tick and turning it off actually stops the fetching. A missing file is
|
|
* the defaults (OFF), but any other read or parse failure rejects and the scheduler skips that tick rather
|
|
* than deciding from defaults. settings.json is replaced atomically (a temp file renamed into place, see
|
|
* settings-writer.ts), so such a failure is a real read error or a file that does not parse (a hand edit),
|
|
* never a write in progress, and the scheduler logs it once rather than every tick.
|
|
*/
|
|
export async function readGitFetchSettings(): Promise<GitFetchSettings> {
|
|
let text: string;
|
|
try {
|
|
text = await readFile(SETTINGS_PATH, 'utf-8');
|
|
} catch (err) {
|
|
if ((err as NodeJS.ErrnoException).code === 'ENOENT') return gitFetchSettingsFrom({});
|
|
throw err;
|
|
}
|
|
return gitFetchSettingsFrom(parseSettingsText(text));
|
|
}
|
|
|
|
/**
|
|
* settings.json's text for the two readers above, which reject a file that does not parse. The parser's
|
|
* own message is never repeated, as in settings-writer.ts: V8 quotes the text around the fault, settings.json
|
|
* can hold an API key (`voiceSettings.apiKey`), and both callers log the error they get.
|
|
*/
|
|
function parseSettingsText(text: string): Record<string, unknown> {
|
|
try {
|
|
return JSON.parse(text) as Record<string, unknown>;
|
|
} catch {
|
|
throw new Error(`${SETTINGS_PATH} is not valid JSON`);
|
|
}
|
|
}
|
|
|
|
function keepWarmSettingsFrom(settings: Record<string, unknown>): KeepWarmSettings {
|
|
const hours = settings?.promptCacheKeepWarmMaxHours;
|
|
return {
|
|
keepWarmDefault: settings?.promptCacheKeepWarm === true,
|
|
maxHours: typeof hours === 'number' && Number.isFinite(hours) && hours > 0 ? hours : DEFAULT_KEEP_WARM_MAX_HOURS,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Resolve the statusLine command to pass as an EPHEMERAL `claude --settings`
|
|
* CLI flag for this one process (see buildSpawnCommandFromRegistry in
|
|
* session-cli-registry-bridge.ts) — never written to disk. This supersedes
|
|
* the old applyStatusLineConfig(path, true) disk-write: a file-based
|
|
* statusLine leaked into any plain `claude` run in that directory outside
|
|
* Codeman entirely (it took precedence over the user's own global/project
|
|
* statusline with no disclosure and no way to remove it — found live
|
|
* 2026-08-31).
|
|
*
|
|
* Also self-heals: if an OLDER Codeman build already wrote its marked
|
|
* exporter into this workspace's settings.local.json, it is stripped here
|
|
* (isOurs-guarded, same as applyStatusLineConfig's removal branch) so every
|
|
* workspace migrates off the disk-based mechanism the first time a session
|
|
* starts there again — no manual cleanup required. This self-heal runs
|
|
* regardless of `telemetryEnabled`, so a legacy leftover is cleaned up even
|
|
* while the setting is currently off.
|
|
*
|
|
* Returns undefined when telemetry isn't currently enabled (see
|
|
* readPlanUsageTelemetryEnabled), or when the workspace already has its OWN
|
|
* hand-configured statusLine (never override a real one).
|
|
*/
|
|
export async function resolveStatusLineCliCommand(
|
|
casePath: string,
|
|
telemetryEnabled: boolean
|
|
): Promise<string | undefined> {
|
|
const settingsPath = join(casePath, '.claude', 'settings.local.json');
|
|
let userHasOwnStatusLine = false;
|
|
const skip = await absentOrUnreachable(settingsPath);
|
|
// Unreachable: whether the user configured their own statusLine there cannot be
|
|
// told, and this must never override a real one, so inject nothing.
|
|
if (skip === 'unreachable') return undefined;
|
|
if (!skip) {
|
|
let raw: string;
|
|
try {
|
|
raw = await readFile(settingsPath, 'utf-8');
|
|
} catch (err) {
|
|
// Gone since the probe: nothing to respect. Unreadable: same reason as above.
|
|
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') return undefined;
|
|
raw = '';
|
|
}
|
|
try {
|
|
const existing = raw ? JSON.parse(raw) : {};
|
|
const current = existing.statusLine as { command?: unknown } | undefined;
|
|
if (current && typeof current.command === 'string') {
|
|
if (current.command.includes(STATUSLINE_MARKER)) {
|
|
await applyStatusLineConfig(casePath, false); // strip legacy disk-written exporter
|
|
} else {
|
|
userHasOwnStatusLine = true;
|
|
}
|
|
}
|
|
} catch {
|
|
// Malformed — leave it alone, same guard applyStatusLineConfig itself uses.
|
|
}
|
|
}
|
|
if (!telemetryEnabled || userHasOwnStatusLine) return undefined;
|
|
return ensureStatusLineExporterScript();
|
|
}
|
|
|
|
// ─── Agent skill injection ───────────────────────────────────────────────────
|
|
|
|
/**
|
|
* Version-agnostic ownership prefix for the injected agent skill, same pattern as
|
|
* `BACKGROUND_WAKE_MARKER_PREFIX`: ownership is decided on the prefix so a wording
|
|
* change in the full marker cannot disown every previously injected copy.
|
|
*/
|
|
const AGENT_SKILL_MARKER_PREFIX = '<!-- codeman-managed-agent-skill';
|
|
|
|
/**
|
|
* Marker appended to the injected SKILL.md. Its presence is what makes a copy OURS:
|
|
* install/refresh/remove all refuse to touch a `skills/codeman` whose SKILL.md lacks
|
|
* it, so a user's hand-authored or hand-edited-and-de-marked skill is never clobbered.
|
|
*/
|
|
const AGENT_SKILL_MARKER = `${AGENT_SKILL_MARKER_PREFIX}: installed by Codeman; edits are overwritten while the agent-skill setting is on -->`;
|
|
|
|
/**
|
|
* Packaged source of the skill: `skills/codeman/` at the package root. Resolved
|
|
* relative to this module so it works from `src/` (tsx dev), `dist/` (tsc build),
|
|
* and an npm install (`files` includes `skills`), all of which sit one level below
|
|
* the package root.
|
|
*/
|
|
function agentSkillSourceDir(): string {
|
|
return join(dirname(fileURLToPath(import.meta.url)), '..', 'skills', 'codeman');
|
|
}
|
|
|
|
interface AgentSkillFile {
|
|
/** Path relative to the target skill dir (e.g. `reference/endpoints.md`). */
|
|
relPath: string;
|
|
content: string;
|
|
}
|
|
|
|
/**
|
|
* Read the packaged skill: SKILL.md (marker appended) plus every markdown file
|
|
* under `reference/`. Enumerated from disk rather than a hardcoded manifest so a
|
|
* new reference file ships without touching this module.
|
|
*/
|
|
async function readAgentSkillSource(): Promise<AgentSkillFile[]> {
|
|
const src = agentSkillSourceDir();
|
|
const skillMd = await readFile(join(src, 'SKILL.md'), 'utf-8');
|
|
const files: AgentSkillFile[] = [{ relPath: 'SKILL.md', content: `${skillMd.trimEnd()}\n\n${AGENT_SKILL_MARKER}\n` }];
|
|
let referenceNames: string[] = [];
|
|
try {
|
|
referenceNames = (await readdir(join(src, 'reference'))).filter((name) => name.endsWith('.md')).sort();
|
|
} catch {
|
|
// no reference dir in the source; SKILL.md alone is still a valid skill
|
|
}
|
|
for (const name of referenceNames) {
|
|
files.push({ relPath: join('reference', name), content: await readFile(join(src, 'reference', name), 'utf-8') });
|
|
}
|
|
return files;
|
|
}
|
|
|
|
/**
|
|
* Publish one skill file with a temp + rename, never a bare overwrite.
|
|
*
|
|
* Claude Code reads SKILL.md whole when it loads the skill, so an in-place rewrite of
|
|
* the file (20KB+, several write() syscalls) lets a load that lands mid-write see a
|
|
* TRUNCATED skill. rename() swaps the finished file in one step, so a
|
|
* reader sees either the old copy or the new one. The pid+random temp name matters
|
|
* because `codeman skill install` writes these same paths from a DIFFERENT process than
|
|
* the server, where the in-process lock cannot help: a shared temp name would let the
|
|
* two tear each other's payload (same reasoning as user-store.ts).
|
|
*/
|
|
async function writeSkillFileAtomic(target: string, content: string): Promise<void> {
|
|
// `.tmp` last, so a leftover temp is never picked up as a `.md` skill file.
|
|
const tmpPath = `${target}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`;
|
|
try {
|
|
await writeFile(tmpPath, content);
|
|
await rename(tmpPath, target);
|
|
} catch (err) {
|
|
await unlink(tmpPath).catch(() => {});
|
|
throw err;
|
|
}
|
|
}
|
|
|
|
async function isSymlink(path: string): Promise<boolean> {
|
|
try {
|
|
return (await lstat(path)).isSymbolicLink();
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Whether a folder INSIDE the copy that holds skill files (today only `reference/`) is a
|
|
* symlink. The checks on the copy and its parent stop at the copy itself, and a write or
|
|
* unlink of `reference/<name>.md` follows a linked `reference/` wherever it points:
|
|
* measured, `reference -> <elsewhere>` made install overwrite a `history.md` there and
|
|
* uninstall delete it. A cloned repository can commit that link, and a Docker case's
|
|
* container can plant it in the bind-mounted workspace that the host injects into, so
|
|
* both are refused like a linked copy. Checked once before the first write or unlink; a
|
|
* link swapped in after the check (a race against the container) is not covered.
|
|
*/
|
|
async function agentSkillSubdirIsSymlink(skillDir: string, files: AgentSkillFile[]): Promise<boolean> {
|
|
const subdirs = new Set<string>(['reference']);
|
|
for (const file of files) {
|
|
// Every folder on the way to the file, outermost first: `a/b/x.md` checks `a`, then `a/b`.
|
|
const parts = dirname(file.relPath)
|
|
.split(/[\\/]/)
|
|
.filter((part) => part !== '' && part !== '.');
|
|
for (let i = 1; i <= parts.length; i++) subdirs.add(join(...parts.slice(0, i)));
|
|
}
|
|
for (const subdir of subdirs) {
|
|
if (await isSymlink(join(skillDir, subdir))) return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* The ignore file every Codeman-managed skill copy carries, and what it holds: `*`
|
|
* matches everything in the copy's own folder (the ignore file included), so a user's
|
|
* repository never lists `.claude/skills/codeman/` (or `.agents/skills/codeman/`) as
|
|
* untracked, without Codeman touching the repository's own `.gitignore` or
|
|
* `info/exclude`. Same idea as the prompt-uploads folder (`ensureUploadDir`).
|
|
*
|
|
* Deliberately NOT part of `readAgentSkillSource()`: it is written once with O_EXCL and
|
|
* never compared or rewritten, so a file the user put there (or edited) is theirs.
|
|
*
|
|
* Measured against Claude Code 2.1.319, whose skill discovery runs `git check-ignore`
|
|
* only on directories at or above `.claude/skills` (the nested-skills walk), never on a
|
|
* skill folder or its SKILL.md: a `*` inside `codeman/` ignores the folder's CONTENTS,
|
|
* not the folder, so the skill still loads. Codex 0.162 does no gitignore check on skills.
|
|
*/
|
|
const AGENT_SKILL_GITIGNORE = '.gitignore';
|
|
const AGENT_SKILL_GITIGNORE_CONTENT = '*\n';
|
|
|
|
/**
|
|
* Write the copy's `.gitignore` if none is there. Returns whether it wrote one.
|
|
* 'wx' (O_CREAT|O_EXCL) never replaces an existing file and refuses a symlink at the
|
|
* name. A create that succeeded before the write failed (ENOSPC) would leave an empty
|
|
* file that reads as the user's next time, so it is taken back; that cleanup's own
|
|
* failure must not replace the cause.
|
|
*/
|
|
async function ensureAgentSkillGitignore(skillDir: string): Promise<boolean> {
|
|
const ignoreFile = join(skillDir, AGENT_SKILL_GITIGNORE);
|
|
try {
|
|
await writeFile(ignoreFile, AGENT_SKILL_GITIGNORE_CONTENT, { flag: 'wx' });
|
|
return true;
|
|
} catch (err) {
|
|
if ((err as NodeJS.ErrnoException).code === 'EEXIST') return false;
|
|
await unlink(ignoreFile).catch(() => {});
|
|
throw err;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Remove the copy's `.gitignore` only when it is the LAST thing in the folder and holds
|
|
* exactly what Codeman writes. Anything else in the folder (a user's own notes) keeps
|
|
* the ignore file, so those files stay out of `git status` as they were, and a
|
|
* `.gitignore` with other content is the user's.
|
|
*/
|
|
async function removeAgentSkillGitignoreIfLast(skillDir: string): Promise<void> {
|
|
const ignoreFile = join(skillDir, AGENT_SKILL_GITIGNORE);
|
|
try {
|
|
const entries = await readdir(skillDir);
|
|
if (entries.length !== 1 || entries[0] !== AGENT_SKILL_GITIGNORE) return;
|
|
if (!(await lstat(ignoreFile)).isFile()) return;
|
|
if ((await readFile(ignoreFile, 'utf-8')) !== AGENT_SKILL_GITIGNORE_CONTENT) return;
|
|
await unlink(ignoreFile);
|
|
} catch {
|
|
// best-effort: a folder that stays behind holds only an ignore file
|
|
}
|
|
}
|
|
|
|
/** What an install/remove actually did, so callers (CLI, logs) can say so. */
|
|
export type AgentSkillApplyResult =
|
|
| 'installed' // fresh copy written
|
|
| 'refreshed' // our copy was stale and got rewritten
|
|
| 'unchanged' // our copy already matches the packaged source
|
|
| 'removed' // our copy deleted
|
|
| 'absent' // nothing there to remove
|
|
| 'foreign' // a copy exists but is not ours; left untouched
|
|
| 'symlink'; // the skill dir, its parent or a folder inside it is a symlink; left untouched
|
|
|
|
/**
|
|
* Install or refresh the Codeman agent skill into `skillDir` (a `.../codeman`
|
|
* directory, e.g. `<case>/.claude/skills/codeman`, `~/.claude/skills/codeman` or
|
|
* `<case>/.agents/skills/codeman`).
|
|
*
|
|
* Refuses these shapes rather than writing through them:
|
|
* - a SYMLINK at the skill dir or its `skills/` parent: this repo's own dogfooding
|
|
* layout (`.claude/skills/codeman -> ../../skills/codeman`) would otherwise have
|
|
* the injector overwrite the repo source through the link;
|
|
* - a SYMLINK at a folder inside the copy (`reference/`), which would carry the skill's
|
|
* files to wherever it points (`agentSkillSubdirIsSymlink`);
|
|
* - a FOREIGN copy (SKILL.md present without our marker): that is the user's own
|
|
* skill, and per the statusLine rule we never clobber what we did not write.
|
|
*
|
|
* Idempotent and cheap: unchanged files are not rewritten, so calling on every
|
|
* session create causes no mtime churn.
|
|
*
|
|
* The copy ignores itself in git: a `.gitignore` of `*` is written FIRST, before any
|
|
* skill file, so a `git status` that runs mid-install never lists the folder either
|
|
* (`ensureAgentSkillGitignore`). It is written once and never rewritten; a copy made
|
|
* before this existed gains it on its next install or refresh, which then reports
|
|
* 'refreshed'.
|
|
*
|
|
* Serialized on the skill dir through the same lock the settings writers use: two
|
|
* sessions created at once in one repo both inject this skill, and interleaving their
|
|
* ownership read with the other's write reports a bogus result (an 'unchanged' for a
|
|
* copy the other writer had not finished). Writes go out via temp + rename, which is
|
|
* what protects a concurrent skill LOAD, in this process or the CLI's.
|
|
*/
|
|
export async function installAgentSkillInto(skillDir: string): Promise<AgentSkillApplyResult> {
|
|
return withSettingsLock(skillDir, async () => {
|
|
if ((await isSymlink(dirname(skillDir))) || (await isSymlink(skillDir))) return 'symlink';
|
|
|
|
let existing: string | null = null;
|
|
try {
|
|
existing = await readFile(join(skillDir, 'SKILL.md'), 'utf-8');
|
|
} catch {
|
|
// absent: fresh install
|
|
}
|
|
if (existing !== null && !existing.includes(AGENT_SKILL_MARKER_PREFIX)) return 'foreign';
|
|
|
|
const files = await readAgentSkillSource();
|
|
if (await agentSkillSubdirIsSymlink(skillDir, files)) return 'symlink';
|
|
await mkdir(skillDir, { recursive: true });
|
|
let changed = await ensureAgentSkillGitignore(skillDir);
|
|
for (const file of files) {
|
|
const target = join(skillDir, file.relPath);
|
|
let current: string | null = null;
|
|
try {
|
|
current = await readFile(target, 'utf-8');
|
|
} catch {
|
|
// missing: will be written
|
|
}
|
|
if (current === file.content) continue;
|
|
await mkdir(dirname(target), { recursive: true });
|
|
await writeSkillFileAtomic(target, file.content);
|
|
changed = true;
|
|
}
|
|
if (!changed) return 'unchanged';
|
|
return existing === null ? 'installed' : 'refreshed';
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Seed a session's agent preamble file (`$XDG_CACHE_HOME/codeman-agent-<id>.sh`,
|
|
* default `~/.cache/`) from the packaged `skills/codeman/preamble.sh`, so the agent
|
|
* skill's §0 bootstrap collapses to a two-line loader instead of a ~150-line block the
|
|
* model has to type out (measured live: that paste alone cost a spawn run ~47 s of
|
|
* generation time). The path formula must match the skill's
|
|
* `${XDG_CACHE_HOME:-$HOME/.cache}` exactly; sessions inherit the server's env, so
|
|
* reading the server's own XDG_CACHE_HOME keeps the two in agreement (`||` mirrors the
|
|
* shell's `:-`, treating empty as unset). Callers gate to LOCAL sessions whose CLI gets
|
|
* the skill (`agentSkillDir()` non-null, any CLI: the preamble is bash + curl + jq, nothing
|
|
* claude-specific; a remote or in-container HOME is not this filesystem) and treat it as
|
|
* best-effort: the skill's §0 fallback block self-heals a missing or stale file. Codex
|
|
* caveat: a local codex started without `--no-daemon` (older than 0.162, or its version
|
|
* probe failed) can run tool commands in a shared app-server daemon whose
|
|
* `CODEMAN_SESSION_ID` is the starting session's, so its loader looks for that session's
|
|
* file and its self id is wrong; the skill tells the agent how to notice.
|
|
*/
|
|
export async function seedAgentSessionPreamble(sessionId: string): Promise<void> {
|
|
const content = await readFile(join(agentSkillSourceDir(), 'preamble.sh'), 'utf-8');
|
|
await mkdir(agentPreambleCacheDir(), { recursive: true });
|
|
await writeFile(agentPreamblePath(sessionId), content, { mode: 0o600 });
|
|
}
|
|
|
|
/** Where the preamble caches live. One formula, shared by seed / remove / prune. */
|
|
function agentPreambleCacheDir(): string {
|
|
return process.env.XDG_CACHE_HOME || join(homedir(), '.cache');
|
|
}
|
|
|
|
/** `codeman-agent-<sessionId>.sh` in that directory. */
|
|
function agentPreamblePath(sessionId: string): string {
|
|
return join(agentPreambleCacheDir(), `codeman-agent-${sessionId}.sh`);
|
|
}
|
|
|
|
/** Matches exactly what seedAgentSessionPreamble writes, and nothing else in ~/.cache. */
|
|
const AGENT_PREAMBLE_FILE_PATTERN = /^codeman-agent-(.+)\.sh$/;
|
|
|
|
/** How long a preamble cache with no live session behind it is kept before the sweep takes it. */
|
|
export const AGENT_PREAMBLE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
|
|
|
|
/**
|
|
* Drop one session's preamble cache. Called when a session is deleted, which is the
|
|
* precise counterpart to seeding it at create: one file per claude session was being
|
|
* written and nothing ever removed them (236 leftovers measured on a working machine,
|
|
* the oldest three weeks old). Best-effort — a file that will not delete is litter,
|
|
* never a reason to fail a teardown.
|
|
*/
|
|
export async function removeAgentSessionPreamble(sessionId: string): Promise<void> {
|
|
await unlink(agentPreamblePath(sessionId)).catch(() => {});
|
|
}
|
|
|
|
/**
|
|
* Sweep preamble caches left by sessions that are gone: the delete path above covers
|
|
* an orderly teardown, and this covers everything else (a crash, a killed server, a
|
|
* session deleted by an older build, another instance's leftovers).
|
|
*
|
|
* ⚠️ Two guards, and both matter: a file whose session is in `keepSessionIds` is never
|
|
* touched however old it is, and everything else needs `maxAgeMs` of age on top. A live
|
|
* session's cache is load-bearing — remove it and the skill's two-line loader fails its
|
|
* version check mid-run — and the age floor is what keeps a session belonging to
|
|
* ANOTHER instance (whose ids this process cannot see) out of the blast radius. Losing
|
|
* one is degradation rather than breakage: the §0 fallback block rewrites it.
|
|
*
|
|
* Returns how many it removed. Best-effort throughout; a missing cache dir is 0.
|
|
*/
|
|
export async function pruneAgentSessionPreambles(
|
|
keepSessionIds: Iterable<string>,
|
|
maxAgeMs: number = AGENT_PREAMBLE_MAX_AGE_MS
|
|
): Promise<number> {
|
|
const cacheDir = agentPreambleCacheDir();
|
|
const keep = new Set(keepSessionIds);
|
|
const cutoff = Date.now() - maxAgeMs;
|
|
let removed = 0;
|
|
|
|
let entries: string[];
|
|
try {
|
|
entries = await readdir(cacheDir);
|
|
} catch {
|
|
return 0;
|
|
}
|
|
|
|
for (const entry of entries) {
|
|
const sessionId = AGENT_PREAMBLE_FILE_PATTERN.exec(entry)?.[1];
|
|
if (!sessionId || keep.has(sessionId)) continue;
|
|
const path = join(cacheDir, entry);
|
|
try {
|
|
if ((await lstat(path)).mtimeMs > cutoff) continue;
|
|
await unlink(path);
|
|
removed++;
|
|
} catch {
|
|
/* best-effort — a vanished or unreadable file is not our problem */
|
|
}
|
|
}
|
|
return removed;
|
|
}
|
|
|
|
/**
|
|
* Refresh the USER-LEVEL skill copy (`~/.claude/skills/codeman`) IF one exists and is
|
|
* Codeman-managed. `codeman skill install` (no `--case`) writes that copy once, and
|
|
* unlike per-case copies (re-installed on every session create) nothing ever refreshed
|
|
* it, so it stayed at whatever version installed it. That matters because Claude Code
|
|
* loads the USER-LEVEL copy over a case's fresh one when both carry the name `codeman`:
|
|
* observed live 2026-08-14, an Aug 9 user copy (pre fast-path, pre lineage header)
|
|
* shadowed the current per-case injections, so every agent-driven spawn ran the old
|
|
* recipes, spawned workers serially, and lost their lineage arcs.
|
|
*
|
|
* Refresh-ONLY: an absent copy is not installed (the user never asked for a global
|
|
* copy), and foreign/symlink copies are refused by installAgentSkillInto itself.
|
|
*/
|
|
export async function refreshUserAgentSkill(): Promise<AgentSkillApplyResult | 'absent'> {
|
|
const skillDir = join(homedir(), '.claude', 'skills', 'codeman');
|
|
try {
|
|
const existing = await readFile(join(skillDir, 'SKILL.md'), 'utf-8');
|
|
if (!existing.includes(AGENT_SKILL_MARKER_PREFIX)) return 'foreign';
|
|
} catch {
|
|
return 'absent';
|
|
}
|
|
return installAgentSkillInto(skillDir);
|
|
}
|
|
|
|
/**
|
|
* Remove a Codeman-managed skill copy from `skillDir`. Same ownership and symlink
|
|
* refusals as the install path. Deletes only files the packaged source would have
|
|
* written (never `rm -rf`, so a user's extra files in the directory survive), then
|
|
* the copy's own `.gitignore` when nothing else is left beside it, then prunes the
|
|
* directories bottom-up if they emptied.
|
|
*
|
|
* Shares the install path's per-dir lock so an uninstall can't run between an install's
|
|
* ownership read and its writes, which would leave half the skill back on disk.
|
|
*/
|
|
export async function removeAgentSkillFrom(skillDir: string): Promise<AgentSkillApplyResult> {
|
|
return withSettingsLock(skillDir, async () => {
|
|
if ((await isSymlink(dirname(skillDir))) || (await isSymlink(skillDir))) return 'symlink';
|
|
|
|
let existing: string | null = null;
|
|
try {
|
|
existing = await readFile(join(skillDir, 'SKILL.md'), 'utf-8');
|
|
} catch {
|
|
return 'absent';
|
|
}
|
|
if (!existing.includes(AGENT_SKILL_MARKER_PREFIX)) return 'foreign';
|
|
|
|
// Manifest-based, with SKILL.md as the fallback when the packaged source is
|
|
// unreadable: removal must still work on an install whose skills/ dir went missing.
|
|
const files = await readAgentSkillSource().catch((): AgentSkillFile[] => [{ relPath: 'SKILL.md', content: '' }]);
|
|
// An unlink through a linked `reference/` deletes files wherever it points.
|
|
if (await agentSkillSubdirIsSymlink(skillDir, files)) return 'symlink';
|
|
for (const file of files) {
|
|
await unlink(join(skillDir, file.relPath)).catch(() => {});
|
|
}
|
|
await rmdir(join(skillDir, 'reference')).catch(() => {}); // fails when non-empty, fine
|
|
await removeAgentSkillGitignoreIfLast(skillDir);
|
|
await rmdir(skillDir).catch(() => {});
|
|
await rmdir(dirname(skillDir)).catch(() => {}); // prune `.claude/skills` (or the CLI's own dir) if now empty
|
|
return 'removed';
|
|
});
|
|
}
|
|
|
|
// ============================================================================
|
|
// omp approval hooks
|
|
// ============================================================================
|
|
|
|
/** Marks the hook file this module owns inside a workspace. */
|
|
const OMP_APPROVAL_HOOK_MARKER = 'CODEMAN_OMP_APPROVAL_HOOK_V1';
|
|
|
|
/**
|
|
* omp's own hook directory, workspace-relative. omp scans `<cwd>/.claude/hooks/pre`
|
|
* and `<cwd>/.claude/hooks/post` (`projectDir` for the `claude` persona) plus a
|
|
* user-level `<agentDir>/hooks`, and loads each `.ts`/`.js` file's default export as
|
|
* `(pi: HookAPI) => void`. A project-level `pre` hook is deliberately the target: it
|
|
* travels with the workspace the session actually runs in, so no per-machine or
|
|
* per-user install is needed and removing the workspace removes the hook.
|
|
*/
|
|
export const OMP_APPROVAL_HOOK_DIR = '.claude/hooks/pre';
|
|
export const OMP_APPROVAL_HOOK_FILE = 'codeman-approval.ts';
|
|
|
|
/**
|
|
* Source of the hook that turns omp's own approval events into Codeman hook events.
|
|
*
|
|
* WHY this exists: omp installs no Claude-style `settings.local.json` hook block — its
|
|
* hooks are modules — so without this file an omp pane asking for tool approval is
|
|
* silent: `/api/approvals` stays empty, the tab never goes red and no notification
|
|
* fires. The registry declares it through `capabilities.approvalHookFile`, NOT
|
|
* `hooks: 'always'` (which would also promise `stop` and answerable dialogs).
|
|
*
|
|
* The mapping uses Claude's event names, because the server routes on them
|
|
* (`APPROVAL_KIND_BY_EVENT` in web/routes/hook-event-routes.ts):
|
|
* - `tool_approval_requested` -> `permission_prompt` (opens an alert-only inbox item)
|
|
* - `tool_approval_resolved` -> `elicitation_complete` (resolves it, whether the user
|
|
* approved or denied, so a denied dialog does not leave a red tab forever)
|
|
*
|
|
* Several calls in one batch can each wait on their own prompt, and the inbox keeps one
|
|
* item per session, so the module tracks pending `toolCallId`s and reports the close only
|
|
* when the last one resolves. That set drains because omp pairs every request with a
|
|
* resolve, an aborted prompt included (its approval wrapper emits `approved: false` from
|
|
* the catch, omp 18.18.6 `extensibility/extensions/wrapper.ts`); only omp dying mid-prompt
|
|
* skips it, which leaves the alert up exactly as it would without the set. Reports go out
|
|
* in order (one chain), so a fast approve cannot overtake the prompt that opened it.
|
|
*
|
|
* `reason` is omp's POLICY note (a restricted folder, a critical-pattern match), not the
|
|
* command, and is absent on an ordinary mode-raised prompt, so it rides `message`.
|
|
*
|
|
* HTTPS: `CODEMAN_API_URL` is loopback HTTPS with a self-signed certificate on `--https`
|
|
* and tailscale installs (Codeman's own hook curl passes `-k`, the DeepSeek shim sets
|
|
* `rejectUnauthorized: false`). omp runs on Bun, whose fetch verifies certificates by
|
|
* default, so an `https:` URL gets Bun's `tls: { rejectUnauthorized: false }`.
|
|
*
|
|
* ⚠️ Fails OPEN and SILENT, like the memory-gate hook: a hook that throws would break
|
|
* the approval flow it exists to report. Every path catches, and nothing is awaited
|
|
* unbounded — each POST carries a short AbortSignal and the handlers never await it.
|
|
*/
|
|
export function generateOmpApprovalHook(): string {
|
|
return `// ${OMP_APPROVAL_HOOK_MARKER} — auto-generated by Codeman; safe to delete, rewritten when a session is created.
|
|
//
|
|
// Reports omp's tool-approval dialogs to Codeman's /api/hook-event so an omp pane
|
|
// raises a tab alert and a desktop notification. Answer the dialog in the terminal.
|
|
// Codeman owns this file: a foreign file of the same name is never overwritten.
|
|
import { readFile } from "node:fs/promises";
|
|
import type { HookAPI } from "@oh-my-pi/pi-coding-agent/extensibility/hooks";
|
|
|
|
const API_URL = process.env.CODEMAN_API_URL;
|
|
const SESSION_ID = process.env.CODEMAN_SESSION_ID;
|
|
const SECRET_FILE = process.env.CODEMAN_HOOK_SECRET_FILE;
|
|
// Loopback HTTPS (--https, tailscale) uses a self-signed certificate, which Bun's fetch
|
|
// refuses by default; Codeman's own hook curl passes -k for the same reason.
|
|
const TLS = API_URL?.startsWith("https:") ? { tls: { rejectUnauthorized: false } } : {};
|
|
|
|
/** POST one Codeman hook event. Never throws; bounded by its timeout. */
|
|
async function send(event: string, data: Record<string, unknown>): Promise<void> {
|
|
if (!API_URL || !SESSION_ID) return;
|
|
try {
|
|
const secret = SECRET_FILE ? (await readFile(SECRET_FILE, "utf8")).trim() : "";
|
|
await fetch(\`\${API_URL}/api/hook-event\`, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json", "X-Codeman-Hook-Secret": secret },
|
|
body: JSON.stringify({ event, sessionId: SESSION_ID, data }),
|
|
signal: AbortSignal.timeout(5000),
|
|
...TLS,
|
|
});
|
|
} catch {
|
|
// Best effort by contract: a failed report must never disturb the dialog itself.
|
|
}
|
|
}
|
|
|
|
// One chain, so reports arrive in the order omp raised them: a fast approve must not
|
|
// overtake the prompt it answers and leave the alert up.
|
|
let chain: Promise<void> = Promise.resolve();
|
|
function report(event: string, data: Record<string, unknown>): void {
|
|
chain = chain.then(() => send(event, data));
|
|
}
|
|
|
|
export default function codemanApprovalHook(pi: HookAPI): void {
|
|
// Calls in one batch can each wait on their own prompt, and Codeman keeps one alert per
|
|
// session, so it is cleared only when the LAST pending approval resolves.
|
|
const pending = new Set<string>();
|
|
|
|
pi.on("tool_approval_requested", (event) => {
|
|
pending.add(event.toolCallId);
|
|
// \`reason\` is omp's policy note (restricted folder, critical pattern), not the command.
|
|
report("permission_prompt", {
|
|
tool_name: event.toolName,
|
|
...(event.reason ? { message: event.reason } : {}),
|
|
});
|
|
});
|
|
|
|
pi.on("tool_approval_resolved", (event) => {
|
|
pending.delete(event.toolCallId);
|
|
if (pending.size > 0) return;
|
|
report("elicitation_complete", {
|
|
tool_name: event.toolName,
|
|
approved: event.approved,
|
|
});
|
|
});
|
|
}
|
|
`;
|
|
}
|
|
|
|
export type ApprovalHookApplyResult = 'installed' | 'refreshed' | 'unchanged' | 'foreign' | 'symlink';
|
|
|
|
/**
|
|
* Install or refresh the omp approval hook in `<workspace>/.claude/hooks/pre/`.
|
|
*
|
|
* Ownership: the file carries `OMP_APPROVAL_HOOK_MARKER` (the generated module has it
|
|
* in its header, and the check takes it anywhere in the file). A file
|
|
* WITHOUT the marker is somebody else's hook and is left untouched (`foreign`) — the
|
|
* same posture `installAgentSkillInto` takes, so Codeman never clobbers user work.
|
|
* EVERY component below the workspace (`.claude`, `.claude/hooks`, `.claude/hooks/pre`)
|
|
* and the target file itself is `lstat`ed, and a symlink anywhere is refused rather than
|
|
* written through: a linked `.claude/hooks` once put `pre/<file>` in the link's target.
|
|
*
|
|
* Idempotent: an unchanged file is not rewritten (`unchanged`), so this is safe to call
|
|
* on every omp session create.
|
|
*/
|
|
export async function applyApprovalHookFile(workspace: string, fileName: string): Promise<ApprovalHookApplyResult> {
|
|
const hookDir = join(workspace, OMP_APPROVAL_HOOK_DIR);
|
|
const target = join(hookDir, fileName);
|
|
return withSettingsLock(target, async () => {
|
|
let component = workspace;
|
|
for (const part of [...OMP_APPROVAL_HOOK_DIR.split('/'), fileName]) {
|
|
component = join(component, part);
|
|
if (await isSymlink(component)) return 'symlink';
|
|
}
|
|
|
|
let existing: string | null = null;
|
|
try {
|
|
existing = await readFile(target, 'utf-8');
|
|
} catch {
|
|
// absent: fresh install
|
|
}
|
|
if (existing !== null && !existing.includes(OMP_APPROVAL_HOOK_MARKER)) return 'foreign';
|
|
|
|
const content = generateOmpApprovalHook();
|
|
if (existing === content) return 'unchanged';
|
|
|
|
await mkdir(hookDir, { recursive: true });
|
|
await writeSkillFileAtomic(target, content);
|
|
return existing === null ? 'installed' : 'refreshed';
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Claude Code's project skills directory, and the meaning `agentSkillInjection: true`
|
|
* had before `capabilities.agentSkillDir` existed.
|
|
*/
|
|
export const CLAUDE_AGENT_SKILL_DIR: AgentSkillDir = '.claude/skills';
|
|
|
|
/**
|
|
* The workspace-relative skills directory this CLI scans, i.e. where its sessions get
|
|
* the skill, or `null` when they get none. Pure registry data, so no call site
|
|
* branches on a CLI id.
|
|
*/
|
|
export function agentSkillDir(
|
|
capabilities: Pick<CliCapabilities, 'agentSkillInjection' | 'agentSkillDir'> | undefined
|
|
): AgentSkillDir | null {
|
|
if (!capabilities?.agentSkillInjection) return null;
|
|
return capabilities.agentSkillDir ?? CLAUDE_AGENT_SKILL_DIR;
|
|
}
|
|
|
|
/** `<casePath>/<dir>/codeman`, the directory the skill's SKILL.md lives in. */
|
|
export function agentSkillDirFor(casePath: string, dir: AgentSkillDir): string {
|
|
return join(casePath, dir, 'codeman');
|
|
}
|
|
|
|
/**
|
|
* Add or remove the Codeman agent skill in `<case>/<dir>/codeman`, where `dir` is the
|
|
* skills directory the session's CLI scans (default: Claude Code's `.claude/skills`;
|
|
* callers resolve it with `agentSkillDir()`), mirroring `applyStatusLineConfig`'s
|
|
* shape. Gated by the synced `agentSkillEnabled` app setting: default ON since 1.50.0
|
|
* (an absent key is on, only an explicit false is off; `getAgentSkillEnabled()` in
|
|
* server.ts), which is safe for a user's repository because the copy ignores itself
|
|
* in git (`ensureAgentSkillGitignore`).
|
|
*
|
|
* Call-site policy is ADD-ONLY on session create (callers pass `enabled: true` or
|
|
* skip the call), for the statusLine reason: sessions in a repo share one workspace,
|
|
* so a single create while the setting is off must not yank the skill out from
|
|
* under other live sessions.
|
|
*
|
|
* ⚠️ Consequence: turning `agentSkillEnabled` OFF sweeps nothing. There is deliberately
|
|
* no server-side toggle-off sweep (it would have to walk every case, including ones
|
|
* with live sessions, and would hit exactly the shared-workspace hazard above), so
|
|
* already-injected copies stay on disk until removed per case with
|
|
* `codeman skill uninstall --case <name>`, which removes the Codeman-managed copy from
|
|
* every skills directory the registry could have written. The `enabled: false` branch
|
|
* here backs that CLI and the tests; it has no server call site. Keep the README's
|
|
* Agent Skill note in sync if this ever changes.
|
|
*/
|
|
export async function applyAgentSkill(
|
|
casePath: string,
|
|
enabled: boolean,
|
|
dir: AgentSkillDir = CLAUDE_AGENT_SKILL_DIR
|
|
): Promise<AgentSkillApplyResult> {
|
|
const skillDir = agentSkillDirFor(casePath, dir);
|
|
return enabled ? installAgentSkillInto(skillDir) : removeAgentSkillFrom(skillDir);
|
|
}
|