@miphamai/cli 0.85.25 → 0.85.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/bin/mipham.ts +34 -24
- package/package.json +1 -1
- package/src/agent/agent-context.ts +23 -3
- package/src/agent/sub-agent.ts +42 -15
- package/src/core/context.ts +32 -0
- package/src/core/engine.ts +182 -20
- package/src/core/instructions.ts +64 -17
- package/src/core/memory/memory-audit.ts +105 -0
- package/src/core/memory/memory-manager.ts +78 -53
- package/src/core/merge-gate.ts +158 -0
- package/src/core/number-provenance.ts +106 -0
- package/src/core/permission-rule-ack.ts +67 -0
- package/src/daemon/engine-capabilities.ts +2 -0
- package/src/daemon/remote-engine.ts +11 -5
- package/src/daemon/schedule-manager.ts +32 -3
- package/src/daemon/server.ts +6 -0
- package/src/i18n-core/locales/en-US.json +11 -3
- package/src/i18n-core/locales/zh-CN.json +11 -3
- package/src/index.tsx +36 -4
- package/src/mcp/client.ts +37 -2
- package/src/mcp/http-transport.ts +20 -1
- package/src/mcp/protocol.ts +13 -5
- package/src/mcp/registry.ts +8 -3
- package/src/mcp/transport.ts +40 -3
- package/src/providers/anthropic.ts +3 -1
- package/src/providers/fetch-utils.ts +40 -6
- package/src/providers/openai-compat.ts +2 -1
- package/src/shared/package-info.ts +2 -2
- package/src/shared/types.ts +9 -0
- package/src/tools/exec/bash.ts +1 -1
- package/src/tools/exec/task.ts +144 -21
- package/src/tools/network/web-fetch.ts +7 -7
- package/src/tools/network/web-search.ts +6 -5
- package/src/ui/commands.ts +43 -3
package/src/core/instructions.ts
CHANGED
|
@@ -500,7 +500,9 @@ Before merging a PR or committing changes that have not been
|
|
|
500
500
|
code-reviewed, run a code review first (the /code-review command or the
|
|
501
501
|
code-review skill) and address its findings. Do not rely on "the user
|
|
502
502
|
happened to ask" to trigger a review — review proactively as a fixed
|
|
503
|
-
step before merge
|
|
503
|
+
step before merge. This is enforced, not merely advised: a built-in
|
|
504
|
+
PreToolUse gate blocks a gh pr merge command when no review skill has run
|
|
505
|
+
in the session.`)
|
|
504
506
|
|
|
505
507
|
// 不可信内容规则 — 读外部产出当数据不当指令,内嵌指令标记而非转述(对齐 §二 prompt-injection 红线)
|
|
506
508
|
parts.push(`## Untrusted-Content Rule
|
|
@@ -687,27 +689,72 @@ Never omit it or present the work as purely human-authored.`)
|
|
|
687
689
|
return { totalChars: files.reduce((n, f) => n + f.chars, 0), files }
|
|
688
690
|
}
|
|
689
691
|
|
|
690
|
-
|
|
691
|
-
|
|
692
|
+
/**
|
|
693
|
+
* A repo-controlled instruction file must be a regular file, not a symlink.
|
|
694
|
+
* A cloned repository can ship `CLAUDE.md -> ~/.ssh/id_rsa`: this loader runs
|
|
695
|
+
* with no permission gate at all, so following the link would put any local
|
|
696
|
+
* file into the system prompt without the model ever asking for it. `lstat`
|
|
697
|
+
* reports the link as itself, which is what makes the shape visible.
|
|
698
|
+
*
|
|
699
|
+
* Only the levels that live *inside* the checkout (`project`, `directory`)
|
|
700
|
+
* are gated. A symlinked `~/.mipham/USER.md` pointing at a dotfiles repo is
|
|
701
|
+
* the user's own arrangement, and the group/company tiers point at the
|
|
702
|
+
* surrounding monorepo the user cloned deliberately — refusing those would
|
|
703
|
+
* break real setups without closing anything a repo did not already control.
|
|
704
|
+
*
|
|
705
|
+
* An unreadable `lstat` counts as unsafe: the shape could not be established.
|
|
706
|
+
*/
|
|
707
|
+
private isUnsafePath(path: string, level: InstructionFile['level']): boolean {
|
|
708
|
+
if (level !== 'project' && level !== 'directory') return false
|
|
709
|
+
try {
|
|
710
|
+
return lstatSync(path).isSymbolicLink()
|
|
711
|
+
} catch {
|
|
712
|
+
return true
|
|
713
|
+
}
|
|
714
|
+
}
|
|
692
715
|
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
716
|
+
/**
|
|
717
|
+
* Re-read every instruction file already in the prompt, and report the paths
|
|
718
|
+
* whose text actually changed.
|
|
719
|
+
*
|
|
720
|
+
* The chain is read once, at `loadAll`. An edit made during the session — the
|
|
721
|
+
* user tightening their `CLAUDE.md`, a skill rewriting `AGENTS.md` — therefore
|
|
722
|
+
* never reached the model. `ContextManager.refreshSystemPrompt()` calls this
|
|
723
|
+
* after compaction, which is the moment the conversation those rules govern
|
|
724
|
+
* has just been replaced anyway.
|
|
725
|
+
*
|
|
726
|
+
* Deliberately does **not** discover new files: which directories to walk is
|
|
727
|
+
* `loadAll`'s decision, and re-walking here would make the prompt depend on
|
|
728
|
+
* what happens to exist at compaction time. A file that disappeared keeps its
|
|
729
|
+
* last-known text rather than silently dropping a rule mid-session, and one
|
|
730
|
+
* that became a symlink keeps it too (same gate as the first read).
|
|
731
|
+
*/
|
|
732
|
+
refresh(): string[] {
|
|
733
|
+
const changed: string[] = []
|
|
734
|
+
for (const inst of this.instructions) {
|
|
735
|
+
if (this.isUnsafePath(inst.path, inst.level)) continue
|
|
736
|
+
if (!existsSync(inst.path)) continue
|
|
705
737
|
try {
|
|
706
|
-
|
|
738
|
+
const { data, content } = parseFrontmatter(readFileSync(inst.path, 'utf-8'))
|
|
739
|
+
const next = capInstructionContent(content, inst.path)
|
|
740
|
+
if (next !== inst.content) {
|
|
741
|
+
inst.content = next
|
|
742
|
+
changed.push(inst.path)
|
|
743
|
+
}
|
|
744
|
+
inst.privacy = (data.privacy as InstructionFile['privacy']) || 'project'
|
|
745
|
+
inst.language = (data.language as string) || 'en-US'
|
|
746
|
+
inst.frontmatter = data
|
|
707
747
|
} catch {
|
|
708
|
-
|
|
748
|
+
// Unreadable right now: keep the text the session has been running on.
|
|
709
749
|
}
|
|
710
750
|
}
|
|
751
|
+
return changed
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
private tryLoad(path: string, level: InstructionFile['level']): void {
|
|
755
|
+
if (!existsSync(path)) return
|
|
756
|
+
|
|
757
|
+
if (this.isUnsafePath(path, level)) return
|
|
711
758
|
|
|
712
759
|
try {
|
|
713
760
|
const raw = readFileSync(path, 'utf-8')
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { existsSync, readdirSync, readFileSync } from 'node:fs'
|
|
2
|
+
import { extname, join } from 'node:path'
|
|
3
|
+
import { extractWikilinks, readMemoryFile } from './memory-manager'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* 记忆库体检:找出「盘上有、系统看不见」的分歧。
|
|
7
|
+
*
|
|
8
|
+
* 四类问题都是同一物种 —— 存储与加载各说各话,而运行时**静默**吞掉差异:
|
|
9
|
+
*
|
|
10
|
+
* - `invisible`:文件读不出记忆条目(无 frontmatter / 无 name / 读不了),
|
|
11
|
+
* 会永远躺在 `~/.mipham/memory/` 里却召不回来。
|
|
12
|
+
* - `duplicate-name`:两个文件声明同一个 `name`,Map 按 name 存 ⇒ 后读的
|
|
13
|
+
* 覆盖先读的,另一个文件从此不可达。
|
|
14
|
+
* - `broken-link`:`[[x]]` 指向不存在的记忆,链接图里那条边是死边。
|
|
15
|
+
* - `index-drift`:`MEMORY.md` 与真实条目对不上(只在写入时重建,手改文件
|
|
16
|
+
* 就会漂移)—— 漂移的是给人看的那份,人读到的清单会说谎。
|
|
17
|
+
*
|
|
18
|
+
* 只读:不移动、不改写、不归档。`/memory gc` 才是会动手的那个。
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
export type MemoryIssueKind = 'invisible' | 'duplicate-name' | 'broken-link' | 'index-drift'
|
|
22
|
+
|
|
23
|
+
export interface MemoryIssue {
|
|
24
|
+
kind: MemoryIssueKind
|
|
25
|
+
/** 文件名、记忆名或链接目标,视 kind 而定 */
|
|
26
|
+
subject: string
|
|
27
|
+
detail: string
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const INDEX_FILE = 'MEMORY.md'
|
|
31
|
+
|
|
32
|
+
const PROBLEM_TEXT: Record<string, string> = {
|
|
33
|
+
'no-frontmatter': 'no frontmatter — the loader skips it',
|
|
34
|
+
'no-name': 'frontmatter has no name — the loader skips it',
|
|
35
|
+
unreadable: 'unreadable',
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function auditMemoryDir(dir: string): MemoryIssue[] {
|
|
39
|
+
const issues: MemoryIssue[] = []
|
|
40
|
+
if (!existsSync(dir)) return issues
|
|
41
|
+
|
|
42
|
+
let files: string[]
|
|
43
|
+
try {
|
|
44
|
+
files = readdirSync(dir)
|
|
45
|
+
.filter((f) => extname(f) === '.md' && f !== INDEX_FILE)
|
|
46
|
+
.sort()
|
|
47
|
+
} catch {
|
|
48
|
+
return issues
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const byName = new Map<string, string[]>()
|
|
52
|
+
const linkSources = new Map<string, string[]>()
|
|
53
|
+
|
|
54
|
+
for (const file of files) {
|
|
55
|
+
const { entry, problem } = readMemoryFile(join(dir, file))
|
|
56
|
+
if (!entry) {
|
|
57
|
+
issues.push({
|
|
58
|
+
kind: 'invisible',
|
|
59
|
+
subject: file,
|
|
60
|
+
detail: PROBLEM_TEXT[problem ?? 'unreadable']!,
|
|
61
|
+
})
|
|
62
|
+
continue
|
|
63
|
+
}
|
|
64
|
+
byName.set(entry.name, [...(byName.get(entry.name) ?? []), file])
|
|
65
|
+
// 用加载器自己的取链接规则(含 10 条硬上限),否则医生会报出系统根本不认的边。
|
|
66
|
+
for (const target of extractWikilinks(entry.content)) {
|
|
67
|
+
linkSources.set(target, [...(linkSources.get(target) ?? []), file])
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
for (const [name, owners] of byName) {
|
|
72
|
+
if (owners.length > 1) {
|
|
73
|
+
issues.push({ kind: 'duplicate-name', subject: name, detail: owners.join(', ') })
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
for (const [target, sources] of linkSources) {
|
|
78
|
+
if (!byName.has(target)) {
|
|
79
|
+
issues.push({ kind: 'broken-link', subject: target, detail: sources.join(', ') })
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
let indexRaw: string | null = null
|
|
84
|
+
try {
|
|
85
|
+
indexRaw = readFileSync(join(dir, INDEX_FILE), 'utf-8')
|
|
86
|
+
} catch {
|
|
87
|
+
indexRaw = null
|
|
88
|
+
}
|
|
89
|
+
const listed = new Set<string>()
|
|
90
|
+
if (indexRaw) {
|
|
91
|
+
for (const match of indexRaw.matchAll(/^- \[([^\]]+)\]\(/gm)) listed.add(match[1]!)
|
|
92
|
+
}
|
|
93
|
+
for (const name of byName.keys()) {
|
|
94
|
+
if (!listed.has(name)) {
|
|
95
|
+
issues.push({ kind: 'index-drift', subject: name, detail: 'missing from MEMORY.md' })
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
for (const name of listed) {
|
|
99
|
+
if (!byName.has(name)) {
|
|
100
|
+
issues.push({ kind: 'index-drift', subject: name, detail: 'stale — no such memory' })
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return issues
|
|
105
|
+
}
|
|
@@ -39,6 +39,78 @@ const CONSOLIDATE_THRESHOLD = 0.5
|
|
|
39
39
|
/** 写时去重的 TF-IDF 余弦阈值(> 此值视为近重复,合并而非新增)。高于合并阈值,只拦近重复。 */
|
|
40
40
|
const DEDUP_THRESHOLD = 0.65
|
|
41
41
|
|
|
42
|
+
/**
|
|
43
|
+
* 读出 `[[wikilink]]` 目标(硬上限 10 条)。
|
|
44
|
+
*
|
|
45
|
+
* 模块级而非 MemoryManager 私有方法:`/memory doctor` 必须用**同一把尺子**
|
|
46
|
+
* 才能报出「系统真会当作链接的东西」。
|
|
47
|
+
*/
|
|
48
|
+
export function extractWikilinks(content: string): string[] {
|
|
49
|
+
const re = /\[\[([^\]]+)\]\]/g
|
|
50
|
+
const links: string[] = []
|
|
51
|
+
let match: RegExpExecArray | null
|
|
52
|
+
while ((match = re.exec(content)) !== null) {
|
|
53
|
+
if (links.length >= 10) break // hard cap
|
|
54
|
+
links.push(match[1]!)
|
|
55
|
+
}
|
|
56
|
+
return links
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* 一个记忆文件被读出来的结果。
|
|
61
|
+
*
|
|
62
|
+
* `entry === null` 时 `problem` 说明**为什么**——这正是 `loadAll` 从前的
|
|
63
|
+
* `catch {}` 与 `return null` 吞掉的那部分:文件还在盘上,召回却永远见不到它。
|
|
64
|
+
*/
|
|
65
|
+
export type MemoryFileProblem = 'no-frontmatter' | 'no-name' | 'unreadable'
|
|
66
|
+
|
|
67
|
+
export interface MemoryFileRead {
|
|
68
|
+
filePath: string
|
|
69
|
+
entry: MemoryEntry | null
|
|
70
|
+
problem: MemoryFileProblem | null
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* 读一个记忆文件。**加载与体检共用这一条路径**——各写一份解析规则,就会
|
|
75
|
+
* 出现「体检说没事、加载却读不进来」的分歧,而医生报告的可信度全靠它。
|
|
76
|
+
*/
|
|
77
|
+
export function readMemoryFile(filePath: string): MemoryFileRead {
|
|
78
|
+
try {
|
|
79
|
+
const raw = readFileSync(filePath, 'utf-8')
|
|
80
|
+
const match = raw.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/)
|
|
81
|
+
if (!match) return { filePath, entry: null, problem: 'no-frontmatter' }
|
|
82
|
+
|
|
83
|
+
const frontmatter = match[1] || ''
|
|
84
|
+
const content = (match[2] || '').trim()
|
|
85
|
+
|
|
86
|
+
// Parse simple YAML-like frontmatter
|
|
87
|
+
const nameMatch = frontmatter.match(/name:\s*(\S+)/)
|
|
88
|
+
const descMatch = frontmatter.match(/description:\s*(.+)/)
|
|
89
|
+
const typeMatch = frontmatter.match(/type:\s*(\S+)/)
|
|
90
|
+
const relevanceMatch = frontmatter.match(/relevance:\s*\[(.+)\]/)
|
|
91
|
+
|
|
92
|
+
if (!nameMatch) return { filePath, entry: null, problem: 'no-name' }
|
|
93
|
+
|
|
94
|
+
return {
|
|
95
|
+
filePath,
|
|
96
|
+
problem: null,
|
|
97
|
+
entry: {
|
|
98
|
+
name: nameMatch[1]!,
|
|
99
|
+
description: descMatch?.[1]?.trim() || '',
|
|
100
|
+
metadata: {
|
|
101
|
+
type: (typeMatch?.[1] as MemoryMetadata['type']) || 'reference',
|
|
102
|
+
relevance: relevanceMatch?.[1]?.split(',').map((s) => s.trim()) || [],
|
|
103
|
+
},
|
|
104
|
+
content,
|
|
105
|
+
filePath,
|
|
106
|
+
updatedAt: statSync(filePath).mtime,
|
|
107
|
+
},
|
|
108
|
+
}
|
|
109
|
+
} catch {
|
|
110
|
+
return { filePath, entry: null, problem: 'unreadable' }
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
42
114
|
/** 确定性 hash(无 Date.now / Math.random,同输入同输出 → 幂等 lesson 名)。 */
|
|
43
115
|
function stableHash(s: string): string {
|
|
44
116
|
let h = 0
|
|
@@ -93,16 +165,8 @@ export class MemoryManager {
|
|
|
93
165
|
|
|
94
166
|
for (const entry of entries) {
|
|
95
167
|
if (entry === INDEX_FILE || entry === LINKS_FILE || extname(entry) !== '.md') continue
|
|
96
|
-
const
|
|
97
|
-
|
|
98
|
-
const raw = readFileSync(filePath, 'utf-8')
|
|
99
|
-
const parsed = this.parseMemoryFile(raw, filePath)
|
|
100
|
-
if (parsed) {
|
|
101
|
-
this.memories.set(parsed.name, parsed)
|
|
102
|
-
}
|
|
103
|
-
} catch {
|
|
104
|
-
// skip unparseable
|
|
105
|
-
}
|
|
168
|
+
const { entry: parsed } = readMemoryFile(join(this.memoryDir, entry))
|
|
169
|
+
if (parsed) this.memories.set(parsed.name, parsed)
|
|
106
170
|
}
|
|
107
171
|
|
|
108
172
|
// Try cached link graph first, fall back to rebuild
|
|
@@ -480,23 +544,12 @@ export class MemoryManager {
|
|
|
480
544
|
atomicWriteFileSync(join(this.memoryDir, INDEX_FILE), lines.join('\n') + '\n', { mode: 0o644 })
|
|
481
545
|
}
|
|
482
546
|
|
|
483
|
-
private extractWikilinks(content: string): string[] {
|
|
484
|
-
const re = /\[\[([^\]]+)\]\]/g
|
|
485
|
-
const links: string[] = []
|
|
486
|
-
let match: RegExpExecArray | null
|
|
487
|
-
while ((match = re.exec(content)) !== null) {
|
|
488
|
-
if (links.length >= 10) break // hard cap
|
|
489
|
-
links.push(match[1]!)
|
|
490
|
-
}
|
|
491
|
-
return links
|
|
492
|
-
}
|
|
493
|
-
|
|
494
547
|
private updateWikilinks(name: string, content: string): void {
|
|
495
548
|
// Clear stale outbound links for this memory
|
|
496
549
|
this.linkGraph.delete(name)
|
|
497
550
|
|
|
498
551
|
// Extract outbound wikilinks from content
|
|
499
|
-
const links =
|
|
552
|
+
const links = extractWikilinks(content)
|
|
500
553
|
if (links.length > 0) {
|
|
501
554
|
this.linkGraph.set(name, new Set(links))
|
|
502
555
|
}
|
|
@@ -504,7 +557,7 @@ export class MemoryManager {
|
|
|
504
557
|
// Update reverse links: other memories that link to this one
|
|
505
558
|
for (const [otherName, otherEntry] of this.memories) {
|
|
506
559
|
if (otherName === name) continue
|
|
507
|
-
const otherLinks =
|
|
560
|
+
const otherLinks = extractWikilinks(otherEntry.content)
|
|
508
561
|
if (otherLinks.includes(name)) {
|
|
509
562
|
const otherSet = this.linkGraph.get(otherName) || new Set()
|
|
510
563
|
otherSet.add(name)
|
|
@@ -518,14 +571,14 @@ export class MemoryManager {
|
|
|
518
571
|
private rebuildLinkGraph(): void {
|
|
519
572
|
this.linkGraph.clear()
|
|
520
573
|
for (const [name, entry] of this.memories) {
|
|
521
|
-
const links =
|
|
574
|
+
const links = extractWikilinks(entry.content)
|
|
522
575
|
if (links.length > 0) {
|
|
523
576
|
this.linkGraph.set(name, new Set(links))
|
|
524
577
|
}
|
|
525
578
|
}
|
|
526
579
|
// Compute reverse links: other memories that link to each memory
|
|
527
580
|
for (const [name, entry] of this.memories) {
|
|
528
|
-
const linked =
|
|
581
|
+
const linked = extractWikilinks(entry.content)
|
|
529
582
|
for (const target of linked) {
|
|
530
583
|
if (target === name) continue
|
|
531
584
|
const targetSet = this.linkGraph.get(target)
|
|
@@ -616,34 +669,6 @@ export class MemoryManager {
|
|
|
616
669
|
}
|
|
617
670
|
}
|
|
618
671
|
|
|
619
|
-
private parseMemoryFile(raw: string, filePath: string): MemoryEntry | null {
|
|
620
|
-
const match = raw.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/)
|
|
621
|
-
if (!match) return null
|
|
622
|
-
|
|
623
|
-
const frontmatter = match[1] || ''
|
|
624
|
-
const content = (match[2] || '').trim()
|
|
625
|
-
|
|
626
|
-
// Parse simple YAML-like frontmatter
|
|
627
|
-
const nameMatch = frontmatter.match(/name:\s*(\S+)/)
|
|
628
|
-
const descMatch = frontmatter.match(/description:\s*(.+)/)
|
|
629
|
-
const typeMatch = frontmatter.match(/type:\s*(\S+)/)
|
|
630
|
-
const relevanceMatch = frontmatter.match(/relevance:\s*\[(.+)\]/)
|
|
631
|
-
|
|
632
|
-
if (!nameMatch) return null
|
|
633
|
-
|
|
634
|
-
return {
|
|
635
|
-
name: nameMatch[1]!,
|
|
636
|
-
description: descMatch?.[1]?.trim() || '',
|
|
637
|
-
metadata: {
|
|
638
|
-
type: (typeMatch?.[1] as MemoryMetadata['type']) || 'reference',
|
|
639
|
-
relevance: relevanceMatch?.[1]?.split(',').map((s) => s.trim()) || [],
|
|
640
|
-
},
|
|
641
|
-
content,
|
|
642
|
-
filePath,
|
|
643
|
-
updatedAt: statSync(filePath).mtime,
|
|
644
|
-
}
|
|
645
|
-
}
|
|
646
|
-
|
|
647
672
|
private formatMemoryFile(name: string, metadata: MemoryMetadata, content: string): string {
|
|
648
673
|
const body = this.formatMemoryBody(metadata, content)
|
|
649
674
|
return `---
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import type { HookContext, HookDefinition, HookResult } from '../shared/index'
|
|
2
|
+
import type { HookEngine } from './hooks'
|
|
3
|
+
import { splitShellSegments } from './permission-rules'
|
|
4
|
+
import { shellWords } from '../tools/exec/bash'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The merge gate: a review must run in this session before a pull request is
|
|
8
|
+
* merged.
|
|
9
|
+
*
|
|
10
|
+
* `instructions.ts` has carried this rule as prose ("Code-Review Merge Gate")
|
|
11
|
+
* since the CRSI work, and prose is exactly what failed: a session opened its
|
|
12
|
+
* own PR and squash-merged it without a review, because nothing had an
|
|
13
|
+
* implementation point. This module is that point — a PreToolUse guard on
|
|
14
|
+
* `gh pr merge`, with the review recorded by the tool funnel itself.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
/** How long a review counts for the session that ran it. */
|
|
18
|
+
export const REVIEW_WINDOW_MS = 24 * 60 * 60 * 1000
|
|
19
|
+
|
|
20
|
+
/** The operator's one-way out: an unchanged env is the only way to waive the gate. */
|
|
21
|
+
export const MERGE_GATE_WAIVER_ENV = 'MIPHAM_SKIP_MERGE_GATE'
|
|
22
|
+
|
|
23
|
+
/** Skills whose successful run counts as a review of what is about to merge. */
|
|
24
|
+
export const REVIEW_SKILLS = new Set(['code-review', 'self-review', 'security-review'])
|
|
25
|
+
|
|
26
|
+
/** `NAME=value` ahead of a command — assigned to that command, not a command word. */
|
|
27
|
+
const LEADING_ASSIGNMENT_RE = /^[A-Za-z_][A-Za-z0-9_]*=/
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Commands that run another command in turn. `sudo gh pr merge` merges just as
|
|
31
|
+
* much as the bare form, and the guard has to see through the wrapper.
|
|
32
|
+
*/
|
|
33
|
+
const COMMAND_WRAPPERS = new Set([
|
|
34
|
+
'sudo',
|
|
35
|
+
'doas',
|
|
36
|
+
'env',
|
|
37
|
+
'command',
|
|
38
|
+
'builtin',
|
|
39
|
+
'exec',
|
|
40
|
+
'nohup',
|
|
41
|
+
'nice',
|
|
42
|
+
'time',
|
|
43
|
+
])
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Does this Bash command run `gh pr merge`?
|
|
47
|
+
*
|
|
48
|
+
* Quote-aware on purpose: `git commit -m "gh pr merge 55"` and
|
|
49
|
+
* `echo "gh pr merge"` mention the command without running it. Segments are
|
|
50
|
+
* split with the permission matcher's splitter (which ignores quoting), so a
|
|
51
|
+
* quoted `&&` can still split a segment — the resulting over-match is the safe
|
|
52
|
+
* direction, same trade the matcher makes.
|
|
53
|
+
*/
|
|
54
|
+
export function isPrMergeCommand(command: string): boolean {
|
|
55
|
+
for (const segment of splitShellSegments(command)) {
|
|
56
|
+
const words = shellWords(segment)
|
|
57
|
+
let i = 0
|
|
58
|
+
while (
|
|
59
|
+
i < words.length &&
|
|
60
|
+
(LEADING_ASSIGNMENT_RE.test(words[i]!) ||
|
|
61
|
+
COMMAND_WRAPPERS.has(words[i]!) ||
|
|
62
|
+
words[i]!.startsWith('-'))
|
|
63
|
+
) {
|
|
64
|
+
i++
|
|
65
|
+
}
|
|
66
|
+
if (words[i] !== 'gh') continue
|
|
67
|
+
// `gh` takes global flags before the subcommand (`gh -R owner/repo pr …`),
|
|
68
|
+
// so the subcommand is found by its own name rather than by position.
|
|
69
|
+
const args = words.slice(i + 1)
|
|
70
|
+
const at = args.findIndex((word, n) => word === 'pr' && args[n + 1] === 'merge')
|
|
71
|
+
if (at === -1) continue
|
|
72
|
+
const rest = args.slice(at + 2)
|
|
73
|
+
// `--help` prints usage; it does not merge anything.
|
|
74
|
+
if (rest.includes('--help') || rest.includes('-h')) continue
|
|
75
|
+
return true
|
|
76
|
+
}
|
|
77
|
+
return false
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Which sessions have run a review, and when.
|
|
82
|
+
*
|
|
83
|
+
* Time-bounded rather than cleared on session end: the daemon serves many
|
|
84
|
+
* sessions from one process and has no per-session teardown hook here, so an
|
|
85
|
+
* entry is dropped by age instead. A review is a fact about the last day, not
|
|
86
|
+
* a flag that must be reset.
|
|
87
|
+
*/
|
|
88
|
+
export class ReviewLedger {
|
|
89
|
+
private reviewed = new Map<string, number>()
|
|
90
|
+
|
|
91
|
+
markReviewed(sessionId: string, at: number = Date.now()): void {
|
|
92
|
+
this.prune(at)
|
|
93
|
+
this.reviewed.set(sessionId, at)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
hasReviewed(sessionId: string, now: number = Date.now()): boolean {
|
|
97
|
+
const at = this.reviewed.get(sessionId)
|
|
98
|
+
return at !== undefined && now - at <= REVIEW_WINDOW_MS
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
private prune(now: number): void {
|
|
102
|
+
for (const [sessionId, at] of this.reviewed) {
|
|
103
|
+
if (now - at > REVIEW_WINDOW_MS) this.reviewed.delete(sessionId)
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Record a tool outcome for the gate — called from the engine's tool funnel.
|
|
110
|
+
*
|
|
111
|
+
* Only a *successful* review skill counts: a skill that was not found, or whose
|
|
112
|
+
* run failed, reviewed nothing.
|
|
113
|
+
*/
|
|
114
|
+
export function noteToolOutcome(
|
|
115
|
+
ledger: ReviewLedger,
|
|
116
|
+
sessionId: string,
|
|
117
|
+
toolName: string,
|
|
118
|
+
input: Record<string, unknown>,
|
|
119
|
+
success: boolean,
|
|
120
|
+
): void {
|
|
121
|
+
if (!success || toolName !== 'Skill') return
|
|
122
|
+
const skill = input.skill
|
|
123
|
+
if (typeof skill === 'string' && REVIEW_SKILLS.has(skill)) ledger.markReviewed(sessionId)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function createMergeGateHook(ledger: ReviewLedger): HookDefinition {
|
|
127
|
+
return {
|
|
128
|
+
event: 'PreToolUse',
|
|
129
|
+
toolName: 'Bash',
|
|
130
|
+
source: 'builtin:merge-gate',
|
|
131
|
+
// A guard that cannot run must not silently allow the merge.
|
|
132
|
+
failureMode: 'closed',
|
|
133
|
+
async handler(ctx: HookContext): Promise<HookResult> {
|
|
134
|
+
const command = ctx.toolInput?.command
|
|
135
|
+
if (typeof command !== 'string' || !isPrMergeCommand(command)) return { allowed: true }
|
|
136
|
+
if (process.env[MERGE_GATE_WAIVER_ENV] === '1') return { allowed: true }
|
|
137
|
+
if (ledger.hasReviewed(ctx.sessionId)) return { allowed: true }
|
|
138
|
+
return {
|
|
139
|
+
allowed: false,
|
|
140
|
+
reason:
|
|
141
|
+
'This command merges a pull request, and no code review has run in this session. ' +
|
|
142
|
+
'Run /code-review (or the code-review skill) and address its findings before merging. ' +
|
|
143
|
+
`If the review genuinely happened outside this session, restart Mipham Code with ${MERGE_GATE_WAIVER_ENV}=1.`,
|
|
144
|
+
}
|
|
145
|
+
},
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Process-wide ledger — the engine records into it, the gate reads it. */
|
|
150
|
+
export const reviewLedger = new ReviewLedger()
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Install the built-in guards. Both startup paths must call this — the one-shot
|
|
154
|
+
* CLI and the daemon — or the gate exists in only one of them.
|
|
155
|
+
*/
|
|
156
|
+
export function registerBuiltinHooks(engine: HookEngine): void {
|
|
157
|
+
engine.register(createMergeGateHook(reviewLedger))
|
|
158
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 出处判定:「这个数是你量出来的,还是你推出来的?」
|
|
3
|
+
*
|
|
4
|
+
* 只判一种主张 —— **带计数单位的数量**(`4,572 测试` / `343 files` / `1,834 个字符`)。
|
|
5
|
+
* 版本号、端口、日期、行号都不是计数,代码里的数字是在引用而不是在下结论。
|
|
6
|
+
*
|
|
7
|
+
* 出处的定义刻意收窄到**本轮的工具结果**(与用户这句话):模型自己前一轮写下的数
|
|
8
|
+
* 不算出处 —— 那正是「先猜一个、再当事实复述」的形态,也是这条纪律要拦的东西。
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
export interface CountClaim {
|
|
12
|
+
/** 去掉千分位后的数字 —— 判定身份用这个 */
|
|
13
|
+
digits: string
|
|
14
|
+
/** 原文片段(数字 + 单位),好让提示语点名质疑的是哪一处 */
|
|
15
|
+
context: string
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** 计数单位。长的写在前面:正则按顺序试,`字符` 先于 `字` 才能整词匹配。 */
|
|
19
|
+
const UNITS = [
|
|
20
|
+
'行代码',
|
|
21
|
+
'字符',
|
|
22
|
+
'字节',
|
|
23
|
+
'文件',
|
|
24
|
+
'测试',
|
|
25
|
+
'用例',
|
|
26
|
+
'提交',
|
|
27
|
+
'端口',
|
|
28
|
+
'characters',
|
|
29
|
+
'character',
|
|
30
|
+
'chars',
|
|
31
|
+
'char',
|
|
32
|
+
'bytes',
|
|
33
|
+
'tokens',
|
|
34
|
+
'commits',
|
|
35
|
+
'entries',
|
|
36
|
+
'entry',
|
|
37
|
+
'lines',
|
|
38
|
+
'line',
|
|
39
|
+
'tests',
|
|
40
|
+
'test',
|
|
41
|
+
'cases',
|
|
42
|
+
'case',
|
|
43
|
+
'files',
|
|
44
|
+
'file',
|
|
45
|
+
'items',
|
|
46
|
+
'item',
|
|
47
|
+
'passes',
|
|
48
|
+
'pass',
|
|
49
|
+
'runs',
|
|
50
|
+
'run',
|
|
51
|
+
'个',
|
|
52
|
+
'条',
|
|
53
|
+
'笔',
|
|
54
|
+
'次',
|
|
55
|
+
'行',
|
|
56
|
+
'处',
|
|
57
|
+
'项',
|
|
58
|
+
'种',
|
|
59
|
+
'轮',
|
|
60
|
+
'份',
|
|
61
|
+
'张',
|
|
62
|
+
'位',
|
|
63
|
+
'家',
|
|
64
|
+
'字',
|
|
65
|
+
]
|
|
66
|
+
|
|
67
|
+
const UNIT_ALT = UNITS.join('|')
|
|
68
|
+
/** 3 位以上(`343`)或带千分位(`4,572`)—— 一两位的数字太容易是序号而非计数。 */
|
|
69
|
+
const NUMBER = '(\\d{1,3}(?:,\\d{3})+|\\d{3,})'
|
|
70
|
+
const CLAIM_RE = new RegExp(`${NUMBER}\\s*(?:${UNIT_ALT})(?![a-z])`, 'gi')
|
|
71
|
+
|
|
72
|
+
/** 代码块与行内代码里的数字是在引用,不是在下结论。 */
|
|
73
|
+
function stripCode(text: string): string {
|
|
74
|
+
return text.replace(/```[\s\S]*?```/g, ' ').replace(/`[^`\n]*`/g, ' ')
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function normalize(digits: string): string {
|
|
78
|
+
return digits.replace(/,/g, '')
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* 从回复里挑出「没有出处」的计数主张。
|
|
83
|
+
*
|
|
84
|
+
* @param reply 本轮最终回复(模型自己的话)
|
|
85
|
+
* @param evidence 本轮的工具结果 + 用户这句话
|
|
86
|
+
*/
|
|
87
|
+
export function unprovenCountClaims(reply: string, evidence: string): CountClaim[] {
|
|
88
|
+
const prose = stripCode(reply)
|
|
89
|
+
const haystack = evidence.replace(/,/g, '')
|
|
90
|
+
const seen = new Set<string>()
|
|
91
|
+
const claims: CountClaim[] = []
|
|
92
|
+
|
|
93
|
+
for (const match of prose.matchAll(CLAIM_RE)) {
|
|
94
|
+
const digits = normalize(match[1]!)
|
|
95
|
+
if (digits.length < 3) continue
|
|
96
|
+
// 「第 1234 行」是位置不是数量 —— 它指的是哪一行,不是有多少行。
|
|
97
|
+
const before = prose.slice(0, match.index).trimEnd()
|
|
98
|
+
if (before.endsWith('第')) continue
|
|
99
|
+
if (seen.has(digits)) continue
|
|
100
|
+
if (new RegExp(`(?<!\\d)${digits}(?!\\d)`).test(haystack)) continue
|
|
101
|
+
seen.add(digits)
|
|
102
|
+
claims.push({ digits, context: match[0].trim() })
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
return claims
|
|
106
|
+
}
|