@miphamai/cli 0.85.40 → 0.85.42

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.
@@ -0,0 +1,171 @@
1
+ /**
2
+ * 试用期(probation):合并之后、裁定之前。
3
+ *
4
+ * `/crsi modify --approve` 是终态 —— 合并后变坏只能靠人事后发现。本模块给
5
+ * **有一次任务表现测量**的合并开一个观察窗:后续同口径重测满 N 次时出裁定;
6
+ * 判为退化**只打印** `git revert <sha>`,**不执行**(破坏性 git 由人敲)。
7
+ *
8
+ * 边界(刻意):没有随机信号就没有观察窗 —— `core/*.ts` 的合并不开窗,
9
+ * 由 `/crsi stats` 明说「没有可用仪器」,而不是静默跳过。
10
+ */
11
+
12
+ import { randomUUID } from 'node:crypto'
13
+ import { existsSync, mkdirSync, readFileSync } from 'node:fs'
14
+ import { atomicWriteFileSync } from '../shared/atomic-write'
15
+ import { miphamHome } from './paths.ts'
16
+ import { classifyDelta, computeMinEffect, type ImprovementVerdict } from './improvement-track'
17
+
18
+ /** 观察窗长度:同一 skill、同一 gate 池、k≥3 的重测次数。 */
19
+ export const PROBATION_WINDOW = 3
20
+
21
+ export interface ProbationRecord {
22
+ id: string
23
+ filePath: string
24
+ skillName: string
25
+ commitHash: string
26
+ /** 合并时的 k 个 post 臂采样(不是标量:噪声要用它估)。 */
27
+ baselineScores: number[]
28
+ /** 观察窗内每次同口径重测。 */
29
+ checks: number[]
30
+ /** 组内 gate 题数 —— 地板 = 两题步长 = `2 × (100 / poolSize)`。 */
31
+ poolSize: number
32
+ /** 窗口未满时**缺席**(与 `inconclusive` 不同形)。 */
33
+ verdict?: ImprovementVerdict
34
+ /**
35
+ * 这次合并没有任何随机仪器可用(例如改了 `core/*.ts`)。
36
+ * 登记它是为了**说出来** —— 静默跳过会让「没有仪器」和「没有合并」同形。
37
+ */
38
+ noInstrument?: true
39
+ timestamp: string
40
+ }
41
+
42
+ export function probationPath(): string {
43
+ return miphamHome('crsi', 'probation.jsonl')
44
+ }
45
+
46
+ export function readProbations(): ProbationRecord[] {
47
+ const file = probationPath()
48
+ if (!existsSync(file)) return []
49
+ return readFileSync(file, 'utf-8')
50
+ .split('\n')
51
+ .filter((line) => line.trim() !== '')
52
+ .flatMap((line) => {
53
+ try {
54
+ return [JSON.parse(line) as ProbationRecord]
55
+ } catch {
56
+ return [] // 残留坏行跳过,不抛(与引入台账同口径)
57
+ }
58
+ })
59
+ }
60
+
61
+ function writeProbations(records: ProbationRecord[]): void {
62
+ mkdirSync(miphamHome('crsi'), { recursive: true })
63
+ atomicWriteFileSync(
64
+ probationPath(),
65
+ records.map((r) => JSON.stringify(r)).join('\n') + (records.length > 0 ? '\n' : ''),
66
+ )
67
+ }
68
+
69
+ function mean(xs: number[]): number {
70
+ return xs.length === 0 ? 0 : xs.reduce((a, b) => a + b, 0) / xs.length
71
+ }
72
+
73
+ function stdDev(xs: number[]): number {
74
+ if (xs.length < 2) return 0
75
+ const m = mean(xs)
76
+ const variance = xs.reduce((a, b) => a + (b - m) ** 2, 0) / (xs.length - 1)
77
+ return Math.sqrt(variance)
78
+ }
79
+
80
+ /** 地板 = 两题步长(4 题池即 50):单题翻转不判退化。 */
81
+ export function probationMinEffect(baseline: number[], checks: number[], poolSize: number): number {
82
+ const noise = Math.max(stdDev(baseline), stdDev(checks))
83
+ return computeMinEffect(noise, 2 * (100 / Math.max(1, poolSize)))
84
+ }
85
+
86
+ export function openProbation(
87
+ rec: Omit<ProbationRecord, 'id' | 'checks' | 'verdict' | 'timestamp'>,
88
+ ): void {
89
+ const records = readProbations()
90
+ records.push({
91
+ ...rec,
92
+ id: randomUUID(),
93
+ checks: [],
94
+ timestamp: new Date().toISOString(),
95
+ })
96
+ writeProbations(records)
97
+ }
98
+
99
+ /**
100
+ * 登记一次「没有随机仪器」的合并。它没有基线、永远不会结算 —— 存在的唯一目的
101
+ * 是让 `/crsi stats` 说得出这句话,而不是让这次合并从台账里消失。
102
+ */
103
+ export function recordNoInstrument(rec: { filePath: string; commitHash: string }): void {
104
+ const records = readProbations()
105
+ records.push({
106
+ id: randomUUID(),
107
+ filePath: rec.filePath,
108
+ skillName: rec.filePath,
109
+ commitHash: rec.commitHash,
110
+ baselineScores: [],
111
+ checks: [],
112
+ poolSize: 0,
113
+ noInstrument: true,
114
+ timestamp: new Date().toISOString(),
115
+ })
116
+ writeProbations(records)
117
+ }
118
+
119
+ /**
120
+ * 给最近一条未结的该 skill 记录追加一次读数。窗口满 N 次时写 verdict。
121
+ * 没有未结窗口 ⇒ `null`(不是抛错:调用方可能对任何 bench 结果都调一次)。
122
+ */
123
+ export function settleProbation(skillName: string, score: number): ProbationRecord | null {
124
+ const records = readProbations()
125
+ let idx = -1
126
+ for (let i = records.length - 1; i >= 0; i--) {
127
+ const r = records[i]!
128
+ if (!r.noInstrument && r.skillName === skillName && r.verdict === undefined) {
129
+ idx = i
130
+ break
131
+ }
132
+ }
133
+ if (idx < 0) return null
134
+
135
+ const rec = records[idx]!
136
+ const checks = [...rec.checks, score]
137
+ const updated: ProbationRecord = { ...rec, checks }
138
+ if (checks.length >= PROBATION_WINDOW) {
139
+ const minEffect = probationMinEffect(rec.baselineScores, checks, rec.poolSize)
140
+ updated.verdict = classifyDelta(mean(checks) - mean(rec.baselineScores), minEffect)
141
+ }
142
+ records[idx] = updated
143
+ writeProbations(records)
144
+ return updated
145
+ }
146
+
147
+ /** `/crsi stats` 的试用期段。空数组 = 没有试用期记录,不打任何行。 */
148
+ export function formatProbationLines(): string[] {
149
+ const records = readProbations()
150
+ if (records.length === 0) return []
151
+ const lines = ['', '### 试用期(probation)', '']
152
+ for (const r of records) {
153
+ if (r.noInstrument) {
154
+ lines.push(`- ${r.filePath}: no stochastic instrument for this merge`)
155
+ continue
156
+ }
157
+ const base = mean(r.baselineScores).toFixed(1)
158
+ if (r.verdict === undefined) {
159
+ lines.push(
160
+ `- ${r.skillName}: ${r.checks.length}/${PROBATION_WINDOW}(基线 ${base})—— 观察中`,
161
+ )
162
+ continue
163
+ }
164
+ lines.push(`- ${r.skillName}: ${r.verdict}(基线 ${base},${r.checks.length} 次重测)`)
165
+ if (r.verdict === 'regressed') {
166
+ // 只打印。破坏性 git 操作由人执行 —— 本模块不调用任何 git 命令。
167
+ lines.push(` - 建议回退:\`git revert ${r.commitHash}\``)
168
+ }
169
+ }
170
+ return lines
171
+ }
@@ -45,7 +45,15 @@ export function taskPerformanceRewardFn(llm: Llm): RewardFn {
45
45
  return {
46
46
  name: 'task-performance',
47
47
  description: 'LLM 生成 + 冻结测试评 skill/通用任务',
48
- evaluate: () => runTaskPerformance(llm),
48
+ // 没测到 ⇒ 抛错,让 `runCrsiModification` 走它已有的「量具不可用」分支。
49
+ // 返回 score=100 会让奖励闸把一次上游故障读成满分。
50
+ evaluate: async () => {
51
+ const report = await runTaskPerformance(llm)
52
+ if (!report.measurable) {
53
+ throw new Error('task-performance 未测到任何可评分样本(仪器/上游故障)')
54
+ }
55
+ return report
56
+ },
49
57
  }
50
58
  }
