claude-coder 1.7.1 → 1.8.1

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 (58) hide show
  1. package/README.md +80 -46
  2. package/bin/cli.js +41 -43
  3. package/package.json +7 -2
  4. package/src/{auth.js → commands/auth.js} +41 -46
  5. package/src/commands/setup-modules/helpers.js +99 -0
  6. package/src/commands/setup-modules/index.js +26 -0
  7. package/src/commands/setup-modules/mcp.js +95 -0
  8. package/src/commands/setup-modules/provider.js +261 -0
  9. package/src/commands/setup-modules/safety.js +62 -0
  10. package/src/commands/setup-modules/simplify.js +53 -0
  11. package/src/commands/setup.js +172 -0
  12. package/src/common/assets.js +206 -0
  13. package/src/{config.js → common/config.js} +17 -93
  14. package/src/common/constants.js +56 -0
  15. package/src/{indicator.js → common/indicator.js} +45 -56
  16. package/src/common/interaction.js +170 -0
  17. package/src/common/logging.js +78 -0
  18. package/src/common/sdk.js +51 -0
  19. package/src/common/tasks.js +88 -0
  20. package/src/common/utils.js +162 -0
  21. package/src/core/coding.js +55 -0
  22. package/src/core/context.js +117 -0
  23. package/src/core/harness.js +484 -0
  24. package/src/core/hooks.js +533 -0
  25. package/src/{init.js → core/init.js} +31 -12
  26. package/src/core/plan.js +325 -0
  27. package/src/core/prompts.js +226 -0
  28. package/src/core/query.js +50 -0
  29. package/src/core/repair.js +46 -0
  30. package/src/core/runner.js +195 -0
  31. package/src/core/scan.js +89 -0
  32. package/src/core/session.js +57 -0
  33. package/src/core/simplify.js +52 -0
  34. package/templates/bash-process.md +12 -0
  35. package/templates/codingSystem.md +65 -0
  36. package/templates/codingUser.md +17 -0
  37. package/templates/coreProtocol.md +29 -0
  38. package/templates/guidance.json +35 -0
  39. package/templates/planSystem.md +78 -0
  40. package/templates/planUser.md +9 -0
  41. package/templates/playwright.md +17 -0
  42. package/templates/requirements.example.md +4 -3
  43. package/templates/scanSystem.md +120 -0
  44. package/templates/scanUser.md +10 -0
  45. package/prompts/ADD_GUIDE.md +0 -98
  46. package/prompts/CLAUDE.md +0 -199
  47. package/prompts/SCAN_PROTOCOL.md +0 -118
  48. package/prompts/add_user.md +0 -24
  49. package/prompts/coding_user.md +0 -31
  50. package/prompts/scan_user.md +0 -17
  51. package/src/hooks.js +0 -166
  52. package/src/prompts.js +0 -295
  53. package/src/runner.js +0 -396
  54. package/src/scanner.js +0 -62
  55. package/src/session.js +0 -354
  56. package/src/setup.js +0 -579
  57. package/src/tasks.js +0 -172
  58. package/src/validator.js +0 -181
