Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): invalidate stale project skill palette state
nana78d62ab8fabd
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.tsindex f0359ffd3e..c760438285 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@@ -17,6 +17,7 @@ import path from 'node:path';import {assembleApprovedPiProjectResources,+ fingerprintPiProjectSkillEntrypoint,reconcilePiProjectResourceRuntime,stageApprovedPiProjectResources,unavailablePiProjectResourceAssembly,@@ -162,6 +163,8 @@ describe('Pi approved project resource assembly', () => {decision: null,skillPaths: [],launchSkillPaths: [],+ launchSkillDigests: [],+ launchSkillSourceFingerprints: [],diagnostic: {status: 'unavailable',reason: 'approval-resolver-unavailable',@@ -307,6 +310,8 @@ describe('Pi approved project resource assembly', () => {expect(staged.skillPaths).toEqual([skillPath]);expect(staged.launchSkillPaths).toHaveLength(1);+ expect(staged.launchSkillDigests).toHaveLength(1);+ expect(staged.launchSkillSourceFingerprints).toHaveLength(1);expect(staged.launchSkillPaths[0]).toBe(path.join(configHome, 'project-resources', 'skills', '0', 'demo'),);@@ -314,6 +319,11 @@ describe('Pi approved project resource assembly', () => {.toBe('# approved snapshot\n');expect(readFileSync(path.join(staged.launchSkillPaths[0]!, 'assets', 'fixture.txt'), 'utf8')).toBe('snapshot asset\n');+ await expect(fingerprintPiProjectSkillEntrypoint(skillPath, workingDir))+ .resolves.toMatchObject({+ contentDigest: staged.launchSkillDigests[0],+ sourceStateDigest: staged.launchSkillSourceFingerprints[0],+ });const nonBlockingFlag = constants.O_NONBLOCK ?? 0;expect((openSpy.mock.calls[0]?.[1] as number) & nonBlockingFlag).toBe(nonBlockingFlag);@@ -444,6 +454,80 @@ describe('Pi approved project resource assembly', () => {}});+ it('binds the launch fingerprint to the exact source root that was copied', async () => {+ const root = realpathSync.native(mkdtempSync(path.join(tmpdir(), 'pi-project-resource-root-swap-')));+ const configHome = path.join(root, 'config-home');+ const workingDir = path.join(root, 'repo');+ const skillPath = path.join(workingDir, '.pi', 'skills', 'demo');+ const skillFile = path.join(skillPath, 'SKILL.md');+ const oldSkillPath = `${skillPath}-old`;+ try {+ mkdirSync(path.join(workingDir, '.git'), { recursive: true });+ mkdirSync(skillPath, { recursive: true });+ mkdirSync(configHome, { recursive: true });+ writeFileSync(skillFile, '# unchanged entrypoint\n');+ writeFileSync(path.join(skillPath, 'asset.txt'), 'copied asset\n');+ const assembled = await assembleApprovedPiProjectResources(+ inputForRepoRoot(workingDir, 'rev-root-swap', [skillPath]),+ workingDir,+ );+ const realOpen = fsPromises.open.bind(fsPromises);+ let sourceSkillOpenCount = 0;+ vi.spyOn(fsPromises, 'open').mockImplementation(async (candidate, flags, mode) => {+ if (String(candidate) === skillFile) {+ sourceSkillOpenCount += 1;+ if (sourceSkillOpenCount === 2) {+ renameSync(skillPath, oldSkillPath);+ mkdirSync(skillPath);+ writeFileSync(skillFile, '# unchanged entrypoint\n');+ writeFileSync(path.join(skillPath, 'asset.txt'), 'replacement asset\n');+ }+ }+ return realOpen(candidate, flags, mode);+ });++ const staged = await stageApprovedPiProjectResources(assembled, configHome);++ expect(sourceSkillOpenCount).toBeGreaterThanOrEqual(2);+ expect(staged.skillPaths).toEqual([]);+ expect(staged.launchSkillPaths).toEqual([]);+ expect(staged.diagnostic).toMatchObject({+ reason: 'approved-skill-snapshot-failed',+ requestedSkillCount: 0,+ });+ } finally {+ vi.restoreAllMocks();+ rmSync(root, { recursive: true, force: true });+ }+ });++ it('rejects a skill tree that changes between complete fingerprint passes', async () => {+ const root = realpathSync.native(mkdtempSync(path.join(tmpdir(), 'pi-project-resource-fingerprint-')));+ const workingDir = path.join(root, 'repo');+ const skillPath = path.join(workingDir, '.pi', 'skills', 'demo');+ const skillFile = path.join(skillPath, 'SKILL.md');+ try {+ mkdirSync(path.join(workingDir, '.git'), { recursive: true });+ mkdirSync(skillPath, { recursive: true });+ writeFileSync(skillFile, '# first pass\n');+ const realOpen = fsPromises.open.bind(fsPromises);+ let skillOpenCount = 0;+ vi.spyOn(fsPromises, 'open').mockImplementation(async (candidate, flags, mode) => {+ if (String(candidate) === skillFile) {+ skillOpenCount += 1;+ if (skillOpenCount === 2) writeFileSync(skillFile, '# second pass\n');+ }+ return realOpen(candidate, flags, mode);+ });++ await expect(fingerprintPiProjectSkillEntrypoint(skillPath, workingDir)).resolves.toBeNull();+ expect(skillOpenCount).toBe(2);+ } finally {+ vi.restoreAllMocks();+ 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');@@ -559,6 +643,8 @@ describe('Pi approved project resource assembly', () => {const runtimeAssembly = {...assembly,launchSkillPaths: [skillPath],+ launchSkillDigests: ['snapshot-digest'],+ launchSkillSourceFingerprints: ['source-fingerprint'],};const baseManifest = {capturedAt: '2026-08-10T00:00:00.000Z',@@ -587,6 +673,9 @@ describe('Pi approved project resource assembly', () => {sourcePath: skillPath,runtimePath: skillPath,commandName: 'skill:demo',+ snapshotDigest: 'snapshot-digest',+ sourceFingerprint: 'source-fingerprint',+ canonicalRepoRoot: assembly.decision?.canonicalRepoRoot,}],});diff --git a/packages/maker-core/src/agents/pi/project-resource-assembly.ts b/packages/maker-core/src/agents/pi/project-resource-assembly.tsindex 7a0c7b5afc..3cdd0e026c 100644--- a/packages/maker-core/src/agents/pi/project-resource-assembly.ts+++ b/packages/maker-core/src/agents/pi/project-resource-assembly.ts@@ -34,6 +34,10 @@ export interface PiProjectResourceAssemblySnapshot {readonly skillPaths: readonly string[];/** Per-session immutable copies that are safe to pass to Pi. */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. */+ readonly launchSkillSourceFingerprints: readonly string[];readonly diagnostic: PiProjectResourceAssemblyDiagnostic;}@@ -55,6 +59,8 @@ export function unavailablePiProjectResourceAssembly(decision: null,skillPaths: Object.freeze([]),launchSkillPaths: Object.freeze([]),+ launchSkillDigests: Object.freeze([]),+ launchSkillSourceFingerprints: Object.freeze([]),diagnostic: unavailableDiagnostic(reason),});}@@ -208,6 +214,8 @@ export async function assembleApprovedPiProjectResources(decision,skillPaths: frozenSkillPaths,launchSkillPaths: Object.freeze([]),+ launchSkillDigests: Object.freeze([]),+ launchSkillSourceFingerprints: Object.freeze([]),diagnostic: Object.freeze({status: decision.status,reason,@@ -247,6 +255,124 @@ async function hashOpenFile(handle: FileHandle): Promise<string> {return hash.digest('hex');}+export interface PiProjectSkillEntrypointFingerprint {+ readonly contentDigest: string;+ readonly sourceStateDigest: string;+}++async function fingerprintSkillEntrypointOnce(+ rootPath: string,+ canonicalRepoRoot: string,+): Promise<PiProjectSkillEntrypointFingerprint> {+ const skillPath = path.join(rootPath, 'SKILL.md');+ const [rootEntry, canonicalRoot, skillLinkEntry, canonicalSkill, skillTargetEntry] =+ await Promise.all([+ fs.lstat(rootPath),+ fs.realpath(rootPath),+ fs.lstat(skillPath),+ fs.realpath(skillPath),+ fs.stat(skillPath),+ ]);+ if (+ !rootEntry.isDirectory()+ || !skillTargetEntry.isFile()+ || !localPathIsWithin(canonicalRepoRoot, canonicalRoot)+ || !localPathIsWithin(canonicalRepoRoot, canonicalSkill)+ ) {+ throw new Error('approved skill entrypoint escaped its repository');+ }++ const handle = await fs.open(+ canonicalSkill,+ constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0),+ );+ try {+ 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 [+ rootEntryAfterRead,+ canonicalRootAfterRead,+ skillLinkEntryAfterRead,+ canonicalSkillAfterRead,+ skillTargetEntryAfterRead,+ openedAfterRead,+ ] = await Promise.all([+ fs.lstat(rootPath),+ fs.realpath(rootPath),+ fs.lstat(skillPath),+ fs.realpath(skillPath),+ fs.stat(skillPath),+ handle.stat(),+ ]);+ if (+ !sameEntrySnapshot(rootEntry, rootEntryAfterRead)+ || !sameEntrySnapshot(skillLinkEntry, skillLinkEntryAfterRead)+ || !sameEntrySnapshot(skillTargetEntry, skillTargetEntryAfterRead)+ || !sameEntrySnapshot(openedEntry, openedAfterRead)+ || !sameFileIdentity(openedEntry, skillTargetEntryAfterRead)+ || path.relative(canonicalRootAfterRead, canonicalRoot) !== ''+ || path.relative(canonicalSkillAfterRead, canonicalSkill) !== ''+ ) {+ 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'),+ });+ } finally {+ await handle.close();+ }+}++/** Fail-closed SKILL.md identity used when projecting a live session into the palette. */+export async function fingerprintPiProjectSkillEntrypoint(+ rootPath: string,+ canonicalRepoRoot: string,+): Promise<PiProjectSkillEntrypointFingerprint | null> {+ try {+ 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+ : null;+ } catch {+ return null;+ }+}+async function materializeSkillEntry(sourcePath: string,targetPath: string,@@ -387,6 +513,8 @@ export async function stageApprovedPiProjectResources(...assembly,skillPaths: Object.freeze([]),launchSkillPaths: Object.freeze([]),+ launchSkillDigests: Object.freeze([]),+ launchSkillSourceFingerprints: Object.freeze([]),diagnostic: Object.freeze({...assembly.diagnostic,reason: 'approved-skill-snapshot-failed',@@ -401,11 +529,24 @@ export async function stageApprovedPiProjectResources(const temporarySkillsRoot = path.join(temporaryRoot, 'skills');await fs.mkdir(temporarySkillsRoot);const relativeLaunchPaths: string[] = [];+ const launchSkillDigests: string[] = [];+ const launchSkillSourceFingerprints: string[] = [];for (const [index, sourcePath] of assembly.skillPaths.entries()) {const skillName = path.basename(sourcePath);const relativePath = path.join('skills', String(index), skillName);const targetPath = path.join(temporaryRoot, relativePath);await fs.mkdir(path.dirname(targetPath), { recursive: true });+ const [sourceRootBeforeCopy, canonicalSourceBeforeCopy] = await Promise.all([+ fs.lstat(sourcePath),+ fs.realpath(sourcePath),+ ]);+ if (+ !sourceRootBeforeCopy.isDirectory()+ || path.resolve(canonicalSourceBeforeCopy) !== path.resolve(sourcePath)+ || !localPathIsWithin(canonicalRepoRoot, canonicalSourceBeforeCopy)+ ) {+ throw new Error('approved skill root changed before snapshotting');+ }await materializeSkillEntry(sourcePath,targetPath,@@ -419,7 +560,26 @@ export async function stageApprovedPiProjectResources(if (path.resolve(canonicalSourceAfterCopy) !== path.resolve(sourcePath) || !skillEntrypoint.isFile()) {throw new Error('approved skill changed before snapshot publication');}+ const [launchFingerprint, sourceFingerprint] = await Promise.all([+ fingerprintPiProjectSkillEntrypoint(targetPath, targetPath),+ fingerprintPiProjectSkillEntrypoint(sourcePath, canonicalRepoRoot),+ ]);+ const [sourceRootAfterFingerprint, canonicalSourceAfterFingerprint] = await Promise.all([+ fs.lstat(sourcePath),+ fs.realpath(sourcePath),+ ]);+ if (+ !launchFingerprint+ || !sourceFingerprint+ || launchFingerprint.contentDigest !== sourceFingerprint.contentDigest+ || !sameEntrySnapshot(sourceRootBeforeCopy, sourceRootAfterFingerprint)+ || path.resolve(canonicalSourceAfterFingerprint) !== path.resolve(canonicalSourceBeforeCopy)+ ) {+ throw new Error('approved skill snapshot fingerprint failed');+ }relativeLaunchPaths.push(relativePath);+ launchSkillDigests.push(launchFingerprint.contentDigest);+ launchSkillSourceFingerprints.push(sourceFingerprint.sourceStateDigest);}await assertMaterializedTreeContainsNoLinksOrSpecialFiles(temporarySkillsRoot);@@ -431,6 +591,8 @@ export async function stageApprovedPiProjectResources(return Object.freeze({...assembly,launchSkillPaths,+ launchSkillDigests: Object.freeze(launchSkillDigests),+ launchSkillSourceFingerprints: Object.freeze(launchSkillSourceFingerprints),diagnostic: Object.freeze({...assembly.diagnostic,requestedSkillCount: launchSkillPaths.length,@@ -444,6 +606,8 @@ export async function stageApprovedPiProjectResources(...assembly,skillPaths: Object.freeze([]),launchSkillPaths: Object.freeze([]),+ launchSkillDigests: Object.freeze([]),+ launchSkillSourceFingerprints: Object.freeze([]),diagnostic: Object.freeze({...assembly.diagnostic,reason: 'approved-skill-snapshot-failed',@@ -483,7 +647,19 @@ export function reconcilePiProjectResourceRuntime(const loadedSkills = assembly.launchSkillPaths.flatMap((runtimePath, index) => {const commandName = loadedPaths.get(comparableRuntimePath(runtimePath));const sourcePath = assembly.skillPaths[index];- return commandName && sourcePath ? [{ sourcePath, runtimePath, commandName }] : [];+ const snapshotDigest = assembly.launchSkillDigests[index];+ const sourceFingerprint = assembly.launchSkillSourceFingerprints[index];+ const canonicalRepoRoot = assembly.decision?.canonicalRepoRoot;+ return commandName && sourcePath && snapshotDigest && sourceFingerprint && canonicalRepoRoot+ ? [{+ sourcePath,+ runtimePath,+ commandName,+ snapshotDigest,+ sourceFingerprint,+ canonicalRepoRoot,+ }]+ : [];});const loadedSkillCount = [...expectedPaths].filter((skillPath) => loadedPaths.has(skillPath)).length;return Object.freeze({diff --git a/packages/maker-core/src/maker.test.ts b/packages/maker-core/src/maker.test.tsindex ff9e66e970..feb4abcb96 100644--- a/packages/maker-core/src/maker.test.ts+++ b/packages/maker-core/src/maker.test.ts@@ -1,4 +1,12 @@import { describe, expect, it, vi } from 'vitest';+import {+ mkdirSync,+ mkdtempSync,+ realpathSync,+ rmSync,+ writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';import path from 'node:path';import { Maker, type CreateSessionOptions } from './maker.js';@@ -12,6 +20,7 @@ import {import type { SessionMeta, SessionStorage } from './interfaces/session-storage.js';import type { AgentKind, PermissionMode } from './types/common.js';import type { AgentEvent } from './types/events.js';+import { fingerprintPiProjectSkillEntrypoint } from './agents/pi/project-resource-assembly.js';/** A generator that never completes — simulates a live session handle. */async function* neverEndingIterator(): AsyncGenerator<AgentEvent> {@@ -913,7 +922,7 @@ describe('Maker session capabilities', () => {});describe('Maker Pi runtime skill status', () => {- it('marks only project skills confirmed by the matching live session as loaded', async () => {+ it('fails partial project mappings closed without leaking them across live sessions', async () => {const agent = createAgent(async (opts) => {const handle = createHandle({ id: `pi-${opts.sessionId}`, agentKind: 'pi' });handle.getRuntimeCapabilities = () => ({@@ -1019,7 +1028,7 @@ describe('Maker Pi runtime skill status', () => {});expect(one.skills.map((skill) => [skill.name, skill.runtimeStatus])).toEqual([- ['one-skill', 'loaded'],+ ['one-skill', 'discovered'],['one-skill', 'discovered'],['two-skill', 'discovered'],['single-file', 'loaded'],@@ -1028,8 +1037,7 @@ describe('Maker Pi runtime skill status', () => {]);expect(one.skills[0]).toMatchObject({name: 'one-skill',- runtimeStatus: 'loaded',- runtimeCommandName: 'skill:one-frontmatter-name',+ runtimeStatus: 'discovered',});expect(one.skills[3]).toMatchObject({name: 'single-file',@@ -1039,14 +1047,123 @@ describe('Maker Pi runtime skill status', () => {expect(two.skills.map((skill) => [skill.name, skill.runtimeStatus])).toEqual([['one-skill', 'discovered'],['one-skill', 'discovered'],- ['two-skill', 'loaded'],+ ['two-skill', 'discovered'],['single-file', 'loaded'],['user-collision', 'discovered'],['malformed-collision', 'discovered'],]);+ expect(one.errors).toContainEqual(expect.objectContaining({+ path: '/repo/.pi/skills/one-skill',+ }));+ expect(two.errors).toContainEqual(expect.objectContaining({+ path: '/repo/.pi/skills/two-skill',+ }));expect(preview.skills.every((skill) => skill.runtimeStatus === 'discovered')).toBe(true);expect(wrongProject.skills.every((skill) => skill.runtimeStatus === 'discovered')).toBe(true);});++ it('keeps a project skill discovered when its source no longer matches the launch snapshot', async () => {+ const root = realpathSync.native(mkdtempSync(path.join(tmpdir(), 'maker-pi-skill-source-')));+ const repoRoot = path.join(root, 'repo');+ const sourcePath = path.join(repoRoot, '.pi', 'skills', 'demo');+ const runtimePath = path.join(root, 'config-home', 'project-resources', 'skills', '0', 'demo');+ const writeSkill = (skillRoot: string, skillContent: string, assetContent: string): void => {+ mkdirSync(path.join(skillRoot, 'assets'), { recursive: true });+ writeFileSync(path.join(skillRoot, 'SKILL.md'), skillContent);+ writeFileSync(path.join(skillRoot, 'assets', 'fixture.txt'), assetContent);+ };+ try {+ writeSkill(sourcePath, '# approved\n', 'approved asset\n');+ writeSkill(runtimePath, '# approved\n', 'approved asset\n');+ const snapshotFingerprint = await fingerprintPiProjectSkillEntrypoint(runtimePath, runtimePath);+ const sourceFingerprint = await fingerprintPiProjectSkillEntrypoint(sourcePath, repoRoot);+ expect(snapshotFingerprint?.contentDigest).toMatch(/^[a-f0-9]{64}$/);+ expect(sourceFingerprint?.sourceStateDigest).toMatch(/^[a-f0-9]{64}$/);++ const agent = createAgent(async (opts) => {+ const handle = createHandle({ id: `pi-${opts.sessionId}`, agentKind: 'pi' });+ handle.getRuntimeCapabilities = () => ({+ sessionId: opts.sessionId,+ capturedAt: '2026-08-11T00:00:00.000Z',+ generation: 1,+ status: 'loaded',+ source: 'pi:get_commands',+ projectResources: {+ status: 'approved',+ reason: 'runtime-skills-confirmed',+ approvalRevision: 'rev-source-snapshot',+ requestedSkillCount: 1,+ loadedSkillCount: 1,+ loadedSkills: [{+ sourcePath,+ runtimePath,+ commandName: 'skill:demo',+ snapshotDigest: snapshotFingerprint!.contentDigest,+ sourceFingerprint: sourceFingerprint!.sourceStateDigest,+ canonicalRepoRoot: repoRoot,+ }],+ },+ commands: [{+ name: 'skill:demo',+ source: 'skill',+ sourceInfo: {+ source: 'local',+ scope: 'temporary',+ baseDir: runtimePath,+ path: path.join(runtimePath, 'SKILL.md'),+ },+ }],+ });+ return handle;+ }, 'pi');+ agent.listAgentSkills = vi.fn(async () => ({+ skills: [{+ kind: 'agent-skill' as const,+ name: 'demo',+ source: 'skill' as const,+ scope: 'repo' as const,+ path: sourcePath,+ runtimeStatus: 'discovered' as const,+ }],+ }));+ const maker = new Maker({+ agents: { pi: agent },+ storage: createStorage(),+ logger: createLogger(),+ });+ await maker.createSession({+ id: 'source-snapshot',+ agentKind: 'pi',+ workingDir: repoRoot,+ model: 'm',+ });++ const initial = await maker.listAgentSkills('pi', {+ workingDir: repoRoot,+ sessionId: 'source-snapshot',+ });+ expect(initial.skills[0]).toMatchObject({ runtimeStatus: 'loaded' });++ writeFileSync(path.join(sourcePath, 'SKILL.md'), '# changed in place\n');+ const changedFile = await maker.listAgentSkills('pi', {+ workingDir: repoRoot,+ sessionId: 'source-snapshot',+ });+ expect(changedFile.skills[0]).toMatchObject({ runtimeStatus: 'discovered' });+ expect(changedFile.errors).toContainEqual(expect.objectContaining({ path: sourcePath }));++ rmSync(sourcePath, { recursive: true, force: true });+ writeSkill(sourcePath, '# approved\n', 'replacement asset\n');+ const replacedDirectory = await maker.listAgentSkills('pi', {+ workingDir: repoRoot,+ sessionId: 'source-snapshot',+ });+ expect(replacedDirectory.skills[0]).toMatchObject({ runtimeStatus: 'discovered' });+ expect(replacedDirectory.errors?.[0]?.message).toContain('restart the session');+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });});describe('Session turn send guard', () => {diff --git a/packages/maker-core/src/maker.ts b/packages/maker-core/src/maker.tsindex 89130164e6..c8ed84c1ad 100644--- a/packages/maker-core/src/maker.ts+++ b/packages/maker-core/src/maker.ts@@ -35,6 +35,7 @@ import type {} from './types/customizations.js';import type { PiRuntimeCapabilityManifest } from './types/pi-runtime-capabilities.js';import { piExplicitSkillRuntimePath } from './agents/pi/skill-runtime-provenance.js';+import { fingerprintPiProjectSkillEntrypoint } from './agents/pi/project-resource-assembly.js';import { Session, generateSessionId } from './session.js';import type {AgentSessionHandle,@@ -160,15 +161,32 @@ function canonicalPiRuntimePath(value: string): string {}}-function mergePiRuntimeSkillStatuses(+async function mergePiRuntimeSkillStatuses(result: ListAgentSkillsResult,manifest: PiRuntimeCapabilityManifest | undefined,-): ListAgentSkillsResult {+): Promise<ListAgentSkillsResult> {if (manifest?.status !== 'loaded') return result;const loadedExplicitSkills = new Map<string, string>();const loadedLegacyProjectSkills = new Map<string, string>();+ const changedProjectSkills = new Map<string, string>();for (const skill of manifest.projectResources?.loadedSkills ?? []) {- loadedExplicitSkills.set(canonicalPiRuntimePath(skill.sourcePath), skill.commandName);+ const canonicalSourcePath = canonicalPiRuntimePath(skill.sourcePath);+ if (!skill.snapshotDigest || !skill.sourceFingerprint || !skill.canonicalRepoRoot) {+ changedProjectSkills.set(canonicalSourcePath, skill.sourcePath);+ continue;+ }+ const currentFingerprint = await fingerprintPiProjectSkillEntrypoint(+ skill.sourcePath,+ skill.canonicalRepoRoot,+ );+ if (+ currentFingerprint?.contentDigest !== skill.snapshotDigest+ || currentFingerprint.sourceStateDigest !== skill.sourceFingerprint+ ) {+ changedProjectSkills.set(canonicalSourcePath, skill.sourcePath);+ continue;+ }+ loadedExplicitSkills.set(canonicalSourcePath, skill.commandName);}for (const command of manifest.commands) {const baseDir = command.sourceInfo.baseDir;@@ -191,21 +209,36 @@ function mergePiRuntimeSkillStatuses(loadedExplicitSkills.set(canonicalPiRuntimePath(explicitPath), command.name);}}- if (loadedExplicitSkills.size === 0 && loadedLegacyProjectSkills.size === 0) return result;+ if (+ loadedExplicitSkills.size === 0+ && loadedLegacyProjectSkills.size === 0+ && changedProjectSkills.size === 0+ ) return result;+ const changedSkillErrors = [...changedProjectSkills.values()].map((skillPath) => ({+ path: skillPath,+ message: 'Project skill changed after this Pi session started; restart the session to load the current version.',+ }));return {...result,skills: result.skills.map((skill) => {- const runtimeCommandName = skill.scope === 'repo' && skill.path- ? loadedExplicitSkills.get(canonicalPiRuntimePath(skill.path))- ?? [skill.path, path.dirname(path.dirname(skill.path))]- .map(canonicalPiRuntimePath)- .map((skillPath) => loadedLegacyProjectSkills.get([skill.name, skillPath].join('\0')))- .find((commandName) => commandName !== undefined)- : undefined;+ let runtimeCommandName: string | undefined;+ if (skill.scope === 'repo' && skill.path) {+ const canonicalSkillPath = canonicalPiRuntimePath(skill.path);+ if (!changedProjectSkills.has(canonicalSkillPath)) {+ runtimeCommandName = loadedExplicitSkills.get(canonicalSkillPath)+ ?? [skill.path, path.dirname(path.dirname(skill.path))]+ .map(canonicalPiRuntimePath)+ .map((skillPath) => loadedLegacyProjectSkills.get([skill.name, skillPath].join('\0')))+ .find((commandName) => commandName !== undefined);+ }+ }return runtimeCommandName? { ...skill, runtimeStatus: 'loaded' as const, runtimeCommandName }: skill;}),+ ...(changedSkillErrors.length > 0+ ? { errors: [...(result.errors ?? []), ...changedSkillErrors] }+ : {}),};}diff --git a/packages/maker-core/src/types/pi-runtime-capabilities.ts b/packages/maker-core/src/types/pi-runtime-capabilities.tsindex d7aea767ab..87ec72ab54 100644--- a/packages/maker-core/src/types/pi-runtime-capabilities.ts+++ b/packages/maker-core/src/types/pi-runtime-capabilities.ts@@ -58,6 +58,12 @@ export interface PiProjectResourceRuntimeDiagnostic {sourcePath: string;runtimePath: string;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. */+ sourceFingerprint?: string;+ /** Approval-time boundary used to fingerprint the current source fail closed. */+ canonicalRepoRoot?: string;}[];}