51
59
 
@@ -5,38 +5,131 @@
5
5
  "id": "perf-impl-quicksort",
6
6
  "category": "test-driven",
7
7
  "prompt": "实现并导出 quicksort 函数:export function quicksort(arr: number[]): number[]。只输出 TypeScript 代码,不要解释、不要 markdown 代码块。",
8
- "testCode": "import { test, expect } from 'bun:test'\nimport { quicksort } from './solution'\n\ntest('sorts numbers', () => {\n expect(quicksort([3, 1, 4, 1, 5, 9, 2, 6])).toEqual([1, 1, 2, 3, 4, 5, 6, 9])\n expect(quicksort([])).toEqual([])\n expect(quicksort([7])).toEqual([7])\n})\n"
8
+ "testCode": "import { test, expect } from 'bun:test'\nimport { quicksort } from './solution'\n\ntest('sorts numbers', () => {\n expect(quicksort([3, 1, 4, 1, 5, 9, 2, 6])).toEqual([1, 1, 2, 3, 4, 5, 6, 9])\n expect(quicksort([])).toEqual([])\n expect(quicksort([7])).toEqual([7])\n})\n",
9
+ "oracleCode": "export function quicksort(arr: number[]): number[] {\n return [...arr].sort((a, b) => a - b)\n}\n",
10
+ "split": "gate"
9
11
  },
10
12
  {
11
13
  "id": "perf-impl-fibonacci",
12
14
  "category": "test-driven",
13
15
  "prompt": "实现并导出 fibonacci 函数:export function fibonacci(n: number): number。返回第 n 项(fibonacci(0)=0, fibonacci(1)=1)。只输出 TypeScript 代码,不要解释、不要 markdown 代码块。",
14
- "testCode": "import { test, expect } from 'bun:test'\nimport { fibonacci } from './solution'\n\ntest('computes fibonacci', () => {\n expect(fibonacci(0)).toBe(0)\n expect(fibonacci(1)).toBe(1)\n expect(fibonacci(10)).toBe(55)\n expect(fibonacci(20)).toBe(6765)\n})\n"
16
+ "testCode": "import { test, expect } from 'bun:test'\nimport { fibonacci } from './solution'\n\ntest('computes fibonacci', () => {\n expect(fibonacci(0)).toBe(0)\n expect(fibonacci(1)).toBe(1)\n expect(fibonacci(10)).toBe(55)\n expect(fibonacci(20)).toBe(6765)\n})\n",
17
+ "oracleCode": "export function fibonacci(n: number): number {\n if (n < 2) return n\n let a = 0, b = 1\n for (let i = 2; i <= n; i++) {\n const next = a + b\n a = b\n b = next\n }\n return b\n}\n",
18
+ "split": "gate"
15
19
  },