@@ -0,0 +1,325 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const os = require('os');
6
+ const readline = require('readline');
7
+ const { runSession } = require('./session');
8
+ const { buildQueryOptions } = require('./query');
9
+ const { buildSystemPrompt, buildPlanPrompt } = require('./prompts');
10
+ const { log, loadConfig } = require('../common/config');
11
+ const { assets } = require('../common/assets');
12
+ const { extractResultText } = require('../common/logging');
13
+ const { printStats } = require('../common/tasks');
14
+ const { syncAfterPlan } = require('./harness');
15
+
16
+ const EXIT_TIMEOUT_MS = 300000;
17
+ const PLANS_DIR = path.join(os.homedir(), '.claude', 'plans');
18
+
19
+ function buildPlanOnlyPrompt(instruction, opts = {}) {
20
+ const interactive = opts.interactive || false;
21
+ const reqFile = opts.reqFile || null;
22
+
23
+ const inputSection = reqFile
24
+ ? `需求文件路径: ${reqFile}\n先读取该文件,理解用户需求和约束。`
25
+ : `用户需求:\n${instruction}`;
26
+
27
+ const interactionRule = interactive
28
+ ? '如有不确定的关键决策点,向用户提问对话确认方案。'
29
+ : '不要提问,默认使用最佳推荐方案。';
30
+
31
+ return `你是一个资深技术架构师。根据以下需求,探索项目代码库后输出完整的技术方案文档。
32
+
33
+ ${inputSection}
34
+
35
+ 【流程】
36
+ 1. 探索项目代码库,理解结构和技术栈
37
+ 2. ${interactionRule}
38
+ 3. 使用 Write 工具将完整计划写入 ~/.claude/plans/ 目录(.md 格式)
39
+ 4. 写入后输出标记(独占一行):PLAN_FILE_PATH: <计划文件绝对路径>
40
+ 5. 简要总结计划要点
41
+ `;
42
+ }
43
+
44
+ /**
45
+ * 从文本中提取计划文件路径
46
+ * 优先级:PLAN_FILE_PATH 标记 > .claude/plans/*.md > 反引号包裹 .md > 任意绝对 .md
47
+ */
48
+ function extractPlanPath(text) {
49
+ if (!text) return null;
50
+
51
+ const tagMatch = text.match(/PLAN_FILE_PATH:\s*(\S+\.md)/);
52
+ if (tagMatch) return tagMatch[1];
53
+
54
+ const plansMatch = text.match(/([^\s`'"(]*\.claude\/plans\/[^\s`'"()]+\.md)/);
55
+ if (plansMatch) return plansMatch[1];
56
+
57
+ const backtickMatch = text.match(/`([^`]+\.md)`/);
58
+ if (backtickMatch) return backtickMatch[1];
59
+
60
+ const absMatch = text.match(/(\/[^\s`'"]+\.md)/);
61
+ if (absMatch) return absMatch[1];
62
+
63
+ return null;
64
+ }
65
+
66
+ /**
67
+ * 多源提取计划路径(按可靠性从高到低)
68
+ * 1. Write 工具调用参数(最可靠)
69
+ * 2. assistant 消息流文本
70
+ * 3. result.result 文本
71
+ * 4. plans 目录最新文件(兜底)
72
+ */
73
+ function extractPlanPathFromCollected(collected, startTime) {
74
+ // 第一层:从 Write 工具调用参数中直接获取
75
+ for (const msg of collected) {
76
+ if (msg.type !== 'assistant' || !msg.message?.content) continue;
77
+ for (const block of msg.message.content) {
78
+ if (block.type === 'tool_use' && block.name === 'Write') {
79
+ const target = block.input?.file_path || block.input?.path || '';
80
+ if (target.includes('.claude/plans/') && target.endsWith('.md')) {
81
+ if (fs.existsSync(target)) return target;
82
+ }
83
+ }
84
+ }
85
+ }
86
+
87
+ // 第二层:从所有 assistant 文本中提取
88
+ let fullText = '';
89
+ for (const msg of collected) {
90
+ if (msg.type === 'assistant' && msg.message?.content) {
91
+ for (const block of msg.message.content) {
92
+ if (block.type === 'text' && block.text) fullText += block.text;
93
+ }
94
+ }
95
+ }
96
+ if (fullText) {
97
+ const p = extractPlanPath(fullText);
98
+ if (p && fs.existsSync(p)) return p;
99
+ }
100
+
101
+ // 第三层:从 result.result 中提取
102
+ const resultText = extractResultText(collected);
103
+ if (resultText) {
104
+ const p = extractPlanPath(resultText);
105
+ if (p && fs.existsSync(p)) return p;
106
+ }
107
+
108
+ // 第四层:扫描 plans 目录,找 session 期间新建的文件
109
+ if (fs.existsSync(PLANS_DIR)) {
110
+ try {
111
+ const files = fs.readdirSync(PLANS_DIR)
112
+ .filter(f => f.endsWith('.md'))
113
+ .map(f => {
114
+ const fp = path.join(PLANS_DIR, f);
115
+ return { path: fp, mtime: fs.statSync(fp).mtimeMs };
116
+ })
117
+ .filter(f => f.mtime >= startTime)
118
+ .sort((a, b) => b.mtime - a.mtime);
119
+ if (files.length > 0) {
120
+ log('info', `从 plans 目录发现新文件: ${path.basename(files[0].path)}`);
121
+ return files[0].path;
122
+ }
123
+ } catch { /* ignore */ }
124
+ }
125
+
126
+ return null;
127
+ }
128
+
129
+ function copyPlanToProject(generatedPath) {
130
+ const filename = path.basename(generatedPath);
131
+ const targetDir = path.join(assets.projectRoot, '.claude-coder', 'plan');
132
+ const targetPath = path.join(targetDir, filename);
133
+
134
+ try {
135
+ if (!fs.existsSync(targetDir)) {
136
+ fs.mkdirSync(targetDir, { recursive: true });
137
+ }
138
+ fs.copyFileSync(generatedPath, targetPath);
139
+ return targetPath;
140
+ } catch {
141
+ return generatedPath;
142
+ }
143
+ }
144
+
145
+ async function _executePlanGen(sdk, ctx, instruction, opts = {}) {
146
+ const prompt = buildPlanOnlyPrompt(instruction, opts);
147
+ const queryOpts = {
148
+ permissionMode: 'plan',
149
+ cwd: opts.projectRoot || assets.projectRoot,
150
+ hooks: ctx.hooks,
151
+ };
152
+ if (!opts.interactive) {
153
+ queryOpts.disallowedTools = ['askUserQuestion'];
154
+ }
155
+ if (opts.model) queryOpts.model = opts.model;
156
+
157
+ const startTime = Date.now();
158
+ let exitPlanModeDetected = false;
159
+ let exitPlanModeTime = null;
160
+
161
+ const collected = [];
162
+ const session = sdk.query({ prompt, options: queryOpts });
163
+
164
+ for await (const msg of session) {
165
+ if (ctx._isStalled && ctx._isStalled()) {
166
+ log('warn', '停顿超时,中断 plan 生成');
167
+ break;
168
+ }
169
+
170
+ if (exitPlanModeDetected && exitPlanModeTime) {
171
+ const elapsed = Date.now() - exitPlanModeTime;
172
+ if (elapsed > EXIT_TIMEOUT_MS && msg.type !== 'result') {
173
+ log('warn', '检测到 ExitPlanMode,等待审批超时,尝试从已收集消息中提取路径');
174
+ break;
175
+ }
176
+ }
177
+
178
+ collected.push(msg);
179
+ ctx._logMessage(msg);
180
+
181
+ if (msg.type === 'assistant' && msg.message?.content) {
182
+ for (const block of msg.message.content) {
183
+ if (block.type === 'tool_use' && block.name === 'ExitPlanMode') {
184
+ exitPlanModeDetected = true;
185
+ exitPlanModeTime = Date.now();
186
+ }
187
+ }
188
+ }
189
+ }
190
+
191
+ const planPath = extractPlanPathFromCollected(collected, startTime);
192
+
193
+ if (planPath) {
194
+ const targetPath = copyPlanToProject(planPath);
195
+ return { success: true, targetPath, generatedPath: planPath };
196
+ }
197
+
198
+ log('warn', '无法从输出中提取计划路径');
199
+ log('info', `请手动查看: ${PLANS_DIR}`);
200
+ return { success: false, reason: 'no_path', targetPath: null };
201
+ }
202
+
203
+ async function runPlanSession(instruction, opts = {}) {
204
+ const planOnly = opts.planOnly || false;
205
+ const interactive = opts.interactive || false;
206
+ const ts = new Date().toISOString().replace(/[-:T]/g, '').slice(0, 12);
207
+ const label = planOnly ? 'plan_only' : 'plan_tasks';
208
+ const hookType = interactive ? 'plan_interactive' : 'plan';
209
+
210
+ return runSession(hookType, {
211
+ opts,
212
+ sessionNum: 0,
213
+ logFileName: `plan_${ts}.log`,
214
+ label,
215
+
216
+ async execute(sdk, ctx) {
217
+ log('info', '正在生成计划方案...');
218
+
219
+ const planResult = await _executePlanGen(sdk, ctx, instruction, opts);
220
+
221
+ if (!planResult.success) {
222
+ log('error', `\n计划生成失败: ${planResult.reason || planResult.error}`);
223
+ return { success: false, reason: planResult.reason };
224
+ }
225
+
226
+ log('ok', `\n计划已生成: ${planResult.targetPath}`);
227
+
228
+ if (planOnly) {
229
+ return { success: true, planPath: planResult.targetPath };
230
+ }
231
+
232
+ log('info', '正在生成任务列表...');
233
+
234
+ const tasksPrompt = buildPlanPrompt(planResult.targetPath);
235
+ const queryOpts = buildQueryOptions(ctx.config, opts);
236
+ queryOpts.systemPrompt = buildSystemPrompt('plan');
237
+ queryOpts.hooks = ctx.hooks;
238
+ queryOpts.abortController = ctx.abortController;
239
+
240
+ await ctx.runQuery(sdk, tasksPrompt, queryOpts);
241
+
242
+ syncAfterPlan();
243
+ log('ok', '任务追加完成');
244
+ return { success: true, planPath: planResult.targetPath };
245
+ },
246
+ });
247
+ }
248
+
249
+ async function promptAutoRun() {
250
+ if (!process.stdin.isTTY) return false;
251
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
252
+ return new Promise(resolve => {
253
+ rl.question('任务分解完成后是否自动开始执行?(y/n) ', answer => {
254
+ rl.close();
255
+ resolve(/^[Yy]/.test(answer.trim()));
256
+ });
257
+ });
258
+ }
259
+
260
+ async function run(input, opts = {}) {
261
+ const instruction = input || '';
262
+
263
+ assets.ensureDirs();
264
+ const projectRoot = assets.projectRoot;
265
+
266
+ if (opts.readFile) {
267
+ const reqPath = path.resolve(projectRoot, opts.readFile);
268
+ if (!fs.existsSync(reqPath)) {
269
+ log('error', `文件不存在: ${reqPath}`);
270
+ process.exit(1);
271
+ }
272
+ opts.reqFile = reqPath;
273
+ if (instruction) {
274
+ log('info', `-r 模式下忽略文本输入,使用需求文件: ${reqPath}`);
275
+ } else {
276
+ console.log(`需求文件: ${reqPath}`);
277
+ }
278
+ }
279
+
280
+ if (!instruction && !opts.reqFile) {
281
+ log('error', '用法: claude-coder plan "需求内容" 或 claude-coder plan -r [requirements.md]');
282
+ process.exit(1);
283
+ }
284
+
285
+ const config = loadConfig();
286
+ // if opts.model is not set, use the default opus model or default model, make sure the model is set.
287
+ if (!opts.model) {
288
+ if (config.defaultOpus) {
289
+ opts.model = config.defaultOpus;
290
+ } else if (config.model) {
291
+ opts.model = config.model;
292
+ }
293
+ }
294
+
295
+ const displayModel = opts.model || config.model || '(default)';
296
+ log('ok', `模型配置已加载: ${config.provider || 'claude'} (plan 使用: ${displayModel})`);
297
+ if (opts.interactive) {
298
+ log('info', '交互模式已启用,模型可能会向您提问');
299
+ }
300
+
301
+ if (!assets.exists('profile')) {
302
+ log('error', 'profile 不存在,请先运行 claude-coder init 初始化项目');
303
+ process.exit(1);
304
+ }
305
+
306
+ let shouldAutoRun = false;
307
+ if (!opts.planOnly) {
308
+ shouldAutoRun = await promptAutoRun();
309
+ }
310
+
311
+ const result = await runPlanSession(instruction, { projectRoot, ...opts });
312
+
313
+ if (result.success) {
314
+ printStats();
315
+
316
+ if (shouldAutoRun) {
317
+ console.log('');
318
+ log('info', '开始自动执行任务...');
319
+ const { run: runCoding } = require('./runner');
320
+ await runCoding(opts);
321
+ }
322
+ }
323
+ }
324
+
325
+ module.exports = { runPlanSession, run };
@@ -0,0 +1,226 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const { loadConfig } = require('../common/config');
6
+ const { assets } = require('../common/assets');
7
+ const { loadTasks, getStats } = require('../common/tasks');
8
+ const { loadState, selectNextTask } = require('./harness');
9
+
10
+ // --------------- System Prompt ---------------
11
+
12
+ function buildSystemPrompt(type) {
13
+ const core = assets.read('coreProtocol') || '';
14
+ let specific = '';
15
+ switch (type) {
16
+ case 'scan': specific = assets.read('scanSystem') || ''; break;
17
+ case 'coding': specific = assets.read('codingSystem') || ''; break;
18
+ case 'plan': specific = assets.read('planSystem') || ''; break;
19
+ }
20
+ return specific ? `${specific}\n\n${core}` : core;
21
+ }
22
+
23
+ // --------------- Task Type Detection ---------------
24
+
25
+ const WEB_CATEGORIES = new Set(['frontend', 'fullstack', 'test', 'e2e']);
26
+ const WEB_KEYWORDS = /playwright|browser|页面|前端|UI|端到端|e2e/i;
27
+
28
+ function needsWebTools(task) {
29
+ if (!task) return true;
30
+ if (WEB_CATEGORIES.has(task.category)) return true;
31
+ const text = [task.description || '', ...(task.steps || [])].join(' ');
32
+ return WEB_KEYWORDS.test(text);
33
+ }
34
+
35
+ // --------------- Hint Builders ---------------
36
+
37
+ function buildMcpHint(config, task) {
38
+ if (!config.mcpPlaywright) return '';
39
+ if (!needsWebTools(task)) return '';
40
+ return '前端/全栈任务可用 Playwright MCP(browser_navigate、browser_snapshot、browser_click 等)做端到端测试。';
41
+ }
42
+
43
+ function buildRetryHint(consecutiveFailures, lastValidateLog) {
44
+ if (consecutiveFailures > 0 && lastValidateLog) {
45
+ return `注意:上次会话校验失败,原因:${lastValidateLog}。请避免同样的问题。`;
46
+ }
47
+ return '';
48
+ }
49
+
50
+ function buildEnvHint(consecutiveFailures, sessionNum) {
51
+ if (sessionNum <= 1) return '首次会话,需要时执行 claude-coder init 初始化环境。';
52
+ if (consecutiveFailures > 0) return '上次失败,建议先确认环境状态。';
53
+ return '';
54
+ }
55
+
56
+ function buildDocsHint() {
57
+ const profile = assets.readJson('profile', null);
58
+ if (!profile) return '';
59
+ const docs = profile.existing_docs || [];
60
+ if (docs.length > 0) {
61
+ return `项目文档: ${docs.join(', ')}。编码前先读与任务相关的文档,了解接口约定和编码规范。`;
62
+ }
63
+ return '';
64
+ }
65
+
66
+ function buildTaskContext(projectRoot, taskId) {
67
+ try {
68
+ const taskData = loadTasks();
69
+ if (!taskData) return '无法读取 tasks.json,请手动检查。';
70
+ const features = taskData.features || [];
71
+ const stats = getStats(taskData);
72
+
73
+ const task = taskId
74
+ ? features.find(f => f.id === taskId)
75
+ : selectNextTask(taskData);
76
+
77
+ if (!task) return '无待处理任务。';
78
+
79
+ const steps = (task.steps || [])
80
+ .map((s, i) => ` ${i + 1}. ${s}`)
81
+ .join('\n');
82
+
83
+ const deps = (task.depends_on || []).length > 0
84
+ ? `depends_on: [${task.depends_on.join(', ')}]`
85
+ : '';
86
+
87
+ return [
88
+ `**${task.id}**: "${task.description}"`,
89
+ `状态: ${task.status}, category: ${task.category}, priority: ${task.priority || 'N/A'} ${deps}`,
90
+ `步骤:\n${steps}`,
91
+ `进度: ${stats.done}/${stats.total} done, ${stats.failed} failed`,
92
+ `项目路径: ${projectRoot}`,
93
+ ].join('\n');
94
+ } catch {
95
+ return '任务上下文加载失败,请读取 .claude-coder/tasks.json 自行确认。';
96
+ }
97
+ }
98
+
99
+ function buildTestEnvHint(projectRoot) {
100
+ if (assets.exists('testEnv')) {
101
+ return `测试凭证文件: ${projectRoot}/.claude-coder/test.env(含 API Key、测试账号等),测试前用 source 加载。`;
102
+ }
103
+ return '';
104
+ }
105
+
106
+ function buildPlaywrightAuthHint(config, task) {
107
+ if (!config.mcpPlaywright) return '';
108
+ if (!needsWebTools(task)) return '';
109
+ const mode = config.playwrightMode;
110
+ switch (mode) {
111
+ case 'persistent':
112
+ return 'Playwright MCP 使用 persistent 模式,浏览器登录状态持久保存,无需额外登录操作。';
113
+ case 'isolated':
114
+ return assets.exists('playwrightAuth')
115
+ ? 'Playwright MCP 使用 isolated 模式,已检测到登录状态文件,每次会话自动加载。'
116
+ : 'Playwright MCP 使用 isolated 模式,未检测到登录状态文件。如需登录,请先运行 claude-coder auth <URL>。';
117
+ case 'extension':
118
+ return 'Playwright MCP 使用 extension 模式,已连接用户真实浏览器,直接复用已有登录态。';
119
+ default:
120
+ return '';
121
+ }
122
+ }
123
+
124
+ function buildMemoryHint() {
125
+ const sr = assets.readJson('sessionResult', null);
126
+ if (!sr?.session_result) return '';
127
+ const base = `上次会话 ${sr.session_result}(${sr.status_before || '?'} → ${sr.status_after || '?'})。`;
128
+ if (!sr.notes || !sr.notes.trim()) return base;
129
+ return `${base}遗留: ${sr.notes.slice(0, 200)}`;
130
+ }
131
+
132
+ function buildServiceHint(maxSessions) {
133
+ return maxSessions === 1
134
+ ? '单次模式:收尾时停止所有后台服务。'
135
+ : '连续模式:收尾时不要停止后台服务,保持服务运行以便下个 session 继续使用。';
136
+ }
137
+
138
+ // --------------- Context Builders ---------------
139
+
140
+ function _resolveTask(taskId) {
141
+ try {
142
+ const taskData = loadTasks();
143
+ if (!taskData) return null;
144
+ const features = taskData.features || [];
145
+ return taskId ? features.find(f => f.id === taskId) : selectNextTask(taskData);
146
+ } catch { return null; }
147
+ }
148
+
149
+ /**
150
+ * 构建 coding session 的完整上下文(user prompt)
151
+ */
152
+ function buildCodingContext(sessionNum, opts = {}) {
153
+ const config = loadConfig();
154
+ const consecutiveFailures = opts.consecutiveFailures || 0;
155
+ const projectRoot = assets.projectRoot;
156
+ const task = _resolveTask(opts.taskId);
157
+
158
+ return assets.render('codingUser', {
159
+ sessionNum,
160
+ taskContext: buildTaskContext(projectRoot, opts.taskId),
161
+ mcpHint: buildMcpHint(config, task),
162
+ retryContext: buildRetryHint(consecutiveFailures, opts.lastValidateLog),
163
+ envHint: buildEnvHint(consecutiveFailures, sessionNum),
164
+ docsHint: buildDocsHint(),
165
+ testEnvHint: buildTestEnvHint(projectRoot),
166
+ playwrightAuthHint: buildPlaywrightAuthHint(config, task),
167
+ memoryHint: buildMemoryHint(),
168
+ serviceHint: buildServiceHint(opts.maxSessions || 50),
169
+ });
170
+ }
171
+
172
+ // --------------- Scan Session ---------------
173
+
174
+ function buildScanPrompt(projectType) {
175
+ return assets.render('scanUser', { projectType });
176
+ }
177
+
178
+ // --------------- Plan Session ---------------
179
+
180
+ function buildPlanPrompt(planPath) {
181
+ const projectRoot = assets.projectRoot;
182
+
183
+ let taskContext = '';
184
+ let recentExamples = '';
185
+ try {
186
+ const taskData = loadTasks();
187
+ if (taskData) {
188
+ const features = taskData.features || [];
189
+ const state = loadState();
190
+ const nextId = `feat-${String(state.next_task_id).padStart(3, '0')}`;
191
+ const categories = [...new Set(features.map(f => f.category))].join(', ');
192
+
193
+ taskContext = `新任务 ID 从 ${nextId} 开始,priority 从 ${state.next_priority} 开始。已有 category: ${categories || '无'}。`;
194
+
195
+ const recent = features.slice(-3);
196
+ if (recent.length) {
197
+ recentExamples = '已有任务格式参考(保持一致性):\n' +
198
+ recent.map(f => ` ${f.id}: "${f.description}" (category=${f.category}, steps=${(f.steps || []).length}步, depends_on=[${(f.depends_on || []).join(',')}])`).join('\n');
199
+ }
200
+ }
201
+ } catch { /* ignore */ }
202
+
203
+ let testRuleHint = '';
204
+ if (assets.exists('testRule') && assets.exists('mcpConfig')) {
205
+ testRuleHint = '【Playwright 测试规则】项目已配置 Playwright MCP(.mcp.json),' +
206
+ '`.claude-coder/assets/test_rule.md` 包含测试规范(Smart Snapshot、等待策略、步骤模板等)。' +
207
+ '前端页面 test 类任务 steps 首步加入 `【规则】阅读 .claude-coder/assets/test_rule.md`。';
208
+ }
209
+
210
+ return assets.render('planUser', {
211
+ taskContext,
212
+ recentExamples,
213
+ projectRoot,
214
+ planPath,
215
+ testRuleHint,
216
+ });
217
+ }
218
+
219
+ // --------------- Exports ---------------
220
+
221
+ module.exports = {
222
+ buildSystemPrompt,
223
+ buildCodingContext,
224
+ buildScanPrompt,
225
+ buildPlanPrompt,
226
+ };
@@ -0,0 +1,50 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const { buildEnvVars } = require('../common/config');
6
+ const { assets } = require('../common/assets');
7
+
8
+ /**
9
+ * 检查项目是否包含代码文件
10
+ */
11
+ function hasCodeFiles(projectRoot) {
12
+ const markers = [
13
+ 'package.json', 'pyproject.toml', 'requirements.txt', 'setup.py',
14
+ 'Cargo.toml', 'go.mod', 'pom.xml', 'build.gradle',
15
+ 'Makefile', 'Dockerfile', 'docker-compose.yml',
16
+ 'README.md', 'main.py', 'app.py', 'index.js', 'index.ts',
17
+ ];
18
+ for (const m of markers) {
19
+ if (fs.existsSync(path.join(projectRoot, m))) return true;
20
+ }
21
+ for (const d of ['src', 'lib', 'app', 'backend', 'frontend', 'web', 'server', 'client']) {
22
+ if (fs.existsSync(path.join(projectRoot, d)) && fs.statSync(path.join(projectRoot, d)).isDirectory()) return true;
23
+ }
24
+ return false;
25
+ }
26
+
27
+ /**
28
+ * 构建 SDK query 选项
29
+ */
30
+ function buildQueryOptions(config, opts = {}) {
31
+ const mode = opts.permissionMode || 'bypassPermissions';
32
+ const base = {
33
+ permissionMode: mode,
34
+ cwd: opts.projectRoot || assets.projectRoot,
35
+ env: buildEnvVars(config),
36
+ settingSources: ['project'],
37
+ };
38
+ if (mode === 'bypassPermissions') {
39
+ base.allowDangerouslySkipPermissions = true;
40
+ }
41
+ if (config.maxTurns > 0) base.maxTurns = config.maxTurns;
42
+ if (opts.model) base.model = opts.model;
43
+ else if (config.model) base.model = config.model;
44
+ return base;
45
+ }
46
+
47
+ module.exports = {
48
+ hasCodeFiles,
49
+ buildQueryOptions,
50
+ };
@@ -0,0 +1,46 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const { runSession } = require('./session');
6
+ const { buildQueryOptions } = require('./query');
7
+ const { log } = require('../common/config');
8
+
9
+ /**
10
+ * 使用 AI 修复损坏的 JSON 文件
11
+ * @param {string} filePath - 文件绝对路径
12
+ * @param {object} [opts] - 透传给 runSession 的选项
13
+ */
14
+ async function repairJsonFile(filePath, opts = {}) {
15
+ if (!fs.existsSync(filePath)) return;
16
+
17
+ const rawContent = fs.readFileSync(filePath, 'utf8');
18
+ if (!rawContent || !rawContent.trim()) return;
19
+
20
+ const fileName = path.basename(filePath);
21
+ log('info', `正在使用 AI 修复 ${fileName}...`);
22
+
23
+ const prompt = `文件 ${filePath} 的 JSON 格式已损坏,请修复并用 Write 工具写入原路径。\n\n当前损坏内容:\n${rawContent}`;
24
+
25
+ try {
26
+ await runSession('repair', {
27
+ opts,
28
+ sessionNum: 0,
29
+ logFileName: `repair_${fileName.replace('.json', '')}.log`,
30
+ label: `repair:${fileName}`,
31
+
32
+ async execute(sdk, ctx) {
33
+ const queryOpts = buildQueryOptions(ctx.config, opts);
34
+ queryOpts.hooks = ctx.hooks;
35
+ queryOpts.abortController = ctx.abortController;
36
+ await ctx.runQuery(sdk, prompt, queryOpts);
37
+ log('ok', `AI 修复 ${fileName} 完成`);
38
+ return {};
39
+ },
40
+ });
41
+ } catch (err) {
42
+ log('warn', `AI 修复 ${fileName} 失败: ${err.message}`);
43
+ }
44
+ }
45
+
46
+ module.exports = { repairJsonFile };