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): bind palette state to full skill snapshot

nana5ee51715d5ac
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 c760438285..5d34e643c5 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
@@ -476,7 +476,9 @@ describe('Pi approved project resource assembly', () => {
vi.spyOn(fsPromises, 'open').mockImplementation(async (candidate, flags, mode) => {
if (String(candidate) === skillFile) {
sourceSkillOpenCount += 1;
- if (sourceSkillOpenCount === 2) {
+ // Two opens establish the pre-copy fingerprint; the copy itself is
+ // the third. Swap on the first post-copy source fingerprint open.
+ if (sourceSkillOpenCount === 4) {
renameSync(skillPath, oldSkillPath);
mkdirSync(skillPath);
writeFileSync(skillFile, '# unchanged entrypoint\n');
@@ -528,6 +530,49 @@ describe('Pi approved project resource assembly', () => {
}
});
+ it('changes the source-state fingerprint when only a nested asset is rewritten in place', async () => {
+ const root = realpathSync.native(mkdtempSync(path.join(tmpdir(), 'pi-project-resource-asset-')));
+ const workingDir = path.join(root, 'repo');
+ const skillPath = path.join(workingDir, '.pi', 'skills', 'demo');
+ const assetPath = path.join(skillPath, 'assets', 'fixture.txt');
+ try {
+ mkdirSync(path.join(workingDir, '.git'), { recursive: true });
+ mkdirSync(path.dirname(assetPath), { recursive: true });
+ writeFileSync(path.join(skillPath, 'SKILL.md'), '# unchanged entrypoint\n');
+ writeFileSync(assetPath, 'asset-one\n');
+ const before = await fingerprintPiProjectSkillEntrypoint(skillPath, workingDir);
+
+ writeFileSync(assetPath, 'asset-two\n');
+ const after = await fingerprintPiProjectSkillEntrypoint(skillPath, workingDir);
+
+ expect(before?.contentDigest).toBe(after?.contentDigest);
+ expect(before?.sourceStateDigest).not.toBe(after?.sourceStateDigest);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+
+ it('fails closed when a palette fingerprint exhausts its shared entry budget', async () => {
+ const root = realpathSync.native(mkdtempSync(path.join(tmpdir(), 'pi-project-resource-budget-')));
+ const workingDir = path.join(root, 'repo');
+ const skillPath = path.join(workingDir, '.pi', 'skills', 'demo');
+ try {
+ mkdirSync(path.join(workingDir, '.git'), { recursive: true });
+ mkdirSync(path.join(skillPath, 'assets'), { recursive: true });
+ writeFileSync(path.join(skillPath, 'SKILL.md'), '# approved\n');
+ writeFileSync(path.join(skillPath, 'assets', 'fixture.txt'), 'asset\n');
+
+ await expect(fingerprintPiProjectSkillEntrypoint(skillPath, workingDir, {
+ budget: { remainingEntries: 1, deadlineAtMs: Number.POSITIVE_INFINITY },
+ })).resolves.toBeNull();
+ await expect(fingerprintPiProjectSkillEntrypoint(skillPath, workingDir, {
+ budget: { remainingEntries: 10, deadlineAtMs: Date.now() - 1 },
+ })).resolves.toBeNull();
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+
it('fails the entire snapshot closed when a nested symlink escapes the approved repo', async () => {
const root = realpathSync.native(mkdtempSync(path.join(tmpdir(), 'pi-project-resource-escape-')));
const configHome = path.join(root, 'config-home');
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 3cdd0e026c..7d0999e3db 100644
--- a/packages/maker-core/src/agents/pi/project-resource-assembly.ts
+++ b/packages/maker-core/src/agents/pi/project-resource-assembly.ts
@@ -3,6 +3,7 @@ import { constants, createWriteStream } from 'node:fs';
import path from 'node:path';
import { pipeline } from 'node:stream/promises';
import { createHash } from 'node:crypto';
+import { clearTimeout as clearNodeTimeout, setTimeout as setNodeTimeout } from 'node:timers';
import type { FileHandle } from 'node:fs/promises';
import type {
@@ -36,7 +37,7 @@ export interface PiProjectResourceAssemblySnapshot {
readonly launchSkillPaths: readonly string[];
/** Content fingerprints for the immutable launch copies, index-aligned with skillPaths. */
readonly launchSkillDigests: readonly string[];
- /** Launch-time source identities used to detect stale palette entries without hashing assets. */
+ /** Launch-time source-tree identities used to detect stale palette entries without hashing assets. */
readonly launchSkillSourceFingerprints: readonly string[];
readonly diagnostic: PiProjectResourceAssemblyDiagnostic;
}
@@ -247,10 +248,31 @@ function sameEntrySnapshot(
&& first.ctimeMs === second.ctimeMs;
}
-async function hashOpenFile(handle: FileHandle): Promise<string> {
+async function hashOpenFile(handle: FileHandle, deadlineAtMs = Number.POSITIVE_INFINITY): Promise<string> {
+ if (Date.now() >= deadlineAtMs) throw new Error('approved skill fingerprint deadline expired');
const hash = createHash('sha256');
- for await (const chunk of handle.createReadStream({ start: 0, autoClose: false })) {
- hash.update(chunk);
+ const controller = new AbortController();
+ let timeout: number | NodeJS.Timeout | undefined;
+ if (Number.isFinite(deadlineAtMs)) {
+ timeout = setNodeTimeout(
+ () => controller.abort(),
+ Math.max(0, deadlineAtMs - Date.now()),
+ );
+ }
+ try {
+ for await (const chunk of handle.createReadStream({
+ start: 0,
+ autoClose: false,
+ signal: controller.signal,
+ })) {
+ if (Date.now() >= deadlineAtMs) {
+ controller.abort();
+ throw new Error('approved skill fingerprint deadline expired');
+ }
+ hash.update(chunk);
+ }
+ } finally {
+ if (timeout) clearNodeTimeout(timeout);
}
return hash.digest('hex');
}
@@ -260,10 +282,16 @@ export interface PiProjectSkillEntrypointFingerprint {
readonly sourceStateDigest: string;
}
+export interface PiProjectSkillFingerprintBudget {
+ remainingEntries: number;
+ readonly deadlineAtMs: number;
+}
+
async function fingerprintSkillEntrypointOnce(
rootPath: string,
canonicalRepoRoot: string,
-): Promise<PiProjectSkillEntrypointFingerprint> {
+ sharedBudget?: PiProjectSkillFingerprintBudget,
+): Promise<string> {
const skillPath = path.join(rootPath, 'SKILL.md');
const [rootEntry, canonicalRoot, skillLinkEntry, canonicalSkill, skillTargetEntry] =
await Promise.all([
@@ -287,11 +315,14 @@ async function fingerprintSkillEntrypointOnce(
constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0),
);
try {
+ if (sharedBudget && Date.now() >= sharedBudget.deadlineAtMs) {
+ throw new Error('approved skill fingerprint deadline expired');
+ }
const openedEntry = await handle.stat();
if (!openedEntry.isFile() || !sameFileIdentity(skillTargetEntry, openedEntry)) {
throw new Error('approved skill entrypoint changed before fingerprinting');
}
- const contentDigest = await hashOpenFile(handle);
+ const contentDigest = await hashOpenFile(handle, sharedBudget?.deadlineAtMs);
const [
rootEntryAfterRead,
canonicalRootAfterRead,
@@ -318,55 +349,168 @@ async function fingerprintSkillEntrypointOnce(
) {
throw new Error('approved skill entrypoint changed while fingerprinting');
}
- const sourceState = createHash('sha256');
- for (const value of [
- canonicalRoot,
- rootEntry.dev,
- rootEntry.ino,
- rootEntry.size,
- rootEntry.mtimeMs,
- rootEntry.ctimeMs,
- canonicalSkill,
- skillLinkEntry.dev,
- skillLinkEntry.ino,
- skillLinkEntry.size,
- skillLinkEntry.mtimeMs,
- skillLinkEntry.ctimeMs,
- openedEntry.dev,
- openedEntry.ino,
- openedEntry.size,
- openedEntry.mtimeMs,
- openedEntry.ctimeMs,
- contentDigest,
- ]) {
- sourceState.update(String(value));
- sourceState.update('\0');
- }
- return Object.freeze({
- contentDigest,
- sourceStateDigest: sourceState.digest('hex'),
- });
+ return contentDigest;
} finally {
await handle.close();
}
}
+const MAX_PI_PROJECT_SKILL_FINGERPRINT_ENTRIES = 10_000;
+
+function updateFingerprintValue(hash: ReturnType<typeof createHash>, value: unknown): void {
+ hash.update(String(value));
+ hash.update('\0');
+}
+
+async function fingerprintSkillTreeStateOnce(
+ rootPath: string,
+ canonicalRepoRoot: string,
+ sharedBudget?: PiProjectSkillFingerprintBudget,
+): Promise<string> {
+ const hash = createHash('sha256');
+ const activeDirectories = new Set<string>();
+ let entryCount = 0;
+
+ const visit = async (entryPath: string, relativePath: string): Promise<void> => {
+ if (sharedBudget) {
+ if (Date.now() >= sharedBudget.deadlineAtMs || sharedBudget.remainingEntries <= 0) {
+ throw new Error('approved skill tree exceeded the shared fingerprint budget');
+ }
+ sharedBudget.remainingEntries -= 1;
+ }
+ entryCount += 1;
+ if (entryCount > MAX_PI_PROJECT_SKILL_FINGERPRINT_ENTRIES) {
+ throw new Error('approved skill tree exceeds the fingerprint entry budget');
+ }
+ const [linkEntry, canonicalEntry, targetEntry] = await Promise.all([
+ fs.lstat(entryPath),
+ fs.realpath(entryPath),
+ fs.stat(entryPath),
+ ]);
+ if (
+ !localPathIsWithin(canonicalRepoRoot, canonicalEntry)
+ || (!targetEntry.isDirectory() && !targetEntry.isFile())
+ ) {
+ throw new Error('approved skill tree contains an escaped or special entry');
+ }
+ const kind = targetEntry.isDirectory() ? 'directory' : 'file';
+ for (const value of [
+ relativePath,
+ linkEntry.isSymbolicLink() ? `symlink-${kind}` : kind,
+ canonicalEntry,
+ linkEntry.dev,
+ linkEntry.ino,
+ linkEntry.mode,
+ linkEntry.size,
+ linkEntry.mtimeMs,
+ linkEntry.ctimeMs,
+ targetEntry.dev,
+ targetEntry.ino,
+ targetEntry.mode,
+ targetEntry.size,
+ targetEntry.mtimeMs,
+ targetEntry.ctimeMs,
+ ]) updateFingerprintValue(hash, value);
+
+ if (targetEntry.isDirectory()) {
+ if (activeDirectories.has(canonicalEntry)) {
+ throw new Error('approved skill tree contains a directory cycle');
+ }
+ activeDirectories.add(canonicalEntry);
+ try {
+ const remainingEntryBudget = Math.min(
+ MAX_PI_PROJECT_SKILL_FINGERPRINT_ENTRIES - entryCount,
+ sharedBudget?.remainingEntries ?? Number.POSITIVE_INFINITY,
+ );
+ const childNames: string[] = [];
+ const directory = await fs.opendir(entryPath);
+ try {
+ while (true) {
+ if (sharedBudget && Date.now() >= sharedBudget.deadlineAtMs) {
+ throw new Error('approved skill tree exceeded the shared fingerprint deadline');
+ }
+ const child = await directory.read();
+ if (!child) break;
+ if (childNames.length >= remainingEntryBudget) {
+ throw new Error('approved skill tree exceeds the fingerprint entry budget');
+ }
+ childNames.push(child.name);
+ }
+ } finally {
+ await directory.close().catch(() => undefined);
+ }
+ if (sharedBudget && Date.now() >= sharedBudget.deadlineAtMs) {
+ throw new Error('approved skill tree exceeded the shared fingerprint deadline');
+ }
+ childNames.sort((left, right) => Buffer.from(left).compare(Buffer.from(right)));
+ for (const childName of childNames) {
+ await visit(
+ path.join(entryPath, childName),
+ relativePath === '.' ? childName : path.join(relativePath, childName),
+ );
+ }
+ } finally {
+ activeDirectories.delete(canonicalEntry);
+ }
+ }
+
+ const [linkEntryAfter, canonicalEntryAfter, targetEntryAfter] = await Promise.all([
+ fs.lstat(entryPath),
+ fs.realpath(entryPath),
+ fs.stat(entryPath),
+ ]);
+ if (
+ !sameEntrySnapshot(linkEntry, linkEntryAfter)
+ || !sameEntrySnapshot(targetEntry, targetEntryAfter)
+ || path.resolve(canonicalEntryAfter) !== path.resolve(canonicalEntry)
+ ) {
+ throw new Error('approved skill tree changed while fingerprinting');
+ }
+ };
+
+ await visit(rootPath, '.');
+ return hash.digest('hex');
+}
+
/** Fail-closed SKILL.md identity used when projecting a live session into the palette. */
export async function fingerprintPiProjectSkillEntrypoint(
rootPath: string,
canonicalRepoRoot: string,
+ options: { budget?: PiProjectSkillFingerprintBudget } = {},
): Promise<PiProjectSkillEntrypointFingerprint | null> {
try {
+ if (options.budget && Date.now() >= options.budget.deadlineAtMs) return null;
const [canonicalRoot, canonicalBoundary] = await Promise.all([
fs.realpath(rootPath),
fs.realpath(canonicalRepoRoot),
]);
if (!localPathIsWithin(canonicalBoundary, canonicalRoot)) return null;
- const first = await fingerprintSkillEntrypointOnce(rootPath, canonicalBoundary);
- const second = await fingerprintSkillEntrypointOnce(rootPath, canonicalBoundary);
- return first.contentDigest === second.contentDigest
- && first.sourceStateDigest === second.sourceStateDigest
- ? first
+ const firstContentDigest = await fingerprintSkillEntrypointOnce(
+ rootPath,
+ canonicalBoundary,
+ options.budget,
+ );
+ const firstSourceStateDigest = await fingerprintSkillTreeStateOnce(
+ rootPath,
+ canonicalBoundary,
+ options.budget,
+ );
+ const secondContentDigest = await fingerprintSkillEntrypointOnce(
+ rootPath,
+ canonicalBoundary,
+ options.budget,
+ );
+ const secondSourceStateDigest = await fingerprintSkillTreeStateOnce(
+ rootPath,
+ canonicalBoundary,
+ options.budget,
+ );
+ return firstContentDigest === secondContentDigest
+ && firstSourceStateDigest === secondSourceStateDigest
+ ? Object.freeze({
+ contentDigest: firstContentDigest,
+ sourceStateDigest: firstSourceStateDigest,
+ })
: null;
} catch {
return null;
@@ -547,6 +691,13 @@ export async function stageApprovedPiProjectResources(
) {
throw new Error('approved skill root changed before snapshotting');
}
+ const sourceFingerprintBeforeCopy = await fingerprintPiProjectSkillEntrypoint(
+ sourcePath,
+ canonicalRepoRoot,
+ );
+ if (!sourceFingerprintBeforeCopy) {
+ throw new Error('approved skill source fingerprint failed before snapshotting');
+ }
await materializeSkillEntry(
sourcePath,
targetPath,
@@ -572,6 +723,8 @@ export async function stageApprovedPiProjectResources(
!launchFingerprint
|| !sourceFingerprint
|| launchFingerprint.contentDigest !== sourceFingerprint.contentDigest
+ || sourceFingerprintBeforeCopy.contentDigest !== sourceFingerprint.contentDigest
+ || sourceFingerprintBeforeCopy.sourceStateDigest !== sourceFingerprint.sourceStateDigest
|| !sameEntrySnapshot(sourceRootBeforeCopy, sourceRootAfterFingerprint)
|| path.resolve(canonicalSourceAfterFingerprint) !== path.resolve(canonicalSourceBeforeCopy)
) {
diff --git a/packages/maker-core/src/maker.test.ts b/packages/maker-core/src/maker.test.ts
index feb4abcb96..a2106ea307 100644
--- a/packages/maker-core/src/maker.test.ts
+++ b/packages/maker-core/src/maker.test.ts
@@ -1144,6 +1144,14 @@ describe('Maker Pi runtime skill status', () => {
});
expect(initial.skills[0]).toMatchObject({ runtimeStatus: 'loaded' });
+ writeFileSync(path.join(sourcePath, 'assets', 'fixture.txt'), 'changed! asset\n');
+ const changedAsset = await maker.listAgentSkills('pi', {
+ workingDir: repoRoot,
+ sessionId: 'source-snapshot',
+ });
+ expect(changedAsset.skills[0]).toMatchObject({ runtimeStatus: 'discovered' });
+ expect(changedAsset.errors).toContainEqual(expect.objectContaining({ path: sourcePath }));
+
writeFileSync(path.join(sourcePath, 'SKILL.md'), '# changed in place\n');
const changedFile = await maker.listAgentSkills('pi', {
workingDir: repoRoot,
diff --git a/packages/maker-core/src/maker.ts b/packages/maker-core/src/maker.ts
index c8ed84c1ad..de4388e1b9 100644
--- a/packages/maker-core/src/maker.ts
+++ b/packages/maker-core/src/maker.ts
@@ -18,6 +18,7 @@
import { DEFAULT_DRAFT_SESSION_TITLE } from '@cindy/maker-shared/session-title';
import fs from 'node:fs';
import path from 'node:path';
+import { clearTimeout as clearNodeTimeout, setTimeout as setNodeTimeout } from 'node:timers';
import type { AgentKind } from './types/common.js';
import type { Capabilities } from './types/capabilities.js';
@@ -161,6 +162,29 @@ function canonicalPiRuntimePath(value: string): string {
}
}
+const PI_PROJECT_SKILL_PALETTE_FINGERPRINT_TIMEOUT_MS = 250;
+const PI_PROJECT_SKILL_PALETTE_FINGERPRINT_ENTRY_BUDGET = 2_048;
+
+async function fingerprintPiProjectSkillForPalette(
+ sourcePath: string,
+ canonicalRepoRoot: string,
+ budget: { remainingEntries: number; deadlineAtMs: number },
+): ReturnType<typeof fingerprintPiProjectSkillEntrypoint> {
+ const remainingMs = budget.deadlineAtMs - Date.now();
+ if (remainingMs <= 0) return null;
+ let timeout: number | NodeJS.Timeout | undefined;
+ try {
+ return await Promise.race([
+ fingerprintPiProjectSkillEntrypoint(sourcePath, canonicalRepoRoot, { budget }),
+ new Promise<null>((resolve) => {
+ timeout = setNodeTimeout(() => resolve(null), remainingMs);
+ }),
+ ]);
+ } finally {
+ if (timeout) clearNodeTimeout(timeout);
+ }
+}
+
async function mergePiRuntimeSkillStatuses(
result: ListAgentSkillsResult,
manifest: PiRuntimeCapabilityManifest | undefined,
@@ -169,15 +193,20 @@ async function mergePiRuntimeSkillStatuses(
const loadedExplicitSkills = new Map<string, string>();
const loadedLegacyProjectSkills = new Map<string, string>();
const changedProjectSkills = new Map<string, string>();
+ const fingerprintBudget = {
+ remainingEntries: PI_PROJECT_SKILL_PALETTE_FINGERPRINT_ENTRY_BUDGET,
+ deadlineAtMs: Date.now() + PI_PROJECT_SKILL_PALETTE_FINGERPRINT_TIMEOUT_MS,
+ };
for (const skill of manifest.projectResources?.loadedSkills ?? []) {
const canonicalSourcePath = canonicalPiRuntimePath(skill.sourcePath);
if (!skill.snapshotDigest || !skill.sourceFingerprint || !skill.canonicalRepoRoot) {
changedProjectSkills.set(canonicalSourcePath, skill.sourcePath);
continue;
}
- const currentFingerprint = await fingerprintPiProjectSkillEntrypoint(
+ const currentFingerprint = await fingerprintPiProjectSkillForPalette(
skill.sourcePath,
skill.canonicalRepoRoot,
+ fingerprintBudget,
);
if (
currentFingerprint?.contentDigest !== skill.snapshotDigest
diff --git a/packages/maker-core/src/types/pi-runtime-capabilities.ts b/packages/maker-core/src/types/pi-runtime-capabilities.ts
index 87ec72ab54..40b8d1620d 100644
--- a/packages/maker-core/src/types/pi-runtime-capabilities.ts
+++ b/packages/maker-core/src/types/pi-runtime-capabilities.ts
@@ -60,7 +60,7 @@ export interface PiProjectResourceRuntimeDiagnostic {
commandName: string;
/** Present for PR4 immutable project snapshots; absent only on older manifests. */
snapshotDigest?: string;
- /** Launch-time source identity; current sessions require it before reporting loaded. */
+ /** Launch-time source-tree identity; current sessions require it before reporting loaded. */
sourceFingerprint?: string;
/** Approval-time boundary used to fingerprint the current source fail closed. */
canonicalRepoRoot?: string;