@feng0531/dsh-code-review 0.85.5 → 0.85.6

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 CHANGED
@@ -2,6 +2,15 @@
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.6 — 快照正确性、任务隔离与取消修复
6
+
7
+ - Git 工作区撤销暂存重命名后按 HEAD 到当前原路径的净内容比较,不再误报不存在的删除;历史提交允许非 UTF-8 消息,父对象标识仍严格验证。
8
+ - 实例方法绑定保留与 Object 原型同名的合法方法,并拒绝同一构造行附加语句或可执行参数造成的错误唯一性。
9
+ - 后台任务卸载等待启动持久化到终态的完整生命周期,取消后不再启动审核;报告目录按真实路径隔离,拒绝祖先 junction/符号链接别名绕过。
10
+ - SVN 标准关键字按原生别名组收缩,固定字段保持 UTF-8 字节宽度;显式上下文末尾同时复核元数据与原始正文哈希,并累计来源预算。
11
+ - 本地文件以只读非阻塞方式打开后验证句柄类型,避免 Linux FIFO 替换挂起;进程取消时关闭自身输出管道并等待直接子进程结束,正常输出仍完整读取,不承诺终止全部后代。
12
+ - 注册表元数据及安装包正文网络中断使用有界重试,格式、地址、超限与完整性失败仍立即拒绝;测试临时 SVN 工作副本及时清理。
13
+
5
14
  ## 0.85.5 — 凭据来源保护与审核边界修复
6
15
 
7
16
  - SVN 独立替换树在读取正文前检查复制来源及祖先来源,阻断从凭据路径复制到普通目标的内容;调用方扫描不再把带源码扩展名的目录当作文件读取。
package/RELEASE-NOTES.md CHANGED
@@ -1,21 +1,22 @@
1
- # v0.85.5 发布说明
1
+ # v0.85.6 发布说明
2
2
 
3
3
  使用方式见 [README](README.md),详细变化见 [变更记录](CHANGELOG.md),发布门禁见 [开发说明](DEVELOPMENT.md)。
4
4
 
5
- ## 安全修复
5
+ ## 审核正确性
6
6
 
7
- SVN 独立替换树现在在读取正文前检查复制来源及复制祖先来源,阻断把凭据文件复制到普通目标后绕过来源过滤的路径。限定调用方扫描也会区分目录与普通文件,带 `.js` 等源码扩展名的目录不再令预览整体失败。
7
+ - Git 撤销暂存重命名后按实际工作区净内容比较;历史审核不再因合法非 UTF-8 提交消息失败。
8
+ - 方法绑定不再遗漏 `toString`、`valueOf` 等合法名称;构造行附加语句、原型替换及可执行参数不再被错误认证。
9
+ - SVN 标准关键字别名与固定字段 UTF-8 字节宽度保持原生语义;显式上下文增加原始正文哈希重验,验证读取继续累计预算。
8
10
 
9
- ## 审核正确性与可用性
11
+ ## 隔离、取消与发布验证
10
12
 
11
- - Git 默认工作区审核合并暂存删除后重建的同路径记录,保持文件身份唯一。
12
- - 自动上下文的目录索引导入不再被误判为越界;仍只读取精确选中的候选正文,不授权目录下任意文件。
13
- - 已选暂存变更同时作为显式上下文时,复用 index 内容并按同侧版本验证,不把尚未暂存的正文混入变更侧。
14
- - 长编辑分次读取后,综合校验按同一快照、来源及版本侧计算连续覆盖;跨来源、有缺口或错误版本的读取仍不能作为有效证据。
15
- - 文件分成超过 20 个窗口批次时,主窗口继续审核并保留已有成果;综合受限单独披露,整体仍为部分完成,不再以异常丢失整轮报告。
13
+ - 后台任务卸载覆盖首次持久化到终态,避免卸载完成后才启动审核;报告目录以真实路径验证工作区隔离,阻断路径别名绕过。
14
+ - 本地文件以只读非阻塞方式打开并验证句柄,避免 Linux FIFO 替换导致等待;取消时关闭自身捕获管道,仍等待直接子进程退出并保留终止升级机制。正常成功路径继续完整收集输出。
15
+ - npm 元数据及安装包正文网络中断按预算重试;无效 JSON、非法工件地址、输出超限及完整性不一致仍立即失败。
16
+ - 补齐测试临时 SVN 仓库与工作副本清理。
16
17
 
