@doingdev/opencode-claude-manager-plugin 0.1.60 → 0.1.61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/README.md +4 -3
  2. package/dist/claude/claude-agent-sdk-adapter.d.ts +3 -1
  3. package/dist/claude/claude-agent-sdk-adapter.js +57 -6
  4. package/dist/manager/team-orchestrator.js +10 -4
  5. package/dist/plugin/agents/common.d.ts +2 -2
  6. package/dist/plugin/agents/common.js +0 -2
  7. package/dist/plugin/agents/team-planner.js +1 -1
  8. package/dist/plugin/claude-manager.plugin.js +14 -43
  9. package/dist/plugin/service-factory.d.ts +1 -0
  10. package/dist/plugin/service-factory.js +3 -1
  11. package/dist/prompts/registry.js +30 -30
  12. package/dist/src/claude/claude-agent-sdk-adapter.d.ts +3 -1
  13. package/dist/src/claude/claude-agent-sdk-adapter.js +57 -6
  14. package/dist/src/manager/team-orchestrator.js +10 -4
  15. package/dist/src/plugin/agents/common.d.ts +2 -2
  16. package/dist/src/plugin/agents/common.js +0 -2
  17. package/dist/src/plugin/agents/team-planner.js +1 -1
  18. package/dist/src/plugin/claude-manager.plugin.js +14 -43
  19. package/dist/src/plugin/service-factory.d.ts +1 -0
  20. package/dist/src/plugin/service-factory.js +3 -1
  21. package/dist/src/prompts/registry.js +30 -30
  22. package/dist/src/types/contracts.d.ts +3 -3
  23. package/dist/src/util/fs-helpers.d.ts +6 -0
  24. package/dist/src/util/fs-helpers.js +11 -0
  25. package/dist/test/claude-agent-sdk-adapter.test.js +118 -1
  26. package/dist/test/claude-manager.plugin.test.js +23 -150
  27. package/dist/test/fs-helpers.test.d.ts +1 -0
  28. package/dist/test/fs-helpers.test.js +56 -0
  29. package/dist/test/prompt-registry.test.js +24 -28
  30. package/dist/test/team-orchestrator.test.js +18 -0
  31. package/dist/types/contracts.d.ts +3 -3
  32. package/dist/util/fs-helpers.d.ts +6 -0
  33. package/dist/util/fs-helpers.js +11 -0
  34. package/package.json +1 -1
@@ -15,8 +15,6 @@ export const ENGINEER_AGENT_NAMES = PLANNER_ELIGIBLE_ENGINEERS;
15
15
  export const CTO_ONLY_TOOL_IDS = [
16
16
  'team_status',
17
17
  'reset_engineer',
18
- 'confirm_plan',
19
- 'advance_slice',
20
18
  'list_transcripts',
21
19
  'list_history',
22
20
  'git_diff',
@@ -13,7 +13,7 @@ function buildTeamPlannerPermissions() {
13
13
  }
14
14
  export function buildTeamPlannerAgentConfig(prompts) {
15
15
  return {
16
- description: 'Runs dual-engineer planning by calling plan_with_team. Automatically selects two non-overlapping available engineers if engineer names are not provided.',
16
+ description: 'Thin planning wrapper that calls plan_with_team for dual-engineer synthesis with live UI activity.',
17
17
  mode: 'subagent',
18
18
  hidden: false,
19
19
  color: '#D97757',
@@ -1,5 +1,6 @@
1
1
  import { tool } from '@opencode-ai/plugin';
2
2
  import { managerPromptRegistry } from '../prompts/registry.js';
3
+ import { appendDebugLog } from '../util/fs-helpers.js';
3
4
  import { isEngineerName } from '../team/roster.js';
4
5
  import { TeamOrchestrator, createActionableError, getFailureGuidanceText, } from '../manager/team-orchestrator.js';
5
6
  import { AGENT_BROWSER_QA, AGENT_CTO, AGENT_TEAM_PLANNER, buildBrowserQaAgentConfig, buildCtoAgentConfig, buildEngineerAgentConfig, buildTeamPlannerAgentConfig, denyRestrictedToolsGlobally, ENGINEER_AGENT_IDS, ENGINEER_AGENT_NAMES, } from './agents/index.js';
@@ -206,49 +207,6 @@ export const ClaudeManagerPlugin = async ({ worktree, client }) => {
206
207
  }, null, 2);
207
208
  },
208
209
  }),
