Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

`implementation-worker` SubAgent に委譲し、`implement-issue` skill の手順を実行させる。

Codex CLI: spawn the custom agent named implementation-worker for this step; the root thread must not edit files, run tests, commit, push, or make the review judgment directly.

## 委譲呼び出し

Agent ツールで以下を呼ぶ:
Expand Down
2 changes: 2 additions & 0 deletions .claude/skills/impl-review-loop/steps/step-2-verification.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

Step 1 で PR が起票されたら、`test-runner` SubAgent に検証を委譲する。

Codex CLI: spawn the custom agent named test-runner for this step; the root thread must not edit files, run tests, commit, push, or make the review judgment directly.

## 委譲呼び出し

Agent ツールで以下を呼ぶ:
Expand Down
2 changes: 2 additions & 0 deletions .claude/skills/impl-review-loop/steps/step-4-pr-review.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

Step 2 が `PASS` / `PARTIAL` で完了したら、`pr-reviewer` SubAgent に PR レビューを委譲する。Step 2 が `FAIL` の場合は本ステップをスキップして Step 5 に直行(REQUEST_CHANGES 確定)。

Codex CLI: spawn the custom agent named pr-reviewer for this step; the root thread must not edit files, run tests, commit, push, or make the review judgment directly.

## 委譲呼び出し

```
Expand Down
2 changes: 2 additions & 0 deletions .claude/skills/post-merge-cleanup/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ description: PR マージ後のローカル cleanup と Git 整理を行うと

PR マージ後のローカル環境 cleanup と Git 整理を `post-merge-cleanup-worker` SubAgent に委譲して実行する。

Codex CLI: spawn the custom agent named post-merge-cleanup-worker for this step; the root thread must not edit files, run tests, commit, push, or make the review judgment directly.

## Delegation

main thread は以下の手順で SubAgent に委譲する:
Expand Down
5 changes: 5 additions & 0 deletions .codex/config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ default_permissions = "loop-protocol-rtk"
# Project-local custom agents use default_permissions plus [permissions.*].
# Repo-local hooks live in `.codex/hooks.json`; do not mix inline hooks here.
# Known limitation: this is a fail-closed local guardrail, not a security boundary.
# Project-local config is not evidence of profile routing; runtime evidence must
# come from spawned custom-agent events and validated launch-ledger inputs.

[agents]
max_depth = 1

[permissions.loop-protocol-rtk.filesystem]
":minimal" = "read"
Expand Down
8 changes: 8 additions & 0 deletions docs/dev/agent-skill-boundaries.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@ SKILL.md / SubAgent 定義に書くとコンテクスト汚染になるため、
| `implementation-worker` | write | `acceptEdits` | Read, Grep, Glob, Bash, Edit, Write, MultiEdit | — |
| `post-merge-cleanup-worker` | cleanup | `default` | Bash, Read | Agent, Edit, Write, MultiEdit |

## Codex Dispatch Guardrail

- Codex CLI の root thread は control-plane 専用とし、`implementation-worker` / `test-runner` / `pr-reviewer` / `post-merge-cleanup-worker` を明示 spawn して data-plane を委譲する
- repo-side deterministic guardrail の canonical evidence は event-derived `SUBAGENT_LAUNCH_LEDGER_V1` とし、worker self-report 単独では spawn evidence とみなさない
- `SUBAGENT_LAUNCH_LEDGER_V1.coverage_scope` は support 済みの `SubagentStart` / `PreToolUse(Bash|apply_patch|Edit|Write)` 観測範囲を明示する。未対応 path の absence を「完全防止」の証拠として主張しない
- project-local `.codex/config.toml` は profile routing の証拠として扱わず、actual runtime contract と launch-ledger evidence を validator 対象にする
- live spawn の runtime verification は `#601` に deferred し、この文書で扱うのは evidence 不足時に fail-closed する repo-side 監査境界のみ

### `review-issue` / `issue-reviewer` の使い分け

| エントリ | 種別 | 呼び出し元 | 役割 |
Expand Down
6 changes: 6 additions & 0 deletions docs/dev/workflow.md
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,12 @@ implementation_triage_profile:
- この判定には DoR 準拠・VC preflight・GitHub native dependency または `Depends on #N` で表現された blocker / dependency の全 close・human escalation 非該当の確認を含む(詳細は `issue-contract-review` skill 参照)
- `state/needs-human` 等の human escalation 条件が残っていないこと

### Codex custom-agent dispatch guardrail

- Codex CLI では `impl-review-loop` / `post-merge-cleanup` の root thread は control-plane のみを担当し、data-plane 操作は明示 spawn した custom agent に委譲する
- repo-side deterministic guardrail の正本は `.codex/agents/*.toml`、`.codex/hooks.json`、dispatch validator、`SUBAGENT_LAUNCH_LEDGER_V1` fixture 群、`--audit-mode` で監査する generated ledger artifact とする
- live spawn 実証は別スコープの `#601` に deferred し、本 workflow では evidence 不足時に fail-closed する repo-side 監査を成功条件にする

