@miphamai/cli 0.85.48 → 0.85.50
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 +1 -1
- package/src/agent/sub-agent.ts +17 -0
- package/src/core/auto-corrector.ts +0 -8
- package/src/core/auto-memory.ts +13 -0
- package/src/core/capability-inventory.ts +112 -18
- package/src/core/crsi-inbox.ts +230 -0
- package/src/core/engine.ts +64 -11
- package/src/core/error-signature-db.ts +68 -11
- package/src/core/eval-harness.ts +43 -4
- package/src/core/hooks-executor.ts +25 -2
- package/src/core/immune-memory-gc.ts +5 -5
- package/src/core/instructions.ts +12 -3
- package/src/core/metrics.ts +13 -0
- package/src/core/preflight-checker.ts +12 -0
- package/src/core/tool-gate.ts +20 -2
- package/src/i18n-core/locales/en-US.json +5 -2
- package/src/i18n-core/locales/zh-CN.json +5 -2
- package/src/index.tsx +15 -0
- package/src/plugin/plugin-manager.ts +12 -3
- package/src/providers/anthropic.ts +5 -0
- package/src/providers/fetch-utils.ts +16 -1
- package/src/providers/llm-replay.ts +13 -3
- package/src/providers/openai-compat.ts +4 -0
- package/src/shared/package-info.ts +2 -2
- package/src/skills/sanitizer.ts +16 -2
- package/src/tools/exec/bash.ts +43 -8
- package/src/ui/chat.tsx +9 -1
- package/src/ui/commands.ts +116 -16
- package/src/ui/input.tsx +23 -3
- package/src/ui/picker.tsx +15 -3
package/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# Mipham Code v0.85.
|
|
1
|
+
# Mipham Code v0.85.50
|
|
2
2
|
|
|
3
3
|
**Multi-model open-core intelligent coding terminal** — 12 AI providers, 141 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
package/src/agent/sub-agent.ts
CHANGED
|
@@ -758,6 +758,10 @@ export class SubAgent {
|
|
|
758
758
|
// credential executed verbatim one level down.
|
|
759
759
|
let effectiveInput = tu.input
|
|
760
760
|
let gateWarnings: string[] = []
|
|
761
|
+
// SIS pre-flight may have applied a signature's fix; score the outcome
|
|
762
|
+
// on this funnel too (the engine's recording never sees this loop).
|
|
763
|
+
let sisFixSignature: string | undefined
|
|
764
|
+
let sisOutcomeRecorded = false
|
|
761
765
|
if (this.services) {
|
|
762
766
|
const outcome = await runPreToolGate(tu.name, tu.input, this.services.gate, 'sub-agent')
|
|
763
767
|
if (!outcome.ok) {
|
|
@@ -769,6 +773,7 @@ export class SubAgent {
|
|
|
769
773
|
}
|
|
770
774
|
effectiveInput = outcome.params
|
|
771
775
|
gateWarnings = outcome.warnings
|
|
776
|
+
sisFixSignature = outcome.sisFixSignature
|
|
772
777
|
} else if (this.hooks) {
|
|
773
778
|
// Legacy path: a caller that built a SubAgent by hand with only a
|
|
774
779
|
// hook engine still gets its PreToolUse hook. The other four gates
|
|
@@ -829,6 +834,11 @@ export class SubAgent {
|
|
|
829
834
|
try {
|
|
830
835
|
const result = await tool.execute(effectiveInput, toolContext)
|
|
831
836
|
|
|
837
|
+
if (sisFixSignature) {
|
|
838
|
+
this.services?.gate.preflight?.()?.recordOutcome(sisFixSignature, result.success)
|
|
839
|
+
sisOutcomeRecorded = true
|
|
840
|
+
}
|
|
841
|
+
|
|
832
842
|
// Merge gate: a review delegated here still counts for the session
|
|
833
843
|
// that will merge. This loop bypasses `Engine.executeTool`, so the
|
|
834
844
|
// engine's own recording never sees this call — the same two-path
|
|
@@ -899,6 +909,13 @@ export class SubAgent {
|
|
|
899
909
|
],
|
|
900
910
|
})
|
|
901
911
|
} catch (err) {
|
|
912
|
+
// The applied SIS fix was followed by a thrown error — score it. The
|
|
913
|
+
// flag keeps a later hook throw from failing a fix that worked.
|
|
914
|
+
if (sisFixSignature && !sisOutcomeRecorded) {
|
|
915
|
+
this.services?.gate.preflight?.()?.recordOutcome(sisFixSignature, false)
|
|
916
|
+
sisOutcomeRecorded = true
|
|
917
|
+
}
|
|
918
|
+
|
|
902
919
|
// ── P0-5: Run PostToolUseFailure hooks ──
|
|
903
920
|
if (this.hooks) {
|
|
904
921
|
this.hooks
|
|
@@ -86,14 +86,6 @@ export class AutoCorrector {
|
|
|
86
86
|
return this.handleUnknownError(toolName, params, error)
|
|
87
87
|
}
|
|
88
88
|
|
|
89
|
-
/**
|
|
90
|
-
* Record a manual correction (user fixed it themselves).
|
|
91
|
-
* Updates the signature's success rate.
|
|
92
|
-
*/
|
|
93
|
-
recordManualFix(signatureId: string, success: boolean): void {
|
|
94
|
-
this.errorDB.recordResult(signatureId, success)
|
|
95
|
-
}
|
|
96
|
-
|
|
97
89
|
// ── Private ──
|
|
98
90
|
|
|
99
91
|
/** Handle a known error pattern with an existing signature. */
|
package/src/core/auto-memory.ts
CHANGED
|
@@ -19,6 +19,7 @@ import type { ErrorSignatureDB } from './error-signature-db.js'
|
|
|
19
19
|
import type { CrsiProvenanceBridge } from '../agent/crsi-provenance-bridge.js'
|
|
20
20
|
import { getMetrics } from './metrics'
|
|
21
21
|
import { miphamHome } from './paths.ts'
|
|
22
|
+
import { appendSignals, insightsToSignals } from './crsi-inbox'
|
|
22
23
|
|
|
23
24
|
// ── Types ──
|
|
24
25
|
|
|
@@ -211,6 +212,18 @@ export class AutoMemoryEngine {
|
|
|
211
212
|
howToApply: '下次会话开始时回顾此文件,检查是否有可操作的改进项',
|
|
212
213
|
})
|
|
213
214
|
|
|
215
|
+
// CRSI 信号收件箱:进程退出后信号仍在。
|
|
216
|
+
//
|
|
217
|
+
// 不写的话,「学习」隐含一个前提 —— 失败发生后、进程退出前,有人想起来
|
|
218
|
+
// 敲 `/crsi propose`;人不在,insight 随进程消失。收件箱把这一段变成
|
|
219
|
+
// 每轮同步落盘,下次启动由 `refreshPendingLessons` 自动渲染成待并入教训。
|
|
220
|
+
// 失败不能让一轮对话失败:收件箱是非关键路径。
|
|
221
|
+
try {
|
|
222
|
+
appendSignals(insightsToSignals(reflection.crsiInsights.filter((i) => i.autoApplicable)))
|
|
223
|
+
} catch {
|
|
224
|
+
// ignore — 收件箱写失败不影响本轮
|
|
225
|
+
}
|
|
226
|
+
|
|
214
227
|
// Feed CRSI insights into the rule engine
|
|
215
228
|
this.feedCrsiPipeline(reflection)
|
|
216
229
|
}
|
|
@@ -18,6 +18,7 @@ export interface CapabilitySources {
|
|
|
18
18
|
active: number
|
|
19
19
|
degraded: number
|
|
20
20
|
retired: number
|
|
21
|
+
fixable: number
|
|
21
22
|
avgSuccessRate: number
|
|
22
23
|
totalInterceptions: number
|
|
23
24
|
}
|
|
@@ -37,7 +38,36 @@ function safeMetaRuleCount(engine: CapabilitySources): number {
|
|
|
37
38
|
}
|
|
38
39
|
}
|
|
39
40
|
|
|
40
|
-
|
|
41
|
+
/**
|
|
42
|
+
* Ledger-backed numbers, already loaded and summarised by the caller.
|
|
43
|
+
*
|
|
44
|
+
* Kept out of `buildCapabilityReport` so the report stays pure and testable:
|
|
45
|
+
* the command reads `~/.mipham/crsi/*.jsonl`, the builder only renders.
|
|
46
|
+
*/
|
|
47
|
+
export interface CapabilityLedgers {
|
|
48
|
+
lastEval?: { score: number; passed: number; total: number; timestamp: string }
|
|
49
|
+
improvements?: { count: number; verdicts: Record<string, number>; latestTimestamp: string }
|
|
50
|
+
probation?: { count: number; latestTimestamp: string }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** A ledger row, stamped with the file and the record's own timestamp. */
|
|
54
|
+
function ledgerRow(metric: string, value: string, file: string, timestamp?: string): string {
|
|
55
|
+
const source = timestamp ? `ledger:${file}@${timestamp}` : `ledger:${file}(未找到)`
|
|
56
|
+
return `| ${metric} | ${value} | ${source} |`
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* 能力自报告。
|
|
61
|
+
*
|
|
62
|
+
* **每个数字都带出处**:`now(getter)` 是本次调用实时读到的,`ledger:…@…` 是台账
|
|
63
|
+
* 里那条记录的时间戳。这份报告刻意不引用文档数字 —— 文档值不是实测值,而两者
|
|
64
|
+
* 混在一张「读数」表里,正是 2026-11-26 那次自评把 CLAUDE.md 的 5,349 当成
|
|
65
|
+
* 实测结果的原因。
|
|
66
|
+
*/
|
|
67
|
+
export function buildCapabilityReport(
|
|
68
|
+
engine: CapabilitySources,
|
|
69
|
+
ledgers: CapabilityLedgers = {},
|
|
70
|
+
): string {
|
|
41
71
|
const lines: string[] = ['## 🧭 能力自报告 (CRSI Inventory)', '']
|
|
42
72
|
|
|
43
73
|
// ── 🧠 学习 (CRSI) ──
|
|
@@ -49,24 +79,30 @@ export function buildCapabilityReport(engine: CapabilitySources): string {
|
|
|
49
79
|
const insights = engine.getAutoMemory?.()?.accumulatedInsights ?? []
|
|
50
80
|
|
|
51
81
|
lines.push('### 🧠 学习 (CRSI)', '')
|
|
52
|
-
lines.push('| 指标 | 值 |')
|
|
53
|
-
lines.push('
|
|
54
|
-
lines.push(
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
lines.push(`|
|
|
82
|
+
lines.push('| 指标 | 值 | 出处 |')
|
|
83
|
+
lines.push('|------|----|------|')
|
|
84
|
+
lines.push(
|
|
85
|
+
`| 活跃规则 | ${rules.length} (内置 ${builtin} · 自动 ${auto} · 手动 ${manual}) | now(getRuleEngine) |`,
|
|
86
|
+
)
|
|
87
|
+
lines.push(`| 已检测模式 | ${patterns.length} | now(getPatternAnalyzer) |`)
|
|
88
|
+
lines.push(`| 反思洞察 | ${insights.length} | now(getAutoMemory) |`)
|
|
89
|
+
lines.push(`| 元规则 | ${safeMetaRuleCount(engine)} | now(getMetaRuleEngine) |`)
|
|
58
90
|
|
|
59
91
|
// ── 🛡️ 免疫 (SIS) ──
|
|
60
92
|
const sis = engine.getErrorSignatureDB?.()?.getStats()
|
|
61
93
|
lines.push('', '### 🛡️ 免疫 (SIS)', '')
|
|
62
94
|
if (sis) {
|
|
63
|
-
lines.push('| 指标 | 值 |')
|
|
64
|
-
lines.push('
|
|
95
|
+
lines.push('| 指标 | 值 | 出处 |')
|
|
96
|
+
lines.push('|------|----|------|')
|
|
65
97
|
lines.push(
|
|
66
|
-
`| 错误签名 | ${sis.total} 条 (🟢${sis.active} · 🟡${sis.degraded} · ⚫${sis.retired}) |`,
|
|
98
|
+
`| 错误签名 | ${sis.total} 条 (🟢${sis.active} · 🟡${sis.degraded} · ⚫${sis.retired}) | now(getErrorSignatureDB) |`,
|
|
67
99
|
)
|
|
68
|
-
lines.push(
|
|
69
|
-
|
|
100
|
+
lines.push(
|
|
101
|
+
`| 平均成功率 | ${
|
|
102
|
+
sis.fixable > 0 ? `${Math.round(sis.avgSuccessRate * 100)}%` : '—(无可自动修复签名)'
|
|
103
|
+
} | now(getErrorSignatureDB) |`,
|
|
104
|
+
)
|
|
105
|
+
lines.push(`| 总拦截 | ${sis.totalInterceptions} 次 | now(getErrorSignatureDB) |`)
|
|
70
106
|
} else {
|
|
71
107
|
lines.push('_未初始化_')
|
|
72
108
|
}
|
|
@@ -78,13 +114,15 @@ export function buildCapabilityReport(engine: CapabilitySources): string {
|
|
|
78
114
|
const karuna = constitution.principles.filter((p) => p.facet === 'karuna').length
|
|
79
115
|
const prajna = constitution.principles.filter((p) => p.facet === 'prajna').length
|
|
80
116
|
const vajra = constitution.principles.filter((p) => p.facet === 'vajra').length
|
|
81
|
-
lines.push('| 指标 | 值 |')
|
|
82
|
-
lines.push('
|
|
83
|
-
lines.push(`| 版本 | ${constitution.version} |`)
|
|
117
|
+
lines.push('| 指标 | 值 | 出处 |')
|
|
118
|
+
lines.push('|------|----|------|')
|
|
119
|
+
lines.push(`| 版本 | ${constitution.version} | now(getConstitutionLoader) |`)
|
|
120
|
+
lines.push(
|
|
121
|
+
`| 原则 | ${constitution.principles.length} 条 (悲 ${karuna} · 智 ${prajna} · 金刚 ${vajra}) | now(getConstitutionLoader) |`,
|
|
122
|
+
)
|
|
84
123
|
lines.push(
|
|
85
|
-
`|
|
|
124
|
+
`| 愿力序言 | ${constitution.preamble ? '已注入 self-critique' : '无'} | now(getConstitutionLoader) |`,
|
|
86
125
|
)
|
|
87
|
-
lines.push(`| 愿力序言 | ${constitution.preamble ? '已注入 self-critique' : '无'} |`)
|
|
88
126
|
} else {
|
|
89
127
|
lines.push('_未初始化_')
|
|
90
128
|
}
|
|
@@ -92,7 +130,63 @@ export function buildCapabilityReport(engine: CapabilitySources): string {
|
|
|
92
130
|
// ── ⚠️ 未接线 / 待启用 ──
|
|
93
131
|
const selfCritique = engine.getSelfCritique?.()?.getConfig()
|
|
94
132
|
lines.push('', '### ⚠️ 未接线 / 待启用', '')
|
|
95
|
-
lines.push(
|
|
133
|
+
lines.push('| 指标 | 值 | 出处 |')
|
|
134
|
+
lines.push('|------|----|------|')
|
|
135
|
+
lines.push(
|
|
136
|
+
`| self-critique | ${selfCritique?.enabled ? '🟢 已启用' : '⚫ 未启用 (opt-in)'} | now(getSelfCritique) |`,
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
// ── 📊 真值评估(台账) ──
|
|
140
|
+
lines.push('', '### 📊 真值评估(台账)', '')
|
|
141
|
+
lines.push('| 指标 | 值 | 出处 |')
|
|
142
|
+
lines.push('|------|----|------|')
|
|
143
|
+
if (ledgers.lastEval) {
|
|
144
|
+
const e = ledgers.lastEval
|
|
145
|
+
lines.push(
|
|
146
|
+
ledgerRow(
|
|
147
|
+
'最近机制 eval',
|
|
148
|
+
`${e.passed}/${e.total}(score ${e.score})`,
|
|
149
|
+
'eval-scores.jsonl',
|
|
150
|
+
e.timestamp,
|
|
151
|
+
),
|
|
152
|
+
)
|
|
153
|
+
} else {
|
|
154
|
+
lines.push(ledgerRow('最近机制 eval', '无记录', 'eval-scores.jsonl'))
|
|
155
|
+
}
|
|
156
|
+
if (ledgers.improvements) {
|
|
157
|
+
const im = ledgers.improvements
|
|
158
|
+
const verdicts = Object.entries(im.verdicts)
|
|
159
|
+
.map(([verdict, count]) => `${verdict} ${count}`)
|
|
160
|
+
.join(' · ')
|
|
161
|
+
lines.push(
|
|
162
|
+
ledgerRow(
|
|
163
|
+
'改进台账',
|
|
164
|
+
`${im.count} 条${verdicts ? `(${verdicts})` : ''}`,
|
|
165
|
+
'improvements.jsonl',
|
|
166
|
+
im.latestTimestamp,
|
|
167
|
+
),
|
|
168
|
+
)
|
|
169
|
+
} else {
|
|
170
|
+
lines.push(ledgerRow('改进台账', '无记录', 'improvements.jsonl'))
|
|
171
|
+
}
|
|
172
|
+
if (ledgers.probation) {
|
|
173
|
+
lines.push(
|
|
174
|
+
ledgerRow(
|
|
175
|
+
'试用期',
|
|
176
|
+
`${ledgers.probation.count} 条`,
|
|
177
|
+
'probation.jsonl',
|
|
178
|
+
ledgers.probation.latestTimestamp,
|
|
179
|
+
),
|
|
180
|
+
)
|
|
181
|
+
} else {
|
|
182
|
+
lines.push(ledgerRow('试用期', '无记录', 'probation.jsonl'))
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
lines.push(
|
|
186
|
+
'',
|
|
187
|
+
'> 出处:`now(getter)` = 本次调用实时读取;`ledger:<文件>@<ISO 时间>` = 该台账最后一条记录。',
|
|
188
|
+
'> 本报告不引用文档数字 —— 文档值不能当作实测值。',
|
|
189
|
+
)
|
|
96
190
|
|
|
97
191
|
return lines.join('\n')
|
|
98
192
|
}
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CRSI signal inbox —— 让人不在场时失败信号也不蒸发。
|
|
3
|
+
*
|
|
4
|
+
* 缺口:`AutoMemoryEngine` 的 insight 只活在**当前进程**里(`sessionReflections`),
|
|
5
|
+
* `/crsi propose` 读的是 `accumulatedInsights`。于是「学习」有一个隐含前提 ——
|
|
6
|
+
* 失败发生后、进程退出前,得有人想起来敲 `/crsi propose`。人不在,信号就没了。
|
|
7
|
+
*
|
|
8
|
+
* 本模块把这条链拆成两段:
|
|
9
|
+
* 1. **采集**(`appendSignals`):每轮 `persist()` 把 autoApplicable 信号同步落盘
|
|
10
|
+
* 到 `~/.mipham/crsi/signal-inbox.jsonl`(0600,按 category|title 幂等去重)。
|
|
11
|
+
* 2. **产出**(`refreshPendingLessons`):CLI 启动时把收件箱里**尚未并入**的信号
|
|
12
|
+
* 渲染成 `~/.mipham/crsi/pending-lessons.md`。这是一份**派生视图** ——
|
|
13
|
+
* 每次从「收件箱 − 已并入」重算,所以合并后会自动收缩,不需要谁去删。
|
|
14
|
+
*
|
|
15
|
+
* 边界:本模块**只产出候选**,不碰 `crsi-lessons.md` 本体。并入仍走
|
|
16
|
+
* `/crsi propose --pending` → 沙箱 gate → 人类批准/拒绝。自动化的只是「产出」,
|
|
17
|
+
* 不是「合并」—— 后者是 CRSI 的受约束自改进边界,不在这里让渡。
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { existsSync, mkdirSync } from 'node:fs'
|
|
21
|
+
import { dirname, join, parse as parsePath } from 'node:path'
|
|
22
|
+
import {
|
|
23
|
+
LESSONS_FILE,
|
|
24
|
+
buildLessonContent,
|
|
25
|
+
normalizeLessonSeverity,
|
|
26
|
+
type CrsiSignal,
|
|
27
|
+
} from './crsi-producer'
|
|
28
|
+
import type { CrsiInsight } from './auto-memory'
|
|
29
|
+
import { miphamHome } from './paths'
|
|
30
|
+
import { atomicWriteFileSync } from '../shared/atomic-write'
|
|
31
|
+
import { appendRegularFileSync, readRegularFileSync } from '../shared/regular-file'
|
|
32
|
+
|
|
33
|
+
/** 单次最多渲染多少条 —— 一次启动塞几十条教训等于把教训淹掉。 */
|
|
34
|
+
export const MAX_PENDING_LESSONS = 10
|
|
35
|
+
|
|
36
|
+
export function signalInboxPath(): string {
|
|
37
|
+
return join(miphamHome(), 'crsi', 'signal-inbox.jsonl')
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function pendingLessonsPath(): string {
|
|
41
|
+
return join(miphamHome(), 'crsi', 'pending-lessons.md')
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function signalKey(signal: CrsiSignal): string {
|
|
45
|
+
return `${signal.category}::${signal.title}`
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function lessonHeading(signal: CrsiSignal): string {
|
|
49
|
+
return `## ${signal.category}: ${signal.title}`
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** 读收件箱;坏行跳过(一行损坏不应拖垮整个收件箱)。 */
|
|
53
|
+
export function readSignals(path = signalInboxPath()): CrsiSignal[] {
|
|
54
|
+
const raw = readRegularFileSync(path)
|
|
55
|
+
if (!raw) return []
|
|
56
|
+
const out: CrsiSignal[] = []
|
|
57
|
+
for (const line of raw.split('\n')) {
|
|
58
|
+
const trimmed = line.trim()
|
|
59
|
+
if (!trimmed) continue
|
|
60
|
+
try {
|
|
61
|
+
const parsed = JSON.parse(trimmed) as Partial<CrsiSignal>
|
|
62
|
+
if (typeof parsed.category !== 'string' || typeof parsed.title !== 'string') continue
|
|
63
|
+
out.push({
|
|
64
|
+
category: parsed.category,
|
|
65
|
+
title: parsed.title,
|
|
66
|
+
severity: typeof parsed.severity === 'string' ? parsed.severity : undefined,
|
|
67
|
+
suggestion: typeof parsed.suggestion === 'string' ? parsed.suggestion : '',
|
|
68
|
+
evidence: Array.isArray(parsed.evidence)
|
|
69
|
+
? parsed.evidence.filter((e): e is string => typeof e === 'string')
|
|
70
|
+
: [],
|
|
71
|
+
component: parsed.component,
|
|
72
|
+
})
|
|
73
|
+
} catch {
|
|
74
|
+
// 坏行:跳过
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return out
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* 追加信号,按 category|title 去重;返回本次实际新增条数。
|
|
82
|
+
*
|
|
83
|
+
* 去重是**跨调用**的(与文件里已有的比),所以同一失败反复发生不会把收件箱撑爆。
|
|
84
|
+
*/
|
|
85
|
+
export function appendSignals(signals: CrsiSignal[], path = signalInboxPath()): number {
|
|
86
|
+
if (signals.length === 0) return 0
|
|
87
|
+
|
|
88
|
+
const existing = new Set(readSignals(path).map(signalKey))
|
|
89
|
+
const fresh: CrsiSignal[] = []
|
|
90
|
+
for (const signal of signals) {
|
|
91
|
+
const key = signalKey(signal)
|
|
92
|
+
if (existing.has(key)) continue
|
|
93
|
+
existing.add(key)
|
|
94
|
+
fresh.push(signal)
|
|
95
|
+
}
|
|
96
|
+
if (fresh.length === 0) return 0
|
|
97
|
+
|
|
98
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
99
|
+
const payload = fresh.map((s) => JSON.stringify(s)).join('\n') + '\n'
|
|
100
|
+
return appendRegularFileSync(path, payload, { mode: 0o600 }) ? fresh.length : 0
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* 把收件箱渲染成教训 markdown(派生视图)。
|
|
105
|
+
*
|
|
106
|
+
* `mergedLessons` 是 `crsi-lessons.md` 的现状:标题已在里面的信号不再出现。
|
|
107
|
+
* 返回空串表示「没有该产出的东西」—— 不是一段空壳。
|
|
108
|
+
*/
|
|
109
|
+
export function pendingLessonsMarkdown(
|
|
110
|
+
signals: CrsiSignal[],
|
|
111
|
+
mergedLessons: string,
|
|
112
|
+
timestamp: string,
|
|
113
|
+
): string {
|
|
114
|
+
const seen = new Set<string>()
|
|
115
|
+
const blocks: string[] = []
|
|
116
|
+
for (const signal of signals) {
|
|
117
|
+
const heading = lessonHeading(signal)
|
|
118
|
+
if (mergedLessons.includes(heading) || seen.has(heading)) continue
|
|
119
|
+
seen.add(heading)
|
|
120
|
+
blocks.push(
|
|
121
|
+
buildLessonContent(
|
|
122
|
+
signal,
|
|
123
|
+
timestamp,
|
|
124
|
+
normalizeLessonSeverity(signal.severity),
|
|
125
|
+
'CRSI inbox (auto-collected)',
|
|
126
|
+
),
|
|
127
|
+
)
|
|
128
|
+
if (blocks.length >= MAX_PENDING_LESSONS) break
|
|
129
|
+
}
|
|
130
|
+
return blocks.join('\n')
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function readPendingLessons(path = pendingLessonsPath()): string {
|
|
134
|
+
return readRegularFileSync(path) ?? ''
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function writePendingLessons(content: string, path = pendingLessonsPath()): void {
|
|
138
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
139
|
+
// 派生视图也走原子写:读侧把「读不动」当空,半截文件会把整份 pending 读没。
|
|
140
|
+
atomicWriteFileSync(path, content, { mode: 0o600 })
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** 从 `startDir` 向上找 `apps/cli/crsi-lessons.md`(producer 的仓库内路径)。 */
|
|
144
|
+
export function findLessonsFile(startDir: string): string | null {
|
|
145
|
+
let dir = startDir
|
|
146
|
+
for (;;) {
|
|
147
|
+
const candidate = join(dir, LESSONS_FILE)
|
|
148
|
+
if (existsSync(candidate)) return candidate
|
|
149
|
+
const parent = parsePath(dir).dir
|
|
150
|
+
if (parent === dir) return null
|
|
151
|
+
dir = parent
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export interface RefreshResult {
|
|
156
|
+
/** 当前 pending 文件里的教训条数。 */
|
|
157
|
+
total: number
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* 启动时调用:从收件箱重新派生 pending 教训。
|
|
162
|
+
*
|
|
163
|
+
* 不在 mipham-code 仓库里(找不到 lessons 文件)时**什么都不写** —— 这条流水线
|
|
164
|
+
* 只对「能改自己教训文件」的仓库成立;用户安装里产出的 pending 无人能并入。
|
|
165
|
+
*/
|
|
166
|
+
export function refreshPendingLessons(
|
|
167
|
+
startDir: string,
|
|
168
|
+
opts: { inboxPath?: string; pendingPath?: string; timestamp?: string } = {},
|
|
169
|
+
): RefreshResult {
|
|
170
|
+
const lessonsPath = findLessonsFile(startDir)
|
|
171
|
+
if (!lessonsPath) return { total: 0 }
|
|
172
|
+
|
|
173
|
+
const merged = readRegularFileSync(lessonsPath) ?? ''
|
|
174
|
+
const content = pendingLessonsMarkdown(
|
|
175
|
+
readSignals(opts.inboxPath),
|
|
176
|
+
merged,
|
|
177
|
+
opts.timestamp ?? new Date().toISOString(),
|
|
178
|
+
)
|
|
179
|
+
writePendingLessons(content, opts.pendingPath)
|
|
180
|
+
return { total: content ? (content.match(/^## /gm)?.length ?? 0) : 0 }
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* 收件箱信号 → `/crsi propose` 能吃的 insight 形状。
|
|
185
|
+
*
|
|
186
|
+
* 这是「重启后仍能学习」那一步:`produceCrsiProposal` 只认 `CrsiInsight[]`,
|
|
187
|
+
* 而进程内的 `accumulatedInsights` 重启即空。
|
|
188
|
+
*/
|
|
189
|
+
export function insightsToSignals(insights: CrsiInsight[]): CrsiSignal[] {
|
|
190
|
+
return insights.map((insight) => ({
|
|
191
|
+
category: insight.category,
|
|
192
|
+
title: insight.description,
|
|
193
|
+
severity: insight.severity,
|
|
194
|
+
suggestion: insight.suggestion,
|
|
195
|
+
evidence: insight.evidence,
|
|
196
|
+
}))
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* 按顶层 `## ` 把教训 markdown 切成块(前言/说明不混进任何一块)。
|
|
201
|
+
*
|
|
202
|
+
* pending 文件是独立写的,并入前要逐块与 `crsi-lessons.md` 比对 —— 按块比对,
|
|
203
|
+
* 不按整份文本比对,才能做到「只并入新的那几条」。
|
|
204
|
+
*/
|
|
205
|
+
export function splitLessonBlocks(markdown: string): string[] {
|
|
206
|
+
const blocks: string[] = []
|
|
207
|
+
let current: string[] | null = null
|
|
208
|
+
for (const line of markdown.split('\n')) {
|
|
209
|
+
if (line.startsWith('## ')) {
|
|
210
|
+
if (current) blocks.push(current.join('\n'))
|
|
211
|
+
current = [line]
|
|
212
|
+
continue
|
|
213
|
+
}
|
|
214
|
+
if (current) current.push(line)
|
|
215
|
+
}
|
|
216
|
+
if (current) blocks.push(current.join('\n'))
|
|
217
|
+
return blocks
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
export function pendingToInsights(signals: CrsiSignal[]): CrsiInsight[] {
|
|
221
|
+
return signals.map((signal) => ({
|
|
222
|
+
category: signal.category,
|
|
223
|
+
description: signal.title,
|
|
224
|
+
severity:
|
|
225
|
+
signal.severity === 'critical' || signal.severity === 'warning' ? signal.severity : 'info',
|
|
226
|
+
suggestion: signal.suggestion,
|
|
227
|
+
evidence: signal.evidence,
|
|
228
|
+
autoApplicable: true,
|
|
229
|
+
}))
|
|
230
|
+
}
|
package/src/core/engine.ts
CHANGED
|
@@ -1587,6 +1587,10 @@ export class QueryEngine {
|
|
|
1587
1587
|
}
|
|
1588
1588
|
const effectiveParams = gateOutcome.params
|
|
1589
1589
|
const hookWarnings = gateOutcome.warnings
|
|
1590
|
+
// The SIS pre-flight scored the signature by applying its fix; score the
|
|
1591
|
+
// outcome here, once the call actually runs (or throws).
|
|
1592
|
+
const sisFixSignature = gateOutcome.sisFixSignature
|
|
1593
|
+
let sisOutcomeRecorded = false
|
|
1590
1594
|
|
|
1591
1595
|
// The gate at the top of this method ruled on `params`. Everything since —
|
|
1592
1596
|
// the PreToolUse hook's `modifiedInput`, the CRSI RuleEngine's `modified`, the
|
|
@@ -1657,13 +1661,23 @@ export class QueryEngine {
|
|
|
1657
1661
|
// permit a merge. Recorded on the one funnel every tool call passes.
|
|
1658
1662
|
noteToolOutcome(reviewLedger, this.sessionId, name, effectiveParams, result.success)
|
|
1659
1663
|
|
|
1664
|
+
// SIS feedback: the pre-flight applied a signature's fix, so this result is
|
|
1665
|
+
// that fix's outcome. Without this line `successRate` never moves and the
|
|
1666
|
+
// confidence gate can never open (2026-11-26).
|
|
1667
|
+
if (sisFixSignature) {
|
|
1668
|
+
this.getPreFlightChecker().recordOutcome(sisFixSignature, result.success)
|
|
1669
|
+
sisOutcomeRecorded = true
|
|
1670
|
+
}
|
|
1671
|
+
|
|
1660
1672
|
// Prepend PreToolUse `additionalContext` to the result — on failure too.
|
|
1661
1673
|
// It used to ride only on success, so a hook that warned "this command is
|
|
1662
1674
|
// about to fail because X" lost its warning at exactly the moment the
|
|
1663
1675
|
// command failed (CC 2.1.110-027). A failed result is projected as
|
|
1664
1676
|
// `error || content`, so the warning goes where it is actually read.
|
|
1665
1677
|
if (hookWarnings.length > 0) {
|
|
1666
|
-
|
|
1678
|
+
// Same bound as compaction context: a hook (or a rule) can print a whole
|
|
1679
|
+
// file, and this text is prepended to every matching tool result.
|
|
1680
|
+
const warning = this.capHookContext(hookWarnings.join('\n'))
|
|
1667
1681
|
if (result.success) {
|
|
1668
1682
|
result.content = warning + '\n' + (result.content || '')
|
|
1669
1683
|
} else if (result.error) {
|
|
@@ -1686,9 +1700,8 @@ export class QueryEngine {
|
|
|
1686
1700
|
result.content = postResult.updatedOutput
|
|
1687
1701
|
}
|
|
1688
1702
|
if (postResult.additionalContext) {
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
: postResult.additionalContext
|
|
1703
|
+
const context = this.capHookContext(postResult.additionalContext)
|
|
1704
|
+
result.content = result.content ? result.content + '\n' + context : context
|
|
1692
1705
|
}
|
|
1693
1706
|
}
|
|
1694
1707
|
|
|
@@ -1738,6 +1751,14 @@ export class QueryEngine {
|
|
|
1738
1751
|
})
|
|
1739
1752
|
}
|
|
1740
1753
|
|
|
1754
|
+
// The applied SIS fix was followed by a thrown error — score the failure.
|
|
1755
|
+
// Guarded by the flag so a throw *after* a completed run (a hook, the
|
|
1756
|
+
// post-flight checker) cannot retroactively fail a fix that worked.
|
|
1757
|
+
if (sisFixSignature && !sisOutcomeRecorded) {
|
|
1758
|
+
this.getPreFlightChecker().recordOutcome(sisFixSignature, false)
|
|
1759
|
+
sisOutcomeRecorded = true
|
|
1760
|
+
}
|
|
1761
|
+
|
|
1741
1762
|
// Sanitize error: strip stack traces and internal paths to prevent
|
|
1742
1763
|
// information disclosure to the LLM conversation context.
|
|
1743
1764
|
const message =
|
|
@@ -2034,11 +2055,11 @@ export class QueryEngine {
|
|
|
2034
2055
|
type: 'warning',
|
|
2035
2056
|
content: reasoningOnly
|
|
2036
2057
|
? `${activeId} returned only reasoning and no answer — retrying once`
|
|
2037
|
-
: `${activeId} failed (${failure}) — retrying once`,
|
|
2058
|
+
: `${activeId} failed (${explainTransportFailure(failure ?? 'Unknown error')}) — retrying once`,
|
|
2038
2059
|
restart: true,
|
|
2039
2060
|
}
|
|
2040
2061
|
}
|
|
2041
|
-
const detail = failure ?? 'Unknown error'
|
|
2062
|
+
const detail = explainTransportFailure(failure ?? 'Unknown error')
|
|
2042
2063
|
|
|
2043
2064
|
// Deterministic failure: re-sending it to another provider cannot change the
|
|
2044
2065
|
// answer, so surface it once rather than burning the fallback on it.
|
|
@@ -2472,8 +2493,9 @@ export class QueryEngine {
|
|
|
2472
2493
|
return
|
|
2473
2494
|
}
|
|
2474
2495
|
|
|
2475
|
-
// Feed the block reason back to the AI and continue
|
|
2476
|
-
|
|
2496
|
+
// Feed the block reason back to the AI and continue. A hook that blocks with
|
|
2497
|
+
// a whole log attached must not overflow the context it just refused to end.
|
|
2498
|
+
this.context.injectContext(block.source, this.capHookContext(block.text))
|
|
2477
2499
|
yield* this.continueWithTools(signal, roundsLeft)
|
|
2478
2500
|
}
|
|
2479
2501
|
|
|
@@ -2572,16 +2594,47 @@ function toolResultText(content: ContentBlock[]): string {
|
|
|
2572
2594
|
* Kept narrow on purpose: a false positive costs one wasted compaction (the turn
|
|
2573
2595
|
* retries either way), while a false negative ends the turn with a raw upstream
|
|
2574
2596
|
* error the user cannot act on. All of these phrasings are ones the providers
|
|
2575
|
-
* actually send — the
|
|
2576
|
-
*
|
|
2597
|
+
* actually send — the 413 family is what a proxy or gateway in front of the
|
|
2598
|
+
* provider returns when the *request* is over its limit (retrying it verbatim
|
|
2599
|
+
* fails identically; compacting is what changes the size), and the last is the
|
|
2600
|
+
* one a 1M-context model returns while the account has not enabled the charge.
|
|
2577
2601
|
*/
|
|
2578
2602
|
export function isContextOverflowError(message: string | null | undefined): boolean {
|
|
2579
2603
|
if (!message) return false
|
|
2580
|
-
return /context[_ ]length|context window|prompt is too long|input is too long|too many tokens|maximum context length|exceeds? the (?:model'?s )?(?:maximum )?context|usage credits required for 1m context/i.test(
|
|
2604
|
+
return /context[_ ]length|context window|prompt is too long|input is too long|too many tokens|maximum context length|exceeds? the (?:model'?s )?(?:maximum )?context|usage credits required for 1m context|\b413\b|payload too large|request entity too large|request (?:body |size )?too large/i.test(
|
|
2581
2605
|
message,
|
|
2582
2606
|
)
|
|
2583
2607
|
}
|
|
2584
2608
|
|
|
2609
|
+
/**
|
|
2610
|
+
* Turn a transport-level failure into words the user can act on.
|
|
2611
|
+
*
|
|
2612
|
+
* A proxy or gateway that cuts or rewrites a compressed response surfaces as
|
|
2613
|
+
* `ZlibError: incorrect header check` or a bare JSON parse failure. Those are
|
|
2614
|
+
* diagnoses for us, not for the person reading the turn — but dropping them
|
|
2615
|
+
* entirely would take away the only clue, so the plain sentence comes first and
|
|
2616
|
+
* the original follows in parentheses.
|
|
2617
|
+
*/
|
|
2618
|
+
export function explainTransportFailure(message: string): string {
|
|
2619
|
+
if (
|
|
2620
|
+
/zlib|decompress|incorrect header check|invalid (?:stored )?block type|unexpected end of (?:file|stream)/i.test(
|
|
2621
|
+
message,
|
|
2622
|
+
)
|
|
2623
|
+
) {
|
|
2624
|
+
return (
|
|
2625
|
+
'The reply was cut or damaged in transit — a proxy or gateway is the usual cause. ' +
|
|
2626
|
+
`Try again; if it keeps happening, check the proxy. (${message})`
|
|
2627
|
+
)
|
|
2628
|
+
}
|
|
2629
|
+
if (/JSON parse error|unexpected token|unexpected end of JSON input/i.test(message)) {
|
|
2630
|
+
return (
|
|
2631
|
+
"The provider's reply could not be read (malformed JSON — often a proxy or gateway " +
|
|
2632
|
+
`rewriting the response). (${message})`
|
|
2633
|
+
)
|
|
2634
|
+
}
|
|
2635
|
+
return message
|
|
2636
|
+
}
|
|
2637
|
+
|
|
2585
2638
|
function isAbortError(err: unknown): boolean {
|
|
2586
2639
|
if (err instanceof Error && err.name === 'AbortError') return true
|
|
2587
2640
|
if (
|