@michengai/dsh-simplify 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/args.js ADDED
@@ -0,0 +1,70 @@
1
+ /** 解析斜杠命令参数;引号用于组合路径,反斜杠按路径字符保留。非法输入抛出 Error。 */
2
+ export function parseArgs(input) {
3
+ if (input.length > 16_384 || input.includes('\0'))
4
+ throw new Error('参数过长或包含 NUL 字符。');
5
+ const tokens = [];
6
+ let current = '';
7
+ let quote = '';
8
+ let started = false;
9
+ const flush = () => {
10
+ if (!started)
11
+ return;
12
+ if (!current)
13
+ throw new Error('不支持空参数。');
14
+ tokens.push(current);
15
+ current = '';
16
+ started = false;
17
+ };
18
+ for (const char of input) {
19
+ if (quote) {
20
+ if (char === quote)
21
+ quote = '';
22
+ else
23
+ current += char;
24
+ }
25
+ else if (char === '"' || char === "'") {
26
+ quote = char;
27
+ started = true;
28
+ }
29
+ else if (/\s/u.test(char))
30
+ flush();
31
+ else {
32
+ current += char;
33
+ started = true;
34
+ }
35
+ }
36
+ if (quote)
37
+ throw new Error('参数中的引号未闭合。');
38
+ flush();
39
+ const files = [];
40
+ let ref = 'HEAD';
41
+ let explicitRef = false;
42
+ let staged = false;
43
+ let ended = false;
44
+ for (let i = 0; i < tokens.length; i++) {
45
+ const token = tokens[i];
46
+ if (!ended && token === '--')
47
+ ended = true;
48
+ else if (!ended && token === '--staged')
49
+ staged = true;
50
+ else if (!ended && (token === '--ref' || token.startsWith('--ref='))) {
51
+ if (explicitRef)
52
+ throw new Error('--ref 只能指定一次。');
53
+ explicitRef = true;
54
+ ref = token === '--ref' ? (tokens[++i] ?? '') : token.slice(6);
55
+ }
56
+ else if (!ended && token.startsWith('-'))
57
+ throw new Error(`未知选项 ${token};此类文件名请放在 -- 后。`);
58
+ else
59
+ files.push(token);
60
+ }
61
+ if (!ref || ref.length > 256 || ref.startsWith('-') || /[\s\0]/u.test(ref) || ref.includes('..')) {
62
+ throw new Error('--ref 必须是单个有效的 Git 提交引用,不支持范围表达式。');
63
+ }
64
+ if (staged && explicitRef)
65
+ throw new Error('--staged 不能与 --ref 同时使用。');
66
+ if (files.length > 200)
67
+ throw new Error('最多指定 200 个路径。');
68
+ return { files, staged, ref, explicitRef };
69
+ }
70
+ //# sourceMappingURL=args.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"args.js","sourceRoot":"","sources":["../src/args.ts"],"names":[],"mappings":"AAOA,iDAAiD;AACjD,MAAM,UAAU,SAAS,CAAC,KAAa;IACrC,IAAI,KAAK,CAAC,MAAM,GAAG,MAAM,IAAI,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAC;IACtF,MAAM,MAAM,GAAa,EAAE,CAAC;IAC5B,IAAI,OAAO,GAAG,EAAE,CAAC;IACjB,IAAI,KAAK,GAAG,EAAE,CAAC;IACf,IAAI,OAAO,GAAG,KAAK,CAAC;IACpB,MAAM,KAAK,GAAG,GAAG,EAAE;QACjB,IAAI,CAAC,OAAO;YAAE,OAAO;QACrB,IAAI,CAAC,OAAO;YAAE,MAAM,IAAI,KAAK,CAAC,SAAS,CAAC,CAAC;QACzC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACrB,OAAO,GAAG,EAAE,CAAC;QACb,OAAO,GAAG,KAAK,CAAC;IAClB,CAAC,CAAC;IACF,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,IAAI,KAAK,EAAE,CAAC;YACV,IAAI,IAAI,KAAK,KAAK;gBAAE,KAAK,GAAG,EAAE,CAAC;;gBAC1B,OAAO,IAAI,IAAI,CAAC;QACvB,CAAC;aAAM,IAAI,IAAI,KAAK,GAAG,IAAI,IAAI,KAAK,GAAG,EAAE,CAAC;YACxC,KAAK,GAAG,IAAI,CAAC;YACb,OAAO,GAAG,IAAI,CAAC;QACjB,CAAC;aAAM,IAAI,KAAK,CAAC,IAA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iB,CAAC,CAAC;;YACvF,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACzB,CAAC;IACD,IAAI,CAAC,GAAG,IAAI,GAAG,CAAC,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;QACjG,MAAM,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAC;IACvD,CAAC;IACD,IAAI,MAAM,IAAI,WAAW;QAAE,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAC;IACvE,IAAI,KAAK,CAAC,MAAM,GAAG,GAAG;QAAE,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;IACzD,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,WAAW,EAAE,CAAC;AAC7C,CAAC","sourcesContent":["export interface SimplifyOptions {\n readonly files: readonly string[];\n readonly staged: boolean;\n readonly ref: string;\n readonly explicitRef: boolean;\n}\n\n/** 解析斜杠命令参数;引号用于组合路径,反斜杠按路径字符保留。非法输入抛出 Error。 */\nexport function parseArgs(input: string): SimplifyOptions {\n if (input.length > 16_384 || input.includes('\\0')) throw new Error('参数过长或包含 NUL 字符。');\n const tokens: string[] = [];\n let current = '';\n let quote = '';\n let started = false;\n const flush = () => {\n if (!started) return;\n if (!current) throw new Error('不支持空参数。');\n tokens.push(current);\n current = '';\n started = false;\n };\n for (const char of input) {\n if (quote) {\n if (char === quote) quote = '';\n else current += char;\n } else if (char === '\"' || char === \"'\") {\n quote = char;\n started = true;\n } else if (/\\s/u.test(char)) flush();\n else { current += char; started = true; }\n }\n if (quote) throw new Error('参数中的引号未闭合。');\n flush();\n const files: string[] = [];\n let ref = 'HEAD';\n let explicitRef = false;\n let staged = false;\n let ended = false;\n for (let i = 0; i < tokens.length; i++) {\n const token = tokens[i]!;\n if (!ended && token === '--') ended = true;\n else if (!ended && token === '--staged') staged = true;\n else if (!ended && (token === '--ref' || token.startsWith('--ref='))) {\n if (explicitRef) throw new Error('--ref 只能指定一次。');\n explicitRef = true;\n ref = token === '--ref' ? (tokens[++i] ?? '') : token.slice(6);\n } else if (!ended && token.startsWith('-')) throw new Error(`未知选项 ${token};此类文件名请放在 -- 后。`);\n else files.push(token);\n }\n if (!ref || ref.length > 256 || ref.startsWith('-') || /[\\s\\0]/u.test(ref) || ref.includes('..')) {\n throw new Error('--ref 必须是单个有效的 Git 提交引用,不支持范围表达式。');\n }\n if (staged && explicitRef) throw new Error('--staged 不能与 --ref 同时使用。');\n if (files.length > 200) throw new Error('最多指定 200 个路径。');\n return { files, staged, ref, explicitRef };\n}\n"]}
@@ -0,0 +1,4 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import type { CommandInvocation, CommandResult } from '@deepseek-ai/dsh-commands';
3
+ /** 执行一次交互式命令;错误只返回 UI,可靠范围才交给当前 Agent。 */
4
+ export declare function handleCommand(ctx: Pick<Context, 'subprocess'>, invocation: CommandInvocation, lifetime?: AbortSignal): Promise<CommandResult>;
package/lib/command.js ADDED
@@ -0,0 +1,44 @@
1
+ import { createUserMessage } from '@deepseek-ai/dsh-llm';
2
+ import { parseArgs } from './args.js';
3
+ import { createGitRunner } from './exec.js';
4
+ import { collectReview, verifyReview } from './git.js';
5
+ import { buildPrompt } from './prompt.js';
6
+ /** 执行一次交互式命令;错误只返回 UI,可靠范围才交给当前 Agent。 */
7
+ export async function handleCommand(ctx, invocation, lifetime) {
8
+ const deadline = new AbortController();
9
+ const timer = setTimeout(() => deadline.abort(), 60_000);
10
+ const signal = AbortSignal.any([invocation.signal, deadline.signal, ...(lifetime ? [lifetime] : [])]);
11
+ try {
12
+ signal.throwIfAborted();
13
+ const options = parseArgs(invocation.rawInput);
14
+ const cwd = invocation.agent.session.header.cwd;
15
+ if (!cwd)
16
+ throw new Error('当前会话没有工作目录,无法确定审查仓库。');
17
+ const run = createGitRunner(ctx.subprocess, signal);
18
+ const review = await collectReview(run, cwd, options);
19
+ signal.throwIfAborted();
20
+ if (!review.files.length) {
21
+ const skipped = review.skipped.slice(0, 10).map(file => `${JSON.stringify(file.path)}:${file.reason}`).join('\n');
22
+ return { kind: 'success', text: `没有可简化的当前代码行。${skipped ? `\n已跳过 ${review.skipped.length} 个文件:\n${skipped}` : ''}` };
23
+ }
24
+ const prompt = buildPrompt(review);
25
+ await verifyReview(run, review);
26
+ signal.throwIfAborted();
27
+ // followup 在当前宿主中同时负责持久入队与唤醒,避免直接操作 inbox 后缺少唤醒。
28
+ invocation.agent.followup(createUserMessage({
29
+ content: [{ type: 'text', text: prompt }],
30
+ source: { kind: 'plugin', plugin: '@michengai/dsh-simplify' },
31
+ }));
32
+ return { kind: 'success', text: `已提交 ${review.files.length} 个文件的简化审查${review.source === 'previous-commit' ? '(回看上一提交)' : ''}。${review.skipped.length ? `已跳过 ${review.skipped.length} 个不可编辑文件。` : ''}` };
33
+ }
34
+ catch (error) {
35
+ const text = deadline.signal.aborted ? '审查范围收集超过 60 秒,请缩小范围后重试。'
36
+ : signal.aborted ? '简化审查已取消。'
37
+ : error instanceof Error ? error.message : String(error);
38
+ return { kind: 'error', text };
39
+ }
40
+ finally {
41
+ clearTimeout(timer);
42
+ }
43
+ }
44
+ //# sourceMappingURL=command.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"command.js","sourceRoot":"","sources":["../src/command.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AAC5C,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AACvD,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C,0CAA0C;AAC1C,MAAM,CAAC,KAAK,UAAU,aAAa,CA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AAC;IACjC,CAAC;YAAS,CAAC;QAAC,YAAY,CAAC,KAAK,CAAC,CAAC;IAAC,CAAC;AACpC,CAAC","sourcesContent":["import type { Context } from '@deepseek-ai/cordis';\nimport type { CommandInvocation, CommandResult } from '@deepseek-ai/dsh-commands';\nimport { createUserMessage } from '@deepseek-ai/dsh-llm';\nimport { parseArgs } from './args.js';\nimport { createGitRunner } from './exec.js';\nimport { collectReview, verifyReview } from './git.js';\nimport { buildPrompt } from './prompt.js';\n\n/** 执行一次交互式命令;错误只返回 UI,可靠范围才交给当前 Agent。 */\nexport async function handleCommand(ctx: Pick<Context, 'subprocess'>, invocation: CommandInvocation, lifetime?: AbortSignal): Promise<CommandResult> {\n const deadline = new AbortController();\n const timer = setTimeout(() => deadline.abort(), 60_000);\n const signal = AbortSignal.any([invocation.signal, deadline.signal, ...(lifetime ? [lifetime] : [])]);\n try {\n signal.throwIfAborted();\n const options = parseArgs(invocation.rawInput);\n const cwd = invocation.agent.session.header.cwd;\n if (!cwd) throw new Error('当前会话没有工作目录,无法确定审查仓库。');\n const run = createGitRunner(ctx.subprocess, signal);\n const review = await collectReview(run, cwd, options);\n signal.throwIfAborted();\n if (!review.files.length) {\n const skipped = review.skipped.slice(0, 10).map(file => `${JSON.stringify(file.path)}:${file.reason}`).join('\\n');\n return { kind: 'success', text: `没有可简化的当前代码行。${skipped ? `\\n已跳过 ${review.skipped.length} 个文件:\\n${skipped}` : ''}` };\n }\n const prompt = buildPrompt(review);\n await verifyReview(run, review);\n signal.throwIfAborted();\n // followup 在当前宿主中同时负责持久入队与唤醒,避免直接操作 inbox 后缺少唤醒。\n invocation.agent.followup(createUserMessage({\n content: [{ type: 'text', text: prompt }],\n source: { kind: 'plugin', plugin: '@michengai/dsh-simplify' },\n }));\n return { kind: 'success', text: `已提交 ${review.files.length} 个文件的简化审查${review.source === 'previous-commit' ? '(回看上一提交)' : ''}。${review.skipped.length ? `已跳过 ${review.skipped.length} 个不可编辑文件。` : ''}` };\n } catch (error) {\n const text = deadline.signal.aborted ? '审查范围收集超过 60 秒,请缩小范围后重试。'\n : signal.aborted ? '简化审查已取消。'\n : error instanceof Error ? error.message : String(error);\n return { kind: 'error', text };\n } finally { clearTimeout(timer); }\n}\n"]}
package/lib/exec.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ import type { SubprocessRuntime } from '@deepseek-ai/dsh-subprocess';
2
+ import type { GitRunner } from './git.js';
3
+ export declare class GitError extends Error {
4
+ readonly code: 'ABORTED' | 'TIMEOUT' | 'UNAVAILABLE' | 'OUTPUT_TRUNCATED' | 'FAILED';
5
+ constructor(code: 'ABORTED' | 'TIMEOUT' | 'UNAVAILABLE' | 'OUTPUT_TRUNCATED' | 'FAILED', message: string);
6
+ }
7
+ /** 创建一次命令共用的 Git 执行器;调用者负责整个审查的截止时间,单次 Git 默认最多 30 秒。 */
8
+ export declare function createGitRunner(subprocess: Pick<SubprocessRuntime, 'spawn'>, signal: AbortSignal, timeoutMs?: number): GitRunner;
package/lib/exec.js ADDED
@@ -0,0 +1,52 @@
1
+ export class GitError extends Error {
2
+ code;
3
+ constructor(code, message) {
4
+ super(message);
5
+ this.code = code;
6
+ this.name = 'GitError';
7
+ }
8
+ }
9
+ /** 创建一次命令共用的 Git 执行器;调用者负责整个审查的截止时间,单次 Git 默认最多 30 秒。 */
10
+ export function createGitRunner(subprocess, signal, timeoutMs = 30_000) {
11
+ return async (args, cwd, allowedCodes = [0]) => {
12
+ if (signal.aborted)
13
+ throw new GitError('ABORTED', '简化审查已取消。');
14
+ const timeout = new AbortController();
15
+ const combined = AbortSignal.any([signal, timeout.signal]);
16
+ const timer = setTimeout(() => timeout.abort(), timeoutMs);
17
+ const checkAbort = () => {
18
+ if (signal.aborted)
19
+ throw new GitError('ABORTED', '简化审查已取消。');
20
+ if (timeout.signal.aborted)
21
+ throw new GitError('TIMEOUT', `Git 执行超过 ${timeoutMs} 毫秒。`);
22
+ };
23
+ try {
24
+ const handle = subprocess.spawn({
25
+ argv: ['git', ...args], cwd, signal: combined, graceMs: 1_000,
26
+ stdio: { stdin: 'ignore', stdout: { maxBytes: 8 * 1024 * 1024 }, stderr: { maxBytes: 64 * 1024 } },
27
+ env: { GIT_TERMINAL_PROMPT: '0', GIT_OPTIONAL_LOCKS: '0', GIT_PAGER: 'cat' },
28
+ });
29
+ const outcome = await handle.done;
30
+ checkAbort();
31
+ const stdout = handle.collected.stdout?.readFrom(0);
32
+ const stderr = handle.collected.stderr?.readFrom(0);
33
+ if (!stdout || stdout.lossy || stderr?.lossy)
34
+ throw new GitError('OUTPUT_TRUNCATED', 'Git 输出缺失或被截断,请缩小审查范围。');
35
+ if (outcome.exitCode === null || outcome.signal || !allowedCodes.includes(outcome.exitCode)) {
36
+ const detail = stderr?.text.trim().slice(0, 2_000);
37
+ throw new GitError('FAILED', `Git 执行失败(退出码 ${outcome.exitCode ?? '未知'})${detail ? `:${detail}` : '。'}`);
38
+ }
39
+ return { code: outcome.exitCode, stdout: stdout.text };
40
+ }
41
+ catch (error) {
42
+ checkAbort();
43
+ if (error instanceof GitError)
44
+ throw error;
45
+ throw new GitError('UNAVAILABLE', `无法执行 Git:${error instanceof Error ? error.message : String(error)}`);
46
+ }
47
+ finally {
48
+ clearTimeout(timer);
49
+ }
50
+ };
51
+ }
52
+ //# sourceMappingURL=exec.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"exec.js","sourceRoot":"","sources":["../src/exec.ts"],"names":[],"mappings":"AAGA,MAAM,OAAO,QAAS,SAAQ,KAAK;IACZ;IAArB,YAAqB,IAA2E,EAAE,OAAe;QAC/G,KAAK,CAAC,OAAO,CAAC,CAAC;QADI,SAAI,GAAJ,IAAI,CAAuE;QAE9F,IAAI,CAAC,IAAI,GAAG,UAAU,CAAC;IACzB,CAAC;CACF;AAED,yDAAyD;AACzD,MAAM,UAAU,eAAe,CAAC,UAA4C,EAAE,MAAmB,EAAE,SAAS,GAAG,MAAM;IACnH,OAAO,KAAK,EAAE,IAAI,EAAE,GAAG,EAAE,Y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,CAAC","sourcesContent":["import type { SubprocessRuntime } from '@deepseek-ai/dsh-subprocess';\nimport type { GitRunner } from './git.js';\n\nexport class GitError extends Error {\n constructor(readonly code: 'ABORTED' | 'TIMEOUT' | 'UNAVAILABLE' | 'OUTPUT_TRUNCATED' | 'FAILED', message: string) {\n super(message);\n this.name = 'GitError';\n }\n}\n\n/** 创建一次命令共用的 Git 执行器;调用者负责整个审查的截止时间,单次 Git 默认最多 30 秒。 */\nexport function createGitRunner(subprocess: Pick<SubprocessRuntime, 'spawn'>, signal: AbortSignal, timeoutMs = 30_000): GitRunner {\n return async (args, cwd, allowedCodes = [0]) => {\n if (signal.aborted) throw new GitError('ABORTED', '简化审查已取消。');\n const timeout = new AbortController();\n const combined = AbortSignal.any([signal, timeout.signal]);\n const timer = setTimeout(() => timeout.abort(), timeoutMs);\n const checkAbort = () => {\n if (signal.aborted) throw new GitError('ABORTED', '简化审查已取消。');\n if (timeout.signal.aborted) throw new GitError('TIMEOUT', `Git 执行超过 ${timeoutMs} 毫秒。`);\n };\n try {\n const handle = subprocess.spawn({\n argv: ['git', ...args], cwd, signal: combined, graceMs: 1_000,\n stdio: { stdin: 'ignore', stdout: { maxBytes: 8 * 1024 * 1024 }, stderr: { maxBytes: 64 * 1024 } },\n env: { GIT_TERMINAL_PROMPT: '0', GIT_OPTIONAL_LOCKS: '0', GIT_PAGER: 'cat' },\n });\n const outcome = await handle.done;\n checkAbort();\n const stdout = handle.collected.stdout?.readFrom(0);\n const stderr = handle.collected.stderr?.readFrom(0);\n if (!stdout || stdout.lossy || stderr?.lossy) throw new GitError('OUTPUT_TRUNCATED', 'Git 输出缺失或被截断,请缩小审查范围。');\n if (outcome.exitCode === null || outcome.signal || !allowedCodes.includes(outcome.exitCode)) {\n const detail = stderr?.text.trim().slice(0, 2_000);\n throw new GitError('FAILED', `Git 执行失败(退出码 ${outcome.exitCode ?? '未知'})${detail ? `:${detail}` : '。'}`);\n }\n return { code: outcome.exitCode, stdout: stdout.text };\n } catch (error) {\n checkAbort();\n if (error instanceof GitError) throw error;\n throw new GitError('UNAVAILABLE', `无法执行 Git:${error instanceof Error ? error.message : String(error)}`);\n } finally { clearTimeout(timer); }\n };\n}\n"]}
package/lib/git.d.ts ADDED
@@ -0,0 +1,42 @@
1
+ import type { SimplifyOptions } from './args.js';
2
+ export type GitRunner = (args: readonly string[], cwd: string, allowedCodes?: readonly number[]) => Promise<{
3
+ code: number;
4
+ stdout: string;
5
+ }>;
6
+ export interface LineRange {
7
+ readonly start: number;
8
+ readonly end: number;
9
+ }
10
+ interface Change {
11
+ readonly path: string;
12
+ readonly status: string;
13
+ readonly oldPath?: string;
14
+ }
15
+ export interface ReviewFile extends Change {
16
+ readonly ranges: readonly LineRange[];
17
+ readonly sha256: string;
18
+ }
19
+ export interface Review {
20
+ readonly root: string;
21
+ readonly head: string | undefined;
22
+ readonly base: string | undefined;
23
+ readonly staged: boolean;
24
+ readonly paths: readonly string[];
25
+ readonly indexSnapshot: string | undefined;
26
+ readonly source: 'worktree' | 'staged' | 'ref' | 'previous-commit';
27
+ readonly files: readonly ReviewFile[];
28
+ readonly skipped: readonly {
29
+ path: string;
30
+ reason: string;
31
+ }[];
32
+ }
33
+ /** 解析 Git -z 文件列表,拒绝不完整记录以免把截断输出当作完整范围。 */
34
+ export declare function nulFields(text: string): string[];
35
+ export declare function parseNameStatus(text: string): Change[];
36
+ /** 按 unified diff 正文计数,只开放新增行;块计数不一致时抛错。 */
37
+ export declare function parseChangedLines(text: string): LineRange[];
38
+ /** 收集可审查文本文件及行号快照;Git 失败、冲突或不可靠范围会抛错,不产生部分成功。 */
39
+ export declare function collectReview(run: GitRunner, cwd: string, options: SimplifyOptions): Promise<Review>;
40
+ /** 在提交提示词前复核内容及 HEAD;这不是 Agent 后续写入权限的硬限制。 */
41
+ export declare function verifyReview(run: GitRunner, review: Review): Promise<void>;
42
+ export {};
package/lib/git.js ADDED
@@ -0,0 +1,262 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { lstat, open, realpath } from 'node:fs/promises';
3
+ import { isAbsolute, relative, resolve, sep } from 'node:path';
4
+ const MAX_FILES = 200;
5
+ const MAX_FILE_BYTES = 5 * 1024 * 1024;
6
+ const STATUS = { A: 'added', M: 'modified', R: 'renamed', C: 'copied', D: 'deleted', T: 'type-changed', U: 'unmerged', X: 'unknown', B: 'broken' };
7
+ const DIFF = ['diff', '--no-color', '--no-ext-diff', '--no-textconv', '--no-relative', '--ignore-submodules=all', '--find-renames'];
8
+ const GLOBAL = ['--no-pager', '--literal-pathspecs', '-c', 'color.ui=false'];
9
+ /** 解析 Git -z 文件列表,拒绝不完整记录以免把截断输出当作完整范围。 */
10
+ export function nulFields(text) {
11
+ if (!text)
12
+ return [];
13
+ if (!text.endsWith('\0'))
14
+ throw new Error('Git 文件列表不完整。');
15
+ return text.slice(0, -1).split('\0');
16
+ }
17
+ export function parseNameStatus(text) {
18
+ const fields = nulFields(text);
19
+ const files = [];
20
+ for (let i = 0; i < fields.length;) {
21
+ const code = fields[i++];
22
+ const status = STATUS[code[0]];
23
+ const first = fields[i++];
24
+ if (!status || !first || !/^[ACDMRTUXB]\d*$/u.test(code))
25
+ throw new Error('Git 文件状态格式无效。');
26
+ if (code.startsWith('R') || code.startsWith('C')) {
27
+ const path = fields[i++];
28
+ if (!path)
29
+ throw new Error('Git 重命名记录不完整。');
30
+ files.push({ path, oldPath: first, status });
31
+ }
32
+ else
33
+ files.push({ path: first, status });
34
+ }
35
+ return files;
36
+ }
37
+ /** 按 unified diff 正文计数,只开放新增行;块计数不一致时抛错。 */
38
+ export function parseChangedLines(text) {
39
+ const result = [];
40
+ let block;
41
+ let segment;
42
+ const flush = () => {
43
+ if (segment !== undefined && block)
44
+ result.push({ start: segment, end: block.cursor - 1 });
45
+ segment = undefined;
46
+ };
47
+ const finish = () => {
48
+ if (block && (block.oldLeft !== 0 || block.newLeft !== 0))
49
+ throw new Error('Git 补丁正文不完整。');
50
+ flush();
51
+ block = undefined;
52
+ };
53
+ const rows = (text.endsWith('\n') ? text.slice(0, -1) : text).split('\n');
54
+ for (const row of rows) {
55
+ if (row.startsWith('@@')) {
56
+ finish();
57
+ const header = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?: .*)?$/u.exec(row);
58
+ if (!header)
59
+ throw new Error('Git 补丁块头无效。');
60
+ const [oldStart, oldLeft, cursor, newLeft] = [Number(header[1]), Number(header[2] ?? 1), Number(header[3]), Number(header[4] ?? 1)];
61
+ for (const [start, count] of [[oldStart, oldLeft], [cursor, newLeft]]) {
62
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(count) || !Number.isSafeInteger(start + count) || (count > 0 && start === 0)) {
63
+ throw new Error('Git 补丁行号超出有效范围。');
64
+ }
65
+ }
66
+ block = { oldLeft: oldLeft, newLeft: newLeft, cursor: cursor };
67
+ continue;
68
+ }
69
+ if (row.startsWith('diff --git ')) {
70
+ finish();
71
+ continue;
72
+ }
73
+ if (!block)
74
+ continue;
75
+ if (row === '\')
76
+ continue;
77
+ switch (row[0]) {
78
+ case '+':
79
+ segment ??= block.cursor;
80
+ block.cursor++;
81
+ block.newLeft--;
82
+ break;
83
+ case '-':
84
+ block.oldLeft--;
85
+ break;
86
+ case ' ':
87
+ flush();
88
+ block.cursor++;
89
+ block.oldLeft--;
90
+ block.newLeft--;
91
+ break;
92
+ default:
93
+ throw new Error('Git 补丁正文格式无效。');
94
+ }
95
+ if (block.oldLeft < 0 || block.newLeft < 0)
96
+ throw new Error('Git 补丁正文超过声明行数。');
97
+ }
98
+ finish();
99
+ return result;
100
+ }
101
+ function inside(root, path) {
102
+ const rel = relative(root, path);
103
+ return !isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`);
104
+ }
105
+ async function fingerprint(root, path) {
106
+ const absolute = resolve(root, path);
107
+ if (!inside(root, absolute))
108
+ throw new Error('Git 返回了仓库外路径。');
109
+ const stat = await lstat(absolute);
110
+ if (!stat.isFile())
111
+ return { reason: '非普通文件(符号链接或子模块等)' };
112
+ if (!inside(root, await realpath(absolute)))
113
+ return { reason: '路径指向仓库外' };
114
+ if (stat.size > MAX_FILE_BYTES)
115
+ return { reason: '文件超过 5 MiB' };
116
+ const handle = await open(absolute, 'r');
117
+ try {
118
+ const buffer = Buffer.alloc(Math.min(stat.size + 1, MAX_FILE_BYTES + 1));
119
+ let offset = 0;
120
+ while (offset < buffer.length) {
121
+ const { bytesRead } = await handle.read(buffer, offset, buffer.length - offset, null);
122
+ if (!bytesRead)
123
+ break;
124
+ offset += bytesRead;
125
+ }
126
+ if (offset !== stat.size)
127
+ throw new Error(`文件在读取时发生变化:${JSON.stringify(path)},请重试。`);
128
+ const content = buffer.subarray(0, offset);
129
+ if (content.includes(0))
130
+ return { reason: '二进制文件' };
131
+ return { sha256: createHash('sha256').update(content).digest('hex') };
132
+ }
133
+ finally {
134
+ await handle.close();
135
+ }
136
+ }
137
+ async function revision(run, root, ref) {
138
+ const result = await run([...GLOBAL, 'rev-parse', '--verify', '--quiet', '--end-of-options', `${ref}^{commit}`], root, [0, 1]);
139
+ return result.code === 0 ? result.stdout.trim() : undefined;
140
+ }
141
+ async function assertStagedClean(run, root, paths) {
142
+ if (!paths.length)
143
+ return;
144
+ const result = await run([...GLOBAL, ...DIFF, '--name-only', '-z', '--', ...paths], root);
145
+ if (result.stdout)
146
+ throw new Error('待审查的暂存文件还有未暂存改动。请先暂存或自行保存这些改动,再运行 --staged。');
147
+ }
148
+ /** 收集可审查文本文件及行号快照;Git 失败、冲突或不可靠范围会抛错,不产生部分成功。 */
149
+ export async function collectReview(run, cwd, options) {
150
+ if (!cwd)
151
+ throw new Error('当前会话没有工作目录。');
152
+ const rootResult = await run([...GLOBAL, 'rev-parse', '--show-toplevel'], cwd);
153
+ const root = await realpath(rootResult.stdout.replace(/\r?\n$/u, ''));
154
+ const sessionRoot = await realpath(cwd);
155
+ const paths = options.files.map(path => {
156
+ const absolute = resolve(sessionRoot, path);
157
+ if (!inside(root, absolute))
158
+ throw new Error(`路径不在当前仓库内:${JSON.stringify(path)}`);
159
+ return relative(root, absolute).split(sep).join('/') || '.';
160
+ });
161
+ const head = await revision(run, root, 'HEAD');
162
+ let base = options.explicitRef ? await revision(run, root, options.ref) : head;
163
+ if (options.explicitRef && !base)
164
+ throw new Error(`无效的 Git 引用:${options.ref}`);
165
+ let source = options.staged ? 'staged' : options.explicitRef ? 'ref' : 'worktree';
166
+ const scope = ['--', ...paths];
167
+ const indexSnapshot = options.staged ? (await run([...GLOBAL, 'ls-files', '--stage', '-z', ...scope], root)).stdout : undefined;
168
+ const conflicts = await run([...GLOBAL, 'ls-files', '--unmerged', '-z', ...scope], root);
169
+ if (conflicts.stdout)
170
+ throw new Error('所选范围存在未解决的 Git 冲突,请先解决冲突。');
171
+ for (const path of paths) {
172
+ const existing = await run([...GLOBAL, 'ls-files', '--cached', '--others', '--exclude-standard', '-z', '--', path], root);
173
+ if (!existing.stdout)
174
+ throw new Error(`路径不存在、被忽略或未纳入 Git:${JSON.stringify(path)}`);
175
+ }
176
+ const list = async (ref) => {
177
+ if (!ref && !options.staged) {
178
+ const tracked = await run([...GLOBAL, 'ls-files', '--cached', '-z', ...scope], root);
179
+ return [...new Set(nulFields(tracked.stdout))].map(path => ({ path, status: 'added' }));
180
+ }
181
+ const result = await run([...GLOBAL, ...DIFF, '--name-status', '-z', ...(options.staged ? ['--cached'] : [ref]), ...scope], root);
182
+ return parseNameStatus(result.stdout);
183
+ };
184
+ let changes = await list(base);
185
+ if (!options.staged) {
186
+ const untracked = await run([...GLOBAL, 'ls-files', '--others', '--exclude-standard', '-z', ...scope], root);
187
+ const known = new Set(changes.map(file => file.path));
188
+ for (const path of nulFields(untracked.stdout))
189
+ if (!known.has(path)) {
190
+ changes.push({ path, status: 'added' });
191
+ known.add(path);
192
+ }
193
+ }
194
+ if (!changes.length && head && !options.staged && !options.explicitRef && !paths.length) {
195
+ const parent = await revision(run, root, `${head}^`);
196
+ if (parent) {
197
+ base = parent;
198
+ source = 'previous-commit';
199
+ changes = await list(base);
200
+ }
201
+ }
202
+ if (changes.length > MAX_FILES)
203
+ throw new Error('变更超过 200 个文件,请通过路径缩小审查范围。');
204
+ if (options.staged)
205
+ await assertStagedClean(run, root, changes.flatMap(file => file.oldPath ? [file.oldPath, file.path] : [file.path]));
206
+ const files = [];
207
+ const skipped = [];
208
+ for (const file of changes) {
209
+ if (['deleted', 'type-changed', 'unmerged', 'unknown', 'broken'].includes(file.status)) {
210
+ skipped.push({ path: file.path, reason: `不可编辑的文件状态:${file.status}` });
211
+ continue;
212
+ }
213
+ let before;
214
+ try {
215
+ before = await fingerprint(root, file.path);
216
+ }
217
+ catch (error) {
218
+ if (!head && error.code === 'ENOENT') {
219
+ skipped.push({ path: file.path, reason: '新仓库中已从工作区删除' });
220
+ continue;
221
+ }
222
+ throw error;
223
+ }
224
+ if ('reason' in before) {
225
+ skipped.push({ path: file.path, reason: before.reason });
226
+ continue;
227
+ }
228
+ let ranges = [];
229
+ if (file.status !== 'added') {
230
+ const diff = await run([...GLOBAL, ...DIFF, '--unified=0', '--inter-hunk-context=0', ...(options.staged ? ['--cached'] : [base]), '--', ...(file.oldPath ? [file.oldPath] : []), file.path], root);
231
+ ranges = parseChangedLines(diff.stdout);
232
+ const after = await fingerprint(root, file.path);
233
+ if (!('sha256' in after) || after.sha256 !== before.sha256)
234
+ throw new Error(`文件在收集范围时发生变化:${JSON.stringify(file.path)},请重试。`);
235
+ if (!ranges.length) {
236
+ skipped.push({ path: file.path, reason: '没有可简化的当前行(纯删除、仅重命名或非文本 diff)' });
237
+ continue;
238
+ }
239
+ }
240
+ files.push({ ...file, ranges, sha256: before.sha256 });
241
+ }
242
+ const review = { root, head, base, source, staged: options.staged, paths, indexSnapshot, files, skipped };
243
+ await verifyReview(run, review);
244
+ return review;
245
+ }
246
+ /** 在提交提示词前复核内容及 HEAD;这不是 Agent 后续写入权限的硬限制。 */
247
+ export async function verifyReview(run, review) {
248
+ if (await revision(run, review.root, 'HEAD') !== review.head)
249
+ throw new Error('HEAD 在收集范围后发生变化,请重新运行 /simplify。');
250
+ if (review.staged) {
251
+ const index = await run([...GLOBAL, 'ls-files', '--stage', '-z', '--', ...review.paths], review.root);
252
+ if (index.stdout !== review.indexSnapshot)
253
+ throw new Error('暂存区在收集范围后发生变化,请重新运行 /simplify。');
254
+ await assertStagedClean(run, review.root, review.files.map(file => file.path));
255
+ }
256
+ for (const file of review.files) {
257
+ const current = await fingerprint(review.root, file.path);
258
+ if (!('sha256' in current) || current.sha256 !== file.sha256)
259
+ throw new Error(`文件已变化:${JSON.stringify(file.path)},请重新运行 /simplify。`);
260
+ }
261
+ }
262
+ //# sourceMappingURL=git.js.map
package/lib/git.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"git.js","sourceRoot":"","sources":["../src/git.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AACzD,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAqB/D,MAAM,SAAS,GAAG,GAAG,CAAC;AACtB,MAAM,cAAc,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;AACvC,MAAM,MAAM,GAA2B,EAAE,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,QAAQ,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,cAAc,EAAE,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,QAAQ,EAAE,CAAC;AAC3K,MAAM,IAAI,GAAG,CAAC,MAAM,EAAE,YAAY,EAAE,eAAe,EAAE,eAAe,EAAE,eAAe,EAAE,yBAAyB,EAAE,gBAAgB,CAAC,CAAC;AACpI,MAAM,MAAM,GAAG,CAAC,YAAY,E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AAI,MAAM,CAAC,KAAK,EAAE,CAAC;QAChC,MAAM,OAAO,GAAG,MAAM,WAAW,CAAC,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;QAC1D,IAAI,CAAC,CAAC,QAAQ,IAAI,OAAO,CAAC,IAAI,OAAO,CAAC,MAAM,KAAK,IAAI,CAAC,MAAM;YAAE,MAAM,IAAI,KAAK,CAAC,SAAS,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC;IACvI,CAAC;AACH,CAAC","sourcesContent":["import type { SimplifyOptions } from './args.js';\nimport { createHash } from 'node:crypto';\nimport { lstat, open, realpath } from 'node:fs/promises';\nimport { isAbsolute, relative, resolve, sep } from 'node:path';\n\nexport type GitRunner = (args: readonly string[], cwd: string, allowedCodes?: readonly number[]) => Promise<{ code: number; stdout: string }>;\n\nexport interface LineRange { readonly start: number; readonly end: number }\ninterface Change { readonly path: string; readonly status: string; readonly oldPath?: string }\nexport interface ReviewFile extends Change {\n readonly ranges: readonly LineRange[];\n readonly sha256: string;\n}\nexport interface Review {\n readonly root: string;\n readonly head: string | undefined;\n readonly base: string | undefined;\n readonly staged: boolean;\n readonly paths: readonly string[];\n readonly indexSnapshot: string | undefined;\n readonly source: 'worktree' | 'staged' | 'ref' | 'previous-commit';\n readonly files: readonly ReviewFile[];\n readonly skipped: readonly { path: string; reason: string }[];\n}\nconst MAX_FILES = 200;\nconst MAX_FILE_BYTES = 5 * 1024 * 1024;\nconst STATUS: Record<string, string> = { A: 'added', M: 'modified', R: 'renamed', C: 'copied', D: 'deleted', T: 'type-changed', U: 'unmerged', X: 'unknown', B: 'broken' };\nconst DIFF = ['diff', '--no-color', '--no-ext-diff', '--no-textconv', '--no-relative', '--ignore-submodules=all', '--find-renames'];\nconst GLOBAL = ['--no-pager', '--literal-pathspecs', '-c', 'color.ui=false'];\n\n/** 解析 Git -z 文件列表,拒绝不完整记录以免把截断输出当作完整范围。 */\nexport function nulFields(text: string): string[] {\n if (!text) return [];\n if (!text.endsWith('\\0')) throw new Error('Git 文件列表不完整。');\n return text.slice(0, -1).split('\\0');\n}\n\nexport function parseNameStatus(text: string): Change[] {\n const fields = nulFields(text);\n const files: Change[] = [];\n for (let i = 0; i < fields.length;) {\n const code = fields[i++]!;\n const status = STATUS[code[0]!];\n const first = fields[i++];\n if (!status || !first || !/^[ACDMRTUXB]\\d*$/u.test(code)) throw new Error('Git 文件状态格式无效。');\n if (code.startsWith('R') || code.startsWith('C')) {\n const path = fields[i++];\n if (!path) throw new Error('Git 重命名记录不完整。');\n files.push({ path, oldPath: first, status });\n } else files.push({ path: first, status });\n }\n return files;\n}\n\n/** 按 unified diff 正文计数,只开放新增行;块计数不一致时抛错。 */\nexport function parseChangedLines(text: string): LineRange[] {\n const result: LineRange[] = [];\n let block: { oldLeft: number; newLeft: number; cursor: number } | undefined;\n let segment: number | undefined;\n const flush = (): void => {\n if (segment !== undefined && block) result.push({ start: segment, end: block.cursor - 1 });\n segment = undefined;\n };\n const finish = (): void => {\n if (block && (block.oldLeft !== 0 || block.newLeft !== 0)) throw new Error('Git 补丁正文不完整。');\n flush();\n block = undefined;\n };\n const rows = (text.endsWith('\\n') ? text.slice(0, -1) : text).split('\\n');\n for (const row of rows) {\n if (row.startsWith('@@')) {\n finish();\n const header = /^@@ -(\\d+)(?:,(\\d+))? \\+(\\d+)(?:,(\\d+))? @@(?: .*)?$/u.exec(row);\n if (!header) throw new Error('Git 补丁块头无效。');\n const [oldStart, oldLeft, cursor, newLeft] = [Number(header[1]), Number(header[2] ?? 1), Number(header[3]), Number(header[4] ?? 1)];\n for (const [start, count] of [[oldStart!, oldLeft!], [cursor!, newLeft!]]) {\n if (!Number.isSafeInteger(start) || !Number.isSafeInteger(count) || !Number.isSafeInteger(start! + count!) || (count! > 0 && start === 0)) {\n throw new Error('Git 补丁行号超出有效范围。');\n }\n }\n block = { oldLeft: oldLeft!, newLeft: newLeft!, cursor: cursor! };\n continue;\n }\n if (row.startsWith('diff --git ')) { finish(); continue; }\n if (!block) continue;\n if (row === '\\\') continue;\n switch (row[0]) {\n case '+':\n segment ??= block.cursor;\n block.cursor++;\n block.newLeft--;\n break;\n case '-':\n block.oldLeft--;\n break;\n case ' ':\n flush();\n block.cursor++;\n block.oldLeft--;\n block.newLeft--;\n break;\n default:\n throw new Error('Git 补丁正文格式无效。');\n }\n if (block.oldLeft < 0 || block.newLeft < 0) throw new Error('Git 补丁正文超过声明行数。');\n }\n finish();\n return result;\n}\n\nfunction inside(root: string, path: string): boolean {\n const rel = relative(root, path);\n return !isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`);\n}\n\nasync function fingerprint(root: string, path: string): Promise<{ sha256: string } | { reason: string }> {\n const absolute = resolve(root, path);\n if (!inside(root, absolute)) throw new Error('Git 返回了仓库外路径。');\n const stat = await lstat(absolute);\n if (!stat.isFile()) return { reason: '非普通文件(符号链接或子模块等)' };\n if (!inside(root, await realpath(absolute))) return { reason: '路径指向仓库外' };\n if (stat.size > MAX_FILE_BYTES) return { reason: '文件超过 5 MiB' };\n const handle = await open(absolute, 'r');\n try {\n const buffer = Buffer.alloc(Math.min(stat.size + 1, MAX_FILE_BYTES + 1));\n let offset = 0;\n while (offset < buffer.length) {\n const { bytesRead } = await handle.read(buffer, offset, buffer.length - offset, null);\n if (!bytesRead) break;\n offset += bytesRead;\n }\n if (offset !== stat.size) throw new Error(`文件在读取时发生变化:${JSON.stringify(path)},请重试。`);\n const content = buffer.subarray(0, offset);\n if (content.includes(0)) return { reason: '二进制文件' };\n return { sha256: createHash('sha256').update(content).digest('hex') };\n } finally { await handle.close(); }\n}\n\nasync function revision(run: GitRunner, root: string, ref: string): Promise<string | undefined> {\n const result = await run([...GLOBAL, 'rev-parse', '--verify', '--quiet', '--end-of-options', `${ref}^{commit}`], root, [0, 1]);\n return result.code === 0 ? result.stdout.trim() : undefined;\n}\n\nasync function assertStagedClean(run: GitRunner, root: string, paths: readonly string[]): Promise<void> {\n if (!paths.length) return;\n const result = await run([...GLOBAL, ...DIFF, '--name-only', '-z', '--', ...paths], root);\n if (result.stdout) throw new Error('待审查的暂存文件还有未暂存改动。请先暂存或自行保存这些改动,再运行 --staged。');\n}\n\n/** 收集可审查文本文件及行号快照;Git 失败、冲突或不可靠范围会抛错,不产生部分成功。 */\nexport async function collectReview(run: GitRunner, cwd: string, options: SimplifyOptions): Promise<Review> {\n if (!cwd) throw new Error('当前会话没有工作目录。');\n const rootResult = await run([...GLOBAL, 'rev-parse', '--show-toplevel'], cwd);\n const root = await realpath(rootResult.stdout.replace(/\\r?\\n$/u, ''));\n const sessionRoot = await realpath(cwd);\n const paths = options.files.map(path => {\n const absolute = resolve(sessionRoot, path);\n if (!inside(root, absolute)) throw new Error(`路径不在当前仓库内:${JSON.stringify(path)}`);\n return relative(root, absolute).split(sep).join('/') || '.';\n });\n const head = await revision(run, root, 'HEAD');\n let base = options.explicitRef ? await revision(run, root, options.ref) : head;\n if (options.explicitRef && !base) throw new Error(`无效的 Git 引用:${options.ref}`);\n let source: Review['source'] = options.staged ? 'staged' : options.explicitRef ? 'ref' : 'worktree';\n const scope = ['--', ...paths];\n const indexSnapshot = options.staged ? (await run([...GLOBAL, 'ls-files', '--stage', '-z', ...scope], root)).stdout : undefined;\n const conflicts = await run([...GLOBAL, 'ls-files', '--unmerged', '-z', ...scope], root);\n if (conflicts.stdout) throw new Error('所选范围存在未解决的 Git 冲突,请先解决冲突。');\n for (const path of paths) {\n const existing = await run([...GLOBAL, 'ls-files', '--cached', '--others', '--exclude-standard', '-z', '--', path], root);\n if (!existing.stdout) throw new Error(`路径不存在、被忽略或未纳入 Git:${JSON.stringify(path)}`);\n }\n const list = async (ref: string | undefined): Promise<Change[]> => {\n if (!ref && !options.staged) {\n const tracked = await run([...GLOBAL, 'ls-files', '--cached', '-z', ...scope], root);\n return [...new Set(nulFields(tracked.stdout))].map(path => ({ path, status: 'added' }));\n }\n const result = await run([...GLOBAL, ...DIFF, '--name-status', '-z', ...(options.staged ? ['--cached'] : [ref!]), ...scope], root);\n return parseNameStatus(result.stdout);\n };\n let changes = await list(base);\n if (!options.staged) {\n const untracked = await run([...GLOBAL, 'ls-files', '--others', '--exclude-standard', '-z', ...scope], root);\n const known = new Set(changes.map(file => file.path));\n for (const path of nulFields(untracked.stdout)) if (!known.has(path)) { changes.push({ path, status: 'added' }); known.add(path); }\n }\n if (!changes.length && head && !options.staged && !options.explicitRef && !paths.length) {\n const parent = await revision(run, root, `${head}^`);\n if (parent) { base = parent; source = 'previous-commit'; changes = await list(base); }\n }\n if (changes.length > MAX_FILES) throw new Error('变更超过 200 个文件,请通过路径缩小审查范围。');\n if (options.staged) await assertStagedClean(run, root, changes.flatMap(file => file.oldPath ? [file.oldPath, file.path] : [file.path]));\n const files: ReviewFile[] = [];\n const skipped: { path: string; reason: string }[] = [];\n for (const file of changes) {\n if (['deleted', 'type-changed', 'unmerged', 'unknown', 'broken'].includes(file.status)) {\n skipped.push({ path: file.path, reason: `不可编辑的文件状态:${file.status}` });\n continue;\n }\n let before;\n try { before = await fingerprint(root, file.path); }\n catch (error) {\n if (!head && (error as NodeJS.ErrnoException).code === 'ENOENT') { skipped.push({ path: file.path, reason: '新仓库中已从工作区删除' }); continue; }\n throw error;\n }\n if ('reason' in before) { skipped.push({ path: file.path, reason: before.reason }); continue; }\n let ranges: LineRange[] = [];\n if (file.status !== 'added') {\n const diff = await run([...GLOBAL, ...DIFF, '--unified=0', '--inter-hunk-context=0', ...(options.staged ? ['--cached'] : [base!]), '--', ...(file.oldPath ? [file.oldPath] : []), file.path], root);\n ranges = parseChangedLines(diff.stdout);\n const after = await fingerprint(root, file.path);\n if (!('sha256' in after) || after.sha256 !== before.sha256) throw new Error(`文件在收集范围时发生变化:${JSON.stringify(file.path)},请重试。`);\n if (!ranges.length) { skipped.push({ path: file.path, reason: '没有可简化的当前行(纯删除、仅重命名或非文本 diff)' }); continue; }\n }\n files.push({ ...file, ranges, sha256: before.sha256 });\n }\n const review: Review = { root, head, base, source, staged: options.staged, paths, indexSnapshot, files, skipped };\n await verifyReview(run, review);\n return review;\n}\n\n/** 在提交提示词前复核内容及 HEAD;这不是 Agent 后续写入权限的硬限制。 */\nexport async function verifyReview(run: GitRunner, review: Review): Promise<void> {\n if (await revision(run, review.root, 'HEAD') !== review.head) throw new Error('HEAD 在收集范围后发生变化,请重新运行 /simplify。');\n if (review.staged) {\n const index = await run([...GLOBAL, 'ls-files', '--stage', '-z', '--', ...review.paths], review.root);\n if (index.stdout !== review.indexSnapshot) throw new Error('暂存区在收集范围后发生变化,请重新运行 /simplify。');\n await assertStagedClean(run, review.root, review.files.map(file => file.path));\n }\n for (const file of review.files) {\n const current = await fingerprint(review.root, file.path);\n if (!('sha256' in current) || current.sha256 !== file.sha256) throw new Error(`文件已变化:${JSON.stringify(file.path)},请重新运行 /simplify。`);\n }\n}\n"]}
package/lib/index.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ export declare const name = "michengai-simplify";
3
+ export declare const inject: string[];
4
+ /** 注册 /simplify;卸载时取消正在收集的范围,并等待其 Git 进程结束。 */
5
+ export declare function apply(ctx: Context): void;
package/lib/index.js ADDED
@@ -0,0 +1,27 @@
1
+ import { handleCommand } from './command.js';
2
+ export const name = 'michengai-simplify';
3
+ export const inject = ['commands', 'subprocess'];
4
+ /** 注册 /simplify;卸载时取消正在收集的范围,并等待其 Git 进程结束。 */
5
+ export function apply(ctx) {
6
+ ctx.effect(() => {
7
+ const lifetime = new AbortController();
8
+ const active = new Set();
9
+ const unregister = ctx.commands.register({
10
+ name: 'simplify',
11
+ description: '简化最近改动的代码,保持功能并限定修改范围',
12
+ input: { hint: '[--staged] [--ref=<ref>] [--] [文件或目录...]' },
13
+ handler: invocation => {
14
+ const operation = handleCommand(ctx, invocation, lifetime.signal);
15
+ active.add(operation);
16
+ void operation.then(() => active.delete(operation), () => active.delete(operation));
17
+ return operation;
18
+ },
19
+ });
20
+ return async () => {
21
+ lifetime.abort();
22
+ unregister();
23
+ await Promise.allSettled(active);
24
+ };
25
+ });
26
+ }
27
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAE7C,MAAM,CAAC,MAAM,IAAI,GAAG,oBAAoB,CAAC;AACzC,MAAM,CAAC,MAAM,MAAM,GAAG,CAAC,UAAU,EAAE,YAAY,CAAC,CAAC;AAEjD,+CAA+C;AAC/C,MAAM,UAAU,KAAK,CAAC,GAAY;IAChC,GAAG,CAAC,MAAM,CAAC,GAAG,EAAE;QACd,MAAM,QAAQ,GAAG,IAAI,eAAe,EAAE,CAAC;QACvC,MAAM,MAAM,GAAG,IAAI,GAAG,EAA0B,CAAC;QACjD,MAAM,UAAU,GAAG,GAAG,CAAC,QAAQ,CAAC,QAAQ,CAAC;YACvC,IAAI,EAAE,UAAU;YAChB,WAAW,EAAE,uBAAuB;YACpC,KAAK,EAAE,EAAE,IAAI,EAAE,0CAA0C,EAAE;YAC3D,OAAO,EAAE,UAAU,CAAC,EAAE;gBACpB,MAAM,SAAS,GAAG,aAAa,CAAC,GAAG,EAAE,UAAU,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC;gBAClE,MAAM,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;gBACtB,KAAK,SAAS,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC;gBACpF,OAAO,SAAS,CAAC;YACnB,CAAC;SACF,CAAC,CAAC;QACH,OAAO,KAAK,IAAI,EAAE;YAChB,QAAQ,CAAC,KAAK,EAAE,CAAC;YACjB,UAAU,EAAE,CAAC;YACb,MAAM,OAAO,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;QACnC,CAAC,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { Context } from '@deepseek-ai/cordis';\nimport type { CommandResult } from '@deepseek-ai/dsh-commands';\nimport { handleCommand } from './command.js';\n\nexport const name = 'michengai-simplify';\nexport const inject = ['commands', 'subprocess'];\n\n/** 注册 /simplify;卸载时取消正在收集的范围,并等待其 Git 进程结束。 */\nexport function apply(ctx: Context): void {\n ctx.effect(() => {\n const lifetime = new AbortController();\n const active = new Set<Promise<CommandResult>>();\n const unregister = ctx.commands.register({\n name: 'simplify',\n description: '简化最近改动的代码,保持功能并限定修改范围',\n input: { hint: '[--staged] [--ref=<ref>] [--] [文件或目录...]' },\n handler: invocation => {\n const operation = handleCommand(ctx, invocation, lifetime.signal);\n active.add(operation);\n void operation.then(() => active.delete(operation), () => active.delete(operation));\n return operation;\n },\n });\n return async () => {\n lifetime.abort();\n unregister();\n await Promise.allSettled(active);\n };\n });\n}\n"]}
@@ -0,0 +1,4 @@
1
+ import type { Review } from './git.js';
2
+ export declare const MAX_PROMPT_BYTES: number;
3
+ /** 将已验证的 Git 范围转成当前会话的编辑任务,超出消息预算时抛错。 */
4
+ export declare function buildPrompt(review: Review): string;