@miphamai/cli 0.85.9 → 0.85.11

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.81.7
1
+ # Mipham Code v0.85.11
2
2
 
3
3
  **Multi-model open-core intelligent coding terminal** — 12 AI providers, 138 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.9",
3
+ "version": "0.85.11",
4
4
  "description": "Mipham Code — Multi-model open-core intelligent coding terminal by MiphamAI",
5
5
  "keywords": [
6
6
  "ai",
@@ -22,6 +22,27 @@ function getPatternAnalyzer(): PatternAnalyzer {
22
22
  return _patternAnalyzer
23
23
  }
24
24
 
25
+ /** 每进程每条只念一次 —— 与 `core/permission-audit.ts` 的 `warnedOnce` 同形。 */
26
+ const warnedAgentCaps = new Set<string>()
27
+
28
+ /**
29
+ * 项目级 agent 想把自己抬到比父会话更宽、被 `resolveAgentMode` 顶回去时,把这件事念出来。
30
+ *
31
+ * **不静默**是本仓库的既有口径 —— `config/loader.ts` 的 `stripProjectPermission` 对项目级
32
+ * 权限是**拒绝并报告**,不是忽略;agent 定义这条路径此前既不拒绝也不报告。stderr 是本仓库
33
+ * 既有的告警通道(`core/permission-audit.ts` / `core/hooks.ts` / `core/workspace-trust.ts` 同形)。
34
+ *
35
+ * 判读与措辞在 `resolveAgentMode` 里,这里只补上它拿不到的那一半 —— agent 的名字。
36
+ */
37
+ function reportAgentCapWarnings(gate: PermissionSystem, agentName?: string): void {
38
+ for (const warning of gate.getAgentCapWarnings()) {
39
+ const line = `⚠️ agent "${agentName ?? 'unknown'}": ${warning}\n`
40
+ if (warnedAgentCaps.has(line)) continue
41
+ warnedAgentCaps.add(line)
42
+ process.stderr.write(line)
43
+ }
44
+ }
45
+
25
46
  const TYPE_SYSTEM_PROMPTS: Record<SubAgentType, string> = {
26
47
  general: 'You are a focused sub-agent. Complete the assigned task thoroughly and return results.',
27
48
  explore:
@@ -262,7 +283,9 @@ export class SubAgent {
262
283
  agentDef?.permissionMode && agentDef.permissionMode !== 'inherit'
263
284
  ? agentDef.permissionMode
264
285
  : 'inherit'
265
- subPermission = this.permission.createSubAgentPermission(agentPermMode)
286
+ // `source` decides whether the cap applies: a repository-supplied definition may
287
+ // narrow the parent's gate but not widen it. See `resolveAgentMode`.
288
+ subPermission = this.permission.createSubAgentPermission(agentPermMode, agentDef?.source)
266
289
  }
267
290
 
268
291
  // Absence is not a licence to run everything. With no permission system handed in,
@@ -271,6 +294,9 @@ export class SubAgent {
271
294
  // what the CLI itself runs under, so this is the same policy, not a stricter one.
272
295
  const gate = subPermission ?? new PermissionSystem('default')
273
296
 
297
+ // The cap is never silent: say which agent asked for what and what it got instead.
298
+ reportAgentCapWarnings(gate, agentDef?.name)
299
+
274
300
  // Resolve execution directory: worktree isolation or process cwd
275
301
  const execCwd = options.worktreePath || process.cwd()
276
302
 
@@ -80,13 +80,28 @@ export function recordLoopTurn(sessionId: string, summary: string, delta: number
80
80
  }
81
81
  }
82
82
 
83
+ /**
84
+ * The row written when an iteration produced **no visible text**.
85
+ *
86
+ * The summary is the assistant's visible output (`app.tsx` passes
87
+ * `assistantContent`, which only accumulates `type === 'text'` chunks), so a
88
+ * turn that emitted only tool calls — or only thinking, which `formatThinking`
89
+ * hides by default — arrives here as an empty string. Written as `#N: ` that
90
+ * row is indistinguishable from "we recorded nothing at all", which is exactly
91
+ * what `/loop status` must not conflate. So it is spelled out.
92
+ */
93
+ export const NO_VISIBLE_OUTPUT = '(no visible output — tool calls or thinking only)'
94
+
83
95
  /** Log an iteration in the autonomous loop journal. */
84
96
  export function logAutoloopIteration(sessionId: string, summary: string): void {
85
97
  const journal = readAutoloopJournal(sessionId)
86
98
  if (!journal) return
87
99
  journal.iterations++
88
100
  journal.lastIteration = new Date().toISOString()
89
- journal.logs.push(`[${journal.lastIteration}] #${journal.iterations}: ${summary.slice(0, 200)}`)
101
+ const text = summary.trim()
102
+ journal.logs.push(
103
+ `[${journal.lastIteration}] #${journal.iterations}: ${text ? text.slice(0, 200) : NO_VISIBLE_OUTPUT}`,
104
+ )
90
105
  // Keep last 50 log entries
91
106
  if (journal.logs.length > 50) journal.logs = journal.logs.slice(-50)
92
107
  atomicWriteFileSync(journalPath(sessionId), JSON.stringify(journal, null, 2), { mode: 0o644 })
@@ -34,6 +34,30 @@ interface Checkpoint {
34
34
  label: string
35
35
  }
36
36
 
37
+ /**
38
+ * 一次 `compact()` 的调度表 —— 「压完再判一次,仍超预算就再压、且压得更狠」。
39
+ *
40
+ * 存在的理由:**触发尺与削减尺不是同一把**。`needsCompaction()` 按 token 判,而一趟压缩
41
+ * 只按条数削,于是**一条超大消息(大文本 / 图片 / 长工具结果)可以同时穿过两把尺** ——
42
+ * 判着要压,压完却仍超预算,此后每一轮都带着超长请求打上游,直到用户手动 `/compact`
43
+ * 或上游报错。只压一趟且从不复查,就是那个缺口。
44
+ *
45
+ * - 第一趟 `{keep: 20, minLength: 30}` 与历史行为**逐字等价**(`minLength` 就是原来那条
46
+ * `messages.length <= 30` 的 no-op)。
47
+ * - 第二趟的闸取 `keep` 本身而不是 `keep + 10`:第一趟之后只剩 20 条(截断回落)或 21 条
48
+ * (有 summarizer 时多一条摘要),沿用 `keep + 10 = 20` 会让截断那条路命中 `20 <= 20`
49
+ * 而**永不跑第二趟**,整个改动自我抵消。此时唯一要问的是「还有没有可丢的」。
50
+ * - 表是常量、无 `while` ⇒ 有界,不可能死循环。
51
+ *
52
+ * `recountMessageTokens()` 随每趟一起跑(见 `compactOnce`)—— 它是第二趟那道「仍超预算吗」
53
+ * 的**闸所读的那个数**。放在循环外只算一次,闸读到的就是压缩前的旧值,永远为真 ⇒
54
+ * 第二趟变成无条件跑,「复查」就名存实亡。
55
+ */
56
+ const COMPACTION_PASSES: ReadonlyArray<{ keep: number; minLength: number }> = [
57
+ { keep: 20, minLength: 30 },
58
+ { keep: 10, minLength: 10 },
59
+ ]
60
+
37
61
  export class ContextManager {
38
62
  private messages: Message[] = []
39
63
  private systemPrompt = ''
@@ -296,11 +320,25 @@ export class ContextManager {
296
320
  async compact(heading: string): Promise<{ before: number; after: number }> {
297
321
  const beforeTokens = this.getEstimatedTokens()
298
322
 
299
- if (this.messages.length <= 30) {
300
- return { before: beforeTokens, after: beforeTokens }
323
+ for (let i = 0; i < COMPACTION_PASSES.length; i++) {
324
+ const pass = COMPACTION_PASSES[i]!
325
+ // 第一趟无条件跑(手动 `/compact` 即使未超预算也必须动);之后**只**在复查
326
+ // 仍超预算时继续 —— 这一句就是「压完再判一次」。
327
+ if (i > 0 && !this.needsCompaction()) break
328
+ if (this.messages.length <= pass.minLength) continue
329
+ await this.compactOnce(heading, pass.keep)
301
330
  }
302
331
 
303
- const keep = 20
332
+ return { before: beforeTokens, after: this.getEstimatedTokens() }
333
+ }
334
+
335
+ /**
336
+ * 压缩一趟:把消息削到最近 `keep` 条。
337
+ *
338
+ * body(除 `keep` 外)逐行取自旧 `compact()`,两种分支原样保留:LLM 摘要(失败回落截断)
339
+ * 与纯截断。`recountMessageTokens()` 留在**这里**而不是调用方 —— 下一趟的闸要读它。
340
+ */
341
+ private async compactOnce(heading: string, keep: number): Promise<void> {
304
342
  const toDrop = this.messages.slice(0, -keep)
305
343
 
306
344
  if (this.summarizer && toDrop.length >= 4) {
@@ -340,8 +378,6 @@ export class ContextManager {
340
378
 
341
379
  // Re-estimate the message half (the prompt half is derived on read).
342
380
  this.recountMessageTokens()
343
-
344
- return { before: beforeTokens, after: this.getEstimatedTokens() }
345
381
  }
346
382
 
347
383
  /**
@@ -115,7 +115,27 @@ export function buildLessonContent(
115
115
  }
116
116
 
117
117
  /**
118
- * 教训精华(标题 + 建议 + 严重度),用于运行时召回注入系统提示。
118
+ * 档位的**来历** —— 这一格回答的是「谁定的档」,不是「档是什么」。
119
+ *
120
+ * - `declared` —— 文件里逐字写了 `- 严重度: critical` 或 `- 严重度: warning`。
121
+ * - `defaulted` —— 没有那一行,或写了但取值在闭集之外(如 `info`、笔误)⇒
122
+ * {@link normalizeLessonSeverity} fail-open 落 `critical`,于是这条进了常驻档。
123
+ *
124
+ * 为什么非记不可:`severity` 是**归一化之后**的读数,而归一化是 fail-open 的 ⇒
125
+ * 「有人判定它该每次请求都在场」与「压根没人写过档位」在 `severity` 上**同形**。
126
+ * 常驻档的成本是人付的、能动手的也只有人(改文件那一行),看不出这条是被判过的
127
+ * 还是漏写的,就无从复核 —— 这正是本仓库记过的「无声消失与从没写过同形」。
128
+ *
129
+ * 不改任何**判定**行为:`severity` 照旧 fail-open 落 `critical`,常驻/择点/预算一概不看
130
+ * 这一格。它只把不可见的默认**变成可复核的清单**(见 {@link buildResidentLessonReport})。
131
+ *
132
+ * 一条不变量:`severity === 'warning'` ⇒ `severitySource === 'declared'`。
133
+ * 因为归一化只有**逐字** `warning` 才落 `warning`,其余一切落 `critical`。
134
+ */
135
+ export type LessonSeveritySource = 'declared' | 'defaulted'
136
+
137
+ /**
138
+ * 教训精华(标题 + 建议 + 严重度 + 档位来历),用于运行时召回注入系统提示。
119
139
  *
120
140
  * 严重度决定**注入位置**,不只是标签:`critical` 常驻每一次请求,
121
141
  * `warning` 移出常驻块、按需召回(见 {@link isAlwaysOnLesson}),且常驻档整体受
@@ -127,6 +147,12 @@ export interface CrsiLessonSummary {
127
147
  title: string
128
148
  suggestion: string
129
149
  severity: LessonSeverity
150
+ /**
151
+ * 必填而非可选 —— 同 `buildLessonContent` 的 `severity`:可选的话,下一个构造点忘了给
152
+ * 就等于「来历是默认落的」,而那个默认值恰好**说反了**(它说的是「有人判过」)。
153
+ * 忘了要给不出来的东西,必须是编译错误。
154
+ */
155
+ severitySource: LessonSeveritySource
130
156
  }
131
157
 
132
158
  /**
@@ -153,25 +179,50 @@ export function normalizeLessonSeverity(raw: string | undefined): LessonSeverity
153
179
  }
154
180
 
155
181
  /**
156
- * 从 crsi-lessons.md 提取每条教训的「精华」(标题 + 建议 + 严重度),跳过证据段落。
157
- * 这是「只写不读」缺口 → 「写后召回」的读取侧。
182
+ * 闭集成员的**运行时**面 —— `LessonSeverity` 是类型,运行时只存在这一份字面量。
183
+ *
184
+ * 定义在**一处**:{@link isDeclaredLessonSeverity} 读它,而它与
185
+ * {@link normalizeLessonSeverity} 必须对**同一个**闭集说话(一个问「折叠前在不在集里」、
186
+ * 一个做折叠)。两处各写一份字面量的话,哪天闭集加一档,会出现「归一是对的、来历却说
187
+ * 它不在闭集」这种自相矛盾的读数 —— 且没有任何东西会报。
188
+ */
189
+ const LESSON_SEVERITY_SET: ReadonlySet<string> = new Set(['critical', 'warning'])
190
+
191
+ /**
192
+ * 那一行是否**逐字**落在闭集内(= 档位有人判过)。缺席、空串与闭集外取值一律 false。
193
+ *
194
+ * 参数类型与 {@link normalizeLessonSeverity} 刻意**同形**(`string | undefined`):
195
+ * 两者是同一个原始捕获的一对读者(一个折叠、一个问来历),签名不一致的话,调用点迟早
196
+ * 会把某个缺席的捕获只喂给其中一个。
197
+ */
198
+ function isDeclaredLessonSeverity(raw: string | undefined): boolean {
199
+ return typeof raw === 'string' && LESSON_SEVERITY_SET.has(raw)
200
+ }
201
+
202
+ /**
203
+ * 从 crsi-lessons.md 提取每条教训的「精华」(标题 + 建议 + 严重度 + 档位来历),
204
+ * 跳过证据段落。这是「只写不读」缺口 → 「写后召回」的读取侧。
158
205
  *
159
206
  * 按 `##` 块累积、块边界 flush —— 因为 `- 严重度:` 行写在 `- 建议:` **之后**,
160
207
  * 「见到建议即 push」的写法读不到它。块级累积对行序不敏感。
161
208
  *
162
- * 缺 `严重度` 时的落档见 {@link DEFAULT_LESSON_SEVERITY}。
209
+ * 缺 `严重度` 时的落档见 {@link DEFAULT_LESSON_SEVERITY};**它是怎么落的**记在
210
+ * `severitySource` 里(见 {@link LessonSeveritySource})—— 归一化把「有人判过」与
211
+ * 「没人写过」折叠成了同一个 `critical`,本读取侧把这两者**重新分开**。
163
212
  */
164
213
  export function extractCrsiLessonSummaries(content: string): CrsiLessonSummary[] {
165
214
  const out: CrsiLessonSummary[] = []
166
215
  let title = ''
167
216
  let suggestion = ''
168
217
  let severity = DEFAULT_LESSON_SEVERITY
218
+ let severitySource: LessonSeveritySource = 'defaulted'
169
219
 
170
220
  const flush = () => {
171
- if (title && suggestion) out.push({ title, suggestion, severity })
221
+ if (title && suggestion) out.push({ title, suggestion, severity, severitySource })
172
222
  title = ''
173
223
  suggestion = ''
174
224
  severity = DEFAULT_LESSON_SEVERITY
225
+ severitySource = 'defaulted'
175
226
  }
176
227
 
177
228
  for (const line of content.split('\n')) {
@@ -191,6 +242,8 @@ export function extractCrsiLessonSummaries(content: string): CrsiLessonSummary[]
191
242
  // 闭集外的取值一律落常驻档 —— 未知严重度不倒向「按需」。规则在 normalizeLessonSeverity
192
243
  // 一处;写入者同读它(正则已吃掉两侧空白,故传进去的是已经 trim 过的捕获)。
193
244
  severity = normalizeLessonSeverity(v[1])
245
+ // 来历与档位**同一处**算出:分开写迟早出现「档是折叠后的、来历说的还是原文」的错配。
246
+ severitySource = isDeclaredLessonSeverity(v[1]) ? 'declared' : 'defaulted'
194
247
  }
195
248
  }
196
249
  flush()
@@ -346,6 +399,27 @@ export function buildCrsiLessonsPointer(
346
399
  return lines.join('\n')
347
400
  }
348
401
 
402
+ /**
403
+ * 事件型召回扳机的正文,由 {@link selectResidentLessons} 的结果渲染。无可召回时返回空串。
404
+ *
405
+ * 与 {@link buildCrsiLessonsPointer} **共用同一个判据**(`demoted.length === 0`):
406
+ * 没有指针就没有扳机。指针说的是「东西在那儿」,扳机说的是「现在是看它的时机」——
407
+ * 后者只能挂在**事件**上(工具刚失败),挂在系统提示里就是在复述指针本身。
408
+ *
409
+ * 措辞是**非指令式**的:不点名、不排序、不读、不摘要任何一条教训,也不替代理决定
410
+ * 读不读。代理可以完全忽略它,代价只是这一条上下文。
411
+ */
412
+ export function buildLessonRevisitNudge(
413
+ selection: ResidentLessonSelection,
414
+ lessonsPath: string,
415
+ ): string {
416
+ if (selection.demoted.length === 0) return ''
417
+ return (
418
+ `[可回顾] 上一步工具调用失败。若有教训覆盖同一情形,可自行决定是否读 ${lessonsPath}` +
419
+ `(含标题/建议/证据);不作要求,也可以完全忽略。`
420
+ )
421
+ }
422
+
349
423
  /**
350
424
  * 常驻档名册 —— `selectResidentLessons` 的**第三个读者**,也是**唯一给人看的**那一个。
351
425
  *
@@ -359,6 +433,12 @@ export function buildCrsiLessonsPointer(
359
433
  * 报告不可能与真正注入的那一份漂移。逐条成本按**渲染后的文本量**算,且报出可验算的
360
434
  * 加法(表头 + 逐条 + 分隔 == 合计)—— 否则「逐条和 ≠ 合计」会被当成 bug 查一遍。
361
435
  *
436
+ * 另报**档位来历**({@link LessonSeveritySource}):成本答「这档涨得值不值」,来历答
437
+ * 「这一格是谁定的」。两个读者的输出都不需要它(模型不问档位怎么来的),只有人有这个
438
+ * 问题 —— 而「没人复核谁把一条教训标成 critical」正是因此才存在:归一化 fail-open,
439
+ * 「有人判过」与「没人写过」在 `severity` 上同形,名册里读到的就是一个普通的 critical。
440
+ * 故这里把两者分开列、逐条点名 —— 只报数不点名,读者仍要自己去文件里比对。
441
+ *
362
442
  * 只读:**不加写路径**。人的杠杆是改文件那一行;写入侧是生产者与 `/crsi propose`。
363
443
  */
364
444
  export function buildResidentLessonReport(
@@ -394,9 +474,24 @@ export function buildResidentLessonReport(
394
474
  )
395
475
 
396
476
  if (resident.length > 0) {
477
+ // 档位**来历**与成本分开报:成本答「这档涨得值不值」,来历答「这一格是谁定的」。
478
+ // 两者都要人动手才能改,但改动完全不同(前者缩短、后者补/改 `- 严重度:` 那一行)。
479
+ const defaulted = resident.filter((s) => s.severitySource === 'defaulted')
480
+ // 两个分支**同一个形状**(`**默认落档 N** 条`):形状随取值变的话,读者与判据都得先
481
+ // 分辨自己看到的是哪一支 —— 而「0 条」与「这一支没打印」本来就会长得一样。
482
+ lines.push(
483
+ `档位来历:显式判定 **${resident.length - defaulted.length}** 条 · ` +
484
+ `**默认落档 ${defaulted.length}** 条` +
485
+ (defaulted.length > 0
486
+ ? ' —— 文件里没写 `- 严重度:`、或写了闭集外的取值,fail-open 落 critical ⇒ ' +
487
+ '**没有任何人判定过**它们该常驻'
488
+ : ''),
489
+ )
490
+
397
491
  lines.push('', '### 逐条成本(渲染后字符)', '')
398
492
  for (let i = 0; i < resident.length; i++) {
399
- lines.push(`- ${num(itemChars[i]!)} 字符 — ${resident[i]!.title}`)
493
+ const mark = resident[i]!.severitySource === 'defaulted' ? '(档位默认落档)' : ''
494
+ lines.push(`- ${num(itemChars[i]!)} 字符 — ${resident[i]!.title}${mark}`)
400
495
  }
401
496
  // 加法自证:表头是每条共担的,逐条和必然大于合计 —— 与其让人去猜差额,
402
497
  // 不如把算式写出来,且当场验算(`block` 走的是真渲染器,不是我在这里的手算)。
@@ -1015,6 +1110,12 @@ export function removeLessonSections(content: string, headers: string[]): string
1015
1110
  * 3. **不停在「缺省 critical」** —— 那个缺省是给**人类新写**的条目兜底的;合并是**降维**,
1016
1111
  * 没有依据说产物比两个源更紧急。实测(真模块):两条 warning 合并曾升进常驻档,
1017
1112
  * 常驻 6 条 2,155 字符 → 7 条 2,198,而这一切发生在**没有人决定过**的情况下。
1113
+ *
1114
+ * **已知边界(如实写,不假装覆盖)**:来历**不跨代传递**。产物由 `buildLessonContent`
1115
+ * 逐字写 `- 严重度: <merged>`,于是它读回来的来历恒为 `declared` —— 哪怕两个源都是
1116
+ * 默认落档。也就是说 crossover 会把「没人判过」**洗成**「有人判过」,名册看不出来。
1117
+ * 修它要把来历写进文件(新字段),是改教训文件的格式,不在本格口径内 —— 故此处的
1118
+ * 判据只对**人写进去的**条目成立。见 {@link LessonSeveritySource}。
1018
1119
  */
1019
1120
  export function deriveMergedSeverity(a: LessonSeverity, b: LessonSeverity): LessonSeverity {
1020
1121
  return a === 'critical' || b === 'critical' ? 'critical' : 'warning'
@@ -23,6 +23,7 @@ import type { AgentViewManager } from '../agent-view/agent-view-manager'
23
23
  import type { Skills } from '../skills/seam'
24
24
  import { getBackgroundAgentRegistry } from '../agent/background-registry'
25
25
  import { RulesLoader } from './rules-loader'
26
+ import type { InstructionsLoader } from './instructions'
26
27
  import { ExperienceRuleEngine } from './rule-engine.js'
27
28
  import { PatternAnalyzer } from '../agent/pattern-analyzer.js'
28
29
  import { EffectivenessTracker } from '../agent/effectiveness-tracker.js'
@@ -359,8 +360,14 @@ export class QueryEngine {
359
360
 
360
361
  /** Rules loader for path-scoped rules injection. */
361
362
  private rulesLoader?: RulesLoader
363
+ /** Instruction loader — the source of the CRSI lessons *recall nudge* (see injectLessonNudge). */
364
+ private instructionsLoader?: InstructionsLoader
362
365
  /** Files touched in the current turn (for rules matching). */
363
366
  private touchedFiles: Set<string> = new Set()
367
+ /** A tool call failed since the last nudge check. */
368
+ private pendingToolFailure = false
369
+ /** The recall nudge is offered at most once per engine (session). */
370
+ private lessonNudgeOffered = false
364
371
  private usageTracker = new UsageTracker()
365
372
  /** Inference hook (DLP) configuration. */
366
373
  private inferenceHookConfig?: InferenceHookConfig
@@ -373,6 +380,17 @@ export class QueryEngine {
373
380
  this.rulesLoader.load()
374
381
  }
375
382
 
383
+ /**
384
+ * Register the instruction loader — the recall nudge's text source.
385
+ *
386
+ * daemon 侧有意不接:daemon **从不设置系统提示**(`setSystemPrompt` 在 `daemon/`
387
+ * 下零调用点),因此那条路径上既没有常驻块、也没有指针 —— 接上去只会让扳机指向
388
+ * 一个该会话从未被告知过的文件。见守卫的 `daemon:setInstructions` 豁免条目。
389
+ */
390
+ setInstructions(loader: InstructionsLoader): void {
391
+ this.instructionsLoader = loader
392
+ }
393
+
376
394
  /** Register inference hook (DLP) configuration. */
377
395
  setInferenceHookConfig(config: InferenceHookConfig): void {
378
396
  this.inferenceHookConfig = config
@@ -406,6 +424,31 @@ export class QueryEngine {
406
424
  this.touchedFiles.clear()
407
425
  }
408
426
 
427
+ /**
428
+ * Offer the CRSI lessons **recall nudge** after a failed tool call.
429
+ *
430
+ * 为什么落点是「工具失败」而不是更早设想的会话开始/压缩后:那两处指针都是**刚生成的**
431
+ * (`/resume` 会重跑 `setSystemPrompt()`),在那里再说一遍「你可以去读教训」只是在复述
432
+ * 指针本身,却要每次会话都付。工具失败是唯一一个「系统提示没说过、且与当前事件绑定」
433
+ * 的时机 —— 这次失败可能有一条教训正好覆盖它。
434
+ *
435
+ * 与 {@link injectRules} 同形(含**同一个调用时机约束**):必须在本轮 tool_result 都
436
+ * 追加完**之后**才注入。`injectContext` 推的是一条 user 消息,插进 assistant 的
437
+ * `tool_use` 与配对的 user `tool_result` 之间会把消息配对打断。
438
+ *
439
+ * 每会话最多一次:失败循环里同一条命令重试十次就是十次注入。代价是首个失败若不具
440
+ * 代表性,这次机会就用掉了 —— 可接受,因为指针常驻、代理随时仍可去读。
441
+ */
442
+ private injectLessonNudge(): void {
443
+ if (!this.pendingToolFailure) return
444
+ this.pendingToolFailure = false
445
+ if (this.lessonNudgeOffered) return
446
+ const nudge = this.instructionsLoader?.crsiLessonNudgeText() ?? ''
447
+ if (!nudge) return
448
+ this.lessonNudgeOffered = true
449
+ this.context.injectContext('crsi-revisit', nudge)
450
+ }
451
+
409
452
  /**
410
453
  * Drain pending background task notifications.
411
454
  * Call this after tool execution to surface completed/failed background agent results.
@@ -721,6 +764,9 @@ export class QueryEngine {
721
764
  for (const toolUse of toolUses) {
722
765
  const toolStart = Date.now()
723
766
  const result = await this.executeTool(toolUse.name, toolUse.input, signal)
767
+ // 判据取 `result.success`,不取「有没有抛」:失败返回有八种形状(未知工具、
768
+ // 权限拒绝、cwd 已删…),全都在这里汇成同一个 `success: false`。
769
+ if (!result.success) this.pendingToolFailure = true
724
770
  yield {
725
771
  type: 'tool_result',
726
772
  tool_use_id: toolUse.id,
@@ -797,6 +843,9 @@ export class QueryEngine {
797
843
  // Inject path-scoped rules for touched files
798
844
  this.injectRules()
799
845
 
846
+ // Offer the CRSI recall nudge if this round had a failed tool call.
847
+ this.injectLessonNudge()
848
+
800
849
  // Drain task notifications after tool execution
801
850
  for (const chunk of this.drainTaskNotifications()) {
802
851
  yield chunk
@@ -1062,6 +1111,7 @@ export class QueryEngine {
1062
1111
  // Execute tools and feed results back to the model for the next turn
1063
1112
  for (const toolUse of toolUses) {
1064
1113
  const result = await this.executeTool(toolUse.name, toolUse.input, signal)
1114
+ if (!result.success) this.pendingToolFailure = true
1065
1115
  lastActivity = Date.now()
1066
1116
  yield {
1067
1117
  type: 'tool_result',
@@ -1084,6 +1134,10 @@ export class QueryEngine {
1084
1134
  // Path-scoped rules for files touched in this round: process() injects for
1085
1135
  // the first tool round only, so the multi-turn rounds need their own call.
1086
1136
  this.injectRules()
1137
+
1138
+ // Same reason the rules injection is repeated here: the nudge must land after
1139
+ // this round's tool results, and this loop owns those rounds.
1140
+ this.injectLessonNudge()
1087
1141
  }
1088
1142
  // Max turns reached — safety limit, stop gracefully
1089
1143
  }
@@ -1142,9 +1196,37 @@ export class QueryEngine {
1142
1196
  error: preResult.reason || t('errors.tool_blocked', { name }),
1143
1197
  }
1144
1198
  }
1199
+
1200
+ // `permissionDecision` narrows only — never widens. `ask` stops the call here
1201
+ // (this CLI has no interactive approval prompt; `ask` is a hard refusal, the
1202
+ // same as the `default` mode's ask path). `allow` is deliberately **not**
1203
+ // honoured: a hook can come from the repository's own settings, so letting it
1204
+ // auto-approve is the same defect as a project-supplied agent definition that
1205
+ // grants itself `bypassPermissions` — the criterion is the *direction*, not the
1206
+ // key name. `defer` (and an absent decision) means "no override", which is
1207
+ // exactly what happens when we do nothing.
1208
+ if (preResult.permissionDecision === 'ask' || preResult.permissionDecision === 'deny') {
1209
+ return {
1210
+ success: false,
1211
+ content: '',
1212
+ error: preResult.reason || t('errors.tool_hook_ask', { name }),
1213
+ }
1214
+ }
1215
+
1145
1216
  if (preResult.modifiedInput) {
1146
1217
  effectiveParams = { ...params, ...preResult.modifiedInput }
1147
1218
  }
1219
+
1220
+ // A hook's `additionalContext` is how every non-blocking hook speaks — the
1221
+ // exit-1 stderr, a spawn failure, an unreachable `mcp_tool` server (see
1222
+ // `core/hooks-executor.ts`). This path used to read only `allowed` /
1223
+ // `modifiedInput`, so all of it was produced and then dropped. `hookWarnings`
1224
+ // is the channel that already reaches the model: it is prepended to the tool
1225
+ // result below. A non-`[rule:…]` line is ignored by the effectiveness tracker
1226
+ // further down, so pushing prose here is safe.
1227
+ if (preResult.additionalContext) {
1228
+ hookWarnings.push(preResult.additionalContext)
1229
+ }
1148
1230
  }
1149
1231
 
1150
1232
  // CRSI RuleEngine intercept — gated by crsi.preToolHook feature flag
@@ -1155,7 +1237,11 @@ export class QueryEngine {
1155
1237
  effectiveParams = ruleResult.modified
1156
1238
  }
1157
1239
  if (ruleResult.warnings.length > 0) {
1158
- hookWarnings = ruleResult.warnings
1240
+ // Append, do not replace: this array may already hold a PreToolUse hook's
1241
+ // `additionalContext`. Every other writer below uses the spread form for the
1242
+ // same reason — assignment here would silently drop whichever was written
1243
+ // first ("two writers, one list").
1244
+ hookWarnings = [...hookWarnings, ...ruleResult.warnings]
1159
1245
  }
1160
1246
  }
1161
1247
 
@@ -1424,9 +1510,12 @@ export class QueryEngine {
1424
1510
  * Stream a chat response with graceful provider fallback (v2.1.229 alignment).
1425
1511
  *
1426
1512
  * On a connection/availability failure from the active provider (thrown
1427
- * network error or an error chunk), switches to the configured default
1428
- * provider and retries once, yielding a `warning` chunk so the UI can tell
1429
- * the user the provider degraded. Abort errors propagate untouched.
1513
+ * network error or an error chunk), retries that same provider once, then
1514
+ * switches to the configured default provider and retries again, yielding a
1515
+ * `warning` chunk at each step so the UI can tell the user what happened.
1516
+ * When there is no fallback left, the error names the unavailable model and
1517
+ * the next step instead of re-emitting the raw upstream message.
1518
+ * Abort errors propagate untouched.
1430
1519
  */
1431
1520
  private async *chatWithFallback(
1432
1521
  messages: import('../shared/types').Message[],
@@ -1435,30 +1524,49 @@ export class QueryEngine {
1435
1524
  signal?: AbortSignal,
1436
1525
  ): AsyncGenerator<StreamChunk> {
1437
1526
  const activeId = this.registry.getActive().config.id
1527
+ const activeModel = this.registry.getActiveModel()
1438
1528
  const defaultId = this.registry.getDefaultProviderId()
1439
1529
 
1440
- // ── Attempt 1: active provider ──
1530
+ // ── Attempt 1 (+ one same-provider retry): active provider ──
1531
+ //
1532
+ // A failed turn is retried once on the *same* provider before the cross-provider
1533
+ // fallback is considered: overloaded and transient errors are commonly answered
1534
+ // by resending, whereas switching providers is the more expensive move — it flips
1535
+ // the registry's active provider and, with it, the model the user chose. A
1536
+ // foreign `Llm` seam owns the whole chat flow, so it is not retried here, for the
1537
+ // same reason the fallback below is skipped for it.
1538
+ //
1539
+ // Chunks already yielded cannot be taken back, so a retry re-streams that turn.
1540
+ // This is not a new property: the cross-provider fallback below already starts a
1541
+ // fresh attempt after a failed one.
1542
+ const ownsFlow = !(this.llm && this.llm !== this.registry)
1441
1543
  let failure: string | null = null
1442
- try {
1443
- for await (const chunk of this.llmChat({
1444
- model: this.registry.getActiveModel(),
1445
- messages,
1446
- systemPrompt,
1447
- tools: toolDefs,
1448
- signal,
1449
- effort: this.effort,
1450
- })) {
1451
- if (chunk.type === 'error') {
1452
- failure = chunk.error ?? 'Unknown error'
1453
- break
1544
+ for (let attempt = 0; ; attempt++) {
1545
+ failure = null
1546
+ try {
1547
+ for await (const chunk of this.llmChat({
1548
+ model: activeModel,
1549
+ messages,
1550
+ systemPrompt,
1551
+ tools: toolDefs,
1552
+ signal,
1553
+ effort: this.effort,
1554
+ })) {
1555
+ if (chunk.type === 'error') {
1556
+ failure = chunk.error ?? 'Unknown error'
1557
+ break
1558
+ }
1559
+ yield chunk
1454
1560
  }
1455
- yield chunk
1561
+ if (failure === null) return
1562
+ } catch (err) {
1563
+ if (isAbortError(err)) throw err
1564
+ failure = String(err)
1456
1565
  }
1457
- if (failure === null) return
1458
- } catch (err) {
1459
- if (isAbortError(err)) throw err
1460
- failure = String(err)
1566
+ if (!ownsFlow || attempt >= 1) break
1567
+ yield { type: 'warning', content: `${activeId} failed (${failure}) — retrying once` }
1461
1568
  }
1569
+ const detail = failure ?? 'Unknown error'
1462
1570
 
1463
1571
  // ── Fallback: configured default provider, once ──
1464
1572
  // 若注入了**异己**的 Llm 缝,缝拥有整个 chat 流程——不回退(避免切 registry 状态 + 二次调用)。
@@ -1466,18 +1574,18 @@ export class QueryEngine {
1466
1574
  // `mountLlm(vajraContext, registry)` → `setLlm`),按「非空即缝」判定会让本分支
1467
1575
  // 在生产恒不可达,而测试里构造引擎时不注入缝 ⇒ 套件全绿也发现不了。
1468
1576
  if (this.llm && this.llm !== this.registry) {
1469
- yield { type: 'error', error: failure }
1577
+ yield { type: 'error', error: detail }
1470
1578
  return
1471
1579
  }
1472
1580
  if (!defaultId || defaultId === activeId || !this.registry.get(defaultId)) {
1473
- yield { type: 'error', error: failure }
1581
+ yield { type: 'error', error: this.modelUnavailableNotice(activeId, activeModel, detail) }
1474
1582
  return
1475
1583
  }
1476
1584
  const fallbackModel = this.registry
1477
1585
  .get(defaultId)!
1478
1586
  .config.models.find((m) => m.status === 'active')?.id
1479
1587
  if (!fallbackModel) {
1480
- yield { type: 'error', error: failure }
1588
+ yield { type: 'error', error: this.modelUnavailableNotice(activeId, activeModel, detail) }
1481
1589
  return
1482
1590
  }
1483
1591
 
@@ -1504,6 +1612,16 @@ export class QueryEngine {
1504
1612
  }
1505
1613
  }
1506
1614
 
1615
+ /**
1616
+ * 「模型不可用、且已无可回退的默认模型」时的说明。
1617
+ *
1618
+ * 裸的 `failure` 读起来像模型答错了,而实际上**这一轮请求根本没发出去**:把
1619
+ * 这一层说破,并给出下一步(换模型 / 查密钥与网络),比把上游错误原样抛出来有用。
1620
+ */
1621
+ private modelUnavailableNotice(providerId: string, model: string, detail: string): string {
1622
+ return t('errors.model_unavailable', { model, provider: providerId, error: detail })
1623
+ }
1624
+
1507
1625
  getTools(): Map<string, ToolDefinition> {
1508
1626
  return this.tools
1509
1627
  }
@@ -9,6 +9,7 @@ import {
9
9
  extractCrsiLessonSummaries,
10
10
  buildCrsiLessonsBlock,
11
11
  buildCrsiLessonsPointer,
12
+ buildLessonRevisitNudge,
12
13
  selectResidentLessons,
13
14
  type CrsiLessonSummary,
14
15
  } from './crsi-producer'
@@ -400,11 +401,12 @@ say so explicitly instead of claiming it exists.`)
400
401
  Before answering ANY question about this codebase — whether a file,
401
402
  function, feature, or capability exists, how it works, or whether
402
403
  something is missing — you MUST first read the actual code with the
403
- Read, Grep, Glob, or graft tools. Do not infer or assert from memory,
404
- naming conventions, or static tool lists. If you have not read the code,
405
- say so and read it first, rather than answering hastily and retracting
406
- afterwards. This applies to every code question, not only research or
407
- borrow-analysis tasks.`)
404
+ Read, Grep, or Glob tools. When the repository is graft-indexed you also
405
+ have graft — a CLI you run through Bash, not one of your own tools. Do
406
+ not infer or assert from memory, naming conventions, or static tool
407
+ lists. If you have not read the code, say so and read it first, rather
408
+ than answering hastily and retracting afterwards. This applies to every
409
+ code question, not only research or borrow-analysis tasks.`)
408
410
 
409
411
  // CRSI code-review 合并门 — 合并 PR 前必须先 review,勿靠「碰巧触发」
410
412
  parts.push(`## Code-Review Merge Gate
@@ -481,6 +483,23 @@ Never omit it or present the work as purely human-authored.`)
481
483
  .join('\n\n')
482
484
  }
483
485
 
486
+ /**
487
+ * 事件型召回扳机 —— {@link crsiLessonsText} 的姊妹件,走**同一个择点**、同一份
488
+ * `lessonsPath`,因此不可能与系统提示里那条指针漂移(一处说「有 33 条未常驻」、
489
+ * 另一处说「没有」是最坏的形状:两声哨,读者不知道信哪个)。
490
+ *
491
+ * 与 `crsiLessonsText` 的分工:那份进**系统提示**,一次生成、随每次请求发出;
492
+ * 这份在**工具失败**那一刻注入,只在事件上说话。没有未常驻教训时返回空串 ——
493
+ * 与指针同一条件,故不会出现「扳机响了但没有指针」。
494
+ */
495
+ crsiLessonNudgeText(): string {
496
+ if (!this.lessonsPath) return ''
497
+ return buildLessonRevisitNudge(
498
+ selectResidentLessons(this.crsiLessonSummaries),
499
+ this.lessonsPath,
500
+ )
501
+ }
502
+
484
503
  /**
485
504
  * Loader-shaped alias of {@link buildPermissionBlock}(模块级那个才是实现)。
486
505
  * 保留它是因为**已有**的调用点都握着一个装载器:`index.tsx` 的接线行与
@@ -9,6 +9,7 @@ import {
9
9
  } from 'node:fs'
10
10
  import { join, extname, basename } from 'node:path'
11
11
  import { atomicWriteFileSync } from '../../shared/atomic-write'
12
+ import { neutralizeInjectedMarkup } from '../../shared/sanitize.ts'
12
13
  import { similarities, findNearDuplicates } from './tfidf'
13
14
 
14
15
  export interface MemoryMetadata {
@@ -368,7 +369,14 @@ export class MemoryManager {
368
369
 
369
370
  let tokenBudget = 50 // opening tags
370
371
  for (const entry of relevant) {
371
- const line = `- ${entry.name}: ${entry.content.slice(0, 200)}`
372
+ // Both halves are file contents, written by earlier sessions — worth
373
+ // neutralizing before they land inside the `<system-reminder>` wrapper below.
374
+ // Neutralize *before* the 200-char slice, so a tag straddling the boundary is
375
+ // removed whole instead of being truncated into an unterminated `<…` that the
376
+ // wrapper's own `>` could then complete.
377
+ const name = neutralizeInjectedMarkup(entry.name)
378
+ const content = neutralizeInjectedMarkup(entry.content).slice(0, 200)
379
+ const line = `- ${name}: ${content}`
372
380
  const lineTokens = Math.ceil(line.length / 4)
373
381
  if (tokenBudget + lineTokens > effectiveMaxTokens) break
374
382
  lines.push(line)
@@ -310,6 +310,34 @@ export function clampMode(
310
310
  return allowed[0] ?? 'default'
311
311
  }
312
312
 
313
+ /**
314
+ * 「`desired` **确定**不比 `ceiling` 宽」—— 仓库带来的 agent 定义能过的那道门。
315
+ *
316
+ * **刻意不用 `PERMISSION_MODE_HIERARCHY.indexOf` 判宽窄。** 层级表自己(本文件顶部)写明:
317
+ * 那几档**在现实中不是全序**,数组只承载「能测出来的那几条关系」—— `acceptEdits` 与
318
+ * `default` **不可比**(前者自动批 Write/Edit,后者自动批 git/task/web-fetch 这类
319
+ * `'self'` 工具),`auto` 的静态基线什么都不批、只因运行期分类器可能放行更多才被摆到
320
+ * `acceptEdits` 之上。拿下标当安全顶会**两个方向都错**:
321
+ *
322
+ * - **漏判**(危险的那一侧):父 `acceptEdits` + 项目级声明 `default`(下标 1 < 2 ⇒ 放过),
323
+ * 或父 `auto`(无分类器)+ 声明 `acceptEdits`(下标 2 < 3 ⇒ 放过)—— 两者都让子代理
324
+ * 比派它的会话**更宽**,而那正是要挡的。
325
+ * - **误判**(安全但多挡):父 `default` + 声明 `acceptEdits`。
326
+ *
327
+ * 故改用**性质表**:只放行能证明是子集的三类,其余一律 fail-closed。
328
+ * - `plan` —— 层级表已证它「严格最窄」,是任何档的子集;
329
+ * - 与父同档 —— 即 `inherit` 解析后的形状;
330
+ * - 父为 `bypassPermissions` —— 它不挡任何调用 ⇒ 任何档都是它的子集。
331
+ * 表**故意**不完备:不可比的那几对既证不出是子集,就不放行。多拒绝落在安全侧,
332
+ * 而「子代理比派它的会话还宽」不是。
333
+ */
334
+ export function narrowsWithin(desired: PermissionMode, ceiling: PermissionMode): boolean {
335
+ if (desired === ceiling) return true
336
+ if (desired === 'plan') return true
337
+ if (ceiling === 'bypassPermissions') return true
338
+ return false
339
+ }
340
+
313
341
  /**
314
342
  * 从**仓库带来的** `forbiddenModes` 里挑出会造成「放宽」的条目 —— 判据是 `clampMode` 的回落。
315
343
  *
@@ -13,6 +13,7 @@ import {
13
13
  loadPermissionConfig,
14
14
  nextMode,
15
15
  clampMode,
16
+ narrowsWithin,
16
17
  normalizeRestrictions,
17
18
  ALL_MODES,
18
19
  } from './permission-config'
@@ -184,6 +185,14 @@ export class PermissionSystem {
184
185
  private restrictionWarnings: string[] = []
185
186
  /** Unrecognized `permission:` value from the last `setDefaultLevel` — third of the warning family. */
186
187
  private levelWarnings: string[] = []
188
+ /**
189
+ * 仓库带来的 agent 定义请求了比父会话更宽的档、被顶回去的记录 —— 第四位。
190
+ *
191
+ * 与上面三位不同:那三位是**配置**有问题(写错了),读的是入口;这条是**输入合法、
192
+ * 但方向不允许**(项目级 agent 想把自己抬宽),产生在**派发那一刻**、读的是派发处
193
+ * (`agent/sub-agent.ts`,那里才有 agent 的名字)。故不进那两条入口的读法守卫。
194
+ */
195
+ private agentCapWarnings: string[] = []
187
196
  /** Legacy exact-name rules for backward compat (set via setRule with 'self' level). */
188
197
  private legacyRules = new Map<string, PermissionLevel>()
189
198
  /** Legacy default level from constructor when passed non-mode values like 'ask' or 'bypass'. */
@@ -339,9 +348,10 @@ export class PermissionSystem {
339
348
  *
340
349
  * Returns a new PermissionSystem instance — NOT shared with the parent.
341
350
  */
342
- createSubAgentPermission(agentPermissionMode: string): PermissionSystem {
343
- const resolvedMode = this.resolveAgentMode(agentPermissionMode)
351
+ createSubAgentPermission(agentPermissionMode: string, source?: string): PermissionSystem {
352
+ const { mode: resolvedMode, capWarning } = this.resolveAgentMode(agentPermissionMode, source)
344
353
  const subPerm = new PermissionSystem(resolvedMode)
354
+ if (capWarning) subPerm.agentCapWarnings.push(capWarning)
345
355
 
346
356
  // Propagate org restrictions to sub-agent
347
357
  if (this.restrictions) {
@@ -377,8 +387,16 @@ export class PermissionSystem {
377
387
  * Resolve an agent's permissionMode string to a clamped PermissionMode.
378
388
  * 'inherit' means "use the parent's current mode".
379
389
  * 'bypass' is treated as an alias for 'bypassPermissions'.
390
+ *
391
+ * `source` is the agent definition's provenance (`agent/types.ts`). Only
392
+ * `'project'` is capped — see the comment on the cap. Returns the warning
393
+ * (if any) rather than printing, so the one caller that knows the agent's
394
+ * *name* owns the message; the judgement stays here, in one place.
380
395
  */
381
- private resolveAgentMode(agentMode: string): PermissionMode {
396
+ private resolveAgentMode(
397
+ agentMode: string,
398
+ source?: string,
399
+ ): { mode: PermissionMode; capWarning?: string } {
382
400
  // Normalize aliases
383
401
  const normalized = agentMode === 'bypass' ? 'bypassPermissions' : agentMode
384
402
 
@@ -395,8 +413,36 @@ export class PermissionSystem {
395
413
  inherit: this.mode,
396
414
  }
397
415
 
398
- const desired: PermissionMode = modeMap[normalized] || 'default'
399
- return clampMode(desired, this.restrictions)
416
+ let desired: PermissionMode = modeMap[normalized] || 'default'
417
+ let capWarning: string | undefined
418
+
419
+ // 仓库带来的东西可以**收窄**,不得**放宽** —— 与 `config/loader.ts` 的
420
+ // `stripProjectPermission`(项目级 config/settings 不是门)同一条判据,加上
421
+ // agent 定义这条当初没被那句话覆盖的路径。判据是**方向**、不是键名。
422
+ //
423
+ // 判在 `desired` 算完之后,是为了同时盖住上面那条 `|| 'default'` 回落:项目级把档位
424
+ // 名写错(拼错/大小写)会落到 `default`,若父档是 `plan`/`acceptEdits`,那同样是放宽。
425
+ //
426
+ // 边界(**有意**,不是遗漏):只收 `source === 'project'`。插件安装的 agent 由
427
+ // `plugin-loader.ts` / `claude-plugin.ts` 记为 `'user'`,是用户自己装的东西,
428
+ // 不在「仓库带来的」这一侧。
429
+ if (source === 'project' && !narrowsWithin(desired, this.mode)) {
430
+ capWarning =
431
+ `requested permission mode "${desired}", which is wider than the parent session's ` +
432
+ `"${this.mode}" — capped to "${this.mode}" (agent definitions from the repository may ` +
433
+ `narrow the approval gate, not widen it)`
434
+ desired = this.mode
435
+ }
436
+
437
+ return { mode: clampMode(desired, this.restrictions), capWarning }
438
+ }
439
+
440
+ /**
441
+ * 被顶回去的「项目级 agent 想放宽」记录,一条一句。与 `getInvalidRestrictions()` 同形 ——
442
+ * 消费者在派发处(`agent/sub-agent.ts`),那里才有 agent 的名字和 stderr。
443
+ */
444
+ getAgentCapWarnings(): string[] {
445
+ return this.agentCapWarnings
400
446
  }
401
447
 
402
448
  // ── Rule management ──
@@ -17,12 +17,21 @@
17
17
  * ---
18
18
  */
19
19
 
20
- import { readdirSync, readFileSync, existsSync } from 'node:fs'
20
+ import { readdirSync, readFileSync, existsSync, lstatSync, realpathSync } from 'node:fs'
21
21
  import { join } from 'node:path'
22
22
  import { globToRegexSource } from './credential-masker/matcher'
23
23
  import { findWorktreeMarker } from './paths.ts'
24
24
  import { MIPHAM_DIR } from '../shared/constants.ts'
25
25
 
26
+ /**
27
+ * 每个被拒的规则路径**只报告一次**(同 `core/permission-audit.ts` 的 `warnedOnce`)。
28
+ *
29
+ * 按路径去重而不是全局一次:两个坏文件是两件事。若只记一个全局布尔,daemon
30
+ * 那条路径(`daemon/engine-capabilities.ts` 每会话新建一只 loader)会让第二个
31
+ * 会话遇到同一个坏文件时一片沉默 —— 而「沉默」正是这里要消掉的东西。
32
+ */
33
+ const reportedRefusals = new Set<string>()
34
+
26
35
  interface RuleFile {
27
36
  name: string
28
37
  paths: string[] // glob patterns, empty = always loaded
@@ -48,12 +57,18 @@ export class RulesLoader {
48
57
  * `.claude/worktrees/` is not covered.
49
58
  */
50
59
  private projectRulesDir: string | null
60
+ /** Project directory owning `rulesDir` — i.e. `rulesDir` is `<rulesRoot>/.mipham/rules`. */
61
+ private rulesRoot: string
62
+ /** Project directory owning `projectRulesDir`; unused when that is `null`. */
63
+ private projectRoot: string
51
64
 
52
65
  constructor(cwd: string) {
66
+ this.rulesRoot = cwd
53
67
  this.rulesDir = join(cwd, MIPHAM_DIR, 'rules')
54
68
  const marker = findWorktreeMarker(cwd)
55
69
  const projectRulesDir = marker ? join(marker.root, MIPHAM_DIR, 'rules') : null
56
70
  this.projectRulesDir = projectRulesDir === this.rulesDir ? null : projectRulesDir
71
+ this.projectRoot = marker?.root ?? cwd
57
72
  }
58
73
 
59
74
  /**
@@ -61,24 +76,93 @@ export class RulesLoader {
61
76
  */
62
77
  load(): void {
63
78
  this.rules = []
64
- this.readDir(this.rulesDir)
65
- if (this.projectRulesDir) this.readDir(this.projectRulesDir)
79
+ this.readDir(this.rulesDir, this.rulesRoot)
80
+ if (this.projectRulesDir) this.readDir(this.projectRulesDir, this.projectRoot)
66
81
  }
67
82
 
68
83
  /**
69
84
  * Read every `.md` in `dir` into `this.rules`. A name already loaded wins —
70
85
  * "nearest first": a rule the worktree defines overrides the project copy.
86
+ *
87
+ * `root` is the project directory that owns `dir` (i.e. `dir` is exactly
88
+ * `<root>/.mipham/rules`); it bounds what a symlink may resolve to.
89
+ *
90
+ * ### Why every path here is checked before it is read
91
+ *
92
+ * A rule's body is injected into the conversation **verbatim** and shipped to
93
+ * the model provider. So `.mipham/rules/*.md` is not just config — it is an
94
+ * **egress** path that the repository alone controls, and `readFileSync` is
95
+ * the point where a name becomes content. Three shapes are refused:
96
+ *
97
+ * 1. **The rules directory reached through a symlink** — `.mipham/rules ->
98
+ * ~/.mipham/memory` would inject the user's private notes as project
99
+ * rules. It has to be checked on the *directory*: `.mipham` is one segment
100
+ * above the entries, so no per-entry check can see it.
101
+ * 2. **A symlinked rule file** — `-> ~/.ssh/id_rsa`, `-> ../../.env`. Note
102
+ * that "resolve it and require the target to be inside the project" is
103
+ * *not* a safe rule: the project root is exactly where the user's own
104
+ * gitignored secrets live. A rule must be a plain file, not a link.
105
+ * 3. **A non-regular file** — `readFileSync` on a FIFO blocks until a writer
106
+ * appears, and `/dev/zero` reads unboundedly: both *synchronously*, at
107
+ * startup. Same family as the audited non-regular-file hang on the daemon
108
+ * token path.
109
+ *
110
+ * Refusals are **reported, not skipped silently** (once per path, on stderr —
111
+ * this repo's warning channel). The rules directory exists so that its
112
+ * contents are always obeyed; a rule that is present but not loaded must say
113
+ * so. `config/loader.ts`'s `stripProjectPermission` made the same call.
114
+ *
115
+ * Honest boundary: in *this* repo `.mipham/` is gitignored, so these entries
116
+ * cannot be committed from here — the surface is a project that tracks
117
+ * `.mipham/` (or one where the file is placed on disk by other means). And
118
+ * the check is not TOCTOU-proof: it holds at the moment of the `lstat`.
71
119
  */
72
- private readDir(dir: string): void {
120
+ private readDir(dir: string, root: string): void {
73
121
  if (!existsSync(dir)) return
122
+
123
+ // Resolved against the *resolved* root, so a symlink anywhere above the
124
+ // project (macOS `/var -> /private/var`, a symlinked home) is not counted —
125
+ // only the `<root>/.mipham/rules` tail has to be link-free.
126
+ try {
127
+ if (realpathSync(dir) !== join(realpathSync(root), MIPHAM_DIR, 'rules')) {
128
+ this.refuse(dir, '规则目录不是本工程的真实目录(路径中有符号链接)')
129
+ return
130
+ }
131
+ } catch {
132
+ this.refuse(dir, '无法解析规则目录的真实路径')
133
+ return
134
+ }
135
+
74
136
  try {
75
137
  const seen = new Set(this.rules.map((r) => r.name))
76
138
  const files = readdirSync(dir).filter((f) => f.endsWith('.md'))
77
139
  for (const file of files) {
78
140
  const name = file.replace(/\.md$/, '')
79
141
  if (seen.has(name)) continue
142
+ const full = join(dir, file)
143
+
144
+ let entry
145
+ try {
146
+ entry = lstatSync(full)
147
+ } catch {
148
+ this.refuse(full, '无法读取文件状态')
149
+ continue
150
+ }
151
+ // `lstat` (not `stat`) — so a symlink reports as itself, not as its
152
+ // target. The `isFile` gate below would refuse a link anyway (a link is
153
+ // not a regular file); this branch exists to say **which** shape it was,
154
+ // because "refused" with the wrong reason is its own kind of silent.
155
+ if (entry.isSymbolicLink()) {
156
+ this.refuse(full, '是符号链接 —— 规则必须是普通文件')
157
+ continue
158
+ }
159
+ if (!entry.isFile()) {
160
+ this.refuse(full, '不是普通文件(目录/FIFO/设备)')
161
+ continue
162
+ }
163
+
80
164
  try {
81
- const raw = readFileSync(join(dir, file), 'utf-8')
165
+ const raw = readFileSync(full, 'utf-8')
82
166
  const { paths, description, content } = this.parseRule(raw, file)
83
167
  this.rules.push({ name, paths, description, content })
84
168
  seen.add(name)
@@ -91,6 +175,13 @@ export class RulesLoader {
91
175
  }
92
176
  }
93
177
 
178
+ /** Report a refused rule path once per process, on stderr. */
179
+ private refuse(path: string, reason: string): void {
180
+ if (reportedRefusals.has(path)) return
181
+ reportedRefusals.add(path)
182
+ process.stderr.write(`⚠️ 规则未被加载(之后不再重复报告): ${path} — ${reason}\n`)
183
+ }
184
+
94
185
  /**
95
186
  * Get rules that match the given file paths.
96
187
  * Rules with no paths filter ("always") are always included.
@@ -940,9 +940,11 @@
940
940
  "tool_denied_dangerous_rm": "Tool \"{name}\" was refused: this is a recursive rm whose target is not a path written in the command (\"{target}\"). The target is produced when the command runs, so neither an allow rule nor the permission mode can bound what it deletes. Name the directory literally instead — `rm -rf node_modules` rather than `rm -rf \"$(pwd)\"` — and treat this refusal as covering the outcome, not only this exact spelling. To turn this check off: MIPHAM_DISABLE_DANGEROUS_RM_PROMPT=1",
941
941
  "tool_denied_classifier_unavailable": "Tool \"{name}\" was held back because the auto-mode classifier could not be reached or its answer could not be read ({reason}). This is NOT a policy decision — the call was never judged, and retrying is appropriate. If this keeps happening, switch modes with Shift+Tab.",
942
942
  "tool_blocked": "Tool \"{name}\" blocked by hook",
943
+ "tool_hook_ask": "Tool \"{name}\" was marked by a hook as needing approval, and this environment has no interactive prompt — so it is refused. A repository-supplied hook may narrow the gate but not approve a call; if this hook is your own, make it block outright or relax it.",
943
944
  "user_input_blocked": "User input blocked by hook.",
944
945
  "dlp_blocked": "Request blocked by DLP policy.",
945
946
  "model_error": "Error: {error}",
947
+ "model_unavailable": "Model \"{model}\" (provider {provider}) is unavailable, and no default fallback model is configured — this turn produced no model output. Switch models with Ctrl+P, or check that provider's key and network, then retry. Underlying error: {error}",
946
948
  "tool_collision": "[mcp] Tool collision: \"{name}\" already registered. Skipping.",
947
949
  "missing_param": "Missing required parameter: \"{param}\"",
948
950
  "invalid_params": "Invalid parameters: {errors}",
@@ -940,9 +940,11 @@
940
940
  "tool_denied_dangerous_rm": "工具 \"{name}\" 被拒绝:这是一条递归 rm,其目标并非命令里写出的路径(\"{target}\")。该目标要到命令运行时才产生,所以任何放行规则与权限模式都无法界定它会删掉什么。请改为字面写出目录名 —— 用 `rm -rf node_modules` 而不是 `rm -rf \"$(pwd)\"` —— 并把这次拒绝理解为对结果本身的禁止,而不只是这一种写法。关闭此检查:MIPHAM_DISABLE_DANGEROUS_RM_PROMPT=1",
941
941
  "tool_denied_classifier_unavailable": "工具 \"{name}\" 被暂缓:auto 模式的分类器不可达,或其回复无法解析({reason})。这**不是**策略裁决 —— 该调用从未被裁决,重试是恰当的。若持续发生,按 Shift+Tab 切换模式。",
942
942
  "tool_blocked": "工具 \"{name}\" 被钩子拦截",
943
+ "tool_hook_ask": "工具 \"{name}\" 被钩子标为需要批准,而本环境没有交互批准 —— 已按拒绝处理。仓库带来的钩子只能收紧闸门、不能放行;若这是你自己的钩子,请让它直接拦截,或放宽它。",
943
944
  "user_input_blocked": "用户输入被钩子拦截。",
944
945
  "dlp_blocked": "请求被 DLP 策略阻止。",
945
946
  "model_error": "错误:{error}",
947
+ "model_unavailable": "模型 \"{model}\"(提供商 {provider})当前不可用,且没有可回退的默认模型 —— 本轮没有拿到任何模型输出。用 Ctrl+P 换一个模型,或检查该提供商的密钥与网络后重试。底层错误:{error}",
946
948
  "tool_collision": "[mcp] 工具冲突:\"{name}\" 已注册,跳过。",
947
949
  "missing_param": "缺少必需参数:\"{param}\"",
948
950
  "invalid_params": "参数无效:{errors}",
package/src/index.tsx CHANGED
@@ -746,6 +746,12 @@ export async function runApp(options: RunOptions): Promise<void> {
746
746
  // matching file. Loaded once at startup; setRulesLoader performs the load.
747
747
  engine.setRulesLoader(new RulesLoader(process.cwd()))
748
748
 
749
+ // CRSI lessons recall nudge: the instruction loader is where the *pointer* to the
750
+ // non-resident lessons comes from, so the nudge reads its emptiness condition from
751
+ // the same selection rather than guessing at a path. Same loader instance that
752
+ // builds the system prompt above — no second copy of the lessons state.
753
+ engine.setInstructions(instructions)
754
+
749
755
  // Wire inference hooks (DLP) configuration
750
756
  const inferenceHookConfig = loadInferenceHookConfig()
751
757
  engine.setInferenceHookConfig(inferenceHookConfig)
@@ -72,6 +72,14 @@ export function convertMcpTool(serverName: string, mcpTool: McpToolDefinition):
72
72
  async execute(params: Record<string, unknown>, _ctx: ToolContext): Promise<ToolResult> {
73
73
  const client = McpClient.getInstance()
74
74
 
75
+ // Startup connects servers without blocking, and a resumed session re-attaches
76
+ // them the same way — so a call can arrive while its server is still
77
+ // handshaking. Failing outright then is wrong twice over: the tool exists, and
78
+ // the only thing missing is patience. Same wait the `mcp_tool` hook already
79
+ // does (`core/hooks-executor.ts`), so both entry points treat a connecting
80
+ // server identically. A server that is *not* connecting returns immediately.
81
+ await client.waitUntilReady(serverName)
82
+
75
83
  const conn = client.getConnection(serverName)
76
84
  if (!conn || conn.status !== 'connected') {
77
85
  return {
@@ -14,7 +14,11 @@ export interface FetchWithRetryOptions {
14
14
  baseDelay?: number
15
15
  }
16
16
 
17
- const RETRYABLE_STATUSES = new Set([429, 500, 502, 503, 504])
17
+ // 529 is Anthropic's non-standard "overloaded" status: the request is rejected
18
+ // *before* the stream starts, on exactly the same terms as a 503 — transient,
19
+ // retryable, and already bounded by the `Retry-After` clamp below. Without it
20
+ // here, a 529 answers `!response.ok` and the whole turn dies at the first byte.
21
+ const RETRYABLE_STATUSES = new Set([429, 500, 502, 503, 504, 529])
18
22
 
19
23
  /**
20
24
  * Upper bound on a server-supplied `Retry-After`, in ms.
@@ -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.9' as const
12
+ export const PACKAGE_VERSION = '0.85.11' 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 = 3696 as const
93
+ export const TEST_COUNT = 3761 as const
@@ -255,3 +255,35 @@ export function sanitizeForDisplay(input: string): string {
255
255
  result = result.replace(/\f/g, '⟨FF⟩')
256
256
  return result
257
257
  }
258
+
259
+ /**
260
+ * Neutralize text that is about to be **injected into the system prompt** inside a
261
+ * tag-delimited block (memory recall, session summaries).
262
+ *
263
+ * Two steps, both load-bearing:
264
+ *
265
+ * 1. `stripDangerousUnicode` — the same invisible set the command path applies.
266
+ * Without it the text can carry an invisible character that hides part of a
267
+ * delimiter from anything scanning the text, while the model still reads it.
268
+ * 2. Drop `<…>`-shaped runs. The injection point wraps the text in
269
+ * `<system-reminder>…</system-reminder>`, so an entry whose own text contains
270
+ * `</system-reminder>` closes that block early and everything after it reads as
271
+ * ordinary prompt text instead of as recalled data. Stripping the brackets is
272
+ * what makes the wrapper unforgeable: the text stays readable, it just stops
273
+ * being able to *end* the block it was pasted into.
274
+ *
275
+ * Same move as `skills/sanitizer.ts` `sanitizeSkillDescription` (which strips
276
+ * `<[^>]*>` for this exact reason); this one additionally strips the invisible set,
277
+ * which the skill path does not. Both are lossy **on purpose** — an injected entry is
278
+ * prose for a model to read, not markup, so no legitimate entry loses meaning.
279
+ *
280
+ * The run is bounded at 200 characters so a stray `<` in prose cannot swallow the
281
+ * rest of the entry, and a letter must follow `<` (or `</`) immediately — so
282
+ * "a < b and c > d" survives while `</system-reminder>` does not. A forged delimiter
283
+ * with a space inside it (`</ system-reminder>`) is not a form this wrapper emits,
284
+ * and buying that case costs every piece of prose containing `< word >`.
285
+ */
286
+ export function neutralizeInjectedMarkup(input: string): string {
287
+ if (!input) return input
288
+ return stripDangerousUnicode(input).replace(/<\/?[A-Za-z][^<>]{0,200}>/g, '')
289
+ }
@@ -50,7 +50,7 @@ export const toolSearchTool: ToolDefinition = {
50
50
  content:
51
51
  '── MCP Tool Search ──\n\n' +
52
52
  'No MCP servers connected.\n\n' +
53
- 'Connect MCP servers in .mcp.json or via /mcp add <name> <url>.',
53
+ 'Connect MCP servers in .mcp.json or via /mcp connect <server-name>.',
54
54
  }
55
55
  }
56
56
 
@@ -3172,6 +3172,23 @@ const loopCmd: CommandHandler = async (ctx, args) => {
3172
3172
  return { content: lines.join('\n\n') }
3173
3173
  }
3174
3174
 
3175
+ // Shared tail of both autonomous-loop prompts below. It carries two fixes:
3176
+ //
3177
+ // - the journal's per-iteration row is the assistant's **visible text**
3178
+ // (`app.tsx` passes `assistantContent`, which only accumulates
3179
+ // `type === 'text'` chunks), so a loop that never emits text has a
3180
+ // progress log with nothing in it — the prompt now asks for one line;
3181
+ // - the prompts used to say `logAutoloopIteration("<id>", "<summary>")`, a
3182
+ // module export *inside* the CLI that is not a tool and so was never
3183
+ // callable, and to have the model write the journal file itself — which
3184
+ // would clobber the counters the CLI maintains there.
3185
+ const journalNotice = (id: string): string =>
3186
+ `\nEnd each iteration with one line of plain text saying where the loop stands.\n` +
3187
+ `The journal records the text you emit: an iteration that emits none is logged as\n` +
3188
+ `having no visible output, and /loop status shows that instead of progress.\n` +
3189
+ `Do not edit ~/.mipham/autoloop/${id}.json yourself — the CLI writes it (iteration\n` +
3190
+ `count, token totals, status) and a direct write would clobber that accounting.`
3191
+
3175
3192
  // ── /loop auto <prompt> — autonomous self-paced loop ──
3176
3193
  if (sub === 'auto') {
3177
3194
  const prompt = args.slice(1).join(' ')
@@ -3202,9 +3219,8 @@ const loopCmd: CommandHandler = async (ctx, args) => {
3202
3219
  ` - delaySeconds: your best estimate of how long to wait (60-3600)\n` +
3203
3220
  ` - reason: one sentence explaining why\n` +
3204
3221
  ` - prompt: include this full autonomous loop ID: ${sessionId}\n` +
3205
- `3. When the task is COMPLETE, call ScheduleWakeup with stop:true\n\n` +
3206
- `After each iteration, log progress by reading/writing the journal at ~/.mipham/autoloop/${sessionId}.json.\n` +
3207
- `Use the autoloop-journal module: logAutoloopIteration("${sessionId}", "<summary>").`
3222
+ `3. When the task is COMPLETE, call ScheduleWakeup with stop:true\n` +
3223
+ journalNotice(sessionId)
3208
3224
 
3209
3225
  return {
3210
3226
  content:
@@ -3259,8 +3275,8 @@ const loopCmd: CommandHandler = async (ctx, args) => {
3259
3275
  `You are in an autonomous loop (auto-detected — no interval specified). Each iteration:\n` +
3260
3276
  `1. Make progress on the task above\n` +
3261
3277
  `2. When you need to wait, call ScheduleWakeup with your chosen delaySeconds and this loop ID: ${sessionId}\n` +
3262
- `3. When COMPLETE, call ScheduleWakeup with stop:true\n\n` +
3263
- `Log progress using logAutoloopIteration("${sessionId}", "<summary>").`
3278
+ `3. When COMPLETE, call ScheduleWakeup with stop:true\n` +
3279
+ journalNotice(sessionId)
3264
3280
 
3265
3281
  return {
3266
3282
  content: