Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): Review 新鲜度绑定 dirty submodule 内部改动 (#2515)
fico-huba1af4c20fb13
diff --git a/apps/desktop/src/main/git-review/__tests__/statusReader.test.ts b/apps/desktop/src/main/git-review/__tests__/statusReader.test.tsindex 073fd1205f..9f8b1b605c 100644--- a/apps/desktop/src/main/git-review/__tests__/statusReader.test.ts+++ b/apps/desktop/src/main/git-review/__tests__/statusReader.test.ts@@ -71,6 +71,28 @@ describe('git-review statusReader', () => {expect(status.untrackedCount).toBe(1);expect(status.unmergedCount).toBe(1);expect(status.writeDisabledReasons).toContain('unmerged');+ // 普通文件冲突不是 submodule;XY 取自记录本身,不再硬编码。+ const conflict = status.files.find((f) => f.path === 'conflict.txt');+ expect(conflict?.isSubmodule).toBe(false);+ expect(conflict?.rawXY).toBe('UU');+ });++ it('keeps submodule identity on unmerged gitlink records (#2463 review)', () => {+ // 顶层 gitlink 的合并冲突:porcelain=2 的 u 记录 sub 字段为 S 开头 ——+ // 丢掉它会让冲突 gitlink 绕过 submodule reader,目录被普通文件指纹器+ // 拒绝、合法冲突无法启动 Review。+ const status = parsePorcelainV2Status(+ [+ 'u AA S... 160000 160000 160000 160000 aaaaaaa bbbbbbb ccccccc vendor/lib',+ '',+ ].join('\0'),+ scope,+ );++ const gitlink = status.files.find((f) => f.path === 'vendor/lib');+ expect(gitlink?.isSubmodule).toBe(true);+ expect(gitlink?.isUnmerged).toBe(true);+ expect(gitlink?.rawXY).toBe('AA');});it('marks SSH workspace status as view-only', () => {@@ -106,4 +128,28 @@ describe('git-review statusReader', () => {maxStdoutBytes: 128 * 1024 * 1024,});});++ it('passes --ignore-submodules=none so ignore-configured submodules stay visible (#2463 review)', async () => {+ // submodule.<name>.ignore=all/dirty 会让 status 省略脏子仓,dirty 内容进不了+ // Review 发现链;submoduleEvidencePaths() 的 status 兜底显式依赖这个 flag。+ // flag 被静默丢掉时新鲜度绕过会复现,必须有断言拦住。+ runGitMock.mockImplementation(async (args: readonly string[]) => {+ if (args[0] === 'status') {+ return {+ stdout: ['# branch.oid abcdef', '# branch.head main', ''].join('\0'),+ stderr: '',+ exitCode: 0,+ };+ }+ if (args[0] === 'rev-parse') {+ return { stdout: `/repo/.git/${args.at(-1) ?? 'marker'}\n`, stderr: '', exitCode: 0 };+ }+ throw new Error(`unexpected git args: ${args.join(' ')}`);+ });++ await readStatus(scope);++ const statusCall = runGitMock.mock.calls.find(([args]) => (args as readonly string[])[0] === 'status');+ expect(statusCall?.[0]).toContain('--ignore-submodules=none');+ });});diff --git a/apps/desktop/src/main/git-review/indexIdentityReader.ts b/apps/desktop/src/main/git-review/indexIdentityReader.tsindex a85dcad3a1..25b20fcaa7 100644--- a/apps/desktop/src/main/git-review/indexIdentityReader.ts+++ b/apps/desktop/src/main/git-review/indexIdentityReader.ts@@ -36,7 +36,10 @@ export interface IndexIdentityBatchLimits {maxBatchPaths?: number;}-function splitIntoBatches(paths: string[], limits?: IndexIdentityBatchLimits): string[][] {+export function splitIntoBatches(+ paths: readonly string[],+ limits?: IndexIdentityBatchLimits,+): string[][] {const maxBytes = limits?.maxBatchPathspecBytes ?? MAX_BATCH_PATHSPEC_BYTES;const maxPaths = limits?.maxBatchPaths ?? MAX_BATCH_PATHS;const batches: string[][] = [];diff --git a/apps/desktop/src/main/git-review/statusReader.ts b/apps/desktop/src/main/git-review/statusReader.tsindex 92dea919f1..78cf7bc04b 100644--- a/apps/desktop/src/main/git-review/statusReader.ts+++ b/apps/desktop/src/main/git-review/statusReader.ts@@ -179,6 +179,12 @@ export function parsePorcelainV2Status(stdout: string, baseScope: ReviewScope):if (tag === 'u') {const parsed = splitFixedFields(record, 10);if (!parsed) continue;+ // u 记录同样携带 XY 与 sub 字段(porcelain=2:u <XY> <sub> <m1..mW>+ // <h1..h3> <path>)。sub 不能丢:顶层 gitlink 的合并冲突(如 UU 的+ // submodule)必须保留 submodule 身份,否则不会被路由进 submodule+ // reader,gitlink 目录会被普通文件指纹器拒绝、合法冲突无法启动+ // Review(Codex review #2515)。+ const [, xy, sub] = parsed.fields;files.push({path: parsed.rest,oldPath: null,@@ -186,9 +192,9 @@ export function parsePorcelainV2Status(stdout: string, baseScope: ReviewScope):worktreeStatus: 'unmerged',isUntracked: false,isUnmerged: true,- isSubmodule: false,+ isSubmodule: isSubmoduleField(sub),sources: ['staged', 'unstaged'],- rawXY: 'UU',+ rawXY: xy,});}}@@ -271,7 +277,11 @@ export async function readStatus(scope: ReviewScope): Promise<ReviewStatus> {dirty: false,};}- const { stdout } = await runGit(['status', '--porcelain=2', '-z', '--branch', '--renames', '--untracked-files=all'], {+ // --ignore-submodules=none:仓库配置 submodule.<name>.ignore=all/dirty 会让+ // status 直接省略脏的 submodule,dirty 内容根本进不了 Review 发现链 ——+ // 新鲜度身份绑定必须无视该配置(与 reviewSubmoduleIdentity 的子仓 status+ // 同一裁决,Codex review #2515)。+ const { stdout } = await runGit(['status', '--porcelain=2', '-z', '--branch', '--renames', '--untracked-files=all', '--ignore-submodules=none'], {cwd: scope.repoRoot,maxStdoutBytes: STATUS_MAX_STDOUT_BYTES,});diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewCappedWorkspaceFingerprint.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewCappedWorkspaceFingerprint.test.tsindex 5734b7ddd9..b06744eb70 100644--- a/apps/desktop/src/main/reviewer/__tests__/reviewCappedWorkspaceFingerprint.test.ts+++ b/apps/desktop/src/main/reviewer/__tests__/reviewCappedWorkspaceFingerprint.test.ts@@ -80,6 +80,65 @@ describe('capped Review workspace fingerprint', () => {).rejects.toBeInstanceOf(ReviewCappedWorkspaceFingerprintError);});+ it.skipIf(process.platform === 'win32')(+ 'symlinkMode link-text binds the link text without resolving the target (#2463 review)',+ async () => {+ // 悬空 / 指向仓库外的 symlink 是合法 Git 改动(Git 记录的内容就是链接+ // 文本);resolve 语义下会 fail closed 中止,link-text 语义绑定文本本身。+ const repoRoot = await makeTempDir();+ const link = path.join(repoRoot, 'link.ts');+ await fs.symlink('../shared/lib', link);+ const opts = { symlinkMode: 'link-text' as const };++ const before = await fingerprintReviewCappedWorkspaceFiles(repoRoot, ['link.ts'], opts);+ const again = await fingerprintReviewCappedWorkspaceFiles(repoRoot, ['link.ts'], opts);+ expect(again).toBe(before);++ await fs.unlink(link);+ await fs.symlink('../shared/other', link);+ const after = await fingerprintReviewCappedWorkspaceFiles(repoRoot, ['link.ts'], opts);+ expect(after).not.toBe(before);+ },+ );++ it.skipIf(process.platform === 'win32')(+ 'symlinkMode link-text distinguishes non-UTF-8 target bytes (#2463 review)',+ async () => {+ // readlink 默认按 UTF-8 解码,0xff / 0xfe 等非法字节都坍缩成替换字符:+ // 原始字节不同的两个链接文本必须产生不同指纹。+ const repoRoot = await makeTempDir();+ const link = path.join(repoRoot, 'raw-link');+ const opts = { symlinkMode: 'link-text' as const };++ await fs.symlink(Buffer.from([0x2e, 0x2e, 0x2f, 0xff]), link);+ const withFf = await fingerprintReviewCappedWorkspaceFiles(repoRoot, ['raw-link'], opts);+ await fs.unlink(link);+ await fs.symlink(Buffer.from([0x2e, 0x2e, 0x2f, 0xfe]), link);+ const withFe = await fingerprintReviewCappedWorkspaceFiles(repoRoot, ['raw-link'], opts);++ expect(withFe).not.toBe(withFf);+ },+ );++ it.skipIf(process.platform === 'win32')(+ 'symlinkMode link-text never reads target bytes (#2463 review)',+ async () => {+ // 指向敏感文件的链接:只绑定文本,目标内容变化不得进入指纹 ——+ // 反证目标字节从未被读取。+ const repoRoot = await makeTempDir();+ const sensitive = path.join(repoRoot, '.env.local');+ await fs.writeFile(sensitive, 'TOKEN=first');+ await fs.symlink('.env.local', path.join(repoRoot, 'safe-name.ts'));+ const opts = { symlinkMode: 'link-text' as const };++ const before = await fingerprintReviewCappedWorkspaceFiles(repoRoot, ['safe-name.ts'], opts);+ await fs.writeFile(sensitive, 'TOKEN=other-value');+ const after = await fingerprintReviewCappedWorkspaceFiles(repoRoot, ['safe-name.ts'], opts);++ expect(after).toBe(before);+ },+ );+it('fails closed instead of degrading to metadata above the byte limit', async () => {const repoRoot = await makeTempDir();await fs.writeFile(path.join(repoRoot, 'large.ts'), '1234');@@ -89,3 +148,30 @@ describe('capped Review workspace fingerprint', () => {).rejects.toBeInstanceOf(ReviewCappedWorkspaceFingerprintLimitError);});});++describe('git 路径词法校验的平台语义 (#2463 review)', () => {+ it.skipIf(process.platform === 'win32')(+ 'accepts POSIX filenames containing backslashes (C:\\notes, dir\\..\\file)',+ async () => {+ // 反斜杠在 POSIX 上是普通文件名字符,git 会原样输出 —— 不能按 win32+ // 语义误判为绝对路径/越界而中止 Review。+ const repoRoot = await makeTempDir();+ await fs.writeFile(path.join(repoRoot, 'C:\\notes'), 'a');+ await fs.writeFile(path.join(repoRoot, 'dir\\..\\file'), 'b');++ await expect(+ fingerprintReviewCappedWorkspaceFiles(repoRoot, ['C:\\notes', 'dir\\..\\file']),+ ).resolves.toBeTruthy();+ },+ );++ it('still rejects "/"-separated parent traversal and absolute paths', async () => {+ const repoRoot = await makeTempDir();+ await expect(+ fingerprintReviewCappedWorkspaceFiles(repoRoot, ['../escape.ts']),+ ).rejects.toBeInstanceOf(ReviewCappedWorkspaceFingerprintError);+ await expect(+ fingerprintReviewCappedWorkspaceFiles(repoRoot, ['/abs.ts']),+ ).rejects.toBeInstanceOf(ReviewCappedWorkspaceFingerprintError);+ });+});diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewEvidence.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewEvidence.test.tsindex 1f8dd41419..eac985685d 100644--- a/apps/desktop/src/main/reviewer/__tests__/reviewEvidence.test.ts+++ b/apps/desktop/src/main/reviewer/__tests__/reviewEvidence.test.ts@@ -486,9 +486,9 @@ describe('readReviewWorkspaceSnapshot', () => {it('does not hand a dirty submodule to the file fingerprinter', async () => {// A gitlink is a directory and the fingerprinter accepts only regular// files, so including it would abort evidence loading and make the whole- // dirty workspace unreviewable. The cost of excluding it — edits inside- // the submodule are not bound — is stated at the call site and tracked in- // #2463; it is not offset by the porcelain status, which keeps no oid.+ // dirty workspace unreviewable. Its identity is bound by the submodule+ // reader instead (#2463) — stubbed here because this fixture directory is+ // not a real Git repository.const repoRoot = await tempDir();const submodulePath = 'vendor/lib';await fs.mkdir(path.join(repoRoot, submodulePath), { recursive: true });@@ -507,7 +507,259 @@ describe('readReviewWorkspaceSnapshot', () => {},});- await expect(readReviewWorkspaceSnapshot('source')).resolves.toBeTruthy();+ await expect(+ readReviewWorkspaceSnapshot('source', {+ readSubmoduleIdentity: async () => ({ identities: [], hashedContent: false }),+ }),+ ).resolves.toBeTruthy();+ });++ it('excludes capped submodule entries from the content fingerprint paths (#2463 review)', async () => {+ // capped bucket 里的 submodule 条目不得进入普通文件指纹器:gitlink 是+ // 目录,指纹器会直接抛错,含 capped 子仓的大型 dirty workspace 整个+ // Review 起不来;其身份由 submodule reader 绑定。+ const repoRoot = await tempDir();+ const submodulePath = 'vendor/lib';+ await fs.mkdir(path.join(repoRoot, submodulePath), { recursive: true });+ const data = cappedReviewData(repoRoot, submodulePath);+ readReviewDataMock.mockResolvedValue({+ ...data,+ status: data.status+ ? { ...data.status, files: data.status.files.map((f) => ({ ...f, isSubmodule: true })) }+ : data.status,+ diffs: {+ ...data.diffs,+ capped: {+ staged: null,+ unstaged: {+ ...data.diffs.capped!.unstaged!,+ files: data.diffs.capped!.unstaged!.files.map((f) => ({ ...f, isSubmodule: true })),+ },+ },+ },+ });+ const fingerprintCappedWorkspaceFiles = vi.fn(+ async (_repoRoot: string, _paths: readonly string[]) => 'digest',+ );+ const readSubmoduleIdentity = vi.fn(+ async (_repoRoot: string, _paths: readonly string[]) => ({+ identities: [],+ hashedContent: false,+ }),+ );++ await expect(+ readReviewWorkspaceSnapshot('source', {+ fingerprintCappedWorkspaceFiles,+ readSubmoduleIdentity,+ }),+ ).resolves.toBeTruthy();+ for (const [, paths] of fingerprintCappedWorkspaceFiles.mock.calls) {+ expect(paths).not.toContain(submodulePath);+ }+ expect(readSubmoduleIdentity).toHaveBeenCalled();+ expect(readSubmoduleIdentity.mock.calls[0]?.[1]).toContain(submodulePath);+ });++ it('binds a status-only dirty submodule missing from every diff bucket (#2463 review)', async () => {+ // ignoreWhitespace 下只含 untracked 内部内容的子仓没有 numstat 条目,+ // summary 构建把它当空白改动滤掉;unstaged bucket 又处于 capped、不建+ // detail diff——此时它只存在于 status 里。身份收集必须从净化后的+ // status 记录补齐,否则内层同尺寸替换可穿过两道新鲜度门(Codex review)。+ const repoRoot = await tempDir();+ const cappedPath = 'src/big.ts';+ const submodulePath = 'vendor/lib';+ await fs.mkdir(path.join(repoRoot, submodulePath), { recursive: true });+ const data = cappedReviewData(repoRoot, cappedPath);+ readReviewDataMock.mockResolvedValue({+ ...data,+ status: data.status+ ? {+ ...data.status,+ files: [+ ...data.status.files,+ {+ path: submodulePath,+ oldPath: null,+ indexStatus: null,+ worktreeStatus: 'modified' as const,+ isUntracked: false,+ isUnmerged: false,+ isSubmodule: true,+ sources: ['unstaged' as const],+ rawXY: ' M',+ },+ ],+ }+ : data.status,+ // diffs 保持原样:capped bucket 与 detail diffs 都不含该子仓。+ });+ const fingerprintCappedWorkspaceFiles = vi.fn(+ async (_repoRoot: string, _paths: readonly string[]) => 'digest',+ );+ const readSubmoduleIdentity = vi.fn(+ async (_repoRoot: string, _paths: readonly string[]) => ({+ identities: [],+ hashedContent: false,+ }),+ );++ await expect(+ readReviewWorkspaceSnapshot('source', {+ fingerprintCappedWorkspaceFiles,+ readSubmoduleIdentity,+ }),+ ).resolves.toBeTruthy();+ expect(readSubmoduleIdentity).toHaveBeenCalled();+ expect(readSubmoduleIdentity.mock.calls[0]?.[1]).toContain(submodulePath);+ // 子仓仍不得进入普通文件指纹器。+ for (const [, paths] of fingerprintCappedWorkspaceFiles.mock.calls) {+ expect(paths).not.toContain(submodulePath);+ }+ });++ it('fails closed instead of probing local fs for a remote workspace submodule (#2463 review)', async () => {+ // SSH 远程 review 的 repoRoot 是远端路径:本机 fs 探测会把 ENOENT 误判成+ // uninitialized 放行过期结论,同路径本机目录还会绑错字节。命中 dirty+ // submodule 的远程快照必须显式拒绝,且不得触碰 submodule reader。+ const repoRoot = await tempDir();+ const submodulePath = 'vendor/lib';+ const data = cappedReviewData(repoRoot, 'src/big.ts');+ const remoteScope = { ...data.scope, source: 'remote' as const };+ readReviewDataMock.mockResolvedValue({+ ...data,+ scope: remoteScope,+ status: data.status+ ? {+ ...data.status,+ scope: remoteScope,+ files: [+ ...data.status.files,+ {+ path: submodulePath,+ oldPath: null,+ indexStatus: null,+ worktreeStatus: 'modified' as const,+ isUntracked: false,+ isUnmerged: false,+ isSubmodule: true,+ sources: ['unstaged' as const],+ rawXY: ' M',+ },+ ],+ }+ : data.status,+ });+ const readSubmoduleIdentity = vi.fn(+ async (_repoRoot: string, _paths: readonly string[]) => ({+ identities: [],+ hashedContent: false,+ }),+ );++ await expect(+ readReviewWorkspaceSnapshot('source', {+ fingerprintCappedWorkspaceFiles: vi.fn(async () => 'digest'),+ readSubmoduleIdentity,+ }),+ ).rejects.toThrow(/SSH remote/);+ expect(readSubmoduleIdentity).not.toHaveBeenCalled();+ });++ it('keeps a remote workspace snapshot working when no submodule is involved (#2463 review)', async () => {+ const repoRoot = await tempDir();+ const data = cappedReviewData(repoRoot, 'src/big.ts');+ const remoteScope = { ...data.scope, source: 'remote' as const };+ readReviewDataMock.mockResolvedValue({+ ...data,+ scope: remoteScope,+ status: data.status ? { ...data.status, scope: remoteScope } : data.status,+ });++ await expect(+ readReviewWorkspaceSnapshot('source', {+ fingerprintCappedWorkspaceFiles: vi.fn(async () => 'digest'),+ readSubmoduleIdentity: vi.fn(async () => ({ identities: [], hashedContent: false })),+ }),+ ).resolves.toBeTruthy();+ });++ it('routes submodule evidence to the identity reader and binds the manifest (#2463)', async () => {+ const repoRoot = await tempDir();+ const submodulePath = 'vendor/lib';+ await fs.mkdir(path.join(repoRoot, submodulePath), { recursive: true });+ const data = binaryReviewData(repoRoot, submodulePath);+ readReviewDataMock.mockResolvedValue({+ ...data,+ diffs: {+ ...data.diffs,+ unstaged: data.diffs.unstaged.map((diff) => ({+ ...diff,+ kind: 'unrenderable' as const,+ isBinary: false,+ isSubmodule: true,+ error: null,+ })),+ },+ });+ const manifest = (subHead: string) => ({+ identities: [+ {+ path: submodulePath,+ indexRecord: `160000 0 ${'c'.repeat(40)}`,+ headRecord: `160000 commit ${'c'.repeat(40)}`,+ subHead,+ stagedIdentity: [],+ statusRecords: [],+ dirtyContentFingerprint: null,+ nested: [],+ },+ ],+ hashedContent: false,+ });++ const before = await readReviewWorkspaceSnapshot('source', {+ readSubmoduleIdentity: async (_repoRoot, paths) => {+ expect(paths).toEqual([submodulePath]);+ return manifest('a'.repeat(40));+ },+ });+ const after = await readReviewWorkspaceSnapshot('source', {+ readSubmoduleIdentity: async () => manifest('b'.repeat(40)),+ });++ expect(after?.workspace).toEqual(before?.workspace);+ expect(before?.fingerprint).toMatch(/^[a-f0-9]{64}$/);+ expect(after?.fingerprint).not.toBe(before?.fingerprint);+ });++ it('fails closed when the submodule identity cannot be read (#2463)', async () => {+ const repoRoot = await tempDir();+ const submodulePath = 'vendor/lib';+ await fs.mkdir(path.join(repoRoot, submodulePath), { recursive: true });+ const data = binaryReviewData(repoRoot, submodulePath);+ readReviewDataMock.mockResolvedValue({+ ...data,+ diffs: {+ ...data.diffs,+ unstaged: data.diffs.unstaged.map((diff) => ({+ ...diff,+ kind: 'unrenderable' as const,+ isBinary: false,+ isSubmodule: true,+ error: null,+ })),+ },+ });+ const failure = new Error('submodule identity unreadable');++ await expect(+ readReviewWorkspaceSnapshot('source', {+ readSubmoduleIdentity: async () => {+ throw failure;+ },+ }),+ ).rejects.toBe(failure);});it('marks prepared Git evidence stale when the workspace changes before launch', async () => {diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewSubmoduleIdentity.git-integration.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewSubmoduleIdentity.git-integration.test.tsnew file mode 100644index 0000000000..4a05a9f708--- /dev/null+++ b/apps/desktop/src/main/reviewer/__tests__/reviewSubmoduleIdentity.git-integration.test.ts@@ -0,0 +1,689 @@+import { promises as fs } from 'node:fs';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++// Windows 上 git 子进程明显更慢(每次 spawn 数百毫秒),多步 git 编排用例会超默认 5s。+vi.setConfig({ testTimeout: process.platform === 'win32' ? 120_000 : 60_000 });++import { runGit } from '../../git-review/gitRunner';+import { readStatus } from '../../git-review/statusReader';+import type { ReviewScope } from '../../git-review/types';+import {+ readReviewSubmoduleIdentity,+ ReviewSubmoduleIdentityError,+} from '../reviewSubmoduleIdentity';++let workRoot: string;+let parentPath: string;++// CI runner 没有全局 git 身份;每个会执行 commit 的仓库(含 submodule 克隆)都要配本地身份。+async function configureRepo(dir: string): Promise<void> {+ await runGit(['config', 'user.email', '[email protected]'], { cwd: dir });+ await runGit(['config', 'user.name', 'XDT Test'], { cwd: dir });+ await runGit(['config', 'commit.gpgsign', 'false'], { cwd: dir });+ await runGit(['config', 'core.autocrlf', 'false'], { cwd: dir });+}++async function initRepo(dir: string): Promise<void> {+ await fs.mkdir(dir, { recursive: true });+ await runGit(['init'], { cwd: dir });+ await configureRepo(dir);+}++/** 父仓 + 已初始化 submodule(vendor/lib,含一个已提交文件 inner.txt)。 */+async function setupParentWithSubmodule(): Promise<{ parent: string; sub: string }> {+ const upstream = path.join(workRoot, 'lib-upstream');+ await initRepo(upstream);+ await fs.writeFile(path.join(upstream, 'inner.txt'), 'inner-v1\n');+ await runGit(['add', 'inner.txt'], { cwd: upstream });+ await runGit(['commit', '--no-gpg-sign', '-m', 'inner seed'], { cwd: upstream });++ const parent = path.join(workRoot, 'parent');+ await initRepo(parent);+ await fs.writeFile(path.join(parent, 'root.txt'), 'root\n');+ await runGit(['add', 'root.txt'], { cwd: parent });+ await runGit(['commit', '--no-gpg-sign', '-m', 'parent seed'], { cwd: parent });+ await runGit(+ ['-c', 'protocol.file.allow=always', 'submodule', 'add', upstream, 'vendor/lib'],+ { cwd: parent },+ );+ await runGit(['commit', '--no-gpg-sign', '-m', 'add submodule'], { cwd: parent });+ const sub = path.join(parent, 'vendor', 'lib');+ await configureRepo(sub);+ return { parent, sub };+}++beforeEach(async () => {+ workRoot = await fs.mkdtemp(path.join((await import('node:os')).tmpdir(), 'xdt-review-submodule-'));+ parentPath = '';+});++afterEach(async () => {+ await fs.rm(workRoot, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 });+});++describe('readReviewSubmoduleIdentity (#2463)', () => {+ it('binds inner dirty content: swapping one internal edit for another changes the manifest', async () => {+ const { parent, sub } = await setupParentWithSubmodule();+ parentPath = parent;+ const inner = path.join(sub, 'inner.txt');++ // 内部改动 A:同长度字节,父仓 porcelain 只有一个 dirty 布尔位可看。+ await fs.writeFile(inner, 'inner-vA\n');+ const withEditA = await readReviewSubmoduleIdentity(parentPath, ['vendor/lib']);+ // 内部改动 B:同尺寸另一份 —— #2463 的攻击形态。+ await fs.writeFile(inner, 'inner-vB\n');+ const withEditB = await readReviewSubmoduleIdentity(parentPath, ['vendor/lib']);++ expect(withEditA.identities).toHaveLength(1);+ expect(withEditA.hashedContent).toBe(true);+ expect(withEditB.identities).not.toEqual(withEditA.identities);+ });++ it('binds the inner staged identity: index blob swap with restored worktree changes the manifest', async () => {+ const { parent, sub } = await setupParentWithSubmodule();+ parentPath = parent;+ const inner = path.join(sub, 'inner.txt');++ await fs.writeFile(inner, 'inner-vA\n');+ await runGit(['add', 'inner.txt'], { cwd: sub });+ const stagedA = await readReviewSubmoduleIdentity(parentPath, ['vendor/lib']);++ // 换 index blob 后把工作树字节还原:工作树哈希看不出差异,靠 staged 身份。+ await fs.writeFile(inner, 'inner-vB\n');+ await runGit(['add', 'inner.txt'], { cwd: sub });+ await fs.writeFile(inner, 'inner-vA\n');+ const stagedB = await readReviewSubmoduleIdentity(parentPath, ['vendor/lib']);++ expect(stagedB.identities).not.toEqual(stagedA.identities);+ });++ it('keeps a clean submodule manifest stable and records gitlink + inner HEAD', async () => {+ const { parent } = await setupParentWithSubmodule();+ parentPath = parent;++ const first = await readReviewSubmoduleIdentity(parentPath, ['vendor/lib']);+ const second = await readReviewSubmoduleIdentity(parentPath, ['vendor/lib']);++ expect(second).toEqual(first);+ const identity = first.identities[0];+ expect(identity.path).toBe('vendor/lib');+ expect(identity.indexRecord).toMatch(/^160000 0 [0-9a-f]{40,64}$/);+ expect(identity.headRecord).toMatch(/^160000 commit [0-9a-f]{40,64}$/);+ expect(identity.subHead).toMatch(/^[0-9a-f]{40,64}$/);+ expect(identity.stagedIdentity).toEqual([]);+ expect(identity.dirtyContentFingerprint).toBeNull();+ expect(first.hashedContent).toBe(false);+ });++ it('changes the manifest when the inner checkout moves to another commit', async () => {+ const { parent, sub } = await setupParentWithSubmodule();+ parentPath = parent;+ const before = await readReviewSubmoduleIdentity(parentPath, ['vendor/lib']);++ await fs.writeFile(path.join(sub, 'inner.txt'), 'inner-v2\n');+ await runGit(['commit', '--no-gpg-sign', '-am', 'inner v2'], { cwd: sub });+ const after = await readReviewSubmoduleIdentity(parentPath, ['vendor/lib']);++ expect(after.identities[0].subHead).not.toBe(before.identities[0].subHead);+ // 父仓 gitlink 记录(index / HEAD tree)不动 —— 变化只发生在子仓内部。+ expect(after.identities[0].indexRecord).toBe(before.identities[0].indexRecord);+ });++ it('records an uninitialized submodule without touching inner state', async () => {+ const { parent } = await setupParentWithSubmodule();+ parentPath = parent;+ // 模拟未初始化:清掉子仓工作区,只留空目录(gitlink 仍在 index/HEAD)。+ await runGit(['submodule', 'deinit', '-f', 'vendor/lib'], { cwd: parent });++ const result = await readReviewSubmoduleIdentity(parentPath, ['vendor/lib']);+ expect(result.identities[0].subHead).toBe('uninitialized');+ expect(result.identities[0].indexRecord).toMatch(/^160000 0 [0-9a-f]{40,64}$/);+ expect(result.hashedContent).toBe(false);+ });++ // Windows 无 POSIX 权限位,chmod 000 制造不出读取失败。+ it.skipIf(process.platform === 'win32')(+ 'fails closed (not uninitialized) when the submodule worktree is unreadable',+ async () => {+ const { parent, sub } = await setupParentWithSubmodule();+ parentPath = parent;+ try {+ await fs.chmod(sub, 0o000);+ await expect(+ readReviewSubmoduleIdentity(parentPath, ['vendor/lib']),+ ).rejects.toThrow();+ } finally {+ await fs.chmod(sub, 0o755);+ }+ },+ );++ it('treats a fully removed submodule worktree as uninitialized', async () => {+ const { parent, sub } = await setupParentWithSubmodule();+ parentPath = parent;+ await runGit(['submodule', 'deinit', '-f', 'vendor/lib'], { cwd: parent });+ await fs.rm(sub, { recursive: true, force: true });++ const result = await readReviewSubmoduleIdentity(parentPath, ['vendor/lib']);+ expect(result.identities[0].subHead).toBe('uninitialized');+ });++ it('shares one content-hash budget across submodules instead of resetting per repo', async () => {+ // 两个子仓各有一个 6 字节 dirty 文件:预算 8 字节 —— 单个子仓够用,两个+ // 合计超限。共享预算必须在第二个子仓 fail closed;按子仓重置则两个都过。+ const upstream = path.join(workRoot, 'lib-upstream');+ await initRepo(upstream);+ await fs.writeFile(path.join(upstream, 'inner.txt'), 'seed\n');+ await runGit(['add', 'inner.txt'], { cwd: upstream });+ await runGit(['commit', '--no-gpg-sign', '-m', 'inner seed'], { cwd: upstream });++ const parent = path.join(workRoot, 'parent');+ await initRepo(parent);+ await fs.writeFile(path.join(parent, 'root.txt'), 'root\n');+ await runGit(['add', 'root.txt'], { cwd: parent });+ await runGit(['commit', '--no-gpg-sign', '-m', 'parent seed'], { cwd: parent });+ for (const name of ['vendor/a', 'vendor/b']) {+ await runGit(+ ['-c', 'protocol.file.allow=always', 'submodule', 'add', upstream, name],+ { cwd: parent },+ );+ await configureRepo(path.join(parent, ...name.split('/')));+ }+ await runGit(['commit', '--no-gpg-sign', '-m', 'add submodules'], { cwd: parent });+ parentPath = parent;+ await fs.writeFile(path.join(parent, 'vendor', 'a', 'inner.txt'), 'dirtyA\n');+ await fs.writeFile(path.join(parent, 'vendor', 'b', 'inner.txt'), 'dirtyB\n');++ await expect(+ readReviewSubmoduleIdentity(parentPath, ['vendor/a'], { maxContentBytes: 8 }),+ ).resolves.toBeTruthy();+ await expect(+ readReviewSubmoduleIdentity(parentPath, ['vendor/b'], { maxContentBytes: 8 }),+ ).resolves.toBeTruthy();+ await expect(+ readReviewSubmoduleIdentity(parentPath, ['vendor/a', 'vendor/b'], { maxContentBytes: 8 }),+ ).rejects.toThrow();+ });++ it('binds a gitlink-to-regular-file typechange to the file bytes instead of erroring', async () => {+ const { parent, sub } = await setupParentWithSubmodule();+ parentPath = parent;+ // 用户把整个 submodule 目录换成同名普通文件(porcelain 仍标 S,statusReader+ // 会把它当 submodule 送进来)。+ await fs.rm(sub, { recursive: true, force: true });+ await fs.writeFile(sub, 'file-vA\n');++ const withA = await readReviewSubmoduleIdentity(parentPath, ['vendor/lib']);+ expect(withA.identities[0].subHead).toBe('typechange');+ expect(withA.identities[0].dirtyContentFingerprint).not.toBeNull();+ expect(withA.hashedContent).toBe(true);++ // 同尺寸另一份字节必须被身份变化捕获。+ await fs.writeFile(sub, 'file-vB\n');+ const withB = await readReviewSubmoduleIdentity(parentPath, ['vendor/lib']);+ expect(withB.identities).not.toEqual(withA.identities);+ });++ it('queries inner paths in pathspec batches identically to a single call', async () => {+ const { parent, sub } = await setupParentWithSubmodule();+ parentPath = parent;+ for (const name of ['d1.txt', 'd2.txt', 'd3.txt']) {+ await fs.writeFile(path.join(sub, name), `${name}\n`);+ }+ await runGit(['add', '--', 'd1.txt', 'd2.txt'], { cwd: sub });++ const single = await readReviewSubmoduleIdentity(parentPath, ['vendor/lib']);+ const batched = await readReviewSubmoduleIdentity(parentPath, ['vendor/lib'], {+ batch: { maxBatchPaths: 1, maxBatchPathspecBytes: 8 },+ });+ expect(batched).toEqual(single);+ });++ it('counts staged identity records against the shared path budget', async () => {+ const { parent, sub } = await setupParentWithSubmodule();+ parentPath = parent;+ await fs.writeFile(path.join(sub, 's1.txt'), 'one\n');+ await fs.writeFile(path.join(sub, 's2.txt'), 'two\n');+ await runGit(['add', '--', 's1.txt', 's2.txt'], { cwd: sub });++ // 预算按「子仓条目 1 + staged 记录 2 = 3」消耗:2 不够,3 恰好。+ await expect(+ readReviewSubmoduleIdentity(parentPath, ['vendor/lib'], { maxContentPaths: 2 }),+ ).rejects.toThrow(/content-path budget/);+ await expect(+ readReviewSubmoduleIdentity(parentPath, ['vendor/lib'], { maxContentPaths: 3 }),+ ).resolves.toBeTruthy();+ });++ it('allows the shared byte budget to be exactly exhausted by earlier submodules', async () => {+ const upstream = path.join(workRoot, 'lib-upstream');+ await initRepo(upstream);+ await fs.writeFile(path.join(upstream, 'inner.txt'), 'seed\n');+ await runGit(['add', 'inner.txt'], { cwd: upstream });+ await runGit(['commit', '--no-gpg-sign', '-m', 'inner seed'], { cwd: upstream });++ const parent = path.join(workRoot, 'parent');+ await initRepo(parent);+ await fs.writeFile(path.join(parent, 'root.txt'), 'root\n');+ await runGit(['add', 'root.txt'], { cwd: parent });+ await runGit(['commit', '--no-gpg-sign', '-m', 'parent seed'], { cwd: parent });+ for (const name of ['vendor/a', 'vendor/b']) {+ await runGit(+ ['-c', 'protocol.file.allow=always', 'submodule', 'add', upstream, name],+ { cwd: parent },+ );+ await configureRepo(path.join(parent, ...name.split('/')));+ }+ await runGit(['commit', '--no-gpg-sign', '-m', 'add submodules'], { cwd: parent });+ parentPath = parent;+ // vendor/a 的 7 字节文件恰好吃满预算;vendor/b 只有零字节 dirty 文件,+ // 不需要再读任何字节 —— 不允许恰好用尽会在这里误报超限。+ await fs.writeFile(path.join(parent, 'vendor', 'a', 'inner.txt'), 'dirtyA\n');+ await fs.writeFile(path.join(parent, 'vendor', 'b', 'zero.txt'), '');++ await expect(+ readReviewSubmoduleIdentity(parentPath, ['vendor/a', 'vendor/b'], { maxContentBytes: 7 }),+ ).resolves.toBeTruthy();+ });++ it('records every index stage for an unmerged gitlink instead of keeping only the last', async () => {+ const { parent, sub } = await setupParentWithSubmodule();+ parentPath = parent;+ const { stdout: baseOut } = await runGit(['rev-parse', 'HEAD'], { cwd: sub });+ const base = baseOut.trim();++ // 子仓分叉出两个互不为祖先的 commit(祖先关系会被 gitlink 合并自动收敛,+ // 构造不出冲突),父仓两个分支各记一个 → merge 后 index 里 stage 1/2/3。+ await runGit(['checkout', '-b', 'left'], { cwd: parent });+ await fs.writeFile(path.join(sub, 'inner.txt'), 'sub-left\n');+ await runGit(['commit', '--no-gpg-sign', '-am', 'sub left'], { cwd: sub });+ await runGit(['add', 'vendor/lib'], { cwd: parent });+ await runGit(['commit', '--no-gpg-sign', '-m', 'parent left'], { cwd: parent });++ await runGit(['checkout', '-b', 'right', 'HEAD~1'], { cwd: parent });+ await runGit(['checkout', base], { cwd: sub });+ await fs.writeFile(path.join(sub, 'inner.txt'), 'sub-right\n');+ await runGit(['commit', '--no-gpg-sign', '-am', 'sub right'], { cwd: sub });+ await runGit(['add', 'vendor/lib'], { cwd: parent });+ await runGit(['commit', '--no-gpg-sign', '-m', 'parent right'], { cwd: parent });++ await runGit(['merge', 'left'], { cwd: parent, allowedExitCodes: [0, 1] });++ const result = await readReviewSubmoduleIdentity(parentPath, ['vendor/lib']);+ const rows = result.identities[0].indexRecord.split(',');+ expect(rows).toHaveLength(3);+ expect([...rows].sort()).toEqual(rows);+ expect(rows.map((row) => row.split(' ')[1]).sort()).toEqual(['1', '2', '3']);+ for (const row of rows) {+ expect(row).toMatch(/^160000 [123] [0-9a-f]{40,64}$/);+ }+ });++ it('records an initialized checkout with unborn HEAD as unborn', async () => {+ const { parent, sub } = await setupParentWithSubmodule();+ parentPath = parent;+ // orphan checkout:HEAD 指向尚不存在的 ref —— 已初始化空仓的合法形态。+ await runGit(['checkout', '--orphan', 'fresh'], { cwd: sub });++ const result = await readReviewSubmoduleIdentity(parentPath, ['vendor/lib']);+ expect(result.identities[0].subHead).toBe('unborn');+ });++ it('fails closed when the parent repository cannot be read', async () => {+ await expect(+ readReviewSubmoduleIdentity(path.join(workRoot, 'no-such-repo'), ['vendor/lib']),+ ).rejects.toThrow();+ });+});++/**+ * 自底向上构造 levels 层子仓链:chain-l{levels} 是最内层普通仓(含 leaf.txt),+ * 每一层把下一层作为 child 子仓;父仓把 chain-l1 挂在 vendor/lib,随后+ * `submodule update --init --recursive` 初始化全链。返回最内层 worktree 路径。+ * 注意:嵌套子仓只有**脏了**才会出现在上层 status 里、才会被递归绑定 ——+ * 用例都先改脏最内层再读 manifest。+ */+async function setupNestedChain(levels: number): Promise<{ parent: string; innermost: string }> {+ let upstream = path.join(workRoot, `chain-l${levels}`);+ await initRepo(upstream);+ await fs.writeFile(path.join(upstream, 'leaf.txt'), 'leaf-v1\n');+ await runGit(['add', 'leaf.txt'], { cwd: upstream });+ await runGit(['commit', '--no-gpg-sign', '-m', 'leaf seed'], { cwd: upstream });+ for (let i = levels - 1; i >= 1; i -= 1) {+ const repo = path.join(workRoot, `chain-l${i}`);+ await initRepo(repo);+ await fs.writeFile(path.join(repo, `file-l${i}.txt`), `l${i}\n`);+ await runGit(['add', '.'], { cwd: repo });+ await runGit(['commit', '--no-gpg-sign', '-m', `l${i} seed`], { cwd: repo });+ await runGit(['-c', 'protocol.file.allow=always', 'submodule', 'add', upstream, 'child'], {+ cwd: repo,+ });+ await runGit(['commit', '--no-gpg-sign', '-m', 'add child'], { cwd: repo });+ upstream = repo;+ }+ const parent = path.join(workRoot, 'parent-nested');+ await initRepo(parent);+ await fs.writeFile(path.join(parent, 'root.txt'), 'root\n');+ await runGit(['add', 'root.txt'], { cwd: parent });+ await runGit(['commit', '--no-gpg-sign', '-m', 'parent seed'], { cwd: parent });+ await runGit(['-c', 'protocol.file.allow=always', 'submodule', 'add', upstream, 'vendor/lib'], {+ cwd: parent,+ });+ await runGit(['commit', '--no-gpg-sign', '-m', 'add submodule'], { cwd: parent });+ await runGit(+ ['-c', 'protocol.file.allow=always', 'submodule', 'update', '--init', '--recursive'],+ { cwd: parent },+ );+ const innermost = path.join(parent, 'vendor', 'lib', ...Array(levels - 1).fill('child'));+ return { parent, innermost };+}++describe('readReviewSubmoduleIdentity 嵌套递归 (#2463 维护者 review)', () => {+ it('binds nested submodule content: an innermost edit changes the outer manifest', async () => {+ const { parent, innermost } = await setupNestedChain(2);+ parentPath = parent;+ const leaf = path.join(innermost, 'leaf.txt');++ await fs.writeFile(leaf, 'leaf-vA\n');+ const withEditA = await readReviewSubmoduleIdentity(parentPath, ['vendor/lib']);+ await fs.writeFile(leaf, 'leaf-vB\n');+ const withEditB = await readReviewSubmoduleIdentity(parentPath, ['vendor/lib']);++ // 递归确实展开了内层:外层身份携带 nested 子身份,且内层内容参与指纹。+ expect(withEditA.identities).toHaveLength(1);+ expect(withEditA.identities[0].nested).toHaveLength(1);+ expect(withEditA.identities[0].nested[0].path).toBe('child');+ expect(withEditA.identities[0].nested[0].dirtyContentFingerprint).not.toBeNull();+ expect(withEditA.hashedContent).toBe(true);+ // 内层同尺寸字节替换必须改变外层 manifest —— #2463 攻击形态的嵌套版。+ expect(withEditB.identities).not.toEqual(withEditA.identities);+ });++ it('fails closed when the dirty chain nests deeper than the recursion cap', async () => {+ // 6 层脏链:vendor/lib 为深度 1,最内层为深度 6 > MAX(5) —— 必须整体拒绝,+ // 不允许静默截断(截断会让更深处的内容变化映射到同一 manifest)。+ const { parent, innermost } = await setupNestedChain(6);+ parentPath = parent;+ await fs.writeFile(path.join(innermost, 'leaf.txt'), 'leaf-dirty\n');++ await expect(readReviewSubmoduleIdentity(parentPath, ['vendor/lib'])).rejects.toThrow(+ /nested deeper than 5/,+ );+ });+});++describe('readReviewSubmoduleIdentity 路径边界 (#2463 review)', () => {+ // Windows 文件系统不允许目录名以空格结尾,该形态仅在 POSIX 侧存在。+ it.skipIf(process.platform === 'win32')(+ 'binds a submodule whose directory name ends with a space (no path trim)',+ async () => {+ const upstream = path.join(workRoot, 'lib-upstream-sp');+ await initRepo(upstream);+ await fs.writeFile(path.join(upstream, 'inner.txt'), 'inner-v1\n');+ await runGit(['add', 'inner.txt'], { cwd: upstream });+ await runGit(['commit', '--no-gpg-sign', '-m', 'inner seed'], { cwd: upstream });++ const parent = path.join(workRoot, 'parent-space');+ await initRepo(parent);+ await fs.writeFile(path.join(parent, 'root.txt'), 'root\n');+ await runGit(['add', 'root.txt'], { cwd: parent });+ await runGit(['commit', '--no-gpg-sign', '-m', 'parent seed'], { cwd: parent });+ // 目录名以空格结尾:macOS/Linux 文件系统与 git 都合法。rev-parse+ // --show-toplevel 输出被 trim 会裁掉路径本身的尾随空格,realpath 查错+ // 路径 → 整次 Review 失败。+ await runGit(+ ['-c', 'protocol.file.allow=always', 'submodule', 'add', upstream, 'vendor/lib '],+ { cwd: parent },+ );+ await runGit(['commit', '--no-gpg-sign', '-m', 'add submodule'], { cwd: parent });+ const sub = path.join(parent, 'vendor', 'lib ');+ await configureRepo(sub);+ await fs.writeFile(path.join(sub, 'inner.txt'), 'inner-dirty\n');++ const result = await readReviewSubmoduleIdentity(parent, ['vendor/lib ']);+ expect(result.identities).toHaveLength(1);+ expect(result.identities[0].subHead).not.toBe('uninitialized');+ expect(result.identities[0].dirtyContentFingerprint).not.toBeNull();+ },+ );+});++describe('readReviewSubmoduleIdentity 路径边界:尾随回车 (#2463 review)', () => {+ // Windows 文件名不可能含 \r,该形态仅在 POSIX 侧存在。git 的 submodule+ // porcelain 会规范掉路径尾随 \r,所以用「直接 clone + update-index 手工+ // 注册 gitlink」构造:身份读取只依赖 index 里的 gitlink 记录与目录自身的+ // git toplevel 归属,不依赖 .gitmodules。+ it.skipIf(process.platform === 'win32')(+ 'binds a submodule whose directory name ends with a carriage return',+ async () => {+ const upstream = path.join(workRoot, 'lib-upstream-cr');+ await initRepo(upstream);+ await fs.writeFile(path.join(upstream, 'inner.txt'), 'inner-v1\n');+ await runGit(['add', 'inner.txt'], { cwd: upstream });+ await runGit(['commit', '--no-gpg-sign', '-m', 'inner seed'], { cwd: upstream });+ const { stdout: headOut } = await runGit(['rev-parse', 'HEAD'], { cwd: upstream });+ const innerHead = headOut.trim();++ const parent = path.join(workRoot, 'parent-cr');+ await initRepo(parent);+ await fs.writeFile(path.join(parent, 'root.txt'), 'root\n');+ await runGit(['add', 'root.txt'], { cwd: parent });+ await runGit(['commit', '--no-gpg-sign', '-m', 'parent seed'], { cwd: parent });+ const subName = 'vendor/lib\r';+ const sub = path.join(parent, 'vendor', 'lib\r');+ await runGit(['clone', upstream, sub], { cwd: parent });+ await configureRepo(sub);+ await runGit(['update-index', '--add', '--cacheinfo', `160000,${innerHead},${subName}`], {+ cwd: parent,+ });+ await fs.writeFile(path.join(sub, 'inner.txt'), 'inner-dirty\n');++ const result = await readReviewSubmoduleIdentity(parent, [subName]);+ expect(result.identities).toHaveLength(1);+ expect(result.identities[0].subHead).not.toBe('uninitialized');+ expect(result.identities[0].dirtyContentFingerprint).not.toBeNull();+ },+ );+});++describe('readReviewSubmoduleIdentity 无身份目录 (#2463 review)', () => {+ it('fails closed when the gitlink path is a non-empty plain directory without git identity', async () => {+ // .git 被移除、路径被普通目录 + 任意文件替换:porcelain 仍是同一条 S 记录,+ // 目录字节没有任何身份来源 —— 归入固定 'uninitialized' 会让不同内容映射到+ // 同一 manifest,必须整体拒绝。+ const { parent, sub } = await setupParentWithSubmodule();+ parentPath = parent;+ await fs.rm(sub, { recursive: true, force: true });+ await fs.mkdir(sub, { recursive: true });+ await fs.writeFile(path.join(sub, 'arbitrary.txt'), 'not-a-repo\n');++ await expect(readReviewSubmoduleIdentity(parentPath, ['vendor/lib'])).rejects.toThrow(+ /no git identity but is not empty/,+ );+ });++ it('still records an empty deinit-style directory as uninitialized', async () => {+ const { parent, sub } = await setupParentWithSubmodule();+ parentPath = parent;+ await fs.rm(sub, { recursive: true, force: true });+ await fs.mkdir(sub, { recursive: true });++ const result = await readReviewSubmoduleIdentity(parentPath, ['vendor/lib']);+ expect(result.identities[0].subHead).toBe('uninitialized');+ });+});++describe('readReviewSubmoduleIdentity ignore 配置 (#2463 review)', () => {+ it('binds nested dirty content even when submodule.ignore=all is configured', async () => {+ // 子仓配置 submodule.<name>.ignore=all 会让 status 省略脏的嵌套子仓 ——+ // 身份绑定必须显式 --ignore-submodules=none 无视该配置,否则内层内容+ // 替换不进 nested manifest,旧结论照样通过新鲜度门。+ const { parent, innermost } = await setupNestedChain(2);+ parentPath = parent;+ const outerSub = path.join(parent, 'vendor', 'lib');+ await runGit(['config', 'submodule.child.ignore', 'all'], { cwd: outerSub });+ const leaf = path.join(innermost, 'leaf.txt');++ await fs.writeFile(leaf, 'leaf-vA\n');+ const withEditA = await readReviewSubmoduleIdentity(parentPath, ['vendor/lib']);+ await fs.writeFile(leaf, 'leaf-vB\n');+ const withEditB = await readReviewSubmoduleIdentity(parentPath, ['vendor/lib']);++ expect(withEditA.identities[0].nested).toHaveLength(1);+ expect(withEditB.identities).not.toEqual(withEditA.identities);+ });+});++describe('readReviewSubmoduleIdentity index 已删的嵌套 gitlink (#2463 review)', () => {+ it('binds a nested checkout whose gitlink was removed from the index (git rm --cached)', async () => {+ // 外层子仓 git rm --cached child 保留内层 checkout:status 为 D child ++ // ?? child/。gitlink 判定须并入 HEAD tree,否则保留目录被当普通 worktree+ // 路径喂给文件指纹器抛错、Review 无法启动。+ const { parent, innermost } = await setupNestedChain(2);+ parentPath = parent;+ const outerSub = path.join(parent, 'vendor', 'lib');+ await runGit(['rm', '--cached', 'child'], { cwd: outerSub });+ await fs.writeFile(path.join(innermost, 'leaf.txt'), 'leaf-dirty\n');++ const result = await readReviewSubmoduleIdentity(parentPath, ['vendor/lib']);+ expect(result.identities).toHaveLength(1);+ const nested = result.identities[0].nested;+ expect(nested).toHaveLength(1);+ expect(nested[0].path).toBe('child');+ // index 里已无 gitlink:indexRecord 记 absent,但 HEAD 记录与内层身份仍绑定。+ expect(nested[0].indexRecord).toBe('absent');+ expect(nested[0].subHead).not.toBe('uninitialized');+ });+});++describe('readReviewSubmoduleIdentity intent-to-add 状态绑定 (#2463 review)', () => {+ it('distinguishes an intent-to-add file from the same bytes after git reset', async () => {+ // 子仓内 `git add -N new.txt` 与其 `git reset` 后:文件字节相同、内容指纹+ // 相同、staged 身份两态都为空(ita 条目 porcelain 记 ` A`,不进 staged+ // 桶),只有原始状态码(` A` vs `??`)能区分。manifest 不绑状态码时两态+ // 完全同一,旧结论可穿过新鲜度门。+ const { parent, innermost } = await setupNestedChain(1);+ parentPath = parent;+ const newFile = path.join(innermost, 'new.txt');+ await fs.writeFile(newFile, 'same-bytes\n');++ await runGit(['add', '-N', 'new.txt'], { cwd: innermost });+ const withIntentToAdd = await readReviewSubmoduleIdentity(parentPath, ['vendor/lib']);+ await runGit(['reset', '--', 'new.txt'], { cwd: innermost });+ const afterReset = await readReviewSubmoduleIdentity(parentPath, ['vendor/lib']);++ // 字节未动:内容指纹一致,差异必须由状态记录承担。+ expect(afterReset.identities[0].dirtyContentFingerprint).toBe(+ withIntentToAdd.identities[0].dirtyContentFingerprint,+ );+ expect(afterReset.identities).not.toEqual(withIntentToAdd.identities);+ expect(withIntentToAdd.identities[0].statusRecords).toContain(' A new.txt');+ expect(afterReset.identities[0].statusRecords).toContain('?? new.txt');+ });+});++describe('子仓 symlink 按链接文本绑定 (#2463 review)', () => {+ it.skipIf(process.platform === 'win32')(+ 'binds a dirty submodule symlink pointing outside the sub without aborting',+ async () => {+ // 子仓里指向子仓外(../ 解析进父仓)或悬空的 symlink 是常见合法改动:+ // 按目标解析会让整个快照 fail closed 中止 review;链接文本才是 Git 记录+ // 的内容,文本变化必须改变身份。+ const { parent, innermost } = await setupNestedChain(1);+ parentPath = parent;+ const link = path.join(innermost, 'escape-link');+ await fs.symlink('../outside-a', link);++ const withTargetA = await readReviewSubmoduleIdentity(parentPath, ['vendor/lib']);+ await fs.unlink(link);+ await fs.symlink('../outside-b', link);+ const withTargetB = await readReviewSubmoduleIdentity(parentPath, ['vendor/lib']);++ expect(withTargetA.identities).toHaveLength(1);+ expect(withTargetB.identities).not.toEqual(withTargetA.identities);+ },+ );++ it.skipIf(process.platform === 'win32')(+ 'binds a gitlink replaced by an outside-pointing symlink (typechange) without aborting',+ async () => {+ // gitlink 整个被 symlink 替换(typechange):sub 字段仍标 S 路由到子仓+ // 分支;链接悬空 / 指向仓库外同样是合法 Git 状态,须按链接文本绑定。+ const { parent } = await setupNestedChain(1);+ parentPath = parent;+ const subDir = path.join(parent, 'vendor', 'lib');+ await fs.rm(subDir, { recursive: true, force: true });+ await fs.symlink('../outside-a', subDir);++ const withTargetA = await readReviewSubmoduleIdentity(parentPath, ['vendor/lib']);+ await fs.unlink(subDir);+ await fs.symlink('../outside-b', subDir);+ const withTargetB = await readReviewSubmoduleIdentity(parentPath, ['vendor/lib']);++ expect(withTargetA.identities[0].subHead).toBe('typechange');+ expect(withTargetB.identities).not.toEqual(withTargetA.identities);+ },+ );++ it.skipIf(process.platform === 'win32')(+ 'fails closed when a symlinked ancestor resolves the sub outside the parent repo',+ async () => {+ // 祖先目录 vendor 被换成指向父仓外的 symlink:lstat/realpath 跟随中间+ // 链接,仓外 checkout 的 toplevel 等于其自身,仅比对「toplevel === 自身」+ // 拦不住 —— 解析结果必须仍在父仓边界内,否则拒绝读取仓外 status 与字节。+ const { parent } = await setupNestedChain(1);+ parentPath = parent;+ const escapeRoot = path.join(workRoot, 'escape-root');+ const escapeCheckout = path.join(escapeRoot, 'lib');+ await initRepo(escapeCheckout);+ await fs.writeFile(path.join(escapeCheckout, 'evil.txt'), 'outside\n');+ await runGit(['add', 'evil.txt'], { cwd: escapeCheckout });+ await runGit(['commit', '--no-gpg-sign', '-m', 'outside seed'], { cwd: escapeCheckout });++ await fs.rm(path.join(parent, 'vendor'), { recursive: true, force: true });+ await fs.symlink(escapeRoot, path.join(parent, 'vendor'));++ await expect(+ readReviewSubmoduleIdentity(parentPath, ['vendor/lib']),+ ).rejects.toBeInstanceOf(ReviewSubmoduleIdentityError);+ },+ );+});++describe('顶层 readStatus 的 --ignore-submodules=none (#2463 维护者 review)', () => {+ it('keeps an ignore=all submodule with untracked-only content visible in top-level status', async () => {+ // 父仓配置 submodule.<name>.ignore=all 时,不带 --ignore-submodules=none+ // 的 git status 会整个省略脏子仓;submoduleEvidencePaths() 的 status 兜底+ // 依赖顶层 readStatus() 显式覆盖该配置——这里用真实仓库锁住这个行为+ // (untracked-only 内部内容同时也是无 numstat 条目的形态)。+ const { parent } = await setupNestedChain(1);+ parentPath = parent;+ await runGit(['config', 'submodule.vendor/lib.ignore', 'all'], { cwd: parent });+ await fs.writeFile(path.join(parent, 'vendor', 'lib', 'untracked.txt'), 'u\n');++ const scope: ReviewScope = {+ sessionId: 's-status',+ workdir: parent,+ worktreePath: parent,+ workingDir: parent,+ repoRoot: parent,+ branch: null,+ headOid: null,+ isDetached: false,+ isUnborn: false,+ source: 'worktree',+ aheadBehind: { ahead: 0, behind: 0, upstream: null, stale: true },+ disabledReason: null,+ disabledMessage: null,+ resolutionChain: [],+ };+ const status = await readStatus(scope);++ const entry = status.files.find((file) => file.path === 'vendor/lib');+ expect(entry).toBeTruthy();+ expect(entry?.isSubmodule).toBe(true);+ expect(entry?.worktreeStatus).toBe('modified');+ });+});diff --git a/apps/desktop/src/main/reviewer/reviewCappedWorkspaceFingerprint.ts b/apps/desktop/src/main/reviewer/reviewCappedWorkspaceFingerprint.tsindex 43d7e490e1..c2d1d1ebdd 100644--- a/apps/desktop/src/main/reviewer/reviewCappedWorkspaceFingerprint.ts+++ b/apps/desktop/src/main/reviewer/reviewCappedWorkspaceFingerprint.ts@@ -14,6 +14,20 @@ const NOFOLLOW_FLAG = typeof constants.O_NOFOLLOW === 'number' ? constants.O_NOFexport interface ReviewCappedWorkspaceFingerprintOptions {/** Test seam; production remains bounded and fails closed above the limit. */maxTotalBytes?: number;+ /**+ * 跨多次调用共享的字节预算(如 submodule manifest 的整次构建):以当前+ * remainingBytes 为本次上限,结束后按实际哈希字节**原地扣减**。与+ * maxTotalBytes 互斥,同时给时以本字段为准。预算耗尽按超限 fail closed。+ */+ byteBudget?: { remainingBytes: number };+ /**+ * symlink 条目的绑定语义。默认 'resolve':解析目标并哈希目标字节,悬空或+ * 解析出仓库边界一律 fail closed(父仓 capped 路径的既有安全姿态)。+ * 'link-text':只绑定 Git 真正记录的链接文本(readlink),完全不解析、不打开+ * 目标 —— dirty 子仓里指向子仓外(如 ../shared)或悬空的合法链接不再中止+ * 快照,也杜绝经由链接读取边界外字节(Codex review #2515)。+ */+ symlinkMode?: 'resolve' | 'link-text';}export class ReviewCappedWorkspaceFingerprintError extends Error {}@@ -36,12 +50,20 @@ function stableStatMatches(before: Stats, after: Stats): boolean {}function assertSafeGitPath(rawPath: string): void {+ // git 输出的 repo-relative 路径分隔符恒为 '/'。反斜杠在 POSIX 上是普通文件名+ // 字符('C:\\notes' / 'dir\\..\\file' 都是合法 dirty 文件),按 win32 语义做+ // 词法校验会把它们误判成越界、中止整个 Review(Codex review #2515)。win32+ // 词法检查仅在 Windows 生效(那里文件名不可能含反斜杠);词法校验之外的+ // 越界防护由下游 realpath 边界检查兜底。+ const winUnsafe =+ process.platform === 'win32' &&+ (path.win32.isAbsolute(rawPath) || rawPath.split(/[\\/]/).includes('..'));if (!rawPath ||rawPath.includes('\0') ||path.posix.isAbsolute(rawPath) ||- path.win32.isAbsolute(rawPath) ||- rawPath.split(/[\\/]/).includes('..')+ winUnsafe ||+ rawPath.split('/').includes('..')) {throw new ReviewCappedWorkspaceFingerprintError('Review refused an invalid capped workspace path',@@ -153,8 +175,17 @@ export async function fingerprintReviewCappedWorkspaceFiles(rawPaths: readonly string[],options: ReviewCappedWorkspaceFingerprintOptions = {},): Promise<string> {- const maxTotalBytes = options.maxTotalBytes ?? MAX_CAPPED_WORKSPACE_BYTES;- if (!Number.isSafeInteger(maxTotalBytes) || maxTotalBytes <= 0) {+ const budget = options.byteBudget;+ const maxTotalBytes = budget ? budget.remainingBytes : (options.maxTotalBytes ?? MAX_CAPPED_WORKSPACE_BYTES);+ if (budget) {+ // 共享预算允许恰好用尽(剩余 0):零字节文件 / 缺失路径不需要读取任何+ // 字节,是否真正超限交给逐文件的 size > remaining 判断。负值 = 账目损坏。+ if (!Number.isSafeInteger(maxTotalBytes) || maxTotalBytes < 0) {+ throw new ReviewCappedWorkspaceFingerprintLimitError(+ 'Capped Review shared content-byte budget is corrupt',+ );+ }+ } else if (!Number.isSafeInteger(maxTotalBytes) || maxTotalBytes <= 0) {throw new TypeError('maxTotalBytes must be a positive safe integer');}const repoRootReal = await fs.realpath(repoRoot);@@ -187,6 +218,25 @@ export async function fingerprintReviewCappedWorkspaceFiles('Review can only content-fingerprint regular capped workspace files',);}+ if (entryBefore.isSymbolicLink() && options.symlinkMode === 'link-text') {+ // 绑定链接文本本身(即 symlink 的 Git 内容),零目标读取。文本读取前后+ // 各取一次,期间变化按既有稳定性语义抛 ChangedError。+ // Buffer 读取:readlink 默认按 UTF-8 解码,非 UTF-8 目标字节会坍缩成+ // 替换字符,不同原始字节映射同一记录 —— 文本必须按原始字节绑定与比较+ // (Codex review)。+ const targetBefore = await fs.readlink(candidate, { encoding: 'buffer' });+ const entryAfter = await lstatOrNull(candidate);+ const targetAfter = entryAfter?.isSymbolicLink()+ ? await fs.readlink(candidate, { encoding: 'buffer' }).catch(() => null)+ : null;+ if (!entryAfter || !targetAfter || !targetAfter.equals(targetBefore)) {+ throw new ReviewCappedWorkspaceChangedError(+ 'A capped Review file changed while its content baseline was being prepared',+ );+ }+ addRecord(hash, 'symlink-text', rawPath, targetBefore.toString('base64'), entryBefore.mode);+ continue;+ }totalBytes += await hashRegularFile({hash,repoRootReal,@@ -196,5 +246,6 @@ export async function fingerprintReviewCappedWorkspaceFiles(remainingBytes: maxTotalBytes - totalBytes,});}+ if (budget) budget.remainingBytes -= totalBytes;return hash.digest('hex');}diff --git a/apps/desktop/src/main/reviewer/reviewEvidence.ts b/apps/desktop/src/main/reviewer/reviewEvidence.tsindex c2b5fcca41..57454c4a56 100644--- a/apps/desktop/src/main/reviewer/reviewEvidence.ts+++ b/apps/desktop/src/main/reviewer/reviewEvidence.ts@@ -43,6 +43,7 @@ import {ReviewCappedWorkspaceChangedError,} from './reviewCappedWorkspaceFingerprint.js';import { readStagedIndexIdentity } from '../git-review/indexIdentityReader.js';+import { readReviewSubmoduleIdentity } from './reviewSubmoduleIdentity.js';export interface ReviewAttachmentInput {name: string;@@ -196,12 +197,14 @@ interface ReviewWorkspaceSnapshotDeps {readReviewData: typeof readReviewData;fingerprintCappedWorkspaceFiles: typeof fingerprintReviewCappedWorkspaceFiles;readStagedIndexIdentity: typeof readStagedIndexIdentity;+ readSubmoduleIdentity: typeof readReviewSubmoduleIdentity;}const defaultReviewWorkspaceSnapshotDeps: ReviewWorkspaceSnapshotDeps = {readReviewData,fingerprintCappedWorkspaceFiles: fingerprintReviewCappedWorkspaceFiles,readStagedIndexIdentity,+ readSubmoduleIdentity: readReviewSubmoduleIdentity,};/**@@ -217,34 +220,28 @@ function workspacePathsWithoutContent(workspace: ReviewWorkspaceEvidence): strinconst capped = [workspace.diffs.capped?.staged, workspace.diffs.capped?.unstaged].flatMap((bucket) =>bucket- ? bucket.files.flatMap((file) => [file.path, file.oldPath].filter(Boolean) as string[])+ ? bucket.files+ // capped bucket 同样排除 submodule(理由同下方非 capped 分支):+ // gitlink 是目录,喂给普通文件指纹器会直接抛错,含 capped 子仓的+ // 大型 dirty workspace 整个 Review 起不来;其身份由+ // submoduleEvidencePaths()(已含 capped bucket)路由到 submodule+ // reader 绑定(Codex review #2515)。+ .filter((file) => !file.isSubmodule)+ .flatMap((file) => [file.path, file.oldPath].filter(Boolean) as string[]): [],);const contentless = [...workspace.diffs.staged, ...workspace.diffs.unstaged]// Submodules are excluded on purpose: a gitlink is a directory, and the// content fingerprinter only accepts regular files, so passing one would// abort evidence loading outright — an initialized submodule anywhere in- // the workspace would make Review refuse to run at all.+ // the workspace would make Review refuse to run at all. Do not "fix" the+ // binding gap by feeding the directory back in, which is that crash.//- // The accepted cost, stated plainly: edits living *inside* a dirty- // submodule are not bound. Porcelain v2 spends one boolean on "the- // submodule has modified content" and FileStatus keeps neither that flag- // nor any object id, so replacing one internal edit with another leaves- // every value this digest sees unchanged. Closing it needs an identity- // read this layer does not have — the gitlink oid plus a recursive digest- // of the inner worktree — which is a submodule-aware reader, not another- // path added to the file fingerprinter. That reader is out of scope here- // and tracked in #2463; do not "fix" this by feeding the directory back- // in, which is the crash described above.- //- // What bounds the exposure meanwhile: inner content is never part of the- // evidence (diffReader classifies every submodule entry as `submodule`- // with an empty patch, so no inner bytes reach the prompt), and a file- // inside a submodule that is explicitly attached lands in reviewReadPaths- // and is fully content-hashed by fingerprintReviewArtifacts. The unbound- // case is the reviewer opening an inner file that is neither — the same- // class as opening any unchanged tracked file, which no fingerprint here- // covers either.+ // Their identity is bound elsewhere: submoduleEvidencePaths() routes every+ // submodule evidence entry to the submodule-aware reader (#2463), which+ // binds the gitlink oids, the inner HEAD, the inner staged index identity+ // and a bounded content hash of inner dirty regular files — the identity+ // read this file-path digest cannot express..filter((diff) => !diff.rawPatch && !diff.isSubmodule).flatMap((diff) => [diff.path, diff.oldPath].filter(Boolean) as string[]);return [...new Set([...capped, ...contentless])];@@ -274,20 +271,45 @@ function stagedEvidencePaths(workspace: ReviewWorkspaceEvidence): string[] {return [...new Set([...staged, ...capped])];}+/**+ * Sanitized evidence paths that are submodules and need an identity manifest+ * (#2463). The file fingerprinter cannot bind them (a gitlink is a directory)+ * and porcelain keeps only a dirty boolean, so a submodule-aware reader binds+ * the gitlink oids, the inner HEAD and the inner dirty file identities.+ */+function submoduleEvidencePaths(+ workspace: ReviewWorkspaceEvidence,+ sanitizedStatusFiles: readonly { path: string; isSubmodule: boolean }[],+): string[] {+ const capped = [workspace.diffs.capped?.staged, workspace.diffs.capped?.unstaged].flatMap(+ (bucket) => (bucket ? bucket.files.filter((file) => file.isSubmodule).map((file) => file.path) : []),+ );+ const diffs = [...workspace.diffs.staged, ...workspace.diffs.unstaged]+ .filter((diff) => diff.isSubmodule)+ .map((diff) => diff.path);+ // Diffs alone can miss a dirty submodule: one whose only change is untracked+ // inner content has no numstat entry, so with ignoreWhitespace enabled the+ // summary builder drops it as a whitespace-only modification — and when the+ // unstaged bucket is capped there is no detailed diff to catch it either.+ // Status still lists it, so bind from the sanitized status records as well+ // (Codex review #2515).+ const status = sanitizedStatusFiles+ .filter((file) => file.isSubmodule)+ .map((file) => file.path);+ return [...new Set([...diffs, ...capped, ...status])];+}+async function buildReviewWorkspaceSnapshot(reviewData: Awaited<ReturnType<typeof readReviewData>>,deps: Pick<ReviewWorkspaceSnapshotDeps,- 'fingerprintCappedWorkspaceFiles' | 'readStagedIndexIdentity'+ 'fingerprintCappedWorkspaceFiles' | 'readStagedIndexIdentity' | 'readSubmoduleIdentity'>,): Promise<ReviewWorkspaceSnapshot> {const workspace = mapReviewWorkspace(reviewData);const contentlessPaths = workspacePathsWithoutContent(workspace);- // Whichever files needed their own content hash also need the stability- // re-read below: both are answering "did these bytes hold still?".- const hasCappedDiff = contentlessPaths.length > 0;const cappedContentFingerprint =- hasCappedDiff && reviewData.scope.repoRoot+ contentlessPaths.length > 0 && reviewData.scope.repoRoot? await deps.fingerprintCappedWorkspaceFiles(reviewData.scope.repoRoot, contentlessPaths): null;const stagedPaths = stagedEvidencePaths(workspace);@@ -297,6 +319,29 @@ async function buildReviewWorkspaceSnapshot(stagedPaths.length > 0 && reviewData.scope.repoRoot? await deps.readStagedIndexIdentity(reviewData.scope.repoRoot, stagedPaths): null;+ const submodulePaths = submoduleEvidencePaths(+ workspace,+ sanitizeReviewStatusFiles(reviewData.status?.files ?? []),+ );+ // SSH 远程工作区:submodule 身份读取含本机 fs 探测(lstat/realpath/readdir)。+ // repoRoot 在远端时,本机 ENOENT 会被误判成 'uninitialized' 放行过期结论;+ // 本机碰巧存在同路径目录时,还会把本机字节和远端 git 状态绑在一起。git 命令+ // 经 GitExecutionBackend 走远程,fs 探测不走——在读到任何本机状态之前显式+ // fail closed(拒绝发布而非放行),与其它 Git 证据读取失败同一收口。完整远程+ // 支持需经 remote-file-service 通道,见 PR 描述的远程适配结论。+ if (submodulePaths.length > 0 && reviewData.scope.source === 'remote') {+ throw new Error(+ 'Review submodule identity is not supported over SSH remote workspaces; refusing to bind local filesystem state (fail closed).',+ );+ }+ const submoduleIdentity =+ submodulePaths.length > 0 && reviewData.scope.repoRoot+ ? await deps.readSubmoduleIdentity(reviewData.scope.repoRoot, submodulePaths)+ : null;+ // Whichever files needed their own content hash also need the stability+ // re-read below: both are answering "did these bytes hold still?". Inner+ // submodule file hashes (#2463) join the same window.+ const hasCappedDiff = contentlessPaths.length > 0 || submoduleIdentity?.hashedContent === true;return {workspace,// A clean tree is not proof that the reviewer saw the same code: changing@@ -321,6 +366,7 @@ async function buildReviewWorkspaceSnapshot(workspace,cappedContentFingerprint,stagedIndexIdentity,+ submoduleIdentity: submoduleIdentity?.identities ?? null,}),).digest('hex')diff --git a/apps/desktop/src/main/reviewer/reviewSubmoduleIdentity.ts b/apps/desktop/src/main/reviewer/reviewSubmoduleIdentity.tsnew file mode 100644index 0000000000..6f2d8f11ee--- /dev/null+++ b/apps/desktop/src/main/reviewer/reviewSubmoduleIdentity.ts@@ -0,0 +1,474 @@+/**+ * Review 新鲜度的 submodule 感知身份读取(#2463)。+ *+ * gitlink 是目录,文件指纹器只接受普通文件,所以 submodule 被刻意排除在+ * `workspacePathsWithoutContent` 之外(见 reviewEvidence.ts 的注释)——代价+ * 是「dirty submodule 内部的一份改动换成另一份」时,porcelain 的 `S` 布尔位、+ * 空 patch 元数据与父仓工作树指纹全部不变,两道 freshness gate 都会放行。+ *+ * 这里为每个纳入 Review 的 submodule 读取一份**身份 manifest**:+ *+ * - 父仓侧:index 里的 gitlink 记录(mode 160000 + oid)与 HEAD tree 里的+ * gitlink oid —— 绑定「父仓认为子仓应当在哪个 commit」;+ * - 已初始化子仓:当前 checkout 的 HEAD oid —— 绑定「子仓实际在哪」;+ * - dirty 子仓:进入子仓读取 —— staged 侧绑定 index 的 (path, mode, stage,+ * oid)(复用 #2460 的 indexIdentityReader),modified/untracked 工作树侧对+ * **具体普通文件**做有界内容哈希(复用 capped 指纹器的边界、敏感路径过滤+ * 与稳定性重读);+ * - 嵌套 submodule 以相同规则递归,深度封顶,超限 fail closed;+ * - manifest 无法完整读取(git 失败、条目形态超出表达能力)时抛错 fail+ * closed,与其他 Git 证据读取失败同语义。+ *+ * 只保存 `git submodule status` 一类的 commit oid + dirty 布尔是不够的:子仓+ * HEAD 不变、dirty 文件内容从 A 换成 B 时两者完全相同 —— 必须绑定 dirty+ * tracked/untracked 文件的实际身份,这正是本文件与 #2460 机制共用的原因。+ */++import path from 'node:path';+import { promises as fsPromises } from 'node:fs';++import { runGit } from '../git-review/gitRunner.js';+import { isPathInside } from '../git-review/fsPathGuard.js';+import {+ readStagedIndexIdentity,+ splitIntoBatches,+ type IndexIdentityBatchLimits,+} from '../git-review/indexIdentityReader.js';+import { fingerprintReviewCappedWorkspaceFiles } from './reviewCappedWorkspaceFingerprint.js';++/** 嵌套 submodule 的递归深度封顶;超过按无法完整表达处理(fail closed)。 */+const MAX_SUBMODULE_RECURSION_DEPTH = 5;+/** 单个子仓 dirty 条目上限;超过按无法完整表达处理(fail closed)。 */+const MAX_SUBMODULE_DIRTY_ENTRIES = 10_000;+/**+ * 整次 manifest 构建(全部子仓 + 嵌套递归)**共享**的内容哈希预算。上限与+ * capped 指纹器单次调用相同,但这里跨子仓累计扣减 —— 否则 N 个大型 dirty+ * 子仓各自重置 512MB 额度,快照总读取量没有上限。耗尽 fail closed。+ */+const MAX_MANIFEST_CONTENT_BYTES = 512 * 1024 * 1024;+const MAX_MANIFEST_CONTENT_PATHS = 10_000;++interface ManifestContentBudget {+ remainingBytes: number;+ remainingPaths: number;+}++/**+ * 所有 manifest 条目(子仓自身、staged 身份记录、dirty 工作树文件)共同消耗+ * 全局路径预算 —— 只对工作树文件扣减时,N 个子仓仍可各自产生上限条 staged+ * 记录或继续横向展开子仓,总量不受控。耗尽 fail closed。+ */+function consumePathBudget(budget: ManifestContentBudget, count: number): void {+ budget.remainingPaths -= count;+ if (budget.remainingPaths < 0) {+ throw new ReviewSubmoduleIdentityError(+ `Review submodule manifest exceeds the shared content-path budget of ${MAX_MANIFEST_CONTENT_PATHS}`,+ );+ }+}++export class ReviewSubmoduleIdentityError extends Error {}++/** 单个 submodule 的身份 manifest(JSON 可序列化,字段序即声明序,确定性)。 */+export interface ReviewSubmoduleIdentity {+ path: string;+ /**+ * 父仓 index 里的 gitlink 记录(`<mode> <stage> <oid>`);unmerged 时+ * stage 1/2/3 全部并入并稳定排序、逗号连接,缺席记 'absent'。+ */+ indexRecord: string;+ /** 父仓 HEAD tree 里的 gitlink oid,缺席(如新增未提交)记 'absent'。 */+ headRecord: string;+ /** 子仓状态:未初始化 / HEAD oid;unborn HEAD 记 'unborn'。 */+ subHead: string;+ /** 子仓 dirty staged 侧的 index 身份记录(#2460 同格式);clean 为空数组。 */+ stagedIdentity: string[];+ /**+ * 子仓 porcelain status 原始记录(`XY path`,稳定排序)。intent-to-add+ * (` A`)与 reset 后的 untracked(`??`)字节相同、内容指纹相同,staged 侧+ * 也都为空 —— 只有状态码能区分这两种(以及其它同字节的)内层形态,不绑+ * 会让不同状态映射到同一 manifest(Codex review #2515)。+ */+ statusRecords: string[];+ /** 子仓 dirty 工作树普通文件的有界内容指纹;无 dirty 工作树文件为 null。 */+ dirtyContentFingerprint: string | null;+ /** dirty 的嵌套 submodule,按相同规则递归。 */+ nested: ReviewSubmoduleIdentity[];+}++export interface ReviewSubmoduleIdentityResult {+ identities: ReviewSubmoduleIdentity[];+ /** 是否发生过内层文件内容哈希 —— 调用方据此启用快照稳定性重读窗口。 */+ hashedContent: boolean;+}++function literalPathspec(gitPath: string): string {+ return `:(top,literal)${gitPath}`;+}++/** realpath(符号链接归一)——toplevel 归属比较必须在同一坐标系里做。 */+async function fsRealpath(p: string): Promise<string> {+ return fsPromises.realpath(p);+}++/** 父仓 index / HEAD tree 里该路径的 gitlink 记录。 */+async function readParentRecords(+ repoRoot: string,+ subPath: string,+): Promise<{ indexRecord: string; headRecord: string }> {+ const { stdout: stageOut } = await runGit(+ ['ls-files', '--stage', '-z', '--', literalPathspec(subPath)],+ { cwd: repoRoot, maxStdoutBytes: 1024 * 1024 },+ );+ // unmerged gitlink 在 index 里是 stage 1/2/3 三条记录,全部并入身份并稳定+ // 排序 —— 只留最后一条会让「替换较早 stage 的 OID」逃过新鲜度检查(与+ // readStagedIndexIdentity 的多 stage 表达同一裁决)。+ const indexRows: string[] = [];+ for (const record of stageOut.split('\0')) {+ if (!record) continue;+ const tab = record.indexOf('\t');+ if (tab < 0 || record.slice(tab + 1) !== subPath) continue;+ const [mode, oid, stage] = record.slice(0, tab).trim().split(/\s+/);+ if (mode && oid && stage) indexRows.push(`${mode} ${stage} ${oid}`);+ }+ const indexRecord = indexRows.length > 0 ? indexRows.sort().join(',') : 'absent';++ const { stdout: treeOut } = await runGit(+ // 字面 pathspec:子仓名以 pathspec magic 开头(如合法目录名 ':(exclude)')+ // 时,裸路径会以 128 失败中止 Review(Codex review #2515;同函数的+ // ls-files 调用已是 literal)。+ ['ls-tree', '-z', 'HEAD', '--', literalPathspec(subPath)],+ { cwd: repoRoot, maxStdoutBytes: 1024 * 1024, allowedExitCodes: [0, 128] },+ );+ // exit 128 = unborn HEAD 等;当作 tree 无记录处理(absent 本身就是身份)。+ let headRecord = 'absent';+ for (const record of treeOut.split('\0')) {+ if (!record) continue;+ const tab = record.indexOf('\t');+ if (tab < 0 || record.slice(tab + 1) !== subPath) continue;+ const [mode, type, oid] = record.slice(0, tab).trim().split(/\s+/);+ if (mode && type && oid) headRecord = `${mode} ${type} ${oid}`;+ }+ return { indexRecord, headRecord };+}++/** 子仓 porcelain v1 条目(--no-renames,单路径记录)。 */+interface SubStatusEntry {+ staged: boolean;+ worktree: boolean;+ untracked: boolean;+ /** porcelain v1 原始 XY 两字符状态码。 */+ xy: string;+ path: string;+}++async function readSubStatus(subRoot: string): Promise<SubStatusEntry[]> {+ const { stdout } = await runGit(+ // --ignore-submodules=none 显式覆盖仓库配置:.gitmodules / 本地配置里的+ // submodule.<name>.ignore=all/dirty 会让 status 省略脏的嵌套子仓,内层+ // 内容替换不进 nested manifest,旧结论照样通过新鲜度门(Codex review+ // #2515,已实仓验证 ignore=all 会移除 dirty child)。+ ['status', '--porcelain', '-z', '--untracked-files=all', '--no-renames', '--ignore-submodules=none'],+ { cwd: subRoot, maxStdoutBytes: 16 * 1024 * 1024 },+ );+ const entries: SubStatusEntry[] = [];+ for (const record of stdout.split('\0')) {+ if (record.length < 4) continue;+ const x = record[0];+ const y = record[1];+ const entryPath = record.slice(3);+ if (!entryPath) continue;+ if (x === '?' && y === '?') {+ entries.push({ staged: false, worktree: true, untracked: true, xy: '??', path: entryPath });+ continue;+ }+ entries.push({+ staged: x !== ' ' && x !== '?',+ worktree: y !== ' ',+ untracked: false,+ xy: `${x}${y}`,+ path: entryPath,+ });+ }+ if (entries.length > MAX_SUBMODULE_DIRTY_ENTRIES) {+ throw new ReviewSubmoduleIdentityError(+ `Review cannot bind a submodule with more than ${MAX_SUBMODULE_DIRTY_ENTRIES} dirty entries`,+ );+ }+ return entries.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));+}++/**+ * 子仓 index 里 mode 160000 的路径集合(区分嵌套 submodule 与普通文件)。+ * pathspec 与 indexIdentityReader 同规则分批(Windows ~32K 命令行上限),+ * 批间合并集合,语义与单次调用一致。+ */+async function readGitlinkPaths(+ subRoot: string,+ candidates: readonly string[],+ batch?: IndexIdentityBatchLimits,+): Promise<Set<string>> {+ if (candidates.length === 0) return new Set();+ const gitlinks = new Set<string>();+ for (const group of splitIntoBatches(candidates, batch)) {+ const { stdout } = await runGit(+ ['ls-files', '--stage', '-z', '--', ...group.map(literalPathspec)],+ { cwd: subRoot, maxStdoutBytes: Math.max(1024 * 1024, group.length * 512) },+ );+ for (const record of stdout.split('\0')) {+ if (!record) continue;+ const tab = record.indexOf('\t');+ if (tab < 0) continue;+ const mode = record.slice(0, tab).trim().split(/\s+/)[0];+ if (mode === '160000') gitlinks.add(record.slice(tab + 1));+ }+ // HEAD tree 也要查(Codex review #2515):git rm --cached 从 index 删除+ // gitlink 但保留 checkout 时,status 是 D + ?? 目录 —— 只查 index 会把+ // 保留目录当普通 worktree 路径喂给文件指纹器直接抛错。HEAD 里是 gitlink+ // 的路径同样按嵌套子仓处理(indexRecord 记 absent,身份仍完整绑定)。+ // unborn HEAD 等按 exit 128 视作无记录。+ const { stdout: treeOut } = await runGit(+ ['ls-tree', '-z', 'HEAD', '--', ...group.map(literalPathspec)],+ {+ cwd: subRoot,+ maxStdoutBytes: Math.max(1024 * 1024, group.length * 512),+ allowedExitCodes: [0, 128],+ },+ );+ for (const record of treeOut.split('\0')) {+ if (!record) continue;+ const tab = record.indexOf('\t');+ if (tab < 0) continue;+ const mode = record.slice(0, tab).trim().split(/\s+/)[0];+ if (mode === '160000') gitlinks.add(record.slice(tab + 1));+ }+ }+ return gitlinks;+}++/** 未跟踪目录条目(如内嵌仓库)带尾斜杠;与 gitlink 路径比较前归一。 */+function stripTrailingSlash(p: string): string {+ return p.endsWith('/') ? p.slice(0, -1) : p;+}++async function readOneSubmoduleIdentity(+ repoRoot: string,+ subPath: string,+ depth: number,+ budget: ManifestContentBudget,+ batch?: IndexIdentityBatchLimits,+): Promise<{ identity: ReviewSubmoduleIdentity; hashedContent: boolean }> {+ if (depth > MAX_SUBMODULE_RECURSION_DEPTH) {+ throw new ReviewSubmoduleIdentityError(+ `Review cannot bind submodules nested deeper than ${MAX_SUBMODULE_RECURSION_DEPTH} levels`,+ );+ }+ // 子仓条目自身也计入全局路径预算:横向展开的子仓数量同样必须受控。+ consumePathBudget(budget, 1);+ const { indexRecord, headRecord } = await readParentRecords(repoRoot, subPath);+ const subRoot = path.join(repoRoot, ...subPath.split('/'));++ // 已初始化判定:目录里能解析出 git toplevel **且 toplevel 就是子仓目录+ // 本身**。只测 rev-parse 成功是不够的 —— deinit 后留下的空目录仍在父仓+ // 工作树里,rev-parse 会静默落到父仓,把父仓 HEAD 错当子仓身份。+ const uninitialized = {+ identity: {+ path: subPath,+ indexRecord,+ headRecord,+ subHead: 'uninitialized',+ stagedIdentity: [],+ statusRecords: [],+ dirtyContentFingerprint: null,+ nested: [],+ },+ hashedContent: false,+ };+ let subHead: string;+ // 「未初始化」只有两种合法形态:工作树目录整个缺席(gitlink 在、目录被清),+ // 或 deinit 后留下的空目录(rev-parse 静默落到父仓 → toplevel 归属不是子仓+ // 自身)。除这两种外的任何读取失败(权限、git 异常、realpath 失败)都必须+ // 向上抛 fail closed —— 把读取错误降级成稳定的 'uninitialized' 身份,会让+ // 不同的内层内容映射到同一 manifest,新鲜度门形同虚设。+ let subEntry;+ try {+ subEntry = await fsPromises.lstat(subRoot);+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') return uninitialized;+ throw new ReviewSubmoduleIdentityError(+ `Review cannot stat submodule worktree ${subPath}: ${err instanceof Error ? err.message : String(err)}`,+ );+ }+ if (!subEntry.isDirectory()) {+ // gitlink 被普通文件 / 符号链接替换(typechange):porcelain 的 sub 字段仍+ // 标 S,statusReader 把它当 submodule 路由到这里;把 rev-parse 的 cwd 指到+ // 普通文件只会 ENOTDIR。普通文件的新鲜度真身是那份文件字节 —— 交给+ // capped 指纹器绑定内容(同一套路径守卫、敏感过滤与共享预算);symlink+ // 替换与内层 dirty symlink 同语义按链接文本绑定 —— gitlink 换成悬空或+ // 指向仓库外的链接是 Git 可表达的合法 typechange,按目标解析会中止整个+ // 快照(Codex review)。+ consumePathBudget(budget, 1);+ const typechangeFingerprint = await fingerprintReviewCappedWorkspaceFiles(+ repoRoot,+ [subPath],+ { byteBudget: budget, symlinkMode: 'link-text' },+ );+ return {+ identity: {+ path: subPath,+ indexRecord,+ headRecord,+ subHead: 'typechange',+ stagedIdentity: [],+ statusRecords: [],+ dirtyContentFingerprint: typechangeFingerprint,+ nested: [],+ },+ hashedContent: true,+ };+ }+ const { stdout: toplevelOut } = await runGit(['rev-parse', '--show-toplevel'], {+ cwd: subRoot,+ maxStdoutBytes: 4096,+ });+ const [toplevelReal, subRootReal] = await Promise.all([+ // 只剥 git 追加的行终止符,不 trim:目录名允许以空格/制表符结尾(macOS+ // 文件系统与 git 均合法),trim 会把路径本身裁掉导致 realpath 查错路径+ // (Codex review #2515)。\r 按平台区分:Windows 文件名不可能含 \r,行尾+ // \r\n 整体是终止符;POSIX 上 git 只追加 \n,\n 前的 \r 是目录名自身的+ // 字节,必须保留(Codex review 第二轮)。+ fsRealpath(toplevelOut.replace(process.platform === 'win32' ? /\r?\n$/ : /\n$/, '')),+ fsRealpath(subRoot),+ ]);+ // 边界校验:祖先目录被替换成指向父仓外的 symlink 时,lstat/realpath 会+ // 跟随中间链接把 subRoot 解析到仓外 —— 那里的 checkout 有自己的 toplevel,+ // 仅比对「toplevel === 自身」拦不住。解析结果必须仍在父仓 realpath 边界+ // 内,否则 fail closed,不读取仓外 status 与字节(Codex review)。+ const repoRootReal = await fsRealpath(repoRoot);+ if (!isPathInside(repoRootReal, subRootReal)) {+ throw new ReviewSubmoduleIdentityError(+ `Review cannot bind submodule ${subPath}: worktree resolves outside its parent repository`,+ );+ }+ if (toplevelReal !== subRootReal) {+ // toplevel 归属不是子仓自身 = 没有独立 git 身份。只有**空目录**是合法的+ // deinit 形态可以稳定归入 'uninitialized';非空普通目录(.git 被移除、+ // 内容被任意文件替换)必须 fail closed —— 目录里的字节没有任何身份来源,+ // 归入固定的 'uninitialized' 会让不同内容映射到同一 manifest,旧结论+ // 照样通过新鲜度门(Codex review #2515)。+ const entries = await fsPromises.readdir(subRoot);+ if (entries.length === 0) return uninitialized;+ throw new ReviewSubmoduleIdentityError(+ `Review cannot bind submodule ${subPath}: worktree directory has no git identity but is not empty`,+ );+ }+ // --verify --quiet 让「HEAD 不是合法 ref(已初始化的空仓)」确定性地表现为+ // exit 1 + 空输出;超时、进程启动失败等其余错误仍由 runGit 抛出 fail+ // closed —— 无条件 catch 会把读取失败伪装成稳定的 'unborn' 身份。+ {+ const { stdout } = await runGit(['rev-parse', '--verify', '--quiet', 'HEAD'], {+ cwd: subRoot,+ maxStdoutBytes: 1024,+ allowedExitCodes: [0, 1],+ });+ subHead = stdout.trim() || 'unborn';+ }++ const entries = await readSubStatus(subRoot);+ // untracked 条目也参与 gitlink 判定(尾斜杠归一):index 已删但 checkout+ // 保留的嵌套仓在 status 里正是 ?? 目录形态。+ const gitlinkPaths = await readGitlinkPaths(+ subRoot,+ [...new Set(entries.map((entry) => stripTrailingSlash(entry.path)))],+ batch,+ );++ const stagedPaths = entries+ .filter((entry) => entry.staged && !gitlinkPaths.has(stripTrailingSlash(entry.path)))+ .map((entry) => entry.path);+ const worktreePaths = entries+ .filter((entry) => entry.worktree && !gitlinkPaths.has(stripTrailingSlash(entry.path)))+ .map((entry) => entry.path);+ const nestedPaths = [...new Set(+ entries+ .filter((entry) => gitlinkPaths.has(stripTrailingSlash(entry.path)))+ .map((entry) => stripTrailingSlash(entry.path)),+ )];++ // staged 身份记录同样消耗全局路径预算(每条 staged 路径一条记录)。+ consumePathBudget(budget, stagedPaths.length);+ const stagedIdentity = await readStagedIndexIdentity(subRoot, stagedPaths, batch);+ // 工作树 dirty 普通文件走 capped 指纹器:同一套路径守卫、敏感路径过滤、+ // 字节上限与「哈希期间文件变了就抛 ChangedError」的稳定性语义。目录形态+ // (如 untracked 的内嵌仓库)会被它拒绝 —— 即 fail closed,不静默跳过。+ let dirtyContentFingerprint: string | null = null;+ let hashedContent = false;+ if (worktreePaths.length > 0) {+ // 字节与路径预算都从整次构建的共享额度里扣,不按子仓重置。+ consumePathBudget(budget, worktreePaths.length);+ dirtyContentFingerprint = await fingerprintReviewCappedWorkspaceFiles(subRoot, worktreePaths, {+ byteBudget: budget,+ // symlink 绑定链接文本(Git 对 symlink 记录的内容就是文本):子仓里指向+ // 子仓外(如 ../shared 解析进父仓)或悬空的链接是合法 Git 改动,按目标+ // 解析会把整个快照 fail closed 中止;链接文本变化照样改变 manifest,+ // 且完全不读取目标字节(Codex review)。+ symlinkMode: 'link-text',+ });+ hashedContent = true;+ }++ const nested: ReviewSubmoduleIdentity[] = [];+ for (const nestedPath of nestedPaths) {+ const child = await readOneSubmoduleIdentity(subRoot, nestedPath, depth + 1, budget, batch);+ nested.push(child.identity);+ hashedContent = hashedContent || child.hashedContent;+ }++ return {+ identity: {+ path: subPath,+ indexRecord,+ headRecord,+ subHead,+ stagedIdentity,+ // 原始状态码逐条并入 manifest:同字节的状态迁移(如 intent-to-add+ // `git reset` 后变 untracked)不改变 stagedIdentity 与内容指纹,只有+ // 这里能把它们区分开。+ statusRecords: entries.map((entry) => `${entry.xy} ${entry.path}`).sort(),+ dirtyContentFingerprint,+ nested,+ },+ hashedContent,+ };+}++/**+ * 读取一组 submodule 路径的身份 manifest,按路径稳定排序返回。+ *+ * 任何一步 git 读取失败都向上抛(fail closed);调用方把返回的 manifest 并入+ * workspace fingerprint,`hashedContent` 为真时启用快照稳定性重读窗口。+ */+export async function readReviewSubmoduleIdentity(+ repoRoot: string,+ rawPaths: readonly string[],+ limits?: { maxContentBytes?: number; maxContentPaths?: number; batch?: IndexIdentityBatchLimits },+): Promise<ReviewSubmoduleIdentityResult> {+ // 不做字符过滤:pathspec 经 argv 传递、输出全部走 -z(NUL 分隔、无引号+ // 转义),含 \n / \r 的合法 submodule 路径同样必须绑定身份 —— 静默丢弃+ // 就是绕过口(与 indexIdentityReader 同一裁决)。+ const paths = [...new Set(rawPaths)]+ .filter((p) => p.length > 0)+ .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));+ const budget: ManifestContentBudget = {+ remainingBytes: limits?.maxContentBytes ?? MAX_MANIFEST_CONTENT_BYTES,+ remainingPaths: limits?.maxContentPaths ?? MAX_MANIFEST_CONTENT_PATHS,+ };+ const identities: ReviewSubmoduleIdentity[] = [];+ let hashedContent = false;+ for (const subPath of paths) {+ const one = await readOneSubmoduleIdentity(repoRoot, subPath, 1, budget, limits?.batch);+ identities.push(one.identity);+ hashedContent = hashedContent || one.hashedContent;+ }+ return { identities, hashedContent };+}