dsh-svn-review 0.2.2 → 0.2.3

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, 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,97 @@ 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 probe = baseFiles
82
+ .filter((node) => TEXT_EXTENSIONS.has(extensionOf(node.relpath)))
83
+ .slice(0, 6)
84
+
85
+ for (const node of probe) {
86
+ let head
87
+ try {
88
+ const fd = openSync(join(root, node.relpath), 'r')
89
+ try {
90
+ const buffer = Buffer.alloc(32)
91
+ head = buffer.subarray(0, readSync(fd, buffer, 0, 32, 0))
92
+ } finally {
93
+ closeSync(fd)
94
+ }
95
+ } catch {
96
+ continue
97
+ }
98
+ if (head.length === 0) continue
99
+ if (head.includes(0)) return true
100
+ if (head.toString('latin1').includes('TSD-Header')) return true
101
+ }
102
+
103
+ return false
104
+ }
105
+
106
+ /**
107
+ * 交给 python 算一遍。拿不到结果时返回 null,由调用方决定怎么报错。
108
+ * @returns {{root: string, files: unknown[], counts: Record<string, number>} | null}
109
+ */
110
+ function runFallback(root) {
111
+ const output = join(tmpdir(), `dsh-svn-review-${process.pid}-${Date.now()}.json`)
112
+ try {
113
+ for (const interpreter of ['python', 'python3', 'py']) {
114
+ const result = spawnSync(interpreter, [FALLBACK_SCRIPT, root, output], {
115
+ timeout: 300_000,
116
+ windowsHide: true,
117
+ // 不用管道:受限环境下子进程建管道会失败,结果走文件。
118
+ stdio: 'ignore',
119
+ })
120
+ if (result.error !== undefined || result.status !== 0) continue
121
+ if (!existsSync(output)) continue
122
+
123
+ const payload = JSON.parse(readFileSync(output, 'utf8'))
124
+ if (typeof payload.error === 'string') throw new Error(payload.error)
125
+ return { ...payload, engine: 'python' }
126
+ }
127
+ } finally {
128
+ try {
129
+ unlinkSync(output)
130
+ } catch {
131
+ // 删不掉就算了,临时目录里的文件不影响结果。
132
+ }
133
+ }
134
+
135
+ return null
136
+ }
137
+
44
138
  /**
45
139
  * 把 node:sqlite 变成可选依赖。
46
140
  *
@@ -100,6 +194,18 @@ export async function readChangeSet(start, options = {}) {
100
194
  FROM NODES WHERE op_depth > 0
101
195
  `).all()
102
196
 
197
+ // 先确认本进程读到的是不是明文。不是的话,内容哈希必须交给子进程算,
198
+ // 否则整份工作副本会被判成"全改"(原因见 readsCiphertext)。
199
+ if (options.forceFallback === true || readsCiphertext(root, baseFiles)) {
200
+ const delegated = runFallback(root)
201
+ if (delegated !== null) return delegated
202
+ throw new Error(
203
+ `本进程读到的是加密容器(${root} 下的源码文件头不是明文),`
204
+ + '无法用内容哈希判断改动,也没找到可用的 python 来解释码后的内容。'
205
+ + '请把 DeepSeek Harness 加入加密客户端白名单后重试。',
206
+ )
207
+ }
208
+
103
209
  const files = []
104
210
  const counts = { M: 0, A: 0, D: 0, '!': 0, C: 0 }
105
211
 
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.3",
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": [