@miphamai/cli 0.85.7 → 0.85.9

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.
@@ -24,6 +24,16 @@ export const LESSONS_FILE = 'apps/cli/crsi-lessons.md'
24
24
  /** 组件归因(修复决策,非因果断言):失败最可能被哪个记忆组件的局部干预修复。 */
25
25
  export type MemoryComponent = 'experiential' | 'working' | 'invocation' | 'checker'
26
26
 
27
+ /**
28
+ * 教训档位的**闭集** —— 只有两档。
29
+ *
30
+ * 与 `CrsiSignal.severity`(自由字符串,来自 insight,可能是 `info`)不同:这是**落进教训文件**
31
+ * 之后的口径。两者之间的桥是 {@link normalizeLessonSeverity},而它只有一个定义 —— 抽取器
32
+ * (读侧)与写入者(写侧)同读它。写入者若自写一份映射,「写进去的 warning」与「读出来的
33
+ * warning」就可能是两个判据(本仓库记过的「一个渲染器,两个读者」)。
34
+ */
35
+ export type LessonSeverity = 'critical' | 'warning'
36
+
27
37
  /** 归一化的教训信号(insight 与 meta-rule 的公共面)。 */
28
38
  export interface CrsiSignal {
29
39
  category: string
@@ -76,10 +86,19 @@ export function selectCrsiSignal(
76
86
  return null
77
87
  }
78
88
 
79
- /** 模板化地把信号渲染成一段教训 markdown(不动 LLM)。 */
89
+ /**
90
+ * 模板化地把信号渲染成一段教训 markdown(不动 LLM)。
91
+ *
92
+ * `severity` 是**必填参数**,且是档位的**唯一来源**(不再读 `signal.severity`)。
93
+ * 此前它读一个可选字段、缺了就**整行不打** —— 而那条缺席的后果不是「没有标签」,
94
+ * 是抽取器 fail-open 落 `critical`(常驻、每次请求都占字符)。于是「生产者忘了给档位」
95
+ * 这件事在外部读数上与「它本来就该常驻」**同形**,没有任何东西能报。
96
+ * 改成必填后,「忘了」是编译错误 —— 同 `produceProseProposal` 的 `lessonsBlock` 必填第 5 参。
97
+ */
80
98
  export function buildLessonContent(
81
99
  signal: CrsiSignal,
82
100
  timestamp: string,
101
+ severity: LessonSeverity,
83
102
  source = 'CRSI producer (autoApplicable)',
84
103
  ): string {
85
104
  const lines: string[] = [
@@ -87,53 +106,340 @@ export function buildLessonContent(
87
106
  '',
88
107
  `- 建议: ${signal.suggestion}`,
89
108
  `- 组件: ${signal.component ?? 'experiential'}`,
109
+ `- 严重度: ${severity}`,
90
110
  ]
91
- if (signal.severity) lines.push(`- 严重度: ${signal.severity}`)
92
111
  lines.push(`- 生成时间: ${timestamp}`, `- 来源: ${source}`, '', '### 证据')
93
112
  for (const e of signal.evidence) lines.push(`- ${e}`)
94
113
  lines.push('')
95
114
  return lines.join('\n')
96
115
  }
97
116
 
98
- /** 教训精华(标题 + 建议),用于运行时召回注入系统提示。 */
117
+ /**
118
+ * 教训精华(标题 + 建议 + 严重度),用于运行时召回注入系统提示。
119
+ *
120
+ * 严重度决定**注入位置**,不只是标签:`critical` 常驻每一次请求,
121
+ * `warning` 移出常驻块、按需召回(见 {@link isAlwaysOnLesson}),且常驻档整体受
122
+ * {@link RESIDENT_LESSONS_BUDGET} 约束(见 {@link selectResidentLessons})。
123
+ * 这两个数是**当时的读数、不是不变量**(2026-09-28 实测:39 条全量 11,743 字符,
124
+ * 占 40k 指令预算 29.2%;分档后 6 条常驻)。教训加减后它们就作废,别当断言读。
125
+ */
99
126
  export interface CrsiLessonSummary {
100
127
  title: string
101
128
  suggestion: string
129
+ severity: LessonSeverity
102
130
  }
103
131
 
104
132
  /**
105
- * 从 crsi-lessons.md 提取每条教训的「精华」(标题 + 建议),跳过证据段落。
133
+ * 缺 `严重度` 或取值在闭集之外时的落档。
134
+ *
135
+ * 取 `critical`(fail-open 到**常驻**):宁可多花字符,也不把一条守卫
136
+ * 静默降级成「按需」—— 那正是「只写不读」缺口的复发形态。
137
+ * 定义在**一处**:抽取器与 `flush()` 都读它,改一处即改全。
138
+ * 不导出 —— 它没有第二个读者,导出只会让「谁在用」这个问题多一个假答案。
139
+ */
140
+ const DEFAULT_LESSON_SEVERITY: LessonSeverity = 'critical'
141
+
142
+ /**
143
+ * 把任意档位取归一化到闭集:只有**逐字**的 `warning` 是 `warning`,其余一切
144
+ * (含缺席、空串、闭集外取值)落 `critical`。
145
+ *
146
+ * 方向是刻意的:不倒向「按需」。宁可多花字符,也不把一条守卫静默降级成「按需读」——
147
+ * 那正是「只写不读」缺口的复发形态。副作用要认下:`info` 也会落 `critical`(它不在闭集里)。
148
+ *
149
+ * **定义在一处**:抽取器(读侧)与两个写入者(`produceCrsiProposal` / crossover)同读它。
150
+ */
151
+ export function normalizeLessonSeverity(raw: string | undefined): LessonSeverity {
152
+ return raw === 'warning' ? 'warning' : 'critical'
153
+ }
154
+
155
+ /**
156
+ * 从 crsi-lessons.md 提取每条教训的「精华」(标题 + 建议 + 严重度),跳过证据段落。
106
157
  * 这是「只写不读」缺口 → 「写后召回」的读取侧。
158
+ *
159
+ * 按 `##` 块累积、块边界 flush —— 因为 `- 严重度:` 行写在 `- 建议:` **之后**,
160
+ * 「见到建议即 push」的写法读不到它。块级累积对行序不敏感。
161
+ *
162
+ * 缺 `严重度` 时的落档见 {@link DEFAULT_LESSON_SEVERITY}。
107
163
  */
108
164
  export function extractCrsiLessonSummaries(content: string): CrsiLessonSummary[] {
109
165
  const out: CrsiLessonSummary[] = []
110
166
  let title = ''
167
+ let suggestion = ''
168
+ let severity = DEFAULT_LESSON_SEVERITY
169
+
170
+ const flush = () => {
171
+ if (title && suggestion) out.push({ title, suggestion, severity })
172
+ title = ''
173
+ suggestion = ''
174
+ severity = DEFAULT_LESSON_SEVERITY
175
+ }
176
+
111
177
  for (const line of content.split('\n')) {
112
178
  const h = line.match(/^##\s+(.+?)\s*$/)
113
179
  if (h) {
180
+ flush()
114
181
  title = h[1]!.trim()
115
182
  continue
116
183
  }
117
184
  const s = line.match(/^-\s*建议[::]\s*(.+)$/)
118
- if (s && title) {
119
- out.push({ title, suggestion: s[1]!.trim() })
120
- title = ''
185
+ if (s) {
186
+ if (!suggestion) suggestion = s[1]!.trim() // 块内首条建议为准(与旧行为一致)
187
+ continue
188
+ }
189
+ const v = line.match(/^-\s*严重度[::]\s*(.+?)\s*$/)
190
+ if (v) {
191
+ // 闭集外的取值一律落常驻档 —— 未知严重度不倒向「按需」。规则在 normalizeLessonSeverity
192
+ // 一处;写入者同读它(正则已吃掉两侧空白,故传进去的是已经 trim 过的捕获)。
193
+ severity = normalizeLessonSeverity(v[1])
121
194
  }
122
195
  }
196
+ flush()
123
197
  return out
124
198
  }
125
199
 
126
- /** 把教训精华渲染为系统提示召回块。无教训时返回空串。 */
127
- export function buildCrsiLessonsBlock(summaries: CrsiLessonSummary[]): string {
128
- if (summaries.length === 0) return ''
129
- const items = summaries.map((s, i) => `${i + 1}. **${s.title}**\n ${s.suggestion}`).join('\n\n')
130
- return `## CRSI Lessons (Self-Improvement Recall)
200
+ /**
201
+ * 这条教训是否**有资格**常驻(非 `warning` 的一切,含缺省,都有资格)。
202
+ *
203
+ * 这是**逐条**谓词,只说「档位」,不说「进不进得去」—— 进去还要过预算,
204
+ * 见 {@link selectResidentLessons}。两个问题分开是因为两个问题的答案不同:
205
+ * 全是 critical 时这条谓词全真,而预算仍然会拦下一部分。
206
+ */
207
+ export function isAlwaysOnLesson(summary: CrsiLessonSummary): boolean {
208
+ return summary.severity !== 'warning'
209
+ }
210
+
211
+ /**
212
+ * 常驻块的字符预算,按**渲染后**的文本量算。
213
+ *
214
+ * 为什么用字符而不是条数:预算约束的是**每次请求的注入成本**,而单条教训的
215
+ * 长度差三倍以上(2026-09-28 实测 157–570 字符)—— 条数相同,成本可以差一倍。
216
+ *
217
+ * 3,000 ≈ 40k 指令预算的 7.5%(当时 6 条 critical 共 2,155 字符,还有余量)。
218
+ */
219
+ export const RESIDENT_LESSONS_BUDGET = 3000
220
+
221
+ /** {@link selectResidentLessons} 的结果。每个字段各有各的读者,不互相重算。 */
222
+ export interface ResidentLessonSelection {
223
+ /** 进常驻块的那些,**文件序** —— 渲染序稳定,不随择优顺序抖动。 */
224
+ resident: CrsiLessonSummary[]
225
+ /** 未常驻的全部(全部 warning + 被预算挤出的 critical),文件序:指针报的是它的条数。 */
226
+ demoted: CrsiLessonSummary[]
227
+ /** `demoted` 里「因预算被挤出」的那部分,文件序:指针点名的是它。 */
228
+ overBudget: CrsiLessonSummary[]
229
+ /**
230
+ * 这次选择**实际用的**预算。
231
+ *
232
+ * 由结果携带而不是让指针去读常量:常量是「默认值」,不一定是「这一次的值」。
233
+ * 指针报一个与实际不符的数,就是又一个「报告描述的不是发出去的那份」。
234
+ */
235
+ budget: number
236
+ }
237
+
238
+ /**
239
+ * 选出真正进常驻块的那些 —— **唯一的择优点**,两个读者都必须走这里。
240
+ *
241
+ * 为什么要有预算:`severity` 是**逐条**的谓词,预算是**整档**的性质。两者错配的
242
+ * 后果是没有东西能说「常驻档太大了」—— 全是 critical 时,每加一条教训就是每次
243
+ * 请求都多付一份钱,且没有上限。
244
+ *
245
+ * 超预算的 critical **不丢弃**:它们落进 `demoted`,由指针点名。无声消失与
246
+ * 「从来没写过这条教训」在外部读数上同形。
247
+ *
248
+ * 择优方向是**文件倒序**(新的优先留下):文件是追加写的 ⇒ 越靠后越新,而越近的
249
+ * 失败越相关。选中后仍按文件序渲染,避免常驻块的顺序随预算抖动。
250
+ *
251
+ * 单条自身就超预算时它自己出局(在指针里被点名):预算约束的是**总量**,最长的
252
+ * 单条没有豁免权;截断正文会篡改建议本身,所以不做。
253
+ */
254
+ export function selectResidentLessons(
255
+ summaries: CrsiLessonSummary[],
256
+ budget: number = RESIDENT_LESSONS_BUDGET,
257
+ ): ResidentLessonSelection {
258
+ const criticals = summaries.filter(isAlwaysOnLesson)
259
+ let resident: CrsiLessonSummary[] = []
260
+ const overBudget: CrsiLessonSummary[] = []
261
+
262
+ for (let i = criticals.length - 1; i >= 0; i--) {
263
+ const lesson = criticals[i]!
264
+ const candidate = [lesson, ...resident]
265
+ if (buildCrsiLessonsBlock(candidate).length <= budget) {
266
+ resident = candidate
267
+ } else {
268
+ overBudget.unshift(lesson)
269
+ }
270
+ }
271
+
272
+ return {
273
+ resident,
274
+ demoted: summaries.filter((s) => !resident.includes(s)),
275
+ overBudget,
276
+ budget,
277
+ }
278
+ }
279
+
280
+ /**
281
+ * 常驻块的表头(含与正文之间的那个空行),与 {@link buildCrsiLessonsBlock} **共用**。
282
+ *
283
+ * 抽出来是因为常驻档名册要报**逐条**成本,而「逐条和 ≠ 合计」的差额正是这块表头 ——
284
+ * 各写一份,两处迟早对不上,且对不上的时候没人知道该信哪个。
285
+ */
286
+ const CRSI_LESSONS_HEADER = `## CRSI Lessons (Self-Improvement Recall)
131
287
 
132
288
  These are hard-won lessons consolidated by the CRSI self-improvement
133
289
  loop from past sessions. Apply them proactively — do not repeat these
134
290
  mistakes:
135
291
 
136
- ${items}`
292
+ `
293
+
294
+ /**
295
+ * 一条教训在块里的**逐字**形状,与 {@link buildCrsiLessonsBlock} 共用。
296
+ *
297
+ * 序号参与渲染 ⇒ 同一个 `summary` 在不同位置长度不同;常驻档名册按文件序渲染,
298
+ * 与块里看到的序号一致。
299
+ */
300
+ const renderLessonItem = (s: CrsiLessonSummary, i: number): string =>
301
+ `${i + 1}. **${s.title}**\n ${s.suggestion}`
302
+
303
+ /** 逐条之间的分隔符 —— `.join('\n\n')` 的那个 `\n\n`。名册的加法算式要用它的长度。 */
304
+ const LESSON_ITEM_SEPARATOR = '\n\n'
305
+
306
+ /** 把教训精华渲染为系统提示召回块。无教训时返回空串。 */
307
+ export function buildCrsiLessonsBlock(summaries: CrsiLessonSummary[]): string {
308
+ if (summaries.length === 0) return ''
309
+ const items = summaries.map(renderLessonItem).join(LESSON_ITEM_SEPARATOR)
310
+ return `${CRSI_LESSONS_HEADER}${items}`
311
+ }
312
+
313
+ /** 指针最多点名几条被挤出的 critical —— 否则指针自己成了新的无界常驻成本。 */
314
+ const POINTER_NAME_LIMIT = 3
315
+
316
+ /**
317
+ * 未常驻教训的指针行,由 {@link selectResidentLessons} 的结果渲染。全部常驻时返回空串。
318
+ *
319
+ * 指针是**召回触发点**:没有它,移出常驻块就等于把教训变成只写不读。
320
+ * 它不重复正文,只报条数、点名被预算挤出的 critical、给出文件路径 —— 模型用已有的
321
+ * Read/Grep 工具自取(那份文件的路径就是 `lessonsPath`)。
322
+ *
323
+ * 为什么必须把「被预算挤出」与「本来就是 warning」分开说:对读者而言这是两件事 ——
324
+ * 前者是**预算问题**(有杠杆可拉:给别的降档、或把这条缩短),后者是**设计如此**。
325
+ * 混成一句,前者看上去就是后者,问题永远不会有人发现。
326
+ */
327
+ export function buildCrsiLessonsPointer(
328
+ selection: ResidentLessonSelection,
329
+ lessonsPath: string,
330
+ ): string {
331
+ const { demoted, overBudget, budget } = selection
332
+ if (demoted.length === 0) return ''
333
+
334
+ const lines = [`另有 ${demoted.length} 条教训未常驻。`]
335
+
336
+ if (overBudget.length > 0) {
337
+ const named = overBudget.slice(0, POINTER_NAME_LIMIT).map((s) => s.title)
338
+ const tail = overBudget.length > named.length ? ` 等 ${overBudget.length} 条` : ''
339
+ lines.push(
340
+ `其中 ${overBudget.length} 条 critical 因常驻档预算(${budget} 字符)` +
341
+ `被挤出:${named.join('、')}${tail}。`,
342
+ )
343
+ }
344
+
345
+ lines.push(`需要时读 ${lessonsPath}(含标题/建议/证据)。`)
346
+ return lines.join('\n')
347
+ }
348
+
349
+ /**
350
+ * 常驻档名册 —— `selectResidentLessons` 的**第三个读者**,也是**唯一给人看的**那一个。
351
+ *
352
+ * 前两个读者的输出都进了**模型**的上下文(系统提示、`--prose` 算子)。而常驻档的成本
353
+ * 是**人**在付:每一条 `critical` 都随每次请求发出去,永远。能动手的也只有人 —— 把某条
354
+ * 改成 `- 严重度: warning`、或把最长的那条缩短。在此之前,「这档涨得值不值」这件事
355
+ * **没有任何材料可查**:预算只是**上限**,不是**理由**;而启动期那条体积告警只在指令
356
+ * **总额**超 40k 时说话、且只点名最大的三个文件 —— 教训块那两千多字符排不进去,等于不报。
357
+ *
358
+ * 与两个既有读者的关系:**共用** {@link selectResidentLessons}(唯一的择优点)⇒
359
+ * 报告不可能与真正注入的那一份漂移。逐条成本按**渲染后的文本量**算,且报出可验算的
360
+ * 加法(表头 + 逐条 + 分隔 == 合计)—— 否则「逐条和 ≠ 合计」会被当成 bug 查一遍。
361
+ *
362
+ * 只读:**不加写路径**。人的杠杆是改文件那一行;写入侧是生产者与 `/crsi propose`。
363
+ */
364
+ export function buildResidentLessonReport(
365
+ selection: ResidentLessonSelection,
366
+ lessonsPath: string,
367
+ ): string {
368
+ const { resident, demoted, overBudget, budget } = selection
369
+ const num = (n: number) => n.toLocaleString('en-US')
370
+
371
+ if (resident.length === 0 && demoted.length === 0) {
372
+ return `## CRSI 常驻教训(每次请求都注入)\n\n教训文件里没有可召回的教训:${lessonsPath}`
373
+ }
374
+
375
+ const itemChars = resident.map((s, i) => renderLessonItem(s, i).length)
376
+ const items = itemChars.reduce((a, b) => a + b, 0)
377
+ const seps = LESSON_ITEM_SEPARATOR.length * Math.max(0, resident.length - 1)
378
+ const header = resident.length > 0 ? CRSI_LESSONS_HEADER.length : 0
379
+ const total = header + items + seps
380
+ const block = buildCrsiLessonsBlock(resident).length
381
+ const headroom = budget - total
382
+ const used = budget > 0 ? ((total / budget) * 100).toFixed(1) : '—'
383
+
384
+ const lines: string[] = ['## CRSI 常驻教训(每次请求都注入)', '']
385
+ lines.push(
386
+ `常驻 **${resident.length}** 条 / ${num(total)} 字符 · 预算 ${num(budget)}` +
387
+ `(余量 ${num(headroom)},已用 ${used}%)`,
388
+ )
389
+ lines.push(
390
+ `未常驻 **${demoted.length}** 条` +
391
+ (overBudget.length > 0
392
+ ? `(其中 **${overBudget.length}** 条因预算被挤出:${overBudget.map((s) => s.title).join('、')})`
393
+ : '(无因预算被挤出的)'),
394
+ )
395
+
396
+ if (resident.length > 0) {
397
+ lines.push('', '### 逐条成本(渲染后字符)', '')
398
+ for (let i = 0; i < resident.length; i++) {
399
+ lines.push(`- ${num(itemChars[i]!)} 字符 — ${resident[i]!.title}`)
400
+ }
401
+ // 加法自证:表头是每条共担的,逐条和必然大于合计 —— 与其让人去猜差额,
402
+ // 不如把算式写出来,且当场验算(`block` 走的是真渲染器,不是我在这里的手算)。
403
+ lines.push(
404
+ '',
405
+ `合计 ${num(total)} = 表头 ${num(header)} + 逐条 ${num(items)} + 分隔 ${num(seps)}` +
406
+ `(${LESSON_ITEM_SEPARATOR.length} × ${Math.max(0, resident.length - 1)})` +
407
+ ` — 与渲染器实测${block === total ? '相符' : `**不符(${num(block)})**`}`,
408
+ )
409
+ }
410
+
411
+ lines.push(
412
+ '',
413
+ `指针另有 ${num(buildCrsiLessonsPointer(selection, lessonsPath).length)} 字符,**不含在预算内**` +
414
+ `(预算量的是常驻块本身)。`,
415
+ '',
416
+ `文件:${lessonsPath}`,
417
+ '把某条移出常驻档 = 把它的 `- 严重度:` 改成 `warning`。',
418
+ )
419
+ return lines.join('\n')
420
+ }
421
+
422
+ /**
423
+ * 读教训文件、渲染**常驻**(critical)教训块,供生成算子内联。
424
+ *
425
+ * 与 `InstructionsLoader.crsiLessonsText()` 是**两份投影**,此处刻意**不带指针**:
426
+ * 指针要求读者用 Read/Grep 自取,而生成算子是无工具的 `llm.chat` 单条消息 ——
427
+ * 对它而言指针等于零,只能内联或什么都不给。
428
+ *
429
+ * 择点必须与那份投影**共用** `selectResidentLessons`:两份投影各选各的,
430
+ * 就会出现「主代理看到的常驻集」与「算子看到的常驻集」不是同一个 ——
431
+ * 局部正确、全局遗漏。
432
+ *
433
+ * 文件缺席 ⇒ 空串:算子退回「无教训」的旧形状(纯增量,不改既有行为)。
434
+ */
435
+ export function loadAlwaysOnLessonsBlock(lessonsPath: string): string {
436
+ if (!existsSync(lessonsPath)) return ''
437
+ try {
438
+ const summaries = extractCrsiLessonSummaries(readFileSync(lessonsPath, 'utf-8'))
439
+ return buildCrsiLessonsBlock(selectResidentLessons(summaries).resident)
440
+ } catch {
441
+ return ''
442
+ }
137
443
  }
138
444
 
139
445
  /** 产出教训文件变更候选。无合格信号时返回 null。 */
@@ -155,7 +461,9 @@ export function produceCrsiProposal(
155
461
  // 幂等:同一信号的教训标题已在文件中,不再重复产出。
156
462
  if (currentLessons.includes(`## ${signal.category}: ${signal.title}`)) return null
157
463
 
158
- const lesson = buildLessonContent(signal, timestamp)
464
+ // 档位显式取归一化后的值:`signal.severity` 来自 insight(可能是 `info` 或缺席),
465
+ // 它**不是**闭集口径。不给这个参数是编译错误 —— 这就是「忘了给档位」的落点。
466
+ const lesson = buildLessonContent(signal, timestamp, normalizeLessonSeverity(signal.severity))
159
467
  const newContent = currentLessons ? `${currentLessons.trimEnd()}\n\n${lesson}\n` : `${lesson}\n`
160
468
 
161
469
  return {
@@ -285,7 +593,7 @@ export function produceRuleProposal(
285
593
  // ── Producer 散文提议(块 1):从失败信号生成「改 skill 散文」提议 ──
286
594
  // A1 边界首次实演:LLM 只作「生成」(候选),判定仍走确定性(guard 预筛 / 行为效果 / 人审)。
287
595
 
288
- const PROSE_SELECT_PROMPT_VERSION = '1.0.0'
596
+ const PROSE_SELECT_PROMPT_VERSION = '1.1.0'
289
597
 
290
598
  function buildSelectSkillPrompt(signal: CrsiSignal, skillFiles: string[]): string {
291
599
  return [
@@ -294,15 +602,16 @@ function buildSelectSkillPrompt(signal: CrsiSignal, skillFiles: string[]): strin
294
602
  '失败信号:',
295
603
  `- category: ${signal.category}`,
296
604
  `- title: ${signal.title}`,
297
- signal.severity ? `- severity: ${signal.severity}` : '',
605
+ // 缺席(空串)时不占行 —— 与 `buildGenerateProsePrompt` 同一个写法。
606
+ // **不能靠 `.filter(Boolean)` 做这件事**:它分不清「本该丢的条件空串」与「上面那几个
607
+ // 故意的段落分隔符」,于是把三段式结构一并吃掉(实测本函数的提示词里 `\n\n` 一次都没有)。
608
+ ...(signal.severity ? [`- severity: ${signal.severity}`] : []),
298
609
  `- suggestion: ${signal.suggestion}`,
299
610
  `- evidence: ${signal.evidence.join(' | ')}`,
300
611
  '',
301
612
  '候选 skill 文件:',
302
613
  ...skillFiles.map((f) => `- ${f}`),
303
- ]
304
- .filter(Boolean)
305
- .join('\n')
614
+ ].join('\n')
306
615
  }
307
616
 
308
617
  async function collectLlmText(llm: Llm, prompt: string): Promise<string> {
@@ -337,15 +646,19 @@ export async function selectTargetSkill(
337
646
  return extractFilePath(response, skillFiles)
338
647
  }
339
648
 
340
- const PROSE_GENERATE_PROMPT_VERSION = '1.1.0'
649
+ const PROSE_GENERATE_PROMPT_VERSION = '1.2.0'
341
650
 
342
651
  function buildGenerateProsePrompt(
343
652
  signal: CrsiSignal,
344
653
  filePath: string,
345
654
  originalContent: string,
655
+ lessonsBlock: string,
346
656
  ): string {
347
657
  return [
348
658
  `你是 CRSI producer(producer-prose-generate v${PROSE_GENERATE_PROMPT_VERSION})。基于失败信号,改进目标 skill 的内容。`,
659
+ // 常驻教训**内联**(不是指针):算子是无工具的 `llm.chat` 单条消息,给它指针等于零。
660
+ // 缺席(空串)时不占行 —— 无教训的提示词与从前**逐字相同**(纯增量)。
661
+ ...(lessonsBlock ? ['', lessonsBlock] : []),
349
662
  '',
350
663
  '失败信号:',
351
664
  `- category: ${signal.category}`,
@@ -381,6 +694,52 @@ export interface ProsePrediction {
381
694
  risk?: string
382
695
  }
383
696
 
697
+ /**
698
+ * 净变化(未判定):正文字符数与行数的增减。
699
+ *
700
+ * 这是 `#20 simplicity: 未要求的功能是负债` **唯一可机械化的那一半** —— 判「这份改写
701
+ * 是不是加了没要求的功能」需要语义裁判(违反 A1 铁律),而「它长大了多少」是算得出来的事实。
702
+ * 故与 `formatCostLine` / 风险声明同一纪律:**只呈现、不判定**,标签必须带「未判定」,
703
+ * 否则这一行会被读成「已经审过了」。
704
+ *
705
+ * 注意它不是 diff stat:只报**净额**,不报增删行数。
706
+ * 行数定义 = 换行符数 + (末尾无换行且非空 ? 1 : 0)—— 定义写死,否则这个数不可证伪。
707
+ */
708
+ export function formatNetChange(original: string, updated: string): string {
709
+ const signed = (n: number) => (n > 0 ? `+${n}` : String(n))
710
+ const chars = updated.length - original.length
711
+ const lines = countLines(updated) - countLines(original)
712
+ return `📐 净变化(未判定): 字符 ${signed(chars)},行 ${signed(lines)}`
713
+ }
714
+
715
+ function countLines(s: string): number {
716
+ if (s === '') return 0
717
+ const breaks = s.split('\n').length - 1
718
+ return s.endsWith('\n') ? breaks : breaks + 1
719
+ }
720
+
721
+ /**
722
+ * 档位迁移(**只呈现、不判定**)—— 与 `formatNetChange` / `formatCostLine` / 事前风险同一纪律。
723
+ *
724
+ * 报的是**实际写进去的**档位(第 3 参 `merged`),不是按 `deriveMergedSeverity` 应得的那个:
725
+ * 报告要报实际用的那个数,否则读数描述的是规则、不是这次渲染(同 `ResidentLessonSelection.budget`)。
726
+ *
727
+ * **恒打**(含无变化),同 `formatNetChange` 的理由:「这次没升档」正是那条可证伪的基线读数,
728
+ * 只打有变化的等于让读者看不见基线。两个源与产物都已知 ⇒ 语法上不存在「打不出来」的情况。
729
+ *
730
+ * `⬆` 的判据是**相对更宽的那个源**(合并把地板抬起来了吗)—— 因为那才是成本事件:
731
+ * 一条非常驻的教训经合并变成常驻的,占预算。收尾不带换行:回执自己加(否则会与前一行粘连)。
732
+ */
733
+ export function formatSeverityShift(
734
+ a: LessonSeverity,
735
+ b: LessonSeverity,
736
+ merged: LessonSeverity,
737
+ ): string {
738
+ const floor: LessonSeverity = a === 'warning' || b === 'warning' ? 'warning' : 'critical'
739
+ const arrow = merged === 'critical' && floor === 'warning' ? '⬆' : '='
740
+ return `${arrow} 档位(按更严来源派生): ${a} + ${b} → ${merged}`
741
+ }
742
+
384
743
  /**
385
744
  * 解析 prose 响应:可选的一行 JSON 前缀(ε)+ 正文。
386
745
  *
@@ -429,8 +788,9 @@ export async function generateProseContent(
429
788
  llm: Llm,
430
789
  filePath: string,
431
790
  originalContent: string,
791
+ lessonsBlock: string,
432
792
  ): Promise<ProsePrediction | null> {
433
- const prompt = buildGenerateProsePrompt(signal, filePath, originalContent)
793
+ const prompt = buildGenerateProsePrompt(signal, filePath, originalContent, lessonsBlock)
434
794
  const response = await collectLlmText(llm, prompt)
435
795
  if (!response) return null
436
796
  return parseProsePrediction(response)
@@ -452,6 +812,12 @@ export async function produceProseProposal(
452
812
  llm: Llm,
453
813
  skillFiles: string[],
454
814
  readSkill: (filePath: string) => string,
815
+ /**
816
+ * 常驻教训块(由 `loadAlwaysOnLessonsBlock` 渲染)。**故意必填**:漏传或传 `''`
817
+ * 会让「算子收到教训」这件事静默失效 —— 而它正是本函数存在的意义之一。
818
+ * 必填把「忘了」从静默行为变更变成编译错误。
819
+ */
820
+ lessonsBlock: string,
455
821
  ): Promise<ProseProposalResult | null> {
456
822
  const filePath = await selectTargetSkill(signal, llm, skillFiles)
457
823
  if (!filePath) return null
@@ -463,7 +829,7 @@ export async function produceProseProposal(
463
829
  return null
464
830
  }
465
831
 
466
- const generated = await generateProseContent(signal, llm, filePath, originalContent)
832
+ const generated = await generateProseContent(signal, llm, filePath, originalContent, lessonsBlock)
467
833
  if (!generated || !generated.body) return null
468
834
 
469
835
  return {
@@ -638,9 +1004,28 @@ export function removeLessonSections(content: string, headers: string[]): string
638
1004
  return out.join('\n')
639
1005
  }
640
1006
 
1007
+ /**
1008
+ * 合并产物的档位:取两个源中**更严**的那个。
1009
+ *
1010
+ * 三条理由,每条都取自本仓库既有的决定而非新偏好:
1011
+ * 1. **不问 LLM** —— 档位是「这条要不要每次请求都在场」的判定,属 A1 铁律的判定侧,
1012
+ * 只能由确定性规则给(LLM 只生成)⇒ 不可伪造、不可幻觉。
1013
+ * 2. **不取更宽** —— 那会把一个 critical 经合并洗成按需,正是抽取器注释里
1014
+ * 「未知严重度不倒向『按需』」拒绝的方向。
1015
+ * 3. **不停在「缺省 critical」** —— 那个缺省是给**人类新写**的条目兜底的;合并是**降维**,
1016
+ * 没有依据说产物比两个源更紧急。实测(真模块):两条 warning 合并曾升进常驻档,
1017
+ * 常驻 6 条 2,155 字符 → 7 条 2,198,而这一切发生在**没有人决定过**的情况下。
1018
+ */
1019
+ export function deriveMergedSeverity(a: LessonSeverity, b: LessonSeverity): LessonSeverity {
1020
+ return a === 'critical' || b === 'critical' ? 'critical' : 'warning'
1021
+ }
1022
+
641
1023
  /**
642
1024
  * Crossover:合并两条重叠教训 → 「删二增一」的教训文件变更候选。
643
1025
  * LLM 只生成(选对 + 合并版),guard 校验所选教训真实存在(fail-closed 防幻觉)。
1026
+ *
1027
+ * 档位**不在 LLM 的契约里**(提示词只列举 category/title/suggestion/evidence),
1028
+ * 由 `deriveMergedSeverity` 从两个源确定性派生 —— 见该函数的理由。
644
1029
  */
645
1030
  export async function produceCrossoverProposal(
646
1031
  llm: Llm,
@@ -653,6 +1038,10 @@ export async function produceCrossoverProposal(
653
1038
  originalContent: string
654
1039
  blastRadius: string[]
655
1040
  merge: boolean
1041
+ /** 两个源的档位(按 LLM 选定的顺序)与实际写进产物的档位,供回执呈现。 */
1042
+ severityA: LessonSeverity
1043
+ severityB: LessonSeverity
1044
+ mergedSeverity: LessonSeverity
656
1045
  } | null> {
657
1046
  const response = await collectLlmText(llm, buildCrossoverPrompt(currentLessons))
658
1047
  if (!response) return null
@@ -668,8 +1057,22 @@ export async function produceCrossoverProposal(
668
1057
  const lessonLines = currentLessons.split('\n').map((l) => l.trim())
669
1058
  if (!lessonLines.includes(headerA) || !lessonLines.includes(headerB)) return null
670
1059
 
1060
+ // 档位走**读侧同一个抽取器**(不另写一个解析器):`- 严重度:` 写在 `- 建议:` 之后,
1061
+ // 且「有标题没建议」的段抽取器不产出 ⇒ 查不到即 fail-closed 落 critical(同上面第 3 条方向)。
1062
+ const summaries = extractCrsiLessonSummaries(currentLessons)
1063
+ const severityOf = (header: string): LessonSeverity =>
1064
+ normalizeLessonSeverity(summaries.find((s) => `## ${s.title}` === header)?.severity)
1065
+ const severityA = severityOf(headerA)
1066
+ const severityB = severityOf(headerB)
1067
+ const mergedSeverity = deriveMergedSeverity(severityA, severityB)
1068
+
671
1069
  const withoutTwo = removeLessonSections(currentLessons, [headerA, headerB])
672
- const mergedSection = buildLessonContent(parsed.merged, timestamp, 'CRSI producer (crossover)')
1070
+ const mergedSection = buildLessonContent(
1071
+ parsed.merged,
1072
+ timestamp,
1073
+ mergedSeverity,
1074
+ 'CRSI producer (crossover)',
1075
+ )
673
1076
  const newContent = `${withoutTwo.trimEnd()}\n\n${mergedSection}\n`
674
1077
 
675
1078
  return {
@@ -679,5 +1082,8 @@ export async function produceCrossoverProposal(
679
1082
  originalContent: currentLessons,
680
1083
  blastRadius: [LESSONS_FILE],
681
1084
  merge: true,
1085
+ severityA,
1086
+ severityB,
1087
+ mergedSeverity,
682
1088
  }
683
1089
  }
@@ -54,6 +54,13 @@ export interface CrsiModificationResult {
54
54
  diff?: string
55
55
  /** Error message if something failed */
56
56
  error?: string
57
+ /**
58
+ * 奖励闸的附注:过闸,但闸本身**没有完整施加**时的可见声明。
59
+ *
60
+ * 目前唯一的来源是「rewardFn 不提供逐契约结果 ⇒ anchor 闸未施加」。
61
+ * 不静默跳过 —— 沉默与「anchor 全绿」在外部读数上同形。
62
+ */
63
+ rewardNote?: string
57
64
  /** Current phase of the sandbox pipeline */
58
65
  phase:
59
66
  'pending' | 'applied' | 'testing' | 'passed' | 'failed' | 'approved' | 'merged' | 'rolled-back'