209
- confirm_plan: tool({
210
- description: 'Persist plan confirmation and optional slice metadata after the user confirms a plan. For large tasks, provide a slice list to enable per-slice progress tracking. Set preAuthorized to true only when the user has explicitly said to proceed through all slices without further confirmation.',
211
- args: {
212
- summary: tool.schema.string().min(1),
213
- taskSize: tool.schema.enum(['trivial', 'simple', 'large']),
214
- slices: tool.schema.string().array().optional(),
215
- preAuthorized: tool.schema.boolean().optional(),
216
- },
217
- async execute(args, context) {
218
- const teamId = context.sessionID;
219
- annotateToolRun(context, 'Persisting confirmed plan', {
220
- teamId,
221
- taskSize: args.taskSize,
222
- sliceCount: args.slices?.length ?? 0,
223
- });
224
- const activePlan = await services.orchestrator.setActivePlan(context.worktree, teamId, {
225
- summary: args.summary,
226
- taskSize: args.taskSize,
227
- slices: args.slices ?? [],
228
- preAuthorized: args.preAuthorized ?? false,
229
- });
230
- return JSON.stringify(activePlan, null, 2);
231
- },
232
- }),
233
- advance_slice: tool({
234
- description: 'Mark a plan slice as done (or skipped) and advance to the next one. Use this after each slice completes to track large-task progress.',
235
- args: {
236
- sliceIndex: tool.schema.number(),
237
- status: tool.schema.enum(['done', 'skipped']).optional(),
238
- },
239
- async execute(args, context) {
240
- const teamId = context.sessionID;
241
- const status = args.status ?? 'done';
242
- annotateToolRun(context, `Advancing slice ${args.sliceIndex} → ${status}`, {
243
- teamId,
244
- sliceIndex: args.sliceIndex,
245
- status,
246
- });
247
- await services.orchestrator.updateActivePlanSlice(context.worktree, teamId, args.sliceIndex, status);
248
- const team = await services.orchestrator.getOrCreateTeam(context.worktree, teamId);
249
- return JSON.stringify({ activePlan: team.activePlan ?? null }, null, 2);
250
- },
251
- }),
252
210
  reset_engineer: tool({
253
211
  description: 'Reset a stuck or corrupted engineer. Clears the busy flag. Optionally clears the Claude session (starts fresh) and/or wrapper history.',
254
212
  args: {
@@ -499,6 +457,19 @@ async function runEngineerAssignment(input, context) {
499
457
  guidance,
500
458
  },
501
459
  });
460
+ try {
461
+ await appendDebugLog(services.debugLogPath, {
462
+ type: 'engineer_failure',
463
+ engineer: failure.engineer,
464
+ teamId: failure.teamId,
465
+ mode: failure.mode,
466
+ failureKind: failure.failureKind,
467
+ message: failure.message.slice(0, 300),
468
+ });
469
+ }
470
+ catch {
471
+ // Log write failures must not mask the original error.
472
+ }
502
473
  throw createActionableError(failure, error);
503
474
  }
504
475
  await services.orchestrator.recordWrapperExchange(context.worktree, input.teamId, input.engineer, context.sessionID, input.mode, input.message, result.finalText);
@@ -11,6 +11,7 @@ interface ClaudeManagerPluginServices {
11
11
  teamStore: TeamStateStore;
12
12
  orchestrator: TeamOrchestrator;
13
13
  workerCapabilities: Partial<Record<EngineerName, WorkerCapabilities>>;
14
+ debugLogPath: string;
14
15
  }
15
16
  export declare function getOrCreatePluginServices(worktree: string): ClaudeManagerPluginServices;
16
17
  export declare function clearPluginServices(): void;
@@ -21,8 +21,9 @@ export function getOrCreatePluginServices(worktree) {
21
21
  return existing;
22
22
  }
23
23
  const approvalPolicyPath = path.join(worktree, '.claude-manager', 'approval-policy.json');
24
+ const debugLogPath = path.join(worktree, '.claude-manager', 'debug.log');
24
25
  const approvalManager = new ToolApprovalManager(undefined, undefined, approvalPolicyPath);
25
- const sdkAdapter = new ClaudeAgentSdkAdapter(undefined, approvalManager);
26
+ const sdkAdapter = new ClaudeAgentSdkAdapter(undefined, approvalManager, debugLogPath);
26
27
  const sessionService = new ClaudeSessionService(sdkAdapter);
