@feng0531/dsh-code-review 0.85.1 → 0.85.5
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 +20 -0
- package/DEVELOPMENT.md +10 -2
- package/README.md +1 -1
- package/RELEASE-NOTES.md +13 -11
- package/index.mjs +2 -1
- package/package.json +1 -1
- package/src/anchor-correction.mjs +1 -1
- package/src/class-bindings.mjs +3 -0
- package/src/content.mjs +19 -4
- package/src/coverage-followup.mjs +1 -1
- package/src/coverage-plan.mjs +1 -1
- package/src/cpp-relations.mjs +1 -1
- package/src/csharp-context.mjs +5 -1
- package/src/dsh-model.mjs +21 -3
- package/src/git-history.mjs +1 -1
- package/src/git.mjs +8 -2
- package/src/import-call-sites.mjs +4 -1
- package/src/primary-input.mjs +3 -2
- package/src/process.mjs +11 -2
- package/src/project-execution.mjs +1 -1
- package/src/project-review-service.mjs +2 -2
- package/src/project-snapshot.mjs +1 -1
- package/src/review-jobs.mjs +6 -3
- package/src/review.mjs +6 -6
- package/src/snapshot.mjs +7 -1
- package/src/source-segments.mjs +1 -0
- package/src/svn-caller-index.mjs +8 -1
- package/src/svn-history-callers.mjs +2 -1
- package/src/svn-replacement-tree.mjs +12 -2
- package/src/svn-working-special.mjs +4 -2
- package/src/synthesis-evidence.mjs +20 -4
- package/src/tracked-context.mjs +4 -1
- package/src/window-synthesis.mjs +4 -2
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,26 @@
|
|
|
2
2
|
|
|
3
3
|
本文件介绍对使用者有意义的变化。安装与参数见 [README](README.md),本次发布正文见 [发布说明](RELEASE-NOTES.md)。历史提交和安装包保留在 [GitHub Releases](https://github.com/f-e-n-g-0531/dsh-code-review/releases);本文不把开发日志当作功能介绍。
|
|
4
4
|
|
|
5
|
+
## 0.85.5 — 凭据来源保护与审核边界修复
|
|
6
|
+
|
|
7
|
+
- SVN 独立替换树在读取正文前检查复制来源及祖先来源,阻断从凭据路径复制到普通目标的内容;调用方扫描不再把带源码扩展名的目录当作文件读取。
|
|
8
|
+
- Git 默认工作区范围合并暂存删除后重建的同路径记录,避免重复文件身份;自动上下文允许精确目录索引导入探测,但不扩大后代正文授权。
|
|
9
|
+
- 暂存区审核复用已选变更作为上下文时,按相同 index 版本验证,不再误与未暂存工作区内容比较。
|
|
10
|
+
- 综合证据接受同一快照、来源和版本侧连续或重叠读取的完整区间覆盖;仍拒绝有缺口、错来源或错版本的证据。
|
|
11
|
+
- 超过 20 个窗口批次时保留全部可执行主窗口及此前成果,单独披露综合受限并保持未完整审核状态,不再使整轮异常退出。
|
|
12
|
+
|
|
13
|
+
## 0.85.4 — 审查正确性、失败恢复与全项目提速
|
|
14
|
+
|
|
15
|
+
`v0.85.2` 因发布说明缺少导航链接、`v0.85.3` 因 Windows 临时目录短路径别名未被新增测试 mock 规范化而未通过 CI,均未发布 npm 或 GitHub Release。本版本补齐链接、规范化测试匹配路径并重新执行完整门禁,不覆盖旧冻结标签、不削弱拒绝断言。
|
|
16
|
+
|
|
17
|
+
- 本地文件打开改为规范路径,核对最初检查、打开前检查和文件句柄的设备号/inode,并复核祖先身份;SVN special 读取后复核祖先身份。这是竞态检测加固,不是原子目录相对打开,不能保证抵御恶意进程精确交换并恢复路径;高对抗场景应使用隔离、不可并发修改的快照。
|
|
18
|
+
- Git 仓库根只去掉结尾换行,不再 `trim()` 掉路径首尾空格。进程在 SIGTERM 后仍不退出时补发 SIGKILL,超时和取消不再永久等待。
|
|
19
|
+
- 超界行锚点不再误判为精确匹配,仍允许按原有证据规则重定位;具名导入允许单个尾随逗号但拒绝空绑定;注册表元数据及工件网络异常按原次数重试。
|
|
20
|
+
- 模型流兼容完整文本块:终态块替换对应增量而非重复拼接,完整块也计入输出预算;模型拒绝值为 null/undefined 时保留已有文件结果。
|
|
21
|
+
- 实例方法提示拒绝构造器名称遮蔽和原型替换;C# 竞争类型按正文而不只按文件名阻止错误唯一性;C++ include 支持关键字后无空白的合法引用。
|
|
22
|
+
- 后台持久化队列失败不再阻断终态保存;成功落盘后释放已结束任务的内存,失败时保留诊断并唤醒等待者。分段参数拒绝非正整数,SVN 历史调用方预算不再信任低报的正文大小。
|
|
23
|
+
- 全项目默认并发从 3 提到允许上限 8。批内主审、检索和复核仍串行,模型调用次数不减少;提供方限流时把 `projectConcurrency` 调低。
|
|
24
|
+
|
|
5
25
|
## 0.85.1 — 模型失败诊断与定向纠正
|
|
6
26
|
|
|
7
27
|
- 修复宿主 error 终态详情读取位置,保留实际 `finish.reason.failure` 中的已知错误码、HTTP 状态和有效重试间隔,便于区分服务失败类别;不新增对鉴权、额度或取消的盲目重试。
|
package/DEVELOPMENT.md
CHANGED
|
@@ -20,9 +20,17 @@
|
|
|
20
20
|
|
|
21
21
|
## 全项目并发与离线速度对照
|
|
22
22
|
|
|
23
|
-
插件配置 `projectConcurrency` 默认为
|
|
23
|
+
插件配置 `projectConcurrency` 默认为 8,范围 1~8;1 为串行回退。仅独立批准批次并行,各批仍有独立检索来源和账本,所有调用与 JSON 纠正共享原执行计数。该上限按单次执行生效,不是全宿主 RPM/TPM 限流器;提供方不支持并发或遇到 429 时应调低。取消/致命检查点错误必须等待全部在途模型清理后释放会话锁,后台 checkpoint 继续使用原串行持久化队列。
|
|
24
24
|
|
|
25
|
-
运行 `node scripts/review-speed-benchmark.mjs` 比较相同 12 个 mock
|
|
25
|
+
运行 `node scripts/review-speed-benchmark.mjs` 比较相同 12 个 mock 批次在串行、旧默认 3 路与新默认 8 路并发下的耗时;脚本模拟每次模型调用 40ms 延迟,不访问网络、不证明真实模型速度或质量。核对工作量、调用数、完成数和输出顺序一致,不把降低覆盖作为加速。
|
|
26
|
+
|
|
27
|
+
### 当前工作树捕获的安全边界
|
|
28
|
+
|
|
29
|
+
本地捕获校验符号链接、规范路径、文件句柄身份及祖先目录身份。Node 的跨平台公开 API 没有原子 beneath/no-symlink 目录相对打开机制,因此这些前后检查只能检测已观察到的替换,不能证明抵御并发恶意进程交换后恢复路径的攻击。需要严格隔离时,应先在不允许并发修改的独立快照中审核;不要把 inode 检查描述为彻底修复 TOCTOU。
|
|
30
|
+
|
|
31
|
+
### 本次全库审核的实测瓶颈
|
|
32
|
+
|
|
33
|
+
407 个文件、34 个批次、3 路并发的历史任务耗时 40 分 37.208 秒,调用模型 778 次,其中 263 次为额外 JSON 重生成(33.8%),另有 9 条阶段响应纠正事件;共 19 个文件失败。471 条 protocol-correction 检查点包含不同纠正阶段和完成事件,不能当成 471 次额外调用。上述数据不提供逐调用耗时,不能据此声称磁盘 I/O 或某一提供方适配层占用了确定比例。新默认并发与完整块兼容修复尚需真实提供方复测,离线模拟只验证调度开销、调用量和结果顺序。
|
|
26
34
|
|
|
27
35
|
## 模型响应失败与诊断
|
|
28
36
|
|
package/README.md
CHANGED
|
@@ -256,7 +256,7 @@ Git / SVN 历史审查也能使用这些参数;依赖和调用方按对应版
|
|
|
256
256
|
|
|
257
257
|
清单上限10000节点,单次选择最多1000节点/16MiB,12节点一批,单文件256KiB;超限明确拒绝,缩小选择后必须重新预览。单次采集共享8MiB元数据内存保护,不按命令条数、插件秒表或模型调用次数中断;耗时受宿主/模型提供方限制,用户可随时取消。SVN为本地已观察清单,稀疏/外部/链接及不支持属性显示限制;不证明仓库远端完整覆盖。
|
|
258
258
|
|
|
259
|
-
全项目审查默认最多 **
|
|
259
|
+
全项目审查默认最多 **8 个独立批次并行**,每批内主审、检索、复核仍按依赖顺序执行;预览和报告的 `execution.batchConcurrency` 显示实际配置。插件配置 `projectConcurrency` 可设为 1~8,设 1 回退串行;遇到模型提供方并发限制或 429,应降低并发。该设置不是 preview 参数,不扩大来源或共享模型调用预算,也不减少模型调用量或承诺 token 成本下降。仅一个批次时不会获得批间加速;实际提速受提供方吞吐、批次均衡及检查点写入影响。
|
|
260
260
|
|
|
261
261
|
对外只交付一份统一最终报告,给出总数、completed、excluded、blocked、pending、去重后的发现及未完成综合阶段;内部批次快照仅供证据追溯,不需要用户拼接报告。completed只表示所选捕获文件已处理,不代表代码正确;排除与阻断从不算完成。代码或清单变化会拒绝旧预览,运行后无法复核则标记outdated。
|
|
262
262
|
|
package/RELEASE-NOTES.md
CHANGED
|
@@ -1,19 +1,21 @@
|
|
|
1
|
-
# v0.85.
|
|
1
|
+
# v0.85.5 发布说明
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
使用方式见 [README](README.md),详细变化见 [变更记录](CHANGELOG.md),发布门禁见 [开发说明](DEVELOPMENT.md)。
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
## 安全修复
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
SVN 独立替换树现在在读取正文前检查复制来源及复制祖先来源,阻断把凭据文件复制到普通目标后绕过来源过滤的路径。限定调用方扫描也会区分目录与普通文件,带 `.js` 等源码扩展名的目录不再令预览整体失败。
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
## 审核正确性与可用性
|
|
10
10
|
|
|
11
|
-
|
|
11
|
+
- Git 默认工作区审核合并暂存删除后重建的同路径记录,保持文件身份唯一。
|
|
12
|
+
- 自动上下文的目录索引导入不再被误判为越界;仍只读取精确选中的候选正文,不授权目录下任意文件。
|
|
13
|
+
- 已选暂存变更同时作为显式上下文时,复用 index 内容并按同侧版本验证,不把尚未暂存的正文混入变更侧。
|
|
14
|
+
- 长编辑分次读取后,综合校验按同一快照、来源及版本侧计算连续覆盖;跨来源、有缺口或错误版本的读取仍不能作为有效证据。
|
|
15
|
+
- 文件分成超过 20 个窗口批次时,主窗口继续审核并保留已有成果;综合受限单独披露,整体仍为部分完成,不再以异常丢失整轮报告。
|
|
12
16
|
|
|
13
|
-
##
|
|
17
|
+
## 验证与边界
|
|
14
18
|
|
|
15
|
-
|
|
19
|
+
本版为六项已复现问题添加回归测试,并执行完整本地测试及隔离安装验证;正式发布须通过同一冻结标签提交的 Ubuntu/Windows × Node.js 22/24 四组 CI、安装包验证和 npm 实际工件一致性门禁。具体执行结果以该标签 CI 和发布工作流为准。
|
|
16
20
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
用法见 [README](README.md),诊断字段与验证方式见 [DEVELOPMENT](DEVELOPMENT.md)。发布不自动安装、升级或重启 DSH;需要用户更新并重新加载插件。
|
|
21
|
+
本版本不保证模型始终输出合法 JSON,不扩大源码读取权限,不自动安装、升级或重启 DSH;更新并重新加载插件后生效。
|
package/index.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { registerBackgroundReview } from './src/background-review.mjs';
|
|
2
2
|
import { createReviewService } from './src/service.mjs';
|
|
3
|
+
import { DEFAULT_PROJECT_CONCURRENCY } from './src/project-execution.mjs';
|
|
3
4
|
import { reviewToolOutput } from './src/tool-view.mjs';
|
|
4
5
|
|
|
5
6
|
export const name = 'dsh-code-review';
|
|
@@ -13,7 +14,7 @@ const EXECUTE_PARAMETERS = { type: 'object', additionalProperties: false, proper
|
|
|
13
14
|
export function apply(ctx, config = {}) {
|
|
14
15
|
// This entry runs only when the host invokes the registered tool.
|
|
15
16
|
// Host tool policy owns permission; do not request a second approval here.
|
|
16
|
-
const service = createReviewService(ctx.llm, { allowModelSending: true, enableRiskPlanning: true, enableBusinessGrouping: true, enableAnchorCorrection: true, projectConcurrency: config.projectConcurrency ??
|
|
17
|
+
const service = createReviewService(ctx.llm, { allowModelSending: true, enableRiskPlanning: true, enableBusinessGrouping: true, enableAnchorCorrection: true, projectConcurrency: config.projectConcurrency ?? DEFAULT_PROJECT_CONCURRENCY, authorize: async () => true });
|
|
17
18
|
ctx.tools.register({
|
|
18
19
|
name: 'code_review_preview', description: PREVIEW_DESCRIPTION, parameters: PREVIEW_PARAMETERS, output: reviewToolOutput,
|
|
19
20
|
async execute(args, exec) { const preview = await service.preview(args, exec); return { json: JSON.stringify(preview), markdown: '' }; },
|
package/package.json
CHANGED
|
@@ -5,7 +5,7 @@ export function correctAnchor(raw, file, changes, {signal}={}) {
|
|
|
5
5
|
if(!raw||raw.fileId!==file.id||a?.kind!=='line'||!['old','new'].includes(a.side)||!Number.isSafeInteger(a.start)||!Number.isSafeInteger(a.end)||a.start<1||a.end<a.start||typeof a.snippet!=='string'||!a.snippet.trim()||a.snippet.length>8000)return result('not-applicable','invalid-anchor');
|
|
6
6
|
const text=(a.side==='old'?file.left:file.right)?.text;if(typeof text!=='string'||Buffer.byteLength(text)>256*1024)return result('not-applicable','source-limit');
|
|
7
7
|
const source=text.replaceAll('\r\n','\n').split('\n'),snippet=a.snippet.replaceAll('\r\n','\n').split('\n');
|
|
8
|
-
if(source.slice(a.start-1,a.end).join('\n')===snippet.join('\n'))return result('unchanged','already-exact');
|
|
8
|
+
if(a.end<=source.length&&source.slice(a.start-1,a.end).join('\n')===snippet.join('\n'))return result('unchanged','already-exact');
|
|
9
9
|
const currentSource = file.reviewMode === 'project' && a.side === 'new';
|
|
10
10
|
if(file.reviewMode === 'project' && !currentSource)return result('rejected','project-requires-new-side');
|
|
11
11
|
if(!currentSource&&(changes?.status!=='changed'||changes.precision!=='exact'||!Array.isArray(raw.attribution?.editIds)||!raw.attribution.editIds.length))return result('rejected','missing-exact-edit');
|
package/src/class-bindings.mjs
CHANGED
|
@@ -121,6 +121,9 @@ export function instanceMethodBindings(lines, importLine, targetText) {
|
|
|
121
121
|
if (assign === null || inst === member || inst === klass || inst === local) continue;
|
|
122
122
|
const newCount = [...caller.matchAll(new RegExp('(^|[^A-Za-z0-9_$])new\\s+' + escapeDollar(local) + '\\s*\\(', 'g'))].length;
|
|
123
123
|
if (newCount !== 1) continue;
|
|
124
|
+
// Without lexical scope resolution only the import and construction may name the class.
|
|
125
|
+
const localToken = boundaryPattern(local, '(?=[^A-Za-z0-9_$]|$)', 'g');
|
|
126
|
+
if (lines.some((line,i) => i + 1 !== importLine && i + 1 !== assign && [...line.matchAll(localToken)].length)) continue;
|
|
124
127
|
const instToken = boundaryPattern(inst, '(?=[^A-Za-z0-9_$]|$)', 'g');
|
|
125
128
|
const instLines = [];
|
|
126
129
|
for (let i = 0; i < lines.length; i++) {
|
package/src/content.mjs
CHANGED
|
@@ -16,6 +16,7 @@ export function decode(bytes) {
|
|
|
16
16
|
if (/[\x00-\x08\x0e-\x1f]/.test(text)) throw new Error('Binary content');
|
|
17
17
|
return { text, hash: hash(bytes), encoding, bytes: bytes.length };
|
|
18
18
|
}
|
|
19
|
+
|
|
19
20
|
export async function readLocal(root, name, { maxFileBytes = 256 * 1024, signal } = {}) {
|
|
20
21
|
relativePath(name);
|
|
21
22
|
assertNonSecretPath(name);
|
|
@@ -24,19 +25,29 @@ export async function readLocal(root, name, { maxFileBytes = 256 * 1024, signal
|
|
|
24
25
|
const canonicalRoot = await realpath(root);
|
|
25
26
|
const filename = path.resolve(canonicalRoot, ...name.split('/'));
|
|
26
27
|
let cursor = canonicalRoot;
|
|
28
|
+
const ancestors = [];
|
|
29
|
+
let expected;
|
|
27
30
|
for (const part of name.split('/')) {
|
|
28
31
|
cursor = path.join(cursor, part);
|
|
29
32
|
const stat = await lstat(cursor);
|
|
30
33
|
if (stat.isSymbolicLink()) throw new Error('Symbolic links and junctions are excluded');
|
|
31
|
-
if (cursor === filename
|
|
34
|
+
if (cursor === filename) {
|
|
35
|
+
if (!stat.isFile()) throw new Error('Not a regular file');
|
|
36
|
+
expected = stat;
|
|
37
|
+
} else {
|
|
38
|
+
if (!stat.isDirectory()) throw new Error('Not a directory');
|
|
39
|
+
ancestors.push({ path: cursor, stat });
|
|
40
|
+
}
|
|
32
41
|
}
|
|
33
42
|
const canonical = await realpath(filename);
|
|
34
43
|
const rel = path.relative(canonicalRoot, canonical);
|
|
35
44
|
if (rel.startsWith('..' + path.sep) || rel === '..' || path.isAbsolute(rel)) throw new Error('Path escapes repository');
|
|
36
|
-
const
|
|
45
|
+
const opened = await lstat(filename);
|
|
46
|
+
if (opened.isSymbolicLink() || !opened.isFile()) throw new Error(opened.isSymbolicLink() ? 'Symbolic links and junctions are excluded' : 'Not a regular file');
|
|
47
|
+
const handle = await open(canonical, 'r');
|
|
37
48
|
try {
|
|
38
49
|
const before = await handle.stat();
|
|
39
|
-
if (!before.isFile()) throw new Error('
|
|
50
|
+
if (!before.isFile() || before.dev !== expected.dev || before.ino !== expected.ino || before.dev !== opened.dev || before.ino !== opened.ino) throw new Error('File changed during capture');
|
|
40
51
|
if (before.size > maxFileBytes) throw new Error('File size limit exceeded');
|
|
41
52
|
const buffer = Buffer.alloc(maxFileBytes + 1);
|
|
42
53
|
let length = 0;
|
|
@@ -47,8 +58,12 @@ export async function readLocal(root, name, { maxFileBytes = 256 * 1024, signal
|
|
|
47
58
|
length += bytesRead;
|
|
48
59
|
}
|
|
49
60
|
if (length > maxFileBytes) throw new Error('File size limit exceeded');
|
|
61
|
+
for (const ancestor of ancestors) {
|
|
62
|
+
const now = await lstat(ancestor.path);
|
|
63
|
+
if (now.isSymbolicLink() || !now.isDirectory() || now.dev !== ancestor.stat.dev || now.ino !== ancestor.stat.ino || now.ctimeMs !== ancestor.stat.ctimeMs) throw new Error('Ancestor changed during capture');
|
|
64
|
+
}
|
|
50
65
|
const after = await handle.stat();
|
|
51
|
-
if (before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs || canonical !== await realpath(filename)) throw new Error('File changed during capture');
|
|
66
|
+
if (before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs || before.ino !== after.ino || canonical !== await realpath(filename)) throw new Error('File changed during capture');
|
|
52
67
|
return decode(buffer.subarray(0, length));
|
|
53
68
|
} finally { await handle.close(); }
|
|
54
69
|
}
|
|
@@ -5,7 +5,7 @@ export function coverageFollowup(report) {
|
|
|
5
5
|
const items = report.files.map(file => {
|
|
6
6
|
if (!file || typeof file.fileId !== 'string' || !file.fileId || ids.has(file.fileId) || typeof file.path !== 'string' || !file.path || paths.has(file.path) || !['completed', 'excluded', 'blocked', 'failed', 'cancelled', 'pending'].includes(file.status)) throw new Error('Invalid coverage file');
|
|
7
7
|
ids.add(file.fileId); paths.add(file.path);
|
|
8
|
-
const incompleteSynthesis=(file.stageFailures??[]).length>0
|
|
8
|
+
const incompleteSynthesis=(file.stageFailures??[]).length>0||!!file.synthesisStatus&&file.synthesisStatus!=='completed';
|
|
9
9
|
const incompleteVerification = report.findings.some(f => f.fileId === file.fileId && ['pending', 'incomplete'].includes(f.verification?.status));
|
|
10
10
|
return { fileId: file.fileId, path: file.path, status: file.status, incompleteVerification,incompleteSynthesis,
|
|
11
11
|
followup: file.status !== 'excluded' && (file.status !== 'completed' || incompleteVerification || incompleteSynthesis) };
|
package/src/coverage-plan.mjs
CHANGED
|
@@ -21,7 +21,7 @@ export function buildCoveragePlan(input, options) {
|
|
|
21
21
|
if (file.eligibility !== 'reviewable') return item;
|
|
22
22
|
const prepared = preparePrimaryInput(input, file, options);
|
|
23
23
|
const riskPlanning = options.enableRiskPlanning === true ? options.skipSmallRiskPlans === true ? riskPlanningDecision([file]) : {required:true,reason:'unconditional'} : {required:false,reason:'disabled'};
|
|
24
|
-
return { ...item, ...prepared.metadata, riskPlanning, status: prepared.budget.fits ? 'ready' : 'input-blocked', minimumCalls: prepared.budget.fits ? ((prepared.batches?.length ?? 1) * (rounds + (riskPlanning.required ? 1 : 0)) + (prepared.synthesis?.
|
|
24
|
+
return { ...item, ...prepared.metadata, riskPlanning, status: prepared.budget.fits ? 'ready' : 'input-blocked', minimumCalls: prepared.budget.fits ? ((prepared.batches?.length ?? 1) * (rounds + (riskPlanning.required ? 1 : 0)) + (prepared.synthesis?.status === 'ready' ? rounds : 0)) : 0 };
|
|
25
25
|
});
|
|
26
26
|
const local = options.enableBusinessGrouping === true ? localBusinessGroups(input.files) : null;
|
|
27
27
|
const groups = [...(options.grouping?.groups ?? [])];
|
package/src/cpp-relations.mjs
CHANGED
|
@@ -22,7 +22,7 @@ export function inferCppRelations(files) {
|
|
|
22
22
|
// Conditional/macro includes are not resolved without a build configuration.
|
|
23
23
|
if (lines.some(line => /^\s*#\s*(?:if|ifdef|ifndef|elif|else|endif|define|undef)\b/.test(line))) continue;
|
|
24
24
|
for (let i=0;i<lines.length;i++) {
|
|
25
|
-
const match = /^\s*#\s*include\s
|
|
25
|
+
const match = /^\s*#\s*include\s*"([^"\\]+)"\s*(?:\/\/.*)?$/.exec(lines[i]);
|
|
26
26
|
if (!match || match[1].startsWith('/') || match[1].includes(':')) continue;
|
|
27
27
|
const targetPath = path.posix.normalize(path.posix.join(path.posix.dirname(file.path),match[1]));
|
|
28
28
|
if (targetPath.startsWith('../') || targetPath === '..') continue;
|
package/src/csharp-context.mjs
CHANGED
|
@@ -20,7 +20,11 @@ export function inferCsharpContext(input, primary) {
|
|
|
20
20
|
if (lines.some((line,j) => j !== i && token.test(line))) continue;
|
|
21
21
|
// Unsupported declarations still compete; filtering them out must not create uniqueness.
|
|
22
22
|
const competitors = contexts.filter(c => typeof c.text !== 'string' || token.test(c.text));
|
|
23
|
-
if (competitors.length !== 1 || input.files.some(f =>
|
|
23
|
+
if (competitors.length !== 1 || input.files.some(f => {
|
|
24
|
+
if(f === primary || !f.path.endsWith('.cs'))return false;
|
|
25
|
+
const text=(side === 'old' ? f.left : f.right)?.text;
|
|
26
|
+
return f.path.split('/').at(-1) === type + '.cs' || typeof text !== 'string' || token.test(text);
|
|
27
|
+
})) continue;
|
|
24
28
|
const candidates = competitors.filter(c => safe(c.text) && namespaceOf(c.text) === ns && !/\busing\b|\bpartial\b|\bvirtual\b|\boverride\b|\binterface\b/.test(c.text));
|
|
25
29
|
const declarations = [];
|
|
26
30
|
for (const context of candidates) {
|
package/src/dsh-model.mjs
CHANGED
|
@@ -37,6 +37,9 @@ export function createDshModel(llm, route, {
|
|
|
37
37
|
signal?.throwIfAborted();
|
|
38
38
|
let output = '';
|
|
39
39
|
let size = 0;
|
|
40
|
+
// Completed blocks are authoritative snapshots, not additional text deltas.
|
|
41
|
+
// Track them by index so block-only streams work without counting snapshots twice.
|
|
42
|
+
const blocks = new Map();
|
|
40
43
|
let finished = false;
|
|
41
44
|
let finishKind = 'missing';
|
|
42
45
|
const diagnostic = () => ({
|
|
@@ -59,10 +62,25 @@ export function createDshModel(llm, route, {
|
|
|
59
62
|
signal?.throwIfAborted();
|
|
60
63
|
if (finished) throw failure('Model emitted data after finish', 'MODEL_PROTOCOL_ERROR');
|
|
61
64
|
if (isToolCall(chunk)) throw failure('Review model attempted a tool call', 'MODEL_PROTOCOL_ERROR');
|
|
62
|
-
|
|
63
|
-
|
|
65
|
+
const delta = chunk.type === 'text-delta' || chunk.type === 'reasoning-delta';
|
|
66
|
+
const completed = chunk.type === 'block-end' &&
|
|
67
|
+
(chunk.block.type === 'text' || chunk.block.type === 'reasoning');
|
|
68
|
+
if (delta || completed) {
|
|
69
|
+
const type = completed ? chunk.block.type : chunk.type === 'text-delta' ? 'text' : 'reasoning';
|
|
70
|
+
// Unindexed delta-only streams remain supported for older callers.
|
|
71
|
+
const key = chunk.index ?? type;
|
|
72
|
+
const previous = blocks.get(key);
|
|
73
|
+
if (previous && previous.type !== type) throw failure('Model changed block type', 'MODEL_PROTOCOL_ERROR');
|
|
74
|
+
// Like the host BlockAssembler, first close wins; never append stragglers.
|
|
75
|
+
if (previous?.closed) continue;
|
|
76
|
+
const text = completed ? chunk.block.text : (previous?.text ?? '') + chunk.text;
|
|
77
|
+
const bytes = Buffer.byteLength(text);
|
|
78
|
+
// A shorter final snapshot must not refund previously consumed output budget.
|
|
79
|
+
const chargedBytes = Math.max(previous?.chargedBytes ?? 0, bytes);
|
|
80
|
+
size += chargedBytes - (previous?.chargedBytes ?? 0);
|
|
64
81
|
if (size > maxOutputBytes) throw failure('Model output limit exceeded', 'MODEL_OUTPUT_LIMIT');
|
|
65
|
-
|
|
82
|
+
blocks.set(key, { type, text, chargedBytes, closed: completed });
|
|
83
|
+
output = [...blocks.values()].filter(block => block.type === 'text').map(block => block.text).join('');
|
|
66
84
|
}
|
|
67
85
|
if (chunk.type === 'finish') {
|
|
68
86
|
finishKind = chunk.reason.kind;
|
package/src/git-history.mjs
CHANGED
|
@@ -68,7 +68,7 @@ export async function captureGitHistory(cwd, options = {}) {
|
|
|
68
68
|
if (!Number.isSafeInteger(maxFiles) || maxFiles < 1 || maxFiles > 200 || !Number.isSafeInteger(maxFileBytes) || maxFileBytes < 1 || maxFileBytes > 256 * 1024 || !Number.isSafeInteger(maxSnapshotBytes) || maxSnapshotBytes < 1 || maxSnapshotBytes > 4 * 1024 * 1024) throw new Error('Invalid historical capture limits');
|
|
69
69
|
if (selectedPaths !== undefined && (!Array.isArray(selectedPaths) || selectedPaths.some(p => relativePath(p) !== p))) throw new Error('Invalid selected paths');
|
|
70
70
|
|
|
71
|
-
const root = await realpath(utf8(await gitAt(cwd, ['rev-parse', '--show-toplevel'], options)).
|
|
71
|
+
const root = await realpath(utf8(await gitAt(cwd, ['rev-parse', '--show-toplevel'], options)).replace(/\r?\n$/, ''));
|
|
72
72
|
|
|
73
73
|
// Resolve the two endpoints: commit compares against its sole parent; range uses explicit endpoints.
|
|
74
74
|
let base, target;
|
package/src/git.mjs
CHANGED
|
@@ -10,7 +10,7 @@ const git = (cwd, args, options) => checked('git', [...flags, ...args], { ...opt
|
|
|
10
10
|
const text = bytes => new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
|
11
11
|
|
|
12
12
|
async function resolveRoot(cwd, options) {
|
|
13
|
-
const top = text(await git(cwd, ['rev-parse', '--show-toplevel'], options)).
|
|
13
|
+
const top = text(await git(cwd, ['rev-parse', '--show-toplevel'], options)).replace(/\r?\n$/, '');
|
|
14
14
|
return realpath(top);
|
|
15
15
|
}
|
|
16
16
|
|
|
@@ -41,7 +41,13 @@ function parseChanges(bytes) {
|
|
|
41
41
|
|
|
42
42
|
/** Keep only the entries the requested comparison actually observes. */
|
|
43
43
|
function changesInScope(changes, scope) {
|
|
44
|
-
|
|
44
|
+
// Porcelain reports a staged deletion and its untracked recreation separately.
|
|
45
|
+
// Worktree compares HEAD to the current file once, retaining the tracked entry
|
|
46
|
+
// (and its baseline/selection authority), not a second untracked identity.
|
|
47
|
+
if (scope === 'worktree') {
|
|
48
|
+
const tracked = new Set(changes.filter(change => change.rawStatus !== '??').map(change => change.path));
|
|
49
|
+
return changes.filter(change => change.rawStatus !== '??' || !tracked.has(change.path));
|
|
50
|
+
}
|
|
45
51
|
if (scope === 'staged') return changes.filter(change => change.rawStatus[0] !== ' ' && change.rawStatus[0] !== '?');
|
|
46
52
|
return changes.filter(change => change.rawStatus[1] !== ' ' || change.rawStatus === '??');
|
|
47
53
|
}
|
|
@@ -17,7 +17,10 @@ export function importedCallSites(lines, importLine, callIndex = indexStandalone
|
|
|
17
17
|
const identifier = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
18
18
|
if (identifier.test(match[1])) names.push(match[1]);
|
|
19
19
|
else if (match[1].startsWith('{') && match[1].endsWith('}')) {
|
|
20
|
-
|
|
20
|
+
const parts = match[1].slice(1, -1).split(',');
|
|
21
|
+
// A single trailing comma is valid; leading or interior holes are not.
|
|
22
|
+
if (!parts.at(-1).trim()) parts.pop();
|
|
23
|
+
for (const part of parts) {
|
|
21
24
|
const binding = /^\s*([A-Za-z_$][A-Za-z0-9_$]*)(?:\s+as\s+([A-Za-z_$][A-Za-z0-9_$]*))?\s*$/.exec(part);
|
|
22
25
|
if (!binding) return [];
|
|
23
26
|
names.push(binding[2] ?? binding[1]);
|
package/src/primary-input.mjs
CHANGED
|
@@ -167,8 +167,9 @@ export function preparePrimaryInput(input, file, { instructions, scope, grouping
|
|
|
167
167
|
|
|
168
168
|
if (batches?.length > 1) {
|
|
169
169
|
synthesis = prepareWindowSynthesis(batches.map(batch => batch.payload), measure);
|
|
170
|
-
metadata.synthesisStatus = synthesis.
|
|
171
|
-
metadata.
|
|
170
|
+
metadata.synthesisStatus = synthesis.status === 'ready' ? 'ready' : 'blocked';
|
|
171
|
+
if (synthesis.reason) metadata.synthesisBlockedReason = synthesis.reason;
|
|
172
|
+
if (synthesis.budget) metadata.synthesisInputBytes = synthesis.budget.bytes;
|
|
172
173
|
}
|
|
173
174
|
|
|
174
175
|
const budget = measure(payload);
|
package/src/process.mjs
CHANGED
|
@@ -14,13 +14,21 @@ export function run(command, args, { cwd, signal, timeoutMs = 0, maxBytes = 8 *
|
|
|
14
14
|
env: childEnv,
|
|
15
15
|
});
|
|
16
16
|
const stdout = [], stderr = [];
|
|
17
|
-
let bytes = 0, failure;
|
|
18
|
-
const stop = error => {
|
|
17
|
+
let bytes = 0, failure, killer, stopped = false;
|
|
18
|
+
const stop = error => {
|
|
19
|
+
failure ??= error;
|
|
20
|
+
if (stopped) return;
|
|
21
|
+
stopped = true;
|
|
22
|
+
child.kill();
|
|
23
|
+
killer = setTimeout(() => { if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL'); }, 1000);
|
|
24
|
+
killer.unref?.();
|
|
25
|
+
};
|
|
19
26
|
const abort = () => stop(signal.reason ?? new Error('Cancelled'));
|
|
20
27
|
signal?.addEventListener('abort', abort, { once: true });
|
|
21
28
|
if (signal?.aborted) abort();
|
|
22
29
|
const timer = timeoutMs>0?setTimeout(() => stop(new Error('Command timeout')), timeoutMs):undefined;
|
|
23
30
|
const capture = chunks => data => {
|
|
31
|
+
if (stopped) return;
|
|
24
32
|
bytes += data.length;
|
|
25
33
|
if (bytes > maxBytes) stop(new Error('Command output limit exceeded'));
|
|
26
34
|
else chunks.push(data);
|
|
@@ -30,6 +38,7 @@ export function run(command, args, { cwd, signal, timeoutMs = 0, maxBytes = 8 *
|
|
|
30
38
|
child.on('error', error => { failure ??= error; });
|
|
31
39
|
child.on('close', code => {
|
|
32
40
|
clearTimeout(timer);
|
|
41
|
+
clearTimeout(killer);
|
|
33
42
|
signal?.removeEventListener('abort', abort);
|
|
34
43
|
if (failure) reject(failure);
|
|
35
44
|
else resolve({ code, stdout: Buffer.concat(stdout), stderr: Buffer.concat(stderr) });
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { reviewSnapshot } from './review.mjs';
|
|
2
2
|
|
|
3
|
-
export const DEFAULT_PROJECT_CONCURRENCY =
|
|
3
|
+
export const DEFAULT_PROJECT_CONCURRENCY = 8;
|
|
4
4
|
export function projectConcurrency(value = DEFAULT_PROJECT_CONCURRENCY) {
|
|
5
5
|
if (!Number.isSafeInteger(value) || value < 1 || value > 8) throw new Error('Project concurrency must be an integer from 1 to 8');
|
|
6
6
|
return value;
|
|
@@ -5,7 +5,7 @@ import { hash } from './content.mjs';
|
|
|
5
5
|
import { resolveWorkspaceRepository } from './workspace-repository.mjs';
|
|
6
6
|
import { detectVcs } from './snapshot.mjs';
|
|
7
7
|
import { projectInventory, captureProjectBatch } from './project-snapshot.mjs';
|
|
8
|
-
import { reviewProjectBatches, projectConcurrency as validateProjectConcurrency } from './project-execution.mjs';
|
|
8
|
+
import { reviewProjectBatches, projectConcurrency as validateProjectConcurrency, DEFAULT_PROJECT_CONCURRENCY } from './project-execution.mjs';
|
|
9
9
|
import { createDshModel } from './dsh-model.mjs';
|
|
10
10
|
|
|
11
11
|
const PREVIEW_NOTICE_SUFFIX = ' Full current source audit, not regression-only diff. Shared session execution budget: no internal elapsed-time or model-call cutoff, 16MiB capture memory protection. Blocked/excluded/pending files are not reviewed successfully. No untracked/ignored/external bodies; no complete semantic call graph. Independent approved batches run with bounded concurrency; per-batch evidence and global model-call budgets remain enforced. Show scope and model before confirmed execute.';
|
|
@@ -66,7 +66,7 @@ async function captureProject(cwd, args, signal) {
|
|
|
66
66
|
return { ...result, id: hash(JSON.stringify(result)) };
|
|
67
67
|
}
|
|
68
68
|
|
|
69
|
-
export function createProjectReviewService(llm, { allowModelSending = false, authorize = async () => false, now = Date.now, ttlMs = 300000, maxPreviews = 8, projectMaxCalls = Number.MAX_SAFE_INTEGER, projectConcurrency =
|
|
69
|
+
export function createProjectReviewService(llm, { allowModelSending = false, authorize = async () => false, now = Date.now, ttlMs = 300000, maxPreviews = 8, projectMaxCalls = Number.MAX_SAFE_INTEGER, projectConcurrency = DEFAULT_PROJECT_CONCURRENCY } = {}) {
|
|
70
70
|
for (const n of [ttlMs, maxPreviews]) if (!Number.isSafeInteger(n) || n < 1) throw new Error('Invalid project preview limit');
|
|
71
71
|
if (!Number.isSafeInteger(projectMaxCalls) || projectMaxCalls < 1) throw new Error('Invalid project model call limit');
|
|
72
72
|
|
package/src/project-snapshot.mjs
CHANGED
|
@@ -13,7 +13,7 @@ const INVENTORY_NOTICE = 'Tracked current working files only, including unchange
|
|
|
13
13
|
|
|
14
14
|
async function inventoryGit(root, options) {
|
|
15
15
|
const args = ['--no-optional-locks', '-c', 'core.fsmonitor=false', '-c', 'core.untrackedCache=false'];
|
|
16
|
-
const actual = text(await checked('git', [...args, 'rev-parse', '--show-toplevel'], { ...options, cwd: root })).
|
|
16
|
+
const actual = text(await checked('git', [...args, 'rev-parse', '--show-toplevel'], { ...options, cwd: root })).replace(/\r?\n$/, '');
|
|
17
17
|
if (await realpath(actual) !== root) throw new Error('Full project requires explicit repository root');
|
|
18
18
|
const index = await checked('git', [...args, 'ls-files', '--stage', '-z'], { ...options, cwd: root, maxBytes: 2 * 1024 * 1024 });
|
|
19
19
|
const records = [];
|
package/src/review-jobs.mjs
CHANGED
|
@@ -16,12 +16,15 @@ export function createReviewJobs({directory}={}){
|
|
|
16
16
|
async function save(job){await safeDirectory();const tmp=path.join(directory,job.id+'.'+randomUUID()+'.tmp');await writeFile(tmp,JSON.stringify(job.record),{mode:0o600,flag:'wx'});await rename(tmp,filename(job.id));changed(job.id);}
|
|
17
17
|
async function owned(id,exec){const who=identity(exec),job=jobs.get(id);if(job){if(!same(who,job.record.owner))throw new Error('Foreign review job');return job.record;}await safeDirectory();const name=filename(id),stat=await lstat(name);if(stat.isSymbolicLink()||!stat.isFile())throw new Error('Unsafe report file');const r=JSON.parse(await readFile(name,'utf8'));if(!same(who,r.owner))throw new Error('Foreign review job');if(['queued','running'].includes(r.status)){r.status='interrupted';r.notice='Host restarted or plugin disposed. Saved checkpoints are available; resending requires a fresh preview and approval.';}return r;}
|
|
18
18
|
return {
|
|
19
|
-
async start(exec,work){if(disposed)throw new Error('Review job service disposed');exec.signal?.throwIfAborted();const who=identity(exec);const relative=path.relative(path.resolve(who.cwd),directory);if(relative===''||(!relative.startsWith('..'+path.sep)&&relative!=='..'&&!path.isAbsolute(relative)))throw new Error('Report store must be outside reviewed workspace');if([...jobs.values()].some(j=>j.record.owner.sessionId===who.sessionId&&['queued','running'].includes(j.record.status)))throw new Error('Session review job already active');const id=randomUUID(),controller=new AbortController(),job={id,controller,record:{jobId:id,owner:who,status:'queued',stage:'queued',checkpoints:[],createdAt:new Date().toISOString()},pending:Promise.resolve()};jobs.set(id,job);try{await save(job);}catch(error){jobs.delete(id);throw error;}
|
|
19
|
+
async start(exec,work){if(disposed)throw new Error('Review job service disposed');exec.signal?.throwIfAborted();const who=identity(exec);const relative=path.relative(path.resolve(who.cwd),directory);if(relative===''||(!relative.startsWith('..'+path.sep)&&relative!=='..'&&!path.isAbsolute(relative)))throw new Error('Report store must be outside reviewed workspace');if([...jobs.values()].some(j=>j.record.owner.sessionId===who.sessionId&&['queued','running'].includes(j.record.status)))throw new Error('Session review job already active');const id=randomUUID(),controller=new AbortController(),job={id,controller,record:{jobId:id,owner:who,status:'queued',stage:'queued',checkpoints:[],createdAt:new Date().toISOString()},pending:Promise.resolve()};jobs.set(id,job);try{await save(job);}catch(error){jobs.delete(id);throw error;}
|
|
20
|
+
// Keep the serialization tail usable after failure, but return the original
|
|
21
|
+
// rejecting operation so checkpoint callers still observe durability failures.
|
|
22
|
+
const enqueue=fn=>{const operation=job.pending.then(fn);job.pending=operation.catch(()=>{});return operation;};
|
|
20
23
|
// Own cancellation explicitly. The short start RPC ending is NOT task cancellation.
|
|
21
|
-
job.done=(async()=>{await Promise.resolve();try{job.record.status='running';await enqueue(()=>save(job));const result=await work({signal:controller.signal,checkpoint:async value=>enqueue(async()=>{job.record.stage=value.stage??'reviewing';job.record.checkpoints.push(structuredClone(value));await save(job);})});job.record.result=result;job.record.status=controller.signal.aborted?'cancelled':'completed';}catch(error){job.record.status=controller.signal.aborted?'cancelled':'failed';job.record.error=error?.message??String(error);}finally{job.record.finishedAt=new Date().toISOString();try{await enqueue(()=>save(job));}catch(error){job.record.status='failed';job.record.persistenceError=error
|
|
24
|
+
job.done=(async()=>{await Promise.resolve();try{job.record.status='running';await enqueue(()=>save(job));const result=await work({signal:controller.signal,checkpoint:async value=>enqueue(async()=>{job.record.stage=value.stage??'reviewing';job.record.checkpoints.push(structuredClone(value));await save(job);})});job.record.result=result;job.record.status=controller.signal.aborted?'cancelled':'completed';}catch(error){job.record.status=controller.signal.aborted?'cancelled':'failed';job.record.error=error?.message??String(error);}finally{job.record.finishedAt=new Date().toISOString();try{await enqueue(()=>save(job));jobs.delete(id);}catch(error){job.record.status='failed';job.record.persistenceError=error?.message??String(error);}finally{changed(id);}}})();return {jobId:id,status:'queued',nextAction:'Call code_review_wait until terminal status; do not finish the user request at start.',notice:'Background job accepted. Poll status; start is not a completed review. Explicit cancel or plugin disposal stops it.'};
|
|
22
25
|
},
|
|
23
26
|
async status(id,exec,page){const r=structuredClone(await owned(id,exec));r.recovery=recoveryCoverage(r);r.progress=jobProgress(r);r.waitRevision=r.checkpoints.length;r.nextAction=['queued','running'].includes(r.status)?'Call code_review_wait; do not end the user review request while task runs.':r.result?.previewId?'Show preview and request user confirmation before execute.':'Collect final report and unfinished scope, then provide one final answer.';if(!page)return r;const {offset=0,limit=20,checkpointIndex}=page;if(!Number.isSafeInteger(offset)||offset<0||!Number.isSafeInteger(limit)||limit<1||limit>100)throw new Error('Invalid result page');if(checkpointIndex!==undefined){if(!Number.isSafeInteger(checkpointIndex)||checkpointIndex<0||checkpointIndex>=r.checkpoints.length)throw new Error('Invalid checkpoint index');return {jobId:r.jobId,status:r.status,checkpointIndex,checkpoint:pageCheckpoint(r.checkpoints[checkpointIndex],offset,limit),page:{offset,limit}};}const result=r.result;const report=result?.report;return {...r,result:undefined,recovery:{...r.recovery,unfinishedStages:r.recovery.unfinishedStages.slice(offset,offset+limit),files:r.recovery.files.slice(offset,offset+limit),windows:r.recovery.windows.slice(offset,offset+limit),suggestedPaths:r.recovery.suggestedPaths.slice(offset,offset+limit),totalObservedFiles:r.recovery.files.length},checkpoints:r.checkpoints.slice(offset,offset+limit).map(c=>pageCheckpoint(c,0,limit)),checkpointPage:{offset,limit,total:r.checkpoints.length},...(result?{resultSummary:report?{status:report.status,coverage:report.coverage,model:report.model,snapshotId:report.snapshotId}:({...result,files:result.files?.slice(offset,offset+limit),filePage:result.files?{offset,limit,total:result.files.length}:undefined}),resultPage:report?{files:report.files?.slice(offset,offset+limit),findings:report.findings?.slice(offset,offset+limit),totalFiles:report.files?.length,totalFindings:report.findings?.length}:undefined}: {})};},
|
|
24
|
-
async wait(id,exec,{after,timeoutMs=25000,signal}={}){const r=await owned(id,exec);if(!Number.isSafeInteger(timeoutMs)||timeoutMs<1||timeoutMs>60000)throw new Error('Invalid wait duration');if(after!==undefined&&(!Number.isSafeInteger(after)||after<0))throw new Error('Invalid wait revision');const revision=r.checkpoints.length;if(!['queued','running'].includes(r.status)||(after!==undefined&&after!==revision))return {changed:true};signal?.throwIfAborted();await new Promise((resolve,reject)=>{let timer;const cleanup=()=>{clearTimeout(timer);signal?.removeEventListener('abort',abort);listeners.get(id)?.delete(done);};const done=()=>{cleanup();resolve();},abort=()=>{cleanup();reject(signal.reason);};if(!listeners.has(id))listeners.set(id,new Set());listeners.get(id).add(done);signal?.addEventListener('abort',abort,{once:true});timer=setTimeout(done,timeoutMs);const latest=jobs.get(id)?.record;if(latest
|
|
27
|
+
async wait(id,exec,{after,timeoutMs=25000,signal}={}){const r=await owned(id,exec);if(!Number.isSafeInteger(timeoutMs)||timeoutMs<1||timeoutMs>60000)throw new Error('Invalid wait duration');if(after!==undefined&&(!Number.isSafeInteger(after)||after<0))throw new Error('Invalid wait revision');const revision=r.checkpoints.length;if(!['queued','running'].includes(r.status)||(after!==undefined&&after!==revision))return {changed:true};signal?.throwIfAborted();await new Promise((resolve,reject)=>{let timer;const cleanup=()=>{clearTimeout(timer);signal?.removeEventListener('abort',abort);const waiting=listeners.get(id);waiting?.delete(done);if(waiting?.size===0)listeners.delete(id);};const done=()=>{cleanup();resolve();},abort=()=>{cleanup();reject(signal.reason);};if(!listeners.has(id))listeners.set(id,new Set());listeners.get(id).add(done);signal?.addEventListener('abort',abort,{once:true});timer=setTimeout(done,timeoutMs);const latest=jobs.get(id)?.record;if(!latest||latest.checkpoints.length!==revision||!['queued','running'].includes(latest.status))done();if(signal?.aborted)abort();});return {changed:true};},
|
|
25
28
|
async cancel(id,exec){await owned(id,exec);const j=jobs.get(id);if(j)j.controller.abort(new Error('User cancelled review job'));return {jobId:id,cancelRequested:!!j};},
|
|
26
29
|
async dispose(){disposed=true;for(const j of jobs.values())j.controller.abort(new Error('Review plugin disposed'));await Promise.all([...jobs.values()].map(j=>j.done));}
|
|
27
30
|
};
|
package/src/review.mjs
CHANGED
|
@@ -136,8 +136,8 @@ export async function reviewSnapshot(snapshot, model, options = {}) {
|
|
|
136
136
|
const { changes, payload } = prepared;
|
|
137
137
|
Object.assign(state, prepared.metadata);
|
|
138
138
|
if (state.contextMode === 'approved-retrieval') report.limitations.push({ fileId: file.id, text: '窗口初始输入仅带上下文身份目录,全文须按需读取;不声明所有上下文已核查。' });
|
|
139
|
-
if (prepared.synthesis) state.synthesisStatus = prepared.synthesis.
|
|
140
|
-
if (prepared.synthesis
|
|
139
|
+
if (prepared.synthesis) state.synthesisStatus = prepared.synthesis.status === 'ready' ? 'pending' : 'blocked';
|
|
140
|
+
if (prepared.synthesis?.status === 'blocked') report.limitations.push({ fileId: file.id, text: (prepared.synthesis.reason === 'batch-limit' ? '跨窗口综合批次数超过上限(20),未发送;全部主窗口仍独立审查' : '跨窗口综合输入超限,未发送') + ';单窗口完成不表示交互影响已检查' });
|
|
141
141
|
if (state.sourceMode === 'change-windows') state.windowCoverage = { completed: [], pending: [...state.windowIds] };
|
|
142
142
|
if(changes.precision==='envelope')report.limitations.push({fileId:file.id,text:'精确差异不可得,按保守包络分段检查;包络包含可能未变的行,不证明精确编辑或回归因果。'});
|
|
143
143
|
if (changes.status === 'limited') report.limitations.push({ fileId: file.id, text: '精确变更分析受限:' + changes.reason + ';仍按完整两侧内容审查' });
|
|
@@ -192,7 +192,7 @@ export async function reviewSnapshot(snapshot, model, options = {}) {
|
|
|
192
192
|
}
|
|
193
193
|
}
|
|
194
194
|
const batches = [...(prepared.batches ?? [{ payload, windowIds: state.windowIds ?? [] }])];
|
|
195
|
-
if (prepared.synthesis?.
|
|
195
|
+
if (prepared.synthesis?.status === 'ready') batches.push({ payload: prepared.synthesis.payload, windowIds: [], synthesis: true });
|
|
196
196
|
const matchingInteractionPlans = interactionPlans.filter(p => input.files.filter(f => p.group.fileIds.includes(f.id)).at(-1)?.id === file.id);
|
|
197
197
|
for (const interactionPlan of matchingInteractionPlans.filter(p => p.prepared.status === 'ready')) batches.push({ payload: interactionPlan.prepared.payload, windowIds: [], interaction: interactionPlan.group });
|
|
198
198
|
const scheduled = Array.from({length:rounds},(_,i)=>batches.map(b=>({...b,round:i+1}))).flat();
|
|
@@ -326,9 +326,9 @@ export async function reviewSnapshot(snapshot, model, options = {}) {
|
|
|
326
326
|
} catch (error) {
|
|
327
327
|
state.status = signal?.aborted ? 'cancelled' : error?.code === 'PROJECT_MODEL_CALL_LIMIT' ? 'pending' : 'failed';
|
|
328
328
|
state.reason = error?.message ?? String(error);
|
|
329
|
-
if(error
|
|
330
|
-
if(error
|
|
331
|
-
if(error
|
|
329
|
+
if(error?.attempts)state.protocolAttempts=error.attempts;
|
|
330
|
+
if(error?.responseAttempts)state.responseAttempts=error.responseAttempts;
|
|
331
|
+
if(error?.diagnostic)state.protocolDiagnostic=error.diagnostic;
|
|
332
332
|
for(const pass of state.reviewPasses??[])if(pass.status==='running')pass.status=signal?.aborted?'cancelled':'failed';
|
|
333
333
|
state.failureCode = signal?.aborted ? 'CANCELLED' : ['MODEL_INVALID_JSON','MODEL_INCOMPLETE_OUTPUT','MODEL_TIMEOUT','MODEL_INVALID_READ_REQUEST','MODEL_OUTPUT_LIMIT','MODEL_PROTOCOL_ERROR','MODEL_INVALID_REVIEW_RESPONSE','MODEL_INVALID_FINDING_IDENTITY','MODEL_INVALID_FINDING_SEVERITY','MODEL_MISSING_FINDING_FIELD','MODEL_INVALID_ANCHOR','MODEL_ANCHOR_MISMATCH','READER_CALL_BUDGET_EXCEEDED','READER_OUTPUT_BUDGET_EXCEEDED','RETRIEVAL_ROUND_BUDGET_EXCEEDED','RETRIEVAL_FINAL_RESPONSE_REQUIRED','PROJECT_MODEL_CALL_LIMIT'].includes(error?.code) ? error.code : 'REVIEW_EXECUTION_FAILED';
|
|
334
334
|
}
|
package/src/snapshot.mjs
CHANGED
|
@@ -147,7 +147,13 @@ export async function captureSnapshot(cwd, options = {}) {
|
|
|
147
147
|
|
|
148
148
|
// Re-capture verifies both selected sides while collecting explicit context.
|
|
149
149
|
if ((await capture(cwd, indexOptions)).id !== snapshot.id) throw new Error('Snapshot changed while collecting context');
|
|
150
|
-
for (const item of context)
|
|
150
|
+
for (const item of context) {
|
|
151
|
+
// Overlapping staged context reuses the approved index side, not local bytes.
|
|
152
|
+
// The same-side re-capture above verifies its content and index identity,
|
|
153
|
+
// including when the working file differs or no longer exists.
|
|
154
|
+
if (type === 'git' && snapshot.changeScope === 'staged' && snapshot.files.some(file => file.path === item.path)) continue;
|
|
155
|
+
if ((await readLocal(snapshot.root, item.path, indexOptions)).hash !== item.hash) throw new Error('Context changed during capture');
|
|
156
|
+
}
|
|
151
157
|
if (index && (await (type === 'git' ? gitContextIndex : svnContextIndex)(snapshot.root, indexOptions)).fingerprint !== index.fingerprint) throw new Error('Tracked context index changed during capture');
|
|
152
158
|
const verifiedRules = await captureProjectRules(snapshot.root, rulePaths, { signal: options.signal, files: snapshot.files });
|
|
153
159
|
if (JSON.stringify(verifiedRules) !== JSON.stringify(rules)) throw new Error('Rules changed during capture');
|
package/src/source-segments.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// Linear segmentation of approved text. Coordinates remain original one-based lines.
|
|
2
2
|
export function sourceSegments(windows,{maxBytes=12000,maxLines=100}={}){
|
|
3
|
+
if(!Number.isSafeInteger(maxBytes)||maxBytes<1||!Number.isSafeInteger(maxLines)||maxLines<1)throw new Error('Invalid source segment limits');
|
|
3
4
|
const out=[];for(const w of windows){if(w.old.count<=maxLines&&w.new.count<=maxLines&&Buffer.byteLength(w.old.text)<=maxBytes&&Buffer.byteLength(w.new.text)<=maxBytes){out.push(w);continue;}const sides={old:w.old.text.match(/[^\n]*\n|[^\n]+$/g)??[],new:w.new.text.match(/[^\n]*\n|[^\n]+$/g)??[]},pos={old:0,new:0};let i=0;
|
|
4
5
|
while(pos.old<sides.old.length||pos.new<sides.new.length){const item={id:w.id+'-s'+(++i),editIds:[...w.editIds]};for(const side of ['old','new']){const start=pos[side],parts=[];let bytes=0;while(pos[side]<sides[side].length&&parts.length<maxLines){const line=sides[side][pos[side]],n=Buffer.byteLength(line);if(parts.length&&bytes+n>maxBytes)break;parts.push(line);bytes+=n;pos[side]++;if(bytes>=maxBytes)break;}item[side]={start:w[side].start+start,count:parts.length,text:parts.join('')};}out.push(item);}
|
|
5
6
|
if(!i)out.push(w);
|
package/src/svn-caller-index.mjs
CHANGED
|
@@ -7,4 +7,11 @@ import {lstat} from 'node:fs/promises';
|
|
|
7
7
|
import path from 'node:path';
|
|
8
8
|
const canonical=v=>Array.isArray(v)?v.map(canonical):v&&typeof v==='object'?Object.fromEntries(Object.keys(v).sort().map(k=>[k,canonical(v[k])])):v;
|
|
9
9
|
// Offline scoped status only, never svn list or repository-wide enumeration.
|
|
10
|
-
|
|
10
|
+
// Status XML has no node kind: bind local kinds and omit directories from body candidates.
|
|
11
|
+
// Links and other unsafe non-directory nodes still reach the strict source validator.
|
|
12
|
+
export async function svnCallerIndex(root,scopes,options={}){const approved=validateCallerScopes(scopes),entries=[],chunks=[];let bytes=0;const seen=new Set();for(const scope of approved){const ancestors=await svnCallerAncestors(root,scope,options);chunks.push(ancestors.fingerprint);let cursor=root;for(const part of scope.split('/')){cursor=path.join(cursor,part);const s=await lstat(cursor);if(s.isSymbolicLink()||!s.isDirectory())throw new Error('SVN caller scope requires real directories');}
|
|
13
|
+
const raw=await checked('svn',['--non-interactive','status','--xml','--verbose','--ignore-externals','--',scope+'@'],{...options,cwd:root,maxBytes:64*1024});bytes+=raw.length;if(bytes>64*1024)throw new Error('SVN caller index byte limit exceeded');const found=(xml(raw).status?.target??[]).flatMap(t=>t.entry??[]);
|
|
14
|
+
for(const e of found){const name=relativePath(e['@_path'].replaceAll('\\','/'));if(name!==scope&&!name.startsWith(scope+'/'))throw new Error('SVN caller index escaped scope');if(seen.has(name))throw new Error('Duplicate SVN caller index path');seen.add(name);if(seen.size>256)throw new Error('SVN caller index path limit exceeded');entries.push({...e,'@_path':name});}if(!found.some(e=>e['@_path'].replaceAll('\\','/')===scope))throw new Error('SVN caller scope missing from status');chunks.push(scope);}
|
|
15
|
+
entries.sort((a,b)=>a['@_path']<b['@_path']?-1:1);const unsafe=s=>!s||s['@_item']!=='normal'||!['none','normal'].includes(s['@_props'])||['@_switched','@_copied','@_file-external','@_tree-conflicted'].some(k=>s[k]==='true');for(const scope of approved){const e=entries.find(e=>e['@_path']===scope);if(unsafe(e?.['wc-status']))throw new Error('Unsafe SVN caller directory state');}
|
|
16
|
+
const nodes=[];for(const e of entries.filter(e=>!approved.includes(e['@_path'])&&!unsafe(e['wc-status']))){options.signal?.throwIfAborted();const stat=await lstat(path.join(root,e['@_path']));nodes.push({path:e['@_path'],kind:stat.isDirectory()?'dir':stat.isSymbolicLink()?'link':stat.isFile()?'file':'other'});}
|
|
17
|
+
return {scopes:approved,paths:nodes.filter(n=>n.kind!=='dir').map(n=>n.path),entries,records:entries.length,bytes,fingerprint:hash(JSON.stringify(canonical({scopes:chunks,entries,nodes})))};}
|
|
@@ -24,7 +24,8 @@ export async function svnHistoryCallers(files,history,scopes,context,{index,look
|
|
|
24
24
|
if(typeof value?.content?.text!=='string'||value.kind!=='file'||value.source?.operativeRevision!==revision)throw new Error('Invalid fixed SVN caller body');
|
|
25
25
|
const bodyBytes=value.content.bytes??Buffer.byteLength(value.content.text);
|
|
26
26
|
if(!Number.isSafeInteger(bodyBytes)||bodyBytes<0||bodyBytes>256*1024||Buffer.byteLength(value.content.text)>256*1024)throw new Error('Invalid fixed SVN caller size');
|
|
27
|
-
|
|
27
|
+
// Raw encoding bytes may differ from UTF-8; never charge less than the text retained.
|
|
28
|
+
scanBytes+=Math.max(bodyBytes,Buffer.byteLength(value.content.text));
|
|
28
29
|
if(scanBytes>1024*1024)throw new Error('SVN historical caller scan source limit exceeded');
|
|
29
30
|
const source={path:name,...value.content,svnSource:value.source,side,revision};sources.push(source);scanned.push(source);
|
|
30
31
|
}
|
|
@@ -6,11 +6,19 @@ import {readReplacementSource} from './svn-replacement-source.mjs';
|
|
|
6
6
|
import {svnWorkingIdentity} from './svn-working-identity.mjs';
|
|
7
7
|
import {hash,decode,relativePath,readLocal} from './content.mjs';
|
|
8
8
|
import {isSecretPath} from './secret-path.mjs';
|
|
9
|
+
import {canonicalSvnUrl} from './svn-url.mjs';
|
|
9
10
|
import {svnKeywordMapping} from './svn-keyword-mapping.mjs';
|
|
10
11
|
import {svnEolMapping} from './svn-eol-mapping.mjs';
|
|
11
12
|
import {svnSpecialData} from './svn-special.mjs';
|
|
12
13
|
import {readWorkingSvnSpecial} from './svn-working-special.mjs';
|
|
13
14
|
|
|
15
|
+
// Copy provenance is not permission to capture credential bytes at a safe target name.
|
|
16
|
+
function assertCopySource(source,suffix=''){
|
|
17
|
+
if(source===null||source===undefined)return;
|
|
18
|
+
const url=canonicalSvnUrl(source),name=decodeURIComponent(new URL(url).pathname);
|
|
19
|
+
if(isSecretPath(name)||isSecretPath(name+(suffix?'/'+suffix:'')))throw new Error('Credential replacement copy source excluded');
|
|
20
|
+
}
|
|
21
|
+
|
|
14
22
|
// Fixed repository tree versus explicitly selected working replacement tree.
|
|
15
23
|
// Every descendant is a separate source/coverage unit, never an implicit approval.
|
|
16
24
|
export async function captureReplacementTree(root,rootInfo,name,options={}){
|
|
@@ -26,13 +34,14 @@ export async function captureReplacementTree(root,rootInfo,name,options={}){
|
|
|
26
34
|
const ancestors=async p=>{
|
|
27
35
|
const parts=p.split('/').slice(0,-1),names=['.',...parts.map((_,i)=>parts.slice(0,i+1).join('/'))],records=[];
|
|
28
36
|
for(const name of names){
|
|
29
|
-
if(!verifying&&ancestorReceipts.has(name)){
|
|
37
|
+
if(!verifying&&ancestorReceipts.has(name)){const record=ancestorReceipts.get(name);assertCopySource(record.copyFromUrl,name==='.'?p:p.slice(name.length+1));records.push(record);continue;}
|
|
30
38
|
const stat=await lstat(name==='.'?root:path.join(root,name));if(stat.isSymbolicLink()||!stat.isDirectory())throw new Error('Replacement ancestor is not a real directory');
|
|
31
39
|
const node=xml(await run(['info','--xml','--',name+'@'])).info?.entry?.[0],identity=svnWorkingIdentity(node,rootInfo,name);
|
|
32
40
|
const entries=xml(await run(['status','--xml','--verbose','--ignore-externals','--depth','empty','--',name+'@'])).status?.target?.flatMap(t=>t.entry??[])??[],s=entries[0]?.['wc-status'];
|
|
33
41
|
if(entries.length!==1||!s||!['normal','modified','added','replaced'].includes(s['@_item'])||s['@_props']==='conflicted'||['@_switched','@_file-external','@_tree-conflicted'].some(k=>s[k]==='true'))throw new Error('Unsafe replacement ancestor state');
|
|
42
|
+
assertCopySource(identity.source.copyFromUrl,name==='.'?p:p.slice(name.length+1));
|
|
34
43
|
const properties=await props(name);if(Object.hasOwn(properties,'svn:externals')||Object.hasOwn(properties,'svn:special'))throw new Error('Unsafe replacement ancestor properties');
|
|
35
|
-
const record={path:name,fingerprint:hash(JSON.stringify([identity.fingerprint,properties]))};
|
|
44
|
+
const record={path:name,copyFromUrl:identity.source.copyFromUrl,fingerprint:hash(JSON.stringify([identity.fingerprint,properties]))};
|
|
36
45
|
if(verifying){if(ancestorReceipts.get(name)?.fingerprint!==record.fingerprint)throw new Error('Replacement ancestor changed during capture');}else ancestorReceipts.set(name,record);records.push(record);
|
|
37
46
|
}return records;
|
|
38
47
|
};
|
|
@@ -40,6 +49,7 @@ export async function captureReplacementTree(root,rootInfo,name,options={}){
|
|
|
40
49
|
if(['@_switched','@_file-external','@_tree-conflicted'].some(k=>s[k]==='true')||!['normal','modified','added','replaced'].includes(s['@_item'])||s['@_props']==='conflicted')throw new Error('Unsafe replacement descendant state');
|
|
41
50
|
const ancestorEvidence=await ancestors(p);
|
|
42
51
|
const node=xml(await run(['info','--xml','--',p+'@'])).info?.entry?.[0],identity=svnWorkingIdentity(node,rootInfo,p);if(!['file','dir'].includes(node['@_kind']))throw new Error('Unsupported replacement descendant kind');
|
|
52
|
+
assertCopySource(identity.source.copyFromUrl);
|
|
43
53
|
if(node['@_kind']==='dir'&&identity.source.depth!=='infinity')throw new Error('Sparse replacement target cannot prove descendant inventory');
|
|
44
54
|
const properties=await props(p);if(Object.hasOwn(properties,'svn:externals'))throw new Error('Replacement externals require independent scope');
|
|
45
55
|
const content=node['@_kind']==='dir'?decode(Buffer.alloc(0)):Object.hasOwn(properties,'svn:special')?(await readWorkingSvnSpecial(root,p,properties,options)).content:await readLocal(root,p,options);
|
|
@@ -8,13 +8,15 @@ import {svnSpecialData} from './svn-special.mjs';
|
|
|
8
8
|
export async function readWorkingSvnSpecial(root,name,properties,options={}){
|
|
9
9
|
relativePath(name);assertNonSecretPath(name);options.signal?.throwIfAborted();
|
|
10
10
|
const canonical=await realpath(root);let cursor=canonical;const parts=name.split('/');
|
|
11
|
-
|
|
11
|
+
const ancestors=[];
|
|
12
|
+
for(const part of parts.slice(0,-1)){cursor=path.join(cursor,part);const stat=await lstat(cursor);if(stat.isSymbolicLink()||!stat.isDirectory())throw new Error('SVN special ancestor must be a real directory');ancestors.push({path:cursor,dev:stat.dev,ino:stat.ino,ctimeMs:stat.ctimeMs});}
|
|
12
13
|
const filename=path.join(cursor,parts.at(-1)),before=await lstat(filename);let content;
|
|
13
14
|
if(before.isSymbolicLink()){
|
|
14
15
|
const target=await readlink(filename,{encoding:'buffer'});if(target.length>16384)throw new Error('SVN link target byte limit exceeded');
|
|
15
16
|
const bytes=Buffer.concat([Buffer.from('link '),target]);if(bytes.length>(options.maxFileBytes??256*1024))throw new Error('SVN special file size limit exceeded');
|
|
16
17
|
content=decode(bytes);const after=await lstat(filename);const again=await readlink(filename,{encoding:'buffer'});
|
|
17
|
-
if(
|
|
18
|
+
for(const ancestor of ancestors){const now=await lstat(ancestor.path);if(now.isSymbolicLink()||!now.isDirectory()||now.dev!==ancestor.dev||now.ino!==ancestor.ino||now.ctimeMs!==ancestor.ctimeMs)throw new Error('SVN special ancestor changed during capture');}
|
|
19
|
+
if(!after.isSymbolicLink()||before.ino!==after.ino||before.dev!==after.dev||before.mtimeMs!==after.mtimeMs||before.ctimeMs!==after.ctimeMs||!again.equals(target))throw new Error('SVN link changed during capture');
|
|
18
20
|
}else{
|
|
19
21
|
if(!before.isFile())throw new Error('SVN special working node is neither link nor regular link record');
|
|
20
22
|
content=await readLocal(canonical,name,options);
|
|
@@ -1,15 +1,31 @@
|
|
|
1
1
|
// Audit only successful reads from this synthesis generation, never prior batches/searches.
|
|
2
2
|
export function validateSynthesisReads(findings, changes, reads, catalog, fileId, snapshotId) {
|
|
3
3
|
const sources = new Map(catalog.map(s => [s.id, s]));
|
|
4
|
+
const intervals = new Map();
|
|
5
|
+
for (const read of reads) {
|
|
6
|
+
const source = sources.get(read.sourceId);
|
|
7
|
+
if (read.kind !== 'read' || read.snapshotId !== snapshotId || source?.fileId !== fileId || !['old', 'new'].includes(source.side)) continue;
|
|
8
|
+
if (!Number.isSafeInteger(read.start) || read.start < 1 || !Number.isSafeInteger(read.count) || read.count < 1 || !Number.isSafeInteger(read.start + read.count)) continue;
|
|
9
|
+
const ranges = intervals.get(read.sourceId) ?? [];
|
|
10
|
+
ranges.push({ start: read.start, end: read.start + read.count });
|
|
11
|
+
intervals.set(read.sourceId, ranges);
|
|
12
|
+
}
|
|
13
|
+
// Never join different source identities, even when their file and side match.
|
|
14
|
+
for (const [id, ranges] of intervals) {
|
|
15
|
+
const merged = [];
|
|
16
|
+
for (const range of ranges.sort((a, b) => a.start - b.start)) {
|
|
17
|
+
const last = merged.at(-1);
|
|
18
|
+
if (last && range.start <= last.end) last.end = Math.max(last.end, range.end);
|
|
19
|
+
else merged.push({ ...range });
|
|
20
|
+
}
|
|
21
|
+
intervals.set(id, merged);
|
|
22
|
+
}
|
|
4
23
|
for (const finding of findings) {
|
|
5
24
|
for (const id of finding.attribution.editIds) {
|
|
6
25
|
const edit = changes.edits.find(e => e.id === id);
|
|
7
26
|
const covered = ['old', 'new'].some(side => {
|
|
8
27
|
const range = edit?.[side];
|
|
9
|
-
return range?.count > 0 &&
|
|
10
|
-
const source = sources.get(r.sourceId);
|
|
11
|
-
return r.kind === 'read' && r.snapshotId === snapshotId && source?.fileId === fileId && source.side === side && r.start <= range.start && r.start + r.count >= range.start + range.count;
|
|
12
|
-
});
|
|
28
|
+
return range?.count > 0 && [...intervals].some(([sourceId, ranges]) => sources.get(sourceId).side === side && ranges.some(r => r.start <= range.start && r.end >= range.start + range.count));
|
|
13
29
|
});
|
|
14
30
|
if (!covered) throw new Error('Synthesis referenced edit was not read in this generation');
|
|
15
31
|
}
|
package/src/tracked-context.mjs
CHANGED
|
@@ -16,7 +16,10 @@ export async function gitContextIndex(root, options = {}) {
|
|
|
16
16
|
let bytes;
|
|
17
17
|
if(options.probePaths !== undefined){
|
|
18
18
|
if(!Array.isArray(options.probePaths)||options.probePaths.length>512||new Set(options.probePaths).size!==options.probePaths.length)throw new Error('Invalid Git context probes');
|
|
19
|
-
|
|
19
|
+
// A literal pathspec alone still recursively matches a directory. Exclude
|
|
20
|
+
// its literal trailing-slash subtree before output, so directory probes are
|
|
21
|
+
// exact misses without enumerating or authorizing unrequested descendants.
|
|
22
|
+
const chunks=[];let totalBytes=0;for(const name of [...options.probePaths].sort()){relativePath(name);const chunk=await checked('git',['--no-optional-locks','-c','core.fsmonitor=false','-c','core.untrackedCache=false','ls-files','--stage','-z','--',':(top,literal)'+name,':(top,literal,exclude)'+name+'/'],{...options,cwd:root,maxBytes:64*1024});const records=new TextDecoder('utf-8',{fatal:true}).decode(chunk).split('\0').filter(Boolean);for(const record of records)if(record.slice(record.indexOf('\t')+1)!==name)throw new Error('Git context probe expanded beyond literal path');totalBytes+=chunk.length;if(totalBytes>1024*1024)throw new Error('Tracked context index limit exceeded');chunks.push(chunk);}
|
|
20
23
|
bytes=Buffer.concat(chunks);if(bytes.length>1024*1024)throw new Error('Tracked context index limit exceeded');
|
|
21
24
|
}else bytes = await checked('git', ['--no-optional-locks','-c','core.fsmonitor=false','-c','core.untrackedCache=false','ls-files','--stage','-z'], {...options,cwd:root,maxBytes:1024*1024});
|
|
22
25
|
const records = new TextDecoder('utf-8',{fatal:true}).decode(bytes).split('\0').filter(Boolean);
|
package/src/window-synthesis.mjs
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
// Pure approved-data preparation, no reads or sends. No source text is silently clipped.
|
|
2
2
|
export function prepareWindowSynthesis(batchPayloads, measure) {
|
|
3
|
-
if (!Array.isArray(batchPayloads) || batchPayloads.length < 2
|
|
3
|
+
if (!Array.isArray(batchPayloads) || batchPayloads.length < 2) throw new Error('Invalid synthesis batches');
|
|
4
|
+
// A synthesis scheduling limit must not discard any independently reviewable batch.
|
|
5
|
+
if (batchPayloads.length > 20) return { status: 'blocked', reason: 'batch-limit', batchCount: batchPayloads.length };
|
|
4
6
|
const batches = batchPayloads.map(payload => JSON.parse(payload));
|
|
5
7
|
const base = batches[0];
|
|
6
8
|
const windows = batches.flatMap(batch => batch.windows);
|
|
@@ -8,5 +10,5 @@ export function prepareWindowSynthesis(batchPayloads, measure) {
|
|
|
8
10
|
const windowIndex = windows.map(w => ({ id: w.id, editIds: w.editIds, old: { start: w.old.start, count: w.old.count }, new: { start: w.new.start, count: w.new.count } }));
|
|
9
11
|
const payload = JSON.stringify({ ...base, windows: undefined, windowIndex, sourceMode: 'window-synthesis', windowNotice: '本请求综合检查所有窗口的共同影响,不重报单窗口问题;windowIndex仅为原始定位目录,不含源码,必须在批准catalog中读取相关旧新片段,不能仅凭目录认定缺陷。输出仍仅主file的发现,归因至少关联两个不同窗口的编辑;证据不足明确限制。' });
|
|
10
12
|
const budget = measure(payload);
|
|
11
|
-
return { payload, windows, windowIds: windows.map(w => w.id), budget };
|
|
13
|
+
return { status: budget.fits ? 'ready' : 'blocked', ...(budget.fits ? {} : { reason: 'input-budget' }), payload, windows, windowIds: windows.map(w => w.id), budget };
|
|
12
14
|
}
|