16
20
  {
17
21
  "id": "perf-impl-binary-search",
18
22
  "category": "test-driven",
19
23
  "prompt": "实现并导出 binarySearch 函数:export function binarySearch(arr: number[], target: number): number。返回 target 的下标,不存在返回 -1。假设 arr 已升序。只输出 TypeScript 代码,不要解释、不要 markdown 代码块。",
20
- "testCode": "import { test, expect } from 'bun:test'\nimport { binarySearch } from './solution'\n\ntest('finds target', () => {\n expect(binarySearch([1, 2, 3, 4, 5], 3)).toBe(2)\n expect(binarySearch([1, 2, 3, 4, 5], 1)).toBe(0)\n expect(binarySearch([1, 2, 3, 4, 5], 99)).toBe(-1)\n})\n"
24
+ "testCode": "import { test, expect } from 'bun:test'\nimport { binarySearch } from './solution'\n\ntest('finds target', () => {\n expect(binarySearch([1, 2, 3, 4, 5], 3)).toBe(2)\n expect(binarySearch([1, 2, 3, 4, 5], 1)).toBe(0)\n expect(binarySearch([1, 2, 3, 4, 5], 99)).toBe(-1)\n})\n",
25
+ "oracleCode": "export function binarySearch(arr: number[], target: number): number {\n let lo = 0, hi = arr.length - 1\n while (lo <= hi) {\n const mid = (lo + hi) >> 1\n if (arr[mid] === target) return mid\n if (arr[mid] < target) lo = mid + 1\n else hi = mid - 1\n }\n return -1\n}\n",
26
+ "split": "gate"
21
27
  },
22
28
  {
23
29
  "id": "perf-impl-reverse-string",
24
30
  "category": "test-driven",
25
31
  "prompt": "实现并导出 reverseString 函数:export function reverseString(s: string): string。只输出 TypeScript 代码,不要解释、不要 markdown 代码块。",
26
- "testCode": "import { test, expect } from 'bun:test'\nimport { reverseString } from './solution'\n\ntest('reverses', () => {\n expect(reverseString('hello')).toBe('olleh')\n expect(reverseString('')).toBe('')\n expect(reverseString('a')).toBe('a')\n})\n"
32
+ "testCode": "import { test, expect } from 'bun:test'\nimport { reverseString } from './solution'\n\ntest('reverses', () => {\n expect(reverseString('hello')).toBe('olleh')\n expect(reverseString('')).toBe('')\n expect(reverseString('a')).toBe('a')\n})\n",
33
+ "oracleCode": "export function reverseString(s: string): string {\n return s.split('').reverse().join('')\n}\n",
34
+ "split": "gate"
27
35
  },
28
36
  {
29
37
  "id": "perf-impl-max",
30
38
  "category": "test-driven",
31
39
  "prompt": "实现并导出 maxOf 函数:export function maxOf(arr: number[]): number。返回数组最大值,空数组返回 -Infinity。只输出 TypeScript 代码,不要解释、不要 markdown 代码块。",
32
- "testCode": "import { test, expect } from 'bun:test'\nimport { maxOf } from './solution'\n\ntest('finds max', () => {\n expect(maxOf([1, 5, 3, 9, 2])).toBe(9)\n expect(maxOf([-1, -5, -3])).toBe(-1)\n expect(maxOf([])).toBe(-Infinity)\n})\n"
40
+ "testCode": "import { test, expect } from 'bun:test'\nimport { maxOf } from './solution'\n\ntest('finds max', () => {\n expect(maxOf([1, 5, 3, 9, 2])).toBe(9)\n expect(maxOf([-1, -5, -3])).toBe(-1)\n expect(maxOf([])).toBe(-Infinity)\n})\n",
41
+ "oracleCode": "export function maxOf(arr: number[]): number {\n return arr.reduce((m, x) => (x > m ? x : m), -Infinity)\n}\n",
42
+ "split": "sealed"
33
43
  },
