Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(pi): revalidate nearest git boundary

nana6a9ba9ab96de
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
index 469a8fcb2b..3f90a99be6 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
@@ -98,6 +98,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
// non-native sync implementation may preserve an 8.3 alias (RUNNER~1)
// while the async native implementation returns the final long path.
cwd = realpathSync.native(mkdtempSync(path.join(tmpdir(), 'pi-cleanup-cwd-')));
+ mkdirSync(path.join(cwd, '.git'));
});
afterEach(() => {
@@ -154,11 +155,12 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
workingDir: string,
revision: string,
skills: readonly string[],
+ repoRoot = workingDir,
): PiProjectTrustInputSnapshot {
const identity: PiProjectTrustInputSnapshot['identity'] = {
workingDir,
canonicalWorkingDir: workingDir,
- canonicalRepoRoot: workingDir,
+ canonicalRepoRoot: repoRoot,
repoRootStatus: 'resolved',
platform: process.platform === 'win32' ? 'win32' : 'posix',
canonicalPathEncoding: process.platform === 'win32' ? 'utf16-lossless' : 'utf8-lossless',
@@ -296,6 +298,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
it('fails closed when the resolver returns another workingDir approval snapshot', async () => {
const approvedDir = realpathSync.native(mkdtempSync(path.join(tmpdir(), 'pi-approved-other-')));
try {
+ mkdirSync(path.join(approvedDir, '.git'));
const skillPath = path.join(approvedDir, '.pi', 'skills', 'other-project-skill');
mkdirSync(skillPath, { recursive: true });
writeFileSync(path.join(skillPath, 'SKILL.md'), '# other project\n');
@@ -325,6 +328,49 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
}
});
+ it('fails closed when a nearer Git root appears after the approval snapshot', async () => {
+ const outerRepo = realpathSync.native(mkdtempSync(path.join(tmpdir(), 'pi-approved-outer-')));
+ try {
+ const requestedDir = path.join(outerRepo, 'packages', 'nested');
+ const skillPath = path.join(outerRepo, '.agents', 'skills', 'outer-skill');
+ mkdirSync(path.join(outerRepo, '.git'));
+ mkdirSync(requestedDir, { recursive: true });
+ mkdirSync(skillPath, { recursive: true });
+ writeFileSync(path.join(skillPath, 'SKILL.md'), '# outer project\n');
+ const snapshot = approvedInput(
+ requestedDir,
+ 'rev-before-nested-repo',
+ [skillPath],
+ outerRepo,
+ );
+ mkdirSync(path.join(requestedDir, '.git'));
+
+ const agent = new PiAgent(buildDeps({
+ resolvePiProjectTrustInput: async () => snapshot,
+ }));
+ const handle = await agent.startSession({
+ sessionId: 'nested-repo',
+ workingDir: requestedDir,
+ model: 'm',
+ });
+ try {
+ expect(repeatedArgValues(knobs.spawnedArgs[0]!, '--skill')).toEqual([]);
+ await vi.waitFor(() => {
+ expect(handle.getRuntimeCapabilities?.()?.projectResources).toMatchObject({
+ status: 'approved',
+ reason: 'approved-repo-root-changed',
+ approvalRevision: 'rev-before-nested-repo',
+ requestedSkillCount: 0,
+ });
+ });
+ } finally {
+ await handle.close();
+ }
+ } finally {
+ rmSync(outerRepo, { recursive: true, force: true });
+ }
+ });
+
it('injects remote MCP secrets only through env and marks them for bash-child stripping', async () => {
const agent = new PiAgent(buildDeps());
const handle = await agent.startSession(opts());
diff --git a/packages/maker-core/src/agents/pi/__tests__/project-resource-assembly.test.ts b/packages/maker-core/src/agents/pi/__tests__/project-resource-assembly.test.ts
index c8b0703dc5..c71e787c7e 100644
--- a/packages/maker-core/src/agents/pi/__tests__/project-resource-assembly.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/project-resource-assembly.test.ts
@@ -52,6 +52,7 @@ const available = {
isFile: () => candidate.toLowerCase().endsWith('.md'),
}),
realpath: async (skillPath: string) => skillPath,
+ findNearestGitRoot: async (workingDir: string) => workingDir.split('/').slice(0, 3).join('/'),
};
describe('Pi approved project resource assembly', () => {
@@ -124,7 +125,7 @@ describe('Pi approved project resource assembly', () => {
const result = await assembleApprovedPiProjectResources(
inputFor(workingDir, approved(workingDir, 'rev-a'), [first, missing]),
workingDir,
- { stat, realpath: available.realpath },
+ { ...available, stat },
);
expect(stat).toHaveBeenCalled();
@@ -177,7 +178,7 @@ describe('Pi approved project resource assembly', () => {
const workingDir = '/repo-a/packages/app';
const input = inputFor(workingDir, approved(workingDir, 'rev-a'));
const result = await assembleApprovedPiProjectResources(input, workingDir, {
- stat: available.stat,
+ ...available,
realpath: async (candidate) => candidate === input.discovered.skills[0]
? '/outside/retargeted-skill'
: candidate,
@@ -192,7 +193,7 @@ describe('Pi approved project resource assembly', () => {
const input = inputFor(workingDir, approved(workingDir, 'rev-a'));
const skillFile = `${input.discovered.skills[0]}/SKILL.md`;
const result = await assembleApprovedPiProjectResources(input, workingDir, {
- stat: available.stat,
+ ...available,
realpath: async (candidate) => candidate === skillFile
? '/outside/retargeted-SKILL.md'
: candidate,
@@ -207,7 +208,7 @@ describe('Pi approved project resource assembly', () => {
const input = inputFor(workingDir, approved(workingDir, 'rev-a'));
const skillFile = `${input.discovered.skills[0]}/SKILL.md`;
const result = await assembleApprovedPiProjectResources(input, workingDir, {
- stat: available.stat,
+ ...available,
realpath: async (candidate) => candidate === skillFile
? '/repo-a/packages/shared/demo.md'
: candidate,
@@ -254,11 +255,11 @@ describe('Pi approved project resource assembly', () => {
const input = inputFor(workingDir, approved(workingDir, 'rev-a'));
const skillFile = `${input.discovered.skills[0]}/SKILL.md`;
const result = await assembleApprovedPiProjectResources(input, workingDir, {
+ ...available,
stat: async (candidate) => {
if (candidate === skillFile) throw new Error('ENOENT');
return available.stat(candidate);
},
- realpath: available.realpath,
});
expect(result.skillPaths).toEqual([]);
@@ -269,7 +270,7 @@ describe('Pi approved project resource assembly', () => {
const workingDir = '/repo-a/packages/app-link';
const input = inputFor(workingDir, approved(workingDir, 'rev-a'));
const result = await assembleApprovedPiProjectResources(input, workingDir, {
- stat: available.stat,
+ ...available,
realpath: async (candidate) => candidate === input.identity.workingDir
? '/outside/retargeted-working-dir'
: candidate,
@@ -298,6 +299,23 @@ describe('Pi approved project resource assembly', () => {
});
});
+ it('rejects an approval snapshot when a nearer Git root appears before launch', async () => {
+ const workingDir = '/repo-a/packages/app';
+ const input = inputFor(workingDir, approved(workingDir, 'rev-a'));
+ const result = await assembleApprovedPiProjectResources(input, workingDir, {
+ ...available,
+ findNearestGitRoot: async () => workingDir,
+ });
+
+ expect(result.skillPaths).toEqual([]);
+ expect(result.diagnostic).toMatchObject({
+ status: 'approved',
+ reason: 'approved-repo-root-changed',
+ approvalRevision: 'rev-a',
+ requestedSkillCount: 0,
+ });
+ });
+
it('reports loaded only when this get_commands catalog confirms every explicit path', async () => {
const workingDir = '/repo-a/packages/app';
const assembly = await assembleApprovedPiProjectResources(
diff --git a/packages/maker-core/src/agents/pi/project-resource-assembly.ts b/packages/maker-core/src/agents/pi/project-resource-assembly.ts
index 627697682e..330d7e83f9 100644
--- a/packages/maker-core/src/agents/pi/project-resource-assembly.ts
+++ b/packages/maker-core/src/agents/pi/project-resource-assembly.ts
@@ -30,6 +30,8 @@ export interface PiProjectResourceAssemblySnapshot {
readonly diagnostic: PiProjectResourceAssemblyDiagnostic;
}
+type PiPathStat = { isDirectory(): boolean; isFile(): boolean };
+
const unavailableDiagnostic = (
reason: string,
): PiProjectResourceAssemblyDiagnostic => Object.freeze({
@@ -49,23 +51,53 @@ export function unavailablePiProjectResourceAssembly(
});
}
+async function findNearestGitRoot(
+ start: string,
+ stat: (path: string) => Promise<PiPathStat>,
+ pathApi: typeof path.posix | typeof path.win32,
+): Promise<string | null> {
+ let current = start;
+ while (true) {
+ try {
+ const marker = await stat(pathApi.join(current, '.git'));
+ if (marker.isDirectory() || marker.isFile()) return current;
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code;
+ // Match project discovery: an unreadable marker is a conservative
+ // boundary, while a genuinely absent marker permits walking upward.
+ if (code !== 'ENOENT' && code !== 'ENOTDIR') return current;
+ }
+ const parent = pathApi.dirname(current);
+ if (parent === current) return null;
+ current = parent;
+ }
+}
+
async function validateSkillPathsImmediatelyBeforeLaunch(
skillPaths: readonly string[],
- stat: (path: string) => Promise<{ isDirectory(): boolean; isFile(): boolean }>,
+ stat: (path: string) => Promise<PiPathStat>,
realpath: (path: string) => Promise<string>,
identity: PiProjectTrustInputSnapshot['identity'],
requestedWorkingDir: string,
-): Promise<'available' | 'unavailable' | 'request-mismatch' | 'project-changed' | 'skill-changed'> {
+ resolveNearestGitRoot: (
+ workingDir: string,
+ stat: (path: string) => Promise<PiPathStat>,
+ pathApi: typeof path.posix | typeof path.win32,
+ ) => Promise<string | null>,
+): Promise<
+ 'available' | 'unavailable' | 'request-mismatch' | 'repo-mismatch' | 'project-changed' | 'skill-changed'
+> {
try {
const canonicalWorkingDir = identity.canonicalWorkingDir;
const canonicalRepoRoot = identity.canonicalRepoRoot;
if (!canonicalWorkingDir || !canonicalRepoRoot) return 'unavailable';
const pathApi = identity.platform === 'win32' ? path.win32 : path.posix;
- const [resolvedWorkingDir, resolvedRequestedWorkingDir, resolvedRepoRoot, entries] =
+ const resolvedRequestedWorkingDir = await realpath(requestedWorkingDir);
+ const [resolvedWorkingDir, resolvedRepoRoot, currentRepoRoot, entries] =
await Promise.all([
realpath(identity.workingDir),
- realpath(requestedWorkingDir),
realpath(canonicalRepoRoot),
+ resolveNearestGitRoot(resolvedRequestedWorkingDir, stat, pathApi),
Promise.all(skillPaths.map(async (skillPath) => {
const stats = await stat(skillPath);
const resolvedPath = await realpath(skillPath);
@@ -87,6 +119,10 @@ async function validateSkillPathsImmediatelyBeforeLaunch(
if (!piCanonicalPathsEqual(identity, canonicalWorkingDir, resolvedRequestedWorkingDir)) {
return 'request-mismatch';
}
+ if (
+ !currentRepoRoot
+ || !piCanonicalPathsEqual(identity, canonicalRepoRoot, currentRepoRoot)
+ ) return 'repo-mismatch';
if (entries.some(({ skillPath, stats, skillFileStats }) =>
(!stats.isDirectory() && (!stats.isFile() || pathApi.extname(skillPath) !== '.md'))
|| (stats.isDirectory() && !skillFileStats?.isFile()))) return 'unavailable';
@@ -114,8 +150,13 @@ export async function assembleApprovedPiProjectResources(
input: PiProjectTrustInputSnapshot | null,
requestedWorkingDir: string,
options: {
- stat?: (path: string) => Promise<{ isDirectory(): boolean; isFile(): boolean }>;
+ stat?: (path: string) => Promise<PiPathStat>;
realpath?: (path: string) => Promise<string>;
+ findNearestGitRoot?: (
+ workingDir: string,
+ stat: (path: string) => Promise<PiPathStat>,
+ pathApi: typeof path.posix | typeof path.win32,
+ ) => Promise<string | null>;
} = {},
): Promise<PiProjectResourceAssemblySnapshot> {
if (!input) return unavailablePiProjectResourceAssembly('approval-snapshot-unavailable');
@@ -143,9 +184,11 @@ export async function assembleApprovedPiProjectResources(
options.realpath ?? fs.realpath,
input.identity,
requestedWorkingDir,
+ options.findNearestGitRoot ?? findNearestGitRoot,
);
if (pathStatus !== 'available') {
if (pathStatus === 'request-mismatch') reason = 'approval-working-dir-mismatch';
+ else if (pathStatus === 'repo-mismatch') reason = 'approved-repo-root-changed';
else if (pathStatus === 'project-changed') reason = 'approved-project-path-changed';
else if (pathStatus === 'skill-changed') reason = 'approved-skill-path-changed';
else reason = 'approved-skill-path-unavailable';