27
28
  const gitOps = new GitOperations(worktree);
28
29
  const teamStore = new TeamStateStore();
@@ -37,6 +38,7 @@ export function getOrCreatePluginServices(worktree) {
37
38
  teamStore,
38
39
  orchestrator,
39
40
  workerCapabilities,
41
+ debugLogPath,
40
42
  };
41
43
  serviceRegistry.set(worktree, services);
42
44
  return services;
@@ -1,10 +1,11 @@
1
1
  export const managerPromptRegistry = {
2
2
  ctoSystemPrompt: [
3
3
  'You are a principal engineer orchestrating a team of AI-powered engineers.',
4
- 'Your role is to decompose work, delegate precisely, review diffs for production risks, and verify outcomes.',
4
+ 'Your role is to investigate first, delegate precisely, review diffs for production risks, and verify outcomes.',
5
5
  'You do not write code. All edits go through engineers. You multiply output by coordinating parallel work and catching issues others miss.',
6
6
  '',
7
- '# Operating Loop: Orient → ClassifyPlanConfirm → Delegate → Review → Verify → Close',
7
+ '# Operating Loop: Orient → InvestigateDecide → Delegate → Review → Verify → Close',
8
+ 'Treat this loop as adaptive, not rigid. You may revisit earlier steps, skip unnecessary steps, or improvise when the work demands it—as long as you stay explicit about why.',
8
9
  '',
9
10
  '## Orient: Understand the request',
10
11
  '- Extract what you can from the user message, codebase (read/grep/glob/codesearch), prior engineer results, and `websearch`/`webfetch` when relevant.',
@@ -13,38 +14,33 @@ export const managerPromptRegistry = {
13
14
  '- If requirements are vague or architecture is unclear, use `question` tool with 2–3 concrete options, your recommendation, and what breaks if user picks differently.',
14
15
  '- Only ask when the decision will materially change scope, architecture, risk, or how you verify—and you cannot resolve it from context.',
15
16
  '',
16
- '## Classify: Frame the work',
17
+ '## Investigate: Reduce uncertainty before choosing a path',
18
+ '- Start with the smallest useful investigation. For a bug, get to root cause. For a feature, inspect the existing surface area before inventing a plan.',
19
+ '- You may investigate yourself with read-only tools or delegate exploration to one engineer when that is faster or gives better continuity.',
20
+ '- When delegating exploration, explicitly say what artifact you want back: root cause, findings, affected files, options, risk review, file map, or a concrete plan.',
21
+ '- Do not default exploration to planning. Use planning only when the task is genuinely complex, ambiguous, cross-cutting, or risky.',
22
+ '',
23
+ '## Decide: Choose the lightest process that fits the work',
17
24
  '- Is this a bug fix, feature, refactor, or something else?',
18
25
  '- Task size: classify as trivial (single-line fix, unambiguous, no side effects), simple (one focused task, clear scope, 1–2 files), or large (multiple steps, cross-cutting changes, requires vertical slicing).',
19
26
  '- What could go wrong? Is it reversible or irreversible? Can it fail in prod?',
20
27
  '- Does it require careful rollout, data migration, observability, or backwards compatibility handling?',
21
28
  '- Are there decisions the user has not explicitly made (architecture, scope, deployment strategy)?',
22
- '',
23
- '## Plan: Decompose into engineer work',
24
- '- For small, focused tasks: delegate to a named engineer with structured context (goal, acceptance criteria, relevant files, constraints, verification).',
25
- "- For medium or large tasks: use `task(subagent_type: 'team-planner', ...)` for dual-engineer exploration and plan synthesis.",
26
- ' - Team-planner automatically selects two non-overlapping engineers by availability and context; you may optionally specify lead and challenger.',
27
- ' - Challenger engineer identifies missing decisions, risks, and scope gaps before implementation.',
28
- '- For large tasks: break into vertical slices before delegating. Each slice must deliver end-to-end, user-testable value independently (e.g., "user can register and receive a confirmation email", "user can view billing history"). Horizontal layers (e.g., "just types", "just tests") are not vertical slices. Document slices when calling `confirm_plan`.',
29
- '- Break work into independent pieces that can run in parallel. Two engineers exploring then synthesizing beats one engineer doing everything sequentially.',
30
- '- Before delegating, state your success criteria, not just the task. What done looks like. How you will verify it.',
31
- '',
32
- '## Confirm: Get user buy-in before implementing',
33
- '- After planning but before dispatching any engineer in implement mode, present the plan to the user with the `question` tool.',
34
- '- State what will be built or changed, which files or systems are affected, what success looks like, and any risks or open decisions.',
35
- '- If team-planner synthesis surfaced a recommendedQuestion, include it here as part of the confirmation question.',
36
- '- Do not proceed to implementation until the user confirms the plan.',
37
- '- After the user confirms, call `confirm_plan` with a summary, taskSize, and (for large tasks) the slice list. Set preAuthorized: true only if the user explicitly says to proceed through all slices without further confirmation.',
38
- '- For large tasks not preAuthorized: confirm each slice with the user before dispatching it.',
39
- '- Skip `question` only when: the user has explicitly said "proceed" or "just do it", the change is a trivial fix with no ambiguity, or the task is purely exploratory (no edits).',
40
- '- If the user refines or rejects the plan, revise it and re-confirm before implementing.',
29
+ '- For trivial or simple work with clear scope: delegate directly to one engineer.',
30
+ '- For bugs or unclear requests: investigate first, then decide whether implementation is now straightforward.',
31
+ "- For complex or cross-cutting work: use `task(subagent_type: 'team-planner', ...)` so the wrapper can sharpen the request and run `plan_with_team` with live UI activity.",
32
+ '- Ask the user to confirm only when the decision materially changes scope, risk, rollout, or architecture. Do not force confirmation for every non-trivial task.',
41
33
  '',
42
34
  '## Delegate: Send precise assignments',
43
- "- For single-engineer work: use `task(subagent_type: 'tom'|'john'|'maya'|'sara'|'alex', ...)` and structure the prompt with goal, acceptance criteria, relevant files, constraints, and verification.",
44
- "- For dual-engineer planning: use `task(subagent_type: 'team-planner', ...)` which will lead + challenger synthesis.",
35
+ "- For single-engineer work: use `task(subagent_type: 'tom'|'john'|'maya'|'sara'|'alex', ...)` and structure the prompt with goal, mode, expected deliverable, acceptance criteria, relevant context, constraints, and verification.",
36
+ "- For complex planning work: use `task(subagent_type: 'team-planner', ...)`. The wrapper preserves live activity in the UI while it inspects context lightly and runs `plan_with_team`.",
45
37
  "- For browser/UI verification: use `task(subagent_type: 'browser-qa', ...)` with a clear verification goal. BrowserQA uses the Playwright skill to verify in a real browser and can run safe bash when needed.",
46
- '- Each assignment includes: goal, acceptance criteria, relevant context, constraints, and verification method.',
47
- '- For large tasks: after each slice completes, call `advance_slice` to record progress, then confirm the next slice with the user before dispatching (unless preAuthorized).',
38
+ '- For large tasks: break work into genuine vertical slices before implementation. Each slice must deliver end-to-end, user-testable value independently (e.g., "user can register and receive a confirmation email", "user can view billing history"). Horizontal layers (e.g., "just types", "just tests") are not vertical slices.',
39
+ '- Break work into independent pieces that can run in parallel. Two engineers exploring and then synthesizing is often better than one engineer guessing alone.',
40
+ '- Before delegating, state success criteria and expected output shape, not just the task. Say what done looks like and how you will verify it.',
41
+ '- If planning surfaced a recommendedQuestion or the work is risky enough to need confirmation, use the `question` tool before implementation. Otherwise, delegate directly.',
42
+ '',
43
+ '- Each assignment includes: goal, mode, expected deliverable, acceptance criteria, relevant context, constraints, and verification method.',
48
44
  '- Reuse the same engineer when follow-up work builds on their prior context.',
49
45
  '- Only one implementing engineer modifies the worktree at a time. Parallelize exploration, research, and browser verification freely.',
50
46
  '- Context warnings (moderate/high/critical) are informational only. Do NOT reset an engineer session in response to a context warning. Sessions auto-reset only on an actual contextExhausted error.',
@@ -79,6 +75,7 @@ export const managerPromptRegistry = {
79
75
  '',
80
76
  '- Questions: Use the `question` tool when a decision will materially affect scope, architecture, or how you verify the outcome. Name the decision, offer 2–3 concrete options, state your recommendation, and say what breaks if the user picks differently. One high-leverage question at a time.',
81
77
  '- Reframing: Before planning, ask what the user is actually trying to achieve, not just what they asked for. If the request sounds like a feature, ask what job-to-be-done it serves.',
78
+ '- Exploration outputs: when you send an engineer in explore mode, specify the expected output explicitly. Examples: root cause, findings, affected files, options, risk review, or implementation plan.',
82
79
  '- Engineer selection: When assigning to a single engineer, prefer lower context pressure and less-recently-used engineers. Reuse if follow-up work builds on prior context.',
83
80
  '- Context warnings: At moderate/high/critical context levels the system surfaces a warning. These are advisory — do not force session reset. Reserve reset for actual contextExhausted errors only.',
84
81
  '- Failure handling:',
@@ -107,6 +104,7 @@ export const managerPromptRegistry = {
107
104
  '',
108
105
  'Your wrapper context from prior turns is reloaded automatically. Use it to avoid repeating work or re-explaining context that Claude Code already knows.',
109
106
  "Return the tool result directly. Add your own commentary only when something was unexpected or needs the CTO's attention.",
107
+ 'Explore mode is caller-directed. Follow the requested output shape instead of defaulting to a plan. If the assignment does not specify the output, return findings, relevant files, open questions, and the recommended next step.',
110
108
  'If you discover during implementation that the agreed approach is not viable (unexpected constraints, wrong files, missing context), stop immediately and surface the deviation to the CTO before proceeding with a different approach. Do not silently implement something different from what was confirmed.',
111
109
  ].join('\n'),
112
110
  engineerSessionPrompt: [
@@ -117,6 +115,7 @@ export const managerPromptRegistry = {
117
115
  'When investigating bugs:',
118
116
  '- Always explore the root cause before implementing a fix. Do not assume; verify.',
119
117
  '- If three fix attempts fail, question the architecture, not the hypothesis.',
118
+ '- In explore mode, return the artifact the caller asked for. Do not default to a plan unless the caller explicitly asks for one.',
120
119
  '',
121
120
  'When writing code:',
122
121
  '- Consider rollout/migration/observability implications: Will this require staged rollout, data migration, new metrics, or log/trace points?',
@@ -158,14 +157,15 @@ export const managerPromptRegistry = {
158
157
  '<answer or NONE>',
159
158
  ].join('\n'),
160
159
  teamPlannerPrompt: [
161
- 'You are the team planner. Your only job is to invoke `plan_with_team`.',
160
+ 'You are the team-planner wrapper. Your job is to help the CTO get a stronger plan for complex work while preserving live activity in the UI.',
162
161
  '`plan_with_team` dispatches two engineers in parallel (lead + challenger) then synthesizes their plans.',
163
162
  '',
164
- 'Call `plan_with_team` immediately with the task and any engineer names provided.',
163
+ 'Call `plan_with_team` with the task and any engineer names provided.',
165
164
  '- If lead and challenger engineer names are both specified, use them.',
166
165
  '- If either name is missing, `plan_with_team` will auto-select two non-overlapping engineers based on availability and context.',
167
- 'Do not attempt any planning or analysis yourself. Delegate entirely to `plan_with_team`.',
168
- 'After `plan_with_team` returns, pass the full result back to the CTO unchanged. Do not modify, summarize, or act on the synthesis; the CTO will present it to the user for confirmation.',
166
+ '- Keep the wrapper thin. Do not do your own repo investigation or solo planning.',
167
+ '- If the request is blocked by a missing decision, ask one focused question with a recommendation instead of guessing.',
168
+ 'After `plan_with_team` returns, pass the full result back to the CTO unchanged.',
169
169
  ].join('\n'),
170
170
  browserQaAgentPrompt: [
171
171
  "You are the browser QA specialist on the CTO's team.",
@@ -4,9 +4,9 @@ export interface ManagerPromptRegistry {
4
4
  engineerSessionPrompt: string;
5
5
  /** Prompt prepended to the user prompt of the synthesis runTask call inside plan_with_team. */
6
6
  planSynthesisPrompt: string;
7
- /** Visible subagent prompt for teamPlanner — thin bridge that calls plan_with_team. */
7
+ /** Visible subagent prompt for teamPlanner — thin wrapper that calls plan_with_team. */
8
8
  teamPlannerPrompt: string;
9
- /** Visible subagent prompt for browserQa — thin bridge that calls claude tool for browser verification. */
9
+ /** Visible subagent prompt for browserQa — thin wrapper that calls claude tool for browser verification. */
10
10
  browserQaAgentPrompt: string;
11
11
  /** Prompt prepended to browser verification task prompts in Claude Code sessions. */
12
12
  browserQaSessionPrompt: string;
@@ -146,7 +146,7 @@ export interface TeamEngineerRecord {
146
146
  wrapperHistory: WrapperHistoryEntry[];
147
147
  context: SessionContextSnapshot;
148
148
  }
149
- export type EngineerFailureKind = 'sdkError' | 'contextExhausted' | 'toolDenied' | 'aborted' | 'engineerBusy' | 'unknown';
149
+ export type EngineerFailureKind = 'sdkError' | 'contextExhausted' | 'toolDenied' | 'modeNotSupported' | 'aborted' | 'engineerBusy' | 'unknown';
150
150
  export interface EngineerFailureResult {
151
151
  teamId: string;
152
152
  engineer: EngineerName;
@@ -1,2 +1,8 @@
1
1
  export declare function writeJsonAtomically(filePath: string, data: unknown): Promise<void>;
2
2
  export declare function isFileNotFoundError(error: unknown): error is NodeJS.ErrnoException;
3
+ /**
4
+ * Appends a single NDJSON line to a debug log file.
5
+ * Creates the parent directory if it does not exist.
6
+ * A `ts` (ISO timestamp) field is injected automatically.
7
+ */
8
+ export declare function appendDebugLog(logPath: string, entry: Record<string, unknown>): Promise<void>;
@@ -1,5 +1,6 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { promises as fs } from 'node:fs';
3
+ import path from 'node:path';
3
4
  export async function writeJsonAtomically(filePath, data) {
4
5
  const tempPath = `${filePath}.${randomUUID()}.tmp`;
5
6
  await fs.writeFile(tempPath, `${JSON.stringify(data, null, 2)}\n`, 'utf8');
@@ -8,3 +9,13 @@ export async function writeJsonAtomically(filePath, data) {
8
9
  export function isFileNotFoundError(error) {
9
10
  return (error instanceof Error && 'code' in error && error.code === 'ENOENT');
10
11
  }
12
+ /**
13
+ * Appends a single NDJSON line to a debug log file.
14
+ * Creates the parent directory if it does not exist.
15
+ * A `ts` (ISO timestamp) field is injected automatically.
16
+ */
17
+ export async function appendDebugLog(logPath, entry) {
18
+ const line = JSON.stringify({ ...entry, ts: new Date().toISOString() }) + '\n';
19
+ await fs.mkdir(path.dirname(logPath), { recursive: true });
20
+ await fs.appendFile(logPath, line, 'utf8');
21
+ }
@@ -1,5 +1,9 @@
1
- import { describe, expect, it } from 'vitest';
1
+ import { afterEach, describe, expect, it } from 'vitest';
2
+ import { mkdtemp, readFile, rm } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { tmpdir } from 'node:os';
2
5
  import { ClaudeAgentSdkAdapter } from '../src/claude/claude-agent-sdk-adapter.js';
6
+ import { ToolApprovalManager } from '../src/claude/tool-approval-manager.js';
3
7
  function createFakeQuery(messages) {
4
8
  return {
5
9
  async *[Symbol.asyncIterator]() {
@@ -548,4 +552,117 @@ describe('ClaudeAgentSdkAdapter', () => {
548
552
  });
549
553
  expect(capturedPermissionMode).toBe('plan');
550
554
  });
555
+ describe('debug log', () => {
556
+ let tmpDir;
557
+ afterEach(async () => {
558
+ if (tmpDir) {
559
+ await rm(tmpDir, { recursive: true, force: true });
560
+ }
561
+ });
562
+ it('appends a tool_denied entry when restrictWriteTools denies a write tool', async () => {
563
+ tmpDir = await mkdtemp(join(tmpdir(), 'adapter-log-'));
564
+ const logPath = join(tmpDir, '.claude-manager', 'debug.log');
565
+ let capturedCanUseTool;
566
+ const adapter = new ClaudeAgentSdkAdapter({
567
+ query: (params) => {
568
+ capturedCanUseTool = params.options?.canUseTool;
569
+ return createFakeQuery([
570
+ {
571
+ type: 'result',
572
+ subtype: 'success',
573
+ session_id: 'ses_log',
574
+ is_error: false,
575
+ result: 'ok',
576
+ num_turns: 1,
577
+ total_cost_usd: 0,
578
+ },
579
+ ]);
580
+ },
581
+ listSessions: async () => [],
582
+ getSessionMessages: async () => [],
583
+ }, undefined, logPath);
584
+ await adapter.runSession({ cwd: '/tmp/project', prompt: 'Test', restrictWriteTools: true });
585
+ expect(capturedCanUseTool).toBeDefined();
586
+ const result = await capturedCanUseTool('Edit', { file_path: 'x.ts' }, {});
587
+ expect(result.behavior).toBe('deny');
588
+ const content = await readFile(logPath, 'utf8');
589
+ const entry = JSON.parse(content.trim().split('\n')[0]);
590
+ expect(entry.type).toBe('tool_denied');
591
+ expect(entry.toolName).toBe('Edit');
592
+ expect(entry.reason).toBe('restrictWriteTools');
593
+ expect(typeof entry.ts).toBe('string');
594
+ });
595
+ it('appends a tool_denied entry when the approval manager denies a tool', async () => {
596
+ tmpDir = await mkdtemp(join(tmpdir(), 'adapter-log-policy-'));
597
+ const logPath = join(tmpDir, '.claude-manager', 'debug.log');
598
+ const approvalManager = new ToolApprovalManager({
599
+ rules: [
600
+ {
601
+ id: 'deny-bash',
602
+ toolPattern: 'Bash',
603
+ inputPattern: 'rm -rf /',
604
+ action: 'deny',
605
+ denyMessage: 'rm -rf / is not allowed',
606
+ },
607
+ ],
608
+ enabled: true,
609
+ });
610
+ let capturedCanUseTool;
611
+ const adapter = new ClaudeAgentSdkAdapter({
612
+ query: (params) => {
613
+ capturedCanUseTool = params.options?.canUseTool;
614
+ return createFakeQuery([
615
+ {
616
+ type: 'result',
617
+ subtype: 'success',
618
+ session_id: 'ses_policy',
619
+ is_error: false,
620
+ result: 'ok',
621
+ num_turns: 1,
622
+ total_cost_usd: 0,
623
+ },
624
+ ]);
625
+ },
626
+ listSessions: async () => [],
627
+ getSessionMessages: async () => [],
628
+ }, approvalManager, logPath);
629
+ await adapter.runSession({ cwd: '/tmp/project', prompt: 'Test' });
630
+ expect(capturedCanUseTool).toBeDefined();
631
+ const result = await capturedCanUseTool('Bash', { command: 'rm -rf /' }, {});
632
+ expect(result.behavior).toBe('deny');
633
+ const content = await readFile(logPath, 'utf8');
634
+ const entry = JSON.parse(content.trim().split('\n')[0]);
635
+ expect(entry.type).toBe('tool_denied');
636
+ expect(entry.toolName).toBe('Bash');
637
+ expect(entry.reason).toBe('approvalPolicy');
638
+ expect(typeof entry.ts).toBe('string');
639
+ });
640
+ it('does not create a log file when no debugLogPath is provided', async () => {
641
+ tmpDir = await mkdtemp(join(tmpdir(), 'adapter-no-log-'));
642
+ let capturedCanUseTool;
643
+ const adapter = new ClaudeAgentSdkAdapter({
644
+ query: (params) => {
645
+ capturedCanUseTool = params.options?.canUseTool;
646
+ return createFakeQuery([
647
+ {
648
+ type: 'result',
649
+ subtype: 'success',
650
+ session_id: 'ses_nolog',
651
+ is_error: false,
652
+ result: 'ok',
653
+ num_turns: 1,
654
+ total_cost_usd: 0,
655
+ },
656
+ ]);
657
+ },
658
+ listSessions: async () => [],
659
+ getSessionMessages: async () => [],
660
+ });
661
+ await adapter.runSession({ cwd: '/tmp/project', prompt: 'Test', restrictWriteTools: true });
662
+ const result = await capturedCanUseTool('Edit', { file_path: 'x.ts' }, {});
663
+ expect(result.behavior).toBe('deny');
664
+ // No log file should exist
665
+ await expect(readFile(join(tmpDir, 'debug.log'), 'utf8')).rejects.toThrow();
666
+ });
667
+ });
551
668
  });