Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(memory): worktree 会话共享主仓 memory store — scope key git 归一化 (#2379) (#2399)
KingSystemHaiGobc6e22fdd3db
diff --git a/packages/lizi-mcps/src/memory/_shared.ts b/packages/lizi-mcps/src/memory/_shared.tsindex 76baf1c063..73c18e4ce5 100644--- a/packages/lizi-mcps/src/memory/_shared.ts+++ b/packages/lizi-mcps/src/memory/_shared.ts@@ -13,7 +13,11 @@* thread 的真实 workingDir。*/-import { buildMemoryScopeKey, type MakerMemoryStore } from '@cindy/maker-core';+import {+ resolveMemoryScopeKey,+ type MakerMemoryManager,+ type MakerMemoryStore,+} from '@cindy/maker-core';import type { MemoryToolResult } from '../cindy_memoryToolRegistry.js';import type { MemoryMcpDeps } from '../types.js';@@ -30,14 +34,23 @@ export function buildJsonResult(payload: unknown, isError = false): MemoryToolRe* 拿当前 session 绑定 workdir 的 Store. manager 不可用 (没注入 / disabled) 时* 返 MAKER_MEMORY_NOT_READY 错误, 调用方按 plan 决定是否提示用户开 mode。*/+export type WithStoreContext = {+ store: MakerMemoryStore;+ /** 解析后的 session scope key (linked worktree 已归一到主仓)。 */+ scopeKey: string;+ manager: MakerMemoryManager;+};+export async function withStore(deps: MemoryMcpDeps,- fn: (store: MakerMemoryStore) => Promise<unknown>,+ fn: (store: MakerMemoryStore, ctx: WithStoreContext) => Promise<unknown>,): Promise<MemoryToolResult> {let store: MakerMemoryStore;+ let manager: MakerMemoryManager;+ let scopeKey: string;let scopeAtEntry: string | null = null;try {- const manager = deps.getManager();+ manager = deps.getManager();if (!manager.isEnabled()) {return buildJsonResult({ ok: false, code: 'MAKER_MEMORY_NOT_READY', message: 'maker memory disabled (mode != "maker")' },@@ -51,16 +64,33 @@ export async function withStore(const ctx = deps.getSessionContext?.();const workdir = ctx?.workingDir ?? deps.workdir;// SSH remote 会话 (ctx 带 remoteHostId) 的 workdir 是远端路径 — 经 scope- // key 定位, 与 agent 启动注入 (claude-code/codex index.ts) 同一键规则。- store = await manager.getStore(- ctx?.memoryScopeKey ?? buildMemoryScopeKey(workdir, ctx?.remoteHostId),- );+ // key 定位, 与 agent 启动注入 (claude-code/codex index.ts) 同一键规则;+ // 本地会话在此额外做 git worktree 归一化 (#2379)。已注入的 memoryScopeKey+ // (含 bot: / ssh:) 原样透传, 不再二次解析。+ scopeKey =+ ctx?.memoryScopeKey ?? (await resolveMemoryScopeKey(workdir, ctx?.remoteHostId));+ // git 探测是 await: 期间 logout / 切账号会换 owner, 甚至换掉 getManager()+ // 绑定的 manager。必须在 getStore 前按入口 scope 复核, 否则会把解析到的+ // key 开到新 owner 的池里 (Codex #2399 P1, 对齐 manager.getStore 的+ // scopeAtEntry + assertScopeUnchanged)。+ manager = deps.getManager();+ if (scopeAtEntry !== null && manager.currentOwnerScopeKey?.() !== scopeAtEntry) {+ return buildJsonResult(+ {+ ok: false,+ code: 'MAKER_MEMORY_NOT_READY',+ message: 'owner scope changed during async memory operation; aborting (retry against current scope)',+ },+ true,+ );+ }+ store = await manager.getStore(scopeKey);} catch (err) {const { code, message } = classifyMemoryError(err);return buildJsonResult({ ok: false, code, message }, true);}try {- const data = await fn(store);+ const data = await fn(store, { store, scopeKey, manager });// 操作后复核: owner 在 fn 执行期间切换 → 结果不可信, 不得按成功返回。if (scopeAtEntry !== null && deps.getManager().currentOwnerScopeKey?.() !== scopeAtEntry) {return buildJsonResult(diff --git a/packages/lizi-mcps/src/memory/review.ts b/packages/lizi-mcps/src/memory/review.tsindex 1f67985d24..03b0cfa96d 100644--- a/packages/lizi-mcps/src/memory/review.ts+++ b/packages/lizi-mcps/src/memory/review.ts@@ -10,10 +10,8 @@*/import { withStore } from './_shared.js';-import { buildJsonResult } from './_shared.js';import type { MemoryMcpDeps } from '../types.js';import type { MemoryToolRegistry } from '../cindy_memoryToolRegistry.js';-import { classifyMemoryError } from './errors.js';export function registerMemoryReviewTool(registry: MemoryToolRegistry, deps: MemoryMcpDeps): void {registry.register({@@ -24,22 +22,10 @@ export function registerMemoryReviewTool(registry: MemoryToolRegistry, deps: Mem' 不自动执行 — 调用方 LLM 拿到建议后自行决定调 memory_delete / memory_consolidate。' +' 用 host 端 haiku 跑, 几秒钟返回。',inputShape: {},- handler: async () => {- // review 不走 withStore (它需要 manager 而非 store), 自己 try/catch- try {- const manager = deps.getManager();- if (!manager.isEnabled()) {- return buildJsonResult(- { ok: false, code: 'MAKER_MEMORY_NOT_READY', message: 'maker memory disabled' },- true,- );- }- const r = await manager.runReview(deps.workdir);- return buildJsonResult({ ok: true, data: r });- } catch (err) {- const { code, message } = classifyMemoryError(err);- return buildJsonResult({ ok: false, code, message }, true);- }- },+ handler: async () =>+ // 必须走 withStore: list/search/write 已按解析后的 scope 开 store。+ // 原先直接 runReview(deps.workdir) 会在 linked worktree 上读旧分片+ // (Codex #2399 P1)。runReview 的入参是 scope key, 与 getStore 同一把钥匙。+ withStore(deps, (_store, { manager, scopeKey }) => manager.runReview(scopeKey)),});}diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.tsindex fd290fc39d..2b1f19e935 100644--- a/packages/maker-core/src/agents/claude-code/index.ts+++ b/packages/maker-core/src/agents/claude-code/index.ts@@ -74,7 +74,7 @@ import {CONTACTS_RULES_ENABLED,} from '../../contacts/system-prompt.js';import { MemoryFlushController } from '../../memory/flush-controller.js';-import { buildMemoryScopeKey } from '../../memory/storage.js';+import { resolveMemoryScopeKey } from '../../memory/scope-resolver.js';import type {Capabilities,EffortDescriptor,@@ -1492,10 +1492,13 @@ export class ClaudeCodeAgent extends BaseAgent {: opts.makerMemoryEnabled ?? this.deps.runtimeConfig.makerMemoryEnabled ?? false;const makerMemory = this.deps.makerMemory;const makerMemoryEnabled = makerMemoryFlag === true && !!makerMemory;- // SSH remote 的 workingDir 是远端路径 — store 定位统一经 scope key,- // 键规则与理由见 buildMemoryScopeKey (memory/storage.ts)。- const memoryScopeKey =- opts.makerMemoryScopeKey ?? buildMemoryScopeKey(opts.workingDir, opts.remoteHostId);+ // SSH remote 的 workingDir 是远端路径 — store 定位统一经 scope key;+ // 本地会话额外做 git worktree 归一化 (#2379)。已注入的 makerMemoryScopeKey+ // (含 bot:) 原样透传。Maker Memory 关闭时跳过 git 探测 (Codex #2399 P1):+ // 解析结果本就不会被用, 失败还能空耗 3s timeout。+ const memoryScopeKey = makerMemoryEnabled+ ? (opts.makerMemoryScopeKey ?? (await resolveMemoryScopeKey(opts.workingDir, opts.remoteHostId)))+ : (opts.makerMemoryScopeKey ?? opts.workingDir);// This per-session injection flag must not mutate the shared manager.if (makerMemoryEnabled && makerMemory) {try {@@ -1612,7 +1615,7 @@ export class ClaudeCodeAgent extends BaseAgent {const context: McpProviderContext = {agentKind: 'claude-code' as const,workingDir: opts.workingDir,- ...(opts.makerMemoryScopeKey ? { memoryScopeKey: opts.makerMemoryScopeKey } : {}),+ ...((makerMemoryEnabled || opts.makerMemoryScopeKey) ? { memoryScopeKey } : {}),vendorOptions: vo,// business sessionId 由 maker.createSession 通过 opts.sessionId 注入// (见 maker.ts: agent.startSession({...opts, sessionId: id}))。MCP server@@ -3290,7 +3293,7 @@ export class ClaudeCodeAgent extends BaseAgent {makerMemoryEnabled,// 同一个 scope key 也必须随注册的 session ctx 走: prompt 段用它读索引// (上方 memoryScopeKey), 远端工具侧不给就会回落到 workdir 键。- ...(opts.makerMemoryScopeKey ? { makerMemoryScopeKey: opts.makerMemoryScopeKey } : {}),+ ...((makerMemoryEnabled || opts.makerMemoryScopeKey) ? { makerMemoryScopeKey: memoryScopeKey } : {}),onApprovalRequest: async (rawParams: unknown) => {// 110s timeout — must respond before daemon's 120s server-request timeout.// On timeout, dismiss the pending interaction (clears UI) and reject todiff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex b417e9cb56..b80a60f132 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -203,7 +203,7 @@ import {CONTACTS_RULES_ENABLED,} from '../../contacts/system-prompt.js';import { MemoryFlushController } from '../../memory/flush-controller.js';-import { buildMemoryScopeKey } from '../../memory/storage.js';+import { resolveMemoryScopeKey } from '../../memory/scope-resolver.js';import { CODEX_AGENT_COMMANDS } from './commands.js';import {canReuseCodexHostForCredentialMode,@@ -3211,10 +3211,13 @@ export class CodexAgent extends BaseAgent {: opts.makerMemoryEnabled ?? this.deps.runtimeConfig.makerMemoryEnabled ?? false;const makerMemory = this.deps.makerMemory;const makerMemoryEnabled = makerMemoryFlag === true && !!makerMemory;- // SSH remote 的 workingDir 是远端路径 — store 定位统一经 scope key,- // 键规则与理由见 buildMemoryScopeKey (memory/storage.ts)。- const memoryScopeKey =- opts.makerMemoryScopeKey ?? buildMemoryScopeKey(opts.workingDir, opts.remoteHostId);+ // SSH remote 的 workingDir 是远端路径 — store 定位统一经 scope key;+ // 本地会话额外做 git worktree 归一化 (#2379)。已注入的 makerMemoryScopeKey+ // (含 bot:) 原样透传。Maker Memory 关闭时跳过 git 探测 (Codex #2399 P1):+ // 解析结果本就不会被用, 失败还能空耗 3s timeout。+ const memoryScopeKey = makerMemoryEnabled+ ? (opts.makerMemoryScopeKey ?? (await resolveMemoryScopeKey(opts.workingDir, opts.remoteHostId)))+ : (opts.makerMemoryScopeKey ?? opts.workingDir);// This per-session injection flag must not mutate the shared manager.if (makerMemoryEnabled && makerMemory) {try {@@ -5084,7 +5087,7 @@ export class CodexAgent extends BaseAgent {mcpCallerAttested: true,...(opts.sessionInstanceId ? { sessionInstanceId: opts.sessionInstanceId } : {}),workingDir: opts.workingDir,- ...(opts.makerMemoryScopeKey ? { memoryScopeKey: opts.makerMemoryScopeKey } : {}),+ ...((makerMemoryEnabled || opts.makerMemoryScopeKey) ? { memoryScopeKey } : {}),// remote thread ctx: scope key 语义见 buildMemoryScopeKey。...(opts.remoteHostId ? { remoteHostId: opts.remoteHostId } : {}),vendorOptions: vo,diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.tsindex 1ded4f4bda..be21be7f4d 100644--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@ -138,7 +138,7 @@ import {} from '../shared/auto-review-decision.js';import { applyPiDisabledSkillSettings, filterPiDisabledProjectSkills, piDisabledDiscoveryPaths } from './skill-activation.js';import type { ReviewableAction } from '../shared/auto-review.js';-import { buildMemoryScopeKey } from '../../memory/storage.js';+import { resolveMemoryScopeKey } from '../../memory/scope-resolver.js';import { MAKER_MEMORY_RULES } from '../../memory/system-prompt.js';import type {Capabilities,@@ -2129,6 +2129,16 @@ export class PiAgent extends BaseAgent {const sessionMemoryEnabled = !reviewMode&& (opts.makerMemoryEnabled ?? this.deps.runtimeConfig.makerMemoryEnabled ?? false) === true&& (botMemoryScope || (this.memoryOverride ?? true));+ const compactionMemoryEnabled = sessionMemoryEnabled && !!this.deps.makerMemory;+ const makerMemoryPromptEnabled =+ sessionMemoryEnabled &&+ (opts.makerMemoryIndexSnapshot !== undefined || !!this.deps.makerMemory);+ // Maker Memory 关闭时跳过 git 探测 (Codex #2399 P1): 解析结果不会被用。+ // 解析必须发生在 MCP ctx 注册之前, 并把结果冻进 ctx, 避免工具侧 60s TTL+ // 后再解析漂移到 raw worktree 路径 (Codex #2399 P2)。+ const memoryScopeKey = (compactionMemoryEnabled || makerMemoryPromptEnabled)+ ? (opts.makerMemoryScopeKey ?? (await resolveMemoryScopeKey(opts.workingDir, opts.remoteHostId)))+ : (opts.makerMemoryScopeKey ?? opts.workingDir);const remote = Boolean(opts.remoteHostId);const sessionPiAutoCompactPct = this.deps.runtimeConfig.piAutoCompactThresholdPct;@@ -3057,9 +3067,9 @@ export class PiAgent extends BaseAgent {sessionId: opts.sessionId,...(opts.sessionInstanceId ? { sessionInstanceId: opts.sessionInstanceId } : {}),workingDir: opts.workingDir,- // Bot 会话的 scope key 必须随 ctx 走 — prompt 注入用的是同一个 key- // (见上方 memoryScopeKey), 丢掉会让 cindy_memory 工具写进 workdir 记忆。- ...(opts.makerMemoryScopeKey ? { memoryScopeKey: opts.makerMemoryScopeKey } : {}),+ // 冻进启动时解析的 scope key (含 bot: / 归一化后的主仓路径), 工具侧+ // 不得再二次 resolve (Codex #2399 P2)。+ ...((sessionMemoryEnabled || opts.makerMemoryScopeKey) ? { memoryScopeKey } : {}),memoryEnabled: sessionMemoryEnabled,...(opts.botRuntimeProfile?.mcpPolicy? { botMcpPolicy: opts.botRuntimeProfile.mcpPolicy }@@ -3090,14 +3100,7 @@ export class PiAgent extends BaseAgent {// 压缩即记忆:makerMemory 开启时,把 pi 压缩上下文时丢弃内容的摘要沉淀成 `digest`// 记忆(进 FTS 可 memory_search 检索,但排除出 MEMORY.md / system prompt,不污染// curated 记忆)。gate 与 CC 同口径;best-effort,失败只 warn,绝不阻断会话。- const compactionMemoryEnabled =- sessionMemoryEnabled &&- !!this.deps.makerMemory;- const makerMemoryPromptEnabled =- sessionMemoryEnabled &&- (opts.makerMemoryIndexSnapshot !== undefined || !!this.deps.makerMemory);- const memoryScopeKey =- opts.makerMemoryScopeKey ?? buildMemoryScopeKey(opts.workingDir, opts.remoteHostId);+ // memoryScopeKey / compactionMemoryEnabled 已在 MCP 注册前解析并冻进 ctx。let makerMemoryIndex = '';if (makerMemoryPromptEnabled) {try {diff --git a/packages/maker-core/src/index.ts b/packages/maker-core/src/index.tsindex c9d73dac5c..367bae7737 100644--- a/packages/maker-core/src/index.ts+++ b/packages/maker-core/src/index.ts@@ -69,8 +69,15 @@ export {buildFilename,parseFilename,validateSlug,+ SSH_SCOPE_KEY_PREFIX,type MemoryStorageMeta,} from './memory/storage.js';+export {+ resolveMemoryScopeKey,+ __clearMemoryScopeKeyCacheForTests,+ type GitProbe,+ type ResolveMemoryScopeKeyDeps,+} from './memory/scope-resolver.js';export { MemoryFts } from './memory/fts.js';export {MakerMemoryStore,diff --git a/packages/maker-core/src/memory/scope-resolver.git-integration.test.ts b/packages/maker-core/src/memory/scope-resolver.git-integration.test.tsnew file mode 100644index 0000000000..e0f372a378--- /dev/null+++ b/packages/maker-core/src/memory/scope-resolver.git-integration.test.ts@@ -0,0 +1,266 @@+/**+ * resolveMemoryScopeKey — worktree 归一化 (#2379) 的真实 Git 组合矩阵。+ *+ * 属于 git-integration tier (`pnpm test:git-integration`), 不在默认 unit+ * tier 运行 (engineering-conventions §3.1: 每个用例都要建临时仓库 / linked+ * worktree / separate-git-dir clone, 反复 spawn git 子进程)。默认层的+ * fake probe 覆盖与唯一 smoke 见 scope-resolver.test.ts。+ */++import { execFileSync } from 'node:child_process';+import { promises as fs } from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';++import { beforeEach, describe, expect, it } from 'vitest';++import {+ __clearMemoryScopeKeyCacheForTests,+ resolveMemoryScopeKey,+} from './scope-resolver.js';++function gitAvailable(): boolean {+ try {+ execFileSync('git', ['--version'], { stdio: 'ignore' });+ return true;+ } catch {+ return false;+ }+}++beforeEach(() => {+ __clearMemoryScopeKeyCacheForTests();+});++describe.skipIf(!gitAvailable())('resolveMemoryScopeKey — 真实临时 git 仓库矩阵', () => {+ async function makeFixture() {+ const tmpRoot = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'scope-resolver-')));+ const repoRoot = path.join(tmpRoot, 'repo');+ const wt1 = path.join(tmpRoot, 'wt1');+ const wt2 = path.join(tmpRoot, 'wt2');+ const git = (args: string[], cwd: string) =>+ execFileSync('git', args, { cwd, stdio: 'ignore' });++ await fs.mkdir(repoRoot, { recursive: true });+ git(['init'], repoRoot);+ git(['config', 'user.email', '[email protected]'], repoRoot);+ git(['config', 'user.name', 'scope-resolver-test'], repoRoot);+ git(['commit', '--allow-empty', '-m', 'init'], repoRoot);+ git(['worktree', 'add', '-b', 'wt1-branch', wt1], repoRoot);+ git(['worktree', 'add', '-b', 'wt2-branch', wt2], repoRoot);+ await fs.mkdir(path.join(repoRoot, 'apps', 'a'), { recursive: true });+ await fs.mkdir(path.join(repoRoot, 'apps', 'b'), { recursive: true });+ await fs.mkdir(path.join(wt1, 'apps', 'a'), { recursive: true });+ await fs.mkdir(path.join(wt2, 'apps', 'a'), { recursive: true });+ await fs.mkdir(path.join(wt1, 'apps', 'only-in-wt'), { recursive: true });++ const cleanup = async () => {+ try {+ await fs.rm(tmpRoot, { recursive: true, force: true, maxRetries: 3 });+ } catch {+ /* Windows 上 git 只读对象偶发 EPERM — temp 目录交给 OS 清理 */+ }+ };+ return { tmpRoot, repoRoot, wt1, wt2, git, cleanup };+ }++ it('linked worktree 根 cwd → 主仓根', async () => {+ const f = await makeFixture();+ try {+ expect(await resolveMemoryScopeKey(f.wt1)).toBe(f.repoRoot);+ } finally {+ await f.cleanup();+ }+ });++ it('worktree 子目录 cwd → 主仓根 + 相对子路径', async () => {+ const f = await makeFixture();+ try {+ expect(await resolveMemoryScopeKey(path.join(f.wt1, 'apps', 'a'))).toBe(+ path.join(f.repoRoot, 'apps', 'a'),+ );+ } finally {+ await f.cleanup();+ }+ });++ it('子目录在主仓不存在也按字符串映射 (scope key 是身份, 不是磁盘事实)', async () => {+ const f = await makeFixture();+ try {+ expect(await resolveMemoryScopeKey(path.join(f.wt1, 'apps', 'only-in-wt'))).toBe(+ path.join(f.repoRoot, 'apps', 'only-in-wt'),+ );+ } finally {+ await f.cleanup();+ }+ });++ it('两个 linked worktree 的同相对子路径命中同一 scope key', async () => {+ const f = await makeFixture();+ try {+ const k1 = await resolveMemoryScopeKey(path.join(f.wt1, 'apps', 'a'));+ const k2 = await resolveMemoryScopeKey(path.join(f.wt2, 'apps', 'a'));+ expect(k1).toBe(k2);+ expect(k1).toBe(path.join(f.repoRoot, 'apps', 'a'));+ } finally {+ await f.cleanup();+ }+ });++ it('主仓内 cwd (根与子目录) 原样返回 — 非 worktree 场景行为不变', async () => {+ const f = await makeFixture();+ try {+ expect(await resolveMemoryScopeKey(f.repoRoot)).toBe(f.repoRoot);+ expect(await resolveMemoryScopeKey(path.join(f.repoRoot, 'apps', 'b'))).toBe(+ path.join(f.repoRoot, 'apps', 'b'),+ );+ } finally {+ await f.cleanup();+ }+ });++ it('git clone --separate-git-dir 的 checkout 不归一化 (Codex review 第一轮场景)', async () => {+ const f = await makeFixture();+ try {+ const storage = path.join(f.tmpRoot, 'storage', '.git');+ const checkout = path.join(f.tmpRoot, 'separate-checkout');+ // git 不会创建 --separate-git-dir 的父目录+ await fs.mkdir(path.dirname(storage), { recursive: true });+ f.git(['clone', '--separate-git-dir', storage, f.repoRoot, checkout], f.tmpRoot);+ const sub = path.join(checkout, 'apps', 'a');+ await fs.mkdir(sub, { recursive: true });+ expect(await resolveMemoryScopeKey(checkout)).toBe(checkout);+ expect(await resolveMemoryScopeKey(sub)).toBe(sub);+ } finally {+ await f.cleanup();+ }+ });++ it('主仓是 clone --separate-git-dir (无 core.worktree 指针): 跟随 git worktree list 的 canonical 答案 (已知限制)', async () => {+ const f = await makeFixture();+ try {+ const storage = path.join(f.tmpRoot, 'storage2', '.git');+ const main = path.join(f.tmpRoot, 'separate-main');+ const wt3 = path.join(f.tmpRoot, 'wt3');+ await fs.mkdir(path.dirname(storage), { recursive: true });+ f.git(['clone', '--separate-git-dir', storage, f.repoRoot, main], f.tmpRoot);+ f.git(['worktree', 'add', '-b', 'wt3-branch', wt3], main);+ const sub = path.join(wt3, 'apps', 'a');+ await fs.mkdir(sub, { recursive: true });+ // clone --separate-git-dir 不写 core.worktree, git 自身也无法反推真实+ // checkout: `git worktree list` 把 gitdir 父目录报为主工作树 (连从真实+ // checkout 里跑都一样)。resolver 跟随 git 的 canonical 答案, 该布局下+ // 所有 worktree 共享同一 scope; 主 checkout 会话按契约不归一化。+ const canonical = path.dirname(storage);+ expect(await resolveMemoryScopeKey(wt3)).toBe(canonical);+ expect(await resolveMemoryScopeKey(sub)).toBe(path.join(canonical, 'apps', 'a'));+ } finally {+ await f.cleanup();+ }+ });++ it('linked worktree 内初始化过的 submodule → 主仓 submodule 路径 (Codex #2399 P1)', async () => {+ const tmpRoot = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'scope-resolver-sub-')));+ const subRepo = path.join(tmpRoot, 'sub');+ const repoRoot = path.join(tmpRoot, 'repo');+ const wt = path.join(tmpRoot, 'wt');+ const git = (args: string[], cwd: string, extraEnv?: NodeJS.ProcessEnv) =>+ execFileSync('git', args, {+ cwd,+ stdio: 'ignore',+ env: extraEnv ? { ...process.env, ...extraEnv } : process.env,+ });+ try {+ await fs.mkdir(subRepo, { recursive: true });+ git(['init'], subRepo);+ git(['config', 'user.email', '[email protected]'], subRepo);+ git(['config', 'user.name', 'scope-resolver-test'], subRepo);+ await fs.writeFile(path.join(subRepo, 'README'), 'sub\n');+ git(['add', '.'], subRepo);+ git(['commit', '-m', 'sub'], subRepo);++ await fs.mkdir(repoRoot, { recursive: true });+ git(['init'], repoRoot);+ git(['config', 'user.email', '[email protected]'], repoRoot);+ git(['config', 'user.name', 'scope-resolver-test'], repoRoot);+ git(['-c', 'protocol.file.allow=always', 'submodule', 'add', subRepo, 'mod'], repoRoot);+ git(['commit', '-m', 'add sub'], repoRoot);+ git(['worktree', 'add', '-b', 'wt-branch', wt], repoRoot);+ git(['-c', 'protocol.file.allow=always', 'submodule', 'update', '--init'], wt);++ const wtMod = path.join(wt, 'mod');+ const mainMod = path.join(repoRoot, 'mod');+ expect(await resolveMemoryScopeKey(wtMod)).toBe(mainMod);+ expect(await resolveMemoryScopeKey(mainMod)).toBe(mainMod);+ } finally {+ try {+ await fs.rm(tmpRoot, { recursive: true, force: true, maxRetries: 3 });+ } catch {+ /* Windows 上 git 只读对象偶发 EPERM — temp 目录交给 OS 清理 */+ }+ }+ });++ it('linked worktree 内二级 submodule → 主仓嵌套路径 (Codex #2399 P1)', async () => {+ const tmpRoot = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'scope-resolver-nested-sub-')));+ const innerRepo = path.join(tmpRoot, 'inner');+ const midRepo = path.join(tmpRoot, 'mid');+ const repoRoot = path.join(tmpRoot, 'repo');+ const wt = path.join(tmpRoot, 'wt');+ const git = (args: string[], cwd: string) =>+ execFileSync('git', args, {+ cwd,+ stdio: 'ignore',+ env: { ...process.env, GIT_ALLOW_PROTOCOL: 'file' },+ });+ try {+ await fs.mkdir(innerRepo, { recursive: true });+ git(['init'], innerRepo);+ git(['config', 'user.email', '[email protected]'], innerRepo);+ git(['config', 'user.name', 'scope-resolver-test'], innerRepo);+ await fs.writeFile(path.join(innerRepo, 'README'), 'inner\n');+ git(['add', '.'], innerRepo);+ git(['commit', '-m', 'inner'], innerRepo);++ await fs.mkdir(midRepo, { recursive: true });+ git(['init'], midRepo);+ git(['config', 'user.email', '[email protected]'], midRepo);+ git(['config', 'user.name', 'scope-resolver-test'], midRepo);+ git(['-c', 'protocol.file.allow=always', 'submodule', 'add', innerRepo, 'inner'], midRepo);+ git(['commit', '-m', 'add inner'], midRepo);++ await fs.mkdir(repoRoot, { recursive: true });+ git(['init'], repoRoot);+ git(['config', 'user.email', '[email protected]'], repoRoot);+ git(['config', 'user.name', 'scope-resolver-test'], repoRoot);+ git(['-c', 'protocol.file.allow=always', 'submodule', 'add', midRepo, 'mod'], repoRoot);+ git(['commit', '-m', 'add mid'], repoRoot);+ git(['worktree', 'add', '-b', 'wt-nested', wt], repoRoot);+ git(['-c', 'protocol.file.allow=always', 'submodule', 'update', '--init', '--recursive'], wt);++ const wtInner = path.join(wt, 'mod', 'inner');+ const mainInner = path.join(repoRoot, 'mod', 'inner');+ expect(await resolveMemoryScopeKey(wtInner)).toBe(mainInner);+ expect(await resolveMemoryScopeKey(mainInner)).toBe(mainInner);+ } finally {+ try {+ await fs.rm(tmpRoot, { recursive: true, force: true, maxRetries: 3 });+ } catch {+ /* Windows 上 git 只读对象偶发 EPERM — temp 目录交给 OS 清理 */+ }+ }+ });++ it('非 git 目录原样返回', async () => {+ const dir = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'scope-resolver-nogit-')));+ try {+ expect(await resolveMemoryScopeKey(dir)).toBe(dir);+ } finally {+ try {+ await fs.rm(dir, { recursive: true, force: true, maxRetries: 3 });+ } catch {+ /* Windows 上偶发 EBUSY — temp 目录交给 OS 清理 */+ }+ }+ });+});diff --git a/packages/maker-core/src/memory/scope-resolver.test.ts b/packages/maker-core/src/memory/scope-resolver.test.tsnew file mode 100644index 0000000000..c9852ad3ff--- /dev/null+++ b/packages/maker-core/src/memory/scope-resolver.test.ts@@ -0,0 +1,328 @@+/**+ * resolveMemoryScopeKey — worktree 归一化 (#2379) 的单元测试 (默认 unit tier)。+ *+ * 默认层只保留进程内 fake probe 全量覆盖 + 一条真实 Git smoke+ * (engineering-conventions §3.1); 完整真实 Git 矩阵 (多 worktree /+ * separate-git-dir / 主仓内 cwd 等组合语义) 在+ * scope-resolver.git-integration.test.ts, 由 `pnpm test:git-integration` 执行。+ *+ * 与 scope-key.test.ts 的分工: 那边固定 buildMemoryScopeKey 的同步契约+ * (本地原样返回 + SSH 单射); 这边固定 async resolver 的归一化与回落语义。+ */++import { execFileSync } from 'node:child_process';+import { promises as fs } from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';++import { beforeEach, describe, expect, it } from 'vitest';++import {+ __clearMemoryScopeKeyCacheForTests,+ resolveMemoryScopeKey,+ type GitProbe,+} from './scope-resolver.js';+import { buildMemoryScopeKey } from './storage.js';++function gitAvailable(): boolean {+ try {+ execFileSync('git', ['--version'], { stdio: 'ignore' });+ return true;+ } catch {+ return false;+ }+}++beforeEach(() => {+ __clearMemoryScopeKeyCacheForTests();+});++describe('resolveMemoryScopeKey — SSH 与空输入旁路', () => {+ it('SSH remote 会话产出 ssh: 复合键且不 spawn git', async () => {+ let probeCalls = 0;+ const probe: GitProbe = async () => {+ probeCalls += 1;+ throw new Error('should not be called');+ };+ const key = await resolveMemoryScopeKey('/home/me/proj', 'my-host', { execGit: probe });+ expect(key).toBe(buildMemoryScopeKey('/home/me/proj', 'my-host'));+ expect(key).toBe('ssh:my-host:/home/me/proj');+ expect(probeCalls).toBe(0);+ });++ it('空 workingDir 原样返回', async () => {+ expect(await resolveMemoryScopeKey('')).toBe('');+ });++ it('已是 bot: / ssh: 复合键时原样透传且不 spawn git', async () => {+ let probeCalls = 0;+ const probe: GitProbe = async () => {+ probeCalls += 1;+ throw new Error('should not be called');+ };+ await expect(resolveMemoryScopeKey('bot:cindy', null, { execGit: probe })).resolves.toBe('bot:cindy');+ await expect(+ resolveMemoryScopeKey('ssh:my-host:%2Fhome%2Fme', null, { execGit: probe }),+ ).resolves.toBe('ssh:my-host:%2Fhome%2Fme');+ expect(probeCalls).toBe(0);+ });+});++describe('resolveMemoryScopeKey — fake probe 回落与缓存', () => {+ const failingProbe =+ (makeErr: () => Error): GitProbe =>+ async () => {+ throw makeErr();+ };++ /**+ * resolver 的两种探测: rev-parse 单次返回 toplevel/git-dir/common-dir/+ * superproject 四行 (无 superproject 时第四行为空);+ * 仅在真 linked worktree 或 worktree 内 submodule 时再调+ * `worktree list --porcelain` 取主仓根。不传 mainRoot 表示该用例不允许+ * 出现第二次 spawn (在更早的分支就已回落)。+ */+ const probeFor =+ (+ toplevel: string,+ gitDir: string,+ commonDir: string,+ mainRoot?: string,+ superproject = '',+ ): GitProbe =>+ async (args) => {+ if (args.includes('worktree')) {+ if (mainRoot === undefined) throw new Error('worktree list should not be spawned');+ return `worktree ${mainRoot}\n`;+ }+ return `${toplevel}\n${gitDir}\n${commonDir}\n${superproject}\n`;+ };++ it('git 不存在 (ENOENT) → 原样返回', async () => {+ const probe = failingProbe(() => Object.assign(new Error('spawn git ENOENT'), { code: 'ENOENT' }));+ expect(await resolveMemoryScopeKey('/fake/no-git', null, { execGit: probe })).toBe('/fake/no-git');+ });++ it('非 git 目录 (exit 128) → 原样返回', async () => {+ const probe = failingProbe(() => Object.assign(new Error('not a git repository'), { code: 128 }));+ expect(await resolveMemoryScopeKey('/fake/not-repo', null, { execGit: probe })).toBe(+ '/fake/not-repo',+ );+ });++ it('探测超时 → 原样返回', async () => {+ const probe = failingProbe(() => Object.assign(new Error('timed out'), { killed: true }));+ expect(await resolveMemoryScopeKey('/fake/timeout', null, { execGit: probe })).toBe(+ '/fake/timeout',+ );+ });++ it('separate-git-dir checkout (gitdir == common-dir 且 basename 为 .git) → 原样返回', async () => {+ // `git clone --separate-git-dir=/some/storage/.git` 的 common-dir basename+ // 恰好也是 .git, 不做 gitdir ≠ common-dir 区分会把主仓根错误推导到 git+ // 存储目录 (Codex review on #2399)。+ const probe = probeFor('/fake/checkout', '/some/storage/.git', '/some/storage/.git');+ expect(await resolveMemoryScopeKey('/fake/checkout', null, { execGit: probe })).toBe(+ '/fake/checkout',+ );+ });++ it('主仓内 submodule (gitdir == common-dir + superproject == 主仓根) → 原样返回', async () => {+ // 有 superproject 时仍会调 worktree list 确认外层不是 linked worktree;+ // 主仓根与 superproject 相同则保持原路径。+ const probe = probeFor(+ '/main/mod',+ '/main/.git/modules/mod',+ '/main/.git/modules/mod',+ '/main',+ '/main',+ );+ expect(await resolveMemoryScopeKey('/main/mod', null, { execGit: probe })).toBe('/main/mod');+ });++ it('linked worktree 内 submodule → 主仓 submodule 路径 (Codex #2399 P1)', async () => {+ const probe = probeFor(+ '/wt/mod',+ '/main/.git/worktrees/wt/modules/mod',+ '/main/.git/worktrees/wt/modules/mod',+ '/main',+ '/wt',+ );+ expect(await resolveMemoryScopeKey('/wt/mod', null, { execGit: probe })).toBe(+ path.join(path.resolve('/main'), 'mod'),+ );+ });++ it('linked worktree 内二级 submodule 沿 superproject 链归一到主仓 (Codex #2399 P1)', async () => {+ const abs = (p: string) => path.resolve(p);+ const inner = abs('/wt/mod/inner');+ const parentMod = abs('/wt/mod');+ const wt = abs('/wt');+ const main = abs('/main');+ const byCwd: Record<string, { toplevel: string; gitDir: string; commonDir: string; superproject: string }> = {+ [inner]: {+ toplevel: inner,+ gitDir: abs('/main/.git/worktrees/wt/modules/mod/modules/inner'),+ commonDir: abs('/main/.git/worktrees/wt/modules/mod/modules/inner'),+ superproject: parentMod,+ },+ [parentMod]: {+ toplevel: parentMod,+ gitDir: abs('/main/.git/worktrees/wt/modules/mod'),+ commonDir: abs('/main/.git/worktrees/wt/modules/mod'),+ superproject: wt,+ },+ [wt]: {+ toplevel: wt,+ gitDir: abs('/main/.git/worktrees/wt'),+ commonDir: abs('/main/.git'),+ superproject: '',+ },+ };+ const probe: GitProbe = async (args, cwd) => {+ if (args.includes('worktree')) return `worktree ${main}\n`;+ const rec = byCwd[path.normalize(cwd)] ?? byCwd[cwd];+ if (!rec) throw new Error(`unexpected cwd ${cwd}`);+ return `${rec.toplevel}\n${rec.gitDir}\n${rec.commonDir}\n${rec.superproject}\n`;+ };+ expect(await resolveMemoryScopeKey(inner, null, { execGit: probe })).toBe(+ path.join(main, 'mod', 'inner'),+ );+ });++ it('common-dir 非 <root>/.git 形态 (bare/非常规布局) → 原样返回', async () => {+ const probe = probeFor('/fake/bare-wt', '/fake/repo.git/worktrees/x', '/fake/repo.git');+ expect(await resolveMemoryScopeKey('/fake/bare-wt', null, { execGit: probe })).toBe(+ '/fake/bare-wt',+ );+ });++ it('cwd 不在 toplevel 下 (relative 逃逸) → 原样返回', async () => {+ const probe = probeFor('/totally/other', '/main/.git/worktrees/w', '/main/.git', '/main');+ expect(await resolveMemoryScopeKey('/fake/escape', null, { execGit: probe })).toBe(+ '/fake/escape',+ );+ });++ it('主仓本身是 separate-git-dir 布局: linked worktree 映射到真实主 checkout', async () => {+ // common-dir 是 git 存储目录 (/storage/.git), dirname 不是工作树;+ // 主仓根必须来自 `worktree list --porcelain` 第一条 (Codex review 第二轮)。+ const probe = probeFor(+ '/fake/wt',+ '/storage/.git/worktrees/w',+ '/storage/.git',+ '/real/checkout',+ );+ expect(await resolveMemoryScopeKey('/fake/wt/apps/a', null, { execGit: probe })).toBe(+ path.join(path.resolve('/real/checkout'), 'apps', 'a'),+ );+ });++ it('worktree list 取不到主仓根 → 原样返回', async () => {+ const probe: GitProbe = async (args) => {+ if (args.includes('worktree')) return '\n'; // 无 worktree 记录+ return '/fake/wt\n/main/.git/worktrees/w\n/main/.git\n';+ };+ expect(await resolveMemoryScopeKey('/fake/wt', null, { execGit: probe })).toBe('/fake/wt');+ });++ it('同 cwd 重复解析只 spawn 一轮 git (正结果缓存)', async () => {+ // 平台绝对路径: POSIX 风格 '/repo' 在 Windows 上会被 resolve 到当前盘符,+ // fake 输出直接给平台绝对形态, 让断言与盘符无关。+ const abs = (p: string) => (process.platform === 'win32' ? `C:${p}` : p);+ let calls = 0;+ const base = probeFor(+ abs('/repo/.cindy-worktrees/feat'),+ abs('/repo/.git/worktrees/feat'),+ abs('/repo/.git'),+ abs('/repo'),+ );+ const probe: GitProbe = async (args, cwd) => {+ calls += 1;+ return base(args, cwd);+ };+ const first = await resolveMemoryScopeKey(abs('/repo/.cindy-worktrees/feat/apps/a'), null, {+ execGit: probe,+ });+ const second = await resolveMemoryScopeKey(abs('/repo/.cindy-worktrees/feat/apps/a'), null, {+ execGit: probe,+ });+ expect(first).toBe(path.join(abs('/repo'), 'apps', 'a'));+ expect(second).toBe(first);+ expect(calls).toBe(2); // rev-parse + worktree list 各一次, 第二轮全缓存+ });++ it('失败结果同样缓存 (负结果不重复 spawn)', async () => {+ let calls = 0;+ const probe: GitProbe = async () => {+ calls += 1;+ throw Object.assign(new Error('not a git repository'), { code: 128 });+ };+ await resolveMemoryScopeKey('/fake/neg-cache', null, { execGit: probe });+ await resolveMemoryScopeKey('/fake/neg-cache', null, { execGit: probe });+ expect(calls).toBe(1);+ });++ it('TTL 过期后重新探测', async () => {+ let calls = 0;+ let tick = 0;+ const base = probeFor('/repo/.wt/x', '/repo/.git/worktrees/x', '/repo/.git', '/repo');+ const probe: GitProbe = async (args, cwd) => {+ calls += 1;+ return base(args, cwd);+ };+ const now = () => tick;+ await resolveMemoryScopeKey('/repo/.wt/x', null, { execGit: probe, now });+ tick = 30_000;+ await resolveMemoryScopeKey('/repo/.wt/x', null, { execGit: probe, now });+ expect(calls).toBe(2);+ tick = 61_000;+ await resolveMemoryScopeKey('/repo/.wt/x', null, { execGit: probe, now });+ expect(calls).toBe(4);+ });++ it.skipIf(process.platform !== 'win32')(+ 'Windows 风格路径: git 正斜杠输出 + 反斜杠 cwd 混合归一化',+ async () => {+ const probe = probeFor(+ 'C:/repo/.cindy-worktrees/feat',+ 'C:/repo/.git/worktrees/feat',+ 'C:/repo/.git',+ 'C:/repo',+ );+ const key = await resolveMemoryScopeKey('C:\\repo\\.cindy-worktrees\\feat\\apps\\a', null, {+ execGit: probe,+ });+ expect(key).toBe('C:\\repo\\apps\\a');+ },+ );+});++// 默认 unit tier 唯一一条真实 Git smoke (§3.1): 端到端打通「真实 git 探测 ++// 映射」主路径。组合矩阵见 scope-resolver.git-integration.test.ts。+describe.skipIf(!gitAvailable())('resolveMemoryScopeKey — 真实 Git smoke', () => {+ it('linked worktree 子目录 cwd → 主仓根 + 相对子路径', async () => {+ const tmpRoot = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'scope-resolver-')));+ const repoRoot = path.join(tmpRoot, 'repo');+ const wt = path.join(tmpRoot, 'wt');+ const git = (args: string[], cwd: string) =>+ execFileSync('git', args, { cwd, stdio: 'ignore' });+ try {+ await fs.mkdir(repoRoot, { recursive: true });+ git(['init'], repoRoot);+ git(['config', 'user.email', '[email protected]'], repoRoot);+ git(['config', 'user.name', 'scope-resolver-test'], repoRoot);+ git(['commit', '--allow-empty', '-m', 'init'], repoRoot);+ git(['worktree', 'add', '-b', 'wt-branch', wt], repoRoot);+ const sub = path.join(wt, 'apps', 'a');+ await fs.mkdir(sub, { recursive: true });+ expect(await resolveMemoryScopeKey(sub)).toBe(path.join(repoRoot, 'apps', 'a'));+ } finally {+ try {+ await fs.rm(tmpRoot, { recursive: true, force: true, maxRetries: 3 });+ } catch {+ /* Windows 上 git 只读对象偶发 EPERM — temp 目录交给 OS 清理 */+ }+ }+ });+});diff --git a/packages/maker-core/src/memory/scope-resolver.ts b/packages/maker-core/src/memory/scope-resolver.tsnew file mode 100644index 0000000000..2c62fcb6d9--- /dev/null+++ b/packages/maker-core/src/memory/scope-resolver.ts@@ -0,0 +1,291 @@+/**+ * scope-resolver.ts — resolveMemoryScopeKey: Maker Memory scope key 的 async+ * 归一化入口 (#2379 问题一)。+ *+ * 背景: buildMemoryScopeKey (storage.ts) 是纯同步函数, 本地会话原样透传 workdir+ * 绝对路径。git linked worktree 的 cwd ≠ 主仓路径 → 同一仓库被拆成多个独立+ * Store, worktree 会话 memory_search 恒 0 命中 (实测主仓分片 80 条记录,+ * worktree 分片是空库基线)。+ *+ * 本模块只做一件事: 本地会话取 scope key 前先做 worktree 归一化 ——+ * linked worktree 的 cwd → `主仓根 + cwd 相对 worktree 根的子路径`+ * 例: /repo/.cindy-worktrees/feat-x/apps/a → /repo/apps/a+ * 即保留「按 cwd 隔离」的既有语义 (子目录仍是独立 scope), 只把 worktree 根+ * 替换回主仓根。「整个仓库共用一份 memory」是 scope 语义变更, 明确不在+ * 本模块做 (#2379 评论收敛)。+ *+ * 分工:+ * - buildMemoryScopeKey (同步): SSH 复合键规则 + 本地原样透传的既有契约, 不变。+ * - resolveMemoryScopeKey (async, 本模块): 所有 getStore 调用方的统一入口。+ * SSH 直接委托 buildMemoryScopeKey (不在控制端解析远端 git); 本地先归一化。+ *+ * 回落 (一律返回 cwd 原样, 与既有行为完全一致): 非 git 目录 / git 不可用 /+ * 探测超时 / bare repo / 非 linked-worktree 布局 (普通 clone /+ * --separate-git-dir checkout, gitdir == common-dir 且无 superproject) /+ * 非常规 common-dir 布局 / cwd 不在 toplevel 下。+ * 特例: linked worktree 内初始化过的 submodule 的 gitdir == common-dir+ * (都是 `<主仓>/.git/worktrees/<wt>/modules/<sub>`), 不能当普通 clone 回落;+ * `--show-superproject-working-tree` 只给直接父仓库, 二级 submodule 的父是+ * 另一层 submodule 而不是 worktree — 必须沿 superproject 链走到最外层+ * (linked worktree 或主仓) 再归一, 否则 `git worktree list` 会把 `.git`+ * 元数据目录报成唯一 worktree。+ * 非仓库目录由 `.git` 标记上溯预检直接短路, 连 git 进程都不 spawn+ * (hasGitMarkerUpward, 与 rev-parse 上溯语义一致)。+ *+ * 缓存: lizi-mcps withStore 在每次 memory 工具调用都经本函数, 不能每次 spawn+ * git 子进程 — 进程内 Map 缓存 (正/负结果同 TTL, in-flight promise 去重)。+ * TTL 兜底「目录身份在进程生命周期内变化」(目录后变成 worktree 等) 的极端+ * 场景; 归一化本身幂等 (主仓路径再解析返回自身), 缓存不破坏正确性。+ */++import { execFile } from 'node:child_process';+import { promises as fs } from 'node:fs';+import * as path from 'node:path';+import { promisify } from 'node:util';++import { buildMemoryScopeKey, SSH_SCOPE_KEY_PREFIX } from './storage.js';++const BOT_SCOPE_KEY_PREFIX = 'bot:';++/** git 探测抽象: 跑一条 git 命令, resolve stdout。失败 (非 git 目录/超时/无 git) reject。 */+export type GitProbe = (args: string[], cwd: string) => Promise<string>;++export interface ResolveMemoryScopeKeyDeps {+ /**+ * 测试注入: 替代真实 git 调用 (fake 驱动失败/超时/缓存断言)。+ * 注入 execGit 时跳过 .git 标记预检 — 调用方显式接管探测, 预检无意义。+ */+ execGit?: GitProbe;+ /** 测试注入: 时钟 (TTL 过期路径)。 */+ now?: () => number;+}++/** 单次 git 探测超时。会话启动路径, 宁可回落也不卡 spawn。 */+const GIT_PROBE_TIMEOUT_MS = 3_000;+/** 缓存 TTL (正/负结果一致)。目录身份中途变化是极端场景, 60s 收敛足够。 */+const CACHE_TTL_MS = 60_000;++const execFileAsync = promisify(execFile);++/**+ * 预检: cwd 或任一祖先目录存在 `.git` 才值得 spawn git。非仓库目录 (dialogue+ * 一次性目录、临时 cwd) 直接跳过 — 与 git rev-parse 的上溯查找语义一致, 但把+ * 两次进程 spawn 换成几次 stat。对 Windows 还有一层必要收益: 短命子进程引用+ * 临时目录会跟 teardown 删目录撞出 EPERM。+ */+async function hasGitMarkerUpward(cwd: string): Promise<boolean> {+ let dir = cwd;+ for (;;) {+ try {+ await fs.access(path.join(dir, '.git'));+ return true;+ } catch {+ /* 不在这一层, 继续上溯 */+ }+ const parent = path.dirname(dir);+ if (parent === dir) return false;+ dir = parent;+ }+}++async function defaultExecGit(args: string[], cwd: string): Promise<string> {+ // 用 `git -C <dir>` 而不是 child 的 cwd 选项: Windows 上子进程的 CWD 会锁住+ // 该目录, 会话用临时 cwd 的测试/短命场景在 teardown 删目录时 EPERM。+ // 相对路径输出 (--git-common-dir) 相对 -C 目录解析, 与 cwd 选项语义一致。+ const { stdout } = await execFileAsync('git', ['-C', cwd, ...args], {+ timeout: GIT_PROBE_TIMEOUT_MS,+ maxBuffer: 1024 * 1024,+ windowsHide: true,+ });+ return stdout;+}++interface CacheEntry {+ value: Promise<string>;+ expiresAt: number;+}++const scopeKeyCache = new Map<string, CacheEntry>();++/** 测试专用: 清空进程内缓存。生产代码不应调用。 */+export function __clearMemoryScopeKeyCacheForTests(): void {+ scopeKeyCache.clear();+}++/**+ * 取 scope key 的统一入口 (async)。所有 getStore 调用方 (agent 启动注入 /+ * MCP withStore / manager 兜底) 必须经本函数, 不得各自拼 key 或自行探测 git。+ */+export async function resolveMemoryScopeKey(+ workingDir: string,+ remoteHostId?: string | null,+ deps?: ResolveMemoryScopeKeyDeps,+): Promise<string> {+ // SSH remote: 复合键规则不变 (单射性质经过 review, 见 storage.ts),+ // 远端路径是远端机器上的字符串, 控制端不解析远端 git。+ if (remoteHostId) return buildMemoryScopeKey(workingDir, remoteHostId);+ if (!workingDir) return workingDir;+ // 已经是复合键 (bot: / ssh:) 时不得再当本地路径做 git worktree 归一化。+ // Bot scope 由 host 显式注入; SSH 复合键若被二次传入同样原样透传。+ if (workingDir.startsWith(BOT_SCOPE_KEY_PREFIX) || workingDir.startsWith(SSH_SCOPE_KEY_PREFIX)) {+ return workingDir;+ }++ const execGit = deps?.execGit;+ const now = deps?.now ?? (() => Date.now());+ // Windows 路径大小写不敏感, 缓存 key 统一小写 (返回值保留原始大小写)。+ const cacheKey = process.platform === 'win32' ? workingDir.toLowerCase() : workingDir;+ const hit = scopeKeyCache.get(cacheKey);+ if (hit && hit.expiresAt > now()) return hit.value;++ const value = (async () => {+ // 非仓库目录预检 (默认探测路径): 没有 .git 标记时 git rev-parse 必然失败,+ // 直接回落, 省掉一次进程 spawn (也避开 Windows 临时目录的 EPERM 竞争)。+ // 注入了 execGit 的调用方显式接管探测, 跳过预检。+ if (!execGit && !(await hasGitMarkerUpward(path.normalize(workingDir)).catch(() => true))) {+ return workingDir;+ }+ // 任何失败都回落 cwd 原样 — 归一化是纯增强, 绝不让 git 探测故障阻断 memory。+ return canonicalizeLocalWorkdir(workingDir, execGit ?? defaultExecGit).catch(() => workingDir);+ })();+ scopeKeyCache.set(cacheKey, { value, expiresAt: now() + CACHE_TTL_MS });+ return value;+}++/**+ * linked worktree cwd → `主仓根 + cwd 相对 worktree 根的子路径`。+ * 探测方式与 desktop WorktreeManager 同模式: rev-parse + path.resolve+ * 解析相对输出 (兼容不支持 --path-format 的旧 git)。单次 rev-parse 拿+ * toplevel / git-dir / git-common-dir / superproject 四个值 (输出顺序与+ * 参数一致; 无 superproject 时第四行为空); 确认是 linked worktree 或+ * worktree 内 submodule 后再用一次 `worktree list --porcelain` 取主仓根。+ * 失败抛错由调用方回落。+ */+async function canonicalizeLocalWorkdir(workingDir: string, execGit: GitProbe): Promise<string> {+ const cwd = path.normalize(workingDir);+ const out = await execGit(+ [+ 'rev-parse',+ '--show-toplevel',+ '--git-dir',+ '--git-common-dir',+ '--show-superproject-working-tree',+ ],+ cwd,+ );+ const [toplevelRaw, gitDirRaw, commonDirRaw, superRaw] = out.split('\n');+ const toplevel = resolveGitDirOutput(toplevelRaw ?? '', cwd);+ const gitDir = resolveGitDirOutput(gitDirRaw ?? '', cwd);+ const commonDir = resolveGitDirOutput(commonDirRaw ?? '', cwd);+ const directSuper = resolveGitDirOutput(superRaw ?? '', cwd);+ if (!toplevel || !gitDir || !commonDir) return workingDir;++ // 判定链 (Codex #2399 P1, linked-worktree submodule):+ // 1. gitdir ≠ common-dir → 真 linked worktree, 归一到主仓根 + 相对路径。+ // 2. gitdir == common-dir 且有 superproject → cwd 是 submodule。+ // 主仓内 submodule 的 superproject == 主仓根, 原样返回 (与 round-1 契约一致)。+ // linked worktree 内 submodule 的 gitdir == common-dir (都是+ // `<主仓>/.git/worktrees/<wt>/modules/<sub>`), 不能当普通 clone 回落;+ // 把**最外层** superproject (walk 链, 不是直接父) 当 mapping 根再走+ // 同一套主仓映射, 得到 `/main/<nested-rel>` 而不是 `.git` 元数据目录。+ // 3. gitdir == common-dir 且无 superproject → 普通 clone /+ // --separate-git-dir checkout, 原样返回。separate-git-dir 的 common-dir+ // basename 恰好也是 `.git`, 不先排除会把主仓根错误推导到 git 存储目录+ // (Codex review on #2399)。+ const outermostSuper = directSuper+ ? await walkOutermostSuperproject(directSuper, execGit)+ : null;+ if (samePath(gitDir, commonDir)) {+ if (!outermostSuper) return workingDir;+ } else if (path.basename(commonDir) !== '.git') {+ // bare repo 的 linked worktree (common-dir 是 `<name>.git`) 等非常规布局+ // 无法可靠推断主仓根, 回落原样。submodule 走上面 superproject 分支,+ // 不看这一条 (其 gitdir == common-dir)。+ return workingDir;+ }++ const mappingRoot = outermostSuper ?? toplevel;++ // 主仓根不能从 common-dir 推导: 主 checkout 本身用 --separate-git-dir 建+ // 时 common-dir 是 git 存储目录, dirname 不一定是工作树 (Codex review on+ // #2399 第二轮)。统一用 `git worktree list --porcelain` 第一条记录 — git+ // 保证主工作树排第一; 布局带 core.worktree 指针时取到真实主 checkout。+ //+ // 已知限制: `git clone --separate-git-dir` 不写 core.worktree, git 自身+ // 也无法从 gitdir 反推真实 checkout (`git worktree list` 直接把 gitdir+ // 父目录报为主工作树, 连从真实 checkout 里跑都一样)。这种布局下本函数+ // 跟随 git 的 canonical 答案; 主 checkout 会话按 round-1 契约不归一化,+ // 即该极端布局下主 checkout 与 worktree 的 memory 不共享 (与 PR 前行为+ // 一致, 不回归)。+ const mainRoot = await resolveMainWorktreeRoot(mappingRoot, execGit);+ if (!mainRoot) return workingDir;++ // 防御: 映射根即主仓根时无需归一化 (主仓内 cwd / 主仓内 submodule),+ // 原样返回, 保持「本地原样返回」契约。+ if (samePath(mappingRoot, mainRoot)) return workingDir;++ // linked worktree (含其内 submodule): 子路径映射回主仓根下+ // (该路径在主仓可以不存在 — scope key 只是身份字符串, 落盘目录名经+ // memoryScopeDirName 派生)。+ const rel = path.relative(mappingRoot, cwd);+ if (rel === '') return mainRoot;+ // cwd 不在映射根下 (symlink/大小写风格不一致等) — 不猜, 回落。+ if (rel.startsWith('..') || path.isAbsolute(rel)) return workingDir;+ return path.join(mainRoot, rel);+}++/** git rev-parse 输出 → 绝对路径。空输出返 null (调用方回落)。 */+function resolveGitDirOutput(raw: string, cwd: string): string | null {+ const trimmed = raw.trim();+ if (!trimmed) return null;+ return path.normalize(path.resolve(cwd, trimmed));+}++/**+ * `git worktree list --porcelain` 第一条 `worktree ` 记录 = 主工作树路径+ * (git 保证主工作树排第一)。取不到返 null (调用方回落)。+ */+async function resolveMainWorktreeRoot(cwd: string, execGit: GitProbe): Promise<string | null> {+ const out = await execGit(['worktree', 'list', '--porcelain'], cwd);+ const line = out.split('\n').find((l) => l.startsWith('worktree '));+ if (!line) return null;+ return resolveGitDirOutput(line.slice('worktree '.length), cwd);+}++function samePath(a: string, b: string): boolean {+ return process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b;+}++/**+ * `--show-superproject-working-tree` 只给直接父仓库。二级 submodule 的父是+ * 另一层 submodule, 在那一层跑 `git worktree list` 会把+ * `<main>/.git/worktrees/<wt>/modules/<parent>` 报成唯一 worktree, 把+ * scope 映射进 .git 元数据目录 (Codex #2399 P1)。沿链走到没有 superproject+ * 的最外层 (linked worktree 或主仓) 再交给 resolveMainWorktreeRoot。+ */+async function walkOutermostSuperproject(start: string, execGit: GitProbe): Promise<string> {+ let current = start;+ const seen = new Set<string>();+ for (let i = 0; i < 16; i += 1) {+ const key = process.platform === 'win32' ? current.toLowerCase() : current;+ if (seen.has(key)) return current;+ seen.add(key);+ // 与 canonicalize 同一条 4 行 rev-parse, 让既有 cwd-agnostic fake probe+ // 仍返回 superproject 在第四行; 单字段 --show-superproject-working-tree+ // 会被 probeFor 的第一行 toplevel 误当成父仓。+ const out = await execGit(+ [+ 'rev-parse',+ '--show-toplevel',+ '--git-dir',+ '--git-common-dir',+ '--show-superproject-working-tree',+ ],+ current,+ ).catch(() => '');+ const parent = resolveGitDirOutput(out.split('\n')[3] ?? '', current);+ if (!parent || samePath(parent, current)) return current;+ current = parent;+ }+ return current;+}diff --git a/packages/maker-core/src/memory/storage.ts b/packages/maker-core/src/memory/storage.tsindex 9a6636b477..bdbf46af9d 100644--- a/packages/maker-core/src/memory/storage.ts+++ b/packages/maker-core/src/memory/storage.ts@@ -69,7 +69,9 @@ export function sanitizeWorkdir(absPath: string): string {* 裸拼接时 ('/x:/repo','prod') 与 ('/repo','prod:/x') 会撞成同一个 key* (review R5 P2);常规 alias 编码前后相同,键仍可读。数据仍存控制端本机,* 目录名经 memoryScopeDirName 派生。所有 getStore 调用方 (agent 启动注入 /- * MCP withStore) 必须统一经本函数取键,不得各自拼接。+ * MCP withStore) 必须统一取键,不得各自拼接——**统一入口是 async 的+ * resolveMemoryScopeKey (scope-resolver.ts)**: 它在本地会话上额外做 git+ * linked-worktree 归一化 (#2379), 本函数保持同步原契约不变。*/export function buildMemoryScopeKey(workingDir: string, remoteHostId?: string | null): string {return remoteHostId ? `ssh:${encodeURIComponent(remoteHostId)}:${workingDir}` : workingDir;@@ -106,7 +108,7 @@ export function parseBotMemoryScopeKey(scopeKey: string): string | null {}/** buildMemoryScopeKey 的远端键前缀。本地键恒为绝对路径, 不会以它开头。 */-const SSH_SCOPE_KEY_PREFIX = 'ssh:';+export const SSH_SCOPE_KEY_PREFIX = 'ssh:';const BOT_SCOPE_KEY_PREFIX = 'bot:';/**diff --git a/scripts/__tests__/test-workspaces.test.mjs b/scripts/__tests__/test-workspaces.test.mjsindex 1576d16976..d4f7c4af43 100644--- a/scripts/__tests__/test-workspaces.test.mjs+++ b/scripts/__tests__/test-workspaces.test.mjs@@ -216,6 +216,7 @@ test("unit workspace concurrency reserves the full worker budget for heavy worksassert.deepEqual(makerCore.tiers.unit.exclude, ["**/*.integration.test.ts","**/*.e2e.test.ts",+ "**/*.git-integration.test.ts",]);assert.deepEqual(makerCore.tiers.unit.command, {type: "packageBin",@@ -555,6 +556,32 @@ test("desktop real-Git coverage is an explicit coordinated tier outside defaultassert.deepEqual(selectFilesForTier(desktop, tier, files), files.slice(0, 2));});+test("maker-core real-Git worktree matrix is an explicit tier outside default unit", () => {+ const makerCore = manifest.workspaces.find(+ (workspace) => workspace.cwd === "packages/maker-core",+ );+ const tier = makerCore.tiers["git-integration"];++ assert.equal(tier.status, "manual");+ assert.equal(tier.coverage, "allowlist");+ assert.deepEqual(tier.include, ["src/**/*.git-integration.test.ts"]);+ assert.deepEqual(tier.command, {+ type: "packageBin",+ bin: "vitest",+ args: ["run", "--maxWorkers=1"],+ });+ assert.ok(makerCore.tiers.unit.exclude.includes("**/*.git-integration.test.ts"));++ const files = [+ "packages/maker-core/src/memory/scope-resolver.git-integration.test.ts",+ "packages/maker-core/src/memory/scope-resolver.test.ts",+ ];+ assert.deepEqual(selectFilesForTier(makerCore, makerCore.tiers.unit, files), [+ "packages/maker-core/src/memory/scope-resolver.test.ts",+ ]);+ assert.deepEqual(selectFilesForTier(makerCore, tier, files), files.slice(0, 1));+});+test("default desktop unit keeps real Git subprocess coverage to one smoke", () => {const files = discoverTestFiles(readAllFiles(ROOT)).filter((file) =>diff --git a/scripts/test-workspaces.config.mjs b/scripts/test-workspaces.config.mjsindex 5ef7b28f43..529e6734c4 100644--- a/scripts/test-workspaces.config.mjs+++ b/scripts/test-workspaces.config.mjs@@ -258,7 +258,14 @@ export default {unit: {status: 'required',command: unitVitestCommand(1, 'forks'),- exclude: ['**/*.integration.test.ts', '**/*.e2e.test.ts'],+ exclude: ['**/*.integration.test.ts', '**/*.e2e.test.ts', '**/*.git-integration.test.ts'],+ },+ 'git-integration': {+ status: 'manual',+ reason: 'Full real-Git coverage is explicit because each case builds temporary repos, linked worktrees and separate-git-dir clones via git subprocesses.',+ coverage: 'allowlist',+ command: vitestBin('run', '--maxWorkers=1'),+ include: ['src/**/*.git-integration.test.ts'],},integration: {status: 'manual',