@miphamai/cli 0.85.23 → 0.85.25

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.
Files changed (42) hide show
  1. package/README.md +3 -3
  2. package/bin/mipham.ts +21 -2
  3. package/package.json +1 -1
  4. package/src/agent/agent-registry.ts +42 -2
  5. package/src/agent/message-router.ts +30 -0
  6. package/src/agent/sub-agent.ts +17 -0
  7. package/src/artifacts/server.ts +5 -1
  8. package/src/commands/git.ts +9 -1
  9. package/src/commands/project.ts +34 -17
  10. package/src/core/context-microcompact.ts +1 -1
  11. package/src/core/context-token.ts +55 -3
  12. package/src/core/context.ts +180 -43
  13. package/src/core/crsi-sandbox.ts +5 -1
  14. package/src/core/engine.ts +19 -6
  15. package/src/core/hooks.ts +13 -3
  16. package/src/core/instructions.ts +69 -2
  17. package/src/core/permission-rules.ts +141 -25
  18. package/src/i18n-core/locales/en-US.json +1 -0
  19. package/src/i18n-core/locales/zh-CN.json +1 -0
  20. package/src/mcp/client.ts +22 -8
  21. package/src/plugin/plugin-manager.ts +23 -2
  22. package/src/providers/anthropic.ts +8 -2
  23. package/src/providers/openai-compat.ts +14 -2
  24. package/src/providers/registry.ts +23 -1
  25. package/src/shared/arg-validation.ts +2 -1
  26. package/src/shared/git-env.ts +18 -0
  27. package/src/shared/package-info.ts +3 -3
  28. package/src/shared/sanitize.ts +21 -0
  29. package/src/skills/loader.ts +55 -3
  30. package/src/tools/agent/workflow.ts +9 -2
  31. package/src/tools/exec/bash.ts +206 -17
  32. package/src/tools/exec/enter-worktree.ts +26 -2
  33. package/src/tools/network/web-fetch.ts +11 -3
  34. package/src/tools/network/web-search.ts +5 -1
  35. package/src/tools/scheduling/schedule-wakeup.ts +3 -2
  36. package/src/tools/validation.ts +11 -0
  37. package/src/ui/app.tsx +22 -7
  38. package/src/ui/chat.tsx +3 -2
  39. package/src/ui/commands.ts +61 -7
  40. package/src/workflow/primitives/agent.ts +51 -6
  41. package/src/workflow/primitives/verify.ts +36 -20
  42. package/src/workflow/runtime.ts +10 -2
@@ -1,7 +1,20 @@
1
- import type { Message, ToolResult } from '../shared/index.ts'
1
+ import type {
2
+ ContentBlock,
3
+ Message,
4
+ TextContent,
5
+ ToolResult,
6
+ ToolResultContent,
7
+ } from '../shared/index.ts'
8
+ import { safeSlice } from '../shared/sanitize'
2
9
  import { snipMessages } from './context-snip'
