@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.
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # Mipham Code v0.85.40
1
+ # Mipham Code v0.85.42
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.40",
3
+ "version": "0.85.42",
4
4
  "description": "Mipham Code — Multi-model open-core intelligent coding terminal by MiphamAI",
5
5
  "keywords": [
6
6
  "ai",
@@ -72,6 +72,7 @@ const BUILTIN_SYSTEM_PROMPTS: Record<SubAgentType, string> = {
72
72
  plan: 'You are a planning sub-agent. Design implementation approaches. Return a step-by-step plan with files to modify.',
73
73
  'code-review':
74
74
  'You are a code review sub-agent. Find bugs, security issues, and code quality problems. Return findings by severity.',
75
+ fork: 'You are a forked sub-agent. You inherit the conversation so far; continue it rather than restating it.',
75
76
  }
76
77
 
77
78
  const BUILTIN_DESCRIPTIONS: Record<SubAgentType, string> = {
@@ -79,6 +80,7 @@ const BUILTIN_DESCRIPTIONS: Record<SubAgentType, string> = {
79
80
  explore: 'Read-only search agent for broad fan-out searches across files.',
80
81
  plan: 'Software architect agent for designing implementation plans.',
81
82
  'code-review': 'Code review agent for finding bugs and quality issues.',
83
+ fork: 'Sub-agent that inherits the current conversation and continues from it.',
82
84
  }
83
85
 
84
86
  export class AgentRegistry {
@@ -35,7 +35,10 @@ export class FileInboxTransport implements CrossSessionTransport {
35
35
  private initialized = false
36
36
 
37
37
  private ensureDir(dir: string): void {
38
- mkdirSync(dir, { recursive: true })
38
+ // Owner-only. The inbox carries other sessions' message bodies; the default
39
+ // 0755 directory makes them readable by every local account on a machine
40
+ // whose home directory is world-traversable.
41
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
39
42
  }
40
43
 
41
44
  /** Ensure the inbox root directory exists (call on first use). */
@@ -69,7 +72,7 @@ export class FileInboxTransport implements CrossSessionTransport {
69
72
 
70
73
  // Atomic write: temp file then rename
71
74
  const tmpPath = filePath + '.tmp'
72
- atomicWriteFileSync(tmpPath, JSON.stringify(envelope, null, 2), { mode: 0o644 })
75
+ atomicWriteFileSync(tmpPath, JSON.stringify(envelope, null, 2), { mode: 0o600 })
73
76
  renameSync(tmpPath, filePath)
74
77
 
75
78
  return true
@@ -55,6 +55,7 @@ const TYPE_SYSTEM_PROMPTS: Record<SubAgentType, string> = {
55
55
  plan: 'You are a planning sub-agent. Design implementation approaches. Return a step-by-step plan with files to modify.',
56
56
  'code-review':
57
57
  'You are a code review sub-agent. Find bugs, security issues, and code quality problems. Return findings by severity.',
58
+ fork: 'You are a forked sub-agent. You inherit the conversation so far; continue it rather than restating it.',
58
59
  }
59
60
 
60
61
  /**
@@ -2,7 +2,7 @@
2
2
 
3
3
  import type { Message, ToolContext } from '../shared/index.ts'
4
4
 
5
- export type SubAgentType = 'general' | 'explore' | 'plan' | 'code-review'
5
+ export type SubAgentType = 'general' | 'explore' | 'plan' | 'code-review' | 'fork'
6
6
 
7
7
  export interface AgentFrontmatter {
8
8
  name: string
@@ -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
+ }
@@ -6,10 +6,19 @@ import { SecurityGate } from '../../security/gate'
6
6
  * Well-known secret token prefixes. These are high-signal formats that must
7
7
  * never leak into output, independent of the configured patterns.
8
8
  * - GitHub: ghp_ (personal access), gho_ (OAuth), ghs_ (server), ghu_/ghr_ (user/server-to-server), github_pat_ (fine-grained)
9
- * - GitLab: glpat- (personal access), gldt- (deploy), glrt- (runner), gloas- (OAuth app)
9
+ * - GitLab: glpat- (personal access), gldt- (deploy), glrt- (runner), gloas- (OAuth app),
10
+ * glptt- (pipeline trigger), glagent- (agent), glimt- (incoming mail),
11
+ * glsoat- (SCIM OAuth), glcbt- (CI build), glft- (feed), glffct- (feature flags)
12
+ *
13
+ * GitLab "routable" tokens carry a `.` between a short routing segment and the
14
+ * secret (e.g. `glpat-abcde.0123456789abcdef`). A body class without `.` stops
15
+ * at the first segment, redacting the routing prefix and leaving the secret in
16
+ * the clear — the dot-separated tail is part of the credential, not punctuation.
17
+ * Each dot segment must be at least five characters, so a sentence-ending period
18
+ * after a token is not swallowed.
10
19
  */
11
20
  const TOKEN_REDACTION_PATTERN =
12
- /\b(?:ghp_|gho_|ghs_|ghu_|ghr_|github_pat_|glpat-|gldt-|glrt-|gloas-)[A-Za-z0-9_-]{8,}/g
21
+ /\b(?:ghp_|gho_|ghs_|ghu_|ghr_|github_pat_|glpat-|gldt-|glrt-|gloas-|glptt-|glagent-|glimt-|glsoat-|glcbt-|glft-|glffct-)[A-Za-z0-9_-]{5,}(?:\.[A-Za-z0-9_-]{5,})*/g
13
22
 
14
23
  /**
15
24
  * Credentials embedded in a URL's userinfo — `scheme://user:password@host`.
@@ -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
  }
@@ -592,7 +592,7 @@ export class CrsiSandbox {
592
592
  * ONLY call this after human approval and successful test run.
593
593
  * Cherry-picks the changes from the worktree branch to the current branch.
594
594
  */
595
- merge(): { success: boolean; message: string } {
595
+ merge(): { success: boolean; message: string; commitHash?: string } {
596
596
  if (!this.worktreePath || !this.worktreeBranch) {
597
597
  return { success: false, message: 'No worktree to merge from.' }
598
598
  }
@@ -618,9 +618,14 @@ export class CrsiSandbox {
618
618
  )
619
619
 
620
620
  // Cherry-pick to main repo
621
- const commitHash = runIn(this.worktreePath, 'git rev-parse HEAD').trim()
621
+ const worktreeCommit = runIn(this.worktreePath, 'git rev-parse HEAD').trim()
622
622
 
623
- runIn(this.repoRoot, `git cherry-pick "${commitHash}"`, { timeoutMs: 30_000 })
623
+ runIn(this.repoRoot, `git cherry-pick "${worktreeCommit}"`, { timeoutMs: 30_000 })
624
+
625
+ // 回退目标必须是**主分支上那个新提交**:cherry-pick 造的是另一个 SHA,
626
+ // 而工作树随后会被 finalize() 删掉、其分支被 -D —— 工作树那个提交可能变成
627
+ // 不可达对象。`git revert <worktree> ` 会解析不到。
628
+ const commitHash = runIn(this.repoRoot, 'git rev-parse HEAD').trim()
624
629
 
625
630
  // Mark as merged
626
631
  for (const modResult of this.sessionReport.modifications) {
@@ -635,6 +640,7 @@ export class CrsiSandbox {
635
640
  return {
636
641
  success: true,
637
642
  message: `Successfully merged ${this.sessionReport.summary.merged} modification(s).`,
643
+ commitHash,
638
644
  }
639
645
  } catch (err) {
640
646
  return { success: false, message: `Merge failed: ${String(err)}` }
@@ -1572,6 +1572,9 @@ export class QueryEngine {
1572
1572
  llm: this.llm,
1573
1573
  readFiles: this.readFiles,
1574
1574
  readFilesComplete: this.readFilesComplete,
1575
+ // A copy: the sub-agent seeds its own context from this prefix while the
1576
+ // parent turn keeps appending to its list.
1577
+ parentMessages: this.context.getMessages().slice(),
1575
1578
  })
1576
1579
 
1577
1580
  // Track touched files for rules matching
@@ -1854,6 +1857,21 @@ export class QueryEngine {
1854
1857
  }
1855
1858
  continue
1856
1859
  }
1860
+ // Compaction has already run and the request is *still* too large.
1861
+ // Re-sending it — here or to a fallback provider — cannot change the
1862
+ // answer: the messages themselves are the oversized part and there is
1863
+ // nothing left to strip. Say why once instead of spending the retry and
1864
+ // fallback budget on a request that is guaranteed to fail the same way.
1865
+ if (compactedForOverflow && ownsFlow && isContextOverflowError(failure)) {
1866
+ yield {
1867
+ type: 'error',
1868
+ error:
1869
+ `${activeId} rejected the request as too large even after compacting — ` +
1870
+ `the conversation itself exceeds the request size limit, so retrying cannot help. ` +
1871
+ `Start a new session (/clear) or remove large attachments.`,
1872
+ }
1873
+ return
1874
+ }
1857
1875
  if (!retryable || !ownsFlow || attempt >= 1) break
1858
1876
  // `restart: true` tells the consumer to drop what the failed attempt already
1859
1877
  // yielded. Without it the retry's tool calls are *added* to the failed
@@ -63,8 +63,13 @@ export interface ImprovementRecord extends ImprovementReport {
63
63
 
64
64
  // ── 纯函数 ──
65
65
 
66
- export function computeMinEffect(noise: number): number {
67
- return Math.max(MIN_EFFECT_FLOOR, NOISE_K * noise)
66
+ /**
67
+ * 噪声自适应最小效应量。`floor` 缺省为 `MIN_EFFECT_FLOOR` —— 既有调用点不变。
68
+ * 试用期传自己的地板(两题步长),因为 4 题池上单题翻转只有 25 分,按 20 分地板判
69
+ * 退化会让「一次恰好翻转」触发回退提示。
70
+ */
71
+ export function computeMinEffect(noise: number, floor: number = MIN_EFFECT_FLOOR): number {
72
+ return Math.max(floor, NOISE_K * noise)
68
73
  }
69
74
 
70
75
  export function classifyDelta(deltaMean: number, minEffect: number): ImprovementVerdict {
@@ -343,7 +343,6 @@ export function formatInstructionSizeNotice(
343
343
 
344
344
  export class InstructionsLoader {
345
345
  private instructions: InstructionFile[] = []
346
- private crsiLessonSummaries: CrsiLessonSummary[] = []
347
346
  private lessonsPath: string | null = null
348
347
  /** Checkout root resolved at `loadAll`, reused by `loadForPaths`. */
349
348
  private root: string | null = null
@@ -371,8 +370,8 @@ export class InstructionsLoader {
371
370
  // Tier 3: 用户层 ~/.mipham/USER.md
372
371
  this.tryLoad(miphamHome('USER.md'), 'user')
373
372
 
374
- // CRSI 教训召回:读 crsi-lessons.md 提取精华,注入系统提示(只写不读 → 写后召回)
375
- this.crsiLessonSummaries = this.loadCrsiLessons(root)
373
+ // CRSI 教训召回:在这里只**确定来源路径**;内容每次投影时重读(见 currentLessonSummaries)。
374
+ this.loadCrsiLessons(root)
376
375
  }
377
376
 
378
377
  /**
@@ -561,6 +560,9 @@ Never omit it or present the work as purely human-authored.`)
561
560
  this.lessonsPath = path
562
561
  return extractCrsiLessonSummaries(content)
563
562
  } catch {
563
+ // 文件被删:指针必须同时清空。否则「删了教训」与「从来没有过」在 sizeReport
564
+ // 里同形 —— 报告会继续点名一个不存在来源。
565
+ this.lessonsPath = null
564
566
  return []
565
567
  }
566
568
  }
@@ -579,9 +581,21 @@ Never omit it or present the work as purely human-authored.`)
579
581
  * 落进指针(并在指针里被点名)—— 择点走 `selectResidentLessons`,与
580
582
  * `loadAlwaysOnLessonsBlock` 是同一个。
581
583
  */
584
+ /**
585
+ * 教训摘要的**唯一读取点**:每次都从盘上重读。
586
+ *
587
+ * 从前只在 `loadAll` 读一次并缓存 ⇒ 会话中途删掉一条教训,系统提示里那条会一直留着
588
+ * (与 Agnes Harness 报告 Limitations 第 3 条同型的「删了没有墓碑」)。一个文件的
589
+ * 读取成本远低于「给模型看到已经不存在的规则」。
590
+ */
591
+ private currentLessonSummaries(): CrsiLessonSummary[] {
592
+ return this.root ? this.loadCrsiLessons(this.root) : []
593
+ }
594
+
582
595
  private crsiLessonsText(): string {
583
- if (!this.lessonsPath) return ''
584
- const selection = selectResidentLessons(this.crsiLessonSummaries)
596
+ const summaries = this.currentLessonSummaries()
597
+ if (!this.lessonsPath || summaries.length === 0) return ''
598
+ const selection = selectResidentLessons(summaries)
585
599
  return [
586
600
  buildCrsiLessonsBlock(selection.resident),
587
601
  buildCrsiLessonsPointer(selection, this.lessonsPath),
@@ -600,11 +614,9 @@ Never omit it or present the work as purely human-authored.`)
600
614
  * 与指针同一条件,故不会出现「扳机响了但没有指针」。
601
615
  */
602
616
  crsiLessonNudgeText(): string {
603
- if (!this.lessonsPath) return ''
604
- return buildLessonRevisitNudge(
605
- selectResidentLessons(this.crsiLessonSummaries),
606
- this.lessonsPath,
607
- )
617
+ const summaries = this.currentLessonSummaries()
618
+ if (!this.lessonsPath || summaries.length === 0) return ''
619
+ return buildLessonRevisitNudge(selectResidentLessons(summaries), this.lessonsPath)
608
620
  }
609
621
 
610
622
  /**