### human_escalation 後の Issue 本文変更と contract review 再実行

`human_escalation` で停止した後、Issue 本文を **1 文字でも変更した場合**は prior contract-review result が stale となる。
Expand Down
207 changes: 191 additions & 16 deletions scripts/check-codex-agents.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const agentsDir = path.join(repoRoot, '.codex', 'agents');
const configPath = path.join(repoRoot, '.codex', 'config.toml');
const hooksPath = path.join(repoRoot, '.codex', 'hooks.json');
const rulesPath = path.join(repoRoot, '.codex', 'rules', 'default.rules');
const ledgerPath = path.join(repoRoot, 'artifacts', 'codex', 'subagent-launch-ledger.json');

// CODEX_BIN env override for environments without codex on PATH
const CODEX_BIN = process.env.CODEX_BIN ?? 'codex';
Expand Down Expand Up @@ -72,6 +73,16 @@ const writeAgents = new Set([
'review-issue',
]);

const supportedPreToolNames = ['Bash', 'apply_patch', 'Edit', 'Write'];
const prohibitedRootActionKinds = new Set([
'file_edit',
'test_execution',
'git_commit',
'git_push',
'review_judgment',
'cleanup_git_mutation',
]);

function readText(filePath) {
return fs.readFileSync(filePath, 'utf8');
}
Expand Down Expand Up @@ -245,6 +256,44 @@ function validateHooksJson(hooksPath, failures) {
assert(Array.isArray(parsed?.hooks?.SubagentStart), 'hooks.json: must have hooks.SubagentStart array', failures);
assert(Array.isArray(parsed?.hooks?.PreToolUse), 'hooks.json: must have hooks.PreToolUse array', failures);

const subagentEntries = parsed?.hooks?.SubagentStart ?? [];
assert(subagentEntries.length === 1, 'hooks.json: SubagentStart must have exactly one entry', failures);
if (subagentEntries.length === 1) {
assert(subagentEntries[0]?.matcher === '.*', 'hooks.json: SubagentStart matcher must be .*', failures);
const subagentHooks = subagentEntries[0]?.hooks ?? [];
assert(subagentHooks.length === 1, 'hooks.json: SubagentStart must have exactly one command hook', failures);
assert(
subagentHooks[0]?.command?.includes('--hook-subagent-start'),
'hooks.json: SubagentStart command must include --hook-subagent-start',
failures,
);
}

const preToolEntries = parsed?.hooks?.PreToolUse ?? [];
const expectedMatchers = new Map([
['^Bash$', 'Checking LOOP_PROTOCOL Bash guardrail'],
['^(apply_patch|Edit|Write)$', 'Checking LOOP_PROTOCOL patch guardrail'],
]);
for (const [matcher, expectedStatusMessage] of expectedMatchers) {
const entry = preToolEntries.find((candidate) => candidate?.matcher === matcher);
assert(Boolean(entry), `hooks.json: missing PreToolUse matcher ${matcher}`, failures);
if (!entry) {
continue;
}
const hooks = entry?.hooks ?? [];
assert(hooks.length === 1, `hooks.json: matcher ${matcher} must have exactly one hook`, failures);
assert(
hooks[0]?.command?.includes('--hook-pretool'),
`hooks.json: matcher ${matcher} command must include --hook-pretool`,
failures,
);
assert(
hooks[0]?.statusMessage === expectedStatusMessage,
`hooks.json: matcher ${matcher} statusMessage must be ${expectedStatusMessage}`,
failures,
);
}

const allHookCommands = [];
for (const eventKey of ['SubagentStart', 'PreToolUse']) {
const entries = parsed?.hooks?.[eventKey] ?? [];
Expand Down Expand Up @@ -274,22 +323,6 @@ function validateHooksJson(hooksPath, failures) {
'hooks.json: hook command must invoke validator through rtk pnpm exec node',
failures,
);

// Structural check: PreToolUse must have an entry matching apply_patch|Edit|Write
const preToolMatchers = (parsed?.hooks?.PreToolUse ?? []).map((e) => e?.matcher ?? '');
assert(
preToolMatchers.some((m) => m.includes('apply_patch') || m.includes('Edit') || m.includes('Write')),
'hooks.json: PreToolUse must have a matcher covering apply_patch, Edit, and Write tools',
failures,
);

// Structural check: SubagentStart must have at least one catch-all or broad matcher
const subagentMatchers = (parsed?.hooks?.SubagentStart ?? []).map((e) => e?.matcher ?? '');
assert(
subagentMatchers.length > 0,
'hooks.json: SubagentStart must have at least one hook entry',
failures,
);
}

// ---------------------------------------------------------------------------
Expand Down Expand Up @@ -473,6 +506,143 @@ function parseHookInput() {
}
}

function ensureLedgerDirectory() {
fs.mkdirSync(path.dirname(ledgerPath), { recursive: true });
}

function defaultCoverageScope() {
return {
subagent_start_event_recorded: true,
supported_pretooluse_paths: supportedPreToolNames,
unsupported_paths_fail_closed: true,
scope_note: 'This ledger records event-derived SubagentStart launches and supported PreToolUse paths only.',
};
}

