dsh-svn-review 0.2.2 → 0.2.4

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/lib/index.js CHANGED
@@ -197,6 +197,10 @@ export function apply(ctx) {
197
197
  type: 'object',
198
198
  description: '自动识别出的技术栈摘要;详情用 project_profile',
199
199
  },
200
+ engine: {
201
+ type: 'string',
202
+ description: 'node=本进程直接读文件;python=本进程读到的是加密容器,内容哈希由子进程完成',
203
+ },
200
204
  },
201
205
  },
202
206
  render: (_args, value) => {
@@ -209,6 +213,13 @@ export function apply(ctx) {
209
213
  `工作副本 ${value.root}(基线 r${value.revision ?? '?'}):`
210
214
  + `M=${counts.M} A=${counts.A} D=${counts.D} !=${counts['!']} C=${counts.C}`,
211
215
  )
216
+ if (value.engine === 'python') {
217
+ // 不解释清楚,使用者会以为工具在乱报——正是这条让上次的审查跑偏了 12 分钟。
218
+ lines.push(
219
+ ' 说明:本进程读到的内容与基线对不上(多半是透明加密客户端只对白名单进程返回明文),'
220
+ + '已交给 python 子进程复核,结论与 svn status 一致。',
221
+ )
222
+ }
212
223
  // 清单过长会挤占上下文,而且一个真实的变更集不该有上千个文件。
213
224
  // 截断但明确告知,不要静默吞掉。
214
225
  const shown = value.files.slice(0, 300)
@@ -0,0 +1,158 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """当宿主进程读到的是加密容器时,用子进程把变更集重算一遍。
4
+
5
+ 为什么需要这个文件
6
+ ------------------
7
+ 有些公司的透明加密客户端(文件头形如 `%TSD-Header-…`)只对白名单进程返回明文。
8
+ DeepSeek Harness 跑在 Electron 里,通常不在白名单内:`fs.readFileSync` 拿到的是密文,
9
+ 尺寸也比明文大。于是每个文件的 SHA-1 都和 `.svn/pristine` 里的基线对不上,
10
+ 整个工作副本会被判成"全部修改"——一次性几千个假 M,审查就此跑偏。
11
+
12
+ `python.exe` / `powershell.exe` 往往在白名单里,读到的就是明文。所以这一步交给它们做:
13
+ 本进程只负责判断"我读到的是不是密文",真正的哈希由子进程算。
14
+
15
+ 用法
16
+ ----
17
+ python wc-fallback.py <工作副本根> <输出 json 路径>
18
+
19
+ stdout 不用(宿主可能拿不到管道),结果写进输出文件。失败时输出
20
+ `{"error": "原因"}`,退出码非 0 由调用方处理。
21
+ """
22
+
23
+ import hashlib
24
+ import json
25
+ import os
26
+ import sqlite3
27
+ import sys
28
+
29
+ CHECKSUM_PREFIX = '$sha1$'
30
+
31
+
32
+ def sha1_of(path, chunk=1 << 20):
33
+ digest = hashlib.sha1()
34
+ with open(path, 'rb') as handle:
35
+ while True:
36
+ block = handle.read(chunk)
37
+ if not block:
38
+ break
39
+ digest.update(block)
40
+ return digest.hexdigest()
41
+
42
+
43
+ def checksum_hex(checksum):
44
+ if not isinstance(checksum, str):
45
+ return None
46
+ if checksum.startswith(CHECKSUM_PREFIX):
47
+ return checksum[len(CHECKSUM_PREFIX):]
48
+ return checksum
49
+
50
+
51
+ def to_posix(path):
52
+ return path.replace('\\', '/')
53
+
54
+
55
+ def read_change_set(root):
56
+ db_path = os.path.join(root, '.svn', 'wc.db')
57
+ if not os.path.exists(db_path):
58
+ raise RuntimeError('没有找到 .svn/wc.db:%s' % db_path)
59
+
60
+ connection = sqlite3.connect('file:%s?mode=ro' % to_posix(db_path), uri=True)
61
+ try:
62
+ row = connection.execute('SELECT root FROM REPOSITORY LIMIT 1').fetchone()
63
+ repository = row[0] if row else None
64
+ row = connection.execute(
65
+ 'SELECT MAX(revision) FROM NODES WHERE op_depth = 0').fetchone()
66
+ revision = row[0] if row else None
67
+
68
+ base_files = connection.execute(
69
+ """
70
+ SELECT local_relpath, checksum, translated_size, last_mod_time
71
+ FROM NODES
72
+ WHERE op_depth = 0 AND kind = 'file' AND presence = 'normal'
73
+ """).fetchall()
74
+
75
+ working_nodes = connection.execute(
76
+ 'SELECT local_relpath, op_depth, presence, kind FROM NODES WHERE op_depth > 0'
77
+ ).fetchall()
78
+
79
+ conflicts = connection.execute(
80
+ """
81
+ SELECT local_relpath FROM ACTUAL_NODE
82
+ WHERE conflict_old IS NOT NULL OR conflict_new IS NOT NULL
83
+ OR tree_conflict_data IS NOT NULL OR conflict_data IS NOT NULL
84
+ """
85
+ ).fetchall()
86
+ finally:
87
+ connection.close()
88
+
89
+ counts = {'M': 0, 'A': 0, 'D': 0, '!': 0, 'C': 0}
90
+ files = []
91
+
92
+ for relpath, checksum, _translated_size, _last_mod_time in base_files:
93
+ absolute = os.path.join(root, relpath)
94
+ if not os.path.exists(absolute):
95
+ files.append({'status': '!', 'path': relpath})
96
+ counts['!'] += 1
97
+ continue
98
+ if not os.path.isfile(absolute):
99
+ continue
100
+ try:
101
+ size = os.path.getsize(absolute)
102
+ actual = sha1_of(absolute)
103
+ except OSError:
104
+ files.append({'status': '!', 'path': relpath})
105
+ counts['!'] += 1
106
+ continue
107
+ baseline = checksum_hex(checksum)
108
+ # 这里刻意不看 translated_size / last_mod_time 的快路径:
109
+ # 正因为快照字段和密文字节对不上,才走到这个脚本。
110
+ if baseline is not None and actual == baseline:
111
+ continue
112
+ files.append({'status': 'M', 'path': relpath, 'size': size})
113
+ counts['M'] += 1
114
+
115
+ for relpath, _op_depth, presence, kind in working_nodes:
116
+ if kind != 'file':
117
+ continue
118
+ if presence == 'normal':
119
+ files.append({'status': 'A', 'path': relpath})
120
+ counts['A'] += 1
121
+ elif presence in ('base-deleted', 'delete'):
122
+ files.append({'status': 'D', 'path': relpath})
123
+ counts['D'] += 1
124
+
125
+ for (relpath,) in conflicts:
126
+ files.append({'status': 'C', 'path': relpath})
127
+ counts['C'] += 1
128
+
129
+ files.sort(key=lambda item: item['path'])
130
+ return {
131
+ 'root': root,
132
+ 'repository': repository,
133
+ 'revision': revision,
134
+ 'files': files,
135
+ 'counts': counts,
136
+ }
137
+
138
+
139
+ def main():
140
+ if len(sys.argv) < 3:
141
+ sys.stderr.write('usage: wc-fallback.py <working-copy-root> <output-json>\n')
142
+ return 2
143
+
144
+ root = os.path.abspath(sys.argv[1])
145
+ output = sys.argv[2]
146
+
147
+ try:
148
+ payload = read_change_set(root)
149
+ except Exception as error: # noqa: BLE001 - 任何失败都要变成可读的 JSON
150
+ payload = {'error': str(error)}
151
+
152
+ with open(output, 'w', encoding='utf-8') as handle:
153
+ json.dump(payload, handle)
154
+ return 0 if 'error' not in payload else 1
155
+
156
+
157
+ if __name__ == '__main__':
158
+ sys.exit(main())
package/lib/wc.js CHANGED
@@ -8,9 +8,12 @@
8
8
  * 这样设计是为了解决一个很具体的处境:机器上只装了 TortoiseSVN 的图形壳,
9
9
  * `svn.exe` 不在 PATH 里,而 Agent 又必须拿到"这次到底改了哪些文件"。
10
10
  */
11
+ import { spawnSync } from 'node:child_process'
11
12
  import { createHash } from 'node:crypto'
12
- import { existsSync, statSync, readFileSync } from 'node:fs'
13
+ import { closeSync, existsSync, openSync, readdirSync, readSync, readFileSync, statSync, unlinkSync } from 'node:fs'
14
+ import { tmpdir } from 'node:os'
13
15
  import { dirname, isAbsolute, join, resolve } from 'node:path'
16
+ import { fileURLToPath } from 'node:url'
14
17
 
15
18
  /** SVN 用 `$sha1$<40hex>` 表示校验和。 */
16
19
  const CHECKSUM_PREFIX = '$sha1$'
@@ -41,6 +44,125 @@ function sha1OfFile(absolutePath) {
41
44
  return createHash('sha1').update(readFileSync(absolutePath)).digest('hex')
42
45
  }
43
46
 
47
+ /**
48
+ * 用子进程重算变更集的脚本。
49
+ *
50
+ * 宿主读到密文时,哈希只能交给白名单里的解释器做;python 比 powershell 快一个量级,
51
+ * 所以优先 python。脚本把结果写成 JSON 文件而不是走管道——有些受限环境下
52
+ * 管道根本建不起来,读文件最稳。
53
+ */
54
+ const FALLBACK_SCRIPT = fileURLToPath(new URL('./wc-fallback.py', import.meta.url))
55
+
56
+ /** 挑探针文件时只认这些扩展名,避免拿图片/压缩包误判。 */
57
+ const TEXT_EXTENSIONS = new Set([
58
+ '.java', '.kt', '.kts', '.scala', '.cs', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp',
59
+ '.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.vue', '.ets', '.lua',
60
+ '.md', '.txt', '.json', '.xml', '.yml', '.yaml', '.gradle', '.properties',
61
+ '.sql', '.py', '.go', '.rs', '.php', '.rb', '.swift', '.sh', '.bat', '.html', '.css',
62
+ ])
63
+
64
+ function extensionOf(relpath) {
65
+ const dot = relpath.lastIndexOf('.')
66
+ return dot === -1 ? '' : relpath.slice(dot).toLowerCase()
67
+ }
68
+
69
+ /**
70
+ * 判断"本进程读到的是不是明文"。
71
+ *
72
+ * 有些公司的透明加密客户端(文件头形如 `%TSD-Header-…`)只对白名单进程返回明文。
73
+ * DeepSeek Harness 跑在 Electron 里,通常不在白名单内:`readFileSync` 拿到的是密文,
74
+ * 尺寸也比明文大。于是每个文件的 SHA-1 都和 `.svn/pristine` 的基线对不上,
75
+ * 整个工作副本会被判成"全部修改",一次性几千个假 M —— 审查就此跑偏。
76
+ *
77
+ * 判据只用两样最不会误伤源码的东西:NUL 字节,和已知的加密文件头。
78
+ * 刻意不用"能否按 UTF-8 解码",因为 GBK 编码的源码会被误判成加密。
79
+ */
80
+ function readsCiphertext(root, baseFiles) {
81
+ const textFiles = baseFiles.filter((node) => TEXT_EXTENSIONS.has(extensionOf(node.relpath)))
82
+ if (textFiles.length === 0) return false
83
+
84
+ // 均匀取样,不能只取前几个。工作副本开头往往是 .gitignore / build.gradle 这类配置,
85
+ // 加密客户端经常不处理它们(有的库能读出配置、却读不出源码),
86
+ // 只取前缀会稳定漏判——0.2.3 第一版就是这么没生效的。
87
+ const step = Math.max(1, Math.floor(textFiles.length / 12))
88
+ const probe = []
89
+ for (let index = 0; index < textFiles.length && probe.length < 12; index += step) {
90
+ probe.push(textFiles[index])
91
+ }
92
+
93
+ for (const node of probe) {
94
+ let head
95
+ try {
96
+ const fd = openSync(join(root, node.relpath), 'r')
97
+ try {
98
+ const buffer = Buffer.alloc(32)
99
+ head = buffer.subarray(0, readSync(fd, buffer, 0, 32, 0))
100
+ } finally {
101
+ closeSync(fd)
102
+ }
103
+ } catch {
104
+ continue
105
+ }
106
+ if (head.length === 0) continue
107
+ if (head.includes(0)) return true
108
+ if (head.toString('latin1').includes('TSD-Header')) return true
109
+ }
110
+
111
+ return false
112
+ }
113
+
114
+ /**
115
+ * 交给 python 算一遍。拿不到结果时返回 null,由调用方决定怎么报错。
116
+ * @returns {{root: string, files: unknown[], counts: Record<string, number>} | null}
117
+ */
118
+ function runFallback(root) {
119
+ const output = join(tmpdir(), `dsh-svn-review-${process.pid}-${Date.now()}.json`)
120
+ try {
121
+ for (const interpreter of interpreters()) {
122
+ const result = spawnSync(interpreter, [FALLBACK_SCRIPT, root, output], {
123
+ timeout: 300_000,
124
+ windowsHide: true,
125
+ // 不用管道:受限环境下子进程建管道会失败,结果走文件。
126
+ stdio: 'ignore',
127
+ })
128
+ if (result.error !== undefined || result.status !== 0) continue
129
+ if (!existsSync(output)) continue
130
+
131
+ const payload = JSON.parse(readFileSync(output, 'utf8'))
132
+ if (typeof payload.error === 'string') throw new Error(payload.error)
133
+ return { ...payload, engine: 'python' }
134
+ }
135
+ } finally {
136
+ try {
137
+ unlinkSync(output)
138
+ } catch {
139
+ // 删不掉就算了,临时目录里的文件不影响结果。
140
+ }
141
+ }
142
+
143
+ return null
144
+ }
145
+
146
+ /**
147
+ * 候选解释器。宿主进程的 PATH 未必和终端一致(从图形界面启动时尤其如此),
148
+ * 所以除了 PATH 里的名字,再补上 Windows 上最常见的安装位置。
149
+ */
150
+ function interpreters() {
151
+ const candidates = ['python', 'python3', 'py']
152
+ const localAppData = process.env.LOCALAPPDATA
153
+ if (typeof localAppData === 'string' && localAppData.length > 0) {
154
+ const base = join(localAppData, 'Programs', 'Python')
155
+ try {
156
+ for (const entry of readdirSync(base)) {
157
+ if (/^Python\d+$/i.test(entry)) candidates.push(join(base, entry, 'python.exe'))
158
+ }
159
+ } catch {
160
+ // 没装就跳过,不值得报错。
161
+ }
162
+ }
163
+ return candidates
164
+ }
165
+
44
166
  /**
45
167
  * 把 node:sqlite 变成可选依赖。
46
168
  *
@@ -100,6 +222,18 @@ export async function readChangeSet(start, options = {}) {
100
222
  FROM NODES WHERE op_depth > 0
101
223
  `).all()
102
224
 
225
+ // 先确认本进程读到的是不是明文。不是的话,内容哈希必须交给子进程算,
226
+ // 否则整份工作副本会被判成"全改"(原因见 readsCiphertext)。
227
+ if (options.forceFallback === true || readsCiphertext(root, baseFiles)) {
228
+ const delegated = runFallback(root)
229
+ if (delegated !== null) return delegated
230
+ throw new Error(
231
+ `本进程读到的是加密容器(${root} 下的源码文件头不是明文),`
232
+ + '无法用内容哈希判断改动,也没找到可用的 python 来解释码后的内容。'
233
+ + '请把 DeepSeek Harness 加入加密客户端白名单后重试。',
234
+ )
235
+ }
236
+
103
237
  const files = []
104
238
  const counts = { M: 0, A: 0, D: 0, '!': 0, C: 0 }
105
239
 
@@ -168,6 +302,16 @@ export async function readChangeSet(start, options = {}) {
168
302
  counts.C += 1
169
303
  }
170
304
 
305
+ // 第二道保险,与加密客户端用什么格式无关:
306
+ // "几乎整份工作副本都被改过"这个结论本身不可信——正常的提交不会动掉十分之一的文件。
307
+ // 与其把几千个疑点丢给审查者去逐个核实(那会烧掉十几分钟),不如交给子进程复核一次:
308
+ // 子进程读到的是明文,它给出的才是真值。
309
+ const implausible = files.length > Math.max(50, Math.floor(baseFiles.length * 0.1))
310
+ if (implausible) {
311
+ const delegated = runFallback(root)
312
+ if (delegated !== null) return delegated
313
+ }
314
+
171
315
  files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))
172
316
 
173
317
  return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-svn-review",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "displayName": "DSH SVN Review",
5
5
  "description": "SVN change-set scoping plus language and version detection for DeepSeek Harness code review: reads .svn/wc.db directly (no svn.exe), pins down the project language and version, and hands over the matching review rules so findings are judged by that language instead of generic ones.",
6
6
  "keywords": [