17
18
  ## 验证与边界
18
19
 
19
- 本版为六项已复现问题添加回归测试,并执行完整本地测试及隔离安装验证;正式发布须通过同一冻结标签提交的 Ubuntu/Windows × Node.js 22/24 四组 CI、安装包验证和 npm 实际工件一致性门禁。具体执行结果以该标签 CI 和发布工作流为准。
20
+ 新增 43 项回归。本地完整测试:Windows 750 项中 746 通过、4 项平台限定跳过;Linux 750 项全部通过。正式发布仍须通过冻结标签同一提交的 Ubuntu/Windows × Node.js 22/24 四组 CI、隔离安装以及原始包、npm 与 GitHub Release 工件一致性门禁。最终结果以对应 CI 和发布工作流为准。
20
21
 
21
- 本版本不保证模型始终输出合法 JSON,不扩大源码读取权限,不自动安装、升级或重启 DSH;更新并重新加载插件后生效。
22
+ 只读非阻塞打开不是原子防路径替换,不保证任意设备或网络文件系统无阻塞;进程取消不承诺杀死全部后代。本版不保证模型始终输出合法 JSON,也不代表补齐此前自动审核失败的文件。发布不自动安装、升级或重启 DSH;更新并重新加载插件后生效。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@feng0531/dsh-code-review",
3
- "version": "0.85.5",
3
+ "version": "0.85.6",
4
4
  "private": false,
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "publishConfig": { "access": "public", "registry": "https://registry.npmjs.org/" },
@@ -4,6 +4,13 @@
4
4
  const BS = String.fromCharCode(96);
5
5
  const NL = String.fromCharCode(10);
6
6
 
7
+ // Only a whole declaration with inert primitive arguments is proven here. In
8
+ // particular, never exempt a constructor-line suffix or executable argument
9
+ // from the class/instance mutation checks below. Strings are matched as tokens,
10
+ // not stripped as comments (a quoted `);` must not end the declaration).
11
+ const primitiveArgument = /(?:null|true|false|-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?|"(?:[^"\\\r\n]|\\[^\r\n])*"|'(?:[^'\\\r\n]|\\[^\r\n])*')/.source;
12
+ const constructionDeclaration = new RegExp('^\\s*(?:const|let|var)\\s+([A-Za-z_$][A-Za-z0-9_$]*)\\s*=\\s*new\\s+([A-Za-z_$][A-Za-z0-9_$]*)\\s*\\(\\s*(?:' + primitiveArgument + '(?:\\s*,\\s*' + primitiveArgument + ')*\\s*,?)?\\s*\\)\\s*;?\\s*$');
13
+
7
14
  const escapeDollar = name => name.replaceAll('$', '\\$');
