@miphamai/cli 0.85.33 → 0.85.35

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 (43) hide show
  1. package/README.md +1 -1
  2. package/package.json +1 -1
  3. package/src/agent/services.ts +21 -0
  4. package/src/agent/sub-agent.ts +129 -21
  5. package/src/commands/environment.ts +14 -11
  6. package/src/commands/project.ts +43 -12
  7. package/src/config/loader.ts +65 -35
  8. package/src/core/alignment-vocabulary.json +2 -2
  9. package/src/core/constitution-loader.ts +85 -24
  10. package/src/core/context.ts +22 -5
  11. package/src/core/engine.ts +62 -143
  12. package/src/core/hooks-config.ts +32 -0
  13. package/src/core/memory/memory-loader.ts +2 -2
  14. package/src/core/permission-rules.ts +67 -12
  15. package/src/core/session-log.ts +26 -7
  16. package/src/core/session-store.ts +4 -3
  17. package/src/core/tool-gate.ts +222 -0
  18. package/src/daemon/engine-capabilities.ts +124 -2
  19. package/src/daemon/remote-engine.ts +3 -0
  20. package/src/daemon/server.ts +13 -1
  21. package/src/i18n-core/locales/en-US.json +1 -0
  22. package/src/i18n-core/locales/zh-CN.json +1 -0
  23. package/src/mcp/client.ts +22 -2
  24. package/src/plugin/plugin-manager.ts +14 -0
  25. package/src/shared/package-info.ts +2 -2
  26. package/src/shared/types.ts +8 -0
  27. package/src/skills/fork-executor.ts +11 -1
  28. package/src/skills/marketplace.ts +44 -13
  29. package/src/skills/registry.ts +12 -1
  30. package/src/tools/agent/agent.ts +3 -0
  31. package/src/tools/agent/enter-plan.ts +22 -4
  32. package/src/tools/agent/exit-plan.ts +9 -1
  33. package/src/tools/agent/skill.ts +1 -0
  34. package/src/tools/agent/workflow.ts +1 -0
  35. package/src/tools/exec/git.ts +113 -69
  36. package/src/tools/index.ts +2 -2
  37. package/src/ui/app.tsx +15 -0
  38. package/src/ui/chat.tsx +7 -4
  39. package/src/ui/commands.ts +140 -20
  40. package/src/workflow/primitives/agent.ts +12 -1
  41. package/src/workflow/primitives/loop.ts +14 -0
  42. package/src/workflow/primitives/verify.ts +13 -1
  43. package/src/workflow/runtime.ts +1 -0