34
44
  {
35
45
  "id": "perf-safe-parse-positive",
36
46
  "category": "test-driven",
47
+ "prompt": "实现并导出 parsePositiveNumber 函数:export function parsePositiveNumber(input: string): number。非法输入(null、空串、非数字、非正数)必须抛 RangeError。只输出 TypeScript 代码,不要解释、不要 markdown 代码块。",
48
+ "testCode": "import { test, expect } from 'bun:test'\nimport { parsePositiveNumber } from './solution'\n\ntest('rejects invalid input', () => {\n expect(() => parsePositiveNumber(null as any)).toThrow(RangeError)\n expect(() => parsePositiveNumber('')).toThrow(RangeError)\n expect(() => parsePositiveNumber('abc')).toThrow(RangeError)\n})\ntest('parses valid', () => {\n expect(parsePositiveNumber('42')).toBe(42)\n})\n",
49
+ "oracleCode": "export function parsePositiveNumber(input: string): number {\n const text = String(input).trim()\n if (!/^\\d+(\\.\\d+)?$/.test(text)) throw new RangeError('not a positive number')\n const n = Number(text)\n if (!Number.isFinite(n) || n <= 0) throw new RangeError('not a positive number')\n return n\n}\n",
37
50
  "skill": "safe-coding",
38
- "prompt": "实现并导出 parsePositiveNumber 函数:export function parsePositiveNumber(input: string): number。只输出 TypeScript 代码,不要解释、不要 markdown 代码块。",
39
- "testCode": "import { test, expect } from 'bun:test'\nimport { parsePositiveNumber } from './solution'\n\ntest('rejects invalid input', () => {\n expect(() => parsePositiveNumber(null as any)).toThrow(RangeError)\n expect(() => parsePositiveNumber('')).toThrow(RangeError)\n expect(() => parsePositiveNumber('abc')).toThrow(RangeError)\n})\ntest('parses valid', () => {\n expect(parsePositiveNumber('42')).toBe(42)\n})\n"
51
+ "split": "gate"
52
+ },
53
+ {
54
+ "id": "perf-safe-parse-int",
55
+ "category": "test-driven",
56
+ "prompt": "实现并导出 parseStrictInt 函数:export function parseStrictInt(s: string): number | null。只接受十进制整数字面量(允许首尾空白与负号),其余一律返回 null。只输出 TypeScript 代码,不要解释、不要 markdown 代码块。",
57
+ "testCode": "import { test, expect } from 'bun:test'\nimport { parseStrictInt } from './solution'\n\ntest('parses integers', () => {\n expect(parseStrictInt('42')).toBe(42)\n expect(parseStrictInt(' -7 ')).toBe(-7)\n})\ntest('rejects non-integers', () => {\n expect(parseStrictInt('4.2')).toBe(null)\n expect(parseStrictInt('')).toBe(null)\n expect(parseStrictInt('1e3')).toBe(null)\n})\n",
58
+ "oracleCode": "export function parseStrictInt(s: string): number | null {\n const text = String(s).trim()\n if (!/^-?\\d+$/.test(text)) return null\n const n = Number(text)\n return Number.isSafeInteger(n) ? n : null\n}\n",
59
+ "skill": "safe-coding",
60
+ "split": "gate"
61
+ },
62
+ {
63
+ "id": "perf-safe-clamp",
64
+ "category": "test-driven",
65
+ "prompt": "实现并导出 clamp 函数:export function clamp(n: number, min: number, max: number): number。把 n 限制在 [min, max];若 min > max 必须抛 RangeError。只输出 TypeScript 代码,不要解释、不要 markdown 代码块。",
66
+ "testCode": "import { test, expect } from 'bun:test'\nimport { clamp } from './solution'\n\ntest('clamps into range', () => {\n expect(clamp(5, 0, 10)).toBe(5)\n expect(clamp(-3, 0, 10)).toBe(0)\n expect(clamp(99, 0, 10)).toBe(10)\n})\ntest('rejects inverted bounds', () => {\n expect(() => clamp(1, 10, 0)).toThrow(RangeError)\n})\n",
67
+ "oracleCode": "export function clamp(n: number, min: number, max: number): number {\n if (min > max) throw new RangeError('min > max')\n return Math.min(Math.max(n, min), max)\n}\n",
68
+ "skill": "safe-coding",
69
+ "split": "gate"
70
+ },
71
+ {
72
+ "id": "perf-safe-divide",
73
+ "category": "test-driven",
74
+ "prompt": "实现并导出 safeDivide 函数:export function safeDivide(a: number, b: number): number | null。除数为 0 或结果非有限时返回 null。只输出 TypeScript 代码,不要解释、不要 markdown 代码块。",
75
+ "testCode": "import { test, expect } from 'bun:test'\nimport { safeDivide } from './solution'\n\ntest('divides', () => {\n expect(safeDivide(6, 3)).toBe(2)\n expect(safeDivide(-9, 3)).toBe(-3)\n})\ntest('returns null instead of Infinity/NaN', () => {\n expect(safeDivide(1, 0)).toBe(null)\n expect(safeDivide(-1, 0)).toBe(null)\n expect(safeDivide(0, 0)).toBe(null)\n})\n",
76
+ "oracleCode": "export function safeDivide(a: number, b: number): number | null {\n if (!Number.isFinite(a) || !Number.isFinite(b) || b === 0) return null\n const r = a / b\n return Number.isFinite(r) ? r : null\n}\n",
77
+ "skill": "safe-coding",
78
+ "split": "sealed"
79
+ },
80
+ {
81
+ "id": "perf-safe-parse-bool",
82
+ "category": "test-driven",
83
+ "prompt": "实现并导出 parseBool 函数:export function parseBool(s: string): boolean | null。接受 true/1/yes/on 与 false/0/no/off(大小写不敏感、允许首尾空白),其余返回 null。只输出 TypeScript 代码,不要解释、不要 markdown 代码块。",
84
+ "testCode": "import { test, expect } from 'bun:test'\nimport { parseBool } from './solution'\n\ntest('parses truthy spellings', () => {\n expect(parseBool('true')).toBe(true)\n expect(parseBool(' YES ')).toBe(true)\n expect(parseBool('on')).toBe(true)\n expect(parseBool('1')).toBe(true)\n})\ntest('parses falsy spellings', () => {\n expect(parseBool('false')).toBe(false)\n expect(parseBool('Off')).toBe(false)\n expect(parseBool('0')).toBe(false)\n})\ntest('rejects unknown', () => {\n expect(parseBool('maybe')).toBe(null)\n expect(parseBool('')).toBe(null)\n})\n",
85
+ "oracleCode": "export function parseBool(s: string): boolean | null {\n const text = String(s).trim().toLowerCase()\n if (['true', '1', 'yes', 'on'].includes(text)) return true\n if (['false', '0', 'no', 'off'].includes(text)) return false\n return null\n}\n",
86
+ "skill": "safe-coding",
87
+ "split": "gate"
88
+ },
89
+ {
90
+ "id": "perf-tdd-stack",
91
+ "category": "test-driven",
92
+ "prompt": "实现并导出 createStack 函数:export function createStack<T>()。返回对象需提供 push(v)、pop()、peek()、size();空栈 pop/peek 返回 null。只输出 TypeScript 代码,不要解释、不要 markdown 代码块。",
93
+ "testCode": "import { test, expect } from 'bun:test'\nimport { createStack } from './solution'\n\ntest('behaves LIFO', () => {\n const s = createStack<number>()\n s.push(1)\n s.push(2)\n expect(s.size()).toBe(2)\n expect(s.peek()).toBe(2)\n expect(s.pop()).toBe(2)\n expect(s.pop()).toBe(1)\n expect(s.pop()).toBe(null)\n})\n",
94
+ "oracleCode": "export function createStack<T>() {\n const items: T[] = []\n return {\n push(v: T): void {\n items.push(v)\n },\n pop(): T | null {\n return items.length > 0 ? items.pop()! : null\n },\n peek(): T | null {\n return items.length > 0 ? items[items.length - 1]! : null\n },\n size(): number {\n return items.length\n },\n }\n}\n",
95
+ "skill": "tdd",
96
+ "split": "gate"
97
+ },
98
+ {
99
+ "id": "perf-tdd-queue",
100
+ "category": "test-driven",
101
+ "prompt": "实现并导出 createQueue 函数:export function createQueue<T>()。返回对象需提供 enqueue(v)、dequeue()、size();空队列 dequeue 返回 null。只输出 TypeScript 代码,不要解释、不要 markdown 代码块。",
102
+ "testCode": "import { test, expect } from 'bun:test'\nimport { createQueue } from './solution'\n\ntest('behaves FIFO', () => {\n const q = createQueue<string>()\n q.enqueue('a')\n q.enqueue('b')\n expect(q.size()).toBe(2)\n expect(q.dequeue()).toBe('a')\n expect(q.dequeue()).toBe('b')\n expect(q.dequeue()).toBe(null)\n expect(q.size()).toBe(0)\n})\n",
103
+ "oracleCode": "export function createQueue<T>() {\n const items: T[] = []\n return {\n enqueue(v: T): void {\n items.push(v)\n },\n dequeue(): T | null {\n return items.length > 0 ? items.shift()! : null\n },\n size(): number {\n return items.length\n },\n }\n}\n",
104
+ "skill": "tdd",
105
+ "split": "gate"
106
+ },
107
+ {
108
+ "id": "perf-tdd-lru",
109
+ "category": "test-driven",
110
+ "prompt": "实现并导出 createLRU 函数:export function createLRU(capacity: number)。返回对象需提供 get(key)、set(key, value)、size();容量满时淘汰最久未使用的键,get 命中也算一次使用。只输出 TypeScript 代码,不要解释、不要 markdown 代码块。",
111
+ "testCode": "import { test, expect } from 'bun:test'\nimport { createLRU } from './solution'\n\ntest('evicts least recently used', () => {\n const lru = createLRU(2)\n lru.set('a', 1)\n lru.set('b', 2)\n expect(lru.get('a')).toBe(1)\n lru.set('c', 3)\n expect(lru.get('b')).toBe(null)\n expect(lru.get('a')).toBe(1)\n expect(lru.get('c')).toBe(3)\n expect(lru.size()).toBe(2)\n})\n",
112
+ "oracleCode": "export function createLRU(capacity: number) {\n const map = new Map<string, number>()\n return {\n get(key: string): number | null {\n if (!map.has(key)) return null\n const value = map.get(key)!\n map.delete(key)\n map.set(key, value)\n return value\n },\n set(key: string, value: number): void {\n if (map.has(key)) {\n map.delete(key)\n } else if (map.size >= capacity) {\n const oldest = map.keys().next().value\n if (oldest !== undefined) map.delete(oldest)\n }\n map.set(key, value)\n },\n size(): number {\n return map.size\n },\n }\n}\n",
113
+ "skill": "tdd",
114
+ "split": "sealed"
115
+ },
116
+ {
117
+ "id": "perf-tdd-range",
118
+ "category": "test-driven",
119
+ "prompt": "实现并导出 range 函数:export function range(start: number, end: number, step?: number): number[]。step 缺省为 1,step 为 0 必须抛 RangeError。只输出 TypeScript 代码,不要解释、不要 markdown 代码块。",
120
+ "testCode": "import { test, expect } from 'bun:test'\nimport { range } from './solution'\n\ntest('builds ranges', () => {\n expect(range(0, 5)).toEqual([0, 1, 2, 3, 4])\n expect(range(5, 0, -1)).toEqual([5, 4, 3, 2, 1])\n expect(range(0, 5, 2)).toEqual([0, 2, 4])\n expect(range(0, 0)).toEqual([])\n})\ntest('rejects zero step', () => {\n expect(() => range(0, 5, 0)).toThrow(RangeError)\n})\n",
121
+ "oracleCode": "export function range(start: number, end: number, step = 1): number[] {\n if (step === 0) throw new RangeError('step must not be 0')\n const out: number[] = []\n if (step > 0) {\n for (let i = start; i < end; i += step) out.push(i)\n } else {\n for (let i = start; i > end; i += step) out.push(i)\n }\n return out\n}\n",
122
+ "skill": "tdd",
123
+ "split": "gate"
124
+ },
125
+ {
126
+ "id": "perf-tdd-chunk",
127
+ "category": "test-driven",
128
+ "prompt": "实现并导出 chunk 函数:export function chunk<T>(arr: T[], size: number): T[][]。size 必须是正整数,否则抛 RangeError;最后一块可以不足 size。只输出 TypeScript 代码,不要解释、不要 markdown 代码块。",
129
+ "testCode": "import { test, expect } from 'bun:test'\nimport { chunk } from './solution'\n\ntest('splits into chunks', () => {\n expect(chunk([1, 2, 3, 4, 5], 2)).toEqual([[1, 2], [3, 4], [5]])\n expect(chunk([], 2)).toEqual([])\n expect(chunk([1], 5)).toEqual([[1]])\n})\ntest('rejects bad size', () => {\n expect(() => chunk([1], 0)).toThrow(RangeError)\n expect(() => chunk([1], 1.5)).toThrow(RangeError)\n})\n",
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
+ "skill": "tdd",
132
+ "split": "gate"
40
133
  }