8
15
  function boundaryPattern(name, suffix, flags = '') {
9
16
  return new RegExp('(^|[^A-Za-z0-9_$])' + escapeDollar(name) + suffix, flags);
@@ -94,11 +101,11 @@ export function instanceMethodBindings(lines, importLine, targetText) {
94
101
  const body = classBody(targets, classLine);
95
102
  if (!body) return [];
96
103
  const decls = directMethods(body);
97
- const names = {};
98
- for (const d of decls) names[d.name] = (names[d.name] ?? 0) + 1;
104
+ const names = new Map();
105
+ for (const d of decls) names.set(d.name, (names.get(d.name) ?? 0) + 1);
99
106
  const result = [];
100
107
  for (const d of decls) {
101
- if (names[d.name] !== 1) continue;
108
+ if (names.get(d.name) !== 1) continue;
102
109
  if (d.name === 'constructor') continue;
103
110
  const member = d.name;
104
111
  const token = boundaryPattern(member, '(?=[^A-Za-z0-9_$]|$)', 'g');
@@ -115,7 +122,7 @@ export function instanceMethodBindings(lines, importLine, targetText) {
115
122
  if (/[=,:.*#\[\]()]|\b(?:new|function|return|yield|case|throw|typeof|void|delete|instanceof)\b/.test(seg)) continue;
116
123
  let assign = null, inst = null;
117
124
  for (let i = 0; i < lines.length; i++) {
118
- const a = /^\s*(?:const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*new\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*\(/.exec(lines[i]);
125
+ const a = constructionDeclaration.exec(lines[i]);
119
126
  if (a && a[2] === local) { if (assign !== null) return []; assign = i + 1; inst = a[1]; }
120
127
  }
121
128
  if (assign === null || inst === member || inst === klass || inst === local) continue;
package/src/content.mjs CHANGED
@@ -1,6 +1,7 @@
1
1
  import { assertNonSecretPath } from './secret-path.mjs';
2
2
  import path from 'node:path';
3
3
  import { lstat, realpath, open } from 'node:fs/promises';
4
+ import { constants } from 'node:fs';
4
5
  import { createHash } from 'node:crypto';
5
6
 
6
7
  export const hash = value => createHash('sha256').update(value).digest('hex');
@@ -44,7 +45,9 @@ export async function readLocal(root, name, { maxFileBytes = 256 * 1024, signal
44
45
  if (rel.startsWith('..' + path.sep) || rel === '..' || path.isAbsolute(rel)) throw new Error('Path escapes repository');
45
46
  const opened = await lstat(filename);
46
47
  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');
48
+ // A regular file may become a FIFO after lstat. Do not wait for a writer;
49
+ // validate the opened descriptor before reading. These flags never write/create.
50
+ const handle = await open(canonical, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));
48
51
  try {
49
52
  const before = await handle.stat();
50
53
  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');
@@ -20,9 +20,17 @@ async function resolveCommit(root, ref, options) {
20
20
  return oid;
21
21
  }
22
22
 
23
- function parseCommitParents(objectText) {
24
- const header = objectText.split('\n\n', 1)[0];
25
- const parents = header.split('\n').filter(line => line.startsWith('parent ')).map(line => line.slice(7));
23
+ function parseCommitParents(object) {
24
+ // Commit messages (and identities) need not be UTF-8. Decode only the header
25
+ // losslessly; parent object IDs themselves must still be strictly ASCII hex.
26
+ const end = object.indexOf(Buffer.from('\n\n'));
27
+ if (end < 0) throw new Error('Invalid commit header');
28
+ const lines = object.subarray(0, end).toString('latin1').split('\n');
29
+ if (!/^tree (?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(lines[0]) ||
30
+ lines.some(line => line.includes('\0') || !/^(?:[a-z][a-z0-9-]* | )/.test(line))) {
31
+ throw new Error('Invalid commit header');
32
+ }
33
+ const parents = lines.filter(line => line.startsWith('parent ')).map(line => line.slice(7));
26
34
  if (parents.some(oid => !SHA.test(oid))) throw new Error('Invalid commit parent');
27
35
  return parents;
28
36
  }
@@ -75,7 +83,7 @@ export async function captureGitHistory(cwd, options = {}) {
75
83
  if (commit !== undefined) {
76
84
  if (baseRevision !== undefined || targetRevision !== undefined) throw new Error('Commit and range are mutually exclusive');
77
85
  target = await resolveCommit(root, commit, options);
78
- const object = utf8(await gitAt(root, ['cat-file', 'commit', target], options));
86
+ const object = await gitAt(root, ['cat-file', 'commit', target], options);
79
87
  const parents = parseCommitParents(object);
80
88
  if (parents.length > 1) throw new Error('Merge commit requires explicit revision range');
81
89
  base = parents[0] ?? null;
package/src/git.mjs CHANGED
@@ -45,8 +45,15 @@ function changesInScope(changes, scope) {
45
45
  // Worktree compares HEAD to the current file once, retaining the tracked entry
46
46
  // (and its baseline/selection authority), not a second untracked identity.
47
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));
48
+ // A staged rename whose destination was removed compares HEAD's source to
49
+ // that source's current worktree path, not to the absent index destination.
50
+ // Its source remains HEAD-authorized even if porcelain calls it untracked.
51
+ const trackedPaths = new Set(changes.filter(change => change.rawStatus !== '??').map(change => change.path));
52
+ const net = changes.flatMap(change => change.rawStatus === 'RD' && change.oldPath
53
+ ? (trackedPaths.has(change.oldPath) ? [] : [{ path: change.oldPath, rawStatus: 'D ' }])
54
+ : [change]);
55
+ const tracked = new Set(net.filter(change => change.rawStatus !== '??').map(change => change.path));
56
+ return net.filter(change => change.rawStatus !== '??' || !tracked.has(change.path));
50
57
  }
51
58
  if (scope === 'staged') return changes.filter(change => change.rawStatus[0] !== ' ' && change.rawStatus[0] !== '?');
52
59
  return changes.filter(change => change.rawStatus[1] !== ' ' || change.rawStatus === '??');
package/src/process.mjs CHANGED
@@ -19,6 +19,11 @@ export function run(command, args, { cwd, signal, timeoutMs = 0, maxBytes = 8 *
19
19
  failure ??= error;
20
20
  if (stopped) return;
21
21
  stopped = true;
22
+ // Descendants may retain these pipes after the direct child exits. On
23
+ // failure discard owned capture streams, but still join the child via close.
24
+ // Successful commands keep draining to EOF so no output is lost.
25
+ child.stdout?.destroy?.();
26
+ child.stderr?.destroy?.();
22
27
  child.kill();
23
28
  killer = setTimeout(() => { if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL'); }, 1000);
24
29
  killer.unref?.();
@@ -11,17 +11,68 @@ export function createReviewJobs({directory}={}){
11
11
  const identity=exec=>{const a=exec?.agent,s=a?.session;if(!s||!a.options?.provider||!a.options?.model||!s.header?.cwd)throw new Error('Review job requires session identity');const id=s.header.id??s.id;if(typeof id!=='string'||!id)throw new Error('Durable session id required');return {sessionId:id,cwd:s.header.cwd,provider:a.options.provider,model:a.options.model,reasoningEffort:a.options.reasoningEffort??null};};
12
12
  const same=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
13
13
  const pageCheckpoint=(c,offset,limit)=>({...c,...(c.files?{files:c.files.slice(offset,offset+limit),totalFiles:c.files.length}:{}),...(c.findings?{findings:c.findings.slice(offset,offset+limit),totalFindings:c.findings.length}: {})});
14
- const filename=id=>{if(typeof id!=='string'||!/^[a-f0-9-]{36}$/.test(id))throw new Error('Invalid review job id');return path.join(directory,id+'.json');};
15
- async function safeDirectory(){await mkdir(directory,{recursive:true,mode:0o700});const stat=await lstat(directory),resolved=await realpath(directory);if(stat.isSymbolicLink()||!stat.isDirectory()||(canonicalDirectory!==undefined&&resolved!==canonicalDirectory))throw new Error('Unsafe report directory');canonicalDirectory??=resolved;}
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
- 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;}
14
+ const filename=id=>{if(typeof id!=='string'||!/^[a-f0-9-]{36}$/.test(id))throw new Error('Invalid review job id');return path.join(canonicalDirectory??directory,id+'.json');};
15
+ // Resolve existing ancestors before appending a not-yet-created suffix. Lexical
16
+ // paths alone do not identify a workspace reached through a junction or symlink.
17
+ async function projectedRealpath(name){
18
+ let current=path.resolve(name);const suffix=[];
19
+ for(;;){
20
+ try{return path.join(await realpath(current),...suffix);}
21
+ catch(error){
22
+ if(error.code!=='ENOENT')throw error;
23
+ // A dangling link is not an ordinary missing directory.
24
+ try{if((await lstat(current)).isSymbolicLink())throw new Error('Unsafe report directory');}catch(statError){if(statError.code!=='ENOENT')throw statError;}
25
+ const parent=path.dirname(current);if(parent===current)throw error;
26
+ suffix.unshift(path.basename(current));current=parent;
27
+ }
28
+ }
29
+ }
30
+ async function checkDirectory(who){
31
+ const [workspace,resolved]=await Promise.all([projectedRealpath(who.cwd),projectedRealpath(directory)]);
32
+ const relative=path.relative(workspace,resolved);
33
+ if(relative===''||(!relative.startsWith('..'+path.sep)&&relative!=='..'&&!path.isAbsolute(relative)))throw new Error('Report store must be outside reviewed workspace');
34
+ if(canonicalDirectory!==undefined&&resolved!==canonicalDirectory)throw new Error('Unsafe report directory');
35
+ return resolved;
36
+ }
37
+ async function safeDirectory(who){
38
+ const expected=await checkDirectory(who); // Do not even create directories inside the workspace.
39
+ // Use the resolved destination, not a mutable ancestor junction, for creation.
40
+ await mkdir(expected,{recursive:true,mode:0o700});
41
+ const stat=await lstat(directory),resolved=await checkDirectory(who);
42
+ if(stat.isSymbolicLink()||!stat.isDirectory()||resolved!==expected)throw new Error('Unsafe report directory');
43
+ canonicalDirectory??=resolved;
44
+ }
45
+ async function save(job){await safeDirectory(job.record.owner);const tmp=path.join(canonicalDirectory,job.id+'.'+randomUUID()+'.tmp');await writeFile(tmp,JSON.stringify(job.record),{mode:0o600,flag:'wx'});await safeDirectory(job.record.owner);await rename(tmp,filename(job.id));changed(job.id);}
46
+ 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(who);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
47
  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;}
20
- // Keep the serialization tail usable after failure, but return the original
21
- // rejecting operation so checkpoint callers still observe durability failures.
48
+ async start(exec,work){
49
+ if(disposed)throw new Error('Review job service disposed');
50
+ exec.signal?.throwIfAborted();const who=identity(exec);
51
+ 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');
52
+ 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()};
53
+ // Register the entire lifetime before the first await: dispose must also join
54
+ // startup persistence. The start RPC observes startup errors; done never rejects.
55
+ const startup=Promise.resolve().then(()=>save(job));
22
56
  const enqueue=fn=>{const operation=job.pending.then(fn);job.pending=operation.catch(()=>{});return operation;};
23
- // Own cancellation explicitly. The short start RPC ending is NOT task cancellation.
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.'};
57
+ job.done=startup.then(async()=>{
58
+ try{
59
+ controller.signal.throwIfAborted();
60
+ job.record.status='running';await enqueue(()=>save(job));
61
+ controller.signal.throwIfAborted();
62
+ 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);})});
63
+ job.record.result=result;job.record.status=controller.signal.aborted?'cancelled':'completed';
64
+ }catch(error){job.record.status=controller.signal.aborted?'cancelled':'failed';job.record.error=error?.message??String(error);}
65
+ finally{
66
+ job.record.finishedAt=new Date().toISOString();
67
+ try{await enqueue(()=>save(job));jobs.delete(id);}
68
+ catch(error){job.record.status='failed';job.record.persistenceError=error?.message??String(error);}
69
+ finally{changed(id);}
70
+ }
71
+ },()=>{jobs.delete(id);changed(id);});
72
+ jobs.set(id,job);
73
+ // Own cancellation explicitly. The short start RPC ending is NOT cancellation.
74
+ await startup;
75
+ 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.'};
25
76
  },
26
77
  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}: {})};},
27
78
  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};},
@@ -20,6 +20,18 @@ export async function captureSvnExplicitContext(root,names,options={}){
20
20
  }
21
21
  context.push({path:name,...content,...(keywordMapping?{keywordMapping}:{}),...(node.eolStyle?{eolMapping:svnEolMapping(content.text,node.eolStyle)}:{})});identities.push({path:name,fingerprint:node.fingerprint,revision:node.revision});
22
22
  }
23
- const verify=async()=>{for(const node of identities)if((await svnCallerNode(root,node.path,bounded)).fingerprint!==node.fingerprint)throw new Error('SVN explicit context identity changed during capture');signal.throwIfAborted();};
23
+ // SVN metadata can remain identical while raw keyword values change: status
24
+ // compares contracted text, but the original expanded body is our evidence.
25
+ let verifiedBytes=bytes; // sourceBytes below remains the initial capture cost.
26
+ const verify=async()=>{
27
+ for(let i=0;i<identities.length;i++){
28
+ const node=identities[i];
29
+ if((await svnCallerNode(root,node.path,bounded)).fingerprint!==node.fingerprint)throw new Error('SVN explicit context identity changed during capture');
30
+ const current=await readLocal(root,node.path,bounded);bounded.svnNavigationBudget?.charge(current.bytes);verifiedBytes+=current.bytes;
31
+ if(verifiedBytes>1024*1024)throw new Error('SVN explicit context source byte limit exceeded');
32
+ if(current.hash!==context[i].hash)throw new Error('SVN explicit context content changed during capture');
33
+ }
34
+ signal.throwIfAborted();
35
+ };
24
36
  return {context,verify,options:bounded,sourceBytes:bytes,identities};
25
37
  }
@@ -1,7 +1,12 @@
1
1
  import { hash } from './content.mjs';
2
2
  import { keywordConfigurationTokens } from './svn-keyword-config.mjs';
3
3
 
4
- const STANDARD = new Set(['Date', 'LastChangedDate', 'Revision', 'Rev', 'LastChangedRevision', 'Author', 'LastChangedBy', 'HeadURL', 'URL', 'Id', 'Header']);
4
+ // Each standard property spelling enables its complete native SVN alias group.
5
+ const STANDARD_GROUPS = [
6
+ ['Date', 'LastChangedDate'], ['Revision', 'Rev', 'LastChangedRevision'],
7
+ ['Author', 'LastChangedBy'], ['HeadURL', 'URL'], ['Id'], ['Header'],
8
+ ];
9
+ const STANDARD = new Map(STANDARD_GROUPS.flatMap(group => group.map(name => [name, group])));
5
10
  const CUSTOM_DEFINITION = /^([A-Za-z][A-Za-z0-9]*)=(.+)$/;
6
11
  const ALLOWED_FORMAT_FLAGS = 'radDuRPb_HI%';
7
12
  const ALLOWED_LITERAL = /[A-Za-z0-9_.:/ ()-]/;
@@ -23,11 +28,12 @@ function parseCustomFormat(format) {
23
28
  // never reimplemented here; raw source remains the only evidence.
24
29
  export function svnKeywordConfiguration(configuration) {
25
30
  if (typeof configuration !== 'string' || Buffer.byteLength(configuration) > 4096) throw new Error('Invalid SVN keyword configuration');
26
- const enabled = new Set(), custom = [];
31
+ const enabled = new Set(), configured = new Set(), custom = [];
27
32
  for (const token of keywordConfigurationTokens(configuration)) {
28
33
  if (STANDARD.has(token)) {
29
- if (enabled.has(token)) throw new Error('Duplicate SVN keyword configuration');
30
- enabled.add(token);
34
+ if (configured.has(token)) throw new Error('Duplicate SVN keyword configuration');
35
+ configured.add(token);
36
+ for (const alias of STANDARD.get(token)) enabled.add(alias);
31
37
  continue;
32
38
  }
33
39
  const match = CUSTOM_DEFINITION.exec(token);
@@ -47,11 +53,11 @@ export function svnKeywordMapping(text, configuration) {
47
53
  if (!enabled.has(name)) return literal;
48
54
  if (separator === '::') {
49
55
  // SVN reserves the complete field width, including the initial space and
50
- // final space (or # truncation marker); shrink values without changing width.
56
+ // final space (or # truncation marker); retain UTF-8 byte width, not UTF-16 length.
51
57
  if (value.length < 2 || value[0] !== ' ' || ![' ', '#'].includes(value.at(-1))) throw new Error('Ambiguous SVN fixed-width keyword expansion');
52
58
  fixedWidth++;
53
59
  if (/[^ ]/.test(value)) replacements++;
54
- return '$' + name + '::' + ' '.repeat(value.length) + '$';
60
+ return '$' + name + '::' + ' '.repeat(Buffer.byteLength(value, 'utf8')) + '$';
55
61
  }
56
62
  if (!/^ .+ $/.test(value)) throw new Error('Ambiguous SVN keyword expansion');
57
63
  replacements++;