@@ -71,6 +71,37 @@ export const DEFAULT_CONSTITUTION: MiphamConstitution = {
71
71
 
72
72
  // ── Loader ──
73
73
 
74
+ /** `"Write,Edit,Bash"` → `["Write","Edit","Bash"]`; surrounding spaces dropped. */
75
+ function splitScope(scope: string): string[] {
76
+ return scope
77
+ .split(',')
78
+ .map((part) => part.trim())
79
+ .filter(Boolean)
80
+ }
81
+
82
+ /**
83
+ * 写侧:一律用 JSON 字符串。JSON 的双引号标量是合法 YAML,`"` 与 `\` 都被转义 ——
84
+ * 从前 `audit_pattern` 是原样塞进双引号里的,而它自己含 `['"]` 与 `\s`:标量提前闭合,
85
+ * 整份文件不是合法 YAML(自家那枚逐行解析器读得回,任何 YAML 工具读不了)。
86
+ */
87
+ function quoteYaml(value: string): string {
88
+ return JSON.stringify(value)
89
+ }
90
+
91
+ /** 读侧:双引号值按 JSON 解(写侧就是 JSON.stringify),单引号去壳,其余原样。 */
92
+ function parseScalar(raw: string): string {
93
+ const value = raw.trim()
94
+ if (value.startsWith('"')) {
95
+ try {
96
+ const decoded: unknown = JSON.parse(value)
97
+ if (typeof decoded === 'string') return decoded
98
+ } catch {
99
+ // 手写的引号坏掉了 —— 退回去壳,与从前一致
100
+ }
101
+ }
102
+ return value.replace(/^['"]|['"]$/g, '')
103
+ }
104
+
74
105
  export class ConstitutionLoader {
75
106
  private path: string
76
107
  private cached: MiphamConstitution | null = null
@@ -81,26 +112,41 @@ export class ConstitutionLoader {
81
112
 
82
113
  /**
83
114
  * Load the constitution from disk.
84
- * Falls back to the built-in DEFAULT_CONSTITUTION if no file exists.
115
+ * Falls back to the built-in DEFAULT_CONSTITUTION when the file is missing
116
+ * (and writes it out) or when an existing file cannot be read or validated
117
+ * (and leaves it untouched).
85
118
  */
86
119
  load(): MiphamConstitution {
87
120
  if (this.cached) return this.cached
88
121
 
89
- try {
90
- if (existsSync(this.path)) {
91
- const raw = readFileSync(this.path, 'utf-8')
92
- const parsed = this.parseYaml(raw)
122
+ // 文件在、但读不通或不合 schema:本次会话用内置默认原则,**但不动那个文件**。
123
+ // 覆盖它等于把用户手改的内容静默丢掉,而这个文件头正写着「改这里即可自定义」。
124
+ const fileExists = existsSync(this.path)
125
+ if (fileExists) {
126
+ try {
127
+ const parsed = this.parseYaml(readFileSync(this.path, 'utf-8'))
93
128
  if (this.validate(parsed)) {
94
129
  this.cached = parsed
95
130
  return parsed
96
131
  }
132
+ process.stderr.write(
133
+ `⚠ Mipham Code: ${this.path} does not match the guardrails schema ` +
134
+ '(every principle needs id, text and enforce) — using the built-in defaults this session\n' +
135
+ ' (the file was left as-is: fix it, or delete it to have it regenerated)\n',
136
+ )
137
+ } catch (err) {
138
+ const reason = err instanceof Error ? err.message : String(err)
139
+ process.stderr.write(
140
+ `⚠ Mipham Code: could not read ${this.path} (${reason}) — ` +
141
+ 'using the built-in defaults this session\n',
142
+ )
97
143
  }
98
- } catch {
99
- // Fall through to default
100
144
  }
101
145
 
102
- // Write the default constitution to disk for visibility
103
146
  this.cached = DEFAULT_CONSTITUTION
147
+ if (fileExists) return this.cached
148
+
149
+ // Only a missing file gets the default written out.
104
150
  try {
105
151
  const dir = miphamHome()
106
152
  if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
@@ -123,6 +169,12 @@ export class ConstitutionLoader {
123
169
  return constitution.principles.filter((p) => {
124
170
  if (p.scope === 'all-tools') return true
125
171
  if (p.tools && p.tools.includes(toolName)) return true
172
+ // `scope` is also used as a comma-separated tool list — the vocabulary
173
+ // spells `no-credential-leak` as `"Write,Edit,Bash"` and gives it no
174
+ // `tools` array. Reading only `tools` made exactly that entry inert: a
175
+ // rule whose whole purpose is to block a leaked key never ran for any
176
+ // tool, while its neighbours (which declare both keys) ran fine.
177
+ if (p.scope && splitScope(p.scope).includes(toolName)) return true
126
178
  return false
127
179
  })
128
180
  }
@@ -172,14 +224,20 @@ export class ConstitutionLoader {
172
224
  const trimmed = line.trim()
173
225
  if (!trimmed || trimmed.startsWith('#')) continue
174
226
 
175
- // Top-level keys
176
- if (!trimmed.startsWith('-') && !trimmed.startsWith(' ')) {
227
+ // 缩进只能从**原始行**读:`trimmed` 已经把缩进剥掉了,任何
228
+ // `trimmed.startsWith(' ')` 都是恒假 —— 从前就是这样,每个缩进字段
229
+ // 都掉进「顶层键」分支被丢掉,parse 出来的 principle 只剩 id。
230
+ const indented = line.startsWith(' ') || line.startsWith('\t')
231
+
232
+ // Top-level keys (no indentation, not a list item)
233
+ if (!indented && !trimmed.startsWith('-')) {
177
234
  const kv = trimmed.match(/^(\w[\w_]*):\s*(.*)$/)
178
235
  if (kv) {
179
236
  const key = kv[1]!
180
- const val = kv[2]!.trim().replace(/^['"]|['"]$/g, '')
237
+ const val = parseScalar(kv[2]!)
181
238
  if (key === 'version') result.version = val
182
239
  else if (key === 'last_modified') result.last_modified = val
240
+ else if (key === 'preamble') result.preamble = val
183
241
  if (key === 'principles') inPrinciples = true
184
242
  }
185
243
  continue
@@ -199,18 +257,18 @@ export class ConstitutionLoader {
199
257
  const kv = trimmed.substring(2).match(/^(\w[\w_]*):\s*(.*)$/)
200
258
  if (kv) {
201
259
  const key = kv[1]!
202
- const val = kv[2]!.trim().replace(/^['"]|['"]$/g, '')
260
+ const val = parseScalar(kv[2]!)
203
261
  this.setPrincipleField(currentPrinciple, key, val)
204
262
  }
205
263
  continue
206
264
  }
207
265
 
208
266
  // Indented fields of current principle
209
- if (inPrinciples && trimmed.startsWith(' ') && currentPrinciple) {
210
- const kv = trimmed.match(/^\s{2}(\w[\w_]*):\s*(.*)$/)
267
+ if (inPrinciples && indented && currentPrinciple) {
268
+ const kv = trimmed.match(/^(\w[\w_]*):\s*(.*)$/)
211
269
  if (kv) {
212
270
  const key = kv[1]!
213
- const val = kv[2]!.trim().replace(/^['"]|['"]$/g, '')
271
+ const val = parseScalar(kv[2]!)
214
272
  this.setPrincipleField(currentPrinciple, key, val)
215
273
  }
216
274
  }
@@ -279,20 +337,23 @@ export class ConstitutionLoader {
279
337
  '# Edit this file to customize principles. Delete it to restore defaults.',
280
338
  '# Changes take effect after /constitution reload or session restart.',
281
339
  '',
282
- `version: "${constitution.version}"`,
283
- `last_modified: "${constitution.last_modified}"`,
340
+ `version: ${quoteYaml(constitution.version)}`,
341
+ `last_modified: ${quoteYaml(constitution.last_modified)}`,
342
+ // 序言从前只活在内存里的 DEFAULT_CONSTITUTION 上 —— 落到盘上的文件没有它,
343
+ // 于是「读回来的那份」和「内置那份」不是同一份宪法。
344
+ ...(constitution.preamble ? [`preamble: ${quoteYaml(constitution.preamble)}`] : []),
284
345
  '',
285
346
  'principles:',
286
347
  ]
287
348
 
288
349
  for (const p of constitution.principles) {
289
- lines.push(` - id: "${p.id}"`)
290
- lines.push(` text: "${p.text}"`)
291
- lines.push(` enforce: ${p.enforce}`)
292
- if (p.facet) lines.push(` facet: ${p.facet}`)
293
- if (p.audit_pattern) lines.push(` audit_pattern: "${p.audit_pattern}"`)
294
- if (p.scope) lines.push(` scope: "${p.scope}"`)
295
- if (p.hook) lines.push(` hook: ${p.hook}`)
350
+ lines.push(` - id: ${quoteYaml(p.id)}`)
351
+ lines.push(` text: ${quoteYaml(p.text)}`)
352
+ lines.push(` enforce: ${quoteYaml(p.enforce)}`)
353
+ if (p.facet) lines.push(` facet: ${quoteYaml(p.facet)}`)
354
+ if (p.audit_pattern) lines.push(` audit_pattern: ${quoteYaml(p.audit_pattern)}`)
355
+ if (p.scope) lines.push(` scope: ${quoteYaml(p.scope)}`)
356
+ if (p.hook) lines.push(` hook: ${quoteYaml(p.hook)}`)
296
357
  if (p.tools) lines.push(` tools: [${p.tools.join(', ')}]`)
297
358
  if (p.rationale) lines.push(` rationale: "${p.rationale}"`)
298
359
  }
@@ -176,9 +176,24 @@ export class ContextManager {
176
176
 
177
177
  private log?: SessionLog
178
178
 
179
+ /**
180
+ * 这份日志是不是**完整历史**(默认是;CLI 的 `--resume` 语义依赖它为真)。
181
+ *
182
+ * `false` 只有一个场景:daemon 的会话日志是**审计增量** —— 历史的真源在 SQLite,
183
+ * 日志只记本进程窗口内发生的事。此时「model-visible means logged」这条不变量
184
+ * **按构造不成立**(回灌的旧消息从来没进过日志),故运行时断言必须跟着关掉,
185
+ * 否则它会在每次 `addMessage` 上抛一条「有消息没被记录」的错,而那不是缺陷。
186
+ *
187
+ * 关掉的是**断言**,不是写通:新事件照常落盘。两者不要混为一谈 ——
188
+ * 断言的价值是「能发现漏记」,而在一个从不记录历史投影的日志上,
189
+ * 它对每一行历史都会报警,于是报警这件事本身失效。
190
+ */
191
+ private logAuthoritative = true
192
+
179
193
  /** 附加一个 append-only 会话日志;addMessage/seedMessages 将写通镜像到日志。 */
180
- setLog(log?: SessionLog): void {
194
+ setLog(log?: SessionLog, opts?: { authoritative?: boolean }): void {
181
195
  this.log = log
196
+ this.logAuthoritative = opts?.authoritative ?? true
182
197
  }
183
198
 
184
199
  getLog(): SessionLog | undefined {
@@ -188,6 +203,8 @@ export class ContextManager {
188
203
  /** 从已持久化的日志恢复:设 log 为源,messages 为投影(不重复写通)。 */
189
204
  restoreLog(log: SessionLog): void {
190
205
  this.log = log
206
+ // 恢复出来的这份**就是完整历史**(`messages` 正是由它派生的),故断言重新生效。
207
+ this.logAuthoritative = true
191
208
  // 盘上那份历史可能以一条**没有结果**的调用收尾(写盘写到一半被打断,末尾那行半截
192
209
  // 结果被 `open()` 静默丢掉 —— 引擎自己的日志顺序到不了这个形状,见下面那个函数的
193
210
  // 注释)。挂着 `tool_calls` 却没有结果回应的请求会被 provider 整条拒收,用户看到的
@@ -320,7 +337,7 @@ export class ContextManager {
320
337
  for (const e of messageToEvents(msg, Date.now())) this.log.append(e)
321
338
  }
322
339
 
323
- if (this.log && isAssertModelVisibleDebug()) {
340
+ if (this.log && this.logAuthoritative && isAssertModelVisibleDebug()) {
324
341
  assertModelVisible(this.log.events(), this.messages)
325
342
  }
326
343
 
@@ -345,7 +362,7 @@ export class ContextManager {
345
362
  this.log.append({ type: 'context/inject', at: Date.now(), source, text })
346
363
  }
347
364
 
348
- if (this.log && isAssertModelVisibleDebug()) {
365
+ if (this.log && this.logAuthoritative && isAssertModelVisibleDebug()) {
349
366
  assertModelVisible(this.log.events(), this.messages)
350
367
  }
351
368
 
@@ -391,7 +408,7 @@ export class ContextManager {
391
408
  }
392
409
  this.recountMessageTokens()
393
410
 
394
- if (this.log && isAssertModelVisibleDebug()) {
411
+ if (this.log && this.logAuthoritative && isAssertModelVisibleDebug()) {
395
412
  assertModelVisible(this.log.events(), this.messages)
396
413
  }
397
414
  }
@@ -655,7 +672,7 @@ export class ContextManager {
655
672
  // 之后对 `this.messages` 的原地修改回写进已入队的事件里。
656
673
  if (this.log) {
657
674
  this.log.append({ type: 'rewind', at: Date.now(), messages: structuredClone(this.messages) })
658
- if (isAssertModelVisibleDebug()) {
675
+ if (this.logAuthoritative && isAssertModelVisibleDebug()) {
659
676
  assertModelVisible(this.log.events(), this.messages)
660
677
  }
661
678
  }
@@ -47,6 +47,8 @@ import { SelfCritique } from './self-critique.js'
47
47
  import { UsageTracker } from './usage-tracker'
48
48
  import { getMetrics } from './metrics'
49
49
  import { buildRequest, sendInferenceCheck, isInferenceHookEnabled } from './inference-hook'
50
+ import { runPreToolGate, type ToolGateDeps } from './tool-gate'
51
+ import type { SubAgentServices } from '../agent/services'
50
52
  import { getFileInboxTransport } from '../agent/cross-session/file-inbox'
51
53
  import { registerWakeupHandler, unregisterWakeupHandler } from '../tools/scheduling/schedule-wakeup'
52
54
  import { accumulateGraftSavings } from '../shared/graft-savings'
@@ -124,6 +126,17 @@ export function filterExpiredMessages(
124
126
  }
125
127
 
126
128
  export class QueryEngine {
129
+ /**
130
+ * `false` for the local engine; `true` for the attach-mode `RemoteEngine`.
131
+ *
132
+ * Commands that would otherwise *pretend* to change something the daemon owns
133
+ * (`/switch`, the model picker) read this: in attach mode `switchProvider` is a
134
+ * no-op, so the old code reported "✓ Switched" and moved the footer while the
135
+ * daemon kept running the previous model — a change that never happened looking
136
+ * exactly like one that did.
137
+ */
138
+ readonly isRemote = false
139
+
127
140
  private hookEngine?: HookEngine
128
141
  private artifactServer?: ArtifactServer
129
142
  private agentRegistry?: AgentRegistry
@@ -443,9 +456,9 @@ export class QueryEngine {
443
456
  /**
444
457
  * Register the instruction loader — the recall nudge's text source.
445
458
  *
446
- * daemon 侧有意不接:daemon **从不设置系统提示**(`setSystemPrompt` 在 `daemon/`
447
- * 下零调用点),因此那条路径上既没有常驻块、也没有指针 —— 接上去只会让扳机指向
448
- * 一个该会话从未被告知过的文件。见守卫的 `daemon:setInstructions` 豁免条目。
459
+ * 两个入口都接(`index.tsx:848` / `daemon/engine-capabilities.ts`):扳机只有在会话
460
+ * **已经被告知过**那份文件时才有意义,而 daemon 现在也会组装系统提示 —— 指针与常驻块
461
+ * 出自同一个 loader 实例,不存在「两边选了不同的文件」这种分叉。
449
462
  */
450
463
  setInstructions(loader: InstructionsLoader): void {
451
464
  this.instructionsLoader = loader
@@ -1452,150 +1465,22 @@ export class QueryEngine {
1452
1465
  // P1-4: Tool allowed — reset block counter
1453
1466
  this.permission.resetBlockCounter()
1454
1467
 
1455
- // Run PreToolUse hooks
1456
- let effectiveParams = params
1457
- let hookWarnings: string[] = []
1458
- if (this.hookEngine) {
1459
- const preResult = await this.hookEngine.executePreToolUse(name, params, this.sessionId)
1460
- if (!preResult.allowed) {
1461
- return {
1462
- success: false,
1463
- content: '',
1464
- error: preResult.reason || t('errors.tool_blocked', { name }),
1465
- notRun: true,
1466
- }
1467
- }
1468
-
1469
- // `permissionDecision` narrows only — never widens. `ask` stops the call here
1470
- // (this CLI has no interactive approval prompt; `ask` is a hard refusal, the
1471
- // same as the `default` mode's ask path). `allow` is deliberately **not**
1472
- // honoured: a hook can come from the repository's own settings, so letting it
1473
- // auto-approve is the same defect as a project-supplied agent definition that
1474
- // grants itself `bypassPermissions` — the criterion is the *direction*, not the
1475
- // key name. `defer` (and an absent decision) means "no override", which is
1476
- // exactly what happens when we do nothing.
1477
- if (preResult.permissionDecision === 'ask' || preResult.permissionDecision === 'deny') {
1478
- return {
1479
- success: false,
1480
- content: '',
1481
- error: preResult.reason || t('errors.tool_hook_ask', { name }),
1482
- notRun: true,
1483
- }
1484
- }
1485
-
1486
- if (preResult.modifiedInput) {
1487
- effectiveParams = { ...params, ...preResult.modifiedInput }
1488
- }
1489
-
1490
- // A hook's `additionalContext` is how every non-blocking hook speaks — the
1491
- // exit-1 stderr, a spawn failure, an unreachable `mcp_tool` server (see
1492
- // `core/hooks-executor.ts`). This path used to read only `allowed` /
1493
- // `modifiedInput`, so all of it was produced and then dropped. `hookWarnings`
1494
- // is the channel that already reaches the model: it is prepended to the tool
1495
- // result below. A non-`[rule:…]` line is ignored by the effectiveness tracker
1496
- // further down, so pushing prose here is safe.
1497
- if (preResult.additionalContext) {
1498
- hookWarnings.push(preResult.additionalContext)
1499
- }
1500
- }
1501
-
1502
- // CRSI RuleEngine intercept — gated by crsi.preToolHook feature flag
1503
- if (this.crsiConfig?.preToolHook !== false && this.ruleEngine) {
1504
- const ruleResult = this.ruleEngine.intercept(name, effectiveParams)
1505
- if (Object.keys(ruleResult.modified).length > 0) {
1506
- getMetrics().crsiRuleApplications.inc()
1507
- effectiveParams = ruleResult.modified
1508
- }
1509
- if (ruleResult.warnings.length > 0) {
1510
- // Append, do not replace: this array may already hold a PreToolUse hook's
1511
- // `additionalContext`. Every other writer below uses the spread form for the
1512
- // same reason — assignment here would silently drop whichever was written
1513
- // first ("two writers, one list").
1514
- hookWarnings = [...hookWarnings, ...ruleResult.warnings]
1515
- }
1516
- }
1517
-
1518
- // ── SIS PreFlightChecker — known error pattern interception ──
1519
- const preflight = this.getPreFlightChecker().check(name, effectiveParams)
1520
- if (preflight.action === 'block') {
1521
- getMetrics().sisInterceptions.inc()
1468
+ // Run every pre-execution gate. The chain is defined once, in
1469
+ // `core/tool-gate.ts`, because it used to live only in this loop: a `Write`
1470
+ // carrying an `apiKey = "sk-…"` was blocked here and executed verbatim by
1471
+ // `SubAgent`, which runs its own tool loop (`sub-agent.ts`). Two copies of a
1472
+ // gate drift; one definition called from both loops cannot.
1473
+ const gateOutcome = await runPreToolGate(name, params, this.getToolGateDeps(), this.sessionId)
1474
+ if (!gateOutcome.ok) {
1522
1475
  return {
1523
1476
  success: false,
1524
- content: preflight.warning || 'SIS 免疫系统拦截了此操作',
1525
- error: preflight.warning,
1526
- }
1527
- }
1528
- if (preflight.action === 'fix' && preflight.modifiedParams) {
1529
- getMetrics().sisInterceptions.inc()
1530
- effectiveParams = preflight.modifiedParams
1531
- if (preflight.warning) {
1532
- hookWarnings = [...hookWarnings, preflight.warning]
1533
- }
1534
- }
1535
- if (preflight.action === 'warn' && preflight.warning) {
1536
- hookWarnings = [...hookWarnings, preflight.warning]
1537
- }
1538
-
1539
- // ── Mipham Constitution — constitutional principle enforcement ──
1540
- // Checks the tool + params against the machine-readable constitution.
1541
- // Block-level violations (enforce: block) halt execution immediately.
1542
- // Warn-level violations (enforce: warn) are appended to hookWarnings.
1543
- const constitution = this.getConstitutionLoader()
1544
- const principles = constitution.getPrinciplesForTool(name)
1545
- for (const principle of principles) {
1546
- if (principle.enforce === 'block') {
1547
- // Audit: check if the tool params or command match a violation pattern
1548
- if (principle.audit_pattern) {
1549
- try {
1550
- const regex = new RegExp(principle.audit_pattern, 'i')
1551
- const paramsStr = JSON.stringify(effectiveParams)
1552
- if (regex.test(paramsStr)) {
1553
- return {
1554
- success: false,
1555
- content: `🚫 Constitution violation blocked: **${principle.id}** — ${principle.text}`,
1556
- error: `Constitutional principle "${principle.id}" blocked this operation.`,
1557
- }
1558
- }
1559
- } catch {
1560
- // Invalid regex — skip this principle
1561
- }
1562
- }
1563
- }
1564
- if (principle.enforce === 'warn') {
1565
- hookWarnings = [...hookWarnings, `⚖️ Constitution: ${principle.id} — ${principle.text}`]
1566
- }
1567
- }
1568
-
1569
- // ── Self-Critique Hook — RLAIF-style tool-call safety verification ──
1570
- // Uses a fast model (Flash) to critique the tool call before execution.
1571
- // Safe + correct + necessary check with <200ms target latency.
1572
- // Fail-open: if the critique times out or errors, the tool still executes.
1573
- const selfCritique = this.getSelfCritique()
1574
- if (selfCritique.getConfig().enabled) {
1575
- const critiqueResult = await selfCritique.critique(
1576
- name,
1577
- effectiveParams,
1578
- this.registry,
1579
- this.llm,
1580
- )
1581
- if (critiqueResult) {
1582
- if (critiqueResult.score < selfCritique.getConfig().threshold) {
1583
- // Score too low — block with explanation
1584
- if (!critiqueResult.safe) {
1585
- return {
1586
- success: false,
1587
- content: `🔍 Self-Critique blocked: ${critiqueResult.reasoning}`,
1588
- error: `Self-Critique safety check failed (score: ${(critiqueResult.score * 100).toFixed(0)}%). ${critiqueResult.correction || ''}`,
1589
- }
1590
- }
1591
- // Score low but safe — warn but allow
1592
- hookWarnings = [
1593
- ...hookWarnings,
1594
- `🔍 Self-Critique: ${critiqueResult.reasoning}${critiqueResult.correction ? ` — Suggestion: ${critiqueResult.correction}` : ''}`,
1595
- ]
1596
- }
1477
+ content: gateOutcome.content,
1478
+ error: gateOutcome.error,
1479
+ ...(gateOutcome.notRun ? { notRun: true } : {}),
1597
1480
  }
1598
1481
  }
1482
+ const effectiveParams = gateOutcome.params
1483
+ const hookWarnings = gateOutcome.warnings
1599
1484
 
1600
1485
  // The gate at the top of this method ruled on `params`. Everything since —
1601
1486
  // the PreToolUse hook's `modifiedInput`, the CRSI RuleEngine's `modified`, the
@@ -1650,6 +1535,7 @@ export class QueryEngine {
1650
1535
  backgroundAgentRegistry: getBackgroundAgentRegistry(),
1651
1536
  permissionSystem: this.permission,
1652
1537
  ruleEngine: this.ruleEngine,
1538
+ subAgentServices: this.getSubAgentServices(),
1653
1539
  llm: this.llm,
1654
1540
  readFiles: this.readFiles,
1655
1541
  readFilesComplete: this.readFilesComplete,
@@ -2141,6 +2027,39 @@ export class QueryEngine {
2141
2027
  return this._errorSignatureDB
2142
2028
  }
2143
2029
 
2030
+ /**
2031
+ * The pre-execution chain's dependencies, as a value.
2032
+ *
2033
+ * Built on every tool call rather than cached: `hookEngine` is assigned after
2034
+ * construction (`setHooks`), and the three lazy singletons must stay lazy.
2035
+ */
2036
+ getToolGateDeps(): ToolGateDeps {
2037
+ return {
2038
+ hookEngine: this.hookEngine,
2039
+ ruleEngine: this.ruleEngine,
2040
+ preflight: () => this.getPreFlightChecker(),
2041
+ constitution: () => this.getConstitutionLoader(),
2042
+ selfCritique: () => this.getSelfCritique(),
2043
+ crsiPreToolHook: this.crsiConfig?.preToolHook !== false,
2044
+ registry: this.registry,
2045
+ llm: this.llm,
2046
+ }
2047
+ }
2048
+
2049
+ /**
2050
+ * What a sub-agent needs to run the same gates as this loop.
2051
+ *
2052
+ * One producer (`Engine`) and one consumer (`SubAgent`). Before this existed,
2053
+ * all five production `new SubAgent(...)` sites passed `undefined` for the
2054
+ * hook engine and none of them reached the constitution / SIS / CRSI chain.
2055
+ */
2056
+ getSubAgentServices(): SubAgentServices {
2057
+ return {
2058
+ gate: this.getToolGateDeps(),
2059
+ inferenceHook: this.inferenceHookConfig,
2060
+ }
2061
+ }
2062
+
2144
2063
  /**
2145
2064
  * SIS Phase 0: Lazily-initialized PreFlightChecker singleton.
2146
2065
  * Checks tool calls against ErrorSignatureDB + ExperienceRuleEngine
@@ -18,12 +18,36 @@ export interface SettingsHooks {
18
18
  UserPromptSubmit?: HookConfigEntry[]
19
19
  PreCompact?: HookConfigEntry[]
20
20
  PostCompact?: HookConfigEntry[]
21
+ /** ⚠️ 目前**没有派发点** —— 写在这里不报错,但不会跑。见 `UNDISPATCHED_EVENTS`。 */
21
22
  ConfigChange?: HookConfigEntry[]
22
23
  SubagentStart?: HookConfigEntry[]
23
24
  SubagentStop?: HookConfigEntry[]
25
+ /** ⚠️ 目前**没有派发点** —— 写在这里不报错,但不会跑。见 `UNDISPATCHED_EVENTS`。 */
24
26
  PreInference?: HookConfigEntry[]
25
27
  }
26
28
 
29
+ /**
30
+ * `settings.json` 接受、但**生产代码里没有任何派发点**的事件。
31
+ *
32
+ * `HookEngine` 上这两个事件各有一个现成方法(`hooks.ts:162` / `:222`,名字见 ROADMAP D18),
33
+ * 而它们在 `src/` + `bin/` 里**零引用** —— `grep` 只剩定义行与测试。注册进去的后果不是
34
+ * 「静默不生效」那么简单:`/hooks` 遍历的是**配置文件本身**(`ui/commands.ts`),于是用户
35
+ * 看到自己那条 hook 被列出来、计入 `hooks.found N` —— 读起来是「已安装」,实际一次都不会跑。
36
+ * **被告知的东西与发生的事分叉,比「不支持」更坏。**
37
+ *
38
+ * 所以这里**不注册**并说出原因。`/hooks` 读的是配置文件本身、不读注册表,故单靠这一层
39
+ * 并不能改变它的输出 —— 它会**继续列出**这些条目,所以 `ui/commands.ts` 的 `/hooks`
40
+ * 必须用同一个集合给它们打「不会运行」标记并排除出计数。两处共用一个集合,名单才不会
41
+ * 各写一份、各自漂移。接线本身是独立决定(ROADMAP D18):`PreInference` 要先定
42
+ * 「settings.json 的任意命令 hook」与「把整段对话正文发往组织端点的 DLP」如何共存 ——
43
+ * 后者是数据出境面,不能顺手接。
44
+ *
45
+ * ⚠️ 本注释**刻意不逐字写出那两个方法名**:`unwired-disposition.test.ts` 的
46
+ * `referencesOutside` 匹配的是**文本出现**、不是调用点,写出来就会把那条守卫打红
47
+ * (它自己的 docblock 里写着这条反向边界)。要查名字去看 ROADMAP D18。
48
+ */
49
+ export const UNDISPATCHED_EVENTS = new Set<string>(['ConfigChange', 'PreInference'])
50
+
27
51
  /**
28
52
  * Load hook configurations from a settings object and convert them to
29
53
  * executable HookDefinitions suitable for the HookEngine.
@@ -34,6 +58,14 @@ export function loadHookConfigs(configs: SettingsHooks): HookDefinition[] {
34
58
  for (const [eventName, entries] of Object.entries(configs)) {
35
59
  if (!entries || !Array.isArray(entries)) continue
36
60
 
61
+ if (UNDISPATCHED_EVENTS.has(eventName)) {
62
+ process.stderr.write(
63
+ `⚠️ Hook event ${eventName} has no dispatch point in this version — ` +
64
+ `${entries.length} configured hook group(s) under it will not run and are not registered.\n`,
65
+ )
66
+ continue
67
+ }
68
+
37
69
  for (const entry of entries) {
38
70
  // A matcher is only a *filter*, so a malformed one must not take the whole
39
71
  // hook set down with it. `new RegExp` throws here, and both callers register
@@ -18,7 +18,7 @@ export function getMemoryManager(): MemoryManagerType {
18
18
  * Load relevant memories for the current session and inject as
19
19
  * a system-reminder block. Called at SessionStart.
20
20
  */
21
- export function loadSessionMemories(context: string): string {
21
+ export function loadSessionMemories(context: string, maxTokens?: number): string {
22
22
  const mm = getMemoryManager()
23
- return mm.buildSystemReminder(context)
23
+ return mm.buildSystemReminder(context, maxTokens)
24
24
  }