focus-guard 3.0.7 → 3.4.0
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/LICENSE +683 -21
- package/NOTICE +25 -0
- package/README.md +14 -9
- package/README.zh-CN.md +12 -9
- package/docs/AB-PROMPTS.md +123 -0
- package/docs/AB-SESSION.md +161 -0
- package/docs/ARCH-MAP.md +148 -0
- package/docs/BENCH-BASELINE.json +95 -0
- package/docs/BENCH.md +323 -0
- package/docs/GATE-INPUTS.json +10 -0
- package/docs/HANDOFF-2026-10-27.md +736 -0
- package/docs/HOOK-ORDERING.md +139 -0
- package/docs/LEGISLATION-LAW.md +4 -2
- package/docs/MCP-4.0-PLAN.md +184 -0
- package/docs/MEMORY-4.5-PLAN.md +415 -0
- package/docs/PROFILE-TUNING.md +147 -0
- package/docs/RATCHET.json +48 -0
- package/docs/RELEASE-POLICY.md +163 -0
- package/docs/RULES.md +95 -14
- package/docs/THREAT-MODEL.md +68 -0
- package/docs/TOOL-SCHEMA.json +6 -0
- package/docs/VERSION-PLAN.md +532 -0
- package/docs/WRITING-STYLE.md +109 -0
- package/docs/architecture-map.mermaid +186 -0
- package/docs/deepseek-pricing-audit.md +2 -0
- package/hooks/guard.mjs +92 -56
- package/package.json +34 -5
- package/skills/focus-thinking/SKILL.md +9 -7
- package/src/adapters/dsh/eligibility-gate.mjs +446 -23
- package/src/adapters/dsh/tool-kinds.mjs +81 -0
- package/src/core/approval.mjs +2 -8
- package/src/core/approvals.mjs +208 -0
- package/src/core/audit-writer.mjs +297 -0
- package/src/core/audit.mjs +46 -16
- package/src/core/backup.mjs +37 -11
- package/src/core/checkEligibility.mjs +7 -4
- package/src/core/constants.mjs +67 -22
- package/src/core/decisionEngine.mjs +12 -0
- package/src/core/env.mjs +147 -19
- package/src/core/grants.mjs +54 -13
- package/src/core/kpi.mjs +16 -0
- package/src/core/outputGate.mjs +77 -0
- package/src/core/patterns.mjs +129 -0
- package/src/core/prefixStability.mjs +143 -0
- package/src/core/profileLoader.mjs +40 -5
- package/src/core/progressPolicy.mjs +65 -0
- package/src/core/redlines.mjs +49 -5
- package/src/core/risk.mjs +94 -15
- package/src/core/schemaDrift.mjs +125 -0
- package/src/core/sessionScratch.mjs +147 -0
- package/src/core/stageGraph.mjs +104 -0
- package/src/core/staleCleanup.mjs +153 -0
- package/src/core/state.mjs +215 -81
- package/src/core/stopPolicy.mjs +97 -0
- package/src/core/tempPath.mjs +23 -0
- package/src/dsh/audit.mjs +168 -118
- package/src/dsh/compactionWatch/announce.mjs +117 -0
- package/src/dsh/compactionWatch.mjs +68 -153
- package/src/dsh/guard/authz.mjs +97 -0
- package/src/dsh/guard/evidence.mjs +308 -0
- package/src/dsh/guard/hardCheck.mjs +85 -0
- package/src/dsh/guard/redline.mjs +62 -0
- package/src/dsh/guard/risk.mjs +196 -0
- package/src/dsh/guard/runtime.mjs +162 -0
- package/src/dsh/guard/superpowers.mjs +70 -0
- package/src/dsh/guard/tooling.mjs +177 -0
- package/src/dsh/guard/volume.mjs +181 -0
- package/src/dsh/guard/wholeFile.mjs +109 -0
- package/src/dsh/heartbeat.mjs +76 -13
- package/src/dsh/hookOrder.mjs +101 -0
- package/src/dsh/index.js +247 -15
- package/src/dsh/pipeline.mjs +77 -854
- package/src/dsh/policy-audit.mjs +84 -0
- package/src/dsh/postProgress.mjs +400 -274
- package/src/dsh/preGuard.mjs +249 -228
- package/src/dsh/repeatGuard.mjs +98 -0
- package/src/dsh/seams/pre-step.mjs +186 -0
- package/src/dsh/seams/prompt-rules.mjs +59 -0
- package/src/dsh/seams/session-start.mjs +297 -0
- package/src/dsh/seams/shared.mjs +109 -0
- package/src/dsh/seams.mjs +95 -408
- package/src/dsh/search-hints.mjs +136 -0
- package/src/dsh/sessionScope.mjs +28 -0
- package/src/dsh/status.mjs +7 -0
- package/src/dsh/stopGuard.mjs +225 -164
- package/src/dsh/testRuntime.mjs +62 -0
- package/src/dsh/toolKindAudit.mjs +66 -0
- package/src/dsh/tools.mjs +81 -5
- package/src/dsh/traceMeta.mjs +125 -0
- package/src/dsh/value-gate.mjs +93 -0
- package/src/dsh/workspace.mjs +3 -143
- package/src/memory/index.mjs +15 -0
- package/src/memory/tags.mjs +30 -0
- package/src/memory/workspace.mjs +283 -0
- package/src/peak-cost.mjs +1 -1
- package/src/profiles/deepseek-flash.mjs +7 -1
- package/src/profiles/deepseek-pro.mjs +6 -1
- package/src/profiles/default.mjs +6 -1
- package/src/profiles/glm.mjs +6 -1
- package/src/profiles/gpt-astra.mjs +6 -1
- package/tools/bench-ab.mjs +240 -0
- package/tools/bench-cost.mjs +176 -0
- package/tools/brain-cosmic.mjs +43 -0
- package/tools/brain-view.html +853 -0
- package/tools/brain.mjs +317 -0
- package/tools/capture-fixtures.mjs +182 -0
- package/tools/case-audit.mjs +114 -0
- package/tools/collect-panel.mjs +218 -0
- package/tools/dead-export.mjs +60 -0
- package/tools/docs-lint.mjs +82 -0
- package/tools/env-fingerprint.mjs +126 -33
- package/tools/first-run-sweep.mjs +123 -0
- package/tools/focusguard.mjs +155 -0
- package/tools/gate-audit.mjs +140 -0
- package/tools/gate-inputs.mjs +115 -0
- package/tools/handoff.mjs +56 -0
- package/tools/health.mjs +182 -0
- package/tools/knowledge.mjs +118 -0
- package/tools/layering-audit.mjs +105 -0
- package/tools/lib/book-style.mjs +136 -0
- package/tools/lib/brain-core.mjs +342 -0
- package/tools/lib/brain-docs.mjs +293 -0
- package/tools/lib/brain-regions.mjs +169 -0
- package/tools/lib/brain-relate.mjs +235 -0
- package/tools/lib/brain-text.mjs +121 -0
- package/tools/lib/case-tool.mjs +186 -0
- package/tools/lib/docs-core.mjs +392 -0
- package/tools/lib/docs-version.mjs +66 -0
- package/tools/lib/envMap.mjs +31 -0
- package/tools/lib/health-core.mjs +94 -0
- package/tools/lib/import-graph.mjs +118 -0
- package/tools/lib/index-io.mjs +70 -0
- package/tools/lib/open.mjs +32 -0
- package/tools/lib/prefix-cost.mjs +143 -0
- package/tools/lib/ratchet.mjs +174 -0
- package/tools/lib/reach.mjs +28 -0
- package/tools/lib/sessionDump.mjs +80 -0
- package/tools/lib/source-text.mjs +112 -0
- package/tools/library-book.mjs +313 -0
- package/tools/library-build.mjs +50 -12
- package/tools/library-index.mjs +91 -0
- package/tools/lint.mjs +282 -0
- package/tools/log-audit.mjs +108 -0
- package/tools/manifest-sync.mjs +111 -0
- package/tools/memory-audit.mjs +67 -0
- package/tools/module-audit.mjs +56 -0
- package/tools/mutate.mjs +316 -0
- package/tools/prefix-audit.mjs +122 -0
- package/tools/prefix-drift.mjs +325 -0
- package/tools/privacy-guard.mjs +352 -0
- package/tools/quality-audit.mjs +166 -0
- package/tools/schema-fingerprint.mjs +191 -0
- package/{src/dsh → tools}/selftest.mjs +75 -22
- package/tools/smells.mjs +398 -0
- package/tools/verify-case-paths.mjs +93 -0
- package/tools/version.mjs +191 -0
- package/docs/MASTER-PLAN-2.0.0.md +0 -133
- package/docs/MASTER-PLAN-3.0.0.md +0 -76
- package/src/adapters/dsh/fg-appeal-tool.mjs +0 -47
- package/src/adapters/dsh/fg-apply-tool.mjs +0 -68
- /package/{src/adapters/dsh → hooks}/protocol.mjs +0 -0
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* 前缀抖动探针(2026-10-29)
|
|
4
|
+
*
|
|
5
|
+
* 目的:回答"每步的前缀到底是不是同一段字节"。缓存命中要求**前缀逐字节相同**,
|
|
6
|
+
* 而 FG 自己往系统提示里注入卷宗段(决策 / 约束)——若它每回合变一次,
|
|
7
|
+
* 后面整段会话历史都要按未缓存价重付。
|
|
8
|
+
*
|
|
9
|
+
* 本探针只读会话落盘(`session.v4.jsonl.zstd`),按 step 切段,逐段比哈希:
|
|
10
|
+
* · 工具表 / system 段 / developer 段 / 首个 user 段,各自一个指纹
|
|
11
|
+
* · 报"有几个不同版本"与"第一次分歧出现在哪个字段、哪个字符位"
|
|
12
|
+
*
|
|
13
|
+
* 用法:node packages/core/tools/prefix-drift.mjs [--sid <片段>] [--json] [--top 3]
|
|
14
|
+
* --strict 工具表 / 首条 user 段出现多版本即 exit 1(这两段 FG 完全可控、实测恒定)
|
|
15
|
+
* --fail-on-system 连 system 段多版本也算红(默认只报不拦:熔断告知、换会话交接都会合法地变一次)
|
|
16
|
+
* --ab 不读会话落盘,改跑 A/B 重放:同一串输入(30 回合 + 并发会话改写快照)
|
|
17
|
+
* 分别喂给"每回合重渲染"与"首步冻结"两套规则,报版本数 / 断点 / 稳定率
|
|
18
|
+
* --cost 读会话落盘,算"改前 vs 改后"的 token 与费用(est4 口径,非账单)
|
|
19
|
+
* 可配 --panel <file>(默认 panel-runs.json)把 est4 与面板实测对账
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import { basename, dirname, join } from 'node:path'
|
|
23
|
+
import { createHash } from 'node:crypto'
|
|
24
|
+
import { mkdtempSync, rmSync } from 'node:fs'
|
|
25
|
+
import { tmpdir } from 'node:os'
|
|
26
|
+
import { decodeSession, firstDiff, textOfMessage, walkSessionFiles } from './lib/sessionDump.mjs'
|
|
27
|
+
import { attachPanel, runCost } from './lib/prefix-cost.mjs'
|
|
28
|
+
|
|
29
|
+
const SESSIONS = process.env.FG_SESSIONS_DIR || 'E:/DSH/.dsh/sessions'
|
|
30
|
+
const argv = process.argv.slice(2)
|
|
31
|
+
const arg = (k, d = null) => (argv.includes(k) ? argv[argv.indexOf(k) + 1] : d)
|
|
32
|
+
const SID = arg('--sid')
|
|
33
|
+
const AS_JSON = argv.includes('--json')
|
|
34
|
+
const TOP = Number(arg('--top', 3)) || 3
|
|
35
|
+
const STRICT = argv.includes('--strict')
|
|
36
|
+
const FAIL_ON_SYSTEM = argv.includes('--fail-on-system')
|
|
37
|
+
const AB = argv.includes('--ab')
|
|
38
|
+
const COST = argv.includes('--cost')
|
|
39
|
+
|
|
40
|
+
if (COST) {
|
|
41
|
+
const rows = runCost({ sessionsDir: SESSIONS })
|
|
42
|
+
if (!rows.length) {
|
|
43
|
+
console.log('找不到 ≥5 步的会话', SID || '(最近 8 个)')
|
|
44
|
+
process.exit(0)
|
|
45
|
+
}
|
|
46
|
+
// 面板实测对账(2026-10-29):est4 只是估算,真实 token 与命中率在宿主面板;
|
|
47
|
+
// 面板基线(panel-runs.json,collect-panel.mjs 产出)带 session id,能按 sid 匹配时给校准系数。
|
|
48
|
+
// 2026-10-30:attachPanel 现在返回诊断(panelRows / panelLatest / rowsScanned / error),
|
|
49
|
+
// 匹配不上时能说清原因,而不是只丢一句"无可匹配"。
|
|
50
|
+
const diag = attachPanel(rows, arg('--panel', 'panel-runs.json'))
|
|
51
|
+
const { panelFile, matched } = diag
|
|
52
|
+
|
|
53
|
+
if (AS_JSON) {
|
|
54
|
+
console.log(JSON.stringify({ rows, panel: diag }, null, 2))
|
|
55
|
+
process.exit(0)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const pad = (s, n) => String(s).padStart(n)
|
|
59
|
+
console.log('会话'.padEnd(10) + pad('步', 5) + pad('追加', 6) + pad('总输入tok', 12) + pad('额外tok', 10) + pad('token占比', 10) + pad('改前$', 11) + pad('改后$', 11) + pad('费用省', 9))
|
|
60
|
+
for (const r of rows) {
|
|
61
|
+
console.log(
|
|
62
|
+
r.sid.padEnd(10) +
|
|
63
|
+
pad(r.steps, 5) +
|
|
64
|
+
pad(r.appends, 6) +
|
|
65
|
+
pad(r.totalTok, 12) +
|
|
66
|
+
pad(r.extraTok, 10) +
|
|
67
|
+
pad((((r.extraTok / r.totalTok) * 100).toFixed(2) + '%'), 10) +
|
|
68
|
+
pad('$' + r.beforeTotal.toFixed(6), 11) +
|
|
69
|
+
pad('$' + r.afterTotal.toFixed(6), 11) +
|
|
70
|
+
pad(((((r.beforeTotal - r.afterTotal) / r.beforeTotal) * 100).toFixed(2) + '%'), 9),
|
|
71
|
+
)
|
|
72
|
+
}
|
|
73
|
+
const sum = rows.reduce((a, r) => ({ t: a.t + r.totalTok, e: a.e + r.extraTok, b: a.b + r.beforeTotal, f: a.f + r.afterTotal }), { t: 0, e: 0, b: 0, f: 0 })
|
|
74
|
+
console.log(
|
|
75
|
+
`\n合计:总输入 ${sum.t} tok · 额外 ${sum.e} tok(${((sum.e / sum.t) * 100).toFixed(2)}%)· ` +
|
|
76
|
+
`改前 $${sum.b.toFixed(6)} → 改后 $${sum.f.toFixed(6)}(省 ${(((sum.b - sum.f) / sum.b) * 100).toFixed(2)}%)`,
|
|
77
|
+
)
|
|
78
|
+
console.log(`有追加的会话:${rows.filter((r) => r.appends).length}/${rows.length}`)
|
|
79
|
+
|
|
80
|
+
const withReal = rows.filter((r) => r.real)
|
|
81
|
+
if (withReal.length) {
|
|
82
|
+
console.log(`\n面板实测对账(${panelFile},匹配 ${withReal.length} 条):`)
|
|
83
|
+
console.log('会话'.padEnd(10) + pad('实测total', 12) + pad('缓存读', 11) + pad('实测命中', 10) + pad('实测/est4', 11))
|
|
84
|
+
for (const r of withReal) {
|
|
85
|
+
console.log(
|
|
86
|
+
r.sid.padEnd(10) +
|
|
87
|
+
pad(r.real.total, 12) +
|
|
88
|
+
pad(r.real.cacheRead, 11) +
|
|
89
|
+
pad(((r.real.hit || 0) * 100).toFixed(1) + '%', 10) +
|
|
90
|
+
pad((r.real.factor || 0).toFixed(2) + 'x', 11),
|
|
91
|
+
)
|
|
92
|
+
}
|
|
93
|
+
const tr = withReal.reduce((a, r) => ({ t: a.t + r.real.total, c: a.c + r.real.cacheRead, u: a.u + r.real.uncached }), { t: 0, c: 0, u: 0 })
|
|
94
|
+
console.log(`实测合计:total ${tr.t} · 缓存读 ${tr.c}(命中 ${((tr.c / (tr.t || 1)) * 100).toFixed(1)}%)· 未缓存 ${tr.u}`)
|
|
95
|
+
} else {
|
|
96
|
+
// 说清"为什么没对上",别让人分不清是缺数据还是功能坏了。
|
|
97
|
+
const why = diag.error
|
|
98
|
+
? `读不了(${diag.error})`
|
|
99
|
+
: diag.panelRows === 0
|
|
100
|
+
? '文件为空或不是数组'
|
|
101
|
+
: `共 ${diag.panelRows} 条(最新 ${String(diag.panelLatest || '无日期').slice(0, 10)}),` +
|
|
102
|
+
`本次扫描 ${diag.rowsScanned} 个会话——sid 前 8 位无交集`
|
|
103
|
+
console.log(`\n面板实测:${panelFile} ${why}。`)
|
|
104
|
+
console.log(
|
|
105
|
+
' → 对账**没有发生**,est4 仍只是估算。面板数字只能人工从宿主抄:' +
|
|
106
|
+
'`node packages/core/tools/collect-panel.mjs --init` 生成模板,抄完再跑本命令。',
|
|
107
|
+
)
|
|
108
|
+
}
|
|
109
|
+
console.log('\n口径:est4(字符/4),不是账单;费用按"除这次追加外全部命中"算(面板 99.6% 的场景)。')
|
|
110
|
+
console.log('实测/est4 <1 表示 est4 高估(按字符/4 算多了)、>1 表示低估;面板命中率是真实缓存收益,改前改后对比它比 $ 估更有意义。')
|
|
111
|
+
process.exit(0)
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* A/B 重放(`--ab`):不依赖会话落盘,可复现。
|
|
116
|
+
*
|
|
117
|
+
* 输入是"同一工作区 30 回合、期间另一个并发会话每 3 回合改写一次快照"——
|
|
118
|
+
* 这不是编的场景:`workspace.json` 每工作区一份,并发会话本来就互相覆盖,
|
|
119
|
+
* 实测两个真实会话的卷宗段都是 2 个版本,分歧点就在「上次会话」那一行。
|
|
120
|
+
*/
|
|
121
|
+
async function runAB() {
|
|
122
|
+
const TMP = mkdtempSync(join(tmpdir(), 'fg-prefix-ab-'))
|
|
123
|
+
const savedWs = process.env.FG_WORKSPACE_FILE
|
|
124
|
+
const savedAudit = process.env.FG_AUDIT_FILE
|
|
125
|
+
process.env.FG_WORKSPACE_FILE = join(TMP, 'workspace.json')
|
|
126
|
+
process.env.FG_AUDIT_FILE = join(TMP, 'AUDIT.log')
|
|
127
|
+
const url = new URL('../src/dsh/workspace.mjs', import.meta.url).href
|
|
128
|
+
const ws = await import(url)
|
|
129
|
+
const WORK = join(TMP, 'work')
|
|
130
|
+
const SID_A = 'sess-A'
|
|
131
|
+
const OTHER = 'sess-B'
|
|
132
|
+
const TURNS = 30
|
|
133
|
+
// 预置上一场留下的卷宗(真实场景里会话开始前文件就在了)
|
|
134
|
+
ws.mergeWorkspace(WORK, {
|
|
135
|
+
decisions: ['上一场留下的决策'],
|
|
136
|
+
constraints: ['npm publish'],
|
|
137
|
+
snapshot: { at: '2026-10-29T09:00:00.000Z', sid: 'sess-prev', toolCalls: 40, denies: 2, kpi: -9, delegateBudget: 12 },
|
|
138
|
+
})
|
|
139
|
+
const seqA = []
|
|
140
|
+
const seqB = []
|
|
141
|
+
ws.resetWorkspaceSectionCache()
|
|
142
|
+
for (let t = 1; t <= TURNS; t += 1) {
|
|
143
|
+
const rec = ws.readWorkspace(WORK)
|
|
144
|
+
seqA.push(String(ws.renderWorkspaceSection(rec, { sid: SID_A }) || ''))
|
|
145
|
+
seqB.push(String(ws.renderWorkspaceSectionOnce(rec, { sid: SID_A }) || ''))
|
|
146
|
+
ws.mergeWorkspace(WORK, {
|
|
147
|
+
decisions: [`第 ${t} 回合的人类指令`],
|
|
148
|
+
snapshot: { at: `2026-10-29T10:${String(t).padStart(2, '0')}:00.000Z`, sid: SID_A, toolCalls: t, denies: 0, kpi: 0, delegateBudget: 20 },
|
|
149
|
+
})
|
|
150
|
+
if (t % 3 === 0) {
|
|
151
|
+
ws.mergeWorkspace(WORK, {
|
|
152
|
+
snapshot: { at: `2026-10-29T10:${String(t).padStart(2, '0')}:30.000Z`, sid: OTHER, toolCalls: 7, denies: 1, kpi: -3, delegateBudget: 9 },
|
|
153
|
+
})
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
const stat = (seq) => {
|
|
157
|
+
const breaks = []
|
|
158
|
+
for (let i = 1; i < seq.length; i += 1) if (seq[i] !== seq[i - 1]) breaks.push(i + 1)
|
|
159
|
+
return { versions: new Set(seq).size, breaks, rate: ((seq.length - breaks.length) / seq.length) * 100 }
|
|
160
|
+
}
|
|
161
|
+
const a = stat(seqA)
|
|
162
|
+
const b = stat(seqB)
|
|
163
|
+
if (savedWs === undefined) delete process.env.FG_WORKSPACE_FILE
|
|
164
|
+
else process.env.FG_WORKSPACE_FILE = savedWs
|
|
165
|
+
if (savedAudit === undefined) delete process.env.FG_AUDIT_FILE
|
|
166
|
+
else process.env.FG_AUDIT_FILE = savedAudit
|
|
167
|
+
rmSync(TMP, { recursive: true, force: true })
|
|
168
|
+
return { turns: TURNS, before: a, after: b }
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
if (AB) {
|
|
172
|
+
const r = await runAB()
|
|
173
|
+
if (AS_JSON) {
|
|
174
|
+
console.log(JSON.stringify(r, null, 2))
|
|
175
|
+
process.exit(0)
|
|
176
|
+
}
|
|
177
|
+
console.log(`输入:${r.turns} 回合 · 同一工作区 · 并发会话每 3 回合改写快照`)
|
|
178
|
+
console.log('⚠ 这是**压力场景**,不是现状:真实落盘里每个会话的系统段只变 1 次。')
|
|
179
|
+
console.log('⚠ 宿主 `systemPromptUpdate: "in-history"`——系统段变了是往历史里追加一条新 system 消息,')
|
|
180
|
+
console.log(' 不是改写前缀,所以下面这些"断点"不会让整段历史重付,只多背一份系统提示。\n')
|
|
181
|
+
console.log(`改前(每回合重渲染) 版本 ${r.before.versions} · 断点 ${r.before.breaks.length} 次 · 字节稳定率 ${r.before.rate.toFixed(1)}%`)
|
|
182
|
+
console.log(` 断点回合:${r.before.breaks.join(',')}`)
|
|
183
|
+
console.log(`改后(首步冻结) 版本 ${r.after.versions} · 断点 ${r.after.breaks.length} 次 · 字节稳定率 ${r.after.rate.toFixed(1)}%`)
|
|
184
|
+
console.log(` 断点回合:${r.after.breaks.join(',') || '无'}`)
|
|
185
|
+
console.log('\n字节稳定率 ≠ 宿主面板的缓存命中率:前者按回合数算"字节是否相同",')
|
|
186
|
+
console.log('后者按 token 算"命中多少"。两个分母不同,不能直接比。')
|
|
187
|
+
process.exit(0)
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const h = (s) => createHash('sha256').update(s).digest('hex').slice(0, 10)
|
|
191
|
+
// 只取消息本体:`data` 外层还挂着 `{turn, step}` 元数据,那是**记账编号**不是提示内容,
|
|
192
|
+
// 把它算进指纹会把"每步都变"当成前缀抖动(第一次跑就踩了这个坑)。
|
|
193
|
+
const textOf = textOfMessage
|
|
194
|
+
|
|
195
|
+
const files = walkSessionFiles(SESSIONS)
|
|
196
|
+
.filter((x) => x.size < 3 * 1024 * 1024)
|
|
197
|
+
.sort((a, b) => b.m - a.m)
|
|
198
|
+
|
|
199
|
+
/** 按 step/start 切段;每个 step 记下这一步看到的 tools / system / developer / 首个 user。 */
|
|
200
|
+
function stepsOf(lines) {
|
|
201
|
+
const out = []
|
|
202
|
+
let cur = null
|
|
203
|
+
let tools = null
|
|
204
|
+
let sawUser = false
|
|
205
|
+
for (const l of lines) {
|
|
206
|
+
if (l.type === 'request/header') {
|
|
207
|
+
const hd = (l.data && (l.data.header || l.data)) || {}
|
|
208
|
+
if (Array.isArray(hd.tools)) tools = JSON.stringify(hd.tools)
|
|
209
|
+
continue
|
|
210
|
+
}
|
|
211
|
+
if (l.type === 'step/start') {
|
|
212
|
+
cur = { tools, system: [], developer: [], user: null }
|
|
213
|
+
sawUser = false
|
|
214
|
+
out.push(cur)
|
|
215
|
+
continue
|
|
216
|
+
}
|
|
217
|
+
if (!cur) continue
|
|
218
|
+
if (l.type === 'system/message') cur.system.push(textOf(l))
|
|
219
|
+
else if (l.type === 'developer/message') cur.developer.push(textOf(l))
|
|
220
|
+
else if (l.type === 'user/message' && !sawUser) {
|
|
221
|
+
cur.user = textOf(l)
|
|
222
|
+
sawUser = true
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
// 头部可能只写一次且出现在首个 step 之后:统一回填,避免把"没读到"当成"变了"。
|
|
226
|
+
for (const s of out) if (!s.tools && tools) s.tools = tools
|
|
227
|
+
return out
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
const report = []
|
|
231
|
+
for (const cand of SID ? files.filter((x) => x.f.includes(SID)) : files.slice(0, 20)) {
|
|
232
|
+
let lines
|
|
233
|
+
try {
|
|
234
|
+
lines = decodeSession(cand.f)
|
|
235
|
+
} catch {
|
|
236
|
+
continue
|
|
237
|
+
}
|
|
238
|
+
const steps = stepsOf(lines)
|
|
239
|
+
if (steps.length < 2) continue
|
|
240
|
+
const raw = {
|
|
241
|
+
tools: steps.map((s) => s.tools || ''),
|
|
242
|
+
system: steps.map((s) => s.system.join('\n')),
|
|
243
|
+
developer: steps.map((s) => s.developer.join('\n')),
|
|
244
|
+
user: steps.map((s) => s.user || ''),
|
|
245
|
+
}
|
|
246
|
+
const stat = {}
|
|
247
|
+
for (const [k, arr] of Object.entries(raw)) {
|
|
248
|
+
// 只比"有内容"的步:空值是"这一步没落这段",不是"这段变了"。
|
|
249
|
+
const idx = arr.map((x, i) => (x ? i : -1)).filter((i) => i >= 0)
|
|
250
|
+
const vals = idx.map((i) => arr[i])
|
|
251
|
+
if (vals.length < 2) {
|
|
252
|
+
stat[k] = { versions: vals.length ? 1 : 0, steps: arr.length, firstChangeAt: -1, chars: vals[0]?.length || 0 }
|
|
253
|
+
continue
|
|
254
|
+
}
|
|
255
|
+
const uniq = [...new Set(vals.map(h))]
|
|
256
|
+
const base = vals[0]
|
|
257
|
+
const changeIdx = vals.findIndex((x) => x !== base)
|
|
258
|
+
stat[k] = {
|
|
259
|
+
versions: uniq.length,
|
|
260
|
+
steps: arr.length,
|
|
261
|
+
firstChangeAt: changeIdx < 0 ? -1 : idx[changeIdx],
|
|
262
|
+
chars: base.length,
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
report.push({ session: basename(dirname(cand.f)).replace('session-', '').slice(0, 8), steps: steps.length, fields: stat, raw })
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
if (AS_JSON) {
|
|
269
|
+
console.log(JSON.stringify(report.map(({ raw, ...r }) => r), null, 2))
|
|
270
|
+
process.exit(strictVerdict(report) ? 1 : 0)
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* 严格判定:哪些字段"多版本"算红。
|
|
275
|
+
*
|
|
276
|
+
* 分档的理由(别一刀切):
|
|
277
|
+
* · `tools` / 首条 `user` 段 FG 完全可控、实测全程恒定 → 多版本必是有人改坏了,红
|
|
278
|
+
* · `system` 段默认只报不拦:熔断告知(`focus-guard-fuse`)与换会话交接都会合法地变一次,
|
|
279
|
+
* 硬红会变成假阳性——假阳性会训练人加绕过开关,闸门就废了
|
|
280
|
+
* · 需要更严时显式 `--fail-on-system`,而不是改默认值
|
|
281
|
+
*/
|
|
282
|
+
function strictVerdict(list) {
|
|
283
|
+
if (!STRICT) return false
|
|
284
|
+
return list.some((r) => {
|
|
285
|
+
const f = r.fields
|
|
286
|
+
const base = (f.tools?.versions || 0) > 1 || (f.user?.versions || 0) > 1
|
|
287
|
+
return base || (FAIL_ON_SYSTEM && (f.system?.versions || 0) > 1)
|
|
288
|
+
})
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
if (!report.length) {
|
|
292
|
+
console.log('找不到 ≥2 步的会话', SID || '(最近 20 个)')
|
|
293
|
+
process.exit(0)
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
for (const r of report.slice(0, TOP)) {
|
|
297
|
+
console.log(`\n会话 ${r.session} · ${r.steps} 步`)
|
|
298
|
+
console.log('字段'.padEnd(12) + '首段字符'.padStart(10) + '不同版本'.padStart(10) + '首次分歧'.padStart(10))
|
|
299
|
+
for (const [k, s] of Object.entries(r.fields)) {
|
|
300
|
+
const at = s.firstChangeAt < 0 ? '-' : `step ${s.firstChangeAt + 1}`
|
|
301
|
+
console.log(`${k.padEnd(10)}${String(s.chars).padStart(12)}${String(s.versions).padStart(12)}${at.padStart(12)}`)
|
|
302
|
+
}
|
|
303
|
+
// 定位首个变了的 system 段里,到底是哪一块在动
|
|
304
|
+
const sys = r.raw.system.filter(Boolean)
|
|
305
|
+
const i = sys.findIndex((x) => x !== sys[0])
|
|
306
|
+
if (i > 0) {
|
|
307
|
+
const at = firstDiff(sys[0], sys[i])
|
|
308
|
+
const lo = Math.max(0, at - 60)
|
|
309
|
+
const hi = Math.min(sys[i].length, at + 90)
|
|
310
|
+
const ctx = sys[i].slice(lo, hi).split('\\n').join('\n ')
|
|
311
|
+
console.log(` system 段首次分歧 @${at}:…${ctx}…`)
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
const bad = strictVerdict(report)
|
|
316
|
+
if (STRICT) {
|
|
317
|
+
const sysDrift = report.filter((r) => (r.fields.system?.versions || 0) > 1).length
|
|
318
|
+
if (bad) console.log('\n判定:前缀有抖动(exit 1)')
|
|
319
|
+
else if (sysDrift) {
|
|
320
|
+
console.log(
|
|
321
|
+
`\n判定:工具表 / 首条 user 段稳定;${sysDrift} 个会话的 system 段变过(默认不拦——熔断告知与换会话交接会合法地变一次,要看严加 --fail-on-system)`,
|
|
322
|
+
)
|
|
323
|
+
} else console.log('\n判定:前缀稳定(exit 0)')
|
|
324
|
+
}
|
|
325
|
+
process.exit(bad ? 1 : 0)
|
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* 私有面守卫(2026-10-30)
|
|
4
|
+
*
|
|
5
|
+
* ## 为什么需要
|
|
6
|
+
*
|
|
7
|
+
* 私有忽略规则从 `.gitignore`(入库、公开)搬到 `.git/info/exclude`(本地、不入库)之后,
|
|
8
|
+
* 换来一个收益:外人看不到"屏蔽了什么",只知道仓库里没有这些文件。
|
|
9
|
+
*
|
|
10
|
+
* 但也引入一个隐患:**exclude 不随仓库走**。换机器 clone 后如果忘了配,
|
|
11
|
+
* `git add .` 会把私有数据整包收进版本库,而且第一次发现往往是已经推上去之后。
|
|
12
|
+
* 本工具把这个隐患从"数据泄漏事故"降级成"一条检查失败"。
|
|
13
|
+
*
|
|
14
|
+
* ## 为什么规则清单不在本文件里
|
|
15
|
+
*
|
|
16
|
+
* 本文件进版本库、是公开的。如果在这里写死 `.ai/`、`.focus-guard/` 之类的路径,
|
|
17
|
+
* 守卫自己就变成了泄漏源——白折腾一场。
|
|
18
|
+
* 所以:**清单只存在于 `.git/info/exclude`(私有),本工具运行时读它。**
|
|
19
|
+
* 代码里一个字都不提具体目录名。
|
|
20
|
+
*
|
|
21
|
+
* ## 四条断言
|
|
22
|
+
*
|
|
23
|
+
* A. exclude 可读 —— 否则私有面根本没设防
|
|
24
|
+
* B. 没有**已跟踪**文件命中 exclude 规则 —— 命中即已经泄漏,且 .gitignore 拦不住已跟踪文件
|
|
25
|
+
* C. `.gitignore` 没有点名 exclude 里的路径 —— 点名即把分类重新暴露给外人
|
|
26
|
+
* D. 若存在清单备份,其规则须全部已装进 exclude —— 专抓"换机器忘了装"
|
|
27
|
+
*
|
|
28
|
+
* ## 输出也不泄漏
|
|
29
|
+
*
|
|
30
|
+
* 默认只报**数量与规则序号**,不打路径、不打规则原文——本地日志也可能被贴出去。
|
|
31
|
+
* 要处置时加 `--verbose` 才展开。
|
|
32
|
+
*
|
|
33
|
+
* 用法:
|
|
34
|
+
* node packages/core/tools/privacy-guard.mjs # 人读摘要
|
|
35
|
+
* node packages/core/tools/privacy-guard.mjs --verbose # 展开命中的具体路径
|
|
36
|
+
* node packages/core/tools/privacy-guard.mjs --json # 机器读
|
|
37
|
+
* node packages/core/tools/privacy-guard.mjs --install # 把清单备份装进 exclude(幂等)
|
|
38
|
+
* 退出码:0 通过 / 1 有断言失败 / 2 环境不可判(不在 git 仓库里)
|
|
39
|
+
*/
|
|
40
|
+
|
|
41
|
+
import { appendFileSync, existsSync, readFileSync } from 'node:fs'
|
|
42
|
+
import { execFileSync } from 'node:child_process'
|
|
43
|
+
import { join } from 'node:path'
|
|
44
|
+
import { fileURLToPath } from 'node:url'
|
|
45
|
+
|
|
46
|
+
const REPO_ROOT = fileURLToPath(new URL('../../..', import.meta.url))
|
|
47
|
+
const EXCLUDE_PATH = join(REPO_ROOT, '.git', 'info', 'exclude')
|
|
48
|
+
const GITIGNORE_PATH = join(REPO_ROOT, '.gitignore')
|
|
49
|
+
/** 清单备份:放在私有目录里,所以它自己不会进版本库。 */
|
|
50
|
+
const CANONICAL_PATH = join(REPO_ROOT, '.ai', 'private-surface.exclude')
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* 把一条 gitignore 风格规则编译成正则。
|
|
54
|
+
*
|
|
55
|
+
* 支持:`/` 锚定、结尾 `/` 只匹配目录、`*`(不跨 `/`)、`**`(跨 `/`)、`?`。
|
|
56
|
+
* 不支持:字符类 `[a-z]`、转义——清单是我们自己写的,用不到就别写,
|
|
57
|
+
* 写了也不报错(当普通字符处理),但 `--check-rules` 会提示不支持。
|
|
58
|
+
*
|
|
59
|
+
* @param {string} rule 不含 `!` 前缀
|
|
60
|
+
* @returns {{re: RegExp, dirOnly: boolean}}
|
|
61
|
+
*/
|
|
62
|
+
export function compileRule(rule) {
|
|
63
|
+
let r = rule
|
|
64
|
+
const dirOnly = r.endsWith('/')
|
|
65
|
+
if (dirOnly) r = r.slice(0, -1)
|
|
66
|
+
let anchored = r.startsWith('/')
|
|
67
|
+
if (anchored) r = r.slice(1)
|
|
68
|
+
// 中间带 `/` 的规则天然从根锚定(gitignore 同义)
|
|
69
|
+
if (r.includes('/')) anchored = true
|
|
70
|
+
|
|
71
|
+
const body = r
|
|
72
|
+
.replace(/[.+^${}()|[\]\\]/g, '\\$&')
|
|
73
|
+
.replace(/\*\*/g, '\u0000')
|
|
74
|
+
.replace(/\*/g, '[^/]*')
|
|
75
|
+
.replace(/\u0000/g, '.*')
|
|
76
|
+
.replace(/\?/g, '[^/]')
|
|
77
|
+
|
|
78
|
+
// 目录规则:路径里出现这个段即可(段后必须有 `/` 或结束)
|
|
79
|
+
if (dirOnly) {
|
|
80
|
+
const head = anchored ? `^${body}` : `(^|/)${body}`
|
|
81
|
+
return { re: new RegExp(`${head}(/|$)`), dirOnly }
|
|
82
|
+
}
|
|
83
|
+
// 文件规则:无 `/` 时匹配任意深度的同名文件;有 `/` 时从根锚定
|
|
84
|
+
const re = anchored ? new RegExp(`^${body}$`) : new RegExp(`(^|/)${body}$`)
|
|
85
|
+
return { re, dirOnly }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* 解析 exclude 文本为规则列表。跳过注释与空行,保留 `!` 取反语义与顺序。
|
|
90
|
+
* @param {string} text
|
|
91
|
+
* @returns {Array<{raw: string, negate: boolean, re: RegExp, dirOnly: boolean}>}
|
|
92
|
+
*/
|
|
93
|
+
export function parseRules(text) {
|
|
94
|
+
const out = []
|
|
95
|
+
for (const line of String(text || '').split('\n')) {
|
|
96
|
+
const trimmed = line.trim()
|
|
97
|
+
if (!trimmed || trimmed.startsWith('#')) continue
|
|
98
|
+
const negate = trimmed.startsWith('!')
|
|
99
|
+
const body = negate ? trimmed.slice(1) : trimmed
|
|
100
|
+
if (!body) continue
|
|
101
|
+
out.push({ raw: trimmed, negate, ...compileRule(body) })
|
|
102
|
+
}
|
|
103
|
+
return out
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* 按 gitignore 语义判定单个路径是否被忽略:**最后一条命中的规则说了算**。
|
|
108
|
+
*
|
|
109
|
+
* 关键点:必须把**所有祖先目录**也当作候选来匹配。
|
|
110
|
+
* 因为 gitignore 里 `/docs/vault-notes/*` 匹配的是目录 `docs/vault-notes/vendors`,
|
|
111
|
+
* 然后"被忽略的目录下面的一切都跟着被忽略"——如果只拿完整文件路径去套
|
|
112
|
+
* `[^/]*`,嵌套文件永远匹配不上,守卫就成了瞎子。
|
|
113
|
+
* (2026-10-30 实测踩过:git check-ignore 命中,自写匹配器漏判。)
|
|
114
|
+
*
|
|
115
|
+
* @param {Array} rules parseRules 的结果
|
|
116
|
+
* @param {string} path 相对仓库根的路径,用 `/` 分隔
|
|
117
|
+
* @returns {boolean}
|
|
118
|
+
*/
|
|
119
|
+
export function isIgnored(rules, path) {
|
|
120
|
+
const parts = String(path).split('/')
|
|
121
|
+
const cands = []
|
|
122
|
+
for (let i = 1; i <= parts.length; i += 1) cands.push(parts.slice(0, i).join('/'))
|
|
123
|
+
let ignored = false
|
|
124
|
+
for (const rule of rules) {
|
|
125
|
+
if (!cands.some((c) => rule.re.test(c))) continue
|
|
126
|
+
ignored = !rule.negate
|
|
127
|
+
}
|
|
128
|
+
return ignored
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** 取仓库已跟踪文件清单。失败返回 null(调用方判环境不可用)。 */
|
|
132
|
+
function trackedFiles() {
|
|
133
|
+
try {
|
|
134
|
+
const out = execFileSync('git', ['ls-files', '-z'], {
|
|
135
|
+
cwd: REPO_ROOT,
|
|
136
|
+
encoding: 'utf8',
|
|
137
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
138
|
+
})
|
|
139
|
+
return out.split('\0').filter(Boolean)
|
|
140
|
+
} catch {
|
|
141
|
+
return null
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* 断言 C 的实现:`.gitignore` 是否点名了 exclude 里的路径。
|
|
147
|
+
*
|
|
148
|
+
* 判据不看语义、只看**字符串是否重复出现**——同一个路径串既在私有清单里、
|
|
149
|
+
* 又在公开的 .gitignore 里,那它的分类就已经暴露了。
|
|
150
|
+
*
|
|
151
|
+
* 两类必须排除,否则 C 会误报成灾(2026-10-30 首版就踩了):
|
|
152
|
+
* ① 以通配开头的规则(`*.log`)—— 纯后缀/扩展名规则,天然通用,
|
|
153
|
+
* 而且它的"字面前缀"是空串,`startsWith('')` 恒真,会把所有条目都判成泄漏;
|
|
154
|
+
* ② 取反规则在**两边都出现**时才算泄漏,单独出现不算(`.gitignore` 里放行
|
|
155
|
+
* 某个文件不暴露任何东西,暴露的是清单里那条路径)。
|
|
156
|
+
*
|
|
157
|
+
* @param {string} gitignoreText
|
|
158
|
+
* @param {Array} rules
|
|
159
|
+
* @returns {string[]} 泄漏的规则原文(**只在内部用,不直接打印**)
|
|
160
|
+
*/
|
|
161
|
+
export function findLeakedRules(gitignoreText, rules) {
|
|
162
|
+
const lines = String(gitignoreText || '')
|
|
163
|
+
.split('\n')
|
|
164
|
+
.map((l) => l.trim())
|
|
165
|
+
.filter((l) => l && !l.startsWith('#'))
|
|
166
|
+
const leaked = []
|
|
167
|
+
for (const rule of rules) {
|
|
168
|
+
const needle = rule.raw.replace(/^!/, '').replace(/^\//, '').replace(/\/$/, '')
|
|
169
|
+
// 空串或以通配开头 → 通用规则,不是私有路径的身份
|
|
170
|
+
if (!needle || /^[*?]/.test(needle)) continue
|
|
171
|
+
const literal = needle.split(/[*?]/)[0]
|
|
172
|
+
const hit = lines.some((line) => {
|
|
173
|
+
const cand = line.replace(/^!/, '').replace(/^\//, '').replace(/\/$/, '')
|
|
174
|
+
if (!cand) return false
|
|
175
|
+
if (literal) return cand === needle || cand.startsWith(literal)
|
|
176
|
+
return cand === needle
|
|
177
|
+
})
|
|
178
|
+
if (hit) leaked.push(rule.raw)
|
|
179
|
+
}
|
|
180
|
+
return leaked
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* 把清单备份里缺的规则追加进 exclude(幂等:已在的跳过)。
|
|
185
|
+
*
|
|
186
|
+
* 为什么是"追加"而不是"覆盖":exclude 里可能还有别的本地规则(如 IDE 产物),
|
|
187
|
+
* 覆盖会把人家的东西冲掉。只补缺的,最安全。
|
|
188
|
+
*
|
|
189
|
+
* @returns {{added: string[], skipped: number}}
|
|
190
|
+
*/
|
|
191
|
+
export function installRules(canonicalPath = CANONICAL_PATH, excludePath = EXCLUDE_PATH) {
|
|
192
|
+
if (!existsSync(canonicalPath)) {
|
|
193
|
+
throw new Error(`清单备份不存在:${canonicalPath}`)
|
|
194
|
+
}
|
|
195
|
+
const want = parseRules(readFileSync(canonicalPath, 'utf8')).map((r) => r.raw)
|
|
196
|
+
const have = new Set(
|
|
197
|
+
existsSync(excludePath) ? parseRules(readFileSync(excludePath, 'utf8')).map((r) => r.raw) : [],
|
|
198
|
+
)
|
|
199
|
+
const missing = want.filter((w) => !have.has(w))
|
|
200
|
+
if (missing.length === 0) return { added: [], skipped: want.length }
|
|
201
|
+
const block = `\n# —— 私有面(由 privacy-guard --install 维护,勿手改)——\n${missing.join('\n')}\n`
|
|
202
|
+
appendFileSync(excludePath, block, 'utf8')
|
|
203
|
+
return { added: missing, skipped: want.length - missing.length }
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* 四条断言的全过程。拆出来是因为塞在 main() 里会撑破结构预算(113 行 > 80)。
|
|
208
|
+
*
|
|
209
|
+
* @param {string[]} files 已跟踪文件清单
|
|
210
|
+
* @returns {{rules: Array, failures: Array, notes: string[]}}
|
|
211
|
+
*/
|
|
212
|
+
function auditSurface(files) {
|
|
213
|
+
const failures = []
|
|
214
|
+
const notes = []
|
|
215
|
+
|
|
216
|
+
// —— 断言 A:exclude 可读 ——
|
|
217
|
+
//
|
|
218
|
+
// 2026-11-11:**没有清单 = 这台机器没有私有面**,A 不可判,记 skip 不记 fail。
|
|
219
|
+
// 起因:`npm run check` 2026-11-08 起进了发布闸(publish.yml),而 CI checkout 里
|
|
220
|
+
// `.ai/` 整个目录不入库 → `.git/info/exclude` 为空 → A 必红 → npm 发不出去。
|
|
221
|
+
// 这不是"忘了装"(那才是 A 要抓的),是"这台机器根本没有私有面配置"。
|
|
222
|
+
// 与 D 断言、`changelog-audience`(无 origin/main 时 skip)、`env-platform.test.mjs`
|
|
223
|
+
// (缺环境指纹时 skip)同一惯例:前置缺失不该报成缺陷。
|
|
224
|
+
// **检出能力保留**:本地清单还在,"有清单但 exclude 为空"照样红。
|
|
225
|
+
let rules = []
|
|
226
|
+
const hasCanonical = existsSync(CANONICAL_PATH)
|
|
227
|
+
if (!existsSync(EXCLUDE_PATH)) {
|
|
228
|
+
if (hasCanonical) failures.push({ code: 'A', msg: '.git/info/exclude 不存在,私有面没有设防' })
|
|
229
|
+
else notes.push('未找到 .git/info/exclude 与清单备份——本机没有私有面,跳过 A(CI / 新 clone 属此列)')
|
|
230
|
+
} else {
|
|
231
|
+
rules = parseRules(readFileSync(EXCLUDE_PATH, 'utf8'))
|
|
232
|
+
if (rules.length === 0) {
|
|
233
|
+
if (hasCanonical) failures.push({ code: 'A', msg: '清单备份存在但 .git/info/exclude 为空(换机器忘了装?)' })
|
|
234
|
+
else notes.push('exclude 为空且无清单备份——本机没有私有面,跳过 A(CI / 新 clone 属此列)')
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
if (rules.length === 0) return { rules, failures, notes }
|
|
238
|
+
|
|
239
|
+
// —— 断言 B:没有已跟踪文件命中私有规则 ——
|
|
240
|
+
// 注:.gitignore 对**已跟踪**文件无效,所以一旦命中,只能靠 git rm --cached 补救。
|
|
241
|
+
const trackedHits = files.filter((f) => isIgnored(rules, f))
|
|
242
|
+
if (trackedHits.length > 0) {
|
|
243
|
+
failures.push({
|
|
244
|
+
code: 'B',
|
|
245
|
+
msg: `${trackedHits.length} 个已跟踪文件命中私有规则(已泄漏,.gitignore 拦不住已跟踪文件)`,
|
|
246
|
+
detail: trackedHits,
|
|
247
|
+
})
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// —— 断言 C:.gitignore 未点名私有路径 ——
|
|
251
|
+
if (existsSync(GITIGNORE_PATH)) {
|
|
252
|
+
const leaked = findLeakedRules(readFileSync(GITIGNORE_PATH, 'utf8'), rules)
|
|
253
|
+
if (leaked.length > 0) {
|
|
254
|
+
failures.push({
|
|
255
|
+
code: 'C',
|
|
256
|
+
msg: `.gitignore 点名了 ${leaked.length} 条私有路径(分类已暴露,应只留在 exclude)`,
|
|
257
|
+
detail: leaked,
|
|
258
|
+
})
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// —— 断言 D:清单备份已安装 ——
|
|
263
|
+
if (existsSync(CANONICAL_PATH)) {
|
|
264
|
+
const want = parseRules(readFileSync(CANONICAL_PATH, 'utf8')).map((r) => r.raw)
|
|
265
|
+
const have = new Set(rules.map((r) => r.raw))
|
|
266
|
+
const missing = want.filter((w) => !have.has(w))
|
|
267
|
+
if (missing.length > 0) {
|
|
268
|
+
failures.push({
|
|
269
|
+
code: 'D',
|
|
270
|
+
msg: `清单备份里有 ${missing.length} 条规则未装进 exclude(换机器忘了装?)`,
|
|
271
|
+
detail: missing,
|
|
272
|
+
})
|
|
273
|
+
}
|
|
274
|
+
} else {
|
|
275
|
+
notes.push('未找到清单备份(.ai/private-surface.exclude),跳过 D —— 新机器上这是正常的')
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
return { rules, failures, notes }
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/** `--install` 分支:装清单并退出。 */
|
|
282
|
+
function runInstall(json) {
|
|
283
|
+
try {
|
|
284
|
+
const { added, skipped } = installRules()
|
|
285
|
+
if (json) console.log(JSON.stringify({ added: added.length, skipped }))
|
|
286
|
+
else {
|
|
287
|
+
console.log(`[privacy-guard] 已装 ${added.length} 条(已在 ${skipped} 条)→ .git/info/exclude`)
|
|
288
|
+
if (added.length === 0) console.log('[privacy-guard] 无需改动,清单已是最新')
|
|
289
|
+
}
|
|
290
|
+
process.exit(0)
|
|
291
|
+
} catch (error) {
|
|
292
|
+
console.error(`[privacy-guard] 安装失败:${error && error.message}`)
|
|
293
|
+
process.exit(2)
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** 人读输出。默认不展开路径与规则原文——本地日志也可能被贴出去。 */
|
|
298
|
+
function printHuman({ rules, files, failures, notes }, verbose) {
|
|
299
|
+
console.log(`[privacy-guard] 私有规则 ${rules.length} 条 · 已跟踪 ${files.length} 个文件`)
|
|
300
|
+
for (const note of notes) console.log(` · ${note}`)
|
|
301
|
+
if (failures.length === 0) {
|
|
302
|
+
// skip 时不能说「清单已装」——那是没检查过的事。文案必须跟着判据走。
|
|
303
|
+
console.log(
|
|
304
|
+
rules.length === 0
|
|
305
|
+
? '[privacy-guard] PASS:本机无私有面(A/D 不可判,已跳过)'
|
|
306
|
+
: '[privacy-guard] PASS:私有面干净(无已跟踪命中、无 .gitignore 点名、清单已装)',
|
|
307
|
+
)
|
|
308
|
+
return
|
|
309
|
+
}
|
|
310
|
+
for (const f of failures) {
|
|
311
|
+
console.log(` ✗ [${f.code}] ${f.msg}`)
|
|
312
|
+
if (!verbose || !f.detail) continue
|
|
313
|
+
for (const d of f.detail.slice(0, 20)) console.log(` ${d}`)
|
|
314
|
+
if (f.detail.length > 20) console.log(` …还有 ${f.detail.length - 20} 条`)
|
|
315
|
+
}
|
|
316
|
+
console.log(' 处置:A/D → 从清单备份重装 exclude;B → git rm --cached 该文件;C → 从 .gitignore 删掉该条')
|
|
317
|
+
if (!verbose) console.log(' (默认不展开路径与规则原文,加 --verbose 查看)')
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
function main() {
|
|
321
|
+
const json = process.argv.includes('--json')
|
|
322
|
+
const verbose = process.argv.includes('--verbose')
|
|
323
|
+
|
|
324
|
+
if (process.argv.includes('--install')) runInstall(json)
|
|
325
|
+
|
|
326
|
+
const files = trackedFiles()
|
|
327
|
+
if (files === null) {
|
|
328
|
+
console.error('[privacy-guard] 不在 git 仓库里,环境不可判')
|
|
329
|
+
process.exit(2)
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
const { rules, failures, notes } = auditSurface(files)
|
|
333
|
+
const result = {
|
|
334
|
+
rules: rules.length,
|
|
335
|
+
tracked: files.length,
|
|
336
|
+
failures: failures.map((f) => ({
|
|
337
|
+
code: f.code,
|
|
338
|
+
msg: f.msg,
|
|
339
|
+
count: f.detail ? f.detail.length : 0,
|
|
340
|
+
...(verbose && f.detail ? { detail: f.detail } : {}),
|
|
341
|
+
})),
|
|
342
|
+
notes,
|
|
343
|
+
ok: failures.length === 0,
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
if (json) console.log(JSON.stringify(result))
|
|
347
|
+
else printHuman({ rules, files, failures, notes }, verbose)
|
|
348
|
+
|
|
349
|
+
process.exit(failures.length === 0 ? 0 : 1)
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
if (process.argv[1] && process.argv[1].endsWith('privacy-guard.mjs')) main()
|