dsh-knit 0.23.0 → 0.24.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/CHANGELOG.md +168 -0
- package/README.en.md +67 -37
- package/README.md +51 -28
- package/SECURITY.md +9 -3
- package/package.json +5 -3
- package/src/client/client.js +448 -141
- package/src/host/changes.js +208 -0
- package/src/host/git.js +377 -0
- package/src/host/index.js +228 -5
- package/test/client.test.mjs +633 -331
- package/test/git-changes.test.mjs +1238 -0
- package/test/host-http.test.mjs +4 -58
- package/test/http-harness.mjs +79 -0
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Knit · **Git 变更关联投影**(v0.25 Git-aware Context Retrieval)
|
|
3
|
+
*
|
|
4
|
+
* 这一层回答的问题只有一句:**「这些被改过的文件,按已有的关联证据,还牵着谁」**。
|
|
5
|
+
*
|
|
6
|
+
* ## 它不发明关系,只挑已有的边
|
|
7
|
+
*
|
|
8
|
+
* 边全部来自 `relations.js` 的 `buildRelationFacts()` —— 那四类(`tests` / `imports` /
|
|
9
|
+
* `references` / `documents`)已经有各自的证据与守卫。本模块**只做一件事**:
|
|
10
|
+
* 把「变更文件」当作种子,去事实表里取它**已经存在**的边,再把边指向的那一端投影成
|
|
11
|
+
* 一条可以摆进列表的结果。**没有 AST、没有新图、没有猜出来的依赖。**
|
|
12
|
+
*
|
|
13
|
+
* ## 一条边都没有的变更文件怎么办
|
|
14
|
+
*
|
|
15
|
+
* 如实进 `unresolved`(面板据此说「N 个变更文件没有关联证据」),**不硬凑**。
|
|
16
|
+
* 这与 `context.js` 给 Related 层写下的那条纪律是同一条:说不出凭什么,就不出场。
|
|
17
|
+
*
|
|
18
|
+
* ## 为什么已删除 / 重命名前的路径也要当种子
|
|
19
|
+
*
|
|
20
|
+
* 这是本模块唯一一处需要解释的设计:**文件被删掉之后,它就不在候选集里了**,
|
|
21
|
+
* 于是 `relations.js` 的解析(`resolveRef` / `resolveSpec` / `testsOf`)**都不再认它** ——
|
|
22
|
+
* 「删掉 `tests/foo.test.ts`,谁在用它」这个问题会一声不响地没有答案。
|
|
23
|
+
*
|
|
24
|
+
* 修法很小:把**变更清单里那些已经不在工作区里的路径**,作为 `head: ''` 的**合成候选**
|
|
25
|
+
* 一并交给 `buildRelationFacts()`。索引里因此有这个 rel,别人指向它的边就能解析出来。
|
|
26
|
+
* 两条边界:
|
|
27
|
+
* · 合成候选的 `head` 是空的 ⇒ 它**自己**产不出任何出边(它确实已经没了);
|
|
28
|
+
* · 它**永远只能当种子,不能当结果**(`itemRels` 把它排除掉)—— 你没法打开一个不存在的文件。
|
|
29
|
+
*
|
|
30
|
+
* ## 截断(确定性)
|
|
31
|
+
*
|
|
32
|
+
* 结果按「证据类型优先级(沿用 `relations.js` 的 `RELATION_TYPES` 顺序)→ 关联到的变更文件数降序
|
|
33
|
+
* → rel 字典序」排,超过 `MAX_CHANGE_RELATED` 截断并如实给出 `relatedTotal`。
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
import { RELATION_TYPES, MAX_RELATIONS_PER_ITEM } from './relations.js'
|
|
37
|
+
|
|
38
|
+
/** 面板「变更关联」区最多几条(§6.7 同一条预算纪律:这是上限,不是建议)。 */
|
|
39
|
+
export const MAX_CHANGE_RELATED = 8
|
|
40
|
+
|
|
41
|
+
const TYPE_RANK = new Map(RELATION_TYPES.map((t, i) => [t, i]))
|
|
42
|
+
const rankOf = (type) => (TYPE_RANK.has(type) ? TYPE_RANK.get(type) : 99)
|
|
43
|
+
|
|
44
|
+
/** 方向翻转:一条边在两端各有一次登记,`line` 属于**叙述方**,所以翻转方向不改行号。 */
|
|
45
|
+
const flip = (dir) => (dir === 'in' ? 'out' : 'in')
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* 把一次变更清单分成三份:**能当结果的**、**只能当种子的**、**够不着的**。
|
|
49
|
+
*
|
|
50
|
+
* @param {object} changeSet - `git.js` 的 `read()` 产物
|
|
51
|
+
* @param {Set<string>} corpusRels - 当前候选集里的 rel(**只有它们能当结果**)
|
|
52
|
+
* @returns {{seeds: string[], gone: string[], outside: string[], seedRels: string[]}}
|
|
53
|
+
* `seeds` = 变更里确实还在候选集中的路径(含重命名后的新路径)—— 可以当结果,也可以当种子
|
|
54
|
+
* `gone` = 变更里**不在**候选集里的文件路径(删除的、重命名前的、工作区外的)——
|
|
55
|
+
* **只能当种子**(合成候选,见 `ghostCandidates()`),永远不当结果
|
|
56
|
+
* `outside` = 同 `gone`,但只算「看起来像文件」的(目录条目不算)—— 面板据此说
|
|
57
|
+
* 「N 个变更不在检索范围」
|
|
58
|
+
* `seedRels`= `seeds` + `gone`(**查找关系时两者都要问**:删掉的测试文件照样牵着它的被测文件)
|
|
59
|
+
*
|
|
60
|
+
* ⚠️ 目录条目(`?? some/dir/`)既不当种子也不算 `outside`:它不是文件,
|
|
61
|
+
* 而 `resolveRef` / `testsOf` 只会去认文件。它仍然出现在 `changeSet.files` 里(如实报告)。
|
|
62
|
+
*/
|
|
63
|
+
export function splitSeeds(changeSet, corpusRels) {
|
|
64
|
+
const files = Array.isArray(changeSet && changeSet.files) ? changeSet.files : []
|
|
65
|
+
const seeds = []
|
|
66
|
+
const gone = []
|
|
67
|
+
const outside = []
|
|
68
|
+
const seenSeed = new Set()
|
|
69
|
+
const seenGone = new Set()
|
|
70
|
+
// ⚠️ `gone` 与 `outside` 是**两张表、两条去重线**:同一个 rel 同时属于两张表是**正常**的
|
|
71
|
+
// (「不在语料里的变更文件」既是「只能当种子」也是「不在检索范围」)。共用一个 Set
|
|
72
|
+
// 会让第二次 push 被当成重复而静默丢掉一枚(写完当场被测试抓到过一次)。
|
|
73
|
+
const seenOutside = new Set()
|
|
74
|
+
const push = (list, seen, rel) => {
|
|
75
|
+
if (!rel || seen.has(rel)) return
|
|
76
|
+
seen.add(rel)
|
|
77
|
+
list.push(rel)
|
|
78
|
+
}
|
|
79
|
+
const pushGone = (rel, isDir) => {
|
|
80
|
+
if (isDir) return
|
|
81
|
+
push(gone, seenGone, rel)
|
|
82
|
+
push(outside, seenOutside, rel)
|
|
83
|
+
}
|
|
84
|
+
for (const file of files) {
|
|
85
|
+
const rel = String(file.rel || '')
|
|
86
|
+
if (!rel) continue
|
|
87
|
+
const isDir = file.isDir === true
|
|
88
|
+
if (corpusRels.has(rel)) push(seeds, seenSeed, rel)
|
|
89
|
+
else pushGone(rel, isDir)
|
|
90
|
+
// 重命名 / 复制:原路径也当种子 —— 别人引用它的那条边还在,只是目标换了名字
|
|
91
|
+
const orig = file.origRel ? String(file.origRel) : ''
|
|
92
|
+
if (orig) {
|
|
93
|
+
if (corpusRels.has(orig)) push(seeds, seenSeed, orig)
|
|
94
|
+
else pushGone(orig, false)
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
seeds.sort()
|
|
98
|
+
gone.sort()
|
|
99
|
+
outside.sort()
|
|
100
|
+
return { seeds, gone, outside, seedRels: [...seeds, ...gone].sort() }
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* 合成候选:给「已经不在候选集里的变更路径」一个空壳,好让**别人指向它的边**解析得出来。
|
|
105
|
+
* 只喂给 `buildRelationFacts()`,**不进任何结果**。
|
|
106
|
+
*
|
|
107
|
+
* @param {string[]} gone - `splitSeeds()` 的 `gone`
|
|
108
|
+
* @returns {Array<{rel: string, head: string, mtimeMs: number, kind: string}>}
|
|
109
|
+
*/
|
|
110
|
+
export function ghostCandidates(gone) {
|
|
111
|
+
return (Array.isArray(gone) ? gone : []).map((rel) => ({ rel, head: '', mtimeMs: 0, kind: 'md' }))
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* 种子 + 事实表 → 关联结果。**纯函数**(不读盘、不看时钟、不发请求)。
|
|
116
|
+
*
|
|
117
|
+
* @param {object} input
|
|
118
|
+
* @param {string[]} input.seeds - 变更文件里在候选集中的那些
|
|
119
|
+
* @param {Map<string, Array<object>>} input.incident - `buildRelationFacts().incident`
|
|
120
|
+
* @param {Set<string>} input.itemRels - **允许当结果**的 rel(= 候选集;已删除的路径不在里面)
|
|
121
|
+
* @param {Set<string>} [input.exclude] - 明确排除的 rel(变更文件自己 + 已经在三层 / 固定区里的)。
|
|
122
|
+
* 变更文件自己不当结果:这一区要回答的是「**还**该一起看什么」,不是「你改了什么」。
|
|
123
|
+
* @param {number} [input.limit] - 最多几条结果
|
|
124
|
+
* @returns {{related: Array<{rel: string, evidence: Array<object>, types: string[]}>, unresolved: string[], relatedTotal: number}}
|
|
125
|
+
*/
|
|
126
|
+
export function projectChangeRelated(input) {
|
|
127
|
+
const seeds = Array.isArray(input && input.seeds) ? input.seeds : []
|
|
128
|
+
const incident = input && input.incident
|
|
129
|
+
const itemRels = input && input.itemRels instanceof Set ? input.itemRels : new Set()
|
|
130
|
+
const exclude = input && input.exclude instanceof Set ? input.exclude : new Set()
|
|
131
|
+
const limit = Number.isInteger(input && input.limit) && input.limit > 0 ? input.limit : MAX_CHANGE_RELATED
|
|
132
|
+
|
|
133
|
+
/** target rel → { rel, evidence: Map<key, edge> } */
|
|
134
|
+
const targets = new Map()
|
|
135
|
+
const unresolved = []
|
|
136
|
+
|
|
137
|
+
for (const seed of seeds) {
|
|
138
|
+
const edges = (incident && typeof incident.get === 'function' ? incident.get(seed) : null) || []
|
|
139
|
+
let count = 0
|
|
140
|
+
for (const edge of edges) {
|
|
141
|
+
if (!edge || typeof edge.other !== 'string' || !edge.type) continue
|
|
142
|
+
const target = edge.other
|
|
143
|
+
// 结果必须能打开:合成候选(已删除的路径)永远不当结果
|
|
144
|
+
if (target === seed || !itemRels.has(target) || exclude.has(target)) continue
|
|
145
|
+
let bucket = targets.get(target)
|
|
146
|
+
if (!bucket) {
|
|
147
|
+
bucket = { rel: target, evidence: new Map() }
|
|
148
|
+
targets.set(target, bucket)
|
|
149
|
+
}
|
|
150
|
+
// 证据按(起点 + 类型 + 方向)去重:同一对文件只留一条,行号取最靠前的
|
|
151
|
+
const key = `${seed}\u0000${edge.type}\u0000${flip(edge.dir)}`
|
|
152
|
+
const prev = bucket.evidence.get(key)
|
|
153
|
+
if (!prev) {
|
|
154
|
+
// ⚠️ 字段名逐字沿用 `relations.js` 的边形状(`type` / `dir` / `other` / `line`)——
|
|
155
|
+
// 面板的行级证据弹层与工具 `ITEM_SCHEMA` 都直接吃这一份,改个名字就会两处一起坏。
|
|
156
|
+
// 这里的 `other` 就是**关联起点**(那个被改过的文件)。
|
|
157
|
+
bucket.evidence.set(key, {
|
|
158
|
+
type: edge.type,
|
|
159
|
+
dir: flip(edge.dir),
|
|
160
|
+
other: seed,
|
|
161
|
+
...(Number.isInteger(edge.line) ? { line: edge.line } : {}),
|
|
162
|
+
})
|
|
163
|
+
} else if (Number.isInteger(edge.line) && (!Number.isInteger(prev.line) || edge.line < prev.line)) {
|
|
164
|
+
prev.line = edge.line
|
|
165
|
+
}
|
|
166
|
+
count += 1
|
|
167
|
+
}
|
|
168
|
+
if (count === 0) unresolved.push(seed)
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const rows = [...targets.values()].map((bucket) => {
|
|
172
|
+
const evidence = [...bucket.evidence.values()]
|
|
173
|
+
// 同一目标、同一类型、不同起点时,按类型优先级 → 起点字典序
|
|
174
|
+
evidence.sort((a, b) => {
|
|
175
|
+
const ta = rankOf(a.type)
|
|
176
|
+
const tb = rankOf(b.type)
|
|
177
|
+
if (ta !== tb) return ta - tb
|
|
178
|
+
const la = Number.isInteger(a.line) ? a.line : Number.MAX_SAFE_INTEGER
|
|
179
|
+
const lb = Number.isInteger(b.line) ? b.line : Number.MAX_SAFE_INTEGER
|
|
180
|
+
if (la !== lb) return la - lb
|
|
181
|
+
return a.other < b.other ? -1 : a.other > b.other ? 1 : 0
|
|
182
|
+
})
|
|
183
|
+
return { rel: bucket.rel, evidence, sources: new Set(evidence.map((e) => e.other)) }
|
|
184
|
+
})
|
|
185
|
+
|
|
186
|
+
rows.sort((a, b) => {
|
|
187
|
+
const ta = rankOf(a.evidence[0] && a.evidence[0].type)
|
|
188
|
+
const tb = rankOf(b.evidence[0] && b.evidence[0].type)
|
|
189
|
+
if (ta !== tb) return ta - tb
|
|
190
|
+
// 关联到的**变更文件**越多越靠前 —— 两个变更文件都指向它,是更强的「一起改」信号
|
|
191
|
+
if (a.sources.size !== b.sources.size) return b.sources.size - a.sources.size
|
|
192
|
+
return a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0
|
|
193
|
+
})
|
|
194
|
+
|
|
195
|
+
const relatedTotal = rows.length
|
|
196
|
+
const related = rows.slice(0, limit).map((row) => {
|
|
197
|
+
const shown = row.evidence.slice(0, MAX_RELATIONS_PER_ITEM)
|
|
198
|
+
return {
|
|
199
|
+
rel: row.rel,
|
|
200
|
+
evidence: shown,
|
|
201
|
+
evidenceTotal: row.evidence.length,
|
|
202
|
+
types: [...new Set(row.evidence.map((e) => e.type))],
|
|
203
|
+
from: [...new Set(row.evidence.map((e) => e.other))],
|
|
204
|
+
}
|
|
205
|
+
})
|
|
206
|
+
unresolved.sort()
|
|
207
|
+
return { related, unresolved, relatedTotal }
|
|
208
|
+
}
|
package/src/host/git.js
ADDED
|
@@ -0,0 +1,377 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Knit · **Git 变更状态读取**(v0.25 Git-aware Context Retrieval)
|
|
3
|
+
*
|
|
4
|
+
* 这一层只回答一个问题:**这个工作区现在有哪些文件被改过、各自是什么状态**。
|
|
5
|
+
* 它**不解析 diff、不读文件内容、不做任何写操作** —— 只跑一条只读的 `git status`。
|
|
6
|
+
*
|
|
7
|
+
* ## 五条硬约束(用户需求 §三.1 / §三.4)
|
|
8
|
+
*
|
|
9
|
+
* 1. **只读**:只允许两个子命令 —— `status` 与 `rev-parse --show-prefix`
|
|
10
|
+
* (见 `GIT_STATUS_ARGS` / `GIT_PREFIX_ARGS` 与 `MUTATING_VERBS` 的守卫)。
|
|
11
|
+
* 没有 `add` / `commit` / `checkout` / `reset` / `clean` / `stash` … 一条都没有,也永远不会有。
|
|
12
|
+
* 2. **绝不走 shell**:`spawn('git', [...GIT_GLOBAL_ARGS, ...args])`,参数是数组。
|
|
13
|
+
* 全局选项见 `GIT_GLOBAL_ARGS` —— 它挡的是「git 自己被配置牵着去写盘 / 去起进程」。
|
|
14
|
+
* 3. **有界**:`GIT_TIMEOUT_MS` 到点就 kill;`GIT_MAX_BYTES` 超了就 kill 并如实报 `output-too-large`;
|
|
15
|
+
* 解析出来的条目超过 `MAX_CHANGED_FILES` 就截断并标记。**任何一条都不抛**。
|
|
16
|
+
* 4. **失败明着降级**:`not-a-repo` / `git-missing` / `timeout` / `output-too-large` / `failed-fatal`
|
|
17
|
+
* 五种 reason;调用方据此照常出原来的列表,只是不显示变更关联。
|
|
18
|
+
* 5. **零依赖**:只用 Node 内置 `child_process`。**不 import `@deepseek-ai/*`**(AGENTS L1 §6.10)。
|
|
19
|
+
*
|
|
20
|
+
* ## 为什么不用 `--porcelain=v2`
|
|
21
|
+
*
|
|
22
|
+
* v1 的 `-z` 已经给全了我们要的四样(X / Y / 路径 / 重命名原路径),而且 2.7+ 都有。
|
|
23
|
+
* v2 多出来的字段(mode、对象 id)我们一个都不用 —— 不引入用不上的解析面。
|
|
24
|
+
*
|
|
25
|
+
* ## 路径基准(实测过,不是猜的)
|
|
26
|
+
*
|
|
27
|
+
* `git status --porcelain` 的路径**恒以仓库根为基准** —— 从子目录跑也一样
|
|
28
|
+
* (2026-10-13 实测:在 `src/` 下跑,输出仍是 `src/foo.ts`)。所以要把**工作区**
|
|
29
|
+
* 那一层前缀(`git rev-parse --show-prefix`)减掉,两条命令各司其职。
|
|
30
|
+
* 不在这个前缀下的路径(同一个仓库里、但工作区之外)**直接丢弃**,不算变更。
|
|
31
|
+
*
|
|
32
|
+
* 重命名的字段顺序也是实测的:`-z` 下是 `R <新路径>\0<原路径>\0`(新在前)——
|
|
33
|
+
* v1 与 v2 两种口径在这一点上一致。
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
import { spawn } from 'node:child_process'
|
|
37
|
+
|
|
38
|
+
/** 单次 git 调用的墙钟上限。到点 kill,如实回 `timeout`。 */
|
|
39
|
+
export const GIT_TIMEOUT_MS = 2500
|
|
40
|
+
/** 单次 git 调用的 stdout 上限(字节)。超了 kill,如实回 `output-too-large`。 */
|
|
41
|
+
export const GIT_MAX_BYTES = 1 << 20
|
|
42
|
+
/** 结果缓存的存活时长。面板每 5 秒轮询一次,8 秒 ⇒ 一条 git 大约每两轮跑一次。 */
|
|
43
|
+
export const GIT_CACHE_TTL_MS = 8000
|
|
44
|
+
/** 工作区前缀(`--show-prefix`)的缓存时长 —— 它几乎不变,也顺便缓存「不是仓库」这个结论。 */
|
|
45
|
+
export const GIT_PREFIX_TTL_MS = 60_000
|
|
46
|
+
/** 解析出来的变更条目上限(超过就截断并标 `truncated`)。 */
|
|
47
|
+
export const MAX_CHANGED_FILES = 200
|
|
48
|
+
/** 下发到面板的变更清单上限(条目上限是为了载荷体积,与上面的解析上限不是一回事)。 */
|
|
49
|
+
export const MAX_REPORTED_FILES = 30
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* **每次调用都带的全局选项**(在子命令之前)。这三项都是**实测**出来的,不是"照文档加上去":
|
|
53
|
+
*
|
|
54
|
+
* | 选项 | 挡掉什么 | 本机实测(git 2.50.1 / Apple Git-155,2026-10-13) |
|
|
55
|
+
* |---|---|---|
|
|
56
|
+
* | `--no-optional-locks` | `git status` 顺手**重写 `.git/index`**(刷新 stat 缓存 / untracked cache) | 300 文件 + `core.untrackedCache=true` + stat 缓存全过期:裸 `status` **3/3 次**写了 `.git/index`;带这个选项 **0/3 次** |
|
|
57
|
+
* | `-c core.fsmonitor=false` | `core.fsmonitor` 指向**外部钩子**时会**执行那个命令**;为 `true` 时 `git status` 会**拉起 builtin fsmonitor 守护进程**并落 `.git/fsmonitor--daemon` | 钩子形态:裸 `status` 让假钩子**跑了 1 次**(写日志),带覆盖 **0 次**;builtin 形态:裸 `status` 之后 `.git/fsmonitor--daemon` + `.ipc` **存在**,带覆盖**不存在** |
|
|
58
|
+
* | `--no-pager` | 万一有人在全局配了 `pager.status` / `GIT_PAGER`,`status` 会去**起一个分页器进程** | 关掉分页器这条路,与输出是否 TTY 无关 |
|
|
59
|
+
*
|
|
60
|
+
* ⚠️ 这三项是**只读承诺的一部分**:固定 argv + 不走 shell 只挡住"我们主动写",
|
|
61
|
+
* 挡不住 **git 自己被配置牵着去写 / 去起进程**。这一层才是把"只读"真正闭合的地方。
|
|
62
|
+
*/
|
|
63
|
+
export const GIT_GLOBAL_ARGS = ['--no-optional-locks', '--no-pager', '-c', 'core.fsmonitor=false']
|
|
64
|
+
|
|
65
|
+
/** **唯一**允许的两个 git 子命令。改这个数组 = 改安全边界。 */
|
|
66
|
+
export const GIT_STATUS_ARGS = ['status', '--porcelain=v1', '-z', '--untracked-files=all']
|
|
67
|
+
export const GIT_PREFIX_ARGS = ['rev-parse', '--show-prefix']
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* 允许从父进程**继承**的环境变量(白名单)。
|
|
71
|
+
*
|
|
72
|
+
* ⚠️ 这是一条**安全边界**,不是整理癖。`git` 自己承认的一批环境变量能让它读**别的仓库**、
|
|
73
|
+
* 用**别的索引**、往**任意文件**写日志 —— 继承宿主进程的环境就等于把这些开关交给外面:
|
|
74
|
+
*
|
|
75
|
+
* | 变量 | 实测后果(git 2.50.1,2026-10-13,见 `test/git-changes.test.mjs`) |
|
|
76
|
+
* |---|---|
|
|
77
|
+
* | `GIT_DIR` + `GIT_WORK_TREE` | 指向另一个仓库后,`git status` **完全读那个仓库**:本工作区真实存在的改动 `M a.ts` 在结果里**消失** |
|
|
78
|
+
* | `GIT_INDEX_FILE` | 换成一个不存在的索引后,已提交的 `a.ts` 被报成 `D` + `??`,而且结果里混进了**另一个仓库**的文件名 |
|
|
79
|
+
* | `GIT_TRACE` | `git status` 往那个路径**写了 3 行日志**(真实写入) |
|
|
80
|
+
*
|
|
81
|
+
* 所以规则是**白名单 + 前缀**:只继承下面这些「与 Git 配置无关的运行时必需品」,
|
|
82
|
+
* 然后**任何 `GIT_*` 一律不继承**(无论 git 将来新增什么变量,这条规则自动覆盖)。
|
|
83
|
+
* `HOME` / `XDG_CONFIG_HOME` 必须留着 —— 它们决定**全局配置与 ignore 规则**从哪来,
|
|
84
|
+
* 抹掉会让「哪些文件算未跟踪」这个答案跟着变。
|
|
85
|
+
*/
|
|
86
|
+
export const GIT_ENV_ALLOW = Object.freeze([
|
|
87
|
+
// 可执行文件与语言:`PATH` 决定能不能找到 git 与它的子程序;locale 影响 stderr 文案
|
|
88
|
+
// (我们要从 stderr 认「not a git repository」),也影响路径的编码解释。
|
|
89
|
+
'PATH', 'LANG', 'LC_ALL', 'LC_CTYPE', 'LC_MESSAGES',
|
|
90
|
+
// 全局配置与 ignore 规则的来源 —— **不能抹**,抹了未跟踪集合就变了。
|
|
91
|
+
'HOME', 'XDG_CONFIG_HOME', 'USERPROFILE', 'HOMEDRIVE', 'HOMEPATH',
|
|
92
|
+
// 临时目录(git 偶尔要在 TMPDIR 里落临时文件)。
|
|
93
|
+
'TMPDIR', 'TMP', 'TEMP',
|
|
94
|
+
// Windows 上跑起来的必需品(插件在 mac 上开发,但不能让别的平台直接坏掉)。
|
|
95
|
+
'SystemRoot', 'SystemDrive', 'windir', 'ComSpec', 'PATHEXT',
|
|
96
|
+
'APPDATA', 'LOCALAPPDATA', 'PROGRAMDATA', 'ProgramFiles', 'ProgramFiles(x86)',
|
|
97
|
+
])
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* 子进程环境:**白名单 + 我们自己设的只读运行参数**。
|
|
101
|
+
*
|
|
102
|
+
* `GIT_OPTIONAL_LOCKS=0` 是 `--no-optional-locks` 的环境变量等价物(git(1) 明说两者等价),
|
|
103
|
+
* 两条一起给是冗余保险;另外两条把分页器与终端提示钉死。
|
|
104
|
+
*
|
|
105
|
+
* @param {object} [base] - 父进程环境(默认 `process.env`;注入是为了单测)
|
|
106
|
+
* @returns {object} 交给 `spawn` 的环境
|
|
107
|
+
*/
|
|
108
|
+
export function gitEnv(base = process.env) {
|
|
109
|
+
const env = {}
|
|
110
|
+
for (const key of GIT_ENV_ALLOW) {
|
|
111
|
+
if (base && base[key] !== undefined) env[key] = base[key]
|
|
112
|
+
}
|
|
113
|
+
// 前缀规则(**冗余但保留**):就算将来有人往白名单里手滑加了一个 `GIT_*`,这里也会删掉它。
|
|
114
|
+
for (const key of Object.keys(env)) {
|
|
115
|
+
if (key.startsWith('GIT_')) delete env[key]
|
|
116
|
+
}
|
|
117
|
+
return { ...env, ...GIT_ENV }
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* 我们自己显式设置的**只读**运行参数(在白名单之后覆盖上去,所以它们一定生效)。
|
|
122
|
+
*/
|
|
123
|
+
export const GIT_ENV = Object.freeze({
|
|
124
|
+
GIT_OPTIONAL_LOCKS: '0',
|
|
125
|
+
GIT_PAGER: 'cat',
|
|
126
|
+
GIT_TERMINAL_PROMPT: '0',
|
|
127
|
+
})
|
|
128
|
+
/** 这些动词**一个都不许**出现在上面两个数组里(有守卫钉着)。 */
|
|
129
|
+
export const MUTATING_VERBS = [
|
|
130
|
+
'add', 'commit', 'checkout', 'reset', 'clean', 'stash', 'push', 'pull', 'fetch',
|
|
131
|
+
'merge', 'rebase', 'cherry-pick', 'revert', 'rm', 'mv', 'restore', 'switch', 'apply', 'update-index',
|
|
132
|
+
]
|
|
133
|
+
|
|
134
|
+
/** 五种降级原因(`null` = 正常)。客户端按码翻译,宿主不返回文案(AGENTS L1 §6.8)。 */
|
|
135
|
+
export const GIT_REASONS = ['not-a-repo', 'git-missing', 'timeout', 'output-too-large', 'failed-fatal']
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* 一次 `git status` 的原始输出 → 变更条目。**纯函数**,零 I/O、零时钟。
|
|
139
|
+
*
|
|
140
|
+
* 输入是 `--porcelain=v1 -z` 的原文。格式(实测):
|
|
141
|
+
*
|
|
142
|
+
* ```
|
|
143
|
+
* XY PATH\0 普通条目
|
|
144
|
+
* XY NEWPATH\0OLDPATH\0 X 是 R 或 C 时,紧跟一个原路径字段
|
|
145
|
+
* ```
|
|
146
|
+
*
|
|
147
|
+
* @param {string} raw - stdout 原文(含 NUL)
|
|
148
|
+
* @param {{prefix?: string}} [options] - 工作区相对仓库根的前缀(`'src/'` 或 `''`)
|
|
149
|
+
* @returns {Array<{rel: string, x: string, y: string, kinds: string[], origRel?: string, isDir: boolean}>}
|
|
150
|
+
* 按路径字典序(确定性);不在 `prefix` 下的路径**丢弃**
|
|
151
|
+
*/
|
|
152
|
+
export function parseStatusZ(raw, options = {}) {
|
|
153
|
+
const prefix = typeof options.prefix === 'string' ? options.prefix : ''
|
|
154
|
+
const text = typeof raw === 'string' ? raw : ''
|
|
155
|
+
const fields = text.split('\0')
|
|
156
|
+
const out = []
|
|
157
|
+
for (let i = 0; i < fields.length; i += 1) {
|
|
158
|
+
const entry = fields[i]
|
|
159
|
+
// 末段是空串(`-z` 以 NUL 结尾)或半截,跳过
|
|
160
|
+
if (!entry || entry.length < 4) continue
|
|
161
|
+
const x = entry[0]
|
|
162
|
+
const y = entry[1]
|
|
163
|
+
// 第 3 个字符是分隔空格;但 `??` 这类也遵守同一形状(`?? path`)
|
|
164
|
+
if (entry[2] !== ' ') continue
|
|
165
|
+
let path = entry.slice(3)
|
|
166
|
+
let orig = null
|
|
167
|
+
if (x === 'R' || x === 'C') {
|
|
168
|
+
// 重命名 / 复制:下一个 NUL 字段是**原路径**(新在前,实测)
|
|
169
|
+
i += 1
|
|
170
|
+
orig = fields[i] === undefined ? null : fields[i]
|
|
171
|
+
if (orig === '') orig = null
|
|
172
|
+
}
|
|
173
|
+
const trimmed = trimPrefix(path, prefix)
|
|
174
|
+
if (trimmed === null) continue // 同一个仓库里、但工作区之外
|
|
175
|
+
const isDir = trimmed.endsWith('/')
|
|
176
|
+
const rel = isDir ? trimmed.slice(0, -1) : trimmed
|
|
177
|
+
if (!rel) continue
|
|
178
|
+
const origRel = orig === null ? undefined : (trimPrefix(orig, prefix) || undefined)
|
|
179
|
+
out.push({ rel, x, y, kinds: kindsOf(x, y), ...(origRel ? { origRel: isDir ? origRel.replace(/\/$/, '') : origRel } : {}), isDir })
|
|
180
|
+
}
|
|
181
|
+
out.sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0))
|
|
182
|
+
return out
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** 把仓库根基准的路径换成工作区基准;不在工作区内返回 `null`。 */
|
|
186
|
+
function trimPrefix(path, prefix) {
|
|
187
|
+
if (!prefix) return path
|
|
188
|
+
if (!path.startsWith(prefix)) return null
|
|
189
|
+
return path.slice(prefix.length)
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* `XY` 两位 → 人话里的状态集合。
|
|
194
|
+
*
|
|
195
|
+
* X = 索引(HEAD → 索引),Y = 工作区(索引 → 磁盘)。两者**可以同时非空**(`MM`),
|
|
196
|
+
* 所以这里给的是一个**集合**而不是一个枚举 —— 把 `MM` 压成一个标签会丢掉一半事实。
|
|
197
|
+
*
|
|
198
|
+
* @param {string} x - 第一位
|
|
199
|
+
* @param {string} y - 第二位
|
|
200
|
+
* @returns {string[]} 取值来自 `staged` / `unstaged` / `untracked` / `deleted` / `renamed` / `copied` / `added` / `unmerged`
|
|
201
|
+
*/
|
|
202
|
+
export function kindsOf(x, y) {
|
|
203
|
+
if (x === '?' && y === '?') return ['untracked']
|
|
204
|
+
const kinds = []
|
|
205
|
+
// 冲突态(merge / rebase 未解决):`UU` / `AA` / `DD` / `UD` / `DU` / `AU` / `UA`。
|
|
206
|
+
// ⚠️ **这几位不能按「索引侧 / 工作区侧」去读** —— 它们说的是冲突的种类,不是「改好了 / 还没改」。
|
|
207
|
+
// 所以这里**直接返回**,不再补 `staged` / `unstaged`:对一个冲突文件说「已暂存 + 未暂存」
|
|
208
|
+
// 是错的(写完当场被守卫抓到过一次)。`DD` 那种**确实同时是删除**,所以 `deleted` 照旧给。
|
|
209
|
+
const unmerged = x === 'U' || y === 'U' || (x === 'A' && y === 'A') || (x === 'D' && y === 'D')
|
|
210
|
+
if (x === 'D' || y === 'D') kinds.push('deleted')
|
|
211
|
+
if (unmerged) {
|
|
212
|
+
kinds.push('unmerged')
|
|
213
|
+
return kinds
|
|
214
|
+
}
|
|
215
|
+
if (x === 'A') kinds.push('added')
|
|
216
|
+
if (x === 'R') kinds.push('renamed')
|
|
217
|
+
if (x === 'C') kinds.push('copied')
|
|
218
|
+
// X 侧 = 索引相对 HEAD 的变化;Y 侧 = 工作区相对索引的变化。两者可以同时成立(`MM`)。
|
|
219
|
+
if (x !== ' ' && x !== '?') kinds.push('staged')
|
|
220
|
+
if (y !== ' ' && y !== '?') kinds.push('unstaged')
|
|
221
|
+
return kinds
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* 默认的 `exec`:`spawn('git', args)` + 两个上限。**不走 shell**。
|
|
226
|
+
*
|
|
227
|
+
* @param {string[]} args - argv(第一个元素是子命令)
|
|
228
|
+
* @param {{cwd: string, timeoutMs?: number, maxBytes?: number}} options
|
|
229
|
+
* @returns {Promise<{code: number|null, stdout: string, stderr: string, killed: null|'timeout'|'too-large'}>}
|
|
230
|
+
*/
|
|
231
|
+
export function spawnGit(args, options) {
|
|
232
|
+
const timeoutMs = Number(options && options.timeoutMs) > 0 ? Number(options.timeoutMs) : GIT_TIMEOUT_MS
|
|
233
|
+
const maxBytes = Number(options && options.maxBytes) > 0 ? Number(options.maxBytes) : GIT_MAX_BYTES
|
|
234
|
+
return new Promise((resolve) => {
|
|
235
|
+
let child
|
|
236
|
+
try {
|
|
237
|
+
// ⚠️ 全局选项**必须拼在子命令之前** —— `git status --no-optional-locks` 不是合法写法。
|
|
238
|
+
child = spawn('git', [...GIT_GLOBAL_ARGS, ...args], {
|
|
239
|
+
cwd: options.cwd,
|
|
240
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
241
|
+
// ⚠️ **不是** `{...process.env, ...GIT_ENV}` —— 继承宿主环境会把 `GIT_DIR` /
|
|
242
|
+
// `GIT_INDEX_FILE` / `GIT_TRACE` 这些开关一起带进来(见 `GIT_ENV_ALLOW` 的表)。
|
|
243
|
+
env: gitEnv(),
|
|
244
|
+
})
|
|
245
|
+
} catch (error) {
|
|
246
|
+
resolve({ code: null, stdout: '', stderr: String((error && error.message) || error), killed: null, spawnError: true })
|
|
247
|
+
return
|
|
248
|
+
}
|
|
249
|
+
let stdout = ''
|
|
250
|
+
let stderr = ''
|
|
251
|
+
let killed = null
|
|
252
|
+
let bytes = 0
|
|
253
|
+
let settled = false
|
|
254
|
+
const finish = (result) => {
|
|
255
|
+
if (settled) return
|
|
256
|
+
settled = true
|
|
257
|
+
clearTimeout(timer)
|
|
258
|
+
resolve({ ...result, killed })
|
|
259
|
+
}
|
|
260
|
+
const timer = setTimeout(() => { killed = 'timeout'; try { child.kill('SIGKILL') } catch { /* 已经没了 */ } }, timeoutMs)
|
|
261
|
+
child.stdout.on('data', (chunk) => {
|
|
262
|
+
if (killed) return
|
|
263
|
+
bytes += chunk.length
|
|
264
|
+
if (bytes > maxBytes) {
|
|
265
|
+
killed = 'too-large'
|
|
266
|
+
try { child.kill('SIGKILL') } catch { /* 已经没了 */ }
|
|
267
|
+
return
|
|
268
|
+
}
|
|
269
|
+
stdout += chunk.toString('utf8')
|
|
270
|
+
})
|
|
271
|
+
child.stderr.on('data', (chunk) => { stderr += chunk.toString('utf8').slice(0, 4096) })
|
|
272
|
+
child.on('error', (error) => {
|
|
273
|
+
finish({ code: null, stdout, stderr, spawnError: true, message: String((error && error.message) || error) })
|
|
274
|
+
})
|
|
275
|
+
child.on('close', (code) => { finish({ code, stdout, stderr, spawnError: false }) })
|
|
276
|
+
})
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** 把一次 exec 的结果收敛成「成功 / 某个 reason」,**绝不抛**。 */
|
|
280
|
+
function reasonOf(result) {
|
|
281
|
+
if (!result) return 'failed-fatal'
|
|
282
|
+
if (result.spawnError) return 'git-missing'
|
|
283
|
+
if (result.killed === 'timeout') return 'timeout'
|
|
284
|
+
if (result.killed === 'too-large') return 'output-too-large'
|
|
285
|
+
if (result.code !== 0) {
|
|
286
|
+
const err = String(result.stderr || '')
|
|
287
|
+
if (/not a git repository/i.test(err)) return 'not-a-repo'
|
|
288
|
+
return 'failed-fatal'
|
|
289
|
+
}
|
|
290
|
+
return null
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* 造一个**带缓存**的 Git 读取器。
|
|
295
|
+
*
|
|
296
|
+
* 注入 `exec` 是为了可测:测试给它一个纯函数(返回固定 stdout),于是解析、分类、
|
|
297
|
+
* 降级三条路径都能确定性复现,不需要真的建仓库。
|
|
298
|
+
*
|
|
299
|
+
* @param {{exec?: Function, now?: Function, ttlMs?: number, prefixTtlMs?: number}} [options]
|
|
300
|
+
* @returns {{read: (root: string) => Promise<object>, reset: Function}}
|
|
301
|
+
*/
|
|
302
|
+
export function createGitReader(options = {}) {
|
|
303
|
+
const exec = typeof options.exec === 'function' ? options.exec : spawnGit
|
|
304
|
+
const now = typeof options.now === 'function' ? options.now : () => Date.now()
|
|
305
|
+
const ttlMs = Number(options.ttlMs) > 0 ? Number(options.ttlMs) : GIT_CACHE_TTL_MS
|
|
306
|
+
const prefixTtlMs = Number(options.prefixTtlMs) > 0 ? Number(options.prefixTtlMs) : GIT_PREFIX_TTL_MS
|
|
307
|
+
|
|
308
|
+
/** root → {at, prefix};`prefix: null` = 这个 root 不是 git 工作区(**也要缓存**,否则每次轮询都白跑一条 git)。 */
|
|
309
|
+
const prefixCache = new Map()
|
|
310
|
+
/** root → {at, result} */
|
|
311
|
+
const resultCache = new Map()
|
|
312
|
+
/** root → 进行中的 Promise(并发的两轮轮询共用同一次 git 调用)。 */
|
|
313
|
+
const inflight = new Map()
|
|
314
|
+
|
|
315
|
+
const prefixOf = async (root) => {
|
|
316
|
+
const hit = prefixCache.get(root)
|
|
317
|
+
if (hit && now() - hit.at < prefixTtlMs) return hit.prefix
|
|
318
|
+
const res = await exec(GIT_PREFIX_ARGS, { cwd: root, timeoutMs: GIT_TIMEOUT_MS, maxBytes: 64 * 1024 })
|
|
319
|
+
const reason = reasonOf(res)
|
|
320
|
+
// ⚠️ 失败也缓存:`not-a-repo` 的工作区不该每 8 秒重新问一次「你是不是仓库」
|
|
321
|
+
const prefix = reason ? null : String(res.stdout || '').replace(/\r?\n$/, '').trim()
|
|
322
|
+
prefixCache.set(root, { at: now(), prefix, reason: reason || null })
|
|
323
|
+
return prefix
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
const read = async (root) => {
|
|
327
|
+
const key = String(root || '')
|
|
328
|
+
const cached = resultCache.get(key)
|
|
329
|
+
if (cached && now() - cached.at < ttlMs) return cached.result
|
|
330
|
+
if (inflight.has(key)) return inflight.get(key)
|
|
331
|
+
const task = (async () => {
|
|
332
|
+
const prefix = await prefixOf(key)
|
|
333
|
+
const prefixHit = prefixCache.get(key)
|
|
334
|
+
if (prefix === null) {
|
|
335
|
+
return { available: false, reason: prefixHit && prefixHit.reason ? prefixHit.reason : 'not-a-repo', files: [], filesTotal: 0, truncated: false }
|
|
336
|
+
}
|
|
337
|
+
const res = await exec(GIT_STATUS_ARGS, { cwd: key, timeoutMs: GIT_TIMEOUT_MS, maxBytes: GIT_MAX_BYTES })
|
|
338
|
+
const reason = reasonOf(res)
|
|
339
|
+
if (reason) {
|
|
340
|
+
return { available: false, reason, files: [], filesTotal: 0, truncated: false }
|
|
341
|
+
}
|
|
342
|
+
const all = parseStatusZ(res.stdout, { prefix })
|
|
343
|
+
const truncated = all.length > MAX_CHANGED_FILES
|
|
344
|
+
const files = truncated ? all.slice(0, MAX_CHANGED_FILES) : all
|
|
345
|
+
return { available: true, reason: null, files, filesTotal: files.length, truncated }
|
|
346
|
+
})().then((result) => {
|
|
347
|
+
resultCache.set(key, { at: now(), result })
|
|
348
|
+
inflight.delete(key)
|
|
349
|
+
return result
|
|
350
|
+
}).catch(() => {
|
|
351
|
+
inflight.delete(key)
|
|
352
|
+
// 兜底:这一层**绝不抛**(同 `semantic.js` 的纪律)
|
|
353
|
+
return { available: false, reason: 'failed-fatal', files: [], filesTotal: 0, truncated: false }
|
|
354
|
+
})
|
|
355
|
+
inflight.set(key, task)
|
|
356
|
+
return task
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
return {
|
|
360
|
+
read,
|
|
361
|
+
/** 仅供测试 / 显式刷新:清掉两种缓存。 */
|
|
362
|
+
reset() { prefixCache.clear(); resultCache.clear(); inflight.clear() },
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/** 进程内共享一份读取器(同 `control.js` / `semantic.js` 的理由:多次加载只留一个句柄)。 */
|
|
367
|
+
const SHARED = Symbol.for('dsh-knit.git')
|
|
368
|
+
/**
|
|
369
|
+
* @param {object} [backendLike] - 任意对象(这里只借它当挂点,不读它的字段)
|
|
370
|
+
* @param {{exec?: Function}} [options]
|
|
371
|
+
* @returns {object} Git 读取器
|
|
372
|
+
*/
|
|
373
|
+
export function sharedGitReader(backendLike, options = {}) {
|
|
374
|
+
const holder = backendLike && typeof backendLike === 'object' ? backendLike : globalThis
|
|
375
|
+
if (!holder[SHARED]) holder[SHARED] = createGitReader(options)
|
|
376
|
+
return holder[SHARED]
|
|
377
|
+
}
|