@miphamai/cli 0.85.39 → 0.85.41

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 CHANGED
@@ -1,4 +1,4 @@
1
- # Mipham Code v0.85.39
1
+ # Mipham Code v0.85.41
2
2
 
3
3
  **Multi-model open-core intelligent coding terminal** — 12 AI providers, 139 commands, 31 tools, 28 skills + marketplace, self-update. AI-assisted code generation, security auditing, MCP protocol, and extensible skills — in a single CLI.
4
4
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miphamai/cli",
3
- "version": "0.85.39",
3
+ "version": "0.85.41",
4
4
  "description": "Mipham Code — Multi-model open-core intelligent coding terminal by MiphamAI",
5
5
  "keywords": [
6
6
  "ai",
@@ -12,16 +12,19 @@
12
12
 
13
13
  ### GET /health
14
14
 
15
- 健康检查,返回连接状态。
15
+ 健康检查。`status` 为 `ok` **仅当已连上 Chrome**;未连接时为 `disconnected`,`lastError` 说明原因(多半是 Chrome 远程调试未授权)。`connected` 是布尔值。
16
16
 
17
17
  ```bash
18
18
  curl -s http://localhost:3456/health
19
+ # {"status":"ok","connected":true,"lastError":null,"chromePort":9222,"lastSeenChromePort":9222,...}
19
20
  ```
20
21
 
21
22
  ### GET /targets
22
23
 
23
24
  列出所有已打开的页面 tab。返回数组,每项含 `targetId`、`title`、`url`。
24
25
 
26
+ 连不上 Chrome 时返回 HTTP 500,body 含 `error`(原因)与 `hint`(下一步)。**不要**把这种情况读成「localhost 不通」:能收到这个 500 就说明代理可达。
27
+
25
28
  ```bash
26
29
  curl -s http://localhost:3456/targets
27
30
  ```
@@ -13,6 +13,11 @@ import crypto from 'node:crypto'
13
13
 
14
14
  const PORT = parseInt(process.env.CDP_PROXY_PORT || '3456')
15
15
  let ws = null
16
+ // 诊断用:Chrome 连不上时,/health 与 /targets 都要能说出原因,
17
+ // 否则调用方只能看到 `connected: null` + `{"error":"连接失败"}`,
18
+ // 很容易把「Chrome 远程调试未授权」误判成「localhost 不通」。
19
+ let lastConnectError = null
20
+ let lastSeenChromePort = null
16
21
  let cmdId = 0
17
22
  const pending = new Map() // id -> {resolve, timer}
18
23
  const sessions = new Map() // targetId -> sessionId
@@ -196,6 +201,7 @@ async function connect() {
196
201
  chromePort = discovered.port
197
202
  chromeWsPath = discovered.wsPath
198
203
  }
204
+ lastSeenChromePort = chromePort
199
205
 
200
206
  const wsUrl = getWebSocketUrl(chromePort, chromeWsPath)
201
207
  if (!wsUrl) throw new Error('无法获取 Chrome WebSocket URL')
@@ -206,6 +212,7 @@ async function connect() {
206
212
  const onOpen = () => {
207
213
  cleanup()
208
214
  connectingPromise = null
215
+ lastConnectError = null
209
216
  console.log(`[CDP Proxy] 已连接 Chrome (端口 ${chromePort})`)
210
217
  resolve()
211
218
  }
@@ -215,12 +222,18 @@ async function connect() {
215
222
  ws = null
216
223
  chromePort = null
217
224
  chromeWsPath = null
218
- const msg = e.message || e.error?.message || '连接失败'
225
+ // 原生 WebSocket 的 error 事件常常没有 message(Chrome 未授权时握手被拒),
226
+ // 落到「连接失败」四个字上等于什么都没说。
227
+ const msg = e.message || e.error?.message || 'Chrome 拒绝了调试连接(远程调试尚未授权)'
228
+ lastConnectError = msg
219
229
  console.error('[CDP Proxy] 连接错误:', msg, '(端口缓存已清除,下次将重新发现)')
220
230
  reject(new Error(msg))
221
231
  }
222
232
  const onClose = () => {
223
233
  console.log('[CDP Proxy] 连接断开')
234
+ // 握手失败时 onError 先给出可行动的原因,onClose 紧随其后把状态清空。
235
+ // 不要用「连接已断开」盖掉那句话 —— 它才是调用方能据以行动的东西。
236
+ if (!lastConnectError) lastConnectError = 'Chrome 连接已断开'
224
237
  ws = null
225
238
  chromePort = null // 重置端口缓存,下次连接重新发现
226
239
  chromeWsPath = null
@@ -414,16 +427,19 @@ const server = http.createServer(async (req, res) => {
414
427
  res.setHeader('Content-Type', 'application/json; charset=utf-8')
415
428
 
416
429
  try {
417
- // /health 不需要连接 Chrome
430
+ // /health 不需要连接 Chrome,但**必须如实报告没连上**:
431
+ // 一个在坏掉时说 ok 的健康检查,只会把调用方推向错误的根因。
418
432
  if (pathname === '/health') {
419
- const connected = ws && (ws.readyState === WS.OPEN || ws.readyState === 1)
433
+ const connected = !!(ws && (ws.readyState === WS.OPEN || ws.readyState === 1))
420
434
  res.end(
421
435
  JSON.stringify({
422
- status: 'ok',
436
+ status: connected ? 'ok' : 'disconnected',
423
437
  connected,
438
+ lastError: connected ? null : lastConnectError,
439
+ chromePort,
440
+ lastSeenChromePort,
424
441
  sessions: sessions.size,
425
442
  managedTabs: managedTabs.size,
426
- chromePort,
427
443
  }),
428
444
  )
429
445
  return
@@ -437,7 +453,22 @@ const server = http.createServer(async (req, res) => {
437
453
  return
438
454
  }
439
455
 
440
- await connect()
456
+ try {
457
+ await connect()
458
+ } catch (e) {
459
+ // 调用方拿到的是「连不上」时唯一能据以行动的东西:原因 + 下一步。
460
+ res.statusCode = 500
461
+ res.end(
462
+ JSON.stringify({
463
+ error: `Chrome 未连接:${lastConnectError || e.message || '未知原因'}`,
464
+ hint: lastSeenChromePort
465
+ ? `调试端口 ${lastSeenChromePort} 是开着的,但 Chrome 没有允许远程调试。请在 Chrome 打开 chrome://inspect/#remote-debugging 勾选 Allow remote debugging(或点弹窗的「允许」)后重试。`
466
+ : '未发现 Chrome 调试端口。请确认 Chrome 正在运行,并在 chrome://inspect/#remote-debugging 勾选 Allow remote debugging。',
467
+ chromePort: lastSeenChromePort,
468
+ }),
469
+ )
470
+ return
471
+ }
441
472
 
442
473
  // GET /targets - 列出所有页面
443
474
  if (pathname === '/targets') {
@@ -779,7 +810,9 @@ async function main() {
779
810
  .get(`http://127.0.0.1:${PORT}/health`, { timeout: 2000 }, (res) => {
780
811
  let d = ''
781
812
  res.on('data', (c) => (d += c))
782
- res.on('end', () => resolve(d.includes('"ok"')))
813
+ // 只要回的是本 proxy 的 JSON 就算同一实例 —— status 可能是
814
+ // 'ok' 或 'disconnected',后者照样说明端口上是 proxy 而不是别人。
815
+ res.on('end', () => resolve(d.includes('"status"')))
783
816
  })
784
817
  .on('error', () => resolve(false))
785
818
  })
@@ -73,6 +73,24 @@ function activePortFiles() {
73
73
  }
74
74
  }
75
75
 
76
+ /**
77
+ * Chrome 的调试 HTTP 端点在「允许远程调试」之前会回 404/403。
78
+ * 所以 TCP 端口通 ≠ 可调试:只探端口会打印 `chrome: ok`,而代理永远连不上。
79
+ */
80
+ async function probeChromeHttp(port, timeoutMs = 2000) {
81
+ try {
82
+ const res = await fetch(`http://127.0.0.1:${port}/json/version`, {
83
+ signal: AbortSignal.timeout(timeoutMs),
84
+ })
85
+ const body = await res.text()
86
+ if (!res.ok) return { ok: false, status: res.status }
87
+ JSON.parse(body) // 必须是真的 Chrome 调试端点,不是同端口上的别的东西
88
+ return { ok: true, status: res.status }
89
+ } catch {
90
+ return { ok: false, status: 0 }
91
+ }
92
+ }
93
+
76
94
  async function detectChromePort() {
77
95
  // 优先从 DevToolsActivePort 文件读取
78
96
  for (const filePath of activePortFiles()) {
@@ -133,6 +151,18 @@ function startProxyDetached() {
133
151
  fs.closeSync(logFd)
134
152
  }
135
153
 
154
+ async function proxyHealth() {
155
+ try {
156
+ const res = await fetch(`http://127.0.0.1:${PROXY_PORT}/health`, {
157
+ signal: AbortSignal.timeout(2000),
158
+ })
159
+ if (!res.ok) return null
160
+ return await res.json()
161
+ } catch {
162
+ return null
163
+ }
164
+ }
165
+
136
166
  async function ensureProxy() {
137
167
  const targetsUrl = `http://127.0.0.1:${PROXY_PORT}/targets`
138
168
 
@@ -143,7 +173,15 @@ async function ensureProxy() {
143
173
  return true
144
174
  }
145
175
 
146
- // 未运行或未连接,启动并等待
176
+ // proxy 活着但 Chrome 没连上:再拉起一个实例只会撞端口,
177
+ // 真正该做的是把原因说清楚(多半是远程调试还没授权)。
178
+ const health = await proxyHealth()
179
+ if (health) {
180
+ console.log(`proxy: running, but Chrome is not connected — ${health.lastError || '原因未知'}`)
181
+ return false
182
+ }
183
+
184
+ // 未运行,启动并等待
147
185
  console.log('proxy: connecting...')
148
186
  startProxyDetached()
149
187
 
@@ -162,7 +200,12 @@ async function ensureProxy() {
162
200
  await new Promise((r) => setTimeout(r, 1000))
163
201
  }
164
202
 
165
- console.log('❌ 连接超时,请检查 Chrome 调试设置')
203
+ const healthAfter = await proxyHealth()
204
+ console.log(
205
+ healthAfter
206
+ ? `❌ Chrome 未连接:${healthAfter.lastError || '原因未知'}`
207
+ : '❌ CDP Proxy 未能启动,请检查日志',
208
+ )
166
209
  console.log(` 日志:${path.join(os.tmpdir(), 'cdp-proxy.log')}`)
167
210
  return false
168
211
  }
@@ -179,6 +222,16 @@ async function main() {
179
222
  )
180
223
  process.exit(1)
181
224
  }
225
+ // TCP 开着不代表能调试:Chrome 136+ 在「允许远程调试」前会让 /json/* 回 404/403。
226
+ const probe = await probeChromeHttp(chromePort)
227
+ if (!probe.ok) {
228
+ console.log(
229
+ `chrome: not authorized (port ${chromePort}${probe.status ? `, HTTP ${probe.status}` : ',无响应'})` +
230
+ ' — 远程调试尚未允许。请在 Chrome 打开 chrome://inspect/#remote-debugging 勾选 ' +
231
+ 'Allow remote debugging(或点弹窗的「允许」),然后重试。',
232
+ )
233
+ process.exit(1)
234
+ }
182
235
  console.log(`chrome: ok (port ${chromePort})`)
183
236
 
184
237
  const proxyOk = await ensureProxy()
@@ -26,6 +26,9 @@ node ~/.mipham/skills/web-access/scripts/check-deps.mjs
26
26
 
27
27
  > Mipham Code 环境:`node` 不可用时可用 `bun` 替代(Bun 原生支持 WebSocket 与 node: 内建)。未通过时引导用户:Chrome 地址栏打开 `chrome://inspect/#remote-debugging`,勾选 "Allow remote debugging for this browser instance"。
28
28
 
29
+ > **判读输出**:`chrome: ok` = 调试端点已授权;`chrome: not authorized` = 端口开着但 Chrome 没允许远程调试(去 `chrome://inspect/#remote-debugging` 勾 Allow,或点弹窗「允许」);`proxy: running, but Chrome is not connected` = 代理活着、Chrome 没授权。
30
+ > **不要**把以上任何一种读成「Bash 没有网络」:`curl -s http://127.0.0.1:3456/health` 能回 200 就证明 localhost 是通的,真正原因在 `lastError` 字段里。
31
+
29
32
  **必须向用户展示**:部分站点对浏览器自动化检测严格,存在账号封禁风险。已内置防护但无法完全避免,Agent 继续操作即视为接受。
30
33
 
31
34
  ## 工具选择
@@ -40,6 +43,8 @@ node ~/.mipham/skills/web-access/scripts/check-deps.mjs
40
43
 
41
44
  浏览器 CDP 不要求 URL 已知;WebSearch/WebFetch/curl 均不处理登录态。
42
45
 
46
+ > 搜索引擎结果页(Google / Bing / DuckDuckGo / Brave / Mojeek)对 WebFetch/curl 普遍回 403/429 或验证码。需要搜索时**在 Chrome 里打开引擎页**再用 `/eval` 提取结果,不要用 WebFetch 抓结果页。
47
+
43
48
  ## 浏览器 CDP 模式
44
49
 
45
50
  通过 CDP Proxy 直连用户日常 Chrome,天然携带登录态。**不主动操作用户已有 tab**,所有操作在自己创建的后台 tab 中进行,任务结束关闭自建 tab(保留用户原 tab)。
@@ -46,6 +46,17 @@ Question involves...
46
46
 
47
47
  ---
48
48
 
49
+ ### No API key? Do not scrape search engines
50
+
51
+ If `WebSearch` answers "not configured", **do not** fetch search-engine result pages with
52
+ `WebFetch` or `curl`. Google / Bing / DuckDuckGo / Brave / Mojeek all answer automated
53
+ requests with 403, 429 or a captcha — five calls later you have nothing.
54
+
55
+ Go straight to the `web-access` skill: open the search engine **in Chrome** (logged-in
56
+ profile, real fingerprint), then read the result list with `/eval`.
57
+
58
+ ---
59
+
49
60
  ## Phase 1: Construct the Query
50
61
 
51
62
  ### Rules (apply in order)
@@ -170,7 +181,5 @@ If search returns "not configured":
170
181
  2. Set: `export BRAVE_API_KEY="BSA..."`
171
182
  3. Restart Mipham Code
172
183
 
173
- Alternatives (additional API keys supported):
174
-
175
- - `TAVILY_API_KEY` — https://tavily.com
176
- - `SERPAPI_API_KEY` — https://serpapi.com
184
+ Only `BRAVE_API_KEY` is read. There is no Tavily / SerpAPI path in this build — setting
185
+ those variables has no effect.
@@ -0,0 +1,142 @@
1
+ /**
2
+ * 捕获率的编排层(有 LLM 调用、有子进程判定),算术全在 `capture-rate.ts`。
3
+ *
4
+ * 三臂:`off`(不注入)· `on`(注入被测 skill 文本)· `oracle`(手写参考解,
5
+ * **零 LLM 调用**,本地跑该题的冻结测试)。sealed 只作为**旁证读数**给出,
6
+ * 永不进入任何裁定。
7
+ */
8
+
9
+ import type { Llm } from '../providers/llm'
10
+ import {
11
+ judgeGeneratedCode,
12
+ loadPerformanceTasks,
13
+ runTaskPerformance,
14
+ type PerformanceTask,
15
+ type TaskPerformanceReport,
16
+ } from './task-performance'
17
+ import { computeCapture, perTaskValue, type CaptureResult } from './capture-rate'
18
+
19
+ export interface CaptureMeasurement {
20
+ /** k 次 off 运行(不注入)。 */
21
+ off: TaskPerformanceReport[]
22
+ /** k 次 on 运行(注入 skillText)。 */
23
+ on: TaskPerformanceReport[]
24
+ capture: CaptureResult
25
+ /** 参考解是否全部通过自己的冻结测试。false ⇒ 上界不可信,整轮作废。 */
26
+ oraclePassed: boolean
27
+ /**
28
+ * 正对照:把**同一臂**的读数喂给两侧,捕获率必须恰好为 0。
29
+ * 不为 0 ⇒ 分子/分母/臂映射至少有一处接错了,整轮的其它读数都不可信。
30
+ */
31
+ controlRate: number | null
32
+ /** sealed 池的同一套测量。每组只有 1 题,故它只是过拟合旁证,不是第二读数。 */
33
+ sealed: { capture: CaptureResult; oraclePassed: boolean }
34
+ }
35
+
36
+ interface Arms {
37
+ off: TaskPerformanceReport[]
38
+ on: TaskPerformanceReport[]
39
+ capture: CaptureResult
40
+ }
41
+
42
+ async function runArms(
43
+ llm: Llm,
44
+ tasks: PerformanceTask[],
45
+ skillText: string,
46
+ k: number,
47
+ timeoutMs?: number,
48
+ ): Promise<Arms> {
49
+ const off: TaskPerformanceReport[] = []
50
+ const on: TaskPerformanceReport[] = []
51
+ const timeout = timeoutMs ? { timeoutMs } : {}
52
+ for (let i = 0; i < k; i++) off.push(await runTaskPerformance(llm, { tasks, ...timeout }))
53
+ for (let i = 0; i < k; i++) {
54
+ on.push(await runTaskPerformance(llm, { tasks, skillText, ...timeout }))
55
+ }
56
+
57
+ const toArm = (values: Map<string, number | null>) =>
58
+ [...values].map(([taskId, value]) => ({ taskId, value }))
59
+
60
+ const capture = computeCapture({
61
+ off: toArm(
62
+ perTaskValue(
63
+ off.flatMap((r) => r.results),
64
+ k,
65
+ ),
66
+ ),
67
+ on: toArm(
68
+ perTaskValue(
69
+ on.flatMap((r) => r.results),
70
+ k,
71
+ ),
72
+ ),
73
+ total: tasks.length,
74
+ })
75
+ return { off, on, capture }
76
+ }
77
+
78
+ export async function measureCapture(
79
+ llm: Llm,
80
+ opts: { skillName: string; skillText: string; k?: number; timeoutMs?: number },
81
+ ): Promise<CaptureMeasurement> {
82
+ const k = opts.k ?? 3
83
+ const all = loadPerformanceTasks({ pool: 'all' })
84
+ const gateTasks = all.filter((t) => t.skill === opts.skillName && t.split === 'gate')
85
+ const sealedTasks = all.filter((t) => t.skill === opts.skillName && t.split === 'sealed')
86
+
87
+ const gate = await runArms(llm, gateTasks, opts.skillText, k, opts.timeoutMs)
88
+ const sealed = await runArms(llm, sealedTasks, opts.skillText, k, opts.timeoutMs)
89
+
90
+ // 正对照:同一臂两侧相等 ⇒ 率必须为 0。零成本,且能抓到臂接反/池映射错。
91
+ // 取 **off 臂**:它的 headroom 正是真实率的分母,故真实率非 null 时这里必然也可算
92
+ // (off 全满分的轮次本来就没有率,不需要另立一条「对照失效」的判据)。
93
+ const offArm = [
94
+ ...perTaskValue(
95
+ gate.off.flatMap((r) => r.results),
96
+ k,
97
+ ),
98
+ ].map(([taskId, value]) => ({
99
+ taskId,
100
+ value,
101
+ }))
102
+ const control = computeCapture({ off: offArm, on: offArm, total: gateTasks.length })
103
+
104
+ const oraclePassed = gateTasks.every((t) => judgeGeneratedCode(t.testCode, t.oracleCode).passed)
105
+ const sealedOraclePassed = sealedTasks.every(
106
+ (t) => judgeGeneratedCode(t.testCode, t.oracleCode).passed,
107
+ )
108
+
109
+ return {
110
+ off: gate.off,
111
+ on: gate.on,
112
+ capture: gate.capture,
113
+ oraclePassed,
114
+ controlRate: control.rate,
115
+ sealed: { capture: sealed.capture, oraclePassed: sealedOraclePassed },
116
+ }
117
+ }
118
+
119
+ export interface SealedMeasurement {
120
+ off: TaskPerformanceReport[]
121
+ on: TaskPerformanceReport[]
122
+ capture: CaptureResult
123
+ /** 参考解是否全过自己的冻结测试。false ⇒ 读数不可信。 */
124
+ oraclePassed: boolean
125
+ }
126
+
127
+ /**
128
+ * 只跑 sealed 池的独立读面(`/crsi bench --sealed`,设计 §4.3)。
129
+ *
130
+ * 它比 `--capture` 便宜(不跑 gate 臂),答的是同一个问题的一半:这份 skill 在
131
+ * **没参与调参**的题上还吃得到多少。缺省 k=1 —— 它出的不是裁定数,是旁证数。
132
+ */
133
+ export async function measureSealed(
134
+ llm: Llm,
135
+ opts: { skillName: string; skillText: string; k?: number; timeoutMs?: number },
136
+ ): Promise<SealedMeasurement> {
137
+ const k = opts.k ?? 1
138
+ const tasks = loadPerformanceTasks({ pool: 'sealed' }).filter((t) => t.skill === opts.skillName)
139
+ const arms = await runArms(llm, tasks, opts.skillText, k, opts.timeoutMs)
140
+ const oraclePassed = tasks.every((t) => judgeGeneratedCode(t.testCode, t.oracleCode).passed)
141
+ return { off: arms.off, on: arms.on, capture: arms.capture, oraclePassed }
142
+ }
@@ -0,0 +1,149 @@
1
+ /**
2
+ * 捕获率:`(on − off) / (100 − off)` —— 自动改进捕获了「满分上界」的百分之几。
3
+ *
4
+ * 纯算术,无 LLM、无 I/O:题与样本由调用方给。设计约束见
5
+ * `docs/superpowers/specs/2026-11-20-crsi-eval-governance-design.md` §4.2:
6
+ * - headroom `100 − off` 不为正的题 **剔除**(分母不许注水);
7
+ * - 任一侧无合格样本的题 **配对剔除**(不拿半份样本凑数);
8
+ * - 题全被剔除 ⇒ **没有率**(`null`),不是 0,也不是 1。
9
+ */
10
+
11
+ export interface ArmValue {
12
+ taskId: string
13
+ /** 该题在该臂上的 0–100 读数;`null` = 没有合格样本。 */
14
+ value: number | null
15
+ }
16
+
17
+ export interface CaptureInput {
18
+ off: ArmValue[]
19
+ on: ArmValue[]
20
+ /** 组内题数 M(含被剔除的),用于报告 "over N of M tasks"。 */
21
+ total: number
22
+ }
23
+
24
+ export interface CaptureResult {
25
+ numerator: number
26
+ denominator: number
27
+ rate: number | null
28
+ tasksUsed: number
29
+ tasksTotal: number
30
+ noHeadroom: string[]
31
+ dropped: string[]
32
+ ci: { lo: number; hi: number } | null
33
+ }
34
+
35
+ /** 每题每臂的 0–100 读数。合格样本不足 k 次 ⇒ `null`(配对剔除的一半)。 */
36
+ export function perTaskValue(
37
+ results: { id: string; passed: boolean; truncated?: boolean; uncertain?: boolean }[],
38
+ k: number,
39
+ ): Map<string, number | null> {
40
+ const acc = new Map<string, { pass: number; usable: number }>()
41
+ for (const r of results) {
42
+ const entry = acc.get(r.id) ?? { pass: 0, usable: 0 }
43
+ if (!r.truncated && !r.uncertain) {
44
+ entry.usable++
45
+ if (r.passed) entry.pass++
46
+ }
47
+ acc.set(r.id, entry)
48
+ }
49
+ const out = new Map<string, number | null>()
50
+ for (const [id, entry] of acc) {
51
+ out.set(id, entry.usable === k ? (entry.pass / entry.usable) * 100 : null)
52
+ }
53
+ return out
54
+ }
55
+
56
+ function mulberry32(seed: number): () => number {
57
+ let a = seed
58
+ return () => {
59
+ a += 0x6d2b79f5
60
+ let t = a
61
+ t = Math.imul(t ^ (t >>> 15), t | 1)
62
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
63
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
64
+ }
65
+ }
66
+
67
+ function quantile(sorted: number[], q: number): number {
68
+ const pos = (sorted.length - 1) * q
69
+ const lo = Math.floor(pos)
70
+ const hi = Math.ceil(pos)
71
+ if (lo === hi) return sorted[lo]!
72
+ return sorted[lo]! + (sorted[hi]! - sorted[lo]!) * (pos - lo)
73
+ }
74
+
75
+ export function computeCapture(
76
+ input: CaptureInput,
77
+ opts?: { resamples?: number; seed?: number },
78
+ ): CaptureResult {
79
+ const onById = new Map(input.on.map((v) => [v.taskId, v.value]))
80
+ const noHeadroom: string[] = []
81
+ const dropped: string[] = []
82
+ const pairs: { off: number; on: number }[] = []
83
+
84
+ for (const o of input.off) {
85
+ const onValue = onById.get(o.taskId) ?? null
86
+ if (o.value === null || onValue === null) {
87
+ dropped.push(o.taskId)
88
+ continue
89
+ }
90
+ if (100 - o.value <= 0) {
91
+ noHeadroom.push(o.taskId)
92
+ continue
93
+ }
94
+ pairs.push({ off: o.value, on: onValue })
95
+ }
96
+
97
+ let numerator = 0
98
+ let denominator = 0
99
+ for (const p of pairs) {
100
+ numerator += p.on - p.off
101
+ denominator += 100 - p.off
102
+ }
103
+
104
+ if (denominator === 0) {
105
+ return {
106
+ numerator,
107
+ denominator,
108
+ rate: null,
109
+ tasksUsed: 0,
110
+ tasksTotal: input.total,
111
+ noHeadroom,
112
+ dropped,
113
+ ci: null,
114
+ }
115
+ }
116
+
117
+ const rate = numerator / denominator
118
+ const resamples = opts?.resamples ?? 1000
119
+ const random = mulberry32(opts?.seed ?? 42)
120
+ const rates: number[] = []
121
+ for (let i = 0; i < resamples; i++) {
122
+ let num = 0
123
+ let den = 0
124
+ for (let j = 0; j < pairs.length; j++) {
125
+ // `pairs` 在进入重采样前已剔掉 no-headroom / 缺样本的题,抽到的每一题都可计。
126
+ const pick = pairs[Math.floor(random() * pairs.length)]!
127
+ num += pick.on - pick.off
128
+ den += 100 - pick.off
129
+ }
130
+ if (den > 0) rates.push(num / den)
131
+ }
132
+
133
+ let ci: { lo: number; hi: number } | null = null
134
+ if (rates.length >= 2) {
135
+ rates.sort((a, b) => a - b)
136
+ ci = { lo: quantile(rates, 0.025), hi: quantile(rates, 0.975) }
137
+ }
138
+
139
+ return {
140
+ numerator,
141
+ denominator,
142
+ rate,
143
+ tasksUsed: pairs.length,
144
+ tasksTotal: input.total,
145
+ noHeadroom,
146
+ dropped,
147
+ ci,
148
+ }
149
+ }
@@ -26,6 +26,7 @@ import {
26
26
  regressedAnchors,
27
27
  } from './eval-harness'
28
28
  import { mechanismSentinel, type RewardFn, type ScoreReport } from './reward-fn'
29
+ import { openProbation, recordNoInstrument } from './probation'
29
30
 
30
31
  export interface CrsiProposal {
31
32
  /** 人类可读的改动说明 */
@@ -64,6 +65,30 @@ export interface CrsiProposal {
64
65
  // 模块级单例:成功跑完测试的修改停在这里,等待人类 approve / reject。
65
66
  let pendingSandbox: CrsiSandbox | null = null
66
67
 
68
+ /**
69
+ * 与 `pendingSandbox` 同生命周期的试用期基线。
70
+ *
71
+ * **为什么由调用方事后设置**:真实调用顺序是 `runCrsiModification` → `measureModification`
72
+ * (测量排在沙箱之后,避免 failed proposal 白跑 LLM)。所以基线不可能作为
73
+ * `runCrsiModification` 的入参 —— 它在那一刻还不存在。
74
+ */
75
+ export interface PendingProbation {
76
+ filePath: string
77
+ skillName: string
78
+ baselineScores: number[]
79
+ poolSize: number
80
+ }
81
+
82
+ let pendingProbation: PendingProbation | null = null
83
+
84
+ /** 待合并改动的目标文件 —— `approvePending` 用它登记「没有随机仪器」的那句话。 */
85
+ let pendingFilePath: string | null = null
86
+
87
+ /** 设置/清空待合并的试用期基线(清空用 `null`)。 */
88
+ export function setPendingProbation(probation: PendingProbation | null): void {
89
+ pendingProbation = probation
90
+ }
91
+
67
92
  /**
68
93
  * 编排完整 5 阶段:createWorktree → applyModification → runTests →(失败自动
69
94
  * rollback)→ getDiff。测试通过后暂存为 pending,返回 diff 供人类审阅。
@@ -112,6 +137,9 @@ export async function runCrsiModification(
112
137
  }
113
138
  }
114
139
 
140
+ // 新的修改使上一次的测量失效 —— 不让旧基线挂到新合并上。
141
+ pendingProbation = null
142
+ pendingFilePath = proposal.filePath
115
143
  sandbox.createWorktree()
116
144
 
117
145
  const applied = sandbox.applyModification({
@@ -236,15 +264,33 @@ export function hasPending(): boolean {
236
264
  return pendingSandbox !== null
237
265
  }
238
266
 
239
- /** 人类批准:merge 进仓库并清理 worktree。 */
240
- export function approvePending(): { success: boolean; message: string } {
267
+ /** 人类批准:merge 进仓库并清理 worktree;成功且有测量时开试用期。 */
268
+ export function approvePending(): {
269
+ success: boolean
270
+ message: string
271
+ probationOpened?: boolean
272
+ } {
241
273
  if (!pendingSandbox) {
242
274
  return { success: false, message: '没有待批准的修改。先运行 /crsi modify。' }
243
275
  }
244
276
  const sandbox = pendingSandbox
277
+ const probation = pendingProbation
278
+ const filePath = pendingFilePath
245
279
  pendingSandbox = null
280
+ pendingProbation = null
281
+ pendingFilePath = null
246
282
  const merged = sandbox.merge()
247
283
  sandbox.finalize()
284
+ if (merged.success && merged.commitHash) {
285
+ if (probation) {
286
+ openProbation({ ...probation, commitHash: merged.commitHash })
287
+ return { ...merged, probationOpened: true }
288
+ }
289
+ // 没有随机仪器也要**说出来**:静默跳过会让这次合并在 stats 里完全消失。
290
+ if (filePath) {
291
+ recordNoInstrument({ filePath, commitHash: merged.commitHash })
292
+ }
293
+ }
248
294
  return merged
249
295
  }
250
296
 
@@ -255,5 +301,7 @@ export function rejectPending(): { success: boolean; message: string } {
255
301
  }
256
302
  const sandbox = pendingSandbox
257
303
  pendingSandbox = null
304
+ pendingProbation = null
305
+ pendingFilePath = null
258
306
  return sandbox.rollback()
259
307
  }