@miphamai/cli 0.85.53 → 0.85.55
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.
- package/README.md +1 -1
- package/package.json +6 -6
- package/src/agent/agent-registry.ts +17 -2
- package/src/agent/sub-agent.ts +18 -2
- package/src/agent/types.ts +9 -0
- package/src/commands/environment.ts +71 -35
- package/src/commands/project.ts +31 -0
- package/src/config/loader.ts +112 -3
- package/src/core/command-taps.ts +10 -0
- package/src/core/credential-masker/matcher.ts +38 -0
- package/src/core/engine.ts +351 -6
- package/src/core/hooks.ts +18 -7
- package/src/core/instructions.ts +17 -3
- package/src/core/review-gate.ts +192 -0
- package/src/core/rules-loader.ts +4 -1
- package/src/core/session-insights.ts +8 -2
- package/src/core/session-store.ts +30 -23
- package/src/core/task-performance-tasks.json +18 -0
- package/src/core/verification-baseline.ts +277 -0
- package/src/core/write-paths.ts +19 -0
- package/src/daemon/engine-capabilities.ts +22 -1
- package/src/daemon/launch.ts +11 -1
- package/src/i18n-core/locales/en-US.json +9 -1
- package/src/i18n-core/locales/zh-CN.json +9 -1
- package/src/index.tsx +35 -3
- package/src/mcp/transport.ts +35 -3
- package/src/providers/anthropic.ts +17 -1
- package/src/providers/openai-compat.ts +13 -1
- package/src/shared/package-info.ts +2 -2
- package/src/shared/types.ts +11 -0
- package/src/skills/fork-executor.ts +3 -2
- package/src/skills/loader.ts +9 -2
- package/src/tools/agent/skill.ts +1 -0
- package/src/tools/agent/workflow.ts +3 -0
- package/src/tools/exec/task.ts +41 -0
- package/src/tools/file/grep.ts +30 -1
- package/src/tools/network/web-fetch.ts +11 -2
- package/src/ui/chat.tsx +17 -0
- package/src/ui/commands.ts +280 -29
- package/src/ui/picker.tsx +120 -19
- package/src/workflow/primitives/agent.ts +10 -1
- package/src/workflow/runtime.ts +49 -0
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 收尾评审闸门:把「本轮写了文件之后的独立评审」做成可复用的模块。
|
|
3
|
+
*
|
|
4
|
+
* 两条写入路径共用同一个提取器(`writtenPathsFor`)—— 主引擎的
|
|
5
|
+
* `Engine.executeTool` 与子代理的直接 `tool.execute`。只接一条,
|
|
6
|
+
* 「把实现委派给 subagent」这种最常见形态就会让闸门的计数器停在 0,
|
|
7
|
+
* 而闸门看起来一切正常。
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { SubAgent } from '../agent/sub-agent'
|
|
11
|
+
import type { SubAgentServices } from '../agent/services'
|
|
12
|
+
import type { AgentDefinition } from '../agent/types'
|
|
13
|
+
import type { ProviderRegistry } from '../providers/registry'
|
|
14
|
+
import type { ToolDefinition } from '../shared/index.ts'
|
|
15
|
+
import type { PermissionSystem } from './permission'
|
|
16
|
+
import type { BaselineReport } from './verification-baseline'
|
|
17
|
+
export { writtenPathsFor } from './write-paths'
|
|
18
|
+
|
|
19
|
+
export interface ReviewRequest {
|
|
20
|
+
cwd: string
|
|
21
|
+
userPrompt: string
|
|
22
|
+
changedFiles: string[]
|
|
23
|
+
round: number
|
|
24
|
+
maxRounds: number
|
|
25
|
+
/** round > 1 时携带上一轮 findings,供复核而不是从头再报一遍。 */
|
|
26
|
+
previousFindings?: string
|
|
27
|
+
/** 机械检查的观察结果:哪些跑了(含成败)、哪些没跑。 */
|
|
28
|
+
baseline?: BaselineReport
|
|
29
|
+
/** 作者对着 findings 的最后一条说明(申辩或已修复说明),截断后传入。 */
|
|
30
|
+
authorResponse?: string
|
|
31
|
+
/** 本轮 turn 的取消信号 —— Ctrl+C / daemon stop 必须能取消评审。 */
|
|
32
|
+
signal?: AbortSignal
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export type ReviewResult =
|
|
36
|
+
{ status: 'pass' } | { status: 'fail'; findings: string } | { status: 'error'; message: string }
|
|
37
|
+
|
|
38
|
+
export type ReviewRunner = (req: ReviewRequest) => Promise<ReviewResult>
|
|
39
|
+
|
|
40
|
+
/** 引擎收下的闸门配置:开哪一档、跑几次、在哪个目录、用哪个 runner。 */
|
|
41
|
+
export interface ReviewGateConfig {
|
|
42
|
+
enabled: boolean
|
|
43
|
+
maxRounds: number
|
|
44
|
+
/**
|
|
45
|
+
* Reviewer working directory. A getter is resolved at review time so `/cd`
|
|
46
|
+
* moves the reviewer with the session; a string is for callers whose cwd is
|
|
47
|
+
* fixed for the engine's lifetime (the daemon's session cwd).
|
|
48
|
+
*/
|
|
49
|
+
cwd: string | (() => string)
|
|
50
|
+
runner: ReviewRunner
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface ReviewRunnerDeps {
|
|
54
|
+
registry: ProviderRegistry
|
|
55
|
+
toolRegistry: Map<string, ToolDefinition>
|
|
56
|
+
permission?: PermissionSystem
|
|
57
|
+
services?: SubAgentServices
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* 解析首个 `VERDICT: PASS|FAIL`;FAIL 时取 findings。
|
|
62
|
+
*
|
|
63
|
+
* 提示词约定 findings 写在 verdict **之前**(verdict 是最后一行),所以先取
|
|
64
|
+
* match 之前的正文;若之前为空(评审者写在了后面),再退回取 match 之后。
|
|
65
|
+
* 只取一侧会让「按提示词写」的评审永远返回空 findings —— 阻塞了却没有可修的信号。
|
|
66
|
+
*/
|
|
67
|
+
export function parseReviewVerdict(
|
|
68
|
+
text: string,
|
|
69
|
+
): { verdict: 'pass' | 'fail'; findings: string } | null {
|
|
70
|
+
const match = /^\s*VERDICT:\s*(PASS|FAIL)\b/im.exec(text)
|
|
71
|
+
if (!match) return null
|
|
72
|
+
const verdict = match[1]!.toLowerCase() === 'pass' ? 'pass' : 'fail'
|
|
73
|
+
if (verdict === 'pass') return { verdict, findings: '' }
|
|
74
|
+
const before = text.slice(0, match.index).trim()
|
|
75
|
+
const after = text.slice(match.index + match[0].length).trim()
|
|
76
|
+
return { verdict, findings: before || after }
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function buildReviewPrompt(req: ReviewRequest): string {
|
|
80
|
+
const lines = [
|
|
81
|
+
'你是一次独立评审。你看不到作者的推理链;作者也看不到你的。',
|
|
82
|
+
'判断:下面的用户需求是否被产物正确、完整地实现。',
|
|
83
|
+
'',
|
|
84
|
+
`工作目录: ${req.cwd}`,
|
|
85
|
+
'',
|
|
86
|
+
'用户需求:',
|
|
87
|
+
req.userPrompt,
|
|
88
|
+
'',
|
|
89
|
+
'本轮改动的文件:',
|
|
90
|
+
...(req.changedFiles.length > 0
|
|
91
|
+
? req.changedFiles.map((f) => `- ${f}`)
|
|
92
|
+
: ['- (没有记录到具体路径;请在工作目录里自行辨认本轮产物)']),
|
|
93
|
+
]
|
|
94
|
+
|
|
95
|
+
if (req.baseline) {
|
|
96
|
+
lines.push('', '机械检查状态:')
|
|
97
|
+
lines.push(`- 期望: ${req.baseline.expected.join(' / ') || '(无)'}`)
|
|
98
|
+
if (req.baseline.ran.length === 0) {
|
|
99
|
+
lines.push('- 已跑: (无)')
|
|
100
|
+
} else {
|
|
101
|
+
lines.push('- 已跑:')
|
|
102
|
+
for (const run of req.baseline.ran) {
|
|
103
|
+
const outcome = run.ok ? '通过' : '失败'
|
|
104
|
+
lines.push(` - ${run.command} → ${outcome}${run.stale ? '(最后一次修改之前,不算数)' : ''}`)
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
lines.push(`- 未运行: ${req.baseline.missing.join(' / ') || '(无)'}`)
|
|
108
|
+
lines.push('未运行的检查不得当作已通过。')
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
if (req.round > 1) {
|
|
112
|
+
lines.push(
|
|
113
|
+
'',
|
|
114
|
+
`这是第 ${req.round}/${req.maxRounds} 轮复核。`,
|
|
115
|
+
'上一轮评审发现:',
|
|
116
|
+
req.previousFindings || '(未记录)',
|
|
117
|
+
'',
|
|
118
|
+
'作者的最后说明:',
|
|
119
|
+
req.authorResponse || '(未提供)',
|
|
120
|
+
'',
|
|
121
|
+
'请判断上一轮的问题是否已修复,或作者的说明是否成立;不要从头重复报告已解决的问题。',
|
|
122
|
+
)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
lines.push(
|
|
126
|
+
'',
|
|
127
|
+
'要求:',
|
|
128
|
+
'- 只读:不要修改任何文件。',
|
|
129
|
+
'- 假设存在缺陷:主动找,不要做确认性审查。',
|
|
130
|
+
'- 改名/去重/生成标识:结果必须与已有集合不相交。',
|
|
131
|
+
'- 同一事实有两种表示(文本/JSON、服务端/客户端)时,必须交叉一致。',
|
|
132
|
+
'- 禁止静默修正用户输入:钳制、默认值替换要么报错,要么显式告警。',
|
|
133
|
+
'- 每条问题给 file:line、为什么错、以及**建议的**复现步骤(你无法执行命令)。',
|
|
134
|
+
'- 结束时最后一行必须是以下之一:',
|
|
135
|
+
'VERDICT: PASS',
|
|
136
|
+
'VERDICT: FAIL',
|
|
137
|
+
'FAIL 时把 findings 写在 verdict 行之前。',
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
return lines.join('\n')
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const REVIEW_SYSTEM_PROMPT = [
|
|
144
|
+
'你是一个只读的代码评审者,负责在作者收尾前独立检查产物。',
|
|
145
|
+
'你只能使用 Read / Grep / Glob;不能修改文件,不能执行命令,不能派生子代理。',
|
|
146
|
+
'假设存在缺陷。优先检查:边界输入、错误路径、两个表示之间的一致性、静默丢弃或静默改写的值。',
|
|
147
|
+
'每条 finding 必须给 file:line 和理由;复现步骤只能是建议,因为你无法执行。',
|
|
148
|
+
'最后一行必须是 `VERDICT: PASS` 或 `VERDICT: FAIL`。',
|
|
149
|
+
].join('\n')
|
|
150
|
+
|
|
151
|
+
export function createReviewRunner(deps: ReviewRunnerDeps): ReviewRunner {
|
|
152
|
+
return async (req) => {
|
|
153
|
+
const agentDef: AgentDefinition = {
|
|
154
|
+
name: 'review-gate',
|
|
155
|
+
description: 'Independent read-only reviewer for the review gate',
|
|
156
|
+
systemPrompt: REVIEW_SYSTEM_PROMPT,
|
|
157
|
+
tools: 'Read,Grep,Glob',
|
|
158
|
+
model: 'inherit',
|
|
159
|
+
permissionMode: 'plan',
|
|
160
|
+
maxTurns: 8,
|
|
161
|
+
source: 'builtin',
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
try {
|
|
165
|
+
const sub = new SubAgent(
|
|
166
|
+
deps.registry,
|
|
167
|
+
deps.toolRegistry,
|
|
168
|
+
deps.permission,
|
|
169
|
+
undefined,
|
|
170
|
+
undefined,
|
|
171
|
+
undefined,
|
|
172
|
+
deps.services,
|
|
173
|
+
)
|
|
174
|
+
const out = await sub.execute(buildReviewPrompt(req), 'review gate', {
|
|
175
|
+
type: 'general',
|
|
176
|
+
agentDef,
|
|
177
|
+
cwd: req.cwd,
|
|
178
|
+
maxTurns: 8,
|
|
179
|
+
signal: req.signal,
|
|
180
|
+
})
|
|
181
|
+
const parsed = parseReviewVerdict(out)
|
|
182
|
+
if (!parsed) {
|
|
183
|
+
return { status: 'error', message: 'reviewer produced no VERDICT line' }
|
|
184
|
+
}
|
|
185
|
+
return parsed.verdict === 'pass'
|
|
186
|
+
? { status: 'pass' }
|
|
187
|
+
: { status: 'fail', findings: parsed.findings }
|
|
188
|
+
} catch (err) {
|
|
189
|
+
return { status: 'error', message: err instanceof Error ? err.message : String(err) }
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
}
|
package/src/core/rules-loader.ts
CHANGED
|
@@ -273,7 +273,10 @@ export class RulesLoader {
|
|
|
273
273
|
return { paths: [], description: '', content: raw.trim() }
|
|
274
274
|
}
|
|
275
275
|
|
|
276
|
-
|
|
276
|
+
// The fence regex accepts CRLF, but the line parsers below split on `\n`
|
|
277
|
+
// and anchor with `$`, so a trailing `\r` made `paths:`/`description:`
|
|
278
|
+
// silently miss. Normalize before reading keys.
|
|
279
|
+
const frontmatter = (match[1] || '').replace(/\r/g, '')
|
|
277
280
|
const body = (match[2] || '').trim()
|
|
278
281
|
|
|
279
282
|
const paths: string[] = []
|
|
@@ -63,9 +63,15 @@ export function summarizeSessions(inputs: SessionInsightsInput[]): InsightsRepor
|
|
|
63
63
|
let firstAt: number | null = null
|
|
64
64
|
let lastAt: number | null = null
|
|
65
65
|
|
|
66
|
-
const bumpTool = (name:
|
|
66
|
+
const bumpTool = (name: unknown) => {
|
|
67
67
|
toolCalls += 1
|
|
68
|
-
|
|
68
|
+
// A `tool_use` block with no `name` is legal on disk (the provider emits a
|
|
69
|
+
// synthetic name only later), and older logs can carry one. Keying the map
|
|
70
|
+
// with `undefined` made the tie-break sort below call `localeCompare` on it
|
|
71
|
+
// and throw — `/insights` failed on the whole log instead of counting the
|
|
72
|
+
// call (CC 2.1.334-093).
|
|
73
|
+
const key = typeof name === 'string' && name.length > 0 ? name : '(unnamed tool)'
|
|
74
|
+
topTools.set(key, (topTools.get(key) ?? 0) + 1)
|
|
69
75
|
}
|
|
70
76
|
|
|
71
77
|
for (const input of inputs) {
|
|
@@ -415,8 +415,14 @@ export class SessionStore {
|
|
|
415
415
|
static getLatest(): SessionIndexEntry | null {
|
|
416
416
|
const index = SessionStore.loadIndexRaw()
|
|
417
417
|
if (index.length > 0) {
|
|
418
|
-
|
|
419
|
-
|
|
418
|
+
// A session that has only `session/start` (opened, then exited without a
|
|
419
|
+
// turn) is not something `/resume last` or `--continue` can continue. It
|
|
420
|
+
// used to become the newest entry and hide the real previous turn; skip
|
|
421
|
+
// it (CC 2.1.335-067). `undefined` is kept: older indexes predate the field.
|
|
422
|
+
const resumable = index.filter((entry) => entry.messageCount !== 0)
|
|
423
|
+
if (resumable.length === 0) return null
|
|
424
|
+
resumable.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime())
|
|
425
|
+
return resumable[0]!
|
|
420
426
|
}
|
|
421
427
|
// Fallback: scan .jsonl files directly when index is missing
|
|
422
428
|
return SessionStore.scanLatestFromDisk()
|
|
@@ -425,29 +431,30 @@ export class SessionStore {
|
|
|
425
431
|
/** Scan .jsonl files on disk by mtime — fallback when .index.json is missing. */
|
|
426
432
|
private static scanLatestFromDisk(): SessionIndexEntry | null {
|
|
427
433
|
ensureDir()
|
|
428
|
-
const files = readdirSync(SESSIONS_DIR)
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
434
|
+
const files = readdirSync(SESSIONS_DIR)
|
|
435
|
+
.filter((f) => f.endsWith('.jsonl'))
|
|
436
|
+
.map((f) => ({
|
|
437
|
+
name: f.replace('.jsonl', ''),
|
|
438
|
+
mtime: statSync(join(SESSIONS_DIR, f)).mtimeMs,
|
|
439
|
+
}))
|
|
440
|
+
.sort((a, b) => b.mtime - a.mtime)
|
|
441
|
+
for (const candidate of files) {
|
|
442
|
+
const session = SessionStore.load(candidate.name)
|
|
443
|
+
if (!session) continue
|
|
444
|
+
// Same rule as the index path: an empty session is not resumable.
|
|
445
|
+
if (session.metadata.messageCount === 0) continue
|
|
446
|
+
return {
|
|
447
|
+
name: candidate.name,
|
|
448
|
+
createdAt: session.metadata.createdAt,
|
|
449
|
+
updatedAt: session.metadata.updatedAt,
|
|
450
|
+
provider: session.metadata.provider,
|
|
451
|
+
model: session.metadata.model,
|
|
452
|
+
messageCount: session.metadata.messageCount,
|
|
453
|
+
tokenCount: 0,
|
|
454
|
+
cwd: session.metadata.cwd,
|
|
435
455
|
}
|
|
436
456
|
}
|
|
437
|
-
|
|
438
|
-
// Load the session to extract metadata
|
|
439
|
-
const session = SessionStore.load(latest.name)
|
|
440
|
-
if (!session) return null
|
|
441
|
-
return {
|
|
442
|
-
name: latest.name,
|
|
443
|
-
createdAt: session.metadata.createdAt,
|
|
444
|
-
updatedAt: session.metadata.updatedAt,
|
|
445
|
-
provider: session.metadata.provider,
|
|
446
|
-
model: session.metadata.model,
|
|
447
|
-
messageCount: session.metadata.messageCount,
|
|
448
|
-
tokenCount: 0,
|
|
449
|
-
cwd: session.metadata.cwd,
|
|
450
|
-
}
|
|
457
|
+
return null
|
|
451
458
|
}
|
|
452
459
|
|
|
453
460
|
/**
|
|
@@ -130,6 +130,24 @@
|
|
|
130
130
|
"oracleCode": "export function chunk<T>(arr: T[], size: number): T[][] {\n if (!Number.isInteger(size) || size <= 0) throw new RangeError('size must be a positive integer')\n const out: T[][] = []\n for (let i = 0; i < arr.length; i += size) out.push(arr.slice(i, i + size))\n return out\n}\n",
|
|
131
131
|
"skill": "tdd",
|
|
132
132
|
"split": "gate"
|
|
133
|
+
},
|
|
134
|
+
{
|
|
135
|
+
"id": "perf-safe-unique-rename",
|
|
136
|
+
"category": "test-driven",
|
|
137
|
+
"skill": "safe-coding",
|
|
138
|
+
"split": "gate",
|
|
139
|
+
"prompt": "实现并导出 dedupeNames 函数:export function dedupeNames(names: string[]): string[]。首次出现的名字原样保留;重复出现的名字按出现顺序追加 _2、_3……;生成的名字不得与输入里的任何原名、或任何已经输出的名字相同;输出顺序与输入一致。只输出 TypeScript 代码,不要解释、不要 markdown 代码块。",
|
|
140
|
+
"testCode": "import { test, expect } from 'bun:test'\nimport { dedupeNames } from './solution'\n\ntest('renames duplicates', () => {\n expect(dedupeNames(['a', 'a'])).toEqual(['a', 'a_2'])\n})\n\ntest('generated name never collides with an original', () => {\n expect(dedupeNames(['a', 'a_2', 'a'])).toEqual(['a', 'a_2', 'a_3'])\n expect(dedupeNames(['x', 'x', 'x_2'])).toEqual(['x', 'x_3', 'x_2'])\n expect(dedupeNames(['a', 'a_2', 'a', 'a'])).toEqual(['a', 'a_2', 'a_3', 'a_4'])\n})\n\ntest('preserves order and names', () => {\n expect(dedupeNames(['b', 'a', 'b', 'a'])).toEqual(['b', 'a', 'b_2', 'a_2'])\n})\n",
|
|
141
|
+
"oracleCode": "export function dedupeNames(names: string[]): string[] {\n const reserved = new Set(names)\n const used = new Set<string>()\n return names.map((name) => {\n if (!used.has(name)) {\n used.add(name)\n return name\n }\n let n = 2\n while (reserved.has(`${name}_${n}`) || used.has(`${name}_${n}`)) n++\n const candidate = `${name}_${n}`\n used.add(candidate)\n return candidate\n })\n}\n"
|
|
142
|
+
},
|
|
143
|
+
{
|
|
144
|
+
"id": "perf-safe-dual-render",
|
|
145
|
+
"category": "test-driven",
|
|
146
|
+
"skill": "safe-coding",
|
|
147
|
+
"split": "gate",
|
|
148
|
+
"prompt": "实现并导出 summarizeColumns 函数:export function summarizeColumns(headers: string[]): { json: Array<{ index: number; name: string }>; text: string }。json[i].index 从 1 开始;text 每行形如 [index] name;同一列在两种表示里的 index 必须相同,不得遗漏或重排。只输出 TypeScript 代码,不要解释、不要 markdown 代码块。",
|
|
149
|
+
"testCode": "import { test, expect } from 'bun:test'\nimport { summarizeColumns } from './solution'\n\ntest('renders columns in both forms', () => {\n const r = summarizeColumns(['a', 'b'])\n expect(r.json).toEqual([\n { index: 1, name: 'a' },\n { index: 2, name: 'b' },\n ])\n expect(r.text.split('\\n')).toEqual(['[1] a', '[2] b'])\n})\n\ntest('both representations agree per column, even for numeric names', () => {\n const r = summarizeColumns(['b_2', 'b'])\n const lines = r.text.split('\\n')\n expect(lines).toHaveLength(r.json.length)\n lines.forEach((line, i) => {\n const m = /^\\[(\\d+)\\] (.*)$/.exec(line)\n expect(m, line).not.toBeNull()\n expect(Number(m![1])).toBe(r.json[i]!.index)\n expect(m![2]).toBe(r.json[i]!.name)\n })\n})\n",
|
|
150
|
+
"oracleCode": "export function summarizeColumns(headers: string[]): {\n json: Array<{ index: number; name: string }>\n text: string\n} {\n const json = headers.map((name, i) => ({ index: i + 1, name }))\n return { json, text: json.map(({ index, name }) => `[${index}] ${name}`).join('\\n') }\n}\n"
|
|
133
151
|
}
|
|
134
152
|
]
|
|
135
153
|
}
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 观察式项目验证基线:从清单文件推导「该项目应有的机械检查」,再用**本轮
|
|
3
|
+
* 实际执行过的命令**去比对。这里只读文件与命令字符串,不执行任何项目代码。
|
|
4
|
+
*
|
|
5
|
+
* 失败方向是刻意选的:匹配太严 ⇒ 多问一次;匹配太松 ⇒ 把没跑的检查当成
|
|
6
|
+
* 跑过了。后者正是这道基线要消灭的静默放过。
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
10
|
+
import { dirname, join, resolve } from 'node:path'
|
|
11
|
+
|
|
12
|
+
export type ProjectKind = 'rust' | 'node' | 'python' | 'go'
|
|
13
|
+
|
|
14
|
+
export interface CheckMatcher {
|
|
15
|
+
/** 命令段开头的 token,逐字相同。 */
|
|
16
|
+
prefix: string[]
|
|
17
|
+
/** 其他同样算数的段首形式(如无锁文件时任一包管理器)。 */
|
|
18
|
+
prefixAlternatives?: string[][]
|
|
19
|
+
/** 还必须出现在段内的标志位(如 `--check`)。 */
|
|
20
|
+
requiredFlags?: string[]
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface ExpectedCheck {
|
|
24
|
+
id: string
|
|
25
|
+
/** 给人看的命令形态,也是报告里的「缺失项」名字。 */
|
|
26
|
+
label: string
|
|
27
|
+
matcher: CheckMatcher
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface ProjectBaseline {
|
|
31
|
+
kind: ProjectKind
|
|
32
|
+
manifest: string
|
|
33
|
+
sourceExtensions: string[]
|
|
34
|
+
checks: ExpectedCheck[]
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface TurnCommand {
|
|
38
|
+
command: string
|
|
39
|
+
ok: boolean
|
|
40
|
+
seq: number
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Engine-side config. `cwd` is resolved at check time so `/cd` is followed. */
|
|
44
|
+
export interface VerificationBaselineConfig {
|
|
45
|
+
enabled: boolean
|
|
46
|
+
cwd: string | (() => string)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface BaselineReport {
|
|
50
|
+
expected: string[]
|
|
51
|
+
ran: Array<{ command: string; ok: boolean; stale: boolean }>
|
|
52
|
+
missing: string[]
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const PACKAGE_RUNNERS = new Set(['pnpm', 'npm', 'yarn', 'bun'])
|
|
56
|
+
|
|
57
|
+
function readable(path: string): string | null {
|
|
58
|
+
try {
|
|
59
|
+
return readFileSync(path, 'utf-8')
|
|
60
|
+
} catch {
|
|
61
|
+
return null
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function check(
|
|
66
|
+
id: string,
|
|
67
|
+
label: string,
|
|
68
|
+
prefix: string[],
|
|
69
|
+
requiredFlags?: string[],
|
|
70
|
+
): ExpectedCheck {
|
|
71
|
+
return { id, label, matcher: { prefix, ...(requiredFlags ? { requiredFlags } : {}) } }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function detectRust(cwd: string): ProjectBaseline | null {
|
|
75
|
+
if (!existsSync(join(cwd, 'Cargo.toml'))) return null
|
|
76
|
+
const content = readable(join(cwd, 'Cargo.toml'))
|
|
77
|
+
if (content === null) return null
|
|
78
|
+
// Garbage in the manifest means no baseline: the derived commands could
|
|
79
|
+
// never describe this directory.
|
|
80
|
+
if (!/^\s*\[(?:package|workspace)\]/m.test(content)) return null
|
|
81
|
+
return {
|
|
82
|
+
kind: 'rust',
|
|
83
|
+
manifest: 'Cargo.toml',
|
|
84
|
+
sourceExtensions: ['.rs'],
|
|
85
|
+
checks: [
|
|
86
|
+
check('rust-fmt', 'cargo fmt --check', ['cargo', 'fmt'], ['--check']),
|
|
87
|
+
check('rust-clippy', 'cargo clippy', ['cargo', 'clippy']),
|
|
88
|
+
check('rust-test', 'cargo test', ['cargo', 'test']),
|
|
89
|
+
],
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const LOCK_RUNNERS: Array<[string, string]> = [
|
|
94
|
+
['pnpm-lock.yaml', 'pnpm'],
|
|
95
|
+
['package-lock.json', 'npm'],
|
|
96
|
+
['yarn.lock', 'yarn'],
|
|
97
|
+
['bun.lockb', 'bun'],
|
|
98
|
+
['bun.lock', 'bun'],
|
|
99
|
+
]
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* runner 取自**最近的**锁文件。只找 cwd 会把 monorepo 的子包(锁文件在
|
|
103
|
+
* 仓库根)误判成 npm,于是 `pnpm test` 永远对不上 `npm test` —— 默认开启
|
|
104
|
+
* 时这是每个写码轮次都误报。走到文件系统根为止;找不到返回 null(任一
|
|
105
|
+
* 包管理器都算数)。
|
|
106
|
+
*/
|
|
107
|
+
function findNodeRunner(cwd: string): string | null {
|
|
108
|
+
let dir = resolve(cwd)
|
|
109
|
+
for (;;) {
|
|
110
|
+
for (const [file, runner] of LOCK_RUNNERS) {
|
|
111
|
+
if (existsSync(join(dir, file))) return runner
|
|
112
|
+
}
|
|
113
|
+
const parent = dirname(dir)
|
|
114
|
+
if (parent === dir) return null
|
|
115
|
+
dir = parent
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function detectNode(cwd: string): ProjectBaseline | null {
|
|
120
|
+
const raw = readable(join(cwd, 'package.json'))
|
|
121
|
+
if (raw === null) return null
|
|
122
|
+
let scripts: Record<string, unknown>
|
|
123
|
+
try {
|
|
124
|
+
const parsed = JSON.parse(raw) as { scripts?: Record<string, unknown> }
|
|
125
|
+
scripts = parsed.scripts && typeof parsed.scripts === 'object' ? parsed.scripts : {}
|
|
126
|
+
} catch {
|
|
127
|
+
return null
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const runner = findNodeRunner(cwd)
|
|
131
|
+
const checks: ExpectedCheck[] = []
|
|
132
|
+
const addScript = (id: string, script: string): void => {
|
|
133
|
+
if (typeof scripts[script] !== 'string') return
|
|
134
|
+
if (runner) {
|
|
135
|
+
checks.push(check(id, `${runner} ${script}`, [runner, script]))
|
|
136
|
+
return
|
|
137
|
+
}
|
|
138
|
+
// No lockfile anywhere: any of the four runners is a legitimate way to run
|
|
139
|
+
// the script, so accept all of them.
|
|
140
|
+
checks.push({
|
|
141
|
+
id,
|
|
142
|
+
label: `npm ${script}`,
|
|
143
|
+
matcher: {
|
|
144
|
+
prefix: ['npm', script],
|
|
145
|
+
prefixAlternatives: [
|
|
146
|
+
['pnpm', script],
|
|
147
|
+
['yarn', script],
|
|
148
|
+
['bun', script],
|
|
149
|
+
],
|
|
150
|
+
},
|
|
151
|
+
})
|
|
152
|
+
}
|
|
153
|
+
addScript('node-test', 'test')
|
|
154
|
+
addScript('node-lint', 'lint')
|
|
155
|
+
if (typeof scripts.typecheck === 'string') {
|
|
156
|
+
addScript('node-typecheck', 'typecheck')
|
|
157
|
+
} else if (existsSync(join(cwd, 'tsconfig.json'))) {
|
|
158
|
+
checks.push(check('node-tsc', 'tsc --noEmit', ['tsc'], ['--noEmit']))
|
|
159
|
+
}
|
|
160
|
+
addScript('node-format', 'format:check')
|
|
161
|
+
|
|
162
|
+
return {
|
|
163
|
+
kind: 'node',
|
|
164
|
+
manifest: 'package.json',
|
|
165
|
+
sourceExtensions: ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs'],
|
|
166
|
+
checks,
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function detectPython(cwd: string): ProjectBaseline | null {
|
|
171
|
+
if (!existsSync(join(cwd, 'pyproject.toml'))) return null
|
|
172
|
+
const content = readable(join(cwd, 'pyproject.toml'))
|
|
173
|
+
if (content === null) return null
|
|
174
|
+
if (!/^\s*\[(?:project|tool\.)/m.test(content)) return null
|
|
175
|
+
return {
|
|
176
|
+
kind: 'python',
|
|
177
|
+
manifest: 'pyproject.toml',
|
|
178
|
+
sourceExtensions: ['.py'],
|
|
179
|
+
checks: [
|
|
180
|
+
check('python-ruff-check', 'ruff check', ['ruff', 'check']),
|
|
181
|
+
check('python-ruff-format', 'ruff format --check', ['ruff', 'format'], ['--check']),
|
|
182
|
+
check('python-pytest', 'pytest', ['pytest']),
|
|
183
|
+
],
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function detectGo(cwd: string): ProjectBaseline | null {
|
|
188
|
+
if (!existsSync(join(cwd, 'go.mod'))) return null
|
|
189
|
+
const content = readable(join(cwd, 'go.mod'))
|
|
190
|
+
if (content === null) return null
|
|
191
|
+
if (!/^\s*module\s+/m.test(content)) return null
|
|
192
|
+
return {
|
|
193
|
+
kind: 'go',
|
|
194
|
+
manifest: 'go.mod',
|
|
195
|
+
sourceExtensions: ['.go'],
|
|
196
|
+
checks: [
|
|
197
|
+
check('go-fmt', 'gofmt -l', ['gofmt'], ['-l']),
|
|
198
|
+
check('go-vet', 'go vet', ['go', 'vet']),
|
|
199
|
+
check('go-test', 'go test', ['go', 'test']),
|
|
200
|
+
],
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** 先命中先得;任何读取/解析失败都返回 null(基线静默不启用)。 */
|
|
205
|
+
export function detectProjectBaseline(cwd: string): ProjectBaseline | null {
|
|
206
|
+
return detectRust(cwd) ?? detectNode(cwd) ?? detectPython(cwd) ?? detectGo(cwd)
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function commandSegments(command: string): string[][] {
|
|
210
|
+
return command
|
|
211
|
+
.split(/[;&|]{1,2}/)
|
|
212
|
+
.map((segment) => segment.trim().split(/\s+/).filter(Boolean))
|
|
213
|
+
.filter((tokens) => tokens.length > 0)
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* 命令是否覆盖某个检查。按 `&&`/`||`/`;`/`|` 切段后做段首前缀匹配;
|
|
218
|
+
* 含 `--help`/`-h` 的段不算执行。包管理器的可选 `run` 跳过(`pnpm run test`
|
|
219
|
+
* 等价 `pnpm test`),且只对包管理器生效。
|
|
220
|
+
*/
|
|
221
|
+
export function commandCovers(matcher: CheckMatcher, command: string): boolean {
|
|
222
|
+
const prefixes = [matcher.prefix, ...(matcher.prefixAlternatives ?? [])]
|
|
223
|
+
for (const original of commandSegments(command)) {
|
|
224
|
+
if (original.includes('--help') || original.includes('-h')) continue
|
|
225
|
+
for (const prefix of prefixes) {
|
|
226
|
+
let tokens = original
|
|
227
|
+
if (PACKAGE_RUNNERS.has(prefix[0] ?? '') && tokens[1] === 'run') {
|
|
228
|
+
tokens = [tokens[0]!, ...tokens.slice(2)]
|
|
229
|
+
}
|
|
230
|
+
if (!prefix.every((token, i) => tokens[i] === token)) continue
|
|
231
|
+
if (
|
|
232
|
+
matcher.requiredFlags &&
|
|
233
|
+
!matcher.requiredFlags.every((flag) => original.includes(flag))
|
|
234
|
+
) {
|
|
235
|
+
continue
|
|
236
|
+
}
|
|
237
|
+
return true
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
return false
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** 本轮是否写了该项目的源码文件(只认扩展名)。 */
|
|
244
|
+
export function hasSourceWrite(baseline: ProjectBaseline, paths: Iterable<string>): boolean {
|
|
245
|
+
for (const path of paths) {
|
|
246
|
+
const lower = path.toLowerCase()
|
|
247
|
+
if (baseline.sourceExtensions.some((ext) => lower.endsWith(ext))) return true
|
|
248
|
+
}
|
|
249
|
+
return false
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* 汇总本轮命令。`stale` 的命令仍然列出来(作者需要看到自己跑过什么),
|
|
254
|
+
* 但只有发生在最近一次源码写入之后的命中才算覆盖。
|
|
255
|
+
*/
|
|
256
|
+
export function evaluateBaseline(
|
|
257
|
+
baseline: ProjectBaseline,
|
|
258
|
+
commands: TurnCommand[],
|
|
259
|
+
lastSourceWriteSeq: number,
|
|
260
|
+
): BaselineReport {
|
|
261
|
+
const ran: BaselineReport['ran'] = []
|
|
262
|
+
const covered = new Set<string>()
|
|
263
|
+
|
|
264
|
+
for (const command of commands) {
|
|
265
|
+
const matched = baseline.checks.filter((c) => commandCovers(c.matcher, command.command))
|
|
266
|
+
if (matched.length === 0) continue
|
|
267
|
+
const stale = command.seq <= lastSourceWriteSeq
|
|
268
|
+
ran.push({ command: command.command, ok: command.ok, stale })
|
|
269
|
+
if (!stale) for (const c of matched) covered.add(c.label)
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
return {
|
|
273
|
+
expected: baseline.checks.map((c) => c.label),
|
|
274
|
+
ran,
|
|
275
|
+
missing: baseline.checks.filter((c) => !covered.has(c.label)).map((c) => c.label),
|
|
276
|
+
}
|
|
277
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 哪些工具调用写了哪些文件 —— 收尾评审闸门的共享词汇。
|
|
3
|
+
*
|
|
4
|
+
* 单独成文件是为了避免 import 环:`sub-agent.ts` 需要它,而 `review-gate.ts`
|
|
5
|
+
* 需要 `SubAgent`。两条写入路径(主引擎与子代理)共用同一个提取器。
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { extractBashFileAccess } from './permission-rules'
|
|
9
|
+
|
|
10
|
+
/** 成功写入的文件路径;只读工具返回空数组。 */
|
|
11
|
+
export function writtenPathsFor(toolName: string, params: Record<string, unknown>): string[] {
|
|
12
|
+
if (toolName === 'Bash') {
|
|
13
|
+
const command = params.command
|
|
14
|
+
return typeof command === 'string' ? extractBashFileAccess(command).write : []
|
|
15
|
+
}
|
|
16
|
+
if (toolName !== 'Write' && toolName !== 'Edit') return []
|
|
17
|
+
const p = params.file_path
|
|
18
|
+
return typeof p === 'string' && p.length > 0 ? [p] : []
|
|
19
|
+
}
|
|
@@ -33,7 +33,8 @@ import { HookEngine } from '../core/hooks'
|
|
|
33
33
|
import { registerBuiltinHooks } from '../core/merge-gate'
|
|
34
34
|
import { loadHookConfigs } from '../core/hooks-config'
|
|
35
35
|
import { isSafeMode } from '../core/safe-mode'
|
|
36
|
-
import { loadSettingsJson } from '../config/loader'
|
|
36
|
+
import { loadReviewGateConfig, loadVerificationConfig, loadSettingsJson } from '../config/loader'
|
|
37
|
+
import { createReviewRunner } from '../core/review-gate'
|
|
37
38
|
import { getWorkspaceTrust, warnProjectHooksSkipped } from '../core/workspace-trust'
|
|
38
39
|
import { AgentRegistry } from '../agent/agent-registry'
|
|
39
40
|
import { InstructionsLoader } from '../core/instructions'
|
|
@@ -223,6 +224,26 @@ export function wireDaemonEngine(engine: QueryEngine, opts: DaemonEngineCapabili
|
|
|
223
224
|
// 语义等价于不接(`llmChat` 本就是 `this.llm ?? this.registry`),接上是为了让
|
|
224
225
|
// 两个入口的能力集合真的相等;D2 靠它证明「先修语义再对等」这条顺序约束。
|
|
225
226
|
engine.setLlm(opts.registry)
|
|
227
|
+
|
|
228
|
+
// Review gate: same factory as the interactive CLI. `cwd` is the **session's**,
|
|
229
|
+
// not the daemon process's — reviewing the wrong tree is worse than not
|
|
230
|
+
// reviewing, and passing it as `worktreePath` would also write a trust entry.
|
|
231
|
+
engine.setReviewGate({
|
|
232
|
+
...loadReviewGateConfig(),
|
|
233
|
+
cwd: opts.cwd,
|
|
234
|
+
runner: createReviewRunner({
|
|
235
|
+
registry: opts.registry,
|
|
236
|
+
toolRegistry: engine.getTools(),
|
|
237
|
+
permission: engine.getPermission(),
|
|
238
|
+
services: engine.getSubAgentServices(),
|
|
239
|
+
}),
|
|
240
|
+
})
|
|
241
|
+
|
|
242
|
+
// Verification baseline: observation only, session cwd (same as the reviewer).
|
|
243
|
+
engine.setVerificationBaseline({
|
|
244
|
+
...loadVerificationConfig(),
|
|
245
|
+
cwd: opts.cwd,
|
|
246
|
+
})
|
|
226
247
|
}
|
|
227
248
|
|
|
228
249
|
/**
|
package/src/daemon/launch.ts
CHANGED
|
@@ -258,9 +258,19 @@ export async function startDetachedDaemon(
|
|
|
258
258
|
if (status) return { ok: true, pid: status.pid, port: status.port }
|
|
259
259
|
if (exitCode !== null) {
|
|
260
260
|
const tail = tailLog(plan.logPath)
|
|
261
|
+
// A denied folder is the macOS failure users hit most, and the log line
|
|
262
|
+
// is a bare EPERM/EACCES. Name the setting to check instead of leaving
|
|
263
|
+
// them to guess which sandbox refused (CC 2.1.333-158).
|
|
264
|
+
const privacyHint =
|
|
265
|
+
process.platform === 'darwin' &&
|
|
266
|
+
/eacces|eperm|operation not permitted|permission denied/i.test(tail)
|
|
267
|
+
? '\nOn macOS this can mean the daemon may not read the project folder — check ' +
|
|
268
|
+
'System Settings → Privacy & Security → Files and Folders (or Full Disk Access) ' +
|
|
269
|
+
'for your terminal.'
|
|
270
|
+
: ''
|
|
261
271
|
return {
|
|
262
272
|
ok: false,
|
|
263
|
-
reason: `daemon exited with code ${exitCode}${tail ? `:\n${tail}` : ''}`,
|
|
273
|
+
reason: `daemon exited with code ${exitCode}${tail ? `:\n${tail}` : ''}${privacyHint}`,
|
|
264
274
|
}
|
|
265
275
|
}
|
|
266
276
|
}
|