3
- import { microcompact, shouldMicrocompact } from './context-microcompact'
4
- import { NoopCacheTracker, type CacheTracker, type CacheStatus } from './context-token'
10
+ import { microcompact, shouldMicrocompact, isToolResultUserMessage } from './context-microcompact'
11
+ import {
12
+ estimateMessageTokens,
13
+ estimateStringTokens,
14
+ NoopCacheTracker,
15
+ type CacheTracker,
16
+ type CacheStatus,
17
+ } from './context-token'
5
18
  import {
6
19
  SessionLog,
7
20
  messageToEvents,
@@ -11,7 +24,49 @@ import {
11
24
  closeInterruptedToolCalls,
12
25
  } from './session-log'
13
26
 
14
- export type Summarizer = (messages: Message[], heading: string) => Promise<string>
27
+ export type Summarizer = (
28
+ messages: Message[],
29
+ heading: string,
30
+ signal?: AbortSignal,
31
+ ) => Promise<string>
32
+
33
+ /**
34
+ * 削一段文本直到估计值落进预算:对半切、逐次复估 —— 与脚本文种无关的收敛法
35
+ * (`estimateMessageTokens` 对 CJK / emoji 的换算和拉丁文不同,按字符数硬算会切多或切少)。
36
+ * 够小就原样返回;削过则**说出削了多少**,悄悄截断会让模型把自己的半条证据当成全文。
37
+ */
38
+ function shrinkText(text: string, maxTokens: number): string {
39
+ const estimate = (t: string): number => estimateMessageTokens({ role: 'user', content: t })
40
+ if (estimate(text) <= maxTokens) return text
41
+
42
+ let out = text
43
+ for (let guard = 0; guard < 32 && out.length > 0 && estimate(out) > maxTokens; guard++) {
44
+ out = safeSlice(out, Math.floor(out.length / 2))
45
+ }
46
+ return `${out}\n… [truncated to fit the context budget; ${text.length - out.length} characters omitted]`
47
+ }
48
+
49
+ /** 把单条消息里可削的文本削进 `maxTokens`;结构(角色、块类型、`tool_use_id`)一律不动。 */
50
+ function truncateToBudget(msg: Message, maxTokens: number): Message {
51
+ if (typeof msg.content === 'string') {
52
+ const text = shrinkText(msg.content, maxTokens)
53
+ return text === msg.content ? msg : { ...msg, content: text }
54
+ }
55
+ if (!Array.isArray(msg.content)) return msg
56
+
57
+ const blocks = msg.content.map((b): ContentBlock => {
58
+ if (!b || typeof b !== 'object') return b
59
+ const block = b as unknown as Record<string, unknown>
60
+ if (block.type === 'text' && typeof block.text === 'string') {
61
+ return { ...(b as TextContent), text: shrinkText(block.text, maxTokens) }
62
+ }
63
+ if (block.type === 'tool_result' && typeof block.content === 'string') {
64
+ return { ...(b as ToolResultContent), content: shrinkText(block.content, maxTokens) }
65
+ }
66
+ return b
67
+ })
68
+ return { ...msg, content: blocks }
69
+ }
15
70
 
16
71
  interface ContextConfig {
17
72
  maxTokens: number
@@ -317,7 +372,7 @@ export class ContextManager {
317
372
  return this.getEstimatedTokens() > this.config.maxTokens * this.config.compactionThreshold
318
373
  }
319
374
 
320
- async compact(heading: string): Promise<{ before: number; after: number }> {
375
+ async compact(heading: string, signal?: AbortSignal): Promise<{ before: number; after: number }> {
321
376
  const beforeTokens = this.getEstimatedTokens()
322
377
 
323
378
  for (let i = 0; i < COMPACTION_PASSES.length; i++) {
@@ -326,34 +381,145 @@ export class ContextManager {
326
381
  // 仍超预算时继续 —— 这一句就是「压完再判一次」。
327
382
  if (i > 0 && !this.needsCompaction()) break
328
383
  if (this.messages.length <= pass.minLength) continue
329
- await this.compactOnce(heading, pass.keep)
384
+ await this.compactOnce(heading, pass.keep, signal)
330
385
  }
331
386
 
387
+ // 终端一趟:尺是**预算**,不是条数。
388
+ //
389
+ // 上面两趟都按条数削,而触发尺按 token —— 一段十来条消息、里头几个几十万字符的
390
+ // 工具结果 / 长文档的会话,两趟的 `minLength` 闸都会 `continue`,一次也不压。
391
+ // 于是 `needsCompaction()` 恒真、每轮都重试同一个空操作,直到上游拒收。
392
+ // 这里按预算从尾部往前留,留不下的**数清楚**再丢掉,并把这件事写进上下文。
393
+ if (this.needsCompaction()) this.enforceBudget()
394
+
332
395
  return { before: beforeTokens, after: this.getEstimatedTokens() }
333
396
  }
334
397
 
398
+ /**
399
+ * 把消息列表削到预算之内,且**只**在按条数的两趟都够不着时才会走到这里。
400
+ *
401
+ * 两点都是判据本身:
402
+ * - **从尾部往前留**,因为最新的一轮才是模型接下来要接着做的;
403
+ * - 丢弃要留痕。`compactOnce` 的两条路都靠一句话交代「前面被压过」,而这里丢掉的
404
+ * 东西没经摘要器,模型若不被告知,会把自己没见过的早期决定当成从未发生过。
405
+ */
406
+ private enforceBudget(): void {
407
+ // 消息那半能用的额度 = 总预算 − 提示那半。提示段(系统提示、权限段、MCP
408
+ // instructions)不归这里管:它们本来就每轮重派生,而按整份总额度削消息的话,
409
+ // 一段很长的系统提示会让这里把好好的对话截碎,且**削完照样超**。
410
+ const target = Math.max(
411
+ 1,
412
+ this.config.maxTokens * this.config.compactionThreshold - this.promptTokens(),
413
+ )
414
+ const est = (m: Message): number => this.estimateTokensForMessages([m])
415
+
416
+ let cut = this.messages.length
417
+ let used = 0
418
+ for (let i = this.messages.length - 1; i >= 0; i--) {
419
+ const t = est(this.messages[i]!)
420
+ // 最后一条无条件留下:全丢光就没有可回复的上下文了。
421
+ if (cut < this.messages.length && used + t > target) break
422
+ cut = i
423
+ used += t
424
+ }
425
+
426
+ // 幸存窗口不能以一条 `tool_result` 开头 —— 它的 `tool_use` 落在被丢的那半里,
427
+ // 上游会拒收「没有对应调用的结果」。往前多带一条,代价是多一点预算。
428
+ while (cut > 0 && isToolResultUserMessage(this.messages[cut]!)) {
429
+ cut--
430
+ used += est(this.messages[cut]!)
431
+ }
432
+
433
+ const dropped = this.messages.slice(0, cut)
434
+ let kept = this.messages.slice(cut)
435
+
436
+ const omittedNotice = (n: number): Message => ({
437
+ role: 'user',
438
+ content:
439
+ `[${n} earlier message${n === 1 ? '' : 's'} omitted — the context budget ` +
440
+ `could not hold them. They were not summarized; ask before assuming what ` +
441
+ `they said.]`,
442
+ })
443
+
444
+ // 幸存的那半自己就超预算(单条巨型结果 / 整篇文档)⇒ 没有可再丢的,只能截内容。
445
+ //
446
+ // 判据必须是**量出来的**「这份超没超」,不能是 `dropped.length === 0`:
447
+ // 只要有**一条**前面的消息被丢掉,那个条件就为假,而超额的恰恰可以是最后那条
448
+ // (丢弃循环对最后一条无条件保留)—— 于是「削完还超」,下一轮再进这里做同一个
449
+ // 空操作。通知自己也要占预算,所以按去掉通知后的额度分。
450
+ // 每条分到的是它自己那份,不是整份额度 —— 否则几条各占三分之一的消息谁也没超,
451
+ // 削完还是超。
452
+ const noticeTokens = dropped.length > 0 ? est(omittedNotice(dropped.length)) : 0
453
+ const bodyTarget = Math.max(1, target - noticeTokens)
454
+ if (kept.length > 0 && this.estimateTokensForMessages(kept) > bodyTarget) {
455
+ const perMessage = Math.max(1, Math.floor(bodyTarget / kept.length))
456
+ kept = kept.map((m) => truncateToBudget(m, perMessage))
457
+ }
458
+
459
+ // 通知自己也占预算,所以头部再补削,直到**含通知**的整份落进预算。少了这一步,
460
+ // 「刚好削到线内」的会话会因多出这一条而重新超线 —— 下一轮再削一次,逐轮掉消息。
461
+ // 顺带保住配对:若补削后的第一条是 `tool_result`,它的调用已在被丢的那半里,
462
+ // 一起丢,别留一个没有调用的结果给上游。
463
+ while (kept.length > 1) {
464
+ const withNotice = [omittedNotice(dropped.length), ...kept]
465
+ if (this.estimateTokensForMessages(withNotice) <= target) break
466
+ dropped.push(kept[0]!)
467
+ kept = kept.slice(1)
468
+ while (kept.length > 1 && isToolResultUserMessage(kept[0]!)) {
469
+ dropped.push(kept[0]!)
470
+ kept = kept.slice(1)
471
+ }
472
+ }
473
+
474
+ const notice: Message | null = dropped.length > 0 ? omittedNotice(dropped.length) : null
475
+ const next = notice ? [notice, ...kept] : kept
476
+
477
+ if (this.log) {
478
+ this.log.append({ type: 'compaction/rewrite', at: Date.now(), messages: next })
479
+ this.messages = deriveMessages(this.log.events())
480
+ } else {
481
+ this.messages = next
482
+ }
483
+
484
+ this.recountMessageTokens()
485
+ }
486
+
335
487
  /**
336
488
  * 压缩一趟:把消息削到最近 `keep` 条。
337
489
  *
338
490
  * body(除 `keep` 外)逐行取自旧 `compact()`,两种分支原样保留:LLM 摘要(失败回落截断)
339
491
  * 与纯截断。`recountMessageTokens()` 留在**这里**而不是调用方 —— 下一趟的闸要读它。
340
492
  */
341
- private async compactOnce(heading: string, keep: number): Promise<void> {
493
+ private async compactOnce(heading: string, keep: number, signal?: AbortSignal): Promise<void> {
342
494
  const toDrop = this.messages.slice(0, -keep)
343
495
 
344
496
  if (this.summarizer && toDrop.length >= 4) {
345
497
  // LLM-based summarization of truncated messages
346
498
  try {
347
- const summary = await this.summarizer(toDrop, heading)
499
+ const summary = await this.summarizer(toDrop, heading, signal)
500
+ // 摘要**替换**了这些东西,而不是它们被逐字保留:摘要器只读到每条前 2000 字符
501
+ // (见 `Engine.setupContextSummarizer`),写得再详细也回不到原文。把量说在
502
+ // 摘要后面,读的人才知道自己手里是一份缩写,不是完整历史 —— 前缀
503
+ // `[Earlier conversation summary]:` 是 `session-log` 的投影标记,不能改。
504
+ const annotated =
505
+ `${summary}\n\n(${toDrop.length} earlier message` +
506
+ `${toDrop.length === 1 ? '' : 's'} condensed into this summary.)`
348
507
  const summaryMsg: Message = {
349
508
  role: 'user',
350
- content: `[Earlier conversation summary]: ${summary}`,
509
+ content: `[Earlier conversation summary]: ${annotated}`,
351
510
  }
352
511
  this.messages = [summaryMsg, ...this.messages.slice(-keep)]
353
512
  if (this.log) {
354
513
  const derivedCount = deriveMessages(this.log.events()).length
355
514
  const replacedCount = Math.max(0, derivedCount - keep)
356
- this.log.append({ type: 'compaction/summary', at: Date.now(), summary, replacedCount })
515
+ // 记 `annotated` 而不是裸 `summary`:日志是消息投影的唯一真源,
516
+ // 两条路径拼出的字节必须一致(见 session-log 的 SUMMARY_PREFIX)。
517
+ this.log.append({
518
+ type: 'compaction/summary',
519
+ at: Date.now(),
520
+ summary: annotated,
521
+ replacedCount,
522
+ })
357
523
  }
358
524
  } catch {
359
525
  // Fall back to truncation on summarizer failure
@@ -603,40 +769,11 @@ export class ContextManager {
603
769
  /**
604
770
  * Estimate token count for a text string.
605
771
  *
606
- * Uses a character-class-aware heuristic:
607
- * - CJK / emoji: ~1.5 chars per token
608
- * - Other scripts (Latin, Cyrillic, Arabic): ~4 chars per token
609
- * - Whitespace-heavy (code): ~3 chars per token
610
- *
611
- * This is ~30-40% more accurate than flat 4 chars/token for mixed-language text.
772
+ * Delegates to `estimateStringTokens` — the same function the message counter
773
+ * uses. Two copies of the formula are two chances for the budget and the
774
+ * compaction trigger to disagree about the same text.
612
775
  */
613
776
  private estimateTokens(text: string): number {
614
- if (!text) return 0
615
-
616
- let cjk = 0
617
- let latin = 0
618
-
619
- for (const ch of text) {
620
- const cp = ch.codePointAt(0)!
621
- // CJK Unified Ideographs, Hangul, Kana, CJK Extensions, fullwidth forms
622
- if (
623
- (cp >= 0x4e00 && cp <= 0x9fff) || // CJK Unified
624
- (cp >= 0x3400 && cp <= 0x4dbf) || // CJK Ext-A
625
- (cp >= 0x20000 && cp <= 0x2a6df) || // CJK Ext-B
626
- (cp >= 0xac00 && cp <= 0xd7af) || // Hangul
627
- (cp >= 0x3040 && cp <= 0x30ff) || // Hiragana + Katakana
628
- (cp >= 0xff01 && cp <= 0xff60) || // Fullwidth
629
- (cp >= 0x1f300 && cp <= 0x1f9ff) // Emoji / pictographs
630
- ) {
631
- cjk++
632
- } else if (cp > 0x7f) {
633
- latin++
634
- } else {
635
- latin++
636
- }
637
- }
638
-
639
- // CJK: ~1.5 chars/token, Latin/other: ~4 chars/token
640
- return Math.max(1, Math.ceil(cjk / 1.5 + latin / 4))
777
+ return estimateStringTokens(text)
641
778
  }
642
779
  }
@@ -25,6 +25,7 @@ import {
25
25
  realpathSync,
26
26
  } from 'node:fs'
27
27
  import { atomicWriteFileSync } from '../shared/atomic-write'
28
+ import { internalGitEnv } from '../shared/git-env'
28
29
  import { join, resolve, sep, posix } from 'node:path'
29
30
  import { tmpdir } from 'node:os'
30
31
  import { randomUUID } from 'node:crypto'
@@ -296,7 +297,7 @@ function shq(s: string): string {
296
297
  * 对象字面量怎么变都动不了它们。下面那个字面量被抹成 `{}` 只会丢掉超时与编码,
297
298
  * 丢不掉「哪棵树」。**有意不再传 `cwd`** —— 留着它,下一个人会以为承重的是它。
298
299
  *
299
- * 守卫 `test/integrity/crsi-sandbox-command-root.test.ts` 静态钉住这个形状。
300
+ * 守卫 `test/integrity/crsi-sandbox-root.test.ts` 静态钉住这个形状。
300
301
  */
301
302
  function runIn(
302
303
  root: string,
@@ -309,6 +310,9 @@ function runIn(
309
310
  return execSync(rooted, {
310
311
  timeout: opts.timeoutMs ?? 10_000,
311
312
  encoding: 'utf-8',
313
+ // The sandbox derives its worktree from `HEAD`; a `refs/replace/*` entry
314
+ // would make that tree differ from the object graph the user actually has.
315
+ env: internalGitEnv(),
312
316
  ...(opts.quiet ? { stdio: ['ignore', 'pipe', 'ignore'] as StdioOptions } : {}),
313
317
  })
314
318
  }
@@ -46,6 +46,7 @@ import { getFileInboxTransport } from '../agent/cross-session/file-inbox'
46
46
  import { registerWakeupHandler, unregisterWakeupHandler } from '../tools/scheduling/schedule-wakeup'
47
47
  import { accumulateGraftSavings } from '../shared/graft-savings'
48
48
  import { deletedCwdSessionMessage, resolveExistingCwd } from '../shared/deleted-cwd'
49
+ import { safeSlice } from '../shared/sanitize'
49
50
  import {
50
51
  getMessageBus,
51
52
  formatInboundMessage,
@@ -585,12 +586,16 @@ export class QueryEngine {
585
586
 
586
587
  /** Wire LLM-based conversation summarization into the context manager. */
587
588
  setupContextSummarizer(): void {
588
- this.context.setSummarizer(async (messages, heading) => {
589
+ this.context.setSummarizer(async (messages, heading, signal) => {
589
590
  const text = messages
590
591
  .map((m) => {
591
592
  const role = m.role
592
593
  const content = typeof m.content === 'string' ? m.content : JSON.stringify(m.content)
593
- return `[${role}]: ${content.slice(0, 2000)}`
594
+ // 2000 字符是摘要器读得到的上限,但不能是**静默**上限:被切掉的那半里
595
+ // 常是工具结果的结论部分,摘要据此写成「做了什么」而漏掉「结果如何」。
596
+ // 写明省略了多少,摘要器才知道这条不完整。
597
+ if (content.length <= 2000) return `[${role}]: ${content}`
598
+ return `[${role}]: ${content.slice(0, 2000)} … [${content.length - 2000} characters omitted]`
594
599
  })
595
600
  .join('\n')
596
601
 
@@ -612,6 +617,11 @@ export class QueryEngine {
612
617
  systemPrompt: summaryPrompt,
613
618
  messages: [{ role: 'user', content: text }],
614
619
  maxTokens: 2000,
620
+ // An interrupt has to reach *this* call too. Summarising a long
621
+ // conversation is a full model round trip; without the signal, Ctrl+C
622
+ // arrives at the compaction step and simply waits for it to finish
623
+ // before the turn can stop.
624
+ signal,
615
625
  })) {
616
626
  if (chunk.type === 'text' && chunk.content) {
617
627
  summary += chunk.content
@@ -623,7 +633,10 @@ export class QueryEngine {
623
633
  // Return a minimal summary on failure
624
634
  }
625
635
 
626
- return summary.slice(0, 8000) || t('system.context.omitted')
636
+ // Surrogate-safe: this string lands in the JSONL transcript, where a lone
637
+ // half-pair makes the serializer emit an invalid escape and strict parsers
638
+ // reject the entire line.
639
+ return safeSlice(summary, 8000) || t('system.context.omitted')
627
640
  })
628
641
  }
629
642
 
@@ -678,7 +691,7 @@ export class QueryEngine {
678
691
 
679
692
  // Check compaction before processing
680
693
  if (this.context.needsCompaction()) {
681
- await this.compactWithHooks('conversation summary')
694
+ await this.compactWithHooks('conversation summary', signal)
682
695
  }
683
696
 
684
697
  const systemPrompt = this.context.getSystemPrompt()
@@ -2073,7 +2086,7 @@ export class QueryEngine {
2073
2086
  }
2074
2087
 
2075
2088
  /** Wrap context compaction with PreCompact/PostCompact hooks. */
2076
- private async compactWithHooks(heading: string): Promise<void> {
2089
+ private async compactWithHooks(heading: string, signal?: AbortSignal): Promise<void> {
2077
2090
  if (this.hookEngine) {
2078
2091
  const preResult = await this.hookEngine.executePreCompact(this.sessionId)
2079
2092
  if (preResult.additionalContext) {
@@ -2084,7 +2097,7 @@ export class QueryEngine {
2084
2097
  }
2085
2098
  }
2086
2099
 
2087
- await this.context.compact(heading)
2100
+ await this.context.compact(heading, signal)
2088
2101
 
2089
2102
  if (this.hookEngine) {
2090
2103
  const postResult = await this.hookEngine.executePostCompact(this.sessionId)
package/src/core/hooks.ts CHANGED
@@ -361,6 +361,15 @@ export class HookEngine {
361
361
 
362
362
  const result: HookResult = { allowed: true }
363
363
 
364
+ // A guard that could not run denies — but the denial is *remembered* rather
365
+ // than returned on the spot. Returning early would end the loop, and every
366
+ // later hook is a hook the call never got to consult: an explicit deny
367
+ // written after the broken one would never be reached, so the model gets
368
+ // "hook broke" where the real answer is "this was refused, here is why".
369
+ // Keep going, keep the first guard failure, and let an explicit deny
370
+ // (which returns immediately at its own branch) outweigh it.
371
+ let guardDenial: HookResult | undefined
372
+
364
373
  for (const hook of matching) {
365
374
  const key = this.healthKey(hook)
366
375
 
@@ -371,7 +380,7 @@ export class HookEngine {
371
380
  // it for `PreToolUse` would turn five failures into a permanent allow
372
381
  // for the rest of the cooldown — the same fail-open hole, delayed.
373
382
  if (guardFailureBlocks(hook)) {
374
- return {
383
+ guardDenial ??= {
375
384
  allowed: false,
376
385
  reason:
377
386
  `Hook "${key}" is temporarily disabled after repeated failures; ` +
@@ -379,6 +388,7 @@ export class HookEngine {
379
388
  `Fix the hook, re-enable it with /hooks enable "${key}", or set ` +
380
389
  `"failureMode": "open" to allow instead.`,
381
390
  }
391
+ continue
382
392
  }
383
393
  result.additionalContext = result.additionalContext
384
394
  ? result.additionalContext +
@@ -446,7 +456,7 @@ export class HookEngine {
446
456
  // that is not "allow" — see `guardFailureBlocks`.
447
457
  if (guardFailureBlocks(hook)) {
448
458
  const message = (err as { message?: string }).message || String(err)
449
- return {
459
+ guardDenial ??= {
450
460
  allowed: false,
451
461
  reason:
452
462
  `Hook "${key}" failed and the PreToolUse guard is fail-closed: ${message} ` +
@@ -457,7 +467,7 @@ export class HookEngine {
457
467
  }
458
468
  }
459
469
 
460
- return result
470
+ return guardDenial ?? result
461
471
  }
462
472
 
463
473
  listHooks(): HookDefinition[] {
@@ -14,6 +14,7 @@ import {
14
14
  type CrsiLessonSummary,
15
15
  } from './crsi-producer'
16
16
  import { miphamHome } from './paths.ts'
17
+ import { safeSlice } from '../shared/sanitize'
17
18
 
18
19
  export interface FrontmatterResult {
19
20
  data: Record<string, unknown>
@@ -71,7 +72,8 @@ export function parsePromptExclude(value: unknown): string[] {
71
72
  * 就能看见)。但 stdout 仍须是管道 —— 换成 `'ignore'`(`commands.ts` 里那种 stdout
72
73
  * 不用的形状)会让这里永远拿到空串、永远回退 cwd,**连在仓库里都失效**。
73
74
  */
74
- export function gitRoot(cwd: string): string {
75
+ export function gitRoot(cwd: string, available: boolean = gitAvailable()): string {
76
+ if (!available) return cwd
75
77
  try {
76
78
  return execSync('git rev-parse --show-toplevel', {
77
79
  cwd,
@@ -84,6 +86,34 @@ export function gitRoot(cwd: string): string {
84
86
  }
85
87
  }
86
88
 
89
+ let gitAvailableCache: boolean | undefined
90
+
91
+ /**
92
+ * macOS 上 `/usr/bin/git` 是个 **shim**:Command Line Tools 没装时,任何一次调用
93
+ * 都会弹「Install Command Line Developer Tools」的 **GUI 对话框** —— `stdio: 'ignore'`
94
+ * 挡得住 stderr 文本,挡不住这个窗口。本函数每次启动都会被调用(`loadAll`),
95
+ * 所以先花一次 `xcode-select -p`(系统自带、无 CLT 时只退非零、不弹窗)探一下。
96
+ *
97
+ * 探测结果缓存:进程生命周期内工具链不会装上,每个 cwd 各探一次纯属浪费。
98
+ * 非 darwin 平台原样 `true` —— 那些平台的 git 不会弹窗。
99
+ */
100
+ function gitAvailable(): boolean {
101
+ if (process.platform !== 'darwin') return true
102
+ if (gitAvailableCache !== undefined) return gitAvailableCache
103
+ try {
104
+ execSync('/usr/bin/xcode-select -p', {
105
+ timeout: 2000,
106
+ encoding: 'utf-8',
107
+ stdio: ['ignore', 'ignore', 'ignore'],
108
+ })
109
+ gitAvailableCache = true
110
+ } catch {
111
+ // 交互式 shell 里的 `/usr/bin/git` 在这种状态下会弹窗 —— 不要碰它。
112
+ gitAvailableCache = false
113
+ }
114
+ return gitAvailableCache
115
+ }
116
+
87
117
  /** True when `p` is `root` itself or sits underneath it. */
88
118
  function isInside(root: string, p: string): boolean {
89
119
  const rel = relative(root, p)
@@ -221,6 +251,43 @@ export interface InstructionSizeReport {
221
251
  */
222
252
  export const INSTRUCTION_BUDGET_CHARS = 40_000
223
253
 
254
+ /**
255
+ * Hard ceiling on a single instruction file's contribution.
256
+ *
257
+ * The budget above is a **report**: it says the payload has grown past a
258
+ * governance file's size, and the user decides what to trim. A nested
259
+ * `CLAUDE.md` discovered mid-session had no ceiling at all — a generated or
260
+ * concatenated file went into the prompt whole, on every request, and the only
261
+ * signal was a notice arriving after the fact. The two failure modes differ:
262
+ * a startup-tier file lands in the **system prompt** (never compressed, so it
263
+ * can make `needsCompaction()` true turn after turn), a nested file arrives as
264
+ * a **message** (compressible, but injected whole at that moment).
265
+ *
266
+ * Equal to the total budget on purpose: no single file may be worth the whole
267
+ * instruction allowance. The head is kept because instruction files put their
268
+ * rules first and their appendices last.
269
+ */
270
+ export const INSTRUCTION_FILE_MAX_CHARS = INSTRUCTION_BUDGET_CHARS
271
+
272
+ /**
273
+ * Keep the head of an oversized instruction file, and say so **in the payload**.
274
+ *
275
+ * A silent cut is the worse option: the model would follow a partial rule set
276
+ * without knowing anything was missing, and the user would see the usual budget
277
+ * notice (or nothing, if the rest of the payload is small). The marker costs a
278
+ * line and makes the truncation visible to both readers.
279
+ */
280
+ export function capInstructionContent(content: string, path: string): string {
281
+ if (content.length <= INSTRUCTION_FILE_MAX_CHARS) return content
282
+ const num = (n: number) => n.toLocaleString('en-US')
283
+ return (
284
+ safeSlice(content, INSTRUCTION_FILE_MAX_CHARS) +
285
+ `\n\n⚠ [truncated] ${path} is ${num(content.length)} characters; only the first ` +
286
+ `${num(INSTRUCTION_FILE_MAX_CHARS)} were loaded. Trim the file, or move doc-only ` +
287
+ 'sections under a `prompt-exclude` frontmatter key.'
288
+ )
289
+ }
290
+
224
291
  /**
225
292
  * The startup notice, or `null` while the payload is within budget.
226
293
  *
@@ -650,7 +717,7 @@ Never omit it or present the work as purely human-authored.`)
650
717
  level,
651
718
  privacy: (data.privacy as InstructionFile['privacy']) || 'project',
652
719
  language: (data.language as string) || 'en-US',
653
- content,
720
+ content: capInstructionContent(content, path),
654
721
  frontmatter: data,
655
722
  })
656
723
  } catch {