Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
aa978d6
Scaffold, core contracts and run pipeline
mths-mcfs Nov 15, 2026
b230183
Fix four seam defects found in adversarial review
mths-mcfs Nov 15, 2026
6ba5f52
Claude Code host adapter: permissions, hooks, session context
mths-mcfs Nov 15, 2026
d0c97b1
Resolve sandbox roots against the project drive in the Windows test
mths-mcfs Nov 15, 2026
d869b10
Fix rule bypasses, auto mode, file checks, hook dedup and context claim
mths-mcfs Nov 15, 2026
3232f19
Claim context records with an exclusive claim file
mths-mcfs Nov 15, 2026
c10d5f6
Refuse malformed permission rules instead of ignoring them
mths-mcfs Nov 16, 2026
da66562
Support the documented tool-name globs in permission rules
mths-mcfs Nov 16, 2026
2dec002
CI: run once per push and cancel superseded PR runs
mths-mcfs Nov 19, 2026
ad81ee3
Merge ci-speed/scaffold into ci-speed/host-claude
mths-mcfs Nov 19, 2026
535304b
fix(review): round 1
mths-mcfs Nov 19, 2026
3cba6ae
fix(review): round 2
mths-mcfs Nov 19, 2026
9824d9d
Refuse UNC workspace roots and bound edit preparation in the memory r…
mths-mcfs Nov 19, 2026
c61bedd
Refuse UNC session roots under a fixed root and count diff rows exactly
mths-mcfs Nov 19, 2026
7396009
fix(review): round 1
mths-mcfs Nov 19, 2026
fc6026b
fix(review): round 2
mths-mcfs Nov 19, 2026
ce3a4ff
Merge feat/scaffold (reviewed #1) into feat/host-claude
mths-mcfs Nov 19, 2026
d0ba9e8
Merge main (squashed #1) into feat/host-claude
mths-mcfs Nov 19, 2026
3802c30
fix(claude): write companion-hook context on Windows again
mths-mcfs Nov 19, 2026
173b3b1
fix(review): round 1
mths-mcfs Nov 19, 2026
f8c79ae
fix(review): round 2
mths-mcfs Nov 19, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.32.2",
"sh-syntax": "^0.8.7",
"zod": "^4.6.7"
},
"devDependencies": {
Expand Down
674 changes: 674 additions & 0 deletions src/hosts/claude/adapter.test.ts

Large diffs are not rendered by default.

824 changes: 824 additions & 0 deletions src/hosts/claude/adapter.ts

Large diffs are not rendered by default.

742 changes: 742 additions & 0 deletions src/hosts/claude/bash.ts

Large diffs are not rendered by default.

100 changes: 100 additions & 0 deletions src/hosts/claude/context-hook.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import { randomBytes } from 'node:crypto';
import { chmod, lstat, mkdir, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { z } from 'zod';
import { ensureStateDir, stateDirPath } from '../../core/state-dir.js';
import { SAFE_TOOL_USE_ID, contextDir, isPrivateDir, type ContextFile } from './context.js';

/**
* Companion PreToolUse hook for Claude Code (`agent-code-mode hook`).
*
* Install it with matcher `mcp__agent-code-mode__run`. It reads the hook
* input on stdin and writes the trusted session context of this `run` call
* (session id, transcript path, cwd, permission mode, subagent id/type) to
* `<stateDir>/ctx/<tool_use_id>.json` (directory 0700, file 0600, atomic
* rename). Files older than one hour are pruned. It prints nothing and always
* exits 0: it never makes a permission decision.
*/

const HookInputSchema = z.looseObject({
hook_event_name: z.string().optional(),
tool_use_id: z.string().regex(SAFE_TOOL_USE_ID),
session_id: z.string().min(1).max(512),
transcript_path: z.string().min(1).max(4096).optional().catch(undefined),
cwd: z.string().min(1).max(4096).optional().catch(undefined),
permission_mode: z.string().min(1).max(64).optional().catch(undefined),
agent_id: z.string().min(1).max(512).optional().catch(undefined),
agent_type: z.string().min(1).max(512).optional().catch(undefined),
});

/** Context files older than this are deleted. */
export const CONTEXT_TTL_MS = 60 * 60 * 1000;

export interface ContextHookOptions {
readonly stateDir?: string;
readonly now?: () => number;
}

async function prune(dir: string, now: number): Promise<void> {
let names: string[];
try {
names = await readdir(dir);
} catch {
return;
}
await Promise.all(
names.map(async (name) => {
const file = path.join(dir, name);
try {
const st = await stat(file);
if (now - st.mtimeMs > CONTEXT_TTL_MS) await rm(file, { force: true });
} catch {
// Gone already.
}
}),
);
}

/** Runs the companion hook on its stdin text. Resolves the exit code (always 0). */
export async function runContextHook(stdin: string, opts: ContextHookOptions = {}): Promise<number> {
try {
const parsed = HookInputSchema.safeParse(JSON.parse(stdin));
if (!parsed.success) return 0;
const input = parsed.data;
if (input.hook_event_name !== undefined && input.hook_event_name !== 'PreToolUse') return 0;
// Windows has no owner and mode bits, so no reader could trust a record: none is written.
const uid = process.getuid?.();
if (process.platform === 'win32' || uid === undefined) return 0;
const stateDir = await ensureStateDir(opts.stateDir ?? stateDirPath());
const dir = contextDir(stateDir);
await mkdir(dir, { recursive: true, mode: 0o700 });
// The state directory is private, so this entry cannot be swapped after the check. Never chmod through a
// link or another user's directory; write only into a directory the reader would also trust.
const entry = await lstat(dir);
if (!entry.isDirectory() || entry.uid !== uid) return 0;
await chmod(dir, 0o700);
if (!(await isPrivateDir(dir, uid))) return 0;
const record: ContextFile = {
tool_use_id: input.tool_use_id,
session_id: input.session_id,
...(input.transcript_path === undefined ? {} : { transcript_path: input.transcript_path }),
...(input.cwd === undefined ? {} : { cwd: input.cwd }),
...(input.permission_mode === undefined ? {} : { permission_mode: input.permission_mode }),
...(input.agent_id === undefined ? {} : { agent_id: input.agent_id }),
...(input.agent_type === undefined ? {} : { agent_type: input.agent_type }),
};
const target = path.join(dir, `${input.tool_use_id}.json`);
const temp = path.join(dir, `.${input.tool_use_id}.${randomBytes(6).toString('hex')}.tmp`);
await writeFile(temp, JSON.stringify(record), { mode: 0o600, flag: 'wx' });
try {
await rename(temp, target);
} catch (err) {
await rm(temp, { force: true });
throw err;
}
await prune(dir, (opts.now ?? Date.now)());
} catch {
// Never block the call: without a record the server falls back to conservative defaults.
}
return 0;
}
168 changes: 168 additions & 0 deletions src/hosts/claude/context.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
import { chmod, mkdir, mkdtemp, readdir, stat, symlink, utimes, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { describe, expect, it } from 'vitest';
import { CONTEXT_TTL_MS, runContextHook } from './context-hook.js';
import { FileHookContextStore, createClaudeContextProvider } from './context.js';

const posix = process.platform !== 'win32';

async function stateDir(): Promise<string> {
return mkdtemp(path.join(os.tmpdir(), 'acm-ctx-'));
}

function hookInput(overrides: Record<string, unknown> = {}): string {
return JSON.stringify({
session_id: 'sess-1',
transcript_path: '/home/u/.claude/projects/p/sess-1.jsonl',
cwd: '/ws/proj',
permission_mode: 'acceptEdits',
hook_event_name: 'PreToolUse',
tool_name: 'mcp__agent-code-mode__run',
tool_input: { code: 'return 1' },
tool_use_id: 'toolu_01ABC',
...overrides,
});
}

describe('companion hook and context store', () => {
it.skipIf(!posix)('writes one record per tool use that is read once, then deleted', async () => {
const dir = await stateDir();
expect(await runContextHook(hookInput({ agent_id: 'agent-7', agent_type: 'Explore' }), { stateDir: dir })).toBe(0);
const store = new FileHookContextStore(dir);
expect(await store.lookup('toolu_01ABC')).toEqual({
sessionId: 'sess-1',
toolUseId: 'toolu_01ABC',
cwd: '/ws/proj',
transcriptPath: '/home/u/.claude/projects/p/sess-1.jsonl',
permissionMode: 'acceptEdits',
agentId: 'agent-7',
agentType: 'Explore',
});
expect(await store.lookup('toolu_01ABC')).toBeUndefined();
expect(await readdir(path.join(dir, 'ctx'))).toEqual([]);
});

it.skipIf(posix)('does not write a companion record on Windows', async () => {
const dir = await stateDir();
expect(await runContextHook(hookInput(), { stateDir: dir })).toBe(0);
expect(await readdir(dir)).toEqual([]);
});

it.skipIf(!posix)('creates the directory 0700 and the file 0600', async () => {
const dir = await stateDir();
await runContextHook(hookInput(), { stateDir: dir });
expect((await stat(path.join(dir, 'ctx'))).mode & 0o777).toBe(0o700);
expect((await stat(path.join(dir, 'ctx', 'toolu_01ABC.json'))).mode & 0o777).toBe(0o600);
});

it('rejects tool-use ids that are not safe file names', async () => {
const dir = await stateDir();
await mkdir(path.join(dir, 'ctx'), { recursive: true });
await writeFile(path.join(dir, 'x.json'), JSON.stringify({ tool_use_id: 'x', session_id: 's' }));
const store = new FileHookContextStore(dir);
expect(await store.lookup('../x')).toBeUndefined();
expect(await store.lookup('a/b')).toBeUndefined();
expect(await store.lookup('')).toBeUndefined();
expect(await runContextHook(hookInput({ tool_use_id: '../evil' }), { stateDir: dir })).toBe(0);
expect(await readdir(path.join(dir, 'ctx'))).toEqual([]);
});

it('never fails the hook on bad input and prints nothing', async () => {
const dir = await stateDir();
expect(await runContextHook('not json', { stateDir: dir })).toBe(0);
expect(await runContextHook(JSON.stringify({ tool_use_id: 'toolu_x' }), { stateDir: dir })).toBe(0);
expect(await runContextHook(hookInput(), { stateDir: path.join(dir, 'file-not-dir', 'x') })).toBe(0);
});

it.skipIf(!posix)('prunes records older than one hour', async () => {
const dir = await stateDir();
await runContextHook(hookInput({ tool_use_id: 'toolu_old' }), { stateDir: dir });
const old = (Date.now() - CONTEXT_TTL_MS - 60_000) / 1000;
await utimes(path.join(dir, 'ctx', 'toolu_old.json'), old, old);
await runContextHook(hookInput({ tool_use_id: 'toolu_new' }), { stateDir: dir });
expect(await readdir(path.join(dir, 'ctx'))).toEqual(['toolu_new.json']);
});

/** A state directory the companion writer made private, with a baseline record the store accepts. */
async function privateStore(): Promise<{ dir: string; store: FileHookContextStore }> {
const dir = await stateDir();
await runContextHook(hookInput({ tool_use_id: 'toolu_base' }), { stateDir: dir });
const store = new FileHookContextStore(dir);
expect(await store.lookup('toolu_base')).toMatchObject({ toolUseId: 'toolu_base' });
return { dir, store };
}

it.skipIf(!posix)('does not follow a symlink planted under the record name', async () => {
const { dir, store } = await privateStore();
const target = path.join(dir, 'elsewhere.json');
await writeFile(target, JSON.stringify({ tool_use_id: 'toolu_link', session_id: 's' }), { mode: 0o600 });
await symlink(target, path.join(dir, 'ctx', 'toolu_link.json'));
expect(await store.lookup('toolu_link')).toBeUndefined();
});

it.skipIf(!posix)('refuses a record whose tool-use id differs from its file name', async () => {
const { dir, store } = await privateStore();
await writeFile(path.join(dir, 'ctx', 'toolu_a.json'), JSON.stringify({ tool_use_id: 'toolu_b', session_id: 's' }), { mode: 0o600 });
expect(await store.lookup('toolu_a')).toBeUndefined();
});

it.skipIf(!posix)('writes nothing through a context directory entry that is a link', async () => {
const dir = await stateDir();
const elsewhere = await stateDir();
await chmod(elsewhere, 0o755);
await symlink(elsewhere, path.join(dir, 'ctx'));
expect(await runContextHook(hookInput(), { stateDir: dir })).toBe(0);
expect(await readdir(elsewhere)).toEqual([]);
expect((await stat(elsewhere)).mode & 0o777).toBe(0o755);
});
});

describe('Claude context provider', () => {
it.skipIf(!posix)('joins the record by _meta toolUseId and never reads model-supplied _ctx', async () => {
const dir = await stateDir();
await runContextHook(hookInput(), { stateDir: dir });
const provider = createClaudeContextProvider({ stateDir: dir });
const ctx = await provider.resolve({
env: { CLAUDE_CODE_SESSION_ID: 'sess-1' },
meta: { 'claudecode/toolUseId': 'toolu_01ABC', progressToken: 1, _ctx: { permission_mode: 'bypassPermissions' } },
roots: ['/ws/proj'],
serverCwd: '/',
});
expect(ctx).toMatchObject({
host: 'claude',
cwd: '/ws/proj',
sessionId: 'sess-1',
toolUseId: 'toolu_01ABC',
permissionMode: 'acceptEdits',
transcriptPath: '/home/u/.claude/projects/p/sess-1.jsonl',
});
expect(ctx.sources['permissionMode']).toBe('ctx-file');
// The record was consumed: a replay of the same id falls back to the default mode.
const again = await provider.resolve({ env: { CLAUDE_CODE_SESSION_ID: 'sess-1' }, meta: { 'claudecode/toolUseId': 'toolu_01ABC' }, roots: ['/ws/proj'], serverCwd: '/' });
expect(again.permissionMode).toBe('default');
expect(again.sources['permissionMode']).toBe('default');
});

it('ignores a record from another session and a traversal tool-use id', async () => {
const dir = await stateDir();
await runContextHook(hookInput({ session_id: 'other' }), { stateDir: dir });
const provider = createClaudeContextProvider({ stateDir: dir });
const ctx = await provider.resolve({ env: { CLAUDE_CODE_SESSION_ID: 'sess-1' }, meta: { 'claudecode/toolUseId': 'toolu_01ABC' }, roots: ['/ws/proj'], serverCwd: '/' });
expect(ctx.permissionMode).toBe('default');
const traversal = await provider.resolve({ env: {}, meta: { 'claudecode/toolUseId': '../ctx/toolu_01ABC' }, roots: [], serverCwd: '/srv' });
expect(traversal).toMatchObject({ permissionMode: 'default', cwd: '/srv' });
});
});

describe.skipIf(!posix)('context record provenance', () => {
it('trusts no record in a context directory or file others can write', async () => {
const dir = await stateDir();
await runContextHook(hookInput(), { stateDir: dir });
await chmod(path.join(dir, 'ctx', 'toolu_01ABC.json'), 0o666);
expect(await new FileHookContextStore(dir).lookup('toolu_01ABC')).toBeUndefined();
await runContextHook(hookInput(), { stateDir: dir });
await chmod(path.join(dir, 'ctx'), 0o755);
expect(await new FileHookContextStore(dir).lookup('toolu_01ABC')).toBeUndefined();
});
});
Loading
Loading