function loadLedger() {
if (!fs.existsSync(ledgerPath)) {
return {
ledger_schema: 'SUBAGENT_LAUNCH_LEDGER_V1',
generated_by: 'codex_hook_pipeline',
generated_at: new Date().toISOString(),
ledger_path: path.relative(repoRoot, ledgerPath),
codex_binary_status: 'available',
coverage_scope: defaultCoverageScope(),
launches: [],
root_thread_actions: [],
};
}
try {
return JSON.parse(readText(ledgerPath));
} catch {
return {
ledger_schema: 'SUBAGENT_LAUNCH_LEDGER_V1',
generated_by: 'codex_hook_pipeline',
generated_at: new Date().toISOString(),
ledger_path: path.relative(repoRoot, ledgerPath),
codex_binary_status: 'available',
coverage_scope: defaultCoverageScope(),
launches: [],
root_thread_actions: [],
};
}
}

function saveLedger(ledger) {
ensureLedgerDirectory();
ledger.generated_at = new Date().toISOString();
ledger.ledger_path = path.relative(repoRoot, ledgerPath);
fs.writeFileSync(ledgerPath, `${JSON.stringify(ledger, null, 2)}\n`, 'utf8');
}

function getAgentRuntime(agentName) {
const filePath = path.join(agentsDir, `${agentName}.toml`);
if (!fs.existsSync(filePath)) {
return null;
}
const parsed = parseTomlFile(filePath);
return {
model: parsed.model,
reasoning_effort: parsed.model_reasoning_effort,
default_permissions: parsed.default_permissions,
};
}

function buildEventFingerprint(payload, fallback) {
return [
payload?.session_id,
payload?.agent_id,
payload?.tool_use_id,
payload?.tool_name,
payload?.cwd,
fallback,
].filter(Boolean).join(':');
}

function classifyRootThreadAction(toolName, command) {
if (toolName === 'Bash') {
if (/\b(uv|pytest|pnpm\s+(test|lint|build|typecheck))\b/.test(command)) {
return 'test_execution';
}
if (/\brtk\s+gh\s+pr\s+review\b/.test(command)) {
return 'review_judgment';
}
if (/\brtk\s+git\s+commit\b/.test(command)) {
return 'git_commit';
}
if (/\brtk\s+git\s+push\b/.test(command)) {
return 'git_push';
}
if (/\brtk\s+git\s+branch\s+-D\b|\brtk\s+git\s+worktree\s+remove\b/.test(command)) {
return 'cleanup_git_mutation';
}
return 'bash_observed';
}
if (toolName === 'apply_patch' || toolName === 'Edit' || toolName === 'Write') {
return 'file_edit';
}
return 'unsupported_tool_path';
}

function appendLaunchEvidence(payload) {
const agentType = payload.agent_type ?? payload.subagent_type ?? 'unknown-agent';
const runtime = getAgentRuntime(agentType);
if (!runtime) {
return;
}
const fingerprint = buildEventFingerprint(payload, `SubagentStart:${agentType}`);
const ledger = loadLedger();
const alreadyPresent = ledger.launches.some((launch) => launch.event_fingerprint === fingerprint);
if (!alreadyPresent) {
ledger.launches.push({
agent_name: agentType,
event_type: 'SubagentStart',
evidence_source: 'event_derived',
event_fingerprint: fingerprint,
runtime,
});
}
saveLedger(ledger);
}

function appendPreToolEvidence(payload, toolName, command) {
const ledger = loadLedger();
const observedCommand = command || payload?.tool_input?.file_path || payload?.tool_input?.command || '';
const action = {
kind: classifyRootThreadAction(toolName, command),
command: observedCommand,
tool_name: toolName,
coverage_source: 'supported_pretooluse_path',
};
const duplicate = ledger.root_thread_actions.some(
(entry) => entry.tool_name === action.tool_name && entry.command === action.command,
);
if (!duplicate) {
ledger.root_thread_actions.push(action);
}
saveLedger(ledger);
}

function hookDeny(reason) {
process.stdout.write(JSON.stringify({
hookSpecificOutput: {
Expand Down Expand Up @@ -638,6 +808,10 @@ function runPreToolHook() {
const allowedPaths = parseAllowedPaths();
let reason = null;

if (supportedPreToolNames.includes(toolName)) {
appendPreToolEvidence(payload, toolName, command);
}

if (toolName === 'Bash') {
reason = denyForBash(command);
} else if (toolName === 'apply_patch' || toolName === 'Edit' || toolName === 'Write') {
Expand All @@ -652,6 +826,7 @@ function runPreToolHook() {
function runSubagentStartHook() {
const payload = parseHookInput();
const agentType = payload.agent_type ?? 'unknown-agent';
appendLaunchEvidence(payload);
const isReadOnly = readOnlyAgents.has(agentType);
const additionalContext = [
`Agent ${agentType}: keep main-thread context budget low and return structured output only.`,
Expand Down
Loading
Loading