agent-plugin-lifecycle 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/ai/agent-plugin-lifecycle/src/runner.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { mkdir, readFile, realpath, rename, stat, unlink, writeFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';\nimport spawn from 'cross-spawn-cb';\nimport lockfile from 'proper-lockfile';\nimport { type LockedPlugin, loadLock, localEventName, matchesSource, samePath, sourceParts } from './apm.js';\nimport { loadConfig, type PluginPolicy, recordId } from './config.js';\n\nexport type Mode = 'run' | 'check';\nexport interface LifecycleEvent {\n schema_version: 1;\n event: 'post-install' | 'post-update' | 'post-uninstall';\n scope: 'user';\n packages: { name: string; reference: string | null }[];\n}\ninterface State {\n version: 1;\n receipts: Record<string, string>;\n}\nexport interface RunOptions {\n home?: string;\n apmHome?: string;\n configPath?: string;\n environment?: NodeJS.ProcessEnv;\n output?: (line: string) => void;\n event?: LifecycleEvent;\n}\nfunction inside(root: string, child: string): boolean {\n const subpath = relative(root, child);\n return subpath === '' || (subpath !== '..' && !subpath.startsWith(`..${sep}`) && !isAbsolute(subpath));\n}\nasync function existingWithin(root: string, path: string, label: string): Promise<string> {\n const rootReal = await realpath(root);\n const candidate = resolve(rootReal, path);\n if (!inside(rootReal, candidate)) throw new Error(`${label} escapes ${root}`);\n const candidateReal = await realpath(candidate);\n if (!inside(rootReal, candidateReal)) throw new Error(`${label} resolves outside ${root}`);\n return candidateReal;\n}\nfunction pluginRoot(plugin: LockedPlugin, apmHome: string): string {\n return join(apmHome, 'apm_modules', plugin.repo, plugin.path);\n}\nasync function destinations(plugin: LockedPlugin, policy: PluginPolicy, home: string, apmHome: string): Promise<string[]> {\n const output = new Set<string>();\n const root = pluginRoot(plugin, apmHome);\n if (!policy.skill) {\n output.add(await existingWithin(join(apmHome, 'apm_modules'), join(plugin.repo, plugin.path), 'kept plugin'));\n if (plugin.nativePluginRoot) {\n const nativeBase = join(home, '.agents', 'plugins');\n if (plugin.nativePluginRoot.startsWith('.agents/plugins/')) output.add(await existingWithin(nativeBase, plugin.nativePluginRoot.slice('.agents/plugins/'.length), 'native plugin'));\n }\n } else {\n try {\n output.add(await existingWithin(root, `skills/${policy.skill}`, `kept skill ${policy.skill}`));\n } catch (error) {\n if (!(error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT')) throw error;\n }\n if (plugin.nativePluginRoot?.startsWith('.agents/plugins/')) {\n const nativeRoot = plugin.nativePluginRoot.slice('.agents/plugins/'.length);\n try {\n output.add(await existingWithin(join(home, '.agents', 'plugins'), `${nativeRoot}/skills/${policy.skill}`, `native skill ${policy.skill}`));\n } catch (error) {\n if (!(error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT')) throw error;\n }\n }\n for (const file of plugin.deployedFiles) {\n const parts = file.split('/');\n const index = parts.lastIndexOf('skills');\n if (index < 0 || parts[index + 1] !== policy.skill) continue;\n const deployment = parts.slice(0, index + 2).join('/');\n const prefix = ['.agents/skills/', '.hermes/skills/', '.claude/skills/'].find((candidate) => deployment.startsWith(candidate));\n if (prefix) output.add(await existingWithin(home, deployment, `skill ${policy.skill}`));\n }\n if (output.size === 0) throw new Error(`no deployed copy found for skill ${policy.skill}`);\n }\n return [...output];\n}\nasync function readState(path: string): Promise<State> {\n if (!existsSync(path)) return { version: 1, receipts: {} };\n const value: unknown = JSON.parse(await readFile(path, 'utf8'));\n if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('state must be an object');\n const item = value as Record<string, unknown>;\n if (item.version !== 1 || !item.receipts || typeof item.receipts !== 'object' || Array.isArray(item.receipts)) throw new Error('unsupported state format');\n if (Object.values(item.receipts).some((receipt) => typeof receipt !== 'string')) throw new Error('invalid state receipt');\n return item as unknown as State;\n}\nasync function saveState(path: string, state: State): Promise<void> {\n const temp = join(dirname(path), `.state-${process.pid}-${Date.now()}.tmp`);\n try {\n await writeFile(temp, `${JSON.stringify(state, null, 2)}\\n`, { mode: 0o600, flag: 'wx' });\n await rename(temp, path);\n } catch (error) {\n try {\n await unlink(temp);\n } catch {\n /* preserve original error */\n }\n throw error;\n }\n}\nfunction receiptKey(policy: PluginPolicy, destination: string): string {\n return JSON.stringify([recordId(policy), destination]);\n}\nfunction digest(policy: PluginPolicy, command: string): string {\n return createHash('sha256')\n .update(JSON.stringify([recordId(policy), command]))\n .digest('hex');\n}\n// The platform shell runs the configured string as written, as with npm and Node's `shell` option.\nasync function execute(command: string, cwd: string, environment: NodeJS.ProcessEnv): Promise<void> {\n await spawn(command, [], { cwd, env: environment, stdio: ['ignore', 'inherit', 'inherit'], shell: true });\n}\nfunction lockLoadError(error: unknown): boolean {\n return !!error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT';\n}\nexport async function runLifecycle(mode: Mode, options: RunOptions = {}): Promise<number> {\n const home = resolve(options.home ?? homedir());\n const apmHome = resolve(options.apmHome ?? join(home, '.apm'));\n const configPath = options.configPath ?? join(home, '.config', 'agent-plugin-lifecycle', 'config.json');\n const environment = options.environment ?? process.env;\n const output = options.output ?? console.log;\n const config = await loadConfig(configPath);\n let locked: LockedPlugin[];\n try {\n locked = await loadLock(join(apmHome, 'apm.lock.yaml'));\n } catch (error) {\n if (mode === 'run' && options.event?.event === 'post-uninstall' && lockLoadError(error)) {\n const apmDirectory = await stat(apmHome);\n if (!apmDirectory.isDirectory()) throw error;\n locked = [];\n } else throw error;\n }\n const statePath = join(dirname(configPath), 'state.json');\n if (mode === 'run') await mkdir(dirname(statePath), { recursive: true, mode: 0o700 });\n const release = mode === 'run' ? await lockfile.lock(dirname(statePath), { realpath: false }) : undefined;\n try {\n const state = await readState(statePath);\n let failed = 0;\n if (mode === 'run' && options.event?.event === 'post-uninstall') {\n const eventNames = new Set(options.event.packages.map(({ name }) => name));\n for (const policy of config.plugins) {\n const id = recordId(policy);\n const receiptKeys = Object.keys(state.receipts).filter((key) => {\n try {\n return JSON.parse(key)[0] === id;\n } catch {\n return false;\n }\n });\n if (!receiptKeys.length) continue;\n const sourceCandidate =\n policy.source.startsWith('.') || isAbsolute(policy.source) ? locked.find((plugin) => plugin.localPath !== undefined && samePath(policy.source, plugin.localPath)) : locked.find((plugin) => matchesSource(policy.source, plugin) && (plugin.path === (policy.path ?? '.') || plugin.localPath !== undefined));\n const sourcePartsValue = sourceParts(policy.source);\n const removedNameMatch =\n eventNames.has(sourceCandidate?.repo ?? '') ||\n eventNames.has(sourceCandidate ? `${sourceCandidate.host}/${sourceCandidate.repo}` : '') ||\n eventNames.has(sourcePartsValue?.repo ?? '') ||\n eventNames.has(sourcePartsValue ? `${sourcePartsValue.host}/${sourcePartsValue.repo}` : '') ||\n // APM names a removed subfolder plugin `owner/repo/<folder>` (install and update events name it `owner/repo`); exact match only, so removing one folder never matches another plugin of the repository\n (!!sourcePartsValue && !!policy.path && policy.path !== '.' && (eventNames.has(`${sourcePartsValue.repo}/${policy.path}`) || eventNames.has(`${sourcePartsValue.host}/${sourcePartsValue.repo}/${policy.path}`))) ||\n eventNames.has(localEventName(policy.source)) ||\n eventNames.has(policy.source);\n const anyStillInstalled = locked.some((plugin) => matchesSource(policy.source, plugin) && plugin.path === (policy.path ?? '.'));\n if (anyStillInstalled || !removedNameMatch) continue;\n const command = policy['post-uninstall'];\n if (!command) {\n for (const key of receiptKeys) delete state.receipts[key];\n await saveState(statePath, state);\n continue;\n }\n try {\n await execute(command, home, environment);\n for (const key of receiptKeys) delete state.receipts[key];\n await saveState(statePath, state);\n output(`cleaned ${id}`);\n } catch (error) {\n output(`failed cleanup ${id}: ${error instanceof Error ? error.message : String(error)}`);\n failed++;\n }\n }\n return failed ? 1 : 0;\n }\n if (mode === 'run' && !options.event) throw new Error('run requires an APM event');\n const event = options.event?.event ?? 'post-install';\n for (const policy of config.plugins) {\n const command = event === 'post-update' ? (policy['post-update'] ?? policy['post-install']) : policy['post-install'];\n if (!command) continue;\n const matches = locked.filter((plugin) => matchesSource(policy.source, plugin) && plugin.path === (policy.path ?? '.'));\n if (matches.length > 1) {\n output(`failed ambiguous source/path record ${recordId(policy)}`);\n failed++;\n continue;\n }\n if (!matches.length) {\n output(`skipped source not installed ${recordId(policy)}`);\n continue;\n }\n const plugin = matches[0];\n try {\n const found = await destinations(plugin, policy, home, apmHome);\n for (const destination of found) {\n const key = receiptKey(policy, destination);\n if (mode === 'check') {\n const validDigests = [policy['post-install'], policy['post-update']].filter((item): item is string => !!item).map((item) => digest(policy, item));\n const ready = validDigests.includes(state.receipts[key]);\n output(`${ready ? 'ok' : 'missing'} ${recordId(policy)} ${destination}`);\n if (!ready) failed++;\n } else {\n delete state.receipts[key];\n await saveState(statePath, state);\n await execute(command, destination, environment);\n state.receipts[key] = digest(policy, command);\n await saveState(statePath, state);\n output(`ran ${recordId(policy)} ${destination}`);\n }\n }\n } catch (error) {\n output(`failed ${recordId(policy)}: ${error instanceof Error ? error.message : String(error)}`);\n failed++;\n }\n }\n return failed ? 1 : 0;\n } finally {\n await release?.();\n }\n}\n"],"names":["runLifecycle","inside","root","child","subpath","relative","startsWith","sep","isAbsolute","existingWithin","path","label","rootReal","candidate","candidateReal","realpath","resolve","Error","pluginRoot","plugin","apmHome","join","repo","destinations","policy","home","output","nativeBase","error","nativeRoot","Set","skill","add","nativePluginRoot","slice","length","code","file","parts","index","deployment","prefix","split","lastIndexOf","find","deployedFiles","size","readState","value","item","existsSync","version","receipts","JSON","parse","readFile","Array","isArray","Object","values","some","receipt","saveState","state","temp","dirname","Date","process","pid","now","writeFile","stringify","mode","flag","rename","unlink","receiptKey","destination","recordId","digest","command","createHash","update","execute","cwd","environment","spawn","env","stdio","shell","lockLoadError","options","configPath","config","locked","apmDirectory","statePath","release","failed","eventNames","event","homedir","console","log","loadConfig","loadLock","stat","isDirectory","mkdir","recursive","lockfile","lock","undefined","packages","map","name","id","receiptKeys","sourceCandidate","sourcePartsValue","removedNameMatch","anyStillInstalled","key","keys","filter","source","localPath","samePath","matchesSource","sourceParts","has","host","localEventName","message","String","plugins","matches","found","validDigests","ready","includes"],"mappings":";;;;+BAqHsBA;;;eAAAA;;;0BArHK;sBACA;wBACgD;sBACnD;wBAC0C;mEAChD;qEACG;mBAC6E;sBAC1C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqBxD,SAASC,OAAOC,IAAY,EAAEC,KAAa;IACzC,IAAMC,UAAUC,IAAAA,kBAAQ,EAACH,MAAMC;IAC/B,OAAOC,YAAY,MAAOA,YAAY,QAAQ,CAACA,QAAQE,UAAU,CAAC,AAAC,KAAQ,OAAJC,aAAG,MAAO,CAACC,IAAAA,oBAAU,EAACJ;AAC/F;AACA,SAAeK,eAAeP,IAAY,EAAEQ,IAAY,EAAEC,KAAa;;YAC/DC,UACAC,WAEAC;;;;oBAHW;;wBAAMC,IAAAA,kBAAQ,EAACb;;;oBAA1BU,WAAW;oBACXC,YAAYG,IAAAA,iBAAO,EAACJ,UAAUF;oBACpC,IAAI,CAACT,OAAOW,UAAUC,YAAY,MAAM,IAAII,MAAM,AAAC,GAAmBf,OAAjBS,OAAM,aAAgB,OAALT;oBAChD;;wBAAMa,IAAAA,kBAAQ,EAACF;;;oBAA/BC,gBAAgB;oBACtB,IAAI,CAACb,OAAOW,UAAUE,gBAAgB,MAAM,IAAIG,MAAM,AAAC,GAA4Bf,OAA1BS,OAAM,sBAAyB,OAALT;oBACnF;;wBAAOY;;;;IACT;;AACA,SAASI,WAAWC,MAAoB,EAAEC,OAAe;IACvD,OAAOC,IAAAA,cAAI,EAACD,SAAS,eAA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AAQH,SAASH,aAAaQ;;;oCAApC;oCACAtB,MAAMX,QAAQ,CAACsE,IAAI,GAAG3C,OAAOvD,QAAQwD;oCACrC;;wCAAMlB,UAAUkC,WAAWjC;;;oCAA3B;oCACArC,OAAO,AAAC,OAA0BmD,OAApBC,IAAAA,gBAAQ,EAACtD,SAAQ,KAAe,OAAZqD;;;oCAbjC;;;;;;;;;;;;oCAAA;oCAAA;;;;;;;6CAAA,6BAAA;4CAAA;;;4CAAA;kDAAA;;;;;;;;;;;;oCAgBEjD;oCACPF,OAAO,AAAC,UAA8BE,OAArBkD,IAAAA,gBAAQ,EAACtD,SAAQ,MAA2D,OAAvDI,AAAK,YAALA,OAAiBX,SAAQW,MAAMyG,OAAO,GAAGC,OAAO1G;oCACtFsE;;;;;;;;;;;oBAEJ;oBApCK,aAAgBL,OAAO0C,OAAO;;;2BAA9B,8BAAA,SAAA;;;;;;;;;;;;oBAAA;;;;;;;;;;;;oBAAA;oBAAA;;;;;;;6BAAA,8BAAA;4BAAA;;;4BAAA;kCAAA;;;;;;;oBAqCL;;wBAAOrC,SAAS,IAAI;;;oBAEpB;;wBAAMD,oBAAAA,8BAAAA;;;oBAAN;;;;;;;;;;IAEJ"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/agent-plugin-lifecycle/src/runner.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { mkdir, readFile, realpath, rename, stat, unlink, writeFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';\nimport spawn from 'cross-spawn-cb';\nimport lockfile from 'proper-lockfile';\nimport { type LockedPlugin, loadLock, localEventName, matchesSource, samePath, sourceParts } from './apm.js';\nimport { loadConfig, type PluginPolicy, recordId } from './config.js';\n\nexport type Mode = 'run' | 'check';\nexport interface LifecycleEvent {\n schema_version: 1;\n event: 'post-install' | 'post-update' | 'post-uninstall';\n scope: 'user';\n packages: { name: string; reference: string | null }[];\n}\n// `revision` is the locked revision the command last ran against; '' is a version 1 receipt, whose revision was never recorded.\ninterface Receipt {\n digest: string;\n revision: string;\n}\ninterface State {\n version: 2;\n receipts: Record<string, Receipt>;\n}\nexport interface RunOptions {\n home?: string;\n apmHome?: string;\n configPath?: string;\n environment?: NodeJS.ProcessEnv;\n output?: (line: string) => void;\n event?: LifecycleEvent;\n}\nfunction inside(root: string, child: string): boolean {\n const subpath = relative(root, child);\n return subpath === '' || (subpath !== '..' && !subpath.startsWith(`..${sep}`) && !isAbsolute(subpath));\n}\nasync function existingWithin(root: string, path: string, label: string): Promise<string> {\n const rootReal = await realpath(root);\n const candidate = resolve(rootReal, path);\n if (!inside(rootReal, candidate)) throw new Error(`${label} escapes ${root}`);\n const candidateReal = await realpath(candidate);\n if (!inside(rootReal, candidateReal)) throw new Error(`${label} resolves outside ${root}`);\n return candidateReal;\n}\nfunction pluginRoot(plugin: LockedPlugin, apmHome: string): string {\n return join(apmHome, 'apm_modules', plugin.repo, plugin.path);\n}\nfunction missing(error: unknown): boolean {\n return !!error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT';\n}\nasync function existingOrNone(root: string, path: string, label: string): Promise<string | undefined> {\n try {\n return await existingWithin(root, path, label);\n } catch (error) {\n if (missing(error)) return undefined;\n throw error;\n }\n}\nconst SKILL_ROOTS = ['.agents/skills/', '.hermes/skills/', '.claude/skills/'];\nfunction deployedSkillFolders(plugin: LockedPlugin, skill: string): string[] {\n const folders = new Set<string>();\n for (const file of plugin.deployedFiles) {\n const parts = file.split('/');\n const index = parts.lastIndexOf('skills');\n if (index < 0 || parts[index + 1] !== skill) continue;\n const deployment = parts.slice(0, index + 2).join('/');\n if (SKILL_ROOTS.some((candidate) => deployment.startsWith(candidate))) folders.add(deployment);\n }\n return [...folders];\n}\n// APM's kept copy (`apm_modules/...`) is a destination only when the lock names no other copy: a target such as copilot reads it in place.\n// When the lock names a native plugin root or deployed skill copies, the kept copy is APM's cache and is never used, even if the listed copies are missing on disk (they are skipped, and check reports them).\nasync function destinations(plugin: LockedPlugin, policy: PluginPolicy, home: string, apmHome: string): Promise<string[]> {\n const found = new Set<string>();\n const add = (path: string | undefined) => {\n if (path) found.add(path);\n };\n const nativeRoot = plugin.nativePluginRoot?.startsWith('.agents/plugins/') ? plugin.nativePluginRoot.slice('.agents/plugins/'.length) : undefined;\n if (!policy.skill) {\n if (!nativeRoot) return [await existingWithin(join(apmHome, 'apm_modules'), join(plugin.repo, plugin.path), 'kept plugin')];\n add(await existingOrNone(join(home, '.agents', 'plugins'), nativeRoot, 'native plugin'));\n if (!found.size) throw new Error(`no native plugin copy found for ${plugin.repo}`);\n return [...found];\n }\n const deployed = deployedSkillFolders(plugin, policy.skill);\n if (!nativeRoot && !deployed.length) {\n const kept = await existingOrNone(pluginRoot(plugin, apmHome), `skills/${policy.skill}`, `kept skill ${policy.skill}`);\n if (!kept) throw new Error(`no deployed copy found for skill ${policy.skill}`);\n return [kept];\n }\n if (nativeRoot) add(await existingOrNone(join(home, '.agents', 'plugins'), `${nativeRoot}/skills/${policy.skill}`, `native skill ${policy.skill}`));\n for (const deployment of deployed) add(await existingOrNone(home, deployment, `skill ${policy.skill}`));\n if (!found.size) throw new Error(`no deployed copy found for skill ${policy.skill}`);\n return [...found];\n}\nasync function readState(path: string): Promise<State> {\n if (!existsSync(path)) return { version: 2, receipts: {} };\n const value: unknown = JSON.parse(await readFile(path, 'utf8'));\n if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('state must be an object');\n const item = value as Record<string, unknown>;\n if ((item.version !== 1 && item.version !== 2) || !item.receipts || typeof item.receipts !== 'object' || Array.isArray(item.receipts)) throw new Error('unsupported state format');\n const receipts: Record<string, Receipt> = {};\n for (const [key, receipt] of Object.entries(item.receipts)) {\n if (item.version === 1 && typeof receipt === 'string') receipts[key] = { digest: receipt, revision: '' };\n else if (item.version === 2 && receipt && typeof receipt === 'object' && typeof (receipt as Receipt).digest === 'string' && typeof (receipt as Receipt).revision === 'string') receipts[key] = receipt as Receipt;\n else throw new Error('invalid state receipt');\n }\n return { version: 2, receipts };\n}\nasync function saveState(path: string, state: State): Promise<void> {\n const temp = join(dirname(path), `.state-${process.pid}-${Date.now()}.tmp`);\n try {\n await writeFile(temp, `${JSON.stringify(state, null, 2)}\\n`, { mode: 0o600, flag: 'wx' });\n await rename(temp, path);\n } catch (error) {\n try {\n await unlink(temp);\n } catch {\n /* preserve original error */\n }\n throw error;\n }\n}\nfunction receiptKey(policy: PluginPolicy, destination: string): string {\n return JSON.stringify([recordId(policy), destination]);\n}\nfunction digest(policy: PluginPolicy, command: string): string {\n return createHash('sha256')\n .update(JSON.stringify([recordId(policy), command]))\n .digest('hex');\n}\n// The platform shell runs the configured string as written, as with npm and Node's `shell` option.\nasync function execute(command: string, cwd: string, environment: NodeJS.ProcessEnv): Promise<void> {\n await spawn(command, [], { cwd, env: environment, stdio: ['ignore', 'inherit', 'inherit'], shell: true });\n}\nfunction receiptRecord(key: string): string | undefined {\n try {\n return JSON.parse(key)[0];\n } catch {\n return undefined;\n }\n}\nfunction lockLoadError(error: unknown): boolean {\n return !!error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT';\n}\nexport async function runLifecycle(mode: Mode, options: RunOptions = {}): Promise<number> {\n const home = resolve(options.home ?? homedir());\n const apmHome = resolve(options.apmHome ?? join(home, '.apm'));\n const configPath = options.configPath ?? join(home, '.config', 'agent-plugin-lifecycle', 'config.json');\n const environment = options.environment ?? process.env;\n const output = options.output ?? console.log;\n const config = await loadConfig(configPath);\n let locked: LockedPlugin[];\n try {\n locked = await loadLock(join(apmHome, 'apm.lock.yaml'));\n } catch (error) {\n if (mode === 'run' && options.event?.event === 'post-uninstall' && lockLoadError(error)) {\n const apmDirectory = await stat(apmHome);\n if (!apmDirectory.isDirectory()) throw error;\n locked = [];\n } else if (mode === 'check' && lockLoadError(error)) {\n output('nothing installed');\n return 0;\n } else throw error;\n }\n const statePath = join(dirname(configPath), 'state.json');\n if (mode === 'run') await mkdir(dirname(statePath), { recursive: true, mode: 0o700 });\n const release = mode === 'run' ? await lockfile.lock(dirname(statePath), { realpath: false }) : undefined;\n try {\n const state = await readState(statePath);\n let failed = 0;\n if (mode === 'run' && options.event?.event === 'post-uninstall') {\n const eventNames = new Set(options.event.packages.map(({ name }) => name));\n for (const policy of config.plugins) {\n const id = recordId(policy);\n const receiptKeys = Object.keys(state.receipts).filter((key) => {\n try {\n return JSON.parse(key)[0] === id;\n } catch {\n return false;\n }\n });\n if (!receiptKeys.length) continue;\n const sourceCandidate =\n policy.source.startsWith('.') || isAbsolute(policy.source) ? locked.find((plugin) => plugin.localPath !== undefined && samePath(policy.source, plugin.localPath)) : locked.find((plugin) => matchesSource(policy.source, plugin) && (plugin.path === (policy.path ?? '.') || plugin.localPath !== undefined));\n const sourcePartsValue = sourceParts(policy.source);\n const removedNameMatch =\n eventNames.has(sourceCandidate?.repo ?? '') ||\n eventNames.has(sourceCandidate ? `${sourceCandidate.host}/${sourceCandidate.repo}` : '') ||\n eventNames.has(sourcePartsValue?.repo ?? '') ||\n eventNames.has(sourcePartsValue ? `${sourcePartsValue.host}/${sourcePartsValue.repo}` : '') ||\n // APM names a removed subfolder plugin `owner/repo/<folder>` (install and update events name it `owner/repo`); exact match only, so removing one folder never matches another plugin of the repository\n (!!sourcePartsValue && !!policy.path && policy.path !== '.' && (eventNames.has(`${sourcePartsValue.repo}/${policy.path}`) || eventNames.has(`${sourcePartsValue.host}/${sourcePartsValue.repo}/${policy.path}`))) ||\n eventNames.has(localEventName(policy.source)) ||\n eventNames.has(policy.source);\n const anyStillInstalled = locked.some((plugin) => matchesSource(policy.source, plugin) && plugin.path === (policy.path ?? '.'));\n if (anyStillInstalled || !removedNameMatch) continue;\n // APM keeps a folder holding files it did not write; report it, delete nothing\n for (const key of receiptKeys) {\n const destination: string = JSON.parse(key)[1];\n if (existsSync(destination)) output(`left ${destination}`);\n }\n const command = policy['post-uninstall'];\n if (!command) {\n for (const key of receiptKeys) delete state.receipts[key];\n await saveState(statePath, state);\n continue;\n }\n try {\n await execute(command, home, environment);\n for (const key of receiptKeys) delete state.receipts[key];\n await saveState(statePath, state);\n output(`cleaned ${id}`);\n } catch (error) {\n output(`failed cleanup ${id}: ${error instanceof Error ? error.message : String(error)}`);\n failed++;\n }\n }\n return failed ? 1 : 0;\n }\n if (mode === 'run' && !options.event) throw new Error('run requires an APM event');\n const event = options.event?.event ?? 'post-install';\n let installed = 0;\n for (const policy of config.plugins) {\n const command = event === 'post-update' ? (policy['post-update'] ?? policy['post-install']) : policy['post-install'];\n if (!command) continue;\n const matches = locked.filter((plugin) => matchesSource(policy.source, plugin) && plugin.path === (policy.path ?? '.'));\n if (matches.length > 1) {\n output(`failed ambiguous source/path record ${recordId(policy)}`);\n failed++;\n continue;\n }\n if (!matches.length) {\n if (mode === 'run') output(`skipped source not installed ${recordId(policy)}`);\n continue;\n }\n installed++;\n const plugin = matches[0];\n const id = recordId(policy);\n try {\n const recorded = Object.keys(state.receipts).filter((key) => receiptRecord(key) === id);\n let found: string[];\n try {\n found = await destinations(plugin, policy, home, apmHome);\n } catch (error) {\n // check still reports a copy that was recorded and is now gone\n if (mode === 'check' && recorded.length && (missing(error) || (error instanceof Error && error.message.startsWith('no ')))) found = [];\n else throw error;\n }\n const gone = recorded.filter((key) => !existsSync(JSON.parse(key)[1]));\n if (mode === 'run') {\n // a copy that no longer exists loses its receipt, so the copy APM recreates in its place runs again\n for (const key of gone) delete state.receipts[key];\n if (gone.length) await saveState(statePath, state);\n } else {\n const validDigests = [policy['post-install'], policy['post-update']].filter((item): item is string => !!item).map((item) => digest(policy, item));\n for (const key of gone) {\n const receipt = state.receipts[key];\n if (validDigests.includes(receipt.digest) && receipt.revision === plugin.revision) {\n output(`broken ${id} ${JSON.parse(key)[1]}`);\n failed++;\n }\n }\n for (const destination of found) {\n const receipt = state.receipts[receiptKey(policy, destination)];\n let status = 'missing';\n if (receipt) {\n const current = validDigests.includes(receipt.digest) && receipt.revision === plugin.revision;\n status = current ? 'ok' : 'stale';\n }\n output(`${status} ${id} ${destination}`);\n if (status !== 'ok') failed++;\n }\n continue;\n }\n for (const destination of found) {\n const key = receiptKey(policy, destination);\n const wanted = digest(policy, command);\n const receipt = state.receipts[key];\n if (receipt && receipt.digest === wanted && receipt.revision === plugin.revision) {\n output(`current ${id} ${destination}`);\n continue;\n }\n delete state.receipts[key];\n await saveState(statePath, state);\n await execute(command, destination, environment);\n state.receipts[key] = { digest: wanted, revision: plugin.revision };\n await saveState(statePath, state);\n output(`ran ${id} ${destination}`);\n }\n } catch (error) {\n output(`failed ${id}: ${error instanceof Error ? error.message : String(error)}`);\n failed++;\n }\n }\n if (mode === 'check' && !installed && !failed) output('nothing installed');\n return failed ? 1 : 0;\n } finally {\n await release?.();\n }\n}\n"],"names":["runLifecycle","inside","root","child","subpath","relative","startsWith","sep","isAbsolute","existingWithin","path","label","rootReal","candidate","candidateReal","realpath","resolve","Error","pluginRoot","plugin","apmHome","join","repo","missing","error","code","existingOrNone","undefined","SKILL_ROOTS","deployedSkillFolders","skill","folders","Set","file","parts","split","index","lastIndexOf","deployment","slice","some","add","deployedFiles","destinations","policy","home","found","nativeRoot","deployed","kept","nativePluginRoot","length","size","readState","value","item","receipts","key","receipt","existsSync","version","JSON","parse","readFile","Array","isArray","Object","entries","digest","revision","saveState","state","temp","dirname","Date","process","pid","now","writeFile","stringify","mode","flag","rename","unlink","receiptKey","destination","recordId","command","createHash","update","execute","cwd","environment","spawn","env","stdio","shell","receiptRecord","lockLoadError","options","configPath","output","config","locked","apmDirectory","statePath","release","failed","eventNames","event","installed","homedir","console","log","loadConfig","loadLock","stat","isDirectory","mkdir","recursive","lockfile","lock","packages","map","name","id","receiptKeys","sourceCandidate","sourcePartsValue","removedNameMatch","anyStillInstalled","keys","filter","source","find","localPath","samePath","matchesSource","sourceParts","has","host","localEventName","message","String","plugins","matches","recorded","gone","validDigests","status","current","wanted","includes"],"mappings":";;;;+BAmJsBA;;;eAAAA;;;0BAnJK;sBAC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CAbjB;;;;;;;;;;;;oCAAA;oCAAA;;;;;;;6CAAA,8BAAA;4CAAA;;;4CAAA;kDAAA;;;;;;;;;;;;oCAeE7D;oCACP6E,OAAO,AAAC,UAAgB7E,OAAPqG,IAAG,MAA2D,OAAvDrG,AAAK,YAALA,QAAiBP,SAAQO,OAAMsH,OAAO,GAAGC,OAAOvH;oCACxEmF;;;;;;;;;;;oBAEJ;oBAvEK,aAAgBL,OAAO0C,OAAO;;;2BAA9B,8BAAA,SAAA;;;;;;;;;;;;oBAAA;;;;;;;;;;;;oBAAA;oBAAA;;;;;;;6BAAA,8BAAA;4BAAA;;;4BAAA;kCAAA;;;;;;;oBAwEL,IAAIhE,SAAS,WAAW,CAAC8B,aAAa,CAACH,QAAQN,OAAO;oBACtD;;wBAAOM,SAAS,IAAI;;;oBAEpB;;wBAAMD,oBAAAA,8BAAAA;;;oBAAN;;;;;;;;;;IAEJ"}
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/ai/agent-plugin-lifecycle/src/apm.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { basename, posix, win32 } from 'node:path';\nimport { parse } from 'yaml';\n\nexport interface LockedPlugin {\n host: string;\n repo: string;\n path: string;\n revision: string;\n localPath?: string;\n nativePluginRoot?: string;\n deployedFiles: string[];\n}\nfunction record(value: unknown, label: string): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(`${label} must be an object`);\n return value as Record<string, unknown>;\n}\nfunction requiredString(value: unknown, label: string): string {\n if (typeof value !== 'string' || !value) throw new Error(`${label} must be a nonempty string`);\n return value;\n}\nfunction safePath(value: unknown, label: string, dot = false): string {\n const path = requiredString(value, label);\n if (dot && path === '.') return path;\n if (path.startsWith('/') || path.includes('\\\\') || /^[A-Za-z]:/.test(path) || path.split('/').some((part) => !part || part === '.' || part === '..')) throw new Error(`${label} contains an unsafe path segment`);\n return path;\n}\nexport function sourceParts(source: string): { host: string; repo: string } | undefined {\n let host: string;\n let path: string;\n const scp = source.includes('://') ? null : /^(?:[^@/:]+@)?([^/:]+):(.+)$/.exec(source);\n if (scp) {\n host = scp[1];\n path = scp[2];\n } else {\n try {\n const url = new URL(source);\n if (!['https:', 'ssh:', 'http:'].includes(url.protocol)) return undefined;\n host = url.hostname;\n path = url.pathname.replace(/^\\//, '');\n } catch {\n return undefined;\n }\n }\n path = path.replace(/\\.git$/, '').replace(/\\/$/, '');\n if (!host || !path || path.split('/').some((part) => !part || part === '.' || part === '..')) return undefined;\n return { host: host.toLowerCase(), repo: path };\n}\n// Same path whatever separators or trailing slash either side was written with; Windows paths also ignore case.\nexport function samePath(left: string, right: string, platform: NodeJS.Platform = process.platform): boolean {\n if (platform !== 'win32') return posix.resolve(left) === posix.resolve(right);\n return win32.resolve(left).toLowerCase() === win32.resolve(right).toLowerCase();\n}\nexport function matchesSource(policySource: string, plugin: LockedPlugin, platform: NodeJS.Platform = process.platform): boolean {\n if (plugin.localPath !== undefined) return samePath(policySource, plugin.localPath, platform);\n const parts = sourceParts(policySource);\n return !!parts && parts.host === plugin.host.toLowerCase() && parts.repo === plugin.repo.replace(/\\.git$/, '');\n}\nexport function localEventName(source: string): string {\n return `_local/${basename(source).replace(/\\/$/, '')}`;\n}\nexport function lockIdentity(plugin: LockedPlugin): string {\n return JSON.stringify([plugin.host, plugin.repo, plugin.path, plugin.localPath ?? null]);\n}\nexport function parseLock(value: unknown): LockedPlugin[] {\n const root = record(value, 'APM lock');\n if (!Array.isArray(root.dependencies)) throw new Error('APM lock dependencies must be an array');\n const seen = new Set<string>();\n return root.dependencies.map((raw, index): LockedPlugin => {\n const label = `APM lock dependencies[${index}]`;\n const source = record(raw, label);\n let plugin: LockedPlugin;\n if (source.source === 'local' && source.package_type === 'agent_plugin') {\n const repo = safePath(source.repo_url, `${label}.repo_url`);\n if (!repo.startsWith('_local/')) throw new Error(`${label}.repo_url is not a local plugin key`);\n const localPath = requiredString(source.local_path, `${label}.local_path`);\n const hash = requiredString(source.content_hash, `${label}.content_hash`);\n if (!/^sha256:[0-9a-f]{64}$/.test(hash)) throw new Error(`${label} has invalid content hash`);\n plugin = { host: 'local', repo, path: '.', revision: hash, localPath, deployedFiles: [] };\n } else {\n const host = requiredString(source.host, `${label}.host`);\n const repo = safePath(source.repo_url, `${label}.repo_url`);\n // APM writes no virtual_path for a plugin at the repository root (recorded from APM 0.37.0)\n const path = source.virtual_path === undefined || source.virtual_path === null ? '.' : safePath(source.virtual_path, `${label}.virtual_path`, true);\n const commit = requiredString(source.resolved_commit, `${label}.resolved_commit`);\n const hash = requiredString(source.content_hash, `${label}.content_hash`);\n if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(commit) || !/^sha256:[0-9a-f]{64}$/.test(hash)) throw new Error(`${label} has invalid revision evidence`);\n const native = source.native_plugin === undefined || source.native_plugin === null ? undefined : record(source.native_plugin, `${label}.native_plugin`);\n const nativePluginRoot = native ? safePath(native.root, `${label}.native_plugin.root`) : undefined;\n const deployed = source.deployed_files ?? [];\n if (!Array.isArray(deployed) || !deployed.every((file) => typeof file === 'string')) throw new Error(`${label}.deployed_files must be an array of paths`);\n const deployedFiles = deployed.map((file: string, fileIndex: number) => safePath(file, `${label}.deployed_files[${fileIndex}]`));\n plugin = { host, repo, path, revision: `${commit}:${hash}`, nativePluginRoot, deployedFiles };\n }\n const identity = lockIdentity(plugin);\n if (seen.has(identity)) throw new Error(`${label} duplicates another lock entry`);\n seen.add(identity);\n return plugin;\n });\n}\nexport async function loadLock(path: string): Promise<LockedPlugin[]> {\n return parseLock(parse(await readFile(path, 'utf8')));\n}\n"],"names":["readFile","basename","posix","win32","parse","record","value","label","Array","isArray","Error","requiredString","safePath","dot","path","startsWith","includes","test","split","some","part","sourceParts","source","host","scp","exec","url","URL","protocol","undefined","hostname","pathname","replace","toLowerCase","repo","samePath","left","right","platform","process","resolve","matchesSource","policySource","plugin","localPath","parts","localEventName","lockIdentity","JSON","stringify","parseLock","root","dependencies","seen","Set","map","raw","index","package_type","repo_url","local_path","hash","content_hash","revision","deployedFiles","virtual_path","commit","resolved_commit","native","native_plugin","nativePluginRoot","deployed","deployed_files","every","file","fileIndex","identity","has","add","loadLock"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,mBAAmB;AAC5C,SAASC,QAAQ,EAAEC,KAAK,EAAEC,KAAK,QAAQ,YAAY;AACnD,SAASC,KAAK,QAAQ,OAAO;AAW7B,SAASC,OAAOC,KAAc,EAAEC,KAAa;IAC3C,IAAI,CAACD,SAAS,OAAOA,UAAU,YAAYE,MAAMC,OAAO,CAACH,QAAQ,MAAM,IAAII,MAAM,GAAGH,MAAM,kBAAkB,CAAC;IAC7G,OAAOD;AACT;AACA,SAASK,eAAeL,KAAc,EAAEC,KAAa;IACnD,IAAI,OAAOD,UAAU,YAAY,CAACA,OAAO,MAAM,IAAII,MAAM,GAAGH,MAAM,0BAA0B,CAAC;IAC7F,OAAOD;AACT;AACA,SAASM,SAASN,KAAc,EAAEC,KAAa,EAAEM,MAAM,KAAK;IAC1D,MAAMC,OAAOH,eAAeL,OAAOC;IACnC,IAAIM,OAAOC,SAAS,KAAK,OAAOA;IAChC,IAAIA,KAAKC,UAAU,CAAC,QAAQD,KAAKE,QAAQ,CAAC,SAAS,aAAaC,IAAI,CAACH,SAASA,KAAKI,KAAK,CAAC,KAAKC,IAAI,CAAC,CAACC,OAAS,CAACA,QAAQA,SAAS,OAAOA,SAAS,OAAO,MAAM,IAAIV,MAAM,GAAGH,MAAM,gCAAgC,CAAC;IAChN,OAAOO;AACT;AACA,OAAO,SAASO,YAAYC,MAAc;IACxC,IAAIC;IACJ,IAAIT;IACJ,MAAMU,MAAMF,OAAON,QAAQ,CAAC,SAAS,OAAO,+BAA+BS,IAAI,CAACH;IAChF,IAAIE,KAAK;QACPD,OAAOC,GAAG,CAAC,EAAE;QACbV,OAAOU,GAAG,CAAC,EAAE;IACf,OAAO;QACL,IAAI;YACF,MAAME,MAAM,IAAIC,IAAIL;YACpB,IAAI,CAAC;g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MY,WAAW7B,aAAaJ;QAC9B,IAAIU,KAAKwB,GAAG,CAACD,WAAW,MAAM,IAAIlE,MAAM,GAAGH,MAAM,8BAA8B,CAAC;QAChF8C,KAAKyB,GAAG,CAACF;QACT,OAAOjC;IACT;AACF;AACA,OAAO,eAAeoC,SAASjE,IAAY;IACzC,OAAOoC,UAAU9C,MAAM,MAAMJ,SAASc,MAAM;AAC9C"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/agent-plugin-lifecycle/src/apm.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { basename, posix, win32 } from 'node:path';\nimport { parse } from 'yaml';\n\nexport interface LockedPlugin {\n host: string;\n repo: string;\n path: string;\n revision: string;\n localPath?: string;\n nativePluginRoot?: string;\n deployedFiles: string[];\n}\nfunction record(value: unknown, label: string): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(`${label} must be an object`);\n return value as Record<string, unknown>;\n}\nfunction requiredString(value: unknown, label: string): string {\n if (typeof value !== 'string' || !value) throw new Error(`${label} must be a nonempty string`);\n return value;\n}\nfunction safePath(value: unknown, label: string, dot = false): string {\n const path = requiredString(value, label);\n if (dot && path === '.') return path;\n if (path.startsWith('/') || path.includes('\\\\') || /^[A-Za-z]:/.test(path) || path.split('/').some((part) => !part || part === '.' || part === '..')) throw new Error(`${label} contains an unsafe path segment`);\n return path;\n}\nexport function sourceParts(source: string): { host: string; repo: string } | undefined {\n let host: string;\n let path: string;\n const scp = source.includes('://') ? null : /^(?:[^@/:]+@)?([^/:]+):(.+)$/.exec(source);\n if (scp) {\n host = scp[1];\n path = scp[2];\n } else {\n try {\n const url = new URL(source);\n if (!['https:', 'ssh:', 'http:'].includes(url.protocol)) return undefined;\n host = url.hostname;\n path = url.pathname.replace(/^\\//, '');\n } catch {\n return undefined;\n }\n }\n path = path.replace(/\\.git$/, '').replace(/\\/$/, '');\n if (!host || !path || path.split('/').some((part) => !part || part === '.' || part === '..')) return undefined;\n return { host: host.toLowerCase(), repo: path };\n}\n// Same path whatever separators or trailing slash either side was written with; Windows paths also ignore case.\nexport function samePath(left: string, right: string, platform: NodeJS.Platform = process.platform): boolean {\n if (platform !== 'win32') return posix.resolve(left) === posix.resolve(right);\n return win32.resolve(left).toLowerCase() === win32.resolve(right).toLowerCase();\n}\nexport function matchesSource(policySource: string, plugin: LockedPlugin, platform: NodeJS.Platform = process.platform): boolean {\n if (plugin.localPath !== undefined) return samePath(policySource, plugin.localPath, platform);\n const parts = sourceParts(policySource);\n return !!parts && parts.host === plugin.host.toLowerCase() && parts.repo === plugin.repo.replace(/\\.git$/, '');\n}\nexport function localEventName(source: string): string {\n return `_local/${basename(source).replace(/\\/$/, '')}`;\n}\nexport function lockIdentity(plugin: LockedPlugin): string {\n return JSON.stringify([plugin.host, plugin.repo, plugin.path, plugin.localPath ?? null]);\n}\nexport function parseLock(value: unknown): LockedPlugin[] {\n const root = record(value, 'APM lock');\n if (!Array.isArray(root.dependencies)) throw new Error('APM lock dependencies must be an array');\n const seen = new Set<string>();\n return root.dependencies.map((raw, index): LockedPlugin => {\n const label = `APM lock dependencies[${index}]`;\n const source = record(raw, label);\n let plugin: LockedPlugin;\n if (source.source === 'local' && source.package_type === 'agent_plugin') {\n const repo = safePath(source.repo_url, `${label}.repo_url`);\n if (!repo.startsWith('_local/')) throw new Error(`${label}.repo_url is not a local plugin key`);\n const localPath = requiredString(source.local_path, `${label}.local_path`);\n const hash = requiredString(source.content_hash, `${label}.content_hash`);\n if (!/^sha256:[0-9a-f]{64}$/.test(hash)) throw new Error(`${label} has invalid content hash`);\n plugin = { host: 'local', repo, path: '.', revision: hash, localPath, deployedFiles: [] };\n } else {\n const host = requiredString(source.host, `${label}.host`);\n const repo = safePath(source.repo_url, `${label}.repo_url`);\n // APM writes no virtual_path for a plugin at the repository root (recorded from APM 0.37.0)\n const path = source.virtual_path === undefined || source.virtual_path === null ? '.' : safePath(source.virtual_path, `${label}.virtual_path`, true);\n const commit = requiredString(source.resolved_commit, `${label}.resolved_commit`);\n const hash = requiredString(source.content_hash, `${label}.content_hash`);\n if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(commit) || !/^sha256:[0-9a-f]{64}$/.test(hash)) throw new Error(`${label} has invalid revision evidence`);\n const native = source.native_plugin === undefined || source.native_plugin === null ? undefined : record(source.native_plugin, `${label}.native_plugin`);\n const nativePluginRoot = native ? safePath(native.root, `${label}.native_plugin.root`) : undefined;\n const deployed = source.deployed_files ?? [];\n if (!Array.isArray(deployed) || !deployed.every((file) => typeof file === 'string')) throw new Error(`${label}.deployed_files must be an array of paths`);\n const deployedFiles = deployed.map((file: string, fileIndex: number) => safePath(file, `${label}.deployed_files[${fileIndex}]`));\n plugin = { host, repo, path, revision: `${commit}:${hash}`, nativePluginRoot, deployedFiles };\n }\n const identity = lockIdentity(plugin);\n if (seen.has(identity)) throw new Error(`${label} duplicates another lock entry`);\n seen.add(identity);\n return plugin;\n });\n}\nexport async function loadLock(path: string): Promise<LockedPlugin[]> {\n return parseLock(parse(await readFile(path, 'utf8')));\n}\n"],"names":["readFile","basename","posix","win32","parse","record","value","label","Array","isArray","Error","requiredString","safePath","dot","path","startsWith","includes","test","split","some","part","sourceParts","source","host","scp","exec","url","URL","protocol","undefined","hostname","pathname","replace","toLowerCase","repo","samePath","left","right","platform","process","resolve","matchesSource","policySource","plugin","localPath","parts","localEventName","lockIdentity","JSON","stringify","parseLock","root","dependencies","seen","Set","map","raw","index","package_type","repo_url","local_path","hash","content_hash","revision","deployedFiles","virtual_path","commit","resolved_commit","native","native_plugin","nativePluginRoot","deployed","deployed_files","every","file","fileIndex","identity","has","add","loadLock"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,mBAAmB;AAC5C,SAASC,QAAQ,EAAEC,KAAK,EAAEC,KAAK,QAAQ,YAAY;AACnD,SAASC,KAAK,QAAQ,OAAO;AAW7B,SAASC,OAAOC,KAAc,EAAEC,KAAa;IAC3C,IAAI,CAACD,SAAS,OAAOA,UA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ts"],"sourcesContent":["import { parseArgs } from 'node:util';\n\nimport { runLifecycle } from './runner.js';\n\nconst HELP = `agent-plugin-lifecycle\n\nUsage:\n agent-plugin-lifecycle run Dispatch an APM post-install/update/uninstall event from stdin\n agent-plugin-lifecycle check Report missing or failed plugin setup\n agent-plugin-lifecycle --help\n\nPolicy: ~/.config/agent-plugin-lifecycle/config.json\nAPM lock: ~/.apm/apm.lock.yaml (or $APM_HOME/apm.lock.yaml)\n`;\n\nasync function readEvent(): Promise<import('./runner.js').LifecycleEvent> {\n if (process.stdin.isTTY) throw new Error('run requires an APM event on stdin');\n let payload = '';\n for await (const chunk of process.stdin) {\n payload += chunk.toString();\n if (payload.length > 1024 * 1024) throw new Error('APM event exceeds 1 MiB');\n }\n if (!payload.trim()) throw new Error('run requires an APM event on stdin');\n const event: unknown = JSON.parse(payload);\n if (!event || typeof event !== 'object' || Array.isArray(event)) throw new Error('APM event must be an object');\n const value = event as Record<string, unknown>;\n if (\n value.schema_version !== 1 ||\n !['post-install', 'post-update', 'post-uninstall'].includes(String(value.event)) ||\n !['user', 'project'].includes(String(value.scope)) ||\n !Array.isArray(value.packages) ||\n !value.packages.every((p) => p && typeof p === 'object' && typeof p.name === 'string' && (p.reference === null || typeof p.reference === 'string'))\n ) {\n throw new Error('unsupported APM lifecycle event');\n }\n return value as unknown as import('./runner.js').LifecycleEvent;\n}\n\nasync function main(): Promise<number> {\n const { values, positionals } = parseArgs({\n args: process.argv.slice(2),\n options: { help: { type: 'boolean', short: 'h' } },\n allowPositionals: true,\n });\n if (values.help || positionals.length === 0) {\n process.stdout.write(HELP);\n return 0;\n }\n if (positionals.length !== 1 || !['run', 'check'].includes(positionals[0])) throw new Error('expected run or check; use --help');\n const event = positionals[0] === 'run' ? await readEvent() : undefined;\n if (event?.scope !== undefined && event.scope !== 'user') {\n console.log(`skipped APM ${event.scope} scope event`);\n return 0;\n }\n return runLifecycle(positionals[0] as 'run' | 'check', { apmHome: process.env.APM_HOME, event });\n}\n\nmain()\n .then((status) => {\n process.exitCode = status;\n })\n .catch((error: unknown) => {\n console.error(`agent-plugin-lifecycle: ${error instanceof Error ? error.message : String(error)}`);\n process.exitCode = 2;\n });\n"],"names":["parseArgs","runLifecycle","HELP","readEvent","process","stdin","isTTY","Error","payload","chunk","toString","length","trim","event","JSON","parse","Array","isArray","value","schema_version","includes","String","scope","packages","every","p","name","reference","main","values","positionals","args","argv","slice","options","help","type","short","allowPositionals","stdout","write","undefined","console","log","apmHome","env","APM_HOME","then","status","exitCode","catch","error","message"],"mappings":"AAAA,SAASA,SAAS,QAAQ,YAAY;AAEtC,SAASC,YAAY,QAAQ,cAAc;AAE3C,MAAMC,OAAO,CAAC;;;;;;;;;AASd,CAAC;AAED,eAAeC;IACb,IAAIC,QAAQC,KAAK,CAACC,KAAK,EAAE,MAAM,IAAIC,MAAM;IACzC,IAAIC,UAAU;IACd,WAAW,MAAMC,SAASL,QAAQC,KAAK,CAAE;QACvCG,WAAWC,MAAMC,QAAQ;QACzB,IAAIF,QAAQG,MAAM,GAAG,OAAO,MAAM,MAAM,IAAIJ,MAAM;IACpD;IACA,IAAI,CAACC,QAAQI,IAAI,IAAI,MAAM,IAAIL,MAAM;IACrC,MAAMM,QAAiBC,KAAKC,KAAK,CAACP;IAClC,IAAI,CAACK,SAAS,OAAOA,UAAU,YAAYG,MAAMC,OAAO,CAACJ,QAAQ,MAAM,IAAIN,MAAM;IACjF,MAAMW,QAAQL;IACd,IACEK,MAAMC,cAAc,KAAK,KACzB,CAAC;QAAC;QAAgB;QAAe;KAAiB,CAACC,QAAQ,CAACC,OAAOH,MAAML,KAAK,MAC9E,CAAC;QAAC;QAAQ;KAAU,CAACO,QAAQ,CAACC,OAAOH,MAAMI,KAAK,MAChD,CAACN,MAAMC,OAAO,CAACC,MAAMK,QAAQ,KAC7B,CAACL,MAAMK,QAAQ,CAACC,KAAK,CAAC,CAACC,IAAMA,KAAK,OAAOA,MAAM,YAAY,OAAOA,EAAEC,IAAI,KAAK,YAA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ai/agent-plugin-lifecycle/src/cli.ts"],"sourcesContent":["import { parseArgs } from 'node:util';\n\nimport { runLifecycle } from './runner.js';\n\nconst HELP = `agent-plugin-lifecycle\n\nUsage:\n agent-plugin-lifecycle run Dispatch an APM post-install/update/uninstall event from stdin\n agent-plugin-lifecycle check Report missing or failed plugin setup\n agent-plugin-lifecycle --help\n\nPolicy: ~/.config/agent-plugin-lifecycle/config.json\nAPM lock: ~/.apm/apm.lock.yaml (or $APM_HOME/apm.lock.yaml)\n`;\n\nasync function readEvent(): Promise<import('./runner.js').LifecycleEvent> {\n if (process.stdin.isTTY) throw new Error('run requires an APM event on stdin');\n let payload = '';\n for await (const chunk of process.stdin) {\n payload += chunk.toString();\n if (payload.length > 1024 * 1024) throw new Error('APM event exceeds 1 MiB');\n }\n if (!payload.trim()) throw new Error('run requires an APM event on stdin');\n const event: unknown = JSON.parse(payload);\n if (!event || typeof event !== 'object' || Array.isArray(event)) throw new Error('APM event must be an object');\n const value = event as Record<string, unknown>;\n if (\n value.schema_version !== 1 ||\n !['post-install', 'post-update', 'post-uninstall'].includes(String(value.event)) ||\n !['user', 'project'].includes(String(value.scope)) ||\n !Array.isArray(value.packages) ||\n !value.packages.every((p) => p && typeof p === 'object' && typeof p.name === 'string' && (p.reference === null || typeof p.reference === 'string'))\n ) {\n throw new Error('unsupported APM lifecycle event');\n }\n return value as unknown as import('./runner.js').LifecycleEvent;\n}\n\nasync function main(): Promise<number> {\n const { values, positionals } = parseArgs({\n args: process.argv.slice(2),\n options: { help: { type: 'boolean', short: 'h' } },\n allowPositionals: true,\n });\n if (values.help || positionals.length === 0) {\n process.stdout.write(HELP);\n return 0;\n }\n if (positionals.length !== 1 || !['run', 'check'].includes(positionals[0])) throw new Error('expected run or check; use --help');\n const event = positionals[0] === 'run' ? await readEvent() : undefined;\n if (event?.scope !== undefined && event.scope !== 'user') {\n console.log(`skipped APM ${event.scope} scope event`);\n return 0;\n }\n return runLifecycle(positionals[0] as 'run' | 'check', { apmHome: process.env.APM_HOME, event });\n}\n\nmain()\n .then((status) => {\n process.exitCode = status;\n })\n .catch((error: unknown) => {\n console.error(`agent-plugin-lifecycle: ${error instanceof Error ? error.message : String(error)}`);\n process.exitCode = 2;\n });\n"],"names":["parseArgs","runLifecycle","HELP","readEvent","process","stdin","isTTY","Error","payload","chunk","toString","length","trim","event","JSON","parse","Array","isArray","value","schema_version","includes","String","scope","packages","every","p","name","reference","main","values","positionals","args","argv","slice","options","help","type","short","allowPositionals","stdout","write","undefined","console","log","apmHome","env","APM_HOME","then","status","exitCode","catch","error","message"],"mappings":"AAAA,SAASA,SAAS,QAAQ,YAAY;AAEtC,SAASC,YAAY,QAAQ,cAAc;AAE3C,MAAMC,OAAO,CAAC;;;;;;;;;AASd,CAAC;AAED,eAAeC;IACb,IAAIC,QAAQC,KAAK,CAACC,KAAK,EAAE,MAAM,IAAIC,MAAM;IACzC,IAAIC,UAAU;IACd,WAAW,MAAMC,SAASL,QAAQC,KAAK,CAAE;QACvCG,WAAWC,MAAMC,QAAQ;QACzB,IAAIF,QAAQG,MAAM,GAAG,OAAO,MAAM,MAAM,IAAIJ,MAAM;IACpD;IACA,IAAI,CAACC,QAAQI,IAAI,IAAI,MAAM,IAAIL,MAAM;IACrC,MAAMM,QAAiBC,KAAKC,KAAK,CAACP;IAClC,IAAI,CAACK,SAAS,OAAOA,UAAU,YAAYG,MAAMC,OAAO,CAACJ,QAAQ,MAAM,IAAIN,MAAM;IACjF,MAAMW,QAAQL;IACd,IACEK,MAAMC,cAAc,KAAK,KACzB,CAAC;QAAC;QAAgB;QAAe;KAAiB,CAACC,QAAQ,CAACC,OAAOH,MAAML,KAAK,MAC9E,CAAC;QAAC;QAAQ;KAAU,CAACO,QAAQ,CAACC,OAAOH,MAAMI,KAAK,MAChD,CAACN,MAAMC,OAAO,CAACC,MAAMK,QAAQ,KAC7B,CAACL,MAAMK,QAAQ,CAACC,KAAK,CAAC,CAACC,IAAMA,KAAK,OAAOA,MAAM,YAAY,OAAOA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1
- {"version":3,"sources":["/Users/kevin/Dev/ai/agent-plugin-lifecycle/src/config.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\n\nexport type Platform = 'darwin' | 'linux' | 'win32';\nexport interface PluginPolicy {\n source: string;\n path?: string;\n skill?: string;\n 'post-install'?: string;\n 'post-update'?: string;\n 'post-uninstall'?: string;\n}\nexport interface Config {\n version: 1;\n plugins: PluginPolicy[];\n}\n\nfunction object(value: unknown, label: string, allowed: string[]): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(`${label} must be an object`);\n const result = value as Record<string, unknown>;\n const unknown = Object.keys(result).find((key) => !allowed.includes(key));\n if (unknown) throw new Error(`${label} has unknown field: ${unknown}`);\n return result;\n}\nfunction nonempty(value: unknown, label: string): string {\n if (typeof value !== 'string' || !value.trim()) throw new Error(`${label} must be a nonempty string`);\n return value;\n}\nfunction relativePath(value: unknown, label: string): string {\n const path = nonempty(value, label);\n if (path === '.') return path;\n if (path.startsWith('/') || path.startsWith('\\\\') || /^[A-Za-z]:/.test(path) || path.includes('\\\\') || path.split('/').some((part) => !part || part === '.' || part === '..')) {\n throw new Error(`${label} must be a safe relative POSIX path`);\n }\n return path;\n}\nexport function recordId(plugin: PluginPolicy): string {\n return JSON.stringify([plugin.source, plugin.path ?? '.', plugin.skill ?? null]);\n}\nexport function parseConfig(value: unknown): Config {\n const root = object(value, 'config', ['version', 'plugins']);\n if (root.version !== 1 || !Array.isArray(root.plugins)) throw new Error('config must have version 1 and a plugins array');\n const seen = new Set<string>();\n const plugins = root.plugins.map((raw, index): PluginPolicy => {\n const label = `plugins[${index}]`;\n const item = object(raw, label, ['source', 'path', 'skill', 'post-install', 'post-update', 'post-uninstall']);\n const source = nonempty(item.source, `${label}.source`);\n const path = item.path === undefined ? undefined : relativePath(item.path, `${label}.path`);\n const skill = item.skill === undefined ? undefined : nonempty(item.skill, `${label}.skill`);\n if (skill && (skill.includes('/') || skill.includes('\\\\') || skill === '.' || skill === '..')) throw new Error(`${label}.skill must be one directory name`);\n const plugin: PluginPolicy = { source, path, skill };\n for (const event of ['post-install', 'post-update', 'post-uninstall'] as const) {\n if (item[event] !== undefined) plugin[event] = nonempty(item[event], `${label}.${event}`);\n }\n const id = recordId(plugin);\n if (seen.has(id)) throw new Error(`${label} duplicates another source/path/skill record`);\n seen.add(id);\n return plugin;\n });\n return { version: 1, plugins };\n}\nexport async function loadConfig(path: string): Promise<Config> {\n return parseConfig(JSON.parse(await readFile(path, 'utf8')));\n}\n"],"names":["readFile","object","value","label","allowed","Array","isArray","Error","result","unknown","Object","keys","find","key","includes","nonempty","trim","relativePath","path","startsWith","test","split","some","part","recordId","plugin","JSON","stringify","source","skill","parseConfig","root","version","plugins","seen","Set","map","raw","index","item","undefined","event","id","has","add","loadConfig","parse"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,mBAAmB;AAgB5C,SAASC,OAAOC,KAAc,EAAEC,KAAa,EAAEC,OAAiB;IAC9D,IAAI,CAACF,SAAS,OAAOA,UAAU,YAAYG,MAAMC,OAAO,CAACJ,QAAQ,MAAM,IAAIK,MAAM,GAAGJ,MAAM,kBAAkB,CAAC;IAC7G,MAAMK,SAASN;IACf,MAAMO,UAAUC,OAAOC,IAAI,CAACH,QAAQI,IAAI,CAAC,CAACC,MAAQ,CAACT,QAAQU,QAAQ,CAACD;IACpE,IAAIJ,SAAS,MAAM,IAAIF,MAAM,GAAGJ,MAAM,oBAAoB,EAAEM,SAAS;IACrE,OAAOD;AACT;AACA,SAASO,SAASb,KAAc,EAAEC,KAAa;IAC7C,IAAI,OAAOD,UAAU,YAAY,CAACA,MAAMc,IAAI,IAAI,MAAM,IAAIT,MAAM,GAAGJ,MAAM,0BAA0B,CAAC;IACpG,OAAOD;AACT;AACA,SAASe,aAAaf,KAAc,EAAEC,KAAa;IACjD,MAAMe,OAAOH,SAASb,OAAOC;IAC7B,IAAIe,SAAS,KAAK,OAAOA;IACzB,IAAIA,KAAKC,UAAU,CAAC,QAAQD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AAA,MAAMf,QAAQ,CAAC,QAAQe,MAAMf,QAAQ,CAAC,SAASe,UAAU,OAAOA,UAAU,IAAG,GAAI,MAAM,IAAItB,MAAM,GAAGJ,MAAM,iCAAiC,CAAC;QAC1J,MAAMsB,SAAuB;YAAEG;YAAQV;YAAMW;QAAM;QACnD,KAAK,MAAMY,SAAS;YAAC;YAAgB;YAAe;SAAiB,CAAW;YAC9E,IAAIF,IAAI,CAACE,MAAM,KAAKD,WAAWf,MAAM,CAACgB,MAAM,GAAG1B,SAASwB,IAAI,CAACE,MAAM,EAAE,GAAGtC,MAAM,CAAC,EAAEsC,OAAO;QAC1F;QACA,MAAMC,KAAKlB,SAASC;QACpB,IAAIS,KAAKS,GAAG,CAACD,KAAK,MAAM,IAAInC,MAAM,GAAGJ,MAAM,4CAA4C,CAAC;QACxF+B,KAAKU,GAAG,CAACF;QACT,OAAOjB;IACT;IACA,OAAO;QAAEO,SAAS;QAAGC;IAAQ;AAC/B;AACA,OAAO,eAAeY,WAAW3B,IAAY;IAC3C,OAAOY,YAAYJ,KAAKoB,KAAK,CAAC,MAAM9C,SAASkB,MAAM;AACrD"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/agent-plugin-lifecycle/src/config.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\n\nexport type Platform = 'darwin' | 'linux' | 'win32';\nexport interface PluginPolicy {\n source: string;\n path?: string;\n skill?: string;\n 'post-install'?: string;\n 'post-update'?: string;\n 'post-uninstall'?: string;\n}\nexport interface Config {\n version: 1;\n plugins: PluginPolicy[];\n}\n\nfunction object(value: unknown, label: string, allowed: string[]): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(`${label} must be an object`);\n const result = value as Record<string, unknown>;\n const unknown = Object.keys(result).find((key) => !allowed.includes(key));\n if (unknown) throw new Error(`${label} has unknown field: ${unknown}`);\n return result;\n}\nfunction nonempty(value: unknown, label: string): string {\n if (typeof value !== 'string' || !value.trim()) throw new Error(`${label} must be a nonempty string`);\n return value;\n}\nfunction relativePath(value: unknown, label: string): string {\n const path = nonempty(value, label);\n if (path === '.') return path;\n if (path.startsWith('/') || path.startsWith('\\\\') || /^[A-Za-z]:/.test(path) || path.includes('\\\\') || path.split('/').some((part) => !part || part === '.' || part === '..')) {\n throw new Error(`${label} must be a safe relative POSIX path`);\n }\n return path;\n}\nexport function recordId(plugin: PluginPolicy): string {\n return JSON.stringify([plugin.source, plugin.path ?? '.', plugin.skill ?? null]);\n}\nexport function parseConfig(value: unknown): Config {\n const root = object(value, 'config', ['version', 'plugins']);\n if (root.version !== 1 || !Array.isArray(root.plugins)) throw new Error('config must have version 1 and a plugins array');\n const seen = new Set<string>();\n const plugins = root.plugins.map((raw, index): PluginPolicy => {\n const label = `plugins[${index}]`;\n const item = object(raw, label, ['source', 'path', 'skill', 'post-install', 'post-update', 'post-uninstall']);\n const source = nonempty(item.source, `${label}.source`);\n const path = item.path === undefined ? undefined : relativePath(item.path, `${label}.path`);\n const skill = item.skill === undefined ? undefined : nonempty(item.skill, `${label}.skill`);\n if (skill && (skill.includes('/') || skill.includes('\\\\') || skill === '.' || skill === '..')) throw new Error(`${label}.skill must be one directory name`);\n const plugin: PluginPolicy = { source, path, skill };\n for (const event of ['post-install', 'post-update', 'post-uninstall'] as const) {\n if (item[event] !== undefined) plugin[event] = nonempty(item[event], `${label}.${event}`);\n }\n const id = recordId(plugin);\n if (seen.has(id)) throw new Error(`${label} duplicates another source/path/skill record`);\n seen.add(id);\n return plugin;\n });\n return { version: 1, plugins };\n}\nexport async function loadConfig(path: string): Promise<Config> {\n return parseConfig(JSON.parse(await readFile(path, 'utf8')));\n}\n"],"names":["readFile","object","value","label","allowed","Array","isArray","Error","result","unknown","Object","keys","find","key","includes","nonempty","trim","relativePath","path","startsWith","test","split","some","part","recordId","plugin","JSON","stringify","source","skill","parseConfig","root","version","plugins","seen","Set","map","raw","index","item","undefined","event","id","has","add","loadConfig","parse"],"mappings":"AAAA,SAASA,QAA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U,GAAG,CAACF;QACT,OAAOjB;IACT;IACA,OAAO;QAAEO,SAAS;QAAGC;IAAQ;AAC/B;AACA,OAAO,eAAeY,WAAW3B,IAAY;IAC3C,OAAOY,YAAYJ,KAAKoB,KAAK,CAAC,MAAM9C,SAASkB,MAAM;AACrD"}
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/ai/agent-plugin-lifecycle/src/index.ts"],"sourcesContent":["export type { LockedPlugin } from './apm.js';\nexport { matchesSource, parseLock, sourceParts } from './apm.js';\nexport type { Config, PluginPolicy } from './config.js';\nexport { parseConfig, recordId } from './config.js';\nexport type { LifecycleEvent, Mode, RunOptions } from './runner.js';\nexport { runLifecycle } from './runner.js';\n"],"names":["matchesSource","parseLock","sourceParts","parseConfig","recordId","runLifecycle"],"mappings":"AACA,SAASA,aAAa,EAAEC,SAAS,EAAEC,WAAW,QAAQ,WAAW;AAEjE,SAASC,WAAW,EAAEC,QAAQ,QAAQ,cAAc;AAEpD,SAASC,YAAY,QAAQ,cAAc"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/agent-plugin-lifecycle/src/index.ts"],"sourcesContent":["export type { LockedPlugin } from './apm.js';\nexport { matchesSource, parseLock, sourceParts } from './apm.js';\nexport type { Config, PluginPolicy } from './config.js';\nexport { parseConfig, recordId } from './config.js';\nexport type { LifecycleEvent, Mode, RunOptions } from './runner.js';\nexport { runLifecycle } from './runner.js';\n"],"names":["matchesSource","parseLock","sourceParts","parseConfig","recordId","runLifecycle"],"mappings":"AACA,SAASA,aAAa,EAAEC,SAAS,EAAEC,WAAW,QAAQ,WAAW;AAEjE,SAASC,WAAW,EAAEC,QAAQ,QAAQ,cAAc;AAEpD,SAASC,YAAY,QAAQ,cAAc"}
@@ -22,59 +22,91 @@ async function existingWithin(root, path, label) {
22
22
  function pluginRoot(plugin, apmHome) {
23
23
  return join(apmHome, 'apm_modules', plugin.repo, plugin.path);
24
24
  }
25
+ function missing(error) {
26
+ return !!error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT';
27
+ }
28
+ async function existingOrNone(root, path, label) {
29
+ try {
30
+ return await existingWithin(root, path, label);
31
+ } catch (error) {
32
+ if (missing(error)) return undefined;
33
+ throw error;
34
+ }
35
+ }
36
+ const SKILL_ROOTS = [
37
+ '.agents/skills/',
38
+ '.hermes/skills/',
39
+ '.claude/skills/'
40
+ ];
41
+ function deployedSkillFolders(plugin, skill) {
42
+ const folders = new Set();
43
+ for (const file of plugin.deployedFiles){
44
+ const parts = file.split('/');
45
+ const index = parts.lastIndexOf('skills');
46
+ if (index < 0 || parts[index + 1] !== skill) continue;
47
+ const deployment = parts.slice(0, index + 2).join('/');
48
+ if (SKILL_ROOTS.some((candidate)=>deployment.startsWith(candidate))) folders.add(deployment);
49
+ }
50
+ return [
51
+ ...folders
52
+ ];
53
+ }
54
+ // APM's kept copy (`apm_modules/...`) is a destination only when the lock names no other copy: a target such as copilot reads it in place.
55
+ // When the lock names a native plugin root or deployed skill copies, the kept copy is APM's cache and is never used, even if the listed copies are missing on disk (they are skipped, and check reports them).
25
56
  async function destinations(plugin, policy, home, apmHome) {
26
- const output = new Set();
27
- const root = pluginRoot(plugin, apmHome);
57
+ var _plugin_nativePluginRoot;
58
+ const found = new Set();
59
+ const add = (path)=>{
60
+ if (path) found.add(path);
61
+ };
62
+ const nativeRoot = ((_plugin_nativePluginRoot = plugin.nativePluginRoot) === null || _plugin_nativePluginRoot === void 0 ? void 0 : _plugin_nativePluginRoot.startsWith('.agents/plugins/')) ? plugin.nativePluginRoot.slice('.agents/plugins/'.length) : undefined;
28
63
  if (!policy.skill) {
29
- output.add(await existingWithin(join(apmHome, 'apm_modules'), join(plugin.repo, plugin.path), 'kept plugin'));
30
- if (plugin.nativePluginRoot) {
31
- const nativeBase = join(home, '.agents', 'plugins');
32
- if (plugin.nativePluginRoot.startsWith('.agents/plugins/')) output.add(await existingWithin(nativeBase, plugin.nativePluginRoot.slice('.agents/plugins/'.length), 'native plugin'));
33
- }
34
- } else {
35
- var _plugin_nativePluginRoot;
36
- try {
37
- output.add(await existingWithin(root, `skills/${policy.skill}`, `kept skill ${policy.skill}`));
38
- } catch (error) {
39
- if (!(error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT')) throw error;
40
- }
41
- if ((_plugin_nativePluginRoot = plugin.nativePluginRoot) === null || _plugin_nativePluginRoot === void 0 ? void 0 : _plugin_nativePluginRoot.startsWith('.agents/plugins/')) {
42
- const nativeRoot = plugin.nativePluginRoot.slice('.agents/plugins/'.length);
43
- try {
44
- output.add(await existingWithin(join(home, '.agents', 'plugins'), `${nativeRoot}/skills/${policy.skill}`, `native skill ${policy.skill}`));
45
- } catch (error) {
46
- if (!(error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT')) throw error;
47
- }
48
- }
49
- for (const file of plugin.deployedFiles){
50
- const parts = file.split('/');
51
- const index = parts.lastIndexOf('skills');
52
- if (index < 0 || parts[index + 1] !== policy.skill) continue;
53
- const deployment = parts.slice(0, index + 2).join('/');
54
- const prefix = [
55
- '.agents/skills/',
56
- '.hermes/skills/',
57
- '.claude/skills/'
58
- ].find((candidate)=>deployment.startsWith(candidate));
59
- if (prefix) output.add(await existingWithin(home, deployment, `skill ${policy.skill}`));
60
- }
61
- if (output.size === 0) throw new Error(`no deployed copy found for skill ${policy.skill}`);
64
+ if (!nativeRoot) return [
65
+ await existingWithin(join(apmHome, 'apm_modules'), join(plugin.repo, plugin.path), 'kept plugin')
66
+ ];
67
+ add(await existingOrNone(join(home, '.agents', 'plugins'), nativeRoot, 'native plugin'));
68
+ if (!found.size) throw new Error(`no native plugin copy found for ${plugin.repo}`);
69
+ return [
70
+ ...found
71
+ ];
72
+ }
73
+ const deployed = deployedSkillFolders(plugin, policy.skill);
74
+ if (!nativeRoot && !deployed.length) {
75
+ const kept = await existingOrNone(pluginRoot(plugin, apmHome), `skills/${policy.skill}`, `kept skill ${policy.skill}`);
76
+ if (!kept) throw new Error(`no deployed copy found for skill ${policy.skill}`);
77
+ return [
78
+ kept
79
+ ];
62
80
  }
81
+ if (nativeRoot) add(await existingOrNone(join(home, '.agents', 'plugins'), `${nativeRoot}/skills/${policy.skill}`, `native skill ${policy.skill}`));
82
+ for (const deployment of deployed)add(await existingOrNone(home, deployment, `skill ${policy.skill}`));
83
+ if (!found.size) throw new Error(`no deployed copy found for skill ${policy.skill}`);
63
84
  return [
64
- ...output
85
+ ...found
65
86
  ];
66
87
  }
67
88
  async function readState(path) {
68
89
  if (!existsSync(path)) return {
69
- version: 1,
90
+ version: 2,
70
91
  receipts: {}
71
92
  };
72
93
  const value = JSON.parse(await readFile(path, 'utf8'));
73
94
  if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('state must be an object');
74
95
  const item = value;
75
- if (item.version !== 1 || !item.receipts || typeof item.receipts !== 'object' || Array.isArray(item.receipts)) throw new Error('unsupported state format');
76
- if (Object.values(item.receipts).some((receipt)=>typeof receipt !== 'string')) throw new Error('invalid state receipt');
77
- return item;
96
+ if (item.version !== 1 && item.version !== 2 || !item.receipts || typeof item.receipts !== 'object' || Array.isArray(item.receipts)) throw new Error('unsupported state format');
97
+ const receipts = {};
98
+ for (const [key, receipt] of Object.entries(item.receipts)){
99
+ if (item.version === 1 && typeof receipt === 'string') receipts[key] = {
100
+ digest: receipt,
101
+ revision: ''
102
+ };
103
+ else if (item.version === 2 && receipt && typeof receipt === 'object' && typeof receipt.digest === 'string' && typeof receipt.revision === 'string') receipts[key] = receipt;
104
+ else throw new Error('invalid state receipt');
105
+ }
106
+ return {
107
+ version: 2,
108
+ receipts
109
+ };
78
110
  }
79
111
  async function saveState(path, state) {
80
112
  const temp = join(dirname(path), `.state-${process.pid}-${Date.now()}.tmp`);
@@ -117,6 +149,13 @@ async function execute(command, cwd, environment) {
117
149
  shell: true
118
150
  });
119
151
  }
152
+ function receiptRecord(key) {
153
+ try {
154
+ return JSON.parse(key)[0];
155
+ } catch {
156
+ return undefined;
157
+ }
158
+ }
120
159
  function lockLoadError(error) {
121
160
  return !!error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT';
122
161
  }
@@ -137,6 +176,9 @@ export async function runLifecycle(mode, options = {}) {
137
176
  const apmDirectory = await stat(apmHome);
138
177
  if (!apmDirectory.isDirectory()) throw error;
139
178
  locked = [];
179
+ } else if (mode === 'check' && lockLoadError(error)) {
180
+ output('nothing installed');
181
+ return 0;
140
182
  } else throw error;
141
183
  }
142
184
  const statePath = join(dirname(configPath), 'state.json');
@@ -177,6 +219,11 @@ export async function runLifecycle(mode, options = {}) {
177
219
  return matchesSource(policy.source, plugin) && plugin.path === ((_policy_path = policy.path) !== null && _policy_path !== void 0 ? _policy_path : '.');
178
220
  });
179
221
  if (anyStillInstalled || !removedNameMatch) continue;
222
+ // APM keeps a folder holding files it did not write; report it, delete nothing
223
+ for (const key of receiptKeys){
224
+ const destination = JSON.parse(key)[1];
225
+ if (existsSync(destination)) output(`left ${destination}`);
226
+ }
180
227
  const command = policy['post-uninstall'];
181
228
  if (!command) {
182
229
  for (const key of receiptKeys)delete state.receipts[key];
@@ -197,6 +244,7 @@ export async function runLifecycle(mode, options = {}) {
197
244
  }
198
245
  if (mode === 'run' && !options.event) throw new Error('run requires an APM event');
199
246
  const event = (_ref = (_options_event2 = options.event) === null || _options_event2 === void 0 ? void 0 : _options_event2.event) !== null && _ref !== void 0 ? _ref : 'post-install';
247
+ let installed = 0;
200
248
  for (const policy of config.plugins){
201
249
  var _policy_postupdate;
202
250
  const command = event === 'post-update' ? (_policy_postupdate = policy['post-update']) !== null && _policy_postupdate !== void 0 ? _policy_postupdate : policy['post-install'] : policy['post-install'];
@@ -211,36 +259,75 @@ export async function runLifecycle(mode, options = {}) {
211
259
  continue;
212
260
  }
213
261
  if (!matches.length) {
214
- output(`skipped source not installed ${recordId(policy)}`);
262
+ if (mode === 'run') output(`skipped source not installed ${recordId(policy)}`);
215
263
  continue;
216
264
  }
265
+ installed++;
217
266
  const plugin = matches[0];
267
+ const id = recordId(policy);
218
268
  try {
219
- const found = await destinations(plugin, policy, home, apmHome);
269
+ const recorded = Object.keys(state.receipts).filter((key)=>receiptRecord(key) === id);
270
+ let found;
271
+ try {
272
+ found = await destinations(plugin, policy, home, apmHome);
273
+ } catch (error) {
274
+ // check still reports a copy that was recorded and is now gone
275
+ if (mode === 'check' && recorded.length && (missing(error) || error instanceof Error && error.message.startsWith('no '))) found = [];
276
+ else throw error;
277
+ }
278
+ const gone = recorded.filter((key)=>!existsSync(JSON.parse(key)[1]));
279
+ if (mode === 'run') {
280
+ // a copy that no longer exists loses its receipt, so the copy APM recreates in its place runs again
281
+ for (const key of gone)delete state.receipts[key];
282
+ if (gone.length) await saveState(statePath, state);
283
+ } else {
284
+ const validDigests = [
285
+ policy['post-install'],
286
+ policy['post-update']
287
+ ].filter((item)=>!!item).map((item)=>digest(policy, item));
288
+ for (const key of gone){
289
+ const receipt = state.receipts[key];
290
+ if (validDigests.includes(receipt.digest) && receipt.revision === plugin.revision) {
291
+ output(`broken ${id} ${JSON.parse(key)[1]}`);
292
+ failed++;
293
+ }
294
+ }
295
+ for (const destination of found){
296
+ const receipt = state.receipts[receiptKey(policy, destination)];
297
+ let status = 'missing';
298
+ if (receipt) {
299
+ const current = validDigests.includes(receipt.digest) && receipt.revision === plugin.revision;
300
+ status = current ? 'ok' : 'stale';
301
+ }
302
+ output(`${status} ${id} ${destination}`);
303
+ if (status !== 'ok') failed++;
304
+ }
305
+ continue;
306
+ }
220
307
  for (const destination of found){
221
308
  const key = receiptKey(policy, destination);
222
- if (mode === 'check') {
223
- const validDigests = [
224
- policy['post-install'],
225
- policy['post-update']
226
- ].filter((item)=>!!item).map((item)=>digest(policy, item));
227
- const ready = validDigests.includes(state.receipts[key]);
228
- output(`${ready ? 'ok' : 'missing'} ${recordId(policy)} ${destination}`);
229
- if (!ready) failed++;
230
- } else {
231
- delete state.receipts[key];
232
- await saveState(statePath, state);
233
- await execute(command, destination, environment);
234
- state.receipts[key] = digest(policy, command);
235
- await saveState(statePath, state);
236
- output(`ran ${recordId(policy)} ${destination}`);
309
+ const wanted = digest(policy, command);
310
+ const receipt = state.receipts[key];
311
+ if (receipt && receipt.digest === wanted && receipt.revision === plugin.revision) {
312
+ output(`current ${id} ${destination}`);
313
+ continue;
237
314
  }
315
+ delete state.receipts[key];
316
+ await saveState(statePath, state);
317
+ await execute(command, destination, environment);
318
+ state.receipts[key] = {
319
+ digest: wanted,
320
+ revision: plugin.revision
321
+ };
322
+ await saveState(statePath, state);
323
+ output(`ran ${id} ${destination}`);
238
324
  }
239
325
  } catch (error) {
240
- output(`failed ${recordId(policy)}: ${error instanceof Error ? error.message : String(error)}`);
326
+ output(`failed ${id}: ${error instanceof Error ? error.message : String(error)}`);
241
327
  failed++;
242
328
  }
243
329
  }
330
+ if (mode === 'check' && !installed && !failed) output('nothing installed');
244
331
  return failed ? 1 : 0;
245
332
  } finally{
246
333
  await (release === null || release === void 0 ? void 0 : release());