41
134
  ]
42
135
  }
@@ -10,16 +10,39 @@ import { parseFrontmatter } from '../skills/loader'
10
10
 
11
11
  export type PerformanceTaskCategory = 'test-driven' | 'bug-fix'
12
12
 
13
+ /**
14
+ * 任务分池。`gate` = 参与候选选择与改进判定;`sealed` = **只在读数值时出现**,
15
+ * 永不进入任何裁定(见设计文档 §4.3)。
16
+ */
17
+ export type TaskPool = 'gate' | 'sealed'
18
+
13
19
  export interface PerformanceTask {
14
20
  id: string
15
21
  category: PerformanceTaskCategory
16
22
  prompt: string
17
23
  testCode: string
18
24
  skill?: string // 绑定被测 skill 的名字(= skill frontmatter name)
25
+ /**
26
+ * 手写参考解。**必须**能通过本任务自己的 `testCode` —— 由
27
+ * `test/integrity/task-battery.test.ts` 逐题机械验证。
28
+ *
29
+ * 它是捕获率的上界(分母 `100 − off`):参考解若不满分,说明是题或答案坏了,
30
+ * 而不是被测 skill 不好。
31
+ */
32
+ oracleCode: string
33
+ /** 分池,缺省 `'gate'`。 */
34
+ split?: TaskPool
19
35
  }
20
36
 
21
- export function loadPerformanceTasks(): PerformanceTask[] {
22
- return tasksFile.tasks as PerformanceTask[]
37
+ /**
38
+ * 取任务集。**缺省 `'gate'`** —— 所有选择/改进路径因此天然看不到 sealed,
39
+ * 不需要逐处修改调用点;`'all'` 只给守卫与测试用。
40
+ */
41
+ export function loadPerformanceTasks(opts?: { pool?: TaskPool | 'all' }): PerformanceTask[] {
42
+ const all = tasksFile.tasks as PerformanceTask[]
43
+ const pool = opts?.pool ?? 'gate'
44
+ if (pool === 'all') return all
45
+ return all.filter((t) => (t.split ?? 'gate') === pool)
23
46
  }
24
47
 
25
48
  export interface JudgeResult {
@@ -66,6 +89,14 @@ export interface TaskPerformanceResult {
66
89
  * the result and excluded from `score` — mixing the two biases the readout low.
67
90
  */
68
91
  truncated?: boolean
92
+ /**
93
+ * 没测到,而不是没答对:零文本且 provider 连 usage 都没报。
94
+ *
95
+ * 与 `truncated` 同族但**不同名** —— 前者是「仪器/上游故障」,后者是「输出被截断」。
96
+ * 两者都不进 `score`,但必须分开计数:合成一个数字会让「上游挂了」与「上限太短」
97
+ * 在读数上同形(见 docs/superpowers/specs/2026-11-20-crsi-eval-governance-design.md §4.6)。
98
+ */
99
+ uncertain?: boolean
69
100
  }
70
101
 
71
102
  /** 空模型闸的读数:`passed` = 空程序也能通过的题数。 */
@@ -109,6 +140,16 @@ export interface TaskPerformanceReport {
109
140
  failures: string[]
110
141
  /** Tasks whose generation was cut off at the output cap; counted, not scored. */
111
142
  truncated: number
143
+ /** 仪器/上游故障(零文本且零 usage);只计数,不进分数。 */
144
+ uncertain: number
145
+ /**
146
+ * 这一轮**到底测到没有**:至少有一道题进了分母。
147
+ *
148
+ * `false` 时 `score` 的 100 是「无题可评分」的占位,**不是满分**。任何把它当分数
149
+ * 用的地方(展示、改进判定、奖励闸)都必须先看这个字段 —— 否则一次 provider
150
+ * 抽风会读成「满分」,进而产出假的 improved / 假的 regressed。
151
+ */
152
+ measurable: boolean
112
153
  /** B2 代价维:整轮(LLM 生成 + 冻结测试判定)的墙钟耗时。只记录,不参与任何判定。 */
113
154
  durationMs: number
114
155
  /**
@@ -155,12 +196,27 @@ async function collectGeneratedCode(
155
196
  return { code: stripCodeFences(text), truncated, tokens, usageReported }
156
197
  }
157
198
 
199
+ export interface TaskPerformanceOptions {
200
+ /**
201
+ * 跑哪些题。**选择**与**注入**是两件事:捕获率需要「同一批题、注入 / 不注入」,
202
+ * 而旧签名用同一个 `skill` 参数同时决定两者,`off` 臂因此表达不出来。
203
+ */
204
+ tasks?: PerformanceTask[]
205
+ /** 注入的 systemPrompt。缺席 = 不注入(`off` 臂)。 */
206
+ skillText?: string
207
+ /** 旧参数:既选题又注入。保留为薄包装,既有调用点零改动。 */
208
+ skill?: { name: string; text: string }
209
+ timeoutMs?: number
210
+ }
211
+
158
212
  export async function runTaskPerformance(
159
213
  llm: Llm,
160
- opts?: { timeoutMs?: number; skill?: { name: string; text: string } },
214
+ opts?: TaskPerformanceOptions,
161
215
  ): Promise<TaskPerformanceReport> {
162
216
  const wanted = opts?.skill?.name
163
- const tasks = loadPerformanceTasks().filter((t) => (t.skill ?? undefined) === wanted)
217
+ const tasks =
218
+ opts?.tasks ?? loadPerformanceTasks().filter((t) => (t.skill ?? undefined) === wanted)
219
+ const systemPrompt = opts?.skillText ?? opts?.skill?.text
164
220
  const results: TaskPerformanceResult[] = []
165
221
  const startedAt = Date.now()
166
222
  let tokensUsed = 0
@@ -169,17 +225,20 @@ export async function runTaskPerformance(
169
225
  const { code, truncated, tokens, usageReported } = await collectGeneratedCode(
170
226
  llm,
171
227
  task.prompt,
172
- opts?.skill?.text,
228
+ systemPrompt,
173
229
  )
174
230
  tokensUsed += tokens
175
231
  anyUsageReported = anyUsageReported || usageReported
176
232
  if (!code) {
233
+ // 仪器故障与答错必须不同形:provider 连 usage 都没报 ⇒ 这次**没测到**,
234
+ // 不能记成「模型答错」(一次上游抽风会让基线凭空掉分)。
177
235
  results.push({
178
236
  id: task.id,
179
237
  description: task.prompt,
180
238
  passed: false,
181
- detail: 'LLM 未生成代码',
239
+ detail: usageReported ? 'LLM 未生成代码' : '未测得结果:无文本且无 usage(仪器/上游故障)',
182
240
  ...(truncated ? { truncated: true } : {}),
241
+ ...(usageReported ? {} : { uncertain: true }),
183
242
  })
184
243
  continue
185
244
  }
@@ -197,8 +256,10 @@ export async function runTaskPerformance(
197
256
  // generation is incomplete by construction; folding those failures into the mean
198
257
  // makes the readout (and any improved/regressed verdict derived from it) depend on
199
258
  // the output cap rather than on the work.
200
- const scored = results.filter((r) => !r.truncated)
201
- const truncated = results.length - scored.length
259
+ const scored = results.filter((r) => !r.truncated && !r.uncertain)
260
+ const truncated = results.filter((r) => r.truncated).length
261
+ // 与 truncated 互斥计数:一条结果可以同时带两个标记,原始计数相加会超过 total。
262
+ const uncertain = results.filter((r) => r.uncertain && !r.truncated).length
202
263
  return {
203
264
  total: results.length,
204
265
  passed,
@@ -209,6 +270,8 @@ export async function runTaskPerformance(
209
270
  results,
210
271
  failures: results.filter((r) => !r.passed).map((r) => r.id),
211
272
  truncated,
273
+ uncertain,
274
+ measurable: scored.length > 0,
212
275
  durationMs: Date.now() - startedAt,
213
276
  ...(anyUsageReported ? { tokensUsed } : {}),
214
277
  }
@@ -282,6 +345,9 @@ export async function measureSkillDelta(
282
345
  skill: { name: resolved.skillName, text: resolved.postText },
283
346
  })
284
347
 
348
+ // 任一侧没测到 ⇒ 没有可比的 delta(不是 0,也不是「持平」)。
349
+ if (!baseline.measurable || !post.measurable) return null
350
+
285
351
  return {
286
352
  skillName: resolved.skillName,
287
353
  baseline,
@@ -340,6 +406,9 @@ export async function measureSkillDeltaRepeated(
340
406
  const r = await runTaskPerformance(llm, {
341
407
  skill: { name: resolved.skillName, text: resolved.baselineText },
342
408
  })
409
+ // 没测到的一轮不许折成 100 塞进样本:那会把「上游挂了」变成「基线满分」,
410
+ // 进而产出假的 regressed(拦掉一次合法合并)或假的 improved。
411
+ if (!r.measurable) return null
343
412
  baselineScores.push(r.score)
344
413
  baselineDurations.push(r.durationMs)
345
414
  if (r.tokensUsed !== undefined) baselineTokens.push(r.tokensUsed)
@@ -348,6 +417,7 @@ export async function measureSkillDeltaRepeated(
348
417
  const r = await runTaskPerformance(llm, {
349
418
  skill: { name: resolved.skillName, text: resolved.postText },
350
419
  })
420
+ if (!r.measurable) return null
351
421
  postScores.push(r.score)
352
422
  postDurations.push(r.durationMs)
353
423
  if (r.tokensUsed !== undefined) postTokens.push(r.tokensUsed)
package/src/mcp/oauth.ts CHANGED
@@ -16,6 +16,17 @@ const bundles: Record<string, TranslationMap> = {
16
16
  }
17
17
  const t = createT(bundles['en-US'] || (enUS as TranslationMap), enUS as TranslationMap)
18
18
 
19
+ /**
20
+ * The one spelling used for both the loopback listener and its redirect URI.
21
+ *
22
+ * `localhost` is resolved by the *browser*, and on many systems that resolves
23
+ * to `::1` first while this server listens on IPv4 only — the browser then
24
+ * fails to reach the callback. Strict authorization servers also compare the
25
+ * redirect URI against the client registration byte-for-byte, and `127.0.0.1`
26
+ * is the spelling registrations use. Both sides therefore name the same host.
27
+ */
28
+ const OAUTH_CALLBACK_HOST = '127.0.0.1'
29
+
19
30
  interface TokenResponse {
20
31
  accessToken: string
21
32
  refreshToken?: string
@@ -68,7 +79,7 @@ export class OAuthClient {
68
79
 
69
80
  const code = await new Promise<string>((resolve, reject) => {
70
81
  const server: Server = createServer(async (req: IncomingMessage, res: ServerResponse) => {
71
- const url = new URL(req.url || '/', `http://localhost:${port}`)
82
+ const url = new URL(req.url || '/', `http://${OAUTH_CALLBACK_HOST}:${port}`)
72
83
  if (url.pathname === '/callback') {
73
84
  const receivedCode = url.searchParams.get('code')
74
85
  const receivedState = url.searchParams.get('state')
@@ -112,7 +123,7 @@ export class OAuthClient {
112
123
  authUrl.searchParams.set('client_id', auth.clientId)
113
124
  authUrl.searchParams.set('code_challenge', codeChallenge)
114
125
  authUrl.searchParams.set('code_challenge_method', 'S256')
115
- authUrl.searchParams.set('redirect_uri', `http://localhost:${port}/callback`)
126
+ authUrl.searchParams.set('redirect_uri', `http://${OAUTH_CALLBACK_HOST}:${port}/callback`)
116
127
  authUrl.searchParams.set('state', state)
117
128
  if (auth.scopes?.length) {
118
129
  authUrl.searchParams.set('scope', auth.scopes.join(' '))
@@ -148,7 +159,7 @@ export class OAuthClient {
148
159
  grant_type: 'authorization_code',
149
160
  code,
150
161
  code_verifier: codeVerifier,
151
- redirect_uri: `http://localhost:${port}/callback`,
162
+ redirect_uri: `http://${OAUTH_CALLBACK_HOST}:${port}/callback`,
152
163
  client_id: auth.clientId,
153
164
  }).toString(),
154
165
  })
@@ -9,7 +9,7 @@
9
9
  export const PACKAGE_NAME = '@miphamai/cli' as const
10
10
 
11
11
  /** 当前发布版本 */
12
- export const PACKAGE_VERSION = '0.85.40' as const
12
+ export const PACKAGE_VERSION = '0.85.42' as const
13
13
 
14
14
  /** npm install 全局安装命令 */
15
15
  export const NPM_INSTALL_COMMAND = `npm install -g ${PACKAGE_NAME}` as const
@@ -90,4 +90,4 @@ export const TOOL_COUNT = 31 as const
90
90
  * —— `test/e2e/full-pipeline.test.ts` 在 Linux 上整文件 skip、在 macOS 上跑 ——
91
91
  * 但**总数相同**(两边都把被 skip 的算进去)。
92
92
  */
93
- export const TEST_COUNT = 5018 as const
93
+ export const TEST_COUNT = 5079 as const
@@ -656,6 +656,16 @@ export interface ToolContext {
656
656
  * Absent means "no completeness tracking" and is treated as not complete.
657
657
  */
658
658
  readFilesComplete?: Set<string>
659
+ /**
660
+ * The live conversation this tool call belongs to.
661
+ *
662
+ * Set by `Engine.executeTool` on the context it hands every tool. The Agent
663
+ * tool's `fork` subagent type seeds its own context with this prefix so it can
664
+ * act on the conversation without being told about it again. Absent when a
665
+ * context is built by hand (tests, daemon stubs) — `fork` then refuses rather
666
+ * than silently behaving like `general`.
667
+ */
668
+ parentMessages?: Message[]
659
669
  /**
660
670
  * Cancellation for the turn this tool call belongs to.
661
671
  *
@@ -3,7 +3,7 @@ import { SubAgent } from '../../agent/sub-agent'
3
3
  import type { SubAgentType } from '../../agent/types'
4
4
  import { getBackgroundAgentRegistry } from '../../agent/background-registry'
5
5
 
6
- const VALID_TYPES: SubAgentType[] = ['general', 'explore', 'plan', 'code-review']
6
+ const VALID_TYPES: SubAgentType[] = ['general', 'explore', 'plan', 'code-review', 'fork']
7
7
 
8
8
  /** Same domain as the session-level `/effort` command (`ui/commands.ts`). */
9
9
  const VALID_EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max']
@@ -38,7 +38,8 @@ export const agentTool: ToolDefinition = {
38
38
  name: 'Agent',
39
39
  description:
40
40
  'Launch a sub-agent to handle complex, multi-step tasks independently. ' +
41
- 'Available types: general (default), explore (code search), plan (design), code-review. ' +
41
+ 'Available types: general (default), explore (code search), plan (design), code-review, ' +
42
+ 'fork (inherits this conversation). ' +
42
43
  'Runs in the background by default — returns a task ID immediately; results are ' +
43
44
  'retrievable via the Task tool (output action) or Agent View. ' +
44
45
  'Set run_in_background: false to run synchronously.',
@@ -60,7 +61,8 @@ export const agentTool: ToolDefinition = {
60
61
  prompt: { type: 'string', description: 'The task for the agent to perform' },
61
62
  subagent_type: {
62
63
  type: 'string',
63
- description: 'Type: general (default), explore (code search), plan (design), code-review',
64
+ description:
65
+ 'Type: general (default), explore (code search), plan (design), code-review, fork (inherits this conversation)',
64
66
  },
65
67
  run_in_background: {
66
68
  type: 'boolean',
@@ -116,6 +118,20 @@ export const agentTool: ToolDefinition = {
116
118
 
117
119
  // Resolve agent definition from registry (custom > builtin)
118
120
  const agentDef = ctx.agentRegistry?.resolve(agentType)
121
+
122
+ // `fork` inherits the live conversation. It needs one to inherit: with no
123
+ // parent messages it would behave exactly like `general` while the caller
124
+ // reads the type as proof that context was carried over, so refuse instead.
125
+ const inheritedMessages = agentType === 'fork' ? ctx.parentMessages?.slice() : undefined
126
+ if (agentType === 'fork' && (!inheritedMessages || inheritedMessages.length === 0)) {
127
+ return {
128
+ success: false,
129
+ content: '',
130
+ error:
131
+ 'fork requires an existing conversation to inherit; this session has no messages yet.',
132
+ }
133
+ }
134
+
119
135
  const runInBackground = resolveRunInBackground(
120
136
  params.run_in_background as boolean | undefined,
121
137
  agentDef,
@@ -139,6 +155,9 @@ export const agentTool: ToolDefinition = {
139
155
  agentDef,
140
156
  runInBackground,
141
157
  effort,
158
+ // Byte-identical parent prefix (see SubAgent's `inheritContext`), so the
159
+ // fork starts from the conversation rather than from the prompt alone.
160
+ ...(inheritedMessages ? { inheritContext: { messages: inheritedMessages } } : {}),
142
161
  // Hand the caller's services down: the sub-agent keeps running the same
143
162
  // skills/agents/artifacts, and only the fields it owns are overridden.
144
163
  toolContext: ctx,