harnesstap 1.1.0 → 1.3.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.
- package/README.md +33 -16
- package/dist/apply-QSS4242W.js +67 -0
- package/dist/apply-QSS4242W.js.map +1 -0
- package/dist/approve-CNYQY6DC.js +181 -0
- package/dist/approve-CNYQY6DC.js.map +1 -0
- package/dist/audit-V4SUV7KA.js +434 -0
- package/dist/audit-V4SUV7KA.js.map +1 -0
- package/dist/auth-63FOHIQ3.js +220 -0
- package/dist/auth-63FOHIQ3.js.map +1 -0
- package/dist/bin.js +166 -0
- package/dist/bin.js.map +1 -0
- package/dist/chunk-2H7UOFLK.js +11 -0
- package/dist/chunk-2H7UOFLK.js.map +1 -0
- package/dist/chunk-2NE3QYMP.js +103 -0
- package/dist/chunk-2NE3QYMP.js.map +1 -0
- package/dist/chunk-2P2EOYEW.js +1140 -0
- package/dist/chunk-2P2EOYEW.js.map +1 -0
- package/dist/chunk-37E5M4JX.js +34 -0
- package/dist/chunk-37E5M4JX.js.map +1 -0
- package/dist/chunk-37LQQWMF.js +496 -0
- package/dist/chunk-37LQQWMF.js.map +1 -0
- package/dist/chunk-3FIWOI3H.js +98 -0
- package/dist/chunk-3FIWOI3H.js.map +1 -0
- package/dist/chunk-3PGC6OA3.js +540 -0
- package/dist/chunk-3PGC6OA3.js.map +1 -0
- package/dist/chunk-4IHKBIY3.js +118 -0
- package/dist/chunk-4IHKBIY3.js.map +1 -0
- package/dist/chunk-4ZUBRLSP.js +17 -0
- package/dist/chunk-4ZUBRLSP.js.map +1 -0
- package/dist/chunk-5F3LNDZG.js +9 -0
- package/dist/chunk-5F3LNDZG.js.map +1 -0
- package/dist/chunk-5TXI6BI2.js +1359 -0
- package/dist/chunk-5TXI6BI2.js.map +1 -0
- package/dist/chunk-6P5IO4BX.js +235 -0
- package/dist/chunk-6P5IO4BX.js.map +1 -0
- package/dist/chunk-ABXUKHAU.js +571 -0
- package/dist/chunk-ABXUKHAU.js.map +1 -0
- package/dist/chunk-AOUDSNRK.js +1357 -0
- package/dist/chunk-AOUDSNRK.js.map +1 -0
- package/dist/chunk-BNDJJAEI.js +311 -0
- package/dist/chunk-BNDJJAEI.js.map +1 -0
- package/dist/chunk-C2IWSFF5.js +818 -0
- package/dist/chunk-C2IWSFF5.js.map +1 -0
- package/dist/chunk-CHQGE2HF.js +283 -0
- package/dist/chunk-CHQGE2HF.js.map +1 -0
- package/dist/chunk-DEJLP7QJ.js +681 -0
- package/dist/chunk-DEJLP7QJ.js.map +1 -0
- package/dist/chunk-DJ6FN6EW.js +532 -0
- package/dist/chunk-DJ6FN6EW.js.map +1 -0
- package/dist/chunk-E4WRTRMH.js +1173 -0
- package/dist/chunk-E4WRTRMH.js.map +1 -0
- package/dist/chunk-E5QXNU3K.js +238 -0
- package/dist/chunk-E5QXNU3K.js.map +1 -0
- package/dist/chunk-EMTBGOR3.js +2959 -0
- package/dist/chunk-EMTBGOR3.js.map +1 -0
- package/dist/chunk-FFWYIGQ4.js +18 -0
- package/dist/chunk-FFWYIGQ4.js.map +1 -0
- package/dist/chunk-I6XFZLTJ.js +9 -0
- package/dist/chunk-I6XFZLTJ.js.map +1 -0
- package/dist/chunk-IHWAOIAU.js +172 -0
- package/dist/chunk-IHWAOIAU.js.map +1 -0
- package/dist/chunk-IHZUYG66.js +583 -0
- package/dist/chunk-IHZUYG66.js.map +1 -0
- package/dist/chunk-JQOKQKQT.js +158 -0
- package/dist/chunk-JQOKQKQT.js.map +1 -0
- package/dist/chunk-JRFUTIEH.js +426 -0
- package/dist/chunk-JRFUTIEH.js.map +1 -0
- package/dist/chunk-KCBI6JQC.js +115 -0
- package/dist/chunk-KCBI6JQC.js.map +1 -0
- package/dist/chunk-KDUQMINL.js +60 -0
- package/dist/chunk-KDUQMINL.js.map +1 -0
- package/dist/chunk-KLR2DURP.js +656 -0
- package/dist/chunk-KLR2DURP.js.map +1 -0
- package/dist/chunk-KRI4R7EM.js +25 -0
- package/dist/chunk-KRI4R7EM.js.map +1 -0
- package/dist/chunk-LYQMK6SV.js +87 -0
- package/dist/chunk-LYQMK6SV.js.map +1 -0
- package/dist/chunk-MK3Q37ZN.js +183 -0
- package/dist/chunk-MK3Q37ZN.js.map +1 -0
- package/dist/chunk-MSGAGV7B.js +346 -0
- package/dist/chunk-MSGAGV7B.js.map +1 -0
- package/dist/chunk-MZQRSERO.js +430 -0
- package/dist/chunk-MZQRSERO.js.map +1 -0
- package/dist/chunk-N3WIJXXM.js +691 -0
- package/dist/chunk-N3WIJXXM.js.map +1 -0
- package/dist/chunk-NAGAJ5UM.js +145 -0
- package/dist/chunk-NAGAJ5UM.js.map +1 -0
- package/dist/chunk-NFYPBTKO.js +302 -0
- package/dist/chunk-NFYPBTKO.js.map +1 -0
- package/dist/chunk-NPO2IG6G.js +491 -0
- package/dist/chunk-NPO2IG6G.js.map +1 -0
- package/dist/chunk-OS6NUIBJ.js +38 -0
- package/dist/chunk-OS6NUIBJ.js.map +1 -0
- package/dist/chunk-PFUK3HJ4.js +296 -0
- package/dist/chunk-PFUK3HJ4.js.map +1 -0
- package/dist/chunk-PMQ55GDB.js +115 -0
- package/dist/chunk-PMQ55GDB.js.map +1 -0
- package/dist/chunk-QIVE2YFJ.js +514 -0
- package/dist/chunk-QIVE2YFJ.js.map +1 -0
- package/dist/chunk-QKXD3EUF.js +691 -0
- package/dist/chunk-QKXD3EUF.js.map +1 -0
- package/dist/chunk-RNQYUWF6.js +32 -0
- package/dist/chunk-RNQYUWF6.js.map +1 -0
- package/dist/chunk-S2E4SSQV.js +41 -0
- package/dist/chunk-S2E4SSQV.js.map +1 -0
- package/dist/chunk-SN4BXX3B.js +186 -0
- package/dist/chunk-SN4BXX3B.js.map +1 -0
- package/dist/chunk-SNVAMWB7.js +40 -0
- package/dist/chunk-SNVAMWB7.js.map +1 -0
- package/dist/chunk-T5VRREN4.js +696 -0
- package/dist/chunk-T5VRREN4.js.map +1 -0
- package/dist/chunk-TKBMHZTS.js +10945 -0
- package/dist/chunk-TKBMHZTS.js.map +1 -0
- package/dist/chunk-TNJPTUE4.js +35 -0
- package/dist/chunk-TNJPTUE4.js.map +1 -0
- package/dist/chunk-TQ2NA4Z4.js +24 -0
- package/dist/chunk-TQ2NA4Z4.js.map +1 -0
- package/dist/chunk-TXXDMDPN.js +998 -0
- package/dist/chunk-TXXDMDPN.js.map +1 -0
- package/dist/chunk-UWXUBU7V.js +184 -0
- package/dist/chunk-UWXUBU7V.js.map +1 -0
- package/dist/chunk-UYRK2H24.js +141 -0
- package/dist/chunk-UYRK2H24.js.map +1 -0
- package/dist/chunk-V4IXIM3C.js +806 -0
- package/dist/chunk-V4IXIM3C.js.map +1 -0
- package/dist/chunk-VFHVXXP4.js +6438 -0
- package/dist/chunk-VFHVXXP4.js.map +1 -0
- package/dist/chunk-VQVUJYYY.js +244 -0
- package/dist/chunk-VQVUJYYY.js.map +1 -0
- package/dist/chunk-VZQG2JDV.js +9 -0
- package/dist/chunk-VZQG2JDV.js.map +1 -0
- package/dist/chunk-W7HQ5X3S.js +610 -0
- package/dist/chunk-W7HQ5X3S.js.map +1 -0
- package/dist/chunk-WMSQAFK5.js +65 -0
- package/dist/chunk-WMSQAFK5.js.map +1 -0
- package/dist/chunk-WMYTBJPB.js +364 -0
- package/dist/chunk-WMYTBJPB.js.map +1 -0
- package/dist/chunk-WNLFNCOH.js +7795 -0
- package/dist/chunk-WNLFNCOH.js.map +1 -0
- package/dist/chunk-WRX7CB2M.js +6448 -0
- package/dist/chunk-WRX7CB2M.js.map +1 -0
- package/dist/chunk-XGTTOO4R.js +84 -0
- package/dist/chunk-XGTTOO4R.js.map +1 -0
- package/dist/chunk-YSXRBUR4.js +682 -0
- package/dist/chunk-YSXRBUR4.js.map +1 -0
- package/dist/chunk-YTC2EG64.js +1759 -0
- package/dist/chunk-YTC2EG64.js.map +1 -0
- package/dist/compile-J3UGQSS3.js +161 -0
- package/dist/compile-J3UGQSS3.js.map +1 -0
- package/dist/config-5BPSZND3.js +438 -0
- package/dist/config-5BPSZND3.js.map +1 -0
- package/dist/doctor-BVFKLJVO.js +111 -0
- package/dist/doctor-BVFKLJVO.js.map +1 -0
- package/dist/environment-3RI5H32O.js +2745 -0
- package/dist/environment-3RI5H32O.js.map +1 -0
- package/dist/github-YFJQVH5K.js +114 -0
- package/dist/github-YFJQVH5K.js.map +1 -0
- package/dist/harness-ECGHPEKA.js +746 -0
- package/dist/harness-ECGHPEKA.js.map +1 -0
- package/dist/help-ELPNPPEM.js +2079 -0
- package/dist/help-ELPNPPEM.js.map +1 -0
- package/dist/help-UL5XLY3I.js +1892 -0
- package/dist/help-UL5XLY3I.js.map +1 -0
- package/dist/index.d.ts +164 -1
- package/dist/index.js +50 -54362
- package/dist/index.js.map +1 -1
- package/dist/init-UJQTDHW7.js +873 -0
- package/dist/init-UJQTDHW7.js.map +1 -0
- package/dist/lock-XUMJ63NZ.js +455 -0
- package/dist/lock-XUMJ63NZ.js.map +1 -0
- package/dist/marketplace-ZUMOLVXE.js +495 -0
- package/dist/marketplace-ZUMOLVXE.js.map +1 -0
- package/dist/mcp-RZA5O2ND.js +202 -0
- package/dist/mcp-RZA5O2ND.js.map +1 -0
- package/dist/migrate-CYQI2FH6.js +1043 -0
- package/dist/migrate-CYQI2FH6.js.map +1 -0
- package/dist/open-AWOAWLKO.js +32 -0
- package/dist/open-AWOAWLKO.js.map +1 -0
- package/dist/pack-2QD5ZUIO.js +99 -0
- package/dist/pack-2QD5ZUIO.js.map +1 -0
- package/dist/plugin-GQSSSFX4.js +64 -0
- package/dist/plugin-GQSSSFX4.js.map +1 -0
- package/dist/plugin-from-project-SIQUFYIO.js +16 -0
- package/dist/plugin-from-project-SIQUFYIO.js.map +1 -0
- package/dist/policy-CT4JRCJI.js +105 -0
- package/dist/policy-CT4JRCJI.js.map +1 -0
- package/dist/profile-4JQ6LECP.js +1886 -0
- package/dist/profile-4JQ6LECP.js.map +1 -0
- package/dist/project-JG7QWXRG.js +1392 -0
- package/dist/project-JG7QWXRG.js.map +1 -0
- package/dist/resource-QRMR6CSD.js +555 -0
- package/dist/resource-QRMR6CSD.js.map +1 -0
- package/dist/version-LZ5POOXY.js +17 -0
- package/dist/version-LZ5POOXY.js.map +1 -0
- package/package.json +25 -14
- package/schemas/ap-package.v1.json +36 -0
- package/schemas/fixtures/catalog-missing-schema.ap.json +13 -0
- package/schemas/fixtures/confidence.ap.json +13 -0
- package/schemas/fixtures/context7.ap.json +13 -0
- package/schemas/fixtures/minimal-with-schema.ap.json +13 -0
- package/schemas/fixtures/superpowers.ap.json +13 -0
- package/schemas/fixtures/third-party-skills.ap.json +13 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/services/materialization-ownership.ts","../src/models/resource-materialization.ts","../src/services/shared-emit-paths.ts","../src/models/preexisting-path.ts","../src/services/deploy-gate.ts","../src/services/environment-cascade.ts","../src/services/resource-classification.ts","../src/services/secret-resolver.ts","../src/services/environment-session.ts","../src/services/environment-commands.ts","../src/services/project-drift.ts","../src/services/git.ts","../src/services/project-status-payload.ts","../src/models/global-apply-snapshot.ts","../src/services/active-profile.ts","../src/services/profile-apply.ts","../src/services/applier.ts","../src/platforms/claude-plugin-extensions.ts","../src/services/cursor-host-managed-skills.ts","../src/services/host-plugin-material.ts","../src/services/host-native-mcp.ts","../src/plugins/providers/cursor.ts","../src/plugins/refresh-cache.ts","../src/plugins/cursor-local-install.ts","../src/services/link-materialize.ts","../src/services/profile-commit-resource.ts","../src/services/plugin-apply-merge.ts","../src/services/resource-editor-path.ts","../src/services/resource-apply-selector.ts","../src/services/profile-contents.ts","../src/services/profile-harness-sync.ts","../src/services/profile-untracked-resources.ts","../src/services/project-scan-status.ts","../src/services/safe-file-removal.ts","../src/models/apply-removal-backup.ts","../src/services/snapshot-capture.ts","../src/services/file-contents-drift.ts","../src/utils/json-equal.ts","../src/services/global-profile-cleanup.ts","../src/services/host-config-strip.ts","../src/services/plugin-install-conflicts.ts","../src/services/plugin-catalog-install.ts","../src/plugins/providers/claude-code.ts","../src/plugins/providers/copilot-cli.ts","../src/plugins/providers/goose.ts","../src/plugins/registry.ts","../src/services/plugin-install.ts","../src/services/plugin-apply-validation.ts","../src/services/upstream-plugin.ts","../src/services/claude-marketplace-bootstrap.ts","../src/services/cursor-marketplace-bootstrap.ts","../src/services/plugin-pin-apply.ts","../src/services/profile-apply-lock.ts","../src/services/profile-commands.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport type {\n MaterializationAction,\n MaterializationScope,\n Resource,\n SerializedFile,\n SerializeOptions,\n SerializerTarget,\n} from \"../types.js\";\nimport { getDb } from \"../db/connection.js\";\nimport { formatResourceSelector } from \"../models/resource.js\";\nimport {\n recordResourceMaterialization,\n} from \"../models/resource-materialization.js\";\nimport { isMergeableHostConfigPath } from \"./merged-host-config.js\";\nimport { getPlatformSerializer } from \"./platform-serializers.js\";\n\nfunction normalizeFileContent(content: string): string {\n return content.replace(/\\r\\n/g, \"\\n\").replace(/\\n+$/, \"\");\n}\n\nexport function hashGeneratedContent(content: string): string {\n const hex = createHash(\"sha256\")\n .update(normalizeFileContent(content), \"utf8\")\n .digest(\"hex\");\n return `sha256:${hex}`;\n}\n\nfunction ownershipKey(resource: Pick<Resource, \"type\" | \"name\" | \"namespace\">): string {\n return formatResourceSelector(resource, { includeType: true });\n}\n\nfunction actionForPath(\n path: string,\n shared: boolean,\n): MaterializationAction {\n if (shared || isMergeableHostConfigPath(path)) {\n return \"edit-file\";\n }\n return \"delete-file\";\n}\n\nexport async function attachResourceOwnership(\n files: SerializedFile[],\n resources: Resource[],\n context: {\n platformId: string;\n rootPath: string;\n target: SerializerTarget;\n serializeOptions?: Omit<SerializeOptions, \"target\">;\n },\n): Promise<SerializedFile[]> {\n if (resources.length === 0 || files.length === 0) {\n return files;\n }\n\n const serializer = getPlatformSerializer(context.platformId);\n const serializeOptions: SerializeOptions = {\n target: context.target,\n ...context.serializeOptions,\n };\n const pathToResourceIds = new Map<string, Set<string>>();\n\n for (const resource of resources) {\n const singleFiles = await serializer.serialize(\n [resource],\n context.rootPath,\n serializeOptions,\n );\n for (const file of singleFiles) {\n const ids = pathToResourceIds.get(file.path) ?? new Set<string>();\n ids.add(resource.id);\n pathToResourceIds.set(file.path, ids);\n }\n }\n\n const resourceById = new Map(resources.map((resource) => [resource.id, resource]));\n\n return files.map((file) => {\n const contributorIds = pathToResourceIds.get(file.path);\n if (!contributorIds || contributorIds.size === 0) {\n return file;\n }\n\n const shared = contributorIds.size > 1;\n const ownership = [...contributorIds].flatMap((resourceId) => {\n const resource = resourceById.get(resourceId);\n if (!resource) {\n return [];\n }\n const action = actionForPath(file.path, shared);\n return [{\n resource_id: resourceId,\n action,\n ownership_key: ownershipKey(resource),\n managed_container: action === \"delete-directory\",\n }];\n });\n\n return ownership.length > 0 ? { ...file, ownership } : file;\n });\n}\n\nexport function persistWrittenMaterializations(input: {\n scope: MaterializationScope;\n project_id?: string | null;\n root_path: string;\n platformResults: Array<{\n platformId: string;\n files: SerializedFile[];\n writtenPaths: string[];\n }>;\n}): void {\n const projectId = input.project_id ?? null;\n\n for (const result of input.platformResults) {\n // Only rows for bytes we actually wrote. Skipping a live file must not\n // rewrite generated_hash, or a later removal would treat user edits as owned.\n const writtenPaths = new Set(result.writtenPaths);\n const entries = result.files.flatMap((file) => {\n if (!writtenPaths.has(file.path) || !file.ownership?.length) {\n return [];\n }\n const generatedHash = hashGeneratedContent(file.content);\n return file.ownership.map((ownership) => ({\n resource_id: ownership.resource_id,\n path: file.path,\n action: ownership.action,\n ownership_key: ownership.ownership_key,\n generated_hash: generatedHash,\n managed_container: ownership.managed_container,\n }));\n });\n\n for (const entry of entries) {\n try {\n if (\n !getDb().prepare(\"SELECT 1 as ok FROM resources WHERE id = ? LIMIT 1\").get(entry.resource_id)\n ) {\n continue;\n }\n } catch {\n continue;\n }\n recordResourceMaterialization({\n resource_id: entry.resource_id,\n scope: input.scope,\n project_id: projectId,\n root_path: input.root_path,\n platform_id: result.platformId,\n path: entry.path,\n action: entry.action,\n ownership_key: entry.ownership_key,\n generated_hash: entry.generated_hash,\n managed_container: entry.managed_container,\n });\n }\n }\n}\n","import { getDb } from \"../db/connection.js\";\nimport { ulid } from \"ulid\";\nimport type {\n MaterializationAction,\n MaterializationScope,\n ResourceMaterialization,\n} from \"../types.js\";\n\ninterface ResourceMaterializationRow {\n id: string;\n resource_id: string;\n scope: MaterializationScope;\n project_id: string | null;\n root_path: string;\n platform_id: string;\n path: string;\n action: MaterializationAction;\n ownership_key: string;\n generated_hash: string;\n managed_container: number;\n created_at: string;\n updated_at: string;\n}\n\nfunction rowToMaterialization(\n row: ResourceMaterializationRow,\n): ResourceMaterialization {\n return {\n ...row,\n managed_container: row.managed_container === 1,\n };\n}\n\nfunction queryMaterializations(\n sql: string,\n params: unknown[],\n): ResourceMaterializationRow[] {\n try {\n return getDb().prepare(sql).all(...params) as ResourceMaterializationRow[];\n } catch {\n return [];\n }\n}\n\nexport function recordResourceMaterialization(input: {\n resource_id: string;\n scope: MaterializationScope;\n project_id?: string | null;\n root_path: string;\n platform_id: string;\n path: string;\n action: MaterializationAction;\n ownership_key: string;\n generated_hash: string;\n managed_container?: boolean;\n}): ResourceMaterialization {\n const db = getDb();\n const now = new Date().toISOString();\n const projectId = input.project_id ?? null;\n const managedContainer = input.managed_container ? 1 : 0;\n\n const existing = db\n .prepare(\n `SELECT id FROM resource_materializations\n WHERE resource_id = ?\n AND scope = ?\n AND project_id IS ?\n AND root_path = ?\n AND platform_id = ?\n AND path = ?\n AND ownership_key = ?`,\n )\n .get(\n input.resource_id,\n input.scope,\n projectId,\n input.root_path,\n input.platform_id,\n input.path,\n input.ownership_key,\n ) as { id: string } | undefined;\n\n if (existing) {\n db.prepare(\n `UPDATE resource_materializations\n SET action = ?,\n generated_hash = ?,\n managed_container = ?,\n updated_at = ?\n WHERE id = ?`,\n ).run(\n input.action,\n input.generated_hash,\n managedContainer,\n now,\n existing.id,\n );\n\n const row = db\n .prepare(\"SELECT * FROM resource_materializations WHERE id = ?\")\n .get(existing.id) as ResourceMaterializationRow;\n return rowToMaterialization(row);\n }\n\n const id = ulid();\n db.prepare(\n `INSERT INTO resource_materializations (\n id, resource_id, scope, project_id, root_path, platform_id, path,\n action, ownership_key, generated_hash, managed_container, created_at, updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n ).run(\n id,\n input.resource_id,\n input.scope,\n projectId,\n input.root_path,\n input.platform_id,\n input.path,\n input.action,\n input.ownership_key,\n input.generated_hash,\n managedContainer,\n now,\n now,\n );\n\n return {\n id,\n resource_id: input.resource_id,\n scope: input.scope,\n project_id: projectId,\n root_path: input.root_path,\n platform_id: input.platform_id,\n path: input.path,\n action: input.action,\n ownership_key: input.ownership_key,\n generated_hash: input.generated_hash,\n managed_container: input.managed_container ?? false,\n created_at: now,\n updated_at: now,\n };\n}\n\nexport function listMaterializationsForRoot(\n rootPath: string,\n): ResourceMaterialization[] {\n return queryMaterializations(\n `SELECT * FROM resource_materializations\n WHERE root_path = ?\n ORDER BY path ASC`,\n [rootPath],\n ).map(rowToMaterialization);\n}\n\nexport function listMaterializationsForRootPath(\n rootPath: string,\n relativePath: string,\n): ResourceMaterialization[] {\n return queryMaterializations(\n `SELECT * FROM resource_materializations\n WHERE root_path = ?\n AND path = ?`,\n [rootPath, relativePath],\n ).map(rowToMaterialization);\n}\n\nexport function deleteMaterializationsForRootPaths(\n rootPath: string,\n relativePaths: readonly string[],\n): void {\n if (relativePaths.length === 0) {\n return;\n }\n const db = getDb();\n const stmt = db.prepare(\n `DELETE FROM resource_materializations\n WHERE root_path = ?\n AND path = ?`,\n );\n for (const relativePath of relativePaths) {\n stmt.run(rootPath, relativePath);\n }\n}\n\nexport function listResourceMaterializations(\n resourceId: string,\n): ResourceMaterialization[] {\n const db = getDb();\n const rows = db\n .prepare(\n `SELECT * FROM resource_materializations\n WHERE resource_id = ?\n ORDER BY created_at ASC`,\n )\n .all(resourceId) as ResourceMaterializationRow[];\n return rows.map(rowToMaterialization);\n}\n\nexport function deleteResourceMaterializations(resourceId: string): number {\n const db = getDb();\n const result = db\n .prepare(\"DELETE FROM resource_materializations WHERE resource_id = ?\")\n .run(resourceId);\n return result.changes;\n}\n\nexport function replaceMaterializationsForPlatform(input: {\n scope: MaterializationScope;\n project_id?: string | null;\n root_path: string;\n platform_id: string;\n entries: Array<{\n resource_id: string;\n path: string;\n action: MaterializationAction;\n ownership_key: string;\n generated_hash: string;\n managed_container: boolean;\n }>;\n}): void {\n const db = getDb();\n const projectId = input.project_id ?? null;\n const entries = input.entries.filter((entry) =>\n db.prepare(\"SELECT 1 as ok FROM resources WHERE id = ? LIMIT 1\").get(entry.resource_id),\n );\n if (entries.length === 0 && input.entries.length > 0) {\n return;\n }\n\n db.prepare(\n `DELETE FROM resource_materializations\n WHERE scope = ?\n AND project_id IS ?\n AND root_path = ?\n AND platform_id = ?`,\n ).run(input.scope, projectId, input.root_path, input.platform_id);\n\n for (const entry of entries) {\n recordResourceMaterialization({\n resource_id: entry.resource_id,\n scope: input.scope,\n project_id: projectId,\n root_path: input.root_path,\n platform_id: input.platform_id,\n path: entry.path,\n action: entry.action,\n ownership_key: entry.ownership_key,\n generated_hash: entry.generated_hash,\n managed_container: entry.managed_container,\n });\n }\n}\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { getPlatform } from \"../platforms/registry.js\";\nimport type { SerializedFile, SerializerTarget } from \"../types.js\";\nimport type { ApplyResult } from \"./applier.js\";\nimport { isPreexistingPath } from \"../models/preexisting-path.js\";\nimport {\n listMaterializationsForRoot,\n listMaterializationsForRootPath,\n} from \"../models/resource-materialization.js\";\n\nconst SKILL_FILE_RE = /^(.*)\\/skills\\/([^/]+)\\/(.*)$/;\n\nexport interface SkillFileRef {\n skillsDir: string;\n name: string;\n rest: string;\n}\n\nexport function normalizeSkillDir(raw: string | undefined): string | undefined {\n if (!raw) return undefined;\n let normalized = raw.replace(/\\\\/g, \"/\").replace(/\\/+$/, \"\");\n if (normalized.startsWith(\"~/\")) {\n normalized = normalized.slice(2);\n }\n if (!normalized) return undefined;\n return `${normalized}/`;\n}\n\nexport function parseSkillEmitPath(path: string): SkillFileRef | undefined {\n const normalized = path.replace(/\\\\/g, \"/\");\n // Host plugin install trees often contain skills/; those are not harness skill emits.\n if (/(^|\\/)plugins\\//.test(normalized)) return undefined;\n const match = SKILL_FILE_RE.exec(normalized);\n if (!match) return undefined;\n const prefix = match[1];\n const name = match[2];\n const rest = match[3];\n if (prefix === undefined || !name || rest === undefined) return undefined;\n return {\n skillsDir: `${prefix}/skills/`,\n name,\n rest,\n };\n}\n\nfunction projectCompatFromRelated(path: string): string | undefined {\n const normalized = normalizeSkillDir(path);\n if (normalized === \".claude/skills/\" || normalized === \".agents/skills/\") {\n return normalized;\n }\n return undefined;\n}\n\n/** Directories this harness can read for skills (native, alternates, documented compat). */\nexport function skillConsumeDirs(\n platformId: string,\n target: SerializerTarget,\n): string[] {\n const platform = getPlatform(platformId);\n if (!platform) return [];\n const paths = target === \"global\" ? platform.globalPaths : platform.projectPaths;\n const dirs: string[] = [];\n const add = (raw?: string): void => {\n const normalized = normalizeSkillDir(raw);\n if (normalized && !dirs.includes(normalized)) {\n dirs.push(normalized);\n }\n };\n\n add(paths.skills);\n for (const alternate of paths.pathAlternates?.skills ?? []) {\n add(alternate);\n }\n for (const related of platform.relatedLocations ?? []) {\n if (!related.surfaces.includes(\"skills\")) continue;\n add(related.path);\n if (target === \"project\") {\n add(projectCompatFromRelated(related.path));\n }\n }\n if (target === \"global\") {\n const projectSkills = platform.projectPaths.skills;\n if (projectSkills?.startsWith(\".agents/\")) {\n add(projectSkills);\n }\n }\n return dirs;\n}\n\nexport function sharedSkillDirRank(dir: string): number {\n const normalized = normalizeSkillDir(dir) ?? dir;\n if (normalized === \".agents/skills/\") return 2;\n if (normalized === \".claude/skills/\") return 1;\n return 0;\n}\n\nfunction preferredSharedDir(\n platformIds: readonly string[],\n target: SerializerTarget,\n): string | undefined {\n const consumerCounts = new Map<string, number>();\n for (const platformId of platformIds) {\n const seen = new Set<string>();\n for (const dir of skillConsumeDirs(platformId, target)) {\n if (seen.has(dir)) continue;\n seen.add(dir);\n consumerCounts.set(dir, (consumerCounts.get(dir) ?? 0) + 1);\n }\n }\n let best: string | undefined;\n let bestRank = 0;\n for (const [dir, count] of consumerCounts) {\n if (count < 2) continue;\n const rank = sharedSkillDirRank(dir);\n if (rank > bestRank) {\n best = dir;\n bestRank = rank;\n }\n }\n return bestRank > 0 ? best : undefined;\n}\n\nfunction dropSkillTree(\n files: SerializedFile[],\n name: string,\n): SerializedFile[] {\n return files.filter((file) => {\n const parsed = parseSkillEmitPath(file.path);\n return parsed?.name !== name;\n });\n}\n\n/**\n * When two or more configured harnesses can read a shared skill tree\n * (`.agents/skills` first, then Claude-compat), emit once there and drop\n * native copies for those consumers. Harnesses that cannot read the shared\n * tree keep their native emit.\n */\nexport function preferSharedSkillEmits(\n results: ApplyResult[],\n platformIds: readonly string[],\n target: SerializerTarget,\n options?: { skipSkillNames?: ReadonlySet<string> },\n): ApplyResult[] {\n const preferredDir = preferredSharedDir(platformIds, target);\n if (!preferredDir) {\n return results;\n }\n\n const consume = new Map(\n platformIds.map((id) => [id, new Set(skillConsumeDirs(id, target))]),\n );\n const skillNames = new Set<string>();\n for (const result of results) {\n for (const file of result.files) {\n const parsed = parseSkillEmitPath(file.path);\n if (parsed) skillNames.add(parsed.name);\n }\n }\n\n const next = results.map((result) => ({\n ...result,\n files: [...result.files],\n }));\n const host =\n next.find((result) => consume.get(result.platformId)?.has(preferredDir))\n ?? next[0];\n if (!host) {\n return results;\n }\n\n for (const name of skillNames) {\n if (options?.skipSkillNames?.has(name)) {\n continue;\n }\n placeSkillOnHost(next, host, name, preferredDir, consume);\n }\n\n return next;\n}\n\nfunction skillRelativePath(dir: string, name: string): string {\n return `${dir}${name}/SKILL.md`.replace(/^\\.\\//, \"\");\n}\n\nfunction isUnmanagedLiveSkill(\n rootPath: string,\n relativePath: string,\n): boolean {\n if (isPreexistingPath(rootPath, relativePath)) {\n return true;\n }\n return listMaterializationsForRootPath(rootPath, relativePath).length === 0;\n}\n\nfunction existingUnmanagedSkillConsumeDir(\n rootPath: string,\n name: string,\n consumeDirs: readonly string[],\n): string | undefined {\n let best: string | undefined;\n let bestRank = -1;\n for (const dir of consumeDirs) {\n const relative = skillRelativePath(dir, name);\n if (!existsSync(join(rootPath, relative))) {\n continue;\n }\n if (!isUnmanagedLiveSkill(rootPath, relative)) {\n continue;\n }\n const rank = sharedSkillDirRank(dir);\n if (rank > bestRank) {\n best = dir;\n bestRank = rank;\n }\n }\n return best;\n}\n\nfunction addSkillPlacement(\n placements: Map<string, string[]>,\n name: string,\n skillsDir: string,\n): void {\n const dirs = placements.get(name) ?? [];\n if (!dirs.includes(skillsDir)) {\n dirs.push(skillsDir);\n }\n placements.set(name, dirs);\n}\n\nexport function collectManagedSkillPlacements(rootPath: string): Map<string, string[]> {\n const placements = new Map<string, string[]>();\n for (const row of listMaterializationsForRoot(rootPath)) {\n const parsed = parseSkillEmitPath(row.path);\n if (!parsed || parsed.rest !== \"SKILL.md\") {\n continue;\n }\n addSkillPlacement(placements, parsed.name, parsed.skillsDir);\n }\n return placements;\n}\n\n/** Build skill-name -> emit dirs from a previous apply lock or materialization path set. */\nexport function skillPlacementsFromPaths(\n paths: Iterable<string>,\n): Map<string, string[]> {\n const placements = new Map<string, string[]>();\n for (const path of paths) {\n const parsed = parseSkillEmitPath(path);\n if (!parsed || parsed.rest !== \"SKILL.md\") {\n continue;\n }\n addSkillPlacement(placements, parsed.name, parsed.skillsDir);\n }\n return placements;\n}\n\nfunction collectSkillTreeByRest(\n results: ApplyResult[],\n name: string,\n): Map<string, SerializedFile> {\n const byRest = new Map<string, SerializedFile>();\n for (const result of results) {\n for (const file of result.files) {\n const parsed = parseSkillEmitPath(file.path);\n if (parsed?.name !== name) continue;\n if (!byRest.has(parsed.rest)) {\n byRest.set(parsed.rest, file);\n }\n }\n }\n return byRest;\n}\n\nfunction placeSkillOnHost(\n results: ApplyResult[],\n host: ApplyResult,\n name: string,\n destDir: string,\n consume: ReadonlyMap<string, ReadonlySet<string>>,\n): void {\n const byRest = collectSkillTreeByRest(results, name);\n if (byRest.size === 0) {\n return;\n }\n for (const result of results) {\n if (consume.get(result.platformId)?.has(destDir)) {\n result.files = dropSkillTree(result.files, name);\n }\n }\n const seen = new Set(host.files.map((file) => file.path.replace(/\\\\/g, \"/\")));\n for (const [rest, file] of byRest) {\n const path = `${destDir}${name}/${rest}`;\n if (seen.has(path)) continue;\n seen.add(path);\n host.files.push({ ...file, path });\n }\n}\n\nfunction placeSkillOnDirs(\n results: ApplyResult[],\n name: string,\n destDirs: readonly string[],\n consume: ReadonlyMap<string, ReadonlySet<string>>,\n fallbackHost?: ApplyResult,\n): void {\n const uniqueDirs = [...new Set(destDirs.filter(Boolean))];\n if (uniqueDirs.length === 0) {\n return;\n }\n const byRest = collectSkillTreeByRest(results, name);\n if (byRest.size === 0) {\n return;\n }\n\n for (const result of results) {\n result.files = dropSkillTree(result.files, name);\n }\n\n for (const destDir of uniqueDirs) {\n const host =\n results.find((result) => consume.get(result.platformId)?.has(destDir))\n ?? fallbackHost\n ?? results[0];\n if (!host) {\n continue;\n }\n const seen = new Set(host.files.map((file) => file.path.replace(/\\\\/g, \"/\")));\n for (const [rest, file] of byRest) {\n const path = `${destDir}${name}/${rest}`;\n if (seen.has(path)) continue;\n seen.add(path);\n host.files.push({ ...file, path });\n }\n }\n}\n\n/**\n * Pin skill emits to previous apply placements (all of them) or, on first\n * apply, to a genuinely unmanaged live skill path. Disk existence of a\n * shared dir such as `.agents/skills` must not relocate a later apply.\n */\nexport function pinSkillEmitsToExistingLivePaths(\n rootPath: string,\n results: ApplyResult[],\n platformIds: readonly string[],\n target: SerializerTarget,\n options?: { previousManagedPlacements?: ReadonlyMap<string, readonly string[]> },\n): ApplyResult[] {\n const consumeDirs = [\n ...new Set(platformIds.flatMap((id) => skillConsumeDirs(id, target))),\n ];\n if (consumeDirs.length === 0) {\n return results;\n }\n\n const consume = new Map(\n platformIds.map((id) => [id, new Set(skillConsumeDirs(id, target))]),\n );\n const skillNames = new Set<string>();\n for (const result of results) {\n for (const file of result.files) {\n const parsed = parseSkillEmitPath(file.path);\n if (parsed) skillNames.add(parsed.name);\n }\n }\n\n const next = results.map((result) => ({\n ...result,\n files: [...result.files],\n }));\n const previousManaged =\n options?.previousManagedPlacements ?? collectManagedSkillPlacements(rootPath);\n\n const consumeDirSet = new Set(consumeDirs);\n for (const name of skillNames) {\n const previousDirs = [...(previousManaged.get(name) ?? [])].filter((dir) =>\n consumeDirSet.has(dir),\n );\n if (previousDirs.length > 0) {\n placeSkillOnDirs(next, name, previousDirs, consume, next[0]);\n continue;\n }\n const unmanagedDir = existingUnmanagedSkillConsumeDir(\n rootPath,\n name,\n consumeDirs,\n );\n if (!unmanagedDir) {\n continue;\n }\n const host =\n next.find((result) => consume.get(result.platformId)?.has(unmanagedDir))\n ?? next[0];\n if (!host) {\n continue;\n }\n placeSkillOnHost(next, host, name, unmanagedDir, consume);\n }\n\n return next;\n}\n\nexport function flattenUniqueFiles(results: ApplyResult[]): SerializedFile[] {\n const byPath = new Map<string, SerializedFile>();\n for (const result of results) {\n for (const file of result.files) {\n byPath.set(file.path.replace(/\\\\/g, \"/\"), {\n ...file,\n path: file.path.replace(/\\\\/g, \"/\"),\n });\n }\n }\n return [...byPath.values()];\n}\n","import { ulid } from \"ulid\";\nimport { getDb } from \"../db/connection.js\";\n\ninterface PreexistingPathRow {\n id: string;\n root_path: string;\n path: string;\n content_hash: string;\n created_at: string;\n}\n\nexport interface PreexistingPath {\n id: string;\n root_path: string;\n path: string;\n content_hash: string;\n created_at: string;\n}\n\nexport function recordPreexistingPath(input: {\n root_path: string;\n path: string;\n content_hash?: string;\n}): PreexistingPath {\n const db = getDb();\n try {\n db.prepare(\"SELECT 1 FROM preexisting_paths LIMIT 0\").all();\n } catch {\n return {\n id: \"\",\n root_path: input.root_path,\n path: input.path,\n content_hash: input.content_hash ?? \"\",\n created_at: new Date().toISOString(),\n };\n }\n const now = new Date().toISOString();\n const existing = db\n .prepare(\n `SELECT * FROM preexisting_paths\n WHERE root_path = ? AND path = ?`,\n )\n .get(input.root_path, input.path) as PreexistingPathRow | undefined;\n if (existing) {\n if (input.content_hash && input.content_hash !== existing.content_hash) {\n db.prepare(\n `UPDATE preexisting_paths SET content_hash = ? WHERE id = ?`,\n ).run(input.content_hash, existing.id);\n return { ...existing, content_hash: input.content_hash };\n }\n return existing;\n }\n\n const row: PreexistingPath = {\n id: ulid(),\n root_path: input.root_path,\n path: input.path,\n content_hash: input.content_hash ?? \"\",\n created_at: now,\n };\n db.prepare(\n `INSERT INTO preexisting_paths (id, root_path, path, content_hash, created_at)\n VALUES (?, ?, ?, ?, ?)`,\n ).run(row.id, row.root_path, row.path, row.content_hash, row.created_at);\n return row;\n}\n\nexport function isPreexistingPath(rootPath: string, relativePath: string): boolean {\n try {\n const row = getDb()\n .prepare(\n `SELECT 1 as ok FROM preexisting_paths\n WHERE root_path = ? AND path = ? LIMIT 1`,\n )\n .get(rootPath, relativePath) as { ok: number } | undefined;\n return row !== undefined;\n } catch {\n return false;\n }\n}\n\nexport function listPreexistingPaths(rootPath: string): string[] {\n try {\n const rows = getDb()\n .prepare(\n `SELECT path FROM preexisting_paths WHERE root_path = ? ORDER BY path ASC`,\n )\n .all(rootPath) as Array<{ path: string }>;\n return rows.map((row) => row.path);\n } catch {\n return [];\n }\n}\n","import {\n LockIntegrityError,\n verifyDeployedFileHashes,\n} from \"./lockfile.js\";\nimport { ui } from \"../ui/index.js\";\nimport {\n assertUnicodeAllowed,\n formatUnicodeFinding,\n hasCriticalUnicode,\n scanUnicodeText,\n type UnicodeScanFinding,\n} from \"./unicode-scan.js\";\n\nexport interface DeployFile {\n path: string;\n content: string;\n}\n\nexport interface DeployGateOptions {\n forceUnicode?: boolean;\n verifyHashes?: boolean;\n expectedHashes?: Record<string, string>;\n rootPath?: string;\n}\n\nexport interface DeployGateResult {\n findings: UnicodeScanFinding[];\n}\n\nexport { LockIntegrityError };\n\nexport function printUnicodeGateWarnings(\n findings: UnicodeScanFinding[],\n force = false,\n): void {\n for (const finding of findings.filter((entry) => entry.severity === \"warning\")) {\n ui.warn(formatUnicodeFinding(finding));\n }\n if (force && hasCriticalUnicode(findings)) {\n ui.warn(\"Overriding critical hidden-Unicode findings because --force was passed.\");\n }\n}\n\nexport function gateDeployFiles(\n files: DeployFile[],\n options: DeployGateOptions = {},\n): DeployGateResult {\n const findings: UnicodeScanFinding[] = [];\n for (const file of files) {\n findings.push(...scanUnicodeText(file.content, file.path));\n }\n assertUnicodeAllowed(findings, options.forceUnicode === true);\n if (\n options.verifyHashes === true &&\n options.expectedHashes &&\n Object.keys(options.expectedHashes).length > 0\n ) {\n verifyDeployedFileHashes(\n options.expectedHashes,\n files,\n options.rootPath ? { rootPath: options.rootPath } : {},\n );\n }\n return { findings };\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { getHarnesstapDir } from \"../db/connection.js\";\nimport { getPluginById } from \"../models/plugin-model.js\";\nimport {\n getEnvironmentByName,\n getEnvironmentResources,\n getEnvironmentSecretRefs,\n} from \"../models/environment.js\";\nimport type {\n EnvVarMetadata,\n EnvironmentSecretRef,\n Resource,\n ResourceType,\n} from \"../types.js\";\nimport { ENVIRONMENT_RESOURCE_TYPES } from \"./resource-classification.js\";\nimport { resolveSecretRefs } from \"./secret-resolver.js\";\n\nexport interface EnvironmentFragment {\n vars: Record<string, string>;\n secretRefs: Record<string, { provider: string; ref: string }>;\n}\n\nexport interface EnvironmentCascadeInput {\n home?: EnvironmentFragment;\n pluginDefaults?: EnvironmentFragment[];\n}\n\nexport interface ResolveEnvironmentCascadeForApplyInput {\n configuredPluginIds: string[];\n}\n\nconst EMPTY_FRAGMENT: EnvironmentFragment = { vars: {}, secretRefs: {} };\n\nfunction isEnvironmentResourceType(type: ResourceType): boolean {\n return (ENVIRONMENT_RESOURCE_TYPES as readonly string[]).includes(type);\n}\n\nfunction resourceKey(resource: Pick<Resource, \"type\" | \"name\">): string {\n return `${resource.type}:${resource.name}`;\n}\n\nexport function resolveEnvironmentCascade(\n plugins: EnvironmentCascadeInput,\n): EnvironmentFragment {\n const merge = (\n base: EnvironmentFragment,\n next?: EnvironmentFragment,\n ): EnvironmentFragment => ({\n vars: { ...base.vars, ...(next?.vars ?? {}) },\n secretRefs: { ...base.secretRefs, ...(next?.secretRefs ?? {}) },\n });\n\n let acc: EnvironmentFragment = { vars: {}, secretRefs: {} };\n acc = merge(acc, plugins.home);\n for (const fragment of plugins.pluginDefaults ?? []) {\n acc = merge(acc, fragment);\n }\n return acc;\n}\n\nexport function environmentResourcesToFragment(\n resources: Resource[],\n secretRefs: EnvironmentSecretRef[] = [],\n): EnvironmentFragment {\n const vars: Record<string, string> = {};\n\n for (const resource of resources) {\n if (resource.type === \"env_var\") {\n const meta = resource.metadata as EnvVarMetadata;\n vars[meta.key] = meta.value;\n }\n }\n\n const secretRefMap = Object.fromEntries(\n secretRefs.map((ref) => [\n ref.key,\n { provider: ref.provider, ref: ref.ref },\n ]),\n );\n\n return { vars, secretRefs: secretRefMap };\n}\n\nexport function fragmentFromEnvironmentId(\n environmentId: string,\n): EnvironmentFragment {\n return environmentResourcesToFragment(\n getEnvironmentResources(environmentId),\n getEnvironmentSecretRefs(environmentId),\n );\n}\n\nfunction parseEnvironmentJson(raw: unknown): EnvironmentFragment {\n if (!raw || typeof raw !== \"object\") {\n return EMPTY_FRAGMENT;\n }\n\n const record = raw as Record<string, unknown>;\n const values =\n record.values && typeof record.values === \"object\"\n ? (record.values as Record<string, string>)\n : {};\n const secretRefsRaw =\n record.secret_refs && typeof record.secret_refs === \"object\"\n ? (record.secret_refs as Record<string, { provider: string; ref: string }>)\n : {};\n\n return {\n vars: values,\n secretRefs: secretRefsRaw,\n };\n}\n\nfunction readEnvironmentFile(path: string): EnvironmentFragment {\n if (!existsSync(path)) {\n return EMPTY_FRAGMENT;\n }\n try {\n return parseEnvironmentJson(JSON.parse(readFileSync(path, \"utf-8\")));\n } catch {\n return EMPTY_FRAGMENT;\n }\n}\n\nfunction readActiveEnvironmentName(baseDir: string): string | undefined {\n const jsonPath = join(baseDir, \"active-environment.json\");\n if (existsSync(jsonPath)) {\n try {\n const raw = JSON.parse(readFileSync(jsonPath, \"utf-8\")) as { name?: string };\n if (typeof raw.name === \"string\" && raw.name.length > 0) {\n return raw.name;\n }\n } catch {\n // fall through\n }\n }\n\n const textPath = join(baseDir, \"active-environment\");\n if (existsSync(textPath)) {\n const name = readFileSync(textPath, \"utf-8\").trim();\n if (name.length > 0) {\n return name;\n }\n }\n\n return undefined;\n}\n\nfunction loadActiveEnvironmentFragment(baseDir: string): EnvironmentFragment | undefined {\n const activeName = readActiveEnvironmentName(baseDir);\n if (!activeName) {\n return undefined;\n }\n\n const fileFragment = readEnvironmentFile(\n join(baseDir, \"environments\", `${activeName}.json`),\n );\n if (Object.keys(fileFragment.vars).length > 0 || Object.keys(fileFragment.secretRefs).length > 0) {\n return fileFragment;\n }\n\n const dbEnvironment = getEnvironmentByName(activeName);\n if (dbEnvironment) {\n return fragmentFromEnvironmentId(dbEnvironment.id);\n }\n\n return undefined;\n}\n\nexport function loadHomeEnvironmentFragment(): EnvironmentFragment | undefined {\n return loadActiveEnvironmentFragment(getHarnesstapDir());\n}\n\nexport function loadProjectActiveEnvironmentFragment(\n projectRoot: string,\n): EnvironmentFragment | undefined {\n return loadActiveEnvironmentFragment(join(projectRoot, \".harnesstap\"));\n}\n\nexport function loadPluginDefaultFragments(\n configuredPluginIds: string[],\n): EnvironmentFragment[] {\n return configuredPluginIds.flatMap((configuredPluginId) => {\n const configuredPlugin = getPluginById(configuredPluginId);\n if (!configuredPlugin?.default_environment_id) {\n return [];\n }\n return [fragmentFromEnvironmentId(configuredPlugin.default_environment_id)];\n });\n}\n\nexport function buildEnvironmentCascadeInput(\n input: ResolveEnvironmentCascadeForApplyInput,\n): EnvironmentCascadeInput {\n return {\n home: loadHomeEnvironmentFragment(),\n pluginDefaults: loadPluginDefaultFragments(input.configuredPluginIds),\n };\n}\n\nexport function resolveEnvironmentCascadeForApply(\n input: ResolveEnvironmentCascadeForApplyInput,\n): EnvironmentFragment {\n const cascaded = resolveEnvironmentCascade(buildEnvironmentCascadeInput(input));\n const resolvedSecrets = resolveSecretRefs(cascaded.secretRefs);\n return {\n vars: { ...cascaded.vars, ...resolvedSecrets },\n secretRefs: cascaded.secretRefs,\n };\n}\n\nexport function fragmentToEnvironmentResources(\n fragment: EnvironmentFragment,\n): Resource[] {\n const now = new Date().toISOString();\n return Object.entries(fragment.vars).map(([key, value]) => ({\n id: `cascade:${key}`,\n type: \"env_var\" as const,\n name: key,\n description: \"\",\n content: \"\",\n metadata: { key, value } satisfies EnvVarMetadata,\n source: \"environment-cascade\",\n namespace: \"\",\n origin_kind: \"manual\" as const,\n origin_ref: \"\",\n content_hash: \"\",\n content_blob_ref: \"\",\n created_at: now,\n updated_at: now,\n }));\n}\n\n/**\n * Strip environment resources from the merged plugin set, then overlay the\n * resolved cascade (home ◂ plugin default).\n */\nexport function mergeResolvedEnvironmentIntoResources(\n resources: Resource[],\n cascade: EnvironmentFragment,\n): Resource[] {\n const nonEnvironmentResources = resources.filter(\n (resource) => !isEnvironmentResourceType(resource.type),\n );\n const cascadeResources = fragmentToEnvironmentResources(cascade);\n\n const order: string[] = [];\n const byKey = new Map<string, Resource>();\n for (const resource of [...nonEnvironmentResources, ...cascadeResources]) {\n const key = resourceKey(resource);\n if (!byKey.has(key)) {\n order.push(key);\n }\n byKey.set(key, resource);\n }\n\n return order\n .map((key) => byKey.get(key))\n .filter((resource): resource is Resource => resource !== undefined);\n}\n","export const CONTEXT_SIDE_RESOURCE_TYPES = [\n \"instruction\",\n \"skill\",\n \"rule\",\n \"mcp_server\",\n \"hook\",\n \"agent\",\n \"command\",\n] as const;\n\nexport const ENVIRONMENT_RESOURCE_TYPES = [\n \"env_var\",\n \"model_config\",\n \"permission\",\n] as const;\n\nexport type ContextSideResourceType = (typeof CONTEXT_SIDE_RESOURCE_TYPES)[number];\nexport type EnvironmentResourceType = (typeof ENVIRONMENT_RESOURCE_TYPES)[number];\n","import { execFileSync } from \"node:child_process\";\nimport { readFileSync } from \"node:fs\";\nimport type { EnvironmentSecretProvider } from \"../types.js\";\n\nexport interface SecretRefInput {\n provider: string;\n ref: string;\n}\n\nfunction assertSecretProvider(provider: string): EnvironmentSecretProvider {\n switch (provider) {\n case \"env\":\n case \"file\":\n case \"keychain\":\n return provider;\n default: {\n const _exhaustive: never = provider as never;\n throw new Error(`Unknown secret provider: ${_exhaustive}`);\n }\n }\n}\n\nexport function resolveSecretRef(ref: SecretRefInput): string {\n const provider = assertSecretProvider(ref.provider);\n\n switch (provider) {\n case \"env\": {\n const value = process.env[ref.ref];\n if (value === undefined) {\n throw new Error(\n `Secret ref could not be resolved: environment variable \"${ref.ref}\" is not set`,\n );\n }\n return value;\n }\n case \"file\": {\n try {\n return readFileSync(ref.ref, \"utf-8\").replace(/\\n$/, \"\");\n } catch {\n throw new Error(\n `Secret ref could not be resolved: file \"${ref.ref}\" is missing or unreadable`,\n );\n }\n }\n case \"keychain\":\n return resolveKeychainSecret(ref.ref);\n default: {\n const _exhaustive: never = provider;\n throw new Error(`Unknown secret provider: ${_exhaustive}`);\n }\n }\n}\n\nfunction resolveKeychainSecret(ref: string): string {\n if (process.platform !== \"darwin\") {\n throw new Error(\n \"Secret ref could not be resolved: keychain provider is only supported on macOS\",\n );\n }\n\n const slashIndex = ref.indexOf(\"/\");\n const service = slashIndex >= 0 ? ref.slice(0, slashIndex) : ref;\n const account = slashIndex >= 0 ? ref.slice(slashIndex + 1) : undefined;\n\n if (!service) {\n throw new Error(\n `Secret ref could not be resolved: keychain ref \"${ref}\" must include a service name`,\n );\n }\n\n const args = [\"find-generic-password\", \"-s\", service, \"-w\"];\n if (account) {\n args.splice(2, 0, \"-a\", account);\n }\n\n try {\n return execFileSync(\"security\", args, {\n encoding: \"utf-8\",\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n }).replace(/\\n$/, \"\");\n } catch {\n const label = account ? `${service}/${account}` : service;\n throw new Error(\n `Secret ref could not be resolved: keychain item \"${label}\" was not found`,\n );\n }\n}\n\nexport function resolveSecretRefs(\n secretRefs: Record<string, SecretRefInput>,\n): Record<string, string> {\n const vars: Record<string, string> = {};\n for (const [key, secretRef] of Object.entries(secretRefs)) {\n vars[key] = resolveSecretRef(secretRef);\n }\n return vars;\n}\n\nexport interface SecretRefWarning {\n key: string;\n message: string;\n}\n\nexport function resolveSecretRefsBestEffort(\n secretRefs: Record<string, SecretRefInput>,\n): {\n resolved: Record<string, string>;\n warnings: SecretRefWarning[];\n} {\n const resolved: Record<string, string> = {};\n const warnings: SecretRefWarning[] = [];\n for (const [key, secretRef] of Object.entries(secretRefs)) {\n try {\n resolved[key] = resolveSecretRef(secretRef);\n } catch (error) {\n warnings.push({\n key,\n message: error instanceof Error ? error.message : String(error),\n });\n }\n }\n return { resolved, warnings };\n}\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { getHarnesstapDir } from \"../db/connection.js\";\n\nfunction readActiveEnvironmentName(filePath: string): string | undefined {\n if (!existsSync(filePath)) {\n return undefined;\n }\n try {\n const raw = JSON.parse(readFileSync(filePath, \"utf-8\")) as { name?: string };\n if (typeof raw.name === \"string\" && raw.name.length > 0) {\n return raw.name;\n }\n } catch {\n return undefined;\n }\n return undefined;\n}\n\nfunction writeActiveEnvironmentName(filePath: string, name: string): void {\n mkdirSync(dirname(filePath), { recursive: true });\n writeFileSync(filePath, `${JSON.stringify({ name }, null, 2)}\\n`, \"utf-8\");\n}\n\nexport function environmentSessionKey(): string {\n const fromEnv = process.env.HARNESSTAP_SESSION;\n if (fromEnv && fromEnv.length > 0) {\n return fromEnv;\n }\n return String(process.ppid);\n}\n\nexport function globalActiveEnvironmentPath(): string {\n return join(getHarnesstapDir(), \"active-environment.json\");\n}\n\nexport function localActiveEnvironmentPath(): string {\n return join(\n getHarnesstapDir(),\n \"sessions\",\n environmentSessionKey(),\n \"active-environment.json\",\n );\n}\n\nexport function getGlobalActiveEnvironmentName(): string | undefined {\n return readActiveEnvironmentName(globalActiveEnvironmentPath());\n}\n\nexport function getLocalActiveEnvironmentName(): string | undefined {\n const fromEnv = process.env.HARNESSTAP_LOCAL_ENVIRONMENT;\n if (fromEnv && fromEnv.length > 0) {\n return fromEnv;\n }\n return readActiveEnvironmentName(localActiveEnvironmentPath());\n}\n\nexport function getEffectiveActiveEnvironmentName(): string | undefined {\n return getLocalActiveEnvironmentName() ?? getGlobalActiveEnvironmentName();\n}\n\nexport function setGlobalActiveEnvironment(name: string): string {\n const filePath = globalActiveEnvironmentPath();\n writeActiveEnvironmentName(filePath, name);\n return filePath;\n}\n\nexport function setLocalActiveEnvironment(name: string): string {\n const filePath = localActiveEnvironmentPath();\n writeActiveEnvironmentName(filePath, name);\n return filePath;\n}\n","import {\n loadHomeEnvironmentFragment,\n loadPluginDefaultFragments,\n resolveEnvironmentCascade,\n} from \"./environment-cascade.js\";\nimport {\n getGlobalActiveEnvironmentName,\n setGlobalActiveEnvironment,\n setLocalActiveEnvironment,\n} from \"./environment-session.js\";\nimport { resolveConfiguredPluginOrThrow, resolveEnvironmentOrThrow } from \"./environment-selectors.js\";\nimport {\n addSecretRefToEnvironment,\n createEnvironment,\n deleteEnvironment,\n getEnvironmentResources,\n getEnvironmentSecretRefs,\n hasEnvironmentReferences,\n listEnvironmentReferences,\n listEnvironments,\n removeEnvironmentEnvVar,\n removeEnvironmentModelConfig,\n removeEnvironmentPermission,\n removeSecretRefFromEnvironment,\n upsertEnvironmentEnvVar,\n upsertEnvironmentModelConfig,\n upsertEnvironmentPermission,\n} from \"../models/environment.js\";\nimport {\n setPluginDefaultEnvironment,\n} from \"../models/plugin-model.js\";\nimport { markPluginDirty } from \"./plugin-versioning.js\";\nimport type {\n EnvVarMetadata,\n Environment,\n EnvironmentSecretProvider,\n ModelConfigMetadata,\n PermissionMetadata,\n} from \"../types.js\";\n\nexport interface EnvironmentValuesPayload {\n env_vars: Record<string, string>;\n model_configs: Array<{ name: string; model: string; provider?: string }>;\n permissions: Array<{ name: string; action: string; pattern: string }>;\n}\n\nexport interface EnvironmentShowPayload {\n environment: Environment;\n values: EnvironmentValuesPayload;\n secret_refs: Record<string, { provider: string; ref: string }>;\n references: ReturnType<typeof listEnvironmentReferences>;\n}\n\nfunction environmentValuesPayload(environmentId: string): EnvironmentValuesPayload {\n const envVars: Record<string, string> = {};\n const modelConfigs: Array<{ name: string; model: string; provider?: string }> = [];\n const permissions: Array<{ name: string; action: string; pattern: string }> = [];\n\n for (const resource of getEnvironmentResources(environmentId)) {\n if (resource.type === \"env_var\") {\n const metadata = resource.metadata as EnvVarMetadata;\n envVars[metadata.key] = metadata.value;\n } else if (resource.type === \"model_config\") {\n const metadata = resource.metadata as ModelConfigMetadata;\n modelConfigs.push({\n name: resource.name,\n model: metadata.model,\n ...(metadata.provider ? { provider: metadata.provider } : {}),\n });\n } else if (resource.type === \"permission\") {\n const metadata = resource.metadata as PermissionMetadata;\n permissions.push({\n name: resource.name,\n action: metadata.action,\n pattern: metadata.pattern,\n });\n }\n }\n\n return {\n env_vars: envVars,\n model_configs: modelConfigs.sort((a, b) => a.name.localeCompare(b.name)),\n permissions: permissions.sort((a, b) => a.name.localeCompare(b.name)),\n };\n}\n\nfunction environmentSecretRefsPayload(\n environmentId: string,\n): Record<string, { provider: string; ref: string }> {\n return Object.fromEntries(\n getEnvironmentSecretRefs(environmentId).map((ref) => [\n ref.key,\n { provider: ref.provider, ref: ref.ref },\n ]),\n );\n}\n\nexport function createEnvironmentCommand(input: {\n name: string;\n description?: string;\n}): Environment {\n return createEnvironment(input);\n}\n\nexport function listEnvironmentsCommand(): Array<{\n environment: Environment;\n value_count: number;\n secret_ref_count: number;\n reference_count: number;\n}> {\n return listEnvironments().map((environment) => {\n const refs = listEnvironmentReferences(environment.id);\n return {\n environment,\n value_count: getEnvironmentResources(environment.id).length,\n secret_ref_count: getEnvironmentSecretRefs(environment.id).length,\n reference_count: refs.plugins.length,\n };\n });\n}\n\nexport function showEnvironmentCommand(selector: string): EnvironmentShowPayload {\n const environment = resolveEnvironmentOrThrow(selector);\n return {\n environment,\n values: environmentValuesPayload(environment.id),\n secret_refs: environmentSecretRefsPayload(environment.id),\n references: listEnvironmentReferences(environment.id),\n };\n}\n\nexport function deleteEnvironmentCommand(\n selector: string,\n options?: { force?: boolean },\n): { deleted: boolean; references: ReturnType<typeof listEnvironmentReferences> } {\n const environment = resolveEnvironmentOrThrow(selector);\n const references = listEnvironmentReferences(environment.id);\n if (!options?.force && hasEnvironmentReferences(environment.id)) {\n throw new Error(\n `Environment \"${environment.name}\" is still referenced by configured plugins`,\n );\n }\n return {\n deleted: deleteEnvironment(environment.id),\n references,\n };\n}\n\nexport function setEnvironmentVarCommand(\n selector: string,\n key: string,\n value: string,\n): EnvironmentShowPayload {\n const environment = resolveEnvironmentOrThrow(selector);\n upsertEnvironmentEnvVar(environment.id, key, value);\n return showEnvironmentCommand(environment.id);\n}\n\nexport function unsetEnvironmentVarCommand(\n selector: string,\n key: string,\n): EnvironmentShowPayload {\n const environment = resolveEnvironmentOrThrow(selector);\n removeEnvironmentEnvVar(environment.id, key);\n return showEnvironmentCommand(environment.id);\n}\n\nexport function setEnvironmentModelConfigCommand(\n selector: string,\n modelConfig: { model: string; provider?: string; name?: string },\n): EnvironmentShowPayload {\n const environment = resolveEnvironmentOrThrow(selector);\n upsertEnvironmentModelConfig(environment.id, modelConfig);\n return showEnvironmentCommand(environment.id);\n}\n\nexport function unsetEnvironmentModelConfigCommand(\n selector: string,\n name = \"default\",\n): EnvironmentShowPayload {\n const environment = resolveEnvironmentOrThrow(selector);\n removeEnvironmentModelConfig(environment.id, name);\n return showEnvironmentCommand(environment.id);\n}\n\nexport function setEnvironmentPermissionCommand(\n selector: string,\n permission: { action: PermissionMetadata[\"action\"]; pattern: string; name?: string },\n): EnvironmentShowPayload {\n const environment = resolveEnvironmentOrThrow(selector);\n upsertEnvironmentPermission(environment.id, permission);\n return showEnvironmentCommand(environment.id);\n}\n\nexport function unsetEnvironmentPermissionCommand(\n selector: string,\n permission: { action?: PermissionMetadata[\"action\"]; pattern?: string; name?: string },\n): EnvironmentShowPayload {\n const environment = resolveEnvironmentOrThrow(selector);\n removeEnvironmentPermission(environment.id, permission);\n return showEnvironmentCommand(environment.id);\n}\n\nexport function setEnvironmentSecretCommand(\n selector: string,\n input: {\n key: string;\n provider: EnvironmentSecretProvider;\n ref: string;\n },\n): EnvironmentShowPayload {\n const environment = resolveEnvironmentOrThrow(selector);\n addSecretRefToEnvironment(environment.id, input.key, input.provider, input.ref);\n return showEnvironmentCommand(environment.id);\n}\n\nexport function unsetEnvironmentSecretCommand(\n selector: string,\n key: string,\n): EnvironmentShowPayload {\n const environment = resolveEnvironmentOrThrow(selector);\n removeSecretRefFromEnvironment(environment.id, key);\n return showEnvironmentCommand(environment.id);\n}\n\nexport function setPluginEnvironmentCommand(\n pluginSelector: string,\n environmentSelector: string,\n): { configured_plugin_id: string; environment_id: string } {\n const configuredPlugin = resolveConfiguredPluginOrThrow(pluginSelector);\n const environment = resolveEnvironmentOrThrow(environmentSelector);\n markPluginDirty(configuredPlugin.id);\n const updated = setPluginDefaultEnvironment(\n configuredPlugin.id,\n environment.id,\n );\n if (!updated) {\n throw new Error(`Configured plugin not found: ${configuredPlugin.id}`);\n }\n return {\n configured_plugin_id: configuredPlugin.id,\n environment_id: environment.id,\n };\n}\n\nexport function unsetPluginEnvironmentCommand(pluginSelector: string): {\n configured_plugin_id: string;\n} {\n const configuredPlugin = resolveConfiguredPluginOrThrow(pluginSelector);\n markPluginDirty(configuredPlugin.id);\n const updated = setPluginDefaultEnvironment(configuredPlugin.id, null);\n if (!updated) {\n throw new Error(`Configured plugin not found: ${configuredPlugin.id}`);\n }\n return { configured_plugin_id: configuredPlugin.id };\n}\n\nexport function useEnvironmentCommand(\n selector: string,\n options?: { local?: boolean },\n): {\n environment_id: string;\n environment_name: string;\n scope: \"global\" | \"local\";\n active_environment_file: string;\n} {\n const environment = resolveEnvironmentOrThrow(selector);\n const activeEnvironmentFile = options?.local\n ? setLocalActiveEnvironment(environment.name)\n : setGlobalActiveEnvironment(environment.name);\n return {\n environment_id: environment.id,\n environment_name: environment.name,\n scope: options?.local ? \"local\" : \"global\",\n active_environment_file: activeEnvironmentFile,\n };\n}\n\n/** @deprecated Use useEnvironmentCommand */\nexport function useEnvironmentPayload(selector: string): {\n environment_id: string;\n environment_name: string;\n active_environment: { name: string };\n} {\n const result = useEnvironmentCommand(selector);\n return {\n environment_id: result.environment_id,\n environment_name: result.environment_name,\n active_environment: { name: result.environment_name },\n };\n}\n\nexport function environmentCascadePayload(input: {\n configuredPluginIds?: string[];\n}): {\n global_environment: string | null;\n home?: ReturnType<typeof loadHomeEnvironmentFragment>;\n plugin_defaults: ReturnType<typeof loadPluginDefaultFragments>;\n resolved: ReturnType<typeof resolveEnvironmentCascade>;\n} {\n const home = loadHomeEnvironmentFragment();\n const pluginDefaults = loadPluginDefaultFragments(input.configuredPluginIds ?? []);\n return {\n global_environment: getGlobalActiveEnvironmentName() ?? null,\n ...(home ? { home } : {}),\n plugin_defaults: pluginDefaults,\n resolved: resolveEnvironmentCascade({\n ...(home ? { home } : {}),\n pluginDefaults,\n }),\n };\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { getLatestSnapshot } from \"../models/snapshot.js\";\n\nexport type DriftChangeType = \"added\" | \"modified\" | \"deleted\";\n\nexport interface DriftFileChange {\n path: string;\n type: DriftChangeType;\n platform?: string;\n resource?: { type: string; name: string };\n /** Resources whose scoped FileDiff body actually changed. */\n affected_resources?: Array<{ type: string; name: string }>;\n /** How apply would treat this path when it is a planned removal. */\n removal_group?: \"owned_unmodified\" | \"owned_modified\" | \"unmanaged\";\n}\n\nexport interface ProjectDriftReport {\n project_root: string;\n snapshot_id: string | null;\n snapshot_label: string | null;\n has_drift: boolean;\n changes: DriftFileChange[];\n}\n\nfunction readProjectFile(projectRoot: string, relativePath: string): string | null {\n const fullPath = join(projectRoot, relativePath);\n if (!existsSync(fullPath)) return null;\n try {\n return readFileSync(fullPath, \"utf-8\");\n } catch {\n return null;\n }\n}\n\n/**\n * Compare on-disk project files against the latest apply/sync snapshot.\n */\nexport function detectProjectDrift(\n projectRoot: string,\n snapshot: { id: string; label: string; state: { platform_files: Record<string, Record<string, string>> } },\n): ProjectDriftReport {\n const changes: DriftFileChange[] = [];\n const seen = new Set<string>();\n\n for (const [platformId, files] of Object.entries(snapshot.state.platform_files)) {\n for (const [relativePath, expectedContent] of Object.entries(files)) {\n seen.add(relativePath);\n const current = readProjectFile(projectRoot, relativePath);\n if (current === null) {\n changes.push({ path: relativePath, type: \"deleted\", platform: platformId });\n continue;\n }\n if (current !== expectedContent) {\n changes.push({ path: relativePath, type: \"modified\", platform: platformId });\n }\n }\n }\n\n return {\n project_root: projectRoot,\n snapshot_id: snapshot.id,\n snapshot_label: snapshot.label,\n has_drift: changes.length > 0,\n changes,\n };\n}\n\nexport function detectProjectDriftFromLatest(\n projectRoot: string,\n projectId: string,\n): ProjectDriftReport | null {\n const snapshot = getLatestSnapshot(projectId);\n if (!snapshot) {\n return {\n project_root: projectRoot,\n snapshot_id: null,\n snapshot_label: null,\n has_drift: false,\n changes: [],\n };\n }\n return detectProjectDrift(projectRoot, snapshot);\n}\n","import { execSync } from \"node:child_process\";\nimport { basename } from \"node:path\";\n\n/**\n * Detect the git remote origin URL for a project directory.\n * Returns undefined if not a git repo or no origin remote.\n *\n * Reads the stored `remote.origin.url` so url.*.insteadOf rewrites (credential\n * helpers) do not change project identity.\n */\nexport function getGitOrigin(projectRoot: string): string | undefined {\n try {\n const url = execSync(\"git config --get remote.origin.url\", {\n cwd: projectRoot,\n encoding: \"utf-8\",\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n }).trim();\n return url || undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Normalize a git remote URL to a canonical form.\n * - Strips trailing .git if present\n * - Converts HTTPS URLs to a common format\n * - Preserves SSH URLs as-is\n *\n * Examples:\n * git@github.com:org/repo.git → git@github.com:org/repo.git\n * https://github.com/org/repo.git → https://github.com/org/repo\n * https://github.com/org/repo → https://github.com/org/repo\n */\nexport function normalizeGitUrl(url: string): string {\n let normalized = url.trim();\n\n // SSH URLs: keep as-is (they're already canonical)\n if (normalized.startsWith(\"git@\")) {\n return normalized;\n }\n\n // HTTPS: strip trailing .git\n if (normalized.endsWith(\".git\")) {\n normalized = normalized.slice(0, -4);\n }\n\n return normalized;\n}\n\n/**\n * Extract a human-readable project name from a git URL.\n * e.g. \"git@github.com:org/repo.git\" → \"org/repo\"\n */\nexport function projectNameFromUrl(url: string): string {\n // SSH format: git@github.com:org/repo.git\n const sshMatch = url.match(/:([^/]+\\/[^/]+?)(?:\\.git)?$/);\n if (sshMatch?.[1]) return sshMatch[1];\n\n // HTTPS format: https://github.com/org/repo\n try {\n const parsed = new URL(url);\n const path = parsed.pathname.replace(/^\\//, \"\").replace(/\\.git$/, \"\");\n return path || basename(url);\n } catch {\n return basename(url).replace(/\\.git$/, \"\");\n }\n}\n","import { resolve } from \"node:path\";\nimport { getActiveProfilePayload } from \"./profile-commands.js\";\nimport { mergePluginsForApply } from \"./plugin-apply-merge.js\";\nimport { environmentCascadePayload } from \"./environment-commands.js\";\nimport { assessProjectScanStatus, type ProjectScanStatus } from \"./project-scan-status.js\";\nimport { validatePluginPinsAgainstInventory } from \"./plugin-apply-validation.js\";\nimport { listAttachedPluginPins } from \"./plugin-composition.js\";\nimport { getPluginById, getPluginResources, resolvePluginSelector } from \"../models/plugin-model.js\";\nimport { getProjectByLocalPath, getProjectByOrigin, getProjectConfiguredPlugins } from \"../models/project.js\";\nimport { detectProjectDriftFromLatest, type ProjectDriftReport } from \"./project-drift.js\";\nimport { compareLockToResolution, readLockfile, type LockDrift } from \"./lockfile.js\";\nimport { resolveComposition } from \"./resolve/index.js\";\nimport { detectPlatforms } from \"./scanner.js\";\nimport { getGitOrigin, normalizeGitUrl } from \"./git.js\";\nimport { isProfilePlugin } from \"../constants/profile.js\";\nimport { listSnapshots } from \"../models/snapshot.js\";\nimport type { Plugin, Project, Resource, ResourceType } from \"../types.js\";\nimport { RESOURCE_TYPES } from \"../types.js\";\nimport { formatCount } from \"../copy/plurals.js\";\n\nexport interface AppliedPluginStatusRow {\n plugin: Plugin;\n resource_count: number;\n resource_summary: string;\n platforms: string[];\n applied_at: string;\n}\n\nexport interface ResolvedPluginPinStatus {\n ref: string;\n version_constraint: string;\n status: \"synced\" | \"never_synced\" | \"stale\";\n message?: string;\n}\n\nexport interface ProjectStatusPayload {\n project_root: string;\n git_origin: string | null;\n git_origin_raw: string | null;\n platforms: string[];\n project: Project | null;\n drift: ProjectDriftReport | null;\n snapshots_count: number;\n environment_cascade: ReturnType<typeof environmentCascadePayload>;\n profile: {\n active_profile: string | null;\n plugin: Plugin | null;\n stack_resource_count: number;\n stack_summary: string | null;\n warning?: string;\n };\n applied_plugins: AppliedPluginStatusRow[];\n resolved: {\n resource_count: number;\n resource_summary: string;\n plugin_pins: ResolvedPluginPinStatus[];\n environment_vars: number;\n environment_secrets: number;\n };\n project_resources: ProjectScanStatus;\n lock?: LockDrift;\n}\n\nfunction materialResources(resources: Resource[]): Resource[] {\n return resources.filter(\n (resource) => resource.type !== \"plugin\",\n );\n}\n\nexport function formatResourceTypeSummary(resources: Pick<Resource, \"type\">[]): string {\n const counts = new Map<ResourceType, number>();\n for (const resource of resources) {\n counts.set(resource.type, (counts.get(resource.type) ?? 0) + 1);\n }\n const summary = RESOURCE_TYPES.filter((type) => (counts.get(type) ?? 0) > 0).map(\n (type) => formatCount(counts.get(type) ?? 0, type),\n );\n return summary.join(\", \");\n}\n\nfunction formatPluginLabel(plugin: Pick<Plugin, \"name\" | \"version\">): string {\n return `${plugin.name}@${plugin.version}`;\n}\n\nfunction summarizePluginResources(pluginId: string): {\n count: number;\n summary: string;\n} {\n const resources = materialResources(getPluginResources(pluginId));\n return {\n count: resources.length,\n summary: formatResourceTypeSummary(resources),\n };\n}\n\nfunction buildProfileSection(): ProjectStatusPayload[\"profile\"] {\n const active = getActiveProfilePayload();\n if (!active.active_profile) {\n return {\n active_profile: null,\n plugin: null,\n stack_resource_count: 0,\n stack_summary: null,\n };\n }\n\n const plugin = resolvePluginSelector(active.active_profile);\n if (!plugin) {\n return {\n active_profile: active.active_profile,\n plugin: null,\n stack_resource_count: 0,\n stack_summary: null,\n warning: `missing plugin \"${active.active_profile}\"`,\n };\n }\n\n if (!isProfilePlugin(plugin)) {\n return {\n active_profile: active.active_profile,\n plugin,\n stack_resource_count: 0,\n stack_summary: null,\n warning: `plugin \"${plugin.name}\" is not tagged as a profile`,\n };\n }\n\n const merged = mergePluginsForApply([plugin.id]);\n const resources = materialResources(merged.resources);\n return {\n active_profile: formatPluginLabel(plugin),\n plugin,\n stack_resource_count: resources.length,\n stack_summary: formatResourceTypeSummary(resources),\n };\n}\n\nfunction buildAppliedPlugins(project: Project | null): AppliedPluginStatusRow[] {\n if (!project) {\n return [];\n }\n\n return getProjectConfiguredPlugins(project.id).flatMap((row) => {\n const plugin = getPluginById(row.plugin_id);\n if (!plugin) {\n return [];\n }\n const { count, summary } = summarizePluginResources(plugin.id);\n return [{\n plugin,\n resource_count: count,\n resource_summary: summary,\n platforms: row.platforms,\n applied_at: row.applied_at,\n }];\n });\n}\n\nfunction buildResolvedSection(\n configuredPluginIds: string[],\n): ProjectStatusPayload[\"resolved\"] {\n const environmentCascade = environmentCascadePayload({\n configuredPluginIds,\n });\n\n if (configuredPluginIds.length === 0) {\n return {\n resource_count: 0,\n resource_summary: \"\",\n plugin_pins: [],\n environment_vars: Object.keys(environmentCascade.resolved.vars).length,\n environment_secrets: Object.keys(environmentCascade.resolved.secretRefs).length,\n };\n }\n\n const merged = mergePluginsForApply(configuredPluginIds);\n const resources = materialResources(merged.resources);\n const pinMap = new Map<string, { ref: string; version_constraint: string }>();\n for (const pluginId of configuredPluginIds) {\n for (const pin of listAttachedPluginPins(pluginId)) {\n pinMap.set(pin.ref, {\n ref: pin.ref,\n version_constraint: pin.version_constraint,\n });\n }\n }\n const pins = [...pinMap.values()];\n const validationIssues = validatePluginPinsAgainstInventory(pins);\n const issueByRef = new Map(validationIssues.map((issue) => [issue.ref, issue]));\n\n const pluginPins: ResolvedPluginPinStatus[] = pins.map((pin) => {\n const issue = issueByRef.get(pin.ref);\n if (!issue) {\n return {\n ref: pin.ref,\n version_constraint: pin.version_constraint,\n status: \"synced\",\n };\n }\n return {\n ref: pin.ref,\n version_constraint: pin.version_constraint,\n status: issue.installed === \"never_synced\" ? \"never_synced\" : \"stale\",\n message: issue.message,\n };\n });\n\n return {\n resource_count: resources.length,\n resource_summary: formatResourceTypeSummary(resources),\n plugin_pins: pluginPins,\n environment_vars: Object.keys(environmentCascade.resolved.vars).length,\n environment_secrets: Object.keys(environmentCascade.resolved.secretRefs).length,\n };\n}\n\nexport function formatDriftStatusLabel(\n project: Project | null,\n driftReport: ProjectDriftReport | null,\n): string {\n if (!project) {\n return \"(not tracked)\";\n }\n if (!driftReport?.snapshot_id) {\n return \"(no snapshots)\";\n }\n if (!driftReport.has_drift) {\n return \"none\";\n }\n return `${formatCount(driftReport.changes.length, \"change\")} since snapshot ${driftReport.snapshot_id}`;\n}\n\nexport async function buildProjectStatusPayload(projectRoot: string): Promise<ProjectStatusPayload> {\n const resolvedRoot = resolve(projectRoot);\n const gitOriginRaw = getGitOrigin(resolvedRoot);\n const gitOrigin = gitOriginRaw ? normalizeGitUrl(gitOriginRaw) : null;\n const projectByPath = getProjectByLocalPath(resolvedRoot);\n const project =\n projectByPath\n ?? (gitOrigin ? getProjectByOrigin(gitOrigin) : undefined)\n ?? null;\n const configuredPluginIds = project\n ? getProjectConfiguredPlugins(project.id).map((row) => row.plugin_id)\n : [];\n const environmentCascade = environmentCascadePayload({\n configuredPluginIds,\n });\n const driftReport = project\n ? detectProjectDriftFromLatest(resolvedRoot, project.id)\n : null;\n const appliedPlugins = buildAppliedPlugins(project);\n const resolved = buildResolvedSection(configuredPluginIds);\n const projectResources = await assessProjectScanStatus(resolvedRoot);\n\n const lock = readLockfile(resolvedRoot);\n const lockSection = lock\n ? (() => {\n try {\n return compareLockToResolution(\n lock,\n resolveComposition({ rootSelectors: [lock.root] }),\n );\n } catch {\n // A lock whose root no longer resolves is itself drift.\n return {\n drift: true,\n root: lock.root,\n changes: [],\n added: [],\n removed: lock.plugins.map((entry) => entry.name),\n };\n }\n })()\n : undefined;\n\n return {\n project_root: resolvedRoot,\n git_origin: gitOrigin,\n git_origin_raw: gitOriginRaw ?? null,\n platforms: detectPlatforms(resolvedRoot),\n project,\n drift: driftReport,\n snapshots_count: project ? listSnapshots(project.id).length : 0,\n environment_cascade: environmentCascade,\n profile: buildProfileSection(),\n applied_plugins: appliedPlugins,\n resolved,\n project_resources: projectResources,\n ...(lockSection ? { lock: lockSection } : {}),\n };\n}\n","import { ulid } from \"ulid\";\nimport { getDb } from \"../db/connection.js\";\nimport type {\n GlobalApplySnapshot,\n GlobalApplySnapshotInstall,\n SnapshotState,\n} from \"../types.js\";\n\ninterface GlobalApplySnapshotRow {\n id: string;\n profile_name: string;\n plugin_ids: string;\n resolved_set: string;\n created_at: string;\n state?: string;\n}\n\ninterface GlobalApplySnapshotInstallRow {\n snapshot_id: string;\n platform_id: string;\n files: string;\n installed_at: string;\n}\n\nfunction parseState(raw: string | undefined): SnapshotState | undefined {\n if (!raw || raw === \"{}\") {\n return undefined;\n }\n try {\n return JSON.parse(raw) as SnapshotState;\n } catch {\n return undefined;\n }\n}\n\nfunction rowToGlobalApplySnapshot(row: GlobalApplySnapshotRow): GlobalApplySnapshot {\n const state = parseState(row.state);\n return {\n id: row.id,\n profile_name: row.profile_name,\n plugin_ids: JSON.parse(row.plugin_ids) as string[],\n resolved_set: JSON.parse(row.resolved_set ?? \"[]\") as Array<{\n name: string;\n version: string;\n }>,\n created_at: row.created_at,\n ...(state ? { state } : {}),\n };\n}\n\nfunction rowToGlobalApplySnapshotInstall(\n row: GlobalApplySnapshotInstallRow,\n): GlobalApplySnapshotInstall {\n return {\n ...row,\n files: JSON.parse(row.files) as string[],\n };\n}\n\nexport function createGlobalApplySnapshot(input: {\n profile_name: string;\n plugin_ids: string[];\n resolved_set?: Array<{ name: string; version: string }>;\n state?: SnapshotState;\n}): GlobalApplySnapshot {\n const db = getDb();\n const snapshot: GlobalApplySnapshot = {\n id: ulid(),\n profile_name: input.profile_name,\n plugin_ids: input.plugin_ids,\n resolved_set: input.resolved_set ?? [],\n created_at: new Date().toISOString(),\n ...(input.state ? { state: input.state } : {}),\n };\n db.prepare(\n `INSERT INTO global_apply_snapshots (id, profile_name, plugin_ids, resolved_set, created_at, state)\n VALUES (?, ?, ?, ?, ?, ?)`,\n ).run(\n snapshot.id,\n snapshot.profile_name,\n JSON.stringify(snapshot.plugin_ids),\n JSON.stringify(snapshot.resolved_set),\n snapshot.created_at,\n JSON.stringify(input.state ?? {}),\n );\n return snapshot;\n}\n\nexport function recordGlobalApplySnapshotInstall(input: {\n snapshot_id: string;\n platform_id: string;\n files: string[];\n}): GlobalApplySnapshotInstall {\n const db = getDb();\n const install: GlobalApplySnapshotInstall = {\n ...input,\n installed_at: new Date().toISOString(),\n };\n db.prepare(\n `INSERT INTO global_apply_snapshot_installs (\n snapshot_id,\n platform_id,\n files,\n installed_at\n ) VALUES (?, ?, ?, ?)\n ON CONFLICT(snapshot_id, platform_id) DO UPDATE SET\n files = excluded.files,\n installed_at = excluded.installed_at`,\n ).run(\n install.snapshot_id,\n install.platform_id,\n JSON.stringify(install.files),\n install.installed_at,\n );\n return install;\n}\n\nexport function getGlobalApplySnapshot(snapshotId: string): GlobalApplySnapshot | undefined {\n const db = getDb();\n const row = db\n .prepare(\"SELECT * FROM global_apply_snapshots WHERE id = ?\")\n .get(snapshotId) as GlobalApplySnapshotRow | undefined;\n return row ? rowToGlobalApplySnapshot(row) : undefined;\n}\n\nexport function listGlobalApplySnapshots(): GlobalApplySnapshot[] {\n const db = getDb();\n const rows = db\n .prepare(\"SELECT * FROM global_apply_snapshots ORDER BY created_at DESC, id DESC\")\n .all() as GlobalApplySnapshotRow[];\n return rows.map(rowToGlobalApplySnapshot);\n}\n\nexport function getLatestGlobalApplySnapshotForProfile(\n profileName: string,\n): GlobalApplySnapshot | undefined {\n return listGlobalApplySnapshots().find(\n (snapshot) => snapshot.profile_name === profileName,\n );\n}\n\nexport function renameGlobalApplySnapshotsProfile(\n oldName: string,\n newName: string,\n): number {\n const db = getDb();\n const result = db\n .prepare(\n `UPDATE global_apply_snapshots SET profile_name = ? WHERE profile_name = ?`,\n )\n .run(newName, oldName);\n return result.changes;\n}\n\nexport function listGlobalApplySnapshotInstalls(\n snapshotId: string,\n): GlobalApplySnapshotInstall[] {\n const db = getDb();\n const rows = db\n .prepare(\n `SELECT snapshot_id, platform_id, files, installed_at\n FROM global_apply_snapshot_installs\n WHERE snapshot_id = ?\n ORDER BY installed_at DESC, platform_id ASC`,\n )\n .all(snapshotId) as GlobalApplySnapshotInstallRow[];\n return rows.map(rowToGlobalApplySnapshotInstall);\n}\n","import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { getHarnesstapDir } from \"../db/connection.js\";\n\ninterface ActiveProfileFile {\n name: string;\n}\n\nfunction getActiveProfilePath(): string {\n return join(getHarnesstapDir(), \"active-profile.json\");\n}\n\nexport function getActiveProfileName(): string | undefined {\n const filePath = getActiveProfilePath();\n if (!existsSync(filePath)) {\n return undefined;\n }\n try {\n const parsed = JSON.parse(readFileSync(filePath, \"utf-8\")) as Partial<ActiveProfileFile>;\n if (typeof parsed.name === \"string\" && parsed.name.length > 0) {\n if (parsed.name.trim() === \"empty\") {\n return undefined;\n }\n return parsed.name;\n }\n } catch {\n return undefined;\n }\n return undefined;\n}\n\nexport function setActiveProfileName(name: string): void {\n const home = getHarnesstapDir();\n mkdirSync(home, { recursive: true });\n writeFileSync(\n getActiveProfilePath(),\n `${JSON.stringify({ name } satisfies ActiveProfileFile, null, 2)}\\n`,\n \"utf-8\",\n );\n}\n\nexport function clearActiveProfileName(): void {\n rmSync(getActiveProfilePath(), { force: true });\n}\n","import { mkdirSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n CLEARED_GLOBAL_PROFILE_NAME,\n CLEARED_GLOBAL_PROFILE_PLUGIN_ID,\n isEmptyBuiltinProfile,\n isProfilePlugin,\n} from \"../constants/profile.js\";\nimport { getHarnesstapDir } from \"../db/connection.js\";\nimport { getEnvironment } from \"../models/environment.js\";\nimport {\n createGlobalApplySnapshot,\n getLatestGlobalApplySnapshotForProfile,\n listGlobalApplySnapshotInstalls,\n listGlobalApplySnapshots,\n recordGlobalApplySnapshotInstall,\n} from \"../models/global-apply-snapshot.js\";\nimport {\n getPluginById,\n getPluginByPublishedIdentity,\n mergePluginsById,\n resolvePluginSelector,\n} from \"../models/plugin-model.js\";\nimport type { Plugin } from \"../types.js\";\nimport { ui } from \"../ui/index.js\";\nimport { resolveHomeRoot } from \"../utils/home-root.js\";\nimport { getActiveProfileName } from \"./active-profile.js\";\nimport {\n applyToGlobal,\n type ConflictPolicy,\n type ConflictResolution,\n generateFiles,\n type MaterializationConflict,\n materializeFiles,\n removeGlobalMaterializedFiles,\n} from \"./applier.js\";\nimport { gateDeployFiles } from \"./deploy-gate.js\";\nimport { resolveEnvironmentCascadeForApply } from \"./environment-cascade.js\";\nimport { substituteResourcesForApply } from \"./environment-var-substitution.js\";\nimport {\n collectOtherProfilesSnapshotTrackedFiles,\n planStaleGlobalProfileFiles,\n planStaleMergeableHostConfigFiles,\n} from \"./global-profile-cleanup.js\";\nimport { resolveRegisteredGlobalApplyHarnesses } from \"./harness-targets.js\";\nimport { rewriteStaleMergeableHostConfigs } from \"./host-config-strip.js\";\nimport { installPluginFromCatalog } from \"./plugin-catalog-install.js\";\nimport {\n listAttachedPluginPins,\n listAttachedPluginRefs,\n} from \"./plugin-composition.js\";\nimport { parseDependencyRef } from \"./plugin-dependency.js\";\nimport { collectPluginPinsForPrepare, preparePluginPinsForApply } from \"./plugin-pin-apply.js\";\nimport { parsePluginSelector, resolveRemotePluginSelector } from \"./plugin-selector.js\";\nimport { resolveComposition } from \"./resolve/index.js\";\nimport type { ResolutionResult } from \"./resolve/types.js\";\nimport {\n formatRemovalBackupNotice,\n groupPlannedRemovals,\n mergeSafeRemovalSkips,\n skippedWriteKeepsForOwnership,\n type PlannedRemovals,\n type SafeFileRemovalResult,\n type SafeRemovalSkip,\n} from \"./safe-file-removal.js\";\n\n/** HT library deps that belong in the profile stack (not host marketplace/git/path pins). */\nfunction isProfileStackDependency(ref: string): boolean {\n const parsed = parseDependencyRef(ref);\n if (parsed.source_kind === \"catalog\") {\n return true;\n }\n if (parsed.source_kind !== \"local\") {\n return false;\n }\n return !(\n parsed.origin_ref.startsWith(\"./\")\n || parsed.origin_ref.startsWith(\"../\")\n );\n}\n\nfunction listProfileStackRefs(pluginId: string): ReturnType<typeof listAttachedPluginRefs> {\n return listAttachedPluginRefs(pluginId).filter((ref) =>\n isProfileStackDependency(ref.dependency_name)\n );\n}\n\nfunction listHostPluginPins(pluginId: string): ReturnType<typeof listAttachedPluginPins> {\n return listAttachedPluginPins(pluginId).filter((pin) => {\n const kind = parseDependencyRef(pin.ref).source_kind;\n return kind === \"marketplace\" || kind === \"git\";\n });\n}\n\nexport interface ApplyProfilePluginOptions {\n harness?: string;\n conflictPolicy: ConflictPolicy;\n conflictResolver?: (\n conflict: MaterializationConflict,\n ) => Promise<ConflictResolution> | ConflictResolution;\n dryRun?: boolean;\n pull?: boolean;\n account?: string;\n baseUrl?: string;\n /**\n * When false, allow applying a non-profile plugin to machine home without\n * requiring the `profile` tag. Active-profile recording is owned by callers.\n * Defaults to true (require profile tag).\n */\n recordActiveProfile?: boolean;\n forceUnicode?: boolean;\n forceRemove?: boolean;\n yes?: boolean;\n interactive?: boolean;\n /** When false, status/drift keeps per-harness skill paths. Default true. */\n pinSkillEmits?: boolean;\n /**\n * Dry-run serialize: false compares the library snapshot to live files\n * (status/drift). Default true keeps extra live skill body for apply/preview.\n */\n mergeLiveSkillMarkdown?: boolean;\n}\n\nexport interface ApplyProfilePluginResult {\n profile_name: string;\n profile_plugin_id: string;\n configured_plugin_ids: string[];\n harnesses: string[];\n dry_run: boolean;\n snapshot_id?: string;\n cancelled: boolean;\n files: string[];\n written_files: string[];\n skipped_files: string[];\n conflicts: string[];\n default_environment_name?: string;\n pulled_plugins?: Array<{ plugin_name: string; source: string }>;\n expected_files?: Array<{ path: string; content: string }>;\n removed_files?: string[];\n skipped_removals?: SafeRemovalSkip[];\n removal_backup?: string;\n removals?: PlannedRemovals;\n resolution?: ResolutionResult;\n}\n\nfunction collectProfileSnapshotTrackedFiles(profileName: string): string[] {\n const snapshot = getLatestGlobalApplySnapshotForProfile(profileName);\n if (!snapshot) {\n return [];\n }\n return [\n ...new Set(\n listGlobalApplySnapshotInstalls(snapshot.id).flatMap(\n (install) => install.files,\n ),\n ),\n ];\n}\n\nfunction collectPreviousGlobalApplyTrackedFiles(): string[] {\n const [previousSnapshot] = listGlobalApplySnapshots();\n if (!previousSnapshot) {\n return [];\n }\n return collectProfileSnapshotTrackedFiles(previousSnapshot.profile_name);\n}\n\nasync function collectOutgoingProfileFilesForCleanup(\n outgoingProfileName: string,\n incomingProfileName: string,\n options: Pick<ApplyProfilePluginOptions, \"harness\" | \"pull\">,\n): Promise<string[]> {\n if (outgoingProfileName === incomingProfileName) {\n return collectProfileSnapshotTrackedFiles(outgoingProfileName);\n }\n\n const fromSnapshot = collectProfileSnapshotTrackedFiles(outgoingProfileName);\n const outgoingApply = await applyProfilePlugin(outgoingProfileName, {\n dryRun: true,\n harness: options.harness,\n conflictPolicy: \"replace\",\n pull: options.pull ?? false,\n });\n\n return [...new Set([...fromSnapshot, ...outgoingApply.files])];\n}\n\nasync function resolvePreviousTrackedFilesForApply(\n incomingProfileName: string,\n options: Pick<ApplyProfilePluginOptions, \"harness\" | \"pull\">,\n): Promise<string[]> {\n const outgoingProfile = getActiveProfileName();\n const tracked = new Set<string>();\n\n if (outgoingProfile && outgoingProfile !== incomingProfileName) {\n for (const filePath of await collectOutgoingProfileFilesForCleanup(\n outgoingProfile,\n incomingProfileName,\n options,\n )) {\n tracked.add(filePath);\n }\n } else if (outgoingProfile) {\n for (const filePath of collectProfileSnapshotTrackedFiles(outgoingProfile)) {\n tracked.add(filePath);\n }\n }\n\n for (const filePath of collectOtherProfilesSnapshotTrackedFiles(incomingProfileName)) {\n tracked.add(filePath);\n }\n\n if (tracked.size > 0) {\n return [...tracked];\n }\n\n return collectPreviousGlobalApplyTrackedFiles();\n}\n\nfunction removeStaleGlobalProfileFiles(\n homeRoot: string,\n desiredFiles: readonly string[],\n previousTrackedFiles: readonly string[],\n harnesses: string[],\n options: {\n dryRun?: boolean;\n forceRemove?: boolean;\n applyId?: string;\n snapshotId?: string;\n } = {},\n): SafeFileRemovalResult {\n const staleFiles = planStaleGlobalProfileFiles(\n homeRoot,\n desiredFiles,\n previousTrackedFiles,\n harnesses,\n );\n const mergeFiles = planStaleMergeableHostConfigFiles(\n homeRoot,\n desiredFiles,\n previousTrackedFiles,\n harnesses,\n );\n const removed = removeGlobalMaterializedFiles(homeRoot, staleFiles, {\n dryRun: options.dryRun,\n forceRemove: options.forceRemove,\n applyId: options.applyId,\n snapshotId: options.snapshotId,\n });\n const rewritten = rewriteStaleMergeableHostConfigs(homeRoot, mergeFiles, {\n applyId: removed.applyId,\n snapshotId: options.snapshotId,\n dryRun: options.dryRun,\n });\n return {\n ...removed,\n removed: [...removed.removed, ...rewritten.removed],\n warnings: [\n ...removed.warnings,\n ...rewritten.rewritten.map((path) => `Updated ${path} (removed HarnessTap-managed keys).`),\n ],\n };\n}\n\nfunction warnSkippedRemovals(\n result: SafeFileRemovalResult,\n extraSkips: readonly SafeRemovalSkip[] = [],\n): void {\n const skipMessages = new Set(\n mergeSafeRemovalSkips(result.skipped, extraSkips).map((skip) => skip.message),\n );\n for (const warning of result.warnings) {\n if (skipMessages.has(warning)) {\n continue;\n }\n console.warn(ui.theme.warn(warning));\n }\n const notice = formatRemovalBackupNotice(result, resolveHomeRoot());\n if (notice) {\n ui.info(notice);\n }\n}\n\nfunction removalFields(\n result: SafeFileRemovalResult,\n extraSkips: readonly SafeRemovalSkip[] = [],\n): Pick<\n ApplyProfilePluginResult,\n \"removed_files\" | \"skipped_removals\" | \"removal_backup\" | \"removals\"\n> {\n const skipped = mergeSafeRemovalSkips(result.skipped, extraSkips);\n return {\n ...(result.removed.length > 0 ? { removed_files: result.removed } : {}),\n ...(skipped.length > 0 ? { skipped_removals: skipped } : {}),\n ...(result.removed.length > 0 ? { removal_backup: result.backupDir } : {}),\n removals: groupPlannedRemovals({\n remove: result.removed,\n skip: skipped,\n }),\n };\n}\n\nfunction normalizeVersionConstraint(versionConstraint: string): string | undefined {\n const trimmed = versionConstraint.trim();\n if (!trimmed || trimmed === \"*\" || trimmed === \"latest\") {\n return undefined;\n }\n return trimmed;\n}\n\nfunction resolveDependencyPlugin(ref: {\n dependency_name: string;\n version_constraint: string;\n}): Plugin | undefined {\n try {\n const parsed = parsePluginSelector(ref.dependency_name);\n if (parsed.scope === \"published\") {\n const version = normalizeVersionConstraint(ref.version_constraint) ?? parsed.version;\n if (version) {\n const byPublishedIdentity = getPluginByPublishedIdentity({\n name: parsed.name,\n version,\n org: parsed.org,\n catalog: parsed.catalog,\n });\n if (byPublishedIdentity) {\n return byPublishedIdentity;\n }\n }\n }\n } catch {\n // Fall back to local selector resolution below.\n }\n\n const versionConstraint = normalizeVersionConstraint(ref.version_constraint);\n if (versionConstraint) {\n const withVersion = resolvePluginSelector(\n `${ref.dependency_name}@${versionConstraint}`,\n );\n if (withVersion) {\n return withVersion;\n }\n }\n return resolvePluginSelector(ref.dependency_name);\n}\n\nasync function ensureProfileDependenciesAvailable(\n profilePlugin: Plugin,\n options: ApplyProfilePluginOptions,\n): Promise<Array<{ plugin_name: string; source: string }>> {\n const pulledPlugins: Array<{ plugin_name: string; source: string }> = [];\n const queue: Plugin[] = [profilePlugin];\n const visited = new Set<string>();\n\n while (queue.length > 0) {\n const plugin = queue.shift();\n if (!plugin || visited.has(plugin.id)) {\n continue;\n }\n visited.add(plugin.id);\n\n for (const ref of listProfileStackRefs(plugin.id)) {\n const localDependency = resolveDependencyPlugin(ref);\n if (localDependency) {\n queue.push(localDependency);\n continue;\n }\n\n let parsed: ReturnType<typeof parsePluginSelector>;\n try {\n parsed = parsePluginSelector(ref.dependency_name);\n } catch {\n throw new Error(\n `Missing local plugin dependency \"${ref.dependency_name}\" referenced by profile \"${plugin.name}\"`,\n );\n }\n\n if (parsed.scope !== \"published\") {\n throw new Error(\n `Missing local plugin dependency \"${ref.dependency_name}\" referenced by profile \"${plugin.name}\"`,\n );\n }\n\n if (options.pull === false) {\n throw new Error(\n `Missing published dependency \"${ref.dependency_name}\" for profile \"${plugin.name}\". Re-run without --no-pull.`,\n );\n }\n\n const remoteSelector = resolveRemotePluginSelector(ref.dependency_name, {\n version: normalizeVersionConstraint(ref.version_constraint),\n });\n const installed = await installPluginFromCatalog(remoteSelector, {\n account: options.account,\n baseUrl: options.baseUrl,\n });\n pulledPlugins.push({\n plugin_name: installed.pluginName,\n source: installed.sourceLabel,\n });\n const resolvedInstalled = getPluginById(installed.pluginId);\n if (resolvedInstalled) {\n queue.push(resolvedInstalled);\n }\n }\n }\n\n return pulledPlugins;\n}\n\nexport function collectProfilePluginIds(profilePlugin: Plugin): string[] {\n const orderedIds: string[] = [];\n const queue: Plugin[] = [profilePlugin];\n const visited = new Set<string>();\n\n while (queue.length > 0) {\n const plugin = queue.shift();\n if (!plugin || visited.has(plugin.id)) {\n continue;\n }\n visited.add(plugin.id);\n orderedIds.push(plugin.id);\n\n for (const ref of listProfileStackRefs(plugin.id)) {\n const resolved = resolveDependencyPlugin(ref);\n if (!resolved) {\n throw new Error(\n `Missing local plugin dependency \"${ref.dependency_name}\" referenced by profile \"${plugin.name}\"`,\n );\n }\n queue.push(resolved);\n }\n }\n\n return orderedIds;\n}\n\nfunction listResolvedPluginPins(\n resolution: ResolutionResult,\n): Array<{ ref: string; version_constraint: string }> {\n const pins = new Map<string, { ref: string; version_constraint: string }>();\n // Deeper plugins first so nearer ones overwrite, matching Pass 2.\n const ordered = [...resolution.selected].sort(\n (a, b) => b.depth - a.depth || b.declarationIndex - a.declarationIndex,\n );\n for (const plugin of ordered) {\n for (const pin of listHostPluginPins(plugin.pluginId)) {\n pins.set(pin.ref, {\n ref: pin.ref,\n version_constraint: pin.version_constraint,\n });\n }\n }\n return [...pins.values()];\n}\n\nfunction resolveGlobalApplyHarnessTargets(harnessOption?: string): string[] {\n return resolveRegisteredGlobalApplyHarnesses(harnessOption);\n}\n\nfunction writeHomeActiveEnvironment(name: string): string {\n const home = getHarnesstapDir();\n mkdirSync(home, { recursive: true });\n const filePath = join(home, \"active-environment.json\");\n writeFileSync(filePath, `${JSON.stringify({ name }, null, 2)}\\n`, \"utf-8\");\n return filePath;\n}\n\nexport class ProfileEmptyProfileRemovedError extends Error {\n constructor() {\n super(\n 'Profile \"empty\" is no longer available. Use \"profile stash\" to save the active profile and clear global harness files.',\n );\n this.name = \"ProfileEmptyProfileRemovedError\";\n }\n}\n\nexport async function clearGlobalProfileApply(\n options: ApplyProfilePluginOptions,\n): Promise<ApplyProfilePluginResult> {\n const harnesses = resolveGlobalApplyHarnessTargets(options.harness);\n const homeRoot = resolveHomeRoot();\n const previousTrackedFiles = await resolvePreviousTrackedFilesForApply(\n CLEARED_GLOBAL_PROFILE_NAME,\n options,\n );\n if (options.dryRun) {\n const planned = removeStaleGlobalProfileFiles(\n homeRoot,\n [],\n previousTrackedFiles,\n harnesses,\n { dryRun: true, forceRemove: options.forceRemove },\n );\n return {\n profile_name: CLEARED_GLOBAL_PROFILE_NAME,\n profile_plugin_id: CLEARED_GLOBAL_PROFILE_PLUGIN_ID,\n configured_plugin_ids: [],\n harnesses,\n dry_run: true,\n cancelled: false,\n files: [],\n written_files: [],\n skipped_files: [],\n conflicts: [],\n expected_files: [],\n ...removalFields(planned),\n };\n }\n\n const snapshot = createGlobalApplySnapshot({\n profile_name: CLEARED_GLOBAL_PROFILE_NAME,\n plugin_ids: [],\n });\n const removed = removeStaleGlobalProfileFiles(\n homeRoot,\n [],\n previousTrackedFiles,\n harnesses,\n {\n forceRemove: options.forceRemove,\n applyId: snapshot.id,\n snapshotId: snapshot.id,\n },\n );\n warnSkippedRemovals(removed);\n\n return {\n profile_name: CLEARED_GLOBAL_PROFILE_NAME,\n profile_plugin_id: CLEARED_GLOBAL_PROFILE_PLUGIN_ID,\n configured_plugin_ids: [],\n harnesses,\n dry_run: false,\n snapshot_id: snapshot.id,\n cancelled: false,\n files: [],\n written_files: [],\n skipped_files: [],\n conflicts: [],\n ...removalFields(removed),\n };\n}\n\nexport async function applyProfilePlugin(\n selector: string,\n options: ApplyProfilePluginOptions,\n): Promise<ApplyProfilePluginResult> {\n if (isEmptyBuiltinProfile(selector)) {\n throw new ProfileEmptyProfileRemovedError();\n }\n\n const profilePlugin = resolvePluginSelector(selector);\n if (!profilePlugin) {\n throw new Error(`Plugin not found: ${selector}`);\n }\n const requireProfileTag = options.recordActiveProfile !== false;\n if (requireProfileTag && !isProfilePlugin(profilePlugin)) {\n throw new Error(`Plugin \"${profilePlugin.name}\" is not tagged as a profile`);\n }\n\n const pulledPlugins = await ensureProfileDependenciesAvailable(\n profilePlugin,\n options,\n );\n const homeRoot = resolveHomeRoot();\n const rootPluginPins = collectPluginPinsForPrepare([profilePlugin.id]);\n const skipPluginSync = rootPluginPins.length === 0;\n\n // Marketplace/git pins on the profile root must be materialized before the\n // first composition resolve can walk them as upstream plugins. Dry-run skips\n // host install CLI calls but still syncs from trees that are already installed.\n await preparePluginPinsForApply({\n pins: rootPluginPins,\n baseResources: [],\n projectRoot: homeRoot,\n homeRoot,\n claudeConfig: mergePluginsById([profilePlugin.id]).claude,\n scope: \"user\",\n skipSync: skipPluginSync,\n ignoreMissingInstall: Boolean(options.dryRun),\n yes: options.yes,\n interactive: options.interactive,\n profileName: profilePlugin.name,\n });\n\n let resolution = resolveComposition({ rootSelectors: [profilePlugin.name] });\n let merged = {\n plugins: resolution.selected\n .map((plugin) => getPluginById(plugin.pluginId))\n .filter((plugin): plugin is NonNullable<typeof plugin> => plugin != null),\n resources: resolution.resources,\n claude: mergePluginsById(\n [...resolution.selected]\n .sort((a, b) => b.depth - a.depth || b.declarationIndex - a.declarationIndex)\n .map((plugin) => plugin.pluginId),\n ).claude,\n pluginPins: listResolvedPluginPins(resolution),\n };\n for (const warning of resolution.warnings) {\n console.warn(ui.theme.warn(warning));\n }\n const configuredPluginIds = merged.plugins.map((plugin) => plugin.id);\n const resolvedSet = resolution.selected\n .filter((plugin) => plugin.depth > 0)\n .map((plugin) => ({ name: plugin.name, version: plugin.version }));\n const harnesses = resolveGlobalApplyHarnessTargets(options.harness);\n const resolvedEnvironment = resolveEnvironmentCascadeForApply({\n configuredPluginIds,\n });\n\n let defaultEnvironmentName: string | undefined;\n if (profilePlugin.default_environment_id) {\n const environment = getEnvironment(profilePlugin.default_environment_id);\n if (!environment) {\n throw new Error(\n `Default environment ${profilePlugin.default_environment_id} not found for profile ${profilePlugin.name}`,\n );\n }\n defaultEnvironmentName = environment.name;\n }\n\n const rootPinRefs = new Set(rootPluginPins.map((pin) => pin.ref));\n const additionalPins = collectPluginPinsForPrepare(configuredPluginIds).filter(\n (pin) => !rootPinRefs.has(pin.ref),\n );\n if (!options.dryRun && additionalPins.length > 0) {\n const additionalPrepare = await preparePluginPinsForApply({\n pins: additionalPins,\n baseResources: merged.resources,\n projectRoot: homeRoot,\n claudeConfig: merged.claude,\n scope: \"user\",\n skipSync: false,\n yes: options.yes,\n interactive: options.interactive,\n profileName: profilePlugin.name,\n });\n if (\n additionalPrepare.installs.some(\n (install) => install.status !== \"already_installed\",\n )\n ) {\n resolution = resolveComposition({ rootSelectors: [profilePlugin.name] });\n merged = {\n plugins: resolution.selected\n .map((plugin) => getPluginById(plugin.pluginId))\n .filter((plugin): plugin is NonNullable<typeof plugin> => plugin != null),\n resources: resolution.resources,\n claude: mergePluginsById(\n [...resolution.selected]\n .sort((a, b) => b.depth - a.depth || b.declarationIndex - a.declarationIndex)\n .map((plugin) => plugin.pluginId),\n ).claude,\n pluginPins: listResolvedPluginPins(resolution),\n };\n }\n }\n\n const resolvedResources = merged.resources;\n const applyResources = substituteResourcesForApply(\n resolvedResources,\n resolvedEnvironment.vars,\n ).resources;\n\n if (options.dryRun) {\n const previousTrackedFiles = await resolvePreviousTrackedFilesForApply(\n profilePlugin.name,\n options,\n );\n const generated = await generateFiles(applyResources, harnesses, homeRoot, {\n target: \"global\",\n claudeConfig: merged.claude,\n resolvedEnvironment,\n pinSkillEmits: options.pinSkillEmits,\n mergeLiveSkillMarkdown: options.mergeLiveSkillMarkdown,\n });\n const files = generated.flatMap((result) => result.files);\n gateDeployFiles(files, { forceUnicode: options.forceUnicode });\n const materialized = await materializeFiles(files, homeRoot, {\n conflictPolicy: options.conflictPolicy,\n conflictResolver: options.conflictResolver,\n dryRun: true,\n });\n const desiredFiles = files.map((file) => file.path);\n const plannedRemoval = removeStaleGlobalProfileFiles(\n homeRoot,\n desiredFiles,\n previousTrackedFiles,\n harnesses,\n { dryRun: true, forceRemove: options.forceRemove },\n );\n const writeKeeps = skippedWriteKeepsForOwnership(\n homeRoot,\n materialized.skippedFiles,\n );\n return {\n profile_name: profilePlugin.name,\n profile_plugin_id: profilePlugin.id,\n configured_plugin_ids: configuredPluginIds,\n harnesses,\n dry_run: true,\n cancelled: materialized.cancelled,\n files: files.map((file) => file.path),\n written_files: materialized.writtenFiles,\n skipped_files: materialized.skippedFiles,\n conflicts: materialized.conflicts.map((conflict) => conflict.path),\n expected_files: files.map((file) => ({ path: file.path, content: file.content })),\n ...(defaultEnvironmentName ? { default_environment_name: defaultEnvironmentName } : {}),\n ...(pulledPlugins.length > 0 ? { pulled_plugins: pulledPlugins } : {}),\n resolution,\n ...removalFields(plannedRemoval, writeKeeps),\n };\n }\n\n const previousTrackedFiles = await resolvePreviousTrackedFilesForApply(\n profilePlugin.name,\n options,\n );\n const applied = await applyToGlobal(applyResources, harnesses, homeRoot, {\n conflictPolicy: options.conflictPolicy,\n conflictResolver: options.conflictResolver,\n resolvedEnvironment,\n claudeConfig: merged.claude,\n forceUnicode: options.forceUnicode,\n previousTrackedFiles,\n });\n let snapshotId: string | undefined;\n let removal: SafeFileRemovalResult | undefined;\n const writeKeeps = applied.cancelled\n ? []\n : skippedWriteKeepsForOwnership(homeRoot, applied.skippedFiles);\n if (!applied.cancelled) {\n const desiredFiles = applied.results.flatMap((result) =>\n result.files.map((file) => file.path),\n );\n const plannedRemoval = removeStaleGlobalProfileFiles(\n homeRoot,\n desiredFiles,\n previousTrackedFiles,\n harnesses,\n { dryRun: true, forceRemove: options.forceRemove },\n );\n const hasChanges =\n applied.writtenFiles.length > 0 || plannedRemoval.removed.length > 0;\n const snapshot = createGlobalApplySnapshot({\n profile_name: profilePlugin.name,\n plugin_ids: configuredPluginIds,\n resolved_set: resolvedSet,\n state: applied.preApplyState,\n });\n snapshotId = snapshot.id;\n if (hasChanges) {\n removal = removeStaleGlobalProfileFiles(\n homeRoot,\n desiredFiles,\n previousTrackedFiles,\n harnesses,\n {\n forceRemove: options.forceRemove,\n applyId: snapshot.id,\n snapshotId: snapshot.id,\n },\n );\n warnSkippedRemovals(removal, writeKeeps);\n } else {\n removal = plannedRemoval;\n }\n for (const result of applied.results) {\n const installFiles = result.files.map((file) => file.path);\n if (installFiles.length === 0) continue;\n recordGlobalApplySnapshotInstall({\n snapshot_id: snapshot.id,\n platform_id: result.platformId,\n files: installFiles,\n });\n }\n }\n if (!applied.cancelled && defaultEnvironmentName) {\n writeHomeActiveEnvironment(defaultEnvironmentName);\n }\n\n return {\n profile_name: profilePlugin.name,\n profile_plugin_id: profilePlugin.id,\n configured_plugin_ids: configuredPluginIds,\n harnesses,\n dry_run: false,\n ...(snapshotId ? { snapshot_id: snapshotId } : {}),\n cancelled: applied.cancelled,\n files: applied.results.flatMap((result) => result.files.map((file) => file.path)),\n written_files: applied.writtenFiles,\n skipped_files: applied.skippedFiles,\n conflicts: applied.conflicts.map((conflict) => conflict.path),\n ...(defaultEnvironmentName ? { default_environment_name: defaultEnvironmentName } : {}),\n ...(pulledPlugins.length > 0 ? { pulled_plugins: pulledPlugins } : {}),\n resolution,\n ...(removal ? removalFields(removal, writeKeeps) : {}),\n };\n}\n","import {\n chmodSync,\n existsSync,\n mkdirSync,\n readFileSync,\n realpathSync,\n writeFileSync,\n} from \"node:fs\";\nimport { dirname, resolve, sep } from \"node:path\";\nimport { hasParentTraversalSegment } from \"../utils/path-containment.js\";\nimport { resolveHomeRoot } from \"../utils/home-root.js\";\nimport {\n findImportedSnapshotOwnersByFile,\n getImportedSnapshot,\n listImportedSnapshots,\n listImportedSnapshotInstalls,\n removeImportedSnapshotOwnershipForFiles,\n recordImportedSnapshotInstall,\n} from \"../models/imported-snapshot.js\";\nimport { getResourcesByIds } from \"../models/resource.js\";\nimport { applyClaudePluginExtensions } from \"../platforms/claude-plugin-extensions.js\";\nimport type {\n ClaudePluginConfig,\n HookMetadata,\n Resource,\n SerializedFile,\n SerializeOptions,\n SnapshotState,\n SurfaceWarning,\n} from \"../types.js\";\nimport { getPlatformSerializer } from \"./platform-serializers.js\";\nimport {\n attachResourceOwnership,\n persistWrittenMaterializations,\n} from \"./materialization-ownership.js\";\nimport { isCursorHostManagedSkillsPath } from \"./cursor-host-managed-skills.js\";\nimport { omitHostPluginBundledSkills } from \"./host-plugin-material.js\";\nimport { skippedDuplicateCommand, skippedHostPluginHook } from \"../copy/cli.js\";\nimport { gateDeployFiles } from \"./deploy-gate.js\";\nimport { pruneManagedCursorLocalPlugins } from \"../plugins/cursor-local-plugin.js\";\nimport {\n type EnvironmentFragment,\n mergeResolvedEnvironmentIntoResources,\n} from \"./environment-cascade.js\";\nimport { pinSkillEmitsToExistingLivePaths } from \"./shared-emit-paths.js\";\nimport { resourceAppliesToHarness } from \"./harness-scope.js\";\nimport { hookRequiresPluginRoot } from \"./hook-serialization.js\";\nimport { recordPreexistingPath } from \"../models/preexisting-path.js\";\nimport { isMergeableHostConfigPath } from \"./merged-host-config.js\";\nimport {\n isAggregateConfigManagedPath,\n isPluginRegistryManagedPath,\n} from \"./profile-commit-resource.js\";\nimport {\n executeSafeFileRemovals,\n hasHarnessTapMaterialization,\n hashOnDiskFile,\n isHarnessTapOwnedPath,\n type SafeFileRemovalOptions,\n type SafeFileRemovalResult,\n} from \"./safe-file-removal.js\";\nimport { captureManagedSnapshotState } from \"./snapshot-capture.js\";\nimport { fileContentsEquivalentForDrift } from \"./file-contents-drift.js\";\n\nexport interface ApplyResult {\n platformId: string;\n files: SerializedFile[];\n surface_warnings?: SurfaceWarning[];\n}\n\nexport type ConflictPolicy = \"prompt\" | \"replace\" | \"skip\" | \"cancel\";\nexport type ConflictResolution = \"replace\" | \"skip\" | \"cancel\";\n\nexport interface ImportedSnapshotConflictOwner {\n snapshot_id: string;\n platform_id: string;\n plugin_name: string;\n plugin_version?: string;\n}\n\nexport interface MaterializationConflict {\n path: string;\n fullPath: string;\n owners: ImportedSnapshotConflictOwner[];\n}\n\nexport interface MaterializeFilesOptions {\n conflictPolicy?: ConflictPolicy;\n conflictResolver?: (\n conflict: MaterializationConflict,\n ) => Promise<ConflictResolution> | ConflictResolution;\n currentSnapshotId?: string;\n replaceOwnedSnapshotIds?: string[];\n dryRun?: boolean;\n}\n\nexport interface GenerateFilesOptions extends SerializeOptions {\n claudeConfig?: ClaudePluginConfig;\n resolvedEnvironment?: EnvironmentFragment;\n previousManagedPlacements?: ReadonlyMap<string, readonly string[]>;\n /** When false, keep per-harness skill emits (status/drift). Default true. */\n pinSkillEmits?: boolean;\n}\n\nexport interface GlobalApplyOptions extends GenerateFilesOptions, MaterializeFilesOptions {\n snapshotId?: string;\n forceUnicode?: boolean;\n previousTrackedFiles?: readonly string[];\n}\n\nexport interface MaterializationResult {\n cancelled: boolean;\n writtenFiles: string[];\n skippedFiles: string[];\n conflicts: MaterializationConflict[];\n}\n\nexport interface GlobalApplyResult extends MaterializationResult {\n results: ApplyResult[];\n preApplyState: SnapshotState;\n}\n\nfunction isAutoReplaceConflict(\n conflict: MaterializationConflict,\n snapshotId?: string,\n replaceOwnedSnapshotIds: readonly string[] = [],\n): boolean {\n const allowedSnapshotIds = new Set([\n ...replaceOwnedSnapshotIds,\n ...(snapshotId ? [snapshotId] : []),\n ]);\n return Boolean(\n allowedSnapshotIds.size > 0 &&\n conflict.owners.length > 0 &&\n conflict.owners.every((owner) => allowedSnapshotIds.has(owner.snapshot_id)),\n );\n}\n\nfunction resolveMaterializedPath(rootPath: string, relativePath: string): string {\n if (\n !relativePath ||\n hasParentTraversalSegment(relativePath) ||\n relativePath.startsWith(\"/\") ||\n relativePath.startsWith(\"\\\\\")\n ) {\n throw new Error(`Refusing to materialize path outside root: ${relativePath}`);\n }\n\n const resolvedRoot = resolve(rootPath);\n const fullPath = resolve(resolvedRoot, relativePath);\n if (fullPath !== resolvedRoot && !fullPath.startsWith(`${resolvedRoot}${sep}`)) {\n throw new Error(`Refusing to materialize path outside root: ${relativePath}`);\n }\n\n return fullPath;\n}\n\nfunction assertMaterializedPathIsSafe(rootPath: string, relativePath: string): string {\n const fullPath = resolveMaterializedPath(rootPath, relativePath);\n const resolvedRoot = realpathSync(rootPath);\n\n if (existsSync(fullPath)) {\n const resolvedTarget = realpathSync(fullPath);\n if (resolvedTarget !== resolvedRoot && !resolvedTarget.startsWith(`${resolvedRoot}${sep}`)) {\n throw new Error(`Refusing to materialize path outside root via symlink: ${relativePath}`);\n }\n }\n\n let probePath = dirname(fullPath);\n while (!existsSync(probePath)) {\n const parentPath = dirname(probePath);\n if (parentPath === probePath) {\n throw new Error(`Refusing to materialize path outside root: ${relativePath}`);\n }\n probePath = parentPath;\n }\n\n const resolvedProbe = realpathSync(probePath);\n if (resolvedProbe !== resolvedRoot && !resolvedProbe.startsWith(`${resolvedRoot}${sep}`)) {\n throw new Error(`Refusing to materialize path outside root via symlink: ${relativePath}`);\n }\n\n return fullPath;\n}\n\nfunction shouldPreserveUnownedFile(path: string): boolean {\n if (/\\.(md|mdc)$/i.test(path)) {\n return false;\n }\n return (\n isMergeableHostConfigPath(path)\n || isAggregateConfigManagedPath(path)\n || isPluginRegistryManagedPath(path)\n );\n}\n\nexport function removeGlobalMaterializedFiles(\n rootPath: string,\n filePaths: string[],\n options: SafeFileRemovalOptions = {},\n): SafeFileRemovalResult {\n const filtered = [...new Set(filePaths)].filter(\n (filePath) => !isCursorHostManagedSkillsPath(filePath),\n );\n for (const filePath of filtered) {\n assertMaterializedPathIsSafe(rootPath, filePath);\n }\n return executeSafeFileRemovals(rootPath, filtered, options);\n}\n\nfunction removeMaterializedFiles(\n rootPath: string,\n filePaths: string[],\n options: SafeFileRemovalOptions = {},\n): SafeFileRemovalResult {\n return removeGlobalMaterializedFiles(rootPath, filePaths, options);\n}\n\nfunction fileContentMatchesExisting(fullPath: string, file: SerializedFile): boolean {\n if (!existsSync(fullPath)) return false;\n try {\n const existing = readFileSync(fullPath);\n return existing.equals(serializedFileBytes(file));\n } catch {\n return false;\n }\n}\n\nfunction semanticallyMatchesExisting(fullPath: string, file: SerializedFile): boolean {\n if (fileContentMatchesExisting(fullPath, file)) {\n return true;\n }\n if (!existsSync(fullPath)) {\n return false;\n }\n try {\n return fileContentsEquivalentForDrift(\n file.path,\n readFileSync(fullPath, \"utf-8\"),\n file.content,\n );\n } catch {\n return false;\n }\n}\n\nfunction isGenerateFilesOptions(\n value: ClaudePluginConfig | GenerateFilesOptions | undefined,\n): value is GenerateFilesOptions {\n return Boolean(\n value &&\n (\"target\" in value ||\n \"claudeConfig\" in value ||\n \"resolvedEnvironment\" in value ||\n \"skillCursorMode\" in value ||\n \"skillSourceRoot\" in value ||\n \"previousManagedPlacements\" in value ||\n \"mergeLiveSkillMarkdown\" in value ||\n \"pinSkillEmits\" in value),\n );\n}\n\n/**\n * Generate platform files from resources without writing to disk.\n * Useful for dry-run / diff.\n */\nexport async function generateFiles(\n resources: Resource[],\n platforms: string[],\n projectRoot: string,\n claudeConfigOrOptions?: ClaudePluginConfig | GenerateFilesOptions,\n maybeOptions?: GenerateFilesOptions,\n): Promise<ApplyResult[]> {\n const options =\n maybeOptions ??\n (isGenerateFilesOptions(claudeConfigOrOptions) ? claudeConfigOrOptions : undefined) ??\n {};\n const claudeConfig =\n maybeOptions?.claudeConfig ??\n (isGenerateFilesOptions(claudeConfigOrOptions)\n ? claudeConfigOrOptions.claudeConfig\n : (claudeConfigOrOptions as ClaudePluginConfig | undefined));\n\n const results: ApplyResult[] = [];\n const target = options.target ?? \"project\";\n const serializedResources = options.resolvedEnvironment\n ? mergeResolvedEnvironmentIntoResources(resources, options.resolvedEnvironment)\n : resources;\n const skillSourceRoot =\n options.skillSourceRoot ??\n resources.find((r) => r.type === \"skill\" && r.origin_ref)?.origin_ref;\n\n const homeRoot = resolveHomeRoot();\n for (const pid of platforms) {\n const platformResources = omitHostPluginBundledSkills(\n serializedResources.filter((resource) => resourceAppliesToHarness(resource, pid)),\n pid,\n homeRoot,\n target,\n );\n const serializer = getPlatformSerializer(pid);\n const surfaceWarnings: SurfaceWarning[] = [];\n const skillNames = new Set(\n platformResources.filter((resource) => resource.type === \"skill\").map((resource) => resource.name),\n );\n const emitResources = platformResources.filter((resource) => {\n if (resource.type === \"command\" && skillNames.has(resource.name)) {\n surfaceWarnings.push({\n harness: pid,\n path: \"\",\n category: \"duplicate-command\",\n message: skippedDuplicateCommand(resource.name),\n alias_harnesses: [],\n });\n return false;\n }\n if (resource.type !== \"hook\") {\n return true;\n }\n if (!hookRequiresPluginRoot(resource.metadata as HookMetadata)) {\n return true;\n }\n surfaceWarnings.push({\n harness: pid,\n path: \".claude/settings.json\",\n category: \"plugin-root-hook\",\n message: skippedHostPluginHook(resource.name),\n alias_harnesses: [],\n });\n return false;\n });\n let files = await serializer.serialize(emitResources, projectRoot, {\n target,\n skillCursorMode: options.skillCursorMode,\n skillSourceRoot,\n projectRoot,\n mergeLiveSkillMarkdown: options.mergeLiveSkillMarkdown,\n surfaceWarnings,\n });\n if (pid === \"claude-code\" && claudeConfig) {\n files = applyClaudePluginExtensions(files, claudeConfig, projectRoot);\n }\n files = await attachResourceOwnership(files, platformResources, {\n platformId: pid,\n rootPath: projectRoot,\n target,\n serializeOptions: {\n skillCursorMode: options.skillCursorMode,\n skillSourceRoot,\n mergeLiveSkillMarkdown: options.mergeLiveSkillMarkdown,\n },\n });\n results.push({\n platformId: pid,\n files,\n ...(surfaceWarnings.length > 0 ? { surface_warnings: surfaceWarnings } : {}),\n });\n }\n\n if (options.pinSkillEmits === false) {\n return results;\n }\n return pinSkillEmitsToExistingLivePaths(\n projectRoot,\n results,\n platforms,\n target,\n options.previousManagedPlacements !== undefined\n ? { previousManagedPlacements: options.previousManagedPlacements }\n : undefined,\n );\n}\n\nfunction normalizeDeployedPath(path: string): string {\n return path.replace(/\\\\/g, \"/\").replace(/^\\.\\//, \"\");\n}\n\nexport function removeStaleProjectDeployedFiles(\n projectRoot: string,\n previousPaths: readonly string[],\n desiredPaths: readonly string[],\n options: SafeFileRemovalOptions = {},\n): SafeFileRemovalResult {\n const desired = new Set(desiredPaths.map(normalizeDeployedPath));\n const stale = previousPaths\n .map(normalizeDeployedPath)\n .filter((path) => path.length > 0 && !desired.has(path));\n return removeGlobalMaterializedFiles(projectRoot, stale, options);\n}\n\n/**\n * Write serialized files to disk, creating directories as needed.\n */\nfunction serializedFileBytes(file: SerializedFile): Buffer {\n if (file.encoding === \"base64\") {\n return Buffer.from(file.content, \"base64\");\n }\n return Buffer.from(file.content, \"utf-8\");\n}\n\nfunction applySerializedFileMode(fullPath: string, file: SerializedFile): void {\n if (typeof file.mode !== \"number\") {\n return;\n }\n try {\n chmodSync(fullPath, file.mode & 0o777);\n } catch {\n // Some filesystems do not support chmod.\n }\n}\n\nfunction writeSerializedFile(fullPath: string, file: SerializedFile): void {\n mkdirSync(dirname(fullPath), { recursive: true });\n writeFileSync(fullPath, serializedFileBytes(file));\n applySerializedFileMode(fullPath, file);\n}\n\nexport function writeFiles(\n files: SerializedFile[],\n projectRoot: string,\n): void {\n pruneManagedCursorLocalPlugins(projectRoot, files);\n for (const file of files) {\n const fullPath = assertMaterializedPathIsSafe(projectRoot, file.path);\n if (semanticallyMatchesExisting(fullPath, file)) {\n continue;\n }\n writeSerializedFile(fullPath, file);\n }\n}\n\nexport async function planMaterializationConflicts(\n files: SerializedFile[],\n rootPath: string,\n): Promise<MaterializationConflict[]> {\n const pathCounts = files.reduce((counts, file) => {\n counts.set(file.path, (counts.get(file.path) ?? 0) + 1);\n return counts;\n }, new Map<string, number>());\n const seen = new Set<string>();\n return files.flatMap((file) => {\n if (seen.has(file.path)) return [];\n seen.add(file.path);\n const fullPath = assertMaterializedPathIsSafe(rootPath, file.path);\n if ((pathCounts.get(file.path) ?? 0) > 1) {\n return [{\n path: file.path,\n fullPath,\n owners: [],\n }];\n }\n if (!existsSync(fullPath)) return [];\n if (fileContentMatchesExisting(fullPath, file)) return [];\n const owners = findImportedSnapshotOwnersByFile(file.path);\n return [{\n path: file.path,\n fullPath,\n owners,\n }];\n });\n}\n\nexport async function materializeFiles(\n files: SerializedFile[],\n rootPath: string,\n options: MaterializeFilesOptions = {},\n): Promise<MaterializationResult> {\n const conflictPolicy = options.conflictPolicy ?? \"replace\";\n const conflicts = await planMaterializationConflicts(files, rootPath);\n const decisions = new Map<string, ConflictResolution>();\n\n for (const conflict of conflicts) {\n if (conflictPolicy === \"replace\") {\n decisions.set(conflict.path, \"replace\");\n continue;\n }\n if (conflictPolicy === \"skip\") {\n decisions.set(conflict.path, \"skip\");\n continue;\n }\n if (conflictPolicy === \"cancel\") {\n decisions.set(conflict.path, \"cancel\");\n break;\n }\n if (\n !options.conflictResolver &&\n isAutoReplaceConflict(\n conflict,\n options.currentSnapshotId,\n options.replaceOwnedSnapshotIds,\n )\n ) {\n decisions.set(conflict.path, \"replace\");\n continue;\n }\n if (!options.conflictResolver) {\n decisions.set(conflict.path, \"cancel\");\n break;\n }\n const decision = await options.conflictResolver(conflict);\n decisions.set(conflict.path, decision);\n if (decision === \"cancel\") {\n break;\n }\n }\n\n if ([...decisions.values()].includes(\"cancel\")) {\n return {\n cancelled: true,\n writtenFiles: [],\n skippedFiles: files\n .filter((file) => decisions.get(file.path) === \"skip\")\n .map((file) => file.path),\n conflicts: conflicts.filter(\n (conflict) =>\n !(\n !options.conflictResolver &&\n isAutoReplaceConflict(\n conflict,\n options.currentSnapshotId,\n options.replaceOwnedSnapshotIds,\n )\n ),\n ),\n };\n }\n\n const writtenFiles: string[] = [];\n const skippedFiles: string[] = [];\n\n if (options.dryRun) {\n const skippedPreexisting = files.filter((file) => {\n if (decisions.get(file.path) === \"skip\") {\n return false;\n }\n if (shouldPreserveUnownedFile(file.path)) {\n const fullMergeable = assertMaterializedPathIsSafe(rootPath, file.path);\n return semanticallyMatchesExisting(fullMergeable, file);\n }\n const fullPath = assertMaterializedPathIsSafe(rootPath, file.path);\n return (\n (existsSync(fullPath) && !isHarnessTapOwnedPath(rootPath, file.path))\n || semanticallyMatchesExisting(fullPath, file)\n );\n });\n const skippedPreexistingPaths = new Set(skippedPreexisting.map((file) => file.path));\n return {\n cancelled: false,\n writtenFiles: files\n .filter((file) =>\n decisions.get(file.path) !== \"skip\" && !skippedPreexistingPaths.has(file.path),\n )\n .map((file) => file.path),\n skippedFiles: files\n .filter((file) =>\n decisions.get(file.path) === \"skip\" || skippedPreexistingPaths.has(file.path),\n )\n .map((file) => file.path),\n conflicts: conflicts.filter(\n (conflict) =>\n !(\n !options.conflictResolver &&\n isAutoReplaceConflict(\n conflict,\n options.currentSnapshotId,\n options.replaceOwnedSnapshotIds,\n )\n ),\n ),\n };\n }\n\n pruneManagedCursorLocalPlugins(rootPath, files);\n for (const file of files) {\n const decision = decisions.get(file.path);\n if (decision === \"skip\") {\n skippedFiles.push(file.path);\n continue;\n }\n const fullPath = assertMaterializedPathIsSafe(rootPath, file.path);\n if (existsSync(fullPath) && !isHarnessTapOwnedPath(rootPath, file.path)) {\n if (!hasHarnessTapMaterialization(rootPath, file.path)) {\n recordPreexistingPath({\n root_path: rootPath,\n path: file.path,\n content_hash: hashOnDiskFile(fullPath) ?? \"\",\n });\n }\n if (!shouldPreserveUnownedFile(file.path)) {\n skippedFiles.push(file.path);\n continue;\n }\n }\n if (semanticallyMatchesExisting(fullPath, file)) {\n skippedFiles.push(file.path);\n continue;\n }\n writeSerializedFile(fullPath, file);\n writtenFiles.push(file.path);\n }\n\n return {\n cancelled: false,\n writtenFiles,\n skippedFiles,\n conflicts: conflicts.filter(\n (conflict) =>\n !(\n !options.conflictResolver &&\n isAutoReplaceConflict(\n conflict,\n options.currentSnapshotId,\n options.replaceOwnedSnapshotIds,\n )\n ),\n ),\n };\n}\n\n/**\n * Full apply: serialize resources for each platform and write to disk.\n */\nexport async function applyToProject(\n resources: Resource[],\n platforms: string[],\n projectRoot: string,\n claudeConfig?: ClaudePluginConfig,\n options: Pick<GenerateFilesOptions, \"skillCursorMode\"> & {\n project_id?: string | null;\n } = {},\n): Promise<ApplyResult[]> {\n const results = await generateFiles(resources, platforms, projectRoot, claudeConfig, {\n target: \"project\",\n skillCursorMode: options.skillCursorMode,\n });\n\n for (const result of results) {\n writeFiles(result.files, projectRoot);\n }\n\n persistWrittenMaterializations({\n scope: \"project\",\n project_id: options.project_id ?? null,\n root_path: projectRoot,\n platformResults: results.map((result) => ({\n platformId: result.platformId,\n files: result.files,\n writtenPaths: result.files.map((file) => file.path),\n })),\n });\n\n return results;\n}\n\nexport async function applyToGlobal(\n resources: Resource[],\n platforms: string[],\n homeRoot: string,\n options: GlobalApplyOptions = {},\n): Promise<GlobalApplyResult> {\n const results = await generateFiles(resources, platforms, homeRoot, {\n ...options,\n target: \"global\",\n });\n const allFiles = results.flatMap((result) => result.files);\n gateDeployFiles(allFiles, { forceUnicode: options.forceUnicode });\n const preApplyState = captureManagedSnapshotState({\n rootPath: homeRoot,\n generated: results,\n extraPaths: options.previousTrackedFiles,\n });\n const materialized = await materializeFiles(allFiles, homeRoot, {\n conflictPolicy: options.conflictPolicy ?? \"prompt\",\n conflictResolver: options.conflictResolver,\n currentSnapshotId: options.snapshotId,\n replaceOwnedSnapshotIds: options.replaceOwnedSnapshotIds,\n });\n\n const ownedSkippedFiles = materialized.skippedFiles.filter((filePath) =>\n isHarnessTapOwnedPath(homeRoot, filePath),\n );\n\n if (!materialized.cancelled) {\n persistWrittenMaterializations({\n scope: \"global\",\n project_id: null,\n root_path: homeRoot,\n platformResults: results.map((result) => ({\n platformId: result.platformId,\n files: result.files,\n writtenPaths: materialized.writtenFiles.filter((filePath) =>\n result.files.some((file) => file.path === filePath),\n ),\n })),\n });\n }\n\n if (!materialized.cancelled && options.snapshotId) {\n const currentlyOwnedPaths = [\n ...new Set([...materialized.writtenFiles, ...ownedSkippedFiles]),\n ];\n removeImportedSnapshotOwnershipForFiles(currentlyOwnedPaths, options.snapshotId);\n for (const result of results) {\n const emittedFiles = result.files.map((file) => file.path);\n const writtenFiles = emittedFiles.filter((filePath) =>\n materialized.writtenFiles.includes(filePath),\n );\n const preservedSkippedFiles = emittedFiles.filter(\n (filePath) =>\n materialized.skippedFiles.includes(filePath)\n && ownedSkippedFiles.includes(filePath),\n );\n const installFiles = [...new Set([...writtenFiles, ...preservedSkippedFiles])];\n if (installFiles.length === 0) continue;\n recordImportedSnapshotInstall({\n snapshot_id: options.snapshotId,\n platform_id: result.platformId,\n files: installFiles,\n });\n }\n\n const desiredFiles = new Set(allFiles.map((file) => file.path));\n const staleFiles = [\n ...new Set(\n [options.snapshotId, ...(options.replaceOwnedSnapshotIds ?? [])]\n .flatMap((snapshotId) => listImportedSnapshotInstalls(snapshotId))\n .flatMap((install) => install.files)\n .filter((filePath) => !desiredFiles.has(filePath)),\n ),\n ];\n removeMaterializedFiles(homeRoot, staleFiles, {\n applyId: options.snapshotId,\n snapshotId: options.snapshotId,\n });\n removeImportedSnapshotOwnershipForFiles(staleFiles);\n }\n\n return {\n results,\n ...materialized,\n preApplyState,\n };\n}\n\nexport async function applyImportedSnapshotToGlobal(\n snapshotId: string,\n platforms: string[],\n homeRoot: string,\n options: Omit<GlobalApplyOptions, \"snapshotId\"> = {},\n): Promise<GlobalApplyResult> {\n const snapshot = getImportedSnapshot(snapshotId);\n if (!snapshot) {\n throw new Error(`Imported snapshot not found: ${snapshotId}`);\n }\n\n const resources = getResourcesByIds(snapshot.resource_ids);\n if (resources.length !== snapshot.resource_ids.length) {\n throw new Error(`Imported snapshot ${snapshotId} is missing one or more resources`);\n }\n\n const replaceOwnedSnapshotIds = listImportedSnapshots()\n .filter((candidate) =>\n candidate.id !== snapshot.id &&\n candidate.source_kind === snapshot.source_kind &&\n candidate.source_label === snapshot.source_label &&\n candidate.plugin_name === snapshot.plugin_name,\n )\n .map((candidate) => candidate.id);\n\n return applyToGlobal(resources, platforms, homeRoot, {\n ...options,\n snapshotId,\n replaceOwnedSnapshotIds,\n });\n}\n","import { readFileSync, existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n getInstalledPluginRecord,\n type InstalledPluginsFile,\n} from \"../plugins/claude-installed.js\";\nimport type { ClaudePluginConfig, SerializedFile } from \"../types.js\";\n\nconst SETTINGS_PATH = \".claude/settings.json\";\nconst INSTALLED_PLUGINS_PATH = \".claude/plugins/installed_plugins.json\";\n\nfunction readExistingSettings(projectRoot: string): Record<string, unknown> {\n const fullPath = join(projectRoot, SETTINGS_PATH);\n if (!existsSync(fullPath)) return {};\n\n try {\n return JSON.parse(readFileSync(fullPath, \"utf-8\")) as Record<string, unknown>;\n } catch {\n return {};\n }\n}\n\nfunction mergeRecord<T extends Record<string, unknown>>(\n base: T | undefined,\n patch: T,\n): T {\n return { ...(base ?? {}), ...patch };\n}\n\nfunction parseObject(raw: string | undefined): Record<string, unknown> {\n if (!raw) return {};\n try {\n const parsed: unknown = JSON.parse(raw);\n if (typeof parsed === \"object\" && parsed !== null && !Array.isArray(parsed)) {\n return parsed as Record<string, unknown>;\n }\n } catch {\n return {};\n }\n return {};\n}\n\nfunction generatedInstalledRefs(files: readonly SerializedFile[]): Set<string> {\n const raw = files.find((file) => file.path === INSTALLED_PLUGINS_PATH)?.content;\n const parsed = parseObject(raw) as unknown as InstalledPluginsFile;\n return new Set(Object.keys(parsed.plugins ?? {}));\n}\n\nfunction enabledPluginsRecord(value: unknown): Record<string, boolean> {\n if (value && typeof value === \"object\" && !Array.isArray(value)) {\n return { ...(value as Record<string, boolean>) };\n }\n return {};\n}\n\n/**\n * Merge Claude marketplace and plugin config into serialized files.\n * `enabledPlugins` is merged key by key and never replaces unrelated entries.\n * A pin this apply is writing into installed_plugins.json counts as installed\n * even before that file is flushed to disk.\n */\nexport function applyClaudePluginExtensions(\n files: SerializedFile[],\n config: ClaudePluginConfig | undefined,\n projectRoot: string,\n): SerializedFile[] {\n if (!config || (!config.marketplaces && !config.plugins)) {\n return files;\n }\n\n const settings = readExistingSettings(projectRoot);\n const generatedSettings = parseObject(\n files.find((file) => file.path === SETTINGS_PATH)?.content,\n );\n const pendingInstalls = generatedInstalledRefs(files);\n\n if (config.marketplaces && Object.keys(config.marketplaces).length > 0) {\n settings.extraKnownMarketplaces = mergeRecord(\n settings.extraKnownMarketplaces as Record<string, unknown> | undefined,\n config.marketplaces as Record<string, unknown>,\n );\n }\n\n if (config.plugins && config.plugins.length > 0) {\n const enabledPlugins = {\n ...enabledPluginsRecord(settings.enabledPlugins),\n ...enabledPluginsRecord(generatedSettings.enabledPlugins),\n };\n for (const plugin of config.plugins) {\n const installed =\n Boolean(getInstalledPluginRecord(projectRoot, plugin.id))\n || pendingInstalls.has(plugin.id);\n if (installed) {\n enabledPlugins[plugin.id] = plugin.enabled !== false;\n }\n }\n if (Object.keys(enabledPlugins).length > 0) {\n settings.enabledPlugins = enabledPlugins;\n } else {\n delete settings.enabledPlugins;\n }\n }\n\n const hasMarketplace =\n settings.extraKnownMarketplaces\n && typeof settings.extraKnownMarketplaces === \"object\"\n && Object.keys(settings.extraKnownMarketplaces as Record<string, unknown>).length > 0;\n const hasEnabled =\n settings.enabledPlugins\n && typeof settings.enabledPlugins === \"object\"\n && Object.keys(settings.enabledPlugins as Record<string, unknown>).length > 0;\n const withoutSettings = files.filter((file) => file.path !== SETTINGS_PATH);\n const existingSettings = files.find((file) => file.path === SETTINGS_PATH);\n\n if (existingSettings) {\n try {\n const generated = JSON.parse(existingSettings.content) as Record<string, unknown>;\n const overlay: Record<string, unknown> = { ...generated };\n if (hasMarketplace) {\n overlay.extraKnownMarketplaces = mergeRecord(\n generated.extraKnownMarketplaces as Record<string, unknown> | undefined,\n settings.extraKnownMarketplaces as Record<string, unknown>,\n );\n }\n if (hasEnabled) {\n overlay.enabledPlugins = mergeRecord(\n enabledPluginsRecord(generated.enabledPlugins),\n enabledPluginsRecord(settings.enabledPlugins),\n );\n }\n return [\n ...withoutSettings,\n { path: SETTINGS_PATH, content: JSON.stringify(overlay, null, 2) },\n ];\n } catch {\n return [...withoutSettings, { path: SETTINGS_PATH, content: JSON.stringify(settings, null, 2) }];\n }\n }\n\n if (!hasMarketplace && !hasEnabled && Object.keys(settings).length === 0) {\n return files;\n }\n\n return [...withoutSettings, { path: SETTINGS_PATH, content: JSON.stringify(settings, null, 2) }];\n}\n","import { existsSync, readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport matter from \"gray-matter\";\nimport { getPlatform } from \"../platforms/registry.js\";\n\nexport const CURSOR_HOST_MANAGED_SKILLS_DISPLAY_ROOT =\n \"~/.cursor/skills-cursor\";\nexport const CURSOR_USER_SKILLS_DISPLAY_ROOT = \"~/.cursor/skills\";\n\nconst CURSOR_HOST_MANAGED_SKILLS_PATH_RE =\n /(^|\\/)\\.cursor\\/skills-cursor(\\/|$)/;\n\n/** True for Cursor app-managed `~/.cursor/skills-cursor` (and files under it). */\nexport function isCursorHostManagedSkillsPath(path: string): boolean {\n return CURSOR_HOST_MANAGED_SKILLS_PATH_RE.test(path.replace(/\\\\/g, \"/\"));\n}\n\nexport type CursorHostSkillOverlap = \"user_skill\" | \"profile_skill\";\n\nexport interface CursorHostManagedSkill {\n name: string;\n source: string;\n description: string;\n}\n\nexport interface CursorHostManagedSkillCollision {\n name: string;\n host_source: string;\n user_source: string;\n overlap: CursorHostSkillOverlap;\n}\n\nexport interface CursorHostManagedSkillsStatus {\n skills: CursorHostManagedSkill[];\n collisions: CursorHostManagedSkillCollision[];\n}\n\nexport interface HostManagedStatus {\n cursor?: CursorHostManagedSkillsStatus;\n}\n\nfunction resolveConfiguredHomePath(\n homeRoot: string,\n configuredPath: string,\n): string {\n return configuredPath.startsWith(\"~/\")\n ? join(homeRoot, configuredPath.slice(2))\n : join(homeRoot, configuredPath);\n}\n\nfunction hostManagedSkillsConfiguredPath(): string {\n const platform = getPlatform(\"cursor\");\n return (\n platform?.hostManagedPaths?.skills ?? `${CURSOR_HOST_MANAGED_SKILLS_DISPLAY_ROOT}/`\n );\n}\n\nfunction userSkillsConfiguredPath(): string {\n const platform = getPlatform(\"cursor\");\n return platform?.globalPaths.skills ?? `${CURSOR_USER_SKILLS_DISPLAY_ROOT}/`;\n}\n\nfunction tryParseSkillFrontmatter(content: string):\n | { data: Record<string, unknown>; content: string }\n | undefined {\n try {\n const parsed = matter(content);\n if (content.startsWith(\"---\") && parsed.content === content) {\n return undefined;\n }\n return {\n data: parsed.data as Record<string, unknown>,\n content: parsed.content,\n };\n } catch {\n return undefined;\n }\n}\n\n/** Read-only inventory of Cursor app-managed skills under skills-cursor. */\nexport function scanCursorHostManagedSkills(\n homeRoot: string,\n): CursorHostManagedSkill[] {\n const configured = hostManagedSkillsConfiguredPath();\n const fullPath = resolveConfiguredHomePath(homeRoot, configured);\n if (!existsSync(fullPath)) {\n return [];\n }\n\n let entries: string[];\n try {\n entries = readdirSync(fullPath);\n } catch {\n return [];\n }\n\n const displayRoot = configured.replace(/\\/$/, \"\");\n const skills: CursorHostManagedSkill[] = [];\n\n for (const entry of entries) {\n const entryPath = join(fullPath, entry);\n const skillMd = join(entryPath, \"SKILL.md\");\n try {\n if (!statSync(entryPath).isDirectory() || !existsSync(skillMd)) {\n continue;\n }\n } catch {\n continue;\n }\n\n let raw: string;\n try {\n raw = readFileSync(skillMd, \"utf-8\");\n } catch {\n continue;\n }\n\n const parsed = tryParseSkillFrontmatter(raw);\n if (!parsed) {\n continue;\n }\n\n const name =\n typeof parsed.data[\"name\"] === \"string\" && parsed.data[\"name\"].trim()\n ? parsed.data[\"name\"].trim()\n : entry;\n const description =\n typeof parsed.data[\"description\"] === \"string\"\n ? parsed.data[\"description\"]\n : \"\";\n\n skills.push({\n name,\n source: `${displayRoot}/${entry}/SKILL.md`,\n description,\n });\n }\n\n return skills.sort((left, right) => left.name.localeCompare(right.name));\n}\n\nfunction userSkillSourceForName(name: string): string {\n const configured = userSkillsConfiguredPath().replace(/\\/$/, \"\");\n return `${configured}/${name}/SKILL.md`;\n}\n\nfunction profileSkillSource(\n profileSkills: ReadonlyMap<string, string>,\n name: string,\n): string {\n return profileSkills.get(name) ?? `profile skill:${name}`;\n}\n\nexport function detectCursorHostManagedSkillCollisions(input: {\n hostSkills: readonly CursorHostManagedSkill[];\n homeRoot: string;\n /** Map of profile skill name → source path/label. */\n profileSkills?: ReadonlyMap<string, string>;\n}): CursorHostManagedSkillCollision[] {\n const userSkillsRoot = resolveConfiguredHomePath(\n input.homeRoot,\n userSkillsConfiguredPath(),\n );\n const profileSkills = input.profileSkills ?? new Map<string, string>();\n const collisions: CursorHostManagedSkillCollision[] = [];\n\n for (const host of input.hostSkills) {\n const userSkillMd = join(userSkillsRoot, host.name, \"SKILL.md\");\n if (existsSync(userSkillMd)) {\n collisions.push({\n name: host.name,\n host_source: host.source,\n user_source: userSkillSourceForName(host.name),\n overlap: \"user_skill\",\n });\n }\n\n if (profileSkills.has(host.name)) {\n collisions.push({\n name: host.name,\n host_source: host.source,\n user_source: profileSkillSource(profileSkills, host.name),\n overlap: \"profile_skill\",\n });\n }\n }\n\n return collisions.sort((left, right) => {\n const byName = left.name.localeCompare(right.name);\n if (byName !== 0) return byName;\n return left.overlap.localeCompare(right.overlap);\n });\n}\n\nexport function buildCursorHostManagedStatus(input: {\n homeRoot: string;\n profileSkills?: ReadonlyMap<string, string>;\n}): CursorHostManagedSkillsStatus {\n const skills = scanCursorHostManagedSkills(input.homeRoot);\n const collisions = detectCursorHostManagedSkillCollisions({\n hostSkills: skills,\n homeRoot: input.homeRoot,\n profileSkills: input.profileSkills,\n });\n return { skills, collisions };\n}\n\nexport function buildHostManagedStatus(input: {\n homeRoot: string;\n profileSkills?: ReadonlyMap<string, string>;\n}): HostManagedStatus {\n return {\n cursor: buildCursorHostManagedStatus(input),\n };\n}\n\nexport function profileSkillNameMap(\n resources: ReadonlyArray<{ type: string; name: string; source: string }>,\n): Map<string, string> {\n const map = new Map<string, string>();\n for (const resource of resources) {\n if (resource.type !== \"skill\") continue;\n if (!map.has(resource.name)) {\n map.set(resource.name, resource.source);\n }\n }\n return map;\n}\n","import { existsSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { getPlatform } from \"../platforms/registry.js\";\nimport type { Resource, ResourceCreateInput, SerializerTarget } from \"../types.js\";\nimport { hostPluginPinIsInstalled } from \"./host-native-mcp.js\";\nimport {\n type HostPluginLayout,\n isHostPluginPinResource,\n} from \"./host-plugin-serialize.js\";\nimport { materializeFromSource } from \"./link-materialize.js\";\nimport type { PluginResourceMode } from \"./plugin-resource-mode.js\";\nimport { scanPluginSourceForMerge } from \"./plugin-source-import.js\";\nimport { resourceIdentity } from \"./reference-resources.js\";\nimport { resolveInstallRoot } from \"./resource-sync.js\";\nimport {\n normalizeSkillDir,\n skillConsumeDirs,\n} from \"./shared-emit-paths.js\";\nimport {\n type PluginTranslationSource,\n pluginTranslationSourceFromPin,\n} from \"./plugin-translation-source.js\";\n\nexport const HOST_PLUGIN_TREE_PLATFORMS: ReadonlySet<HostPluginLayout> = new Set([\n \"claude-code\",\n \"cursor\",\n]);\n\nexport function isHostPluginTreePlatform(id: string): id is HostPluginLayout {\n return id === \"claude-code\" || id === \"cursor\";\n}\n\nexport function portableHarnessesForPluginFanout(\n platforms: readonly string[],\n): string[] {\n return platforms.filter((id) => !isHostPluginTreePlatform(id));\n}\n\nconst HOST_PLUGIN_BUNDLED_TYPES = new Set([\"skill\", \"command\", \"agent\", \"hook\"]);\n\nfunction importedFromPluginName(\n resource: Pick<Resource, \"metadata\">,\n): string | undefined {\n const imported = (resource.metadata as { imported_from?: { plugin_name?: unknown } } | undefined)\n ?.imported_from;\n if (typeof imported?.plugin_name === \"string\" && imported.plugin_name.trim()) {\n return imported.plugin_name.trim();\n }\n return undefined;\n}\n\nfunction isHostPluginBundledMaterial(\n resource: Pick<Resource, \"type\" | \"name\" | \"origin_kind\" | \"origin_ref\" | \"metadata\">,\n pins: ReadonlySet<string>,\n pinNames: ReadonlySet<string>,\n homeRoot: string,\n): boolean {\n if (!HOST_PLUGIN_BUNDLED_TYPES.has(resource.type)) {\n return false;\n }\n const originRef = resource.origin_ref?.trim() ?? \"\";\n if (originRef && pins.has(originRef)) {\n return true;\n }\n const pluginName = importedFromPluginName(resource);\n if (pluginName && pinNames.has(pluginName)) {\n return true;\n }\n if (pins.has(`${resource.name}@local`) || pins.has(resource.name)) {\n return (\n resource.origin_kind === \"marketplace_link\"\n || resource.origin_kind === \"local_snapshot\"\n );\n }\n if (\n resource.origin_kind === \"marketplace_link\"\n && originRef.includes(\"@\")\n && hostPluginPinIsInstalled(homeRoot, originRef)\n ) {\n return true;\n }\n return false;\n}\n\n/**\n * Cursor and Claude Code load marketplace plugins from the host plugin tree.\n * Do not also serialize those bundled skills as standalone `skills/` dirs.\n * Portable harnesses (OpenCode, Codex, ...) still receive them as skills.\n */\nexport function omitHostPluginBundledSkills(\n resources: readonly Resource[],\n platformId: string,\n homeRoot: string,\n target: SerializerTarget = \"project\",\n): Resource[] {\n if (!isHostPluginTreePlatform(platformId)) {\n return [...resources];\n }\n // Cursor project skills land in `.agents/skills/` for aliases. Only skip\n // the global `~/.cursor/skills/` copies; Claude native skills duplicate the\n // host plugin at both scopes.\n if (platformId === \"cursor\" && target !== \"global\") {\n return [...resources];\n }\n const pinResources = resources.filter((resource) => isHostPluginPinResource(resource));\n const pins = new Set(\n pinResources.map((resource) => resource.origin_ref || resource.name),\n );\n const pinNames = new Set(pinResources.map((resource) => resource.name));\n return resources.filter(\n (resource) => !isHostPluginBundledMaterial(resource, pins, pinNames, homeRoot),\n );\n}\n\nexport interface ExtractedPluginSkill {\n name: string;\n sourceDir: string;\n plugin: PluginTranslationSource;\n}\n\nexport interface ExtractHostPluginMaterialResult {\n skills: ExtractedPluginSkill[];\n resources: ResourceCreateInput[];\n resourcePlugins: Map<string, PluginTranslationSource>;\n}\n\nfunction isHostPluginPinInput(\n resource: ResourceCreateInput,\n): boolean {\n return isHostPluginPinResource({\n type: resource.type,\n metadata: resource.metadata,\n origin_ref: resource.origin_ref ?? \"\",\n });\n}\n\nfunction skillSourceDir(\n installRoot: string,\n resource: ResourceCreateInput,\n): string | undefined {\n const relative = resource.source.replace(/\\\\/g, \"/\");\n const dir = join(installRoot, dirname(relative));\n if (!existsSync(join(dir, \"SKILL.md\"))) return undefined;\n return dir;\n}\n\n/**\n * Pull skills and other material out of Claude/Cursor host plugin install trees\n * so harnesses that do not load those trees (OpenCode, Codex, ...) can use them.\n */\nexport async function extractHostPluginMaterial(\n pins: readonly ResourceCreateInput[],\n homeRoot: string,\n occupiedIdentities: ReadonlySet<string> = new Set(),\n): Promise<ExtractHostPluginMaterialResult> {\n const skills: ExtractedPluginSkill[] = [];\n const resources: ResourceCreateInput[] = [];\n const resourcePlugins = new Map<string, PluginTranslationSource>();\n const seenSkills = new Set<string>();\n const seenIdentities = new Set<string>(occupiedIdentities);\n\n for (const identity of occupiedIdentities) {\n if (identity.startsWith(\"skill:\")) {\n const name = identity.slice(\"skill:\".length).split(\":\")[0];\n if (name) seenSkills.add(name);\n }\n }\n\n for (const pin of pins) {\n if (!isHostPluginPinInput(pin)) continue;\n const originRef = pin.origin_ref;\n if (!originRef) continue;\n const installRoot = resolveInstallRoot(originRef, homeRoot);\n if (!installRoot || !existsSync(installRoot)) continue;\n const pluginSource = pluginTranslationSourceFromPin(pin);\n if (!pluginSource) continue;\n\n const scans = await scanPluginSourceForMerge(installRoot);\n for (const scan of scans) {\n for (const resource of scan.resources) {\n if (resource.type === \"skill\") {\n if (seenSkills.has(resource.name)) continue;\n const sourceDir = skillSourceDir(installRoot, resource);\n if (!sourceDir) continue;\n seenSkills.add(resource.name);\n skills.push({ name: resource.name, sourceDir, plugin: pluginSource });\n continue;\n }\n const identity = resourceIdentity(resource);\n if (seenIdentities.has(identity)) continue;\n seenIdentities.add(identity);\n resources.push(resource);\n resourcePlugins.set(identity, pluginSource);\n }\n }\n }\n\n return { skills, resources, resourcePlugins };\n}\n\nexport function agentsSkillHubPrefix(): string {\n return \".agents/skills/\";\n}\n\nexport function nativeSkillDir(\n platformId: string,\n target: SerializerTarget,\n): string | undefined {\n const platform = getPlatform(platformId);\n if (!platform) return undefined;\n const raw =\n target === \"global\"\n ? platform.globalPaths.skills\n : platform.projectPaths.skills;\n return normalizeSkillDir(raw);\n}\n\nexport interface SkillHubPlan {\n /** Relative destination directory under the sync root (no trailing slash). */\n destDir: string;\n sourceDir: string;\n skillMdPath: string;\n}\n\n/**\n * Plan `.agents/skills/{name}` hub entries plus fan-out into native skill dirs\n * that cannot read the shared hub.\n */\nexport function planPluginSkillHub(\n skills: readonly ExtractedPluginSkill[],\n portablePlatforms: readonly string[],\n target: SerializerTarget,\n): SkillHubPlan[] {\n const hub = agentsSkillHubPrefix();\n const plans: SkillHubPlan[] = [];\n const seen = new Set<string>();\n\n const push = (destDir: string, sourceDir: string): void => {\n const normalized = destDir.replace(/\\\\/g, \"/\").replace(/\\/+$/, \"\");\n if (seen.has(normalized)) return;\n seen.add(normalized);\n plans.push({\n destDir: normalized,\n sourceDir,\n skillMdPath: `${normalized}/SKILL.md`,\n });\n };\n\n for (const skill of skills) {\n push(`${hub}${skill.name}`, skill.sourceDir);\n for (const platformId of portablePlatforms) {\n const consume = new Set(skillConsumeDirs(platformId, target));\n if (consume.has(hub)) continue;\n const native = nativeSkillDir(platformId, target);\n if (!native || native === hub) continue;\n push(`${native}${skill.name}`, skill.sourceDir);\n }\n }\n\n return plans;\n}\n\nexport function materializeSkillHubPlan(\n rootPath: string,\n plans: readonly SkillHubPlan[],\n mode: PluginResourceMode,\n): void {\n for (const plan of plans) {\n materializeFromSource(join(rootPath, plan.destDir), plan.sourceDir, mode);\n }\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { loadInstalled, parsePluginRef } from \"../plugins/claude-installed.js\";\nimport { findInstalledRefForCatalogPin } from \"../plugins/claude-plugin-ref.js\";\nimport { listCursorNativeMcpPluginNames } from \"../plugins/cursor-enablement.js\";\nimport { listCursorPluginInstalls } from \"../plugins/providers/cursor.js\";\nimport { parseMcpServersDocument } from \"./mcp-config-bridge.js\";\n\nconst PLUGIN_MCP_FILES = [\"mcp.json\", \".mcp.json\"] as const;\n\nfunction mcpNamesFromInstallPath(installPath: string): string[] {\n const names: string[] = [];\n for (const fileName of PLUGIN_MCP_FILES) {\n const fullPath = join(installPath, fileName);\n if (!existsSync(fullPath)) {\n continue;\n }\n try {\n const document = JSON.parse(readFileSync(fullPath, \"utf-8\")) as unknown;\n names.push(...Object.keys(parseMcpServersDocument(document)));\n } catch {\n // skip invalid plugin MCP payloads\n }\n }\n return names;\n}\n\n/**\n * MCP server names provided by the host harness (Cursor/Claude plugin MCP),\n * not by HarnessTap-managed `mcp.json`.\n */\nexport function listHostNativeMcpNames(\n homeRoot: string,\n harnessId: string,\n): Set<string> {\n const names = new Set<string>();\n switch (harnessId) {\n case \"cursor\": {\n for (const name of listCursorNativeMcpPluginNames(homeRoot)) {\n names.add(name);\n }\n for (const install of listCursorPluginInstalls(homeRoot)) {\n if (!install.installPath) {\n continue;\n }\n for (const name of mcpNamesFromInstallPath(install.installPath)) {\n names.add(name);\n }\n }\n break;\n }\n case \"claude-code\": {\n for (const install of loadInstalled(homeRoot)) {\n if (!install.installPath) {\n continue;\n }\n for (const name of mcpNamesFromInstallPath(install.installPath)) {\n names.add(name);\n }\n }\n break;\n }\n default:\n break;\n }\n return names;\n}\n\nexport function hostPluginPinIsInstalled(homeRoot: string, pinRef: string): boolean {\n if (findInstalledRefForCatalogPin(pinRef, homeRoot)) {\n return true;\n }\n const { name } = parsePluginRef(pinRef);\n return listCursorPluginInstalls(homeRoot).some(\n (row) => row.ref === pinRef || row.name === name,\n );\n}\n","import { join } from \"node:path\";\nimport {\n collectCursorEnablementSignals,\n type CollectCursorEnablementSignals,\n} from \"../cursor-enablement.js\";\nimport { listCursorPluginInstalls } from \"../cursor-inventory.js\";\nimport {\n getSourcesToRefresh,\n markSourceRefreshed,\n} from \"../refresh-cache.js\";\nimport {\n cursorRepoSourceKey,\n refreshGitSource,\n} from \"../refresh.js\";\nimport { defaultRunCommand, type RunCommand } from \"../run-command.js\";\nimport { installCursorLocalPlugin } from \"../cursor-local-install.js\";\nimport type {\n PluginCheckOptions,\n PluginCheckResult,\n PluginContext,\n PluginInstall,\n PluginInstallOptions,\n PluginInstallResult,\n PluginProvider,\n PluginUpdateOptions,\n PluginUpdateResult,\n} from \"../types.js\";\n\nexport {\n listCursorPluginFootprintNames,\n listCursorPluginInstalls,\n} from \"../cursor-inventory.js\";\n\nexport interface CursorProviderDeps {\n runCommand?: RunCommand;\n collectEnablementSignals?: CollectCursorEnablementSignals;\n}\n\nexport class CursorPluginProvider implements PluginProvider {\n readonly platformId = \"cursor\";\n readonly capabilities = {\n inventory: true,\n check: true,\n update: true,\n install: true,\n updateMethod: \"git\" as const,\n installMethod: \"unsupported\" as const,\n };\n\n constructor(private readonly deps: CursorProviderDeps = {}) {}\n\n private collectSignals(): CollectCursorEnablementSignals {\n return this.deps.collectEnablementSignals ?? collectCursorEnablementSignals;\n }\n\n async list(ctx: PluginContext): Promise<PluginInstall[]> {\n return listCursorPluginInstalls(ctx.homeRoot, this.collectSignals());\n }\n\n async check(\n ctx: PluginContext,\n opts: PluginCheckOptions,\n ): Promise<PluginCheckResult[]> {\n const installs = listCursorPluginInstalls(\n ctx.homeRoot,\n this.collectSignals(),\n );\n const results: PluginCheckResult[] = [];\n\n for (const install of installs) {\n if (opts.scopes && !opts.scopes.includes(install.scope)) continue;\n const repo = install.metadata?.repository;\n if (!repo) {\n results.push({\n ...install,\n status: \"unknown\",\n message: \"No repository URL; update via Cursor IDE\",\n refreshSkipped: true,\n });\n continue;\n }\n\n const sourceKey = cursorRepoSourceKey(repo);\n const shouldRefresh = getSourcesToRefresh(\n [sourceKey],\n opts.refreshCache,\n opts.maxAgeHours,\n opts.forceRefresh,\n ).includes(sourceKey);\n\n let latestVersion: string | undefined;\n if (shouldRefresh) {\n const tmpParent = join(ctx.harnesstapDir, \"tmp-refresh\");\n const refresh = refreshGitSource({\n url: repo,\n targetDir: join(tmpParent, install.name),\n runCommand: this.deps.runCommand,\n });\n if (refresh.ok && refresh.sha) {\n latestVersion = refresh.sha.slice(0, 12);\n Object.assign(\n opts.refreshCache,\n markSourceRefreshed(opts.refreshCache, sourceKey),\n );\n }\n }\n\n const installedHash = install.installPath?.split(\"/\").pop();\n const status: PluginCheckResult[\"status\"] =\n latestVersion && installedHash\n ? latestVersion === installedHash.slice(0, 12) ||\n installedHash.startsWith(latestVersion)\n ? \"current\"\n : \"outdated\"\n : \"unknown\";\n\n results.push({\n ...install,\n status,\n latestVersion,\n latestSource: sourceKey,\n refreshSkipped: !shouldRefresh,\n });\n }\n return results;\n }\n\n async update(\n ctx: PluginContext,\n opts: PluginUpdateOptions,\n ): Promise<PluginUpdateResult[]> {\n const installs = listCursorPluginInstalls(\n ctx.homeRoot,\n this.collectSignals(),\n );\n const targets = opts.ref\n ? installs.filter((i) => i.ref === opts.ref)\n : installs;\n const results: PluginUpdateResult[] = [];\n\n for (const install of targets) {\n const repo = install.metadata?.repository;\n if (!repo) {\n results.push({\n ref: install.ref,\n platformId: this.platformId,\n scope: install.scope,\n status: \"unsupported\",\n message: \"No repository URL; update via Cursor IDE\",\n });\n continue;\n }\n if (!install.installPath) {\n results.push({\n ref: install.ref,\n platformId: this.platformId,\n scope: install.scope,\n status: \"failed\",\n message: \"Missing install path\",\n });\n continue;\n }\n\n const parent = join(install.installPath, \"..\");\n const refresh = refreshGitSource({\n url: repo,\n targetDir: join(parent, \".refresh-staging\"),\n runCommand: this.deps.runCommand,\n });\n if (!refresh.ok || !refresh.sha) {\n results.push({\n ref: install.ref,\n platformId: this.platformId,\n scope: install.scope,\n status: \"failed\",\n previousVersion: install.version,\n message: refresh.message,\n });\n continue;\n }\n\n const newDir = join(parent, refresh.sha.slice(0, 12));\n const staging = join(parent, \".refresh-staging\");\n const move = (this.deps.runCommand ?? defaultRunCommand)(\"mv\", [\n staging,\n newDir,\n ]);\n if (move.exitCode !== 0) {\n results.push({\n ref: install.ref,\n platformId: this.platformId,\n scope: install.scope,\n status: \"failed\",\n message: move.stderr.trim() || \"Failed to move refreshed plugin\",\n });\n continue;\n }\n\n results.push({\n ref: install.ref,\n platformId: this.platformId,\n scope: install.scope,\n status: \"updated\",\n previousVersion: install.version,\n newVersion: refresh.sha.slice(0, 12),\n message: \"Refreshed from git repository\",\n });\n }\n return results;\n }\n\n async install(\n ctx: PluginContext,\n opts: PluginInstallOptions,\n ): Promise<PluginInstallResult> {\n return installCursorLocalPlugin(ctx, opts);\n }\n}\n","import { existsSync, readFileSync, writeFileSync, mkdirSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nexport interface RefreshCacheEntry {\n lastRefreshedAt: string;\n}\n\nexport interface RefreshCacheFile {\n sources: Record<string, RefreshCacheEntry>;\n}\n\nconst EMPTY_CACHE: RefreshCacheFile = { sources: {} };\n\nexport function loadRefreshCache(harnesstapDir: string): RefreshCacheFile {\n const path = join(harnesstapDir, \"plugin-refresh-cache.json\");\n if (!existsSync(path)) return { ...EMPTY_CACHE };\n try {\n const raw = JSON.parse(readFileSync(path, \"utf-8\")) as Partial<RefreshCacheFile>;\n return { sources: raw.sources ?? {} };\n } catch {\n return { ...EMPTY_CACHE };\n }\n}\n\nexport function saveRefreshCache(\n harnesstapDir: string,\n cache: RefreshCacheFile,\n): void {\n mkdirSync(harnesstapDir, { recursive: true });\n const path = join(harnesstapDir, \"plugin-refresh-cache.json\");\n writeFileSync(path, `${JSON.stringify(cache, null, 2)}\\n`, \"utf-8\");\n}\n\nexport function markSourceRefreshed(\n cache: RefreshCacheFile,\n sourceKey: string,\n at: Date = new Date(),\n): RefreshCacheFile {\n return {\n sources: {\n ...cache.sources,\n [sourceKey]: { lastRefreshedAt: at.toISOString() },\n },\n };\n}\n\nexport function isSourceStale(\n cache: RefreshCacheFile,\n sourceKey: string,\n maxAgeHours: number,\n now: Date = new Date(),\n): boolean {\n const entry = cache.sources[sourceKey];\n if (!entry?.lastRefreshedAt) return true;\n const refreshed = new Date(entry.lastRefreshedAt);\n const ageMs = now.getTime() - refreshed.getTime();\n return ageMs > maxAgeHours * 60 * 60 * 1000;\n}\n\nexport function getSourcesToRefresh(\n sourceKeys: string[],\n cache: RefreshCacheFile,\n maxAgeHours: number,\n forceRefresh: boolean,\n now: Date = new Date(),\n): string[] {\n if (forceRefresh) return [...sourceKeys];\n return sourceKeys.filter((key) => isSourceStale(cache, key, maxAgeHours, now));\n}\n","import { writeFiles } from \"../services/applier.js\";\nimport { emitHostPluginTrees } from \"../services/host-plugin-serialize.js\";\nimport { resolveInstallRoot } from \"../services/resource-sync.js\";\nimport type { Resource } from \"../types.js\";\nimport { parsePluginRef } from \"./host-plugin-manifest.js\";\nimport { listCursorPluginInstalls } from \"./cursor-inventory.js\";\nimport type { PluginContext, PluginInstallOptions, PluginInstallResult } from \"./types.js\";\n\nfunction pinResource(ref: string): Resource {\n const parsed = parsePluginRef(ref);\n const marketplace = parsed.marketplace || \"local\";\n return {\n id: \"\",\n type: \"plugin\",\n name: parsed.name,\n description: \"\",\n content: \"{}\",\n metadata: {\n source_kind: marketplace === \"local\" ? \"local\" : \"marketplace\",\n ...(marketplace === \"local\" ? {} : { marketplace_name: marketplace }),\n },\n source: \"\",\n namespace: marketplace,\n origin_kind: marketplace === \"local\" ? \"manual\" : \"marketplace_link\",\n origin_ref: ref,\n content_hash: \"\",\n content_blob_ref: \"\",\n created_at: \"\",\n updated_at: \"\",\n };\n}\n\nfunction marketplaceShadows(homeRoot: string, name: string): boolean {\n return listCursorPluginInstalls(homeRoot).some(\n (install) => install.scope !== \"local\" && install.enabled && install.name === name,\n );\n}\n\n/**\n * Copy an on-disk plugin tree into `~/.cursor/plugins/local`. Cursor loads that\n * directory on reload. Marketplace installs of the same name are left alone.\n */\nexport function installCursorLocalPlugin(\n ctx: PluginContext,\n opts: PluginInstallOptions,\n): PluginInstallResult {\n const ref = opts.ref;\n const scope = opts.scope ?? \"user\";\n const parsed = parsePluginRef(ref);\n if (marketplaceShadows(ctx.homeRoot, parsed.name)) {\n return {\n ref,\n platformId: \"cursor\",\n scope,\n status: \"already_installed\",\n message: `Cursor already runs ${parsed.name} from a marketplace install, which takes precedence over ~/.cursor/plugins/local. Left that install in place.`,\n };\n }\n\n const source = resolveInstallRoot(ref, ctx.homeRoot, undefined, {\n preferCanonicalPackage: false,\n });\n if (!source) {\n return {\n ref,\n platformId: \"cursor\",\n scope,\n status: \"failed\",\n message: `No on-disk plugin tree for ${ref}. Sync or install it on a host that has the tree, then copy it into ~/.cursor/plugins/local.`,\n };\n }\n\n const files = emitHostPluginTrees([pinResource(ref)], {\n layout: \"cursor\",\n homeRoot: ctx.homeRoot,\n });\n if (!files.some((file) => file.path.startsWith(\".cursor/plugins/local/\"))) {\n return {\n ref,\n platformId: \"cursor\",\n scope,\n status: \"failed\",\n message: `Could not copy ${ref} into ~/.cursor/plugins/local.`,\n };\n }\n\n writeFiles(files, ctx.homeRoot);\n return {\n ref,\n platformId: \"cursor\",\n scope,\n status: \"installed\",\n message: `Copied ${ref} into ~/.cursor/plugins/local. Reload Cursor to load it.`,\n };\n}\n","import {\n constants,\n copyFileSync,\n cpSync,\n existsSync,\n lstatSync,\n mkdirSync,\n readdirSync,\n rmSync,\n symlinkSync,\n} from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport type { PluginResourceMode } from \"./plugin-resource-mode.js\";\n\nfunction isSymlink(path: string): boolean {\n try {\n return lstatSync(path).isSymbolicLink();\n } catch {\n return false;\n }\n}\n\nfunction replaceExisting(dest: string): void {\n if (existsSync(dest) || isSymlink(dest)) {\n rmSync(dest, { recursive: true, force: true });\n }\n}\n\nfunction cloneTree(source: string, dest: string): void {\n const stat = lstatSync(source);\n if (stat.isDirectory()) {\n mkdirSync(dest, { recursive: true });\n for (const entry of readdirSync(source)) {\n cloneTree(join(source, entry), join(dest, entry));\n }\n return;\n }\n\n mkdirSync(dirname(dest), { recursive: true });\n try {\n copyFileSync(source, dest, constants.COPYFILE_FICLONE);\n } catch {\n copyFileSync(source, dest);\n }\n}\n\n/**\n * Materialize `source` at `dest` as a symlink, independent copy, or\n * copy-on-write clone (`fs.copyFile` `COPYFILE_FICLONE`, falling back to copy).\n */\nexport function materializeFromSource(\n dest: string,\n source: string,\n mode: PluginResourceMode,\n): void {\n mkdirSync(dirname(dest), { recursive: true });\n replaceExisting(dest);\n switch (mode) {\n case \"copy\":\n cpSync(source, dest, { recursive: true });\n return;\n case \"symlink\":\n symlinkSync(resolve(source), dest);\n return;\n case \"clone\":\n cloneTree(source, dest);\n return;\n default: {\n const exhaustive: never = mode;\n throw new Error(`Unsupported plugin resource mode: ${exhaustive}`);\n }\n }\n}\n\nexport function replaceWithRelativeSymlink(dest: string, target: string): void {\n mkdirSync(dirname(dest), { recursive: true });\n replaceExisting(dest);\n symlinkSync(target, dest);\n}\n","import { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport {\n findResourceByKey,\n upsertResource,\n} from \"../models/resource.js\";\nimport {\n addResourceToPlugin,\n removeResourceFromPlugin,\n resolvePluginSelector,\n} from \"../models/plugin-model.js\";\nimport { isProfilePlugin } from \"../constants/profile.js\";\nimport {\n MATERIAL_RESOURCE_TYPES,\n type PlatformPaths,\n type Resource,\n type ResourceType,\n} from \"../types.js\";\nimport { mergePluginsForApply } from \"./plugin-apply-merge.js\";\nimport { markPluginDirty } from \"./plugin-versioning.js\";\nimport { collectProfilePluginIds } from \"./profile-apply.js\";\nimport {\n toContentsResource,\n type ProfileContentsResource,\n} from \"./profile-contents.js\";\nimport type { ProfileApplyPreviewScope } from \"./profile-apply-preview.js\";\nimport { resolveRegisteredScanTargets } from \"./profile-harness-sync.js\";\nimport {\n persistScanResults,\n scanHomeDefaults,\n scanProject,\n type ScanResult,\n} from \"./scanner.js\";\nimport { getAllPlatforms } from \"../platforms/registry.js\";\nimport { resolveHomeRoot } from \"../utils/home-root.js\";\nimport { sourceMatchesManagedPath } from \"./mcp-target.js\";\nimport { isMergeableHostConfigPath } from \"./merged-host-config.js\";\nimport { diskCaptureHarnessScope } from \"./harness-scope.js\";\nimport { normalizeManagedPath } from \"./profile-untracked-resources.js\";\nimport { collectManagedSkillPlacements } from \"./shared-emit-paths.js\";\n\nfunction profileHasResource(\n profileSelector: string,\n resourceType: string,\n resourceName: string,\n namespace?: string,\n): Resource | null {\n const profilePlugin = resolvePluginSelector(profileSelector);\n if (!profilePlugin || !isProfilePlugin(profilePlugin)) {\n return null;\n }\n const merged = mergePluginsForApply(collectProfilePluginIds(profilePlugin));\n return (\n merged.resources.find(\n (resource) =>\n resource.type === resourceType\n && resource.name === resourceName\n && (namespace === undefined || (resource.namespace ?? \"\") === namespace),\n ) ?? null\n );\n}\n\ntype ManagedDirKind = \"skills\" | \"agents\" | \"commands\" | \"rules\";\n\ninterface ManagedDirPrefix {\n prefix: string;\n kind: ManagedDirKind;\n}\n\nconst SKILL_REMAINDER = /^([^/]+)\\/SKILL\\.md$/i;\nconst MARKDOWN_REMAINDER = /^([^/]+)\\.md$/i;\nconst AGENT_REMAINDER = /^([^/]+)\\.(md|toml)$/i;\nconst RULE_REMAINDER = /^([^/]+)\\.(md|mdc)$/i;\n\nfunction toManagedDirPrefix(raw: string | undefined): string | null {\n if (!raw) {\n return null;\n }\n const stripped = raw.replace(/^~\\//, \"\");\n if (!stripped.endsWith(\"/\")) {\n return null;\n }\n return stripped;\n}\n\nfunction collectManagedDirPrefixes(): ManagedDirPrefix[] {\n const seen = new Set<string>();\n const entries: ManagedDirPrefix[] = [];\n\n const add = (raw: string | undefined, kind: ManagedDirKind) => {\n const prefix = toManagedDirPrefix(raw);\n if (!prefix) {\n return;\n }\n const key = `${kind}:${prefix.toLowerCase()}`;\n if (seen.has(key)) {\n return;\n }\n seen.add(key);\n entries.push({ prefix, kind });\n };\n\n for (const platform of getAllPlatforms()) {\n for (const paths of [platform.projectPaths, platform.globalPaths]) {\n add(paths.skills, \"skills\");\n add(paths.agents, \"agents\");\n add(paths.commands, \"commands\");\n add(paths.rules, \"rules\");\n for (const alternate of paths.pathAlternates?.skills ?? []) {\n add(alternate, \"skills\");\n }\n for (const alternate of paths.pathAlternates?.commands ?? []) {\n add(alternate, \"commands\");\n }\n for (const alternate of paths.pathAlternates?.rules ?? []) {\n add(alternate, \"rules\");\n }\n }\n }\n\n return entries.sort((left, right) => right.prefix.length - left.prefix.length);\n}\n\nconst MANAGED_DIR_PREFIXES = collectManagedDirPrefixes();\n\nfunction remainderAfterManagedDir(\n normalized: string,\n prefix: string,\n): string | null {\n const lower = normalized.toLowerCase();\n const prefixLower = prefix.toLowerCase();\n if (lower.startsWith(prefixLower)) {\n return normalized.slice(prefix.length);\n }\n const embedded = `/${prefixLower}`;\n const index = lower.indexOf(embedded);\n if (index === -1) {\n return null;\n }\n return normalized.slice(index + embedded.length);\n}\n\nfunction resourceKeyFromDirRemainder(\n kind: ManagedDirKind,\n remainder: string,\n): { type: string; name: string } | null {\n switch (kind) {\n case \"skills\": {\n const match = remainder.match(SKILL_REMAINDER);\n return match?.[1] ? { type: \"skill\", name: match[1] } : null;\n }\n case \"agents\": {\n const match = remainder.match(AGENT_REMAINDER);\n return match?.[1] ? { type: \"agent\", name: match[1] } : null;\n }\n case \"commands\": {\n const match = remainder.match(MARKDOWN_REMAINDER);\n return match?.[1] ? { type: \"command\", name: match[1] } : null;\n }\n case \"rules\": {\n const match = remainder.match(RULE_REMAINDER);\n return match?.[1] ? { type: \"rule\", name: match[1] } : null;\n }\n default: {\n const neverKind: never = kind;\n return neverKind;\n }\n }\n}\n\n/**\n * Map a managed harness path to a material resource identity when the mapping is 1:1.\n * Directory prefixes come from the platform registry so every harness groups together.\n */\nexport function resourceKeyFromManagedPath(\n path: string,\n rootPath?: string,\n): { type: string; name: string } | null {\n const normalized = normalizeManagedPath(path, rootPath);\n for (const { prefix, kind } of MANAGED_DIR_PREFIXES) {\n const remainder = remainderAfterManagedDir(normalized, prefix);\n if (!remainder) {\n continue;\n }\n const mapped = resourceKeyFromDirRemainder(kind, remainder);\n if (mapped) {\n return mapped;\n }\n }\n return null;\n}\n\nfunction collectRegistryFilePaths(\n pick: (paths: PlatformPaths) => Array<string | undefined>,\n): string[] {\n const seen = new Set<string>();\n const entries: string[] = [];\n for (const platform of getAllPlatforms()) {\n for (const group of [platform.projectPaths, platform.globalPaths]) {\n for (const raw of pick(group)) {\n if (!raw || raw.endsWith(\"/\")) {\n continue;\n }\n const stripped = normalizeManagedPath(raw).replace(/^~\\//, \"\");\n const key = stripped.toLowerCase();\n if (seen.has(key)) {\n continue;\n }\n seen.add(key);\n entries.push(stripped);\n }\n }\n }\n return entries;\n}\n\nfunction pathMatchesKnownFile(path: string, known: string[], rootPath?: string): boolean {\n const stripped = normalizeManagedPath(path, rootPath).replace(/^~\\//, \"\");\n return known.some((candidate) => stripped === candidate);\n}\n\nconst REGISTRY_MCP_FILE_PATHS = collectRegistryFilePaths((paths) => [paths.mcp]);\n\nconst REGISTRY_AGGREGATE_FILE_PATHS = collectRegistryFilePaths((paths) => [\n paths.mcp,\n paths.settings,\n paths.hooks,\n paths.permissions,\n ...(paths.pathAlternates?.settings ?? []),\n]);\n\nconst REGISTRY_INSTRUCTION_FILE_PATHS = collectRegistryFilePaths((paths) => [\n paths.instructions,\n paths.legacy_instructions,\n]);\n\nconst INSTRUCTION_FILE_BASENAMES = new Set(\n [\n \"CLAUDE.md\",\n \"AGENTS.md\",\n \"AGENTS.local.md\",\n \"AGENT.md\",\n \"GEMINI.md\",\n \"AmazonQ.md\",\n \"CONVENTIONS.md\",\n \"JULES.md\",\n \".windsurfrules\",\n \".cursorrules\",\n \".goosehints\",\n \".rules\",\n \"copilot-instructions.md\",\n ].map((name) => name.toLowerCase()),\n);\n\n/** Aggregate MCP config files (many mcp_server resources per path). */\nexport function isMcpConfigManagedPath(path: string, rootPath?: string): boolean {\n const normalized = normalizeManagedPath(path, rootPath);\n // Dedicated MCP JSON filenames used across harnesses.\n if (/(^|\\/)(\\.?mcp\\.json|mcp[-_]config\\.json)$/i.test(normalized)) {\n return true;\n }\n return pathMatchesKnownFile(path, REGISTRY_MCP_FILE_PATHS, rootPath);\n}\n\n/**\n * Shared harness config files that hold many resources (settings, hooks,\n * permissions, MCP JSON/TOML). Commit snapshots every live resource bound\n * to the path rather than mapping 1:1 like SKILL.md.\n */\nexport function isAggregateConfigManagedPath(path: string, rootPath?: string): boolean {\n if (isMcpConfigManagedPath(path, rootPath) || isMergeableHostConfigPath(path)) {\n return true;\n }\n return pathMatchesKnownFile(path, REGISTRY_AGGREGATE_FILE_PATHS, rootPath);\n}\n\nexport function isInstructionManagedPath(path: string, rootPath?: string): boolean {\n if (pathMatchesKnownFile(path, REGISTRY_INSTRUCTION_FILE_PATHS, rootPath)) {\n return true;\n }\n const basename = normalizeManagedPath(path, rootPath).split(\"/\").pop()?.toLowerCase();\n return Boolean(basename && INSTRUCTION_FILE_BASENAMES.has(basename));\n}\n\nexport function isPluginRegistryManagedPath(path: string, rootPath?: string): boolean {\n const normalized = normalizeManagedPath(path, rootPath).replace(/^~\\//, \"\");\n return (\n /(^|\\/)\\.claude\\/plugins\\/installed_plugins\\.json$/i.test(normalized)\n || /(^|\\/)\\.cursor\\/plugins\\/(installed_plugins\\.json|installed\\.json)$/i.test(normalized)\n );\n}\n\nfunction isSourceBoundCommitPath(path: string, rootPath?: string): boolean {\n return (\n isAggregateConfigManagedPath(path, rootPath)\n || isInstructionManagedPath(path, rootPath)\n || isPluginRegistryManagedPath(path, rootPath)\n );\n}\n\nasync function scanForCommit(input: {\n scope: ProfileApplyPreviewScope;\n projectPath?: string;\n harness?: string;\n path?: string;\n}): Promise<{ originRef: string; scanned: ScanResult[] }> {\n const originRef =\n input.scope === \"project\"\n ? resolve(input.projectPath ?? \"\")\n : resolveHomeRoot();\n if (input.scope === \"project\" && !input.projectPath) {\n throw new Error(\"projectPath is required for project scope\");\n }\n const scanned =\n input.scope === \"project\"\n ? await scanProject(originRef)\n : await scanHomeDefaults(\n input.path || !input.harness\n ? undefined\n : resolveRegisteredScanTargets(input.harness)[0],\n originRef,\n );\n return { originRef, scanned };\n}\n\nconst COMMITTABLE_RESOURCE_TYPE_SET = new Set<string>([\n ...MATERIAL_RESOURCE_TYPES,\n \"plugin\",\n]);\n\nfunction resourceLiveKey(resource: {\n type: string;\n name: string;\n namespace?: string;\n origin_ref?: string;\n}): string {\n if (resource.type === \"plugin\") {\n return `plugin:${resource.origin_ref || `${resource.namespace ?? \"\"}:${resource.name}`}`;\n }\n return `${resource.type}:${resource.namespace ?? \"\"}:${resource.name}`;\n}\n\nasync function commitAggregateConfigFromLive(input: {\n profileSelector: string;\n path: string;\n scope: ProfileApplyPreviewScope;\n projectPath?: string;\n harness?: string;\n}): Promise<ProfileContentsResource[]> {\n const profilePlugin = resolvePluginSelector(input.profileSelector);\n if (!profilePlugin) {\n throw new Error(`Profile not found: ${input.profileSelector}`);\n }\n if (!isProfilePlugin(profilePlugin)) {\n throw new Error(`Plugin \"${profilePlugin.name}\" is not tagged as a profile`);\n }\n\n const { originRef, scanned } = await scanForCommit(input);\n const matching = scanned\n .map((result) => ({\n ...result,\n resources: result.resources.filter((resource) =>\n sourceMatchesManagedPath(resource.source, input.path, originRef),\n ),\n }))\n .filter((result) => result.resources.length > 0);\n\n const liveKeys = new Set<string>();\n const committed: ProfileContentsResource[] = [];\n\n if (matching.length > 0) {\n const persisted = persistScanResults(matching, {\n conflictPolicy: \"overwrite\",\n originRef,\n });\n\n markPluginDirty(profilePlugin.id);\n for (const resource of persisted.resolved) {\n if (!COMMITTABLE_RESOURCE_TYPE_SET.has(resource.type)) {\n continue;\n }\n liveKeys.add(resourceLiveKey(resource));\n if (\n !profileHasResource(\n input.profileSelector,\n resource.type,\n resource.name,\n resource.namespace,\n )\n ) {\n addResourceToPlugin(\n profilePlugin.id,\n resource.id,\n diskCaptureHarnessScope(resource),\n );\n }\n committed.push(toContentsResource(resource));\n }\n }\n\n // Live file is source of truth for this path: drop profile resources that\n // were bound to this path but are no longer on disk.\n const merged = mergePluginsForApply(collectProfilePluginIds(profilePlugin));\n let removedAny = false;\n for (const resource of merged.resources) {\n if (!COMMITTABLE_RESOURCE_TYPE_SET.has(resource.type)) {\n continue;\n }\n if (!sourceMatchesManagedPath(resource.source, input.path, originRef)) {\n continue;\n }\n if (liveKeys.has(resourceLiveKey(resource))) {\n continue;\n }\n if (!removedAny) {\n markPluginDirty(profilePlugin.id);\n removedAny = true;\n }\n removeResourceFromPlugin(profilePlugin.id, resource.id);\n }\n\n if (matching.length === 0 && committed.length === 0) {\n // Empty live aggregate file is a valid commit (clears path-owned resources).\n return [];\n }\n\n if (committed.length === 0 && matching.length > 0) {\n throw new Error(`Could not commit resources from: ${input.path}`);\n }\n return committed;\n}\n\n/**\n * Snapshot live disk content into the library for a profile-managed resource.\n */\nexport async function commitManagedResourceFromLive(input: {\n profileSelector: string;\n resourceType: string;\n resourceName: string;\n scope: ProfileApplyPreviewScope;\n projectPath?: string;\n harness?: string;\n path?: string;\n}): Promise<ProfileContentsResource> {\n const profilePlugin = resolvePluginSelector(input.profileSelector);\n if (!profilePlugin) {\n throw new Error(`Profile not found: ${input.profileSelector}`);\n }\n if (!isProfilePlugin(profilePlugin)) {\n throw new Error(`Plugin \"${profilePlugin.name}\" is not tagged as a profile`);\n }\n\n let resourceType = input.resourceType;\n let resourceName = input.resourceName;\n if ((!resourceType || !resourceName) && input.path) {\n const mapped = resourceKeyFromManagedPath(input.path);\n if (!mapped) {\n throw new Error(\n `Cannot map path to a single resource for commit: ${input.path}`,\n );\n }\n resourceType = mapped.type;\n resourceName = mapped.name;\n }\n\n const attached = profileHasResource(\n input.profileSelector,\n resourceType,\n resourceName,\n );\n if (!attached) {\n throw new Error(\n `Resource is not in profile: ${resourceType}:${resourceName}`,\n );\n }\n\n const { originRef, scanned } = await scanForCommit(input);\n\n const matching = scanned\n .map((result) => ({\n ...result,\n resources: result.resources.filter((resource) => {\n if (resource.type !== resourceType || resource.name !== resourceName) {\n return false;\n }\n if (!input.path) {\n return true;\n }\n return sourceMatchesManagedPath(resource.source, input.path, originRef);\n }),\n }))\n .filter((result) => result.resources.length > 0);\n\n if (matching.length === 0) {\n // Fall back: update from attached resource path if scan name differs (instructions).\n if (input.path && attached.type === \"instruction\") {\n const fullPath = join(originRef, normalizeManagedPath(input.path, originRef));\n if (!existsSync(fullPath)) {\n throw new Error(`Live file not found: ${input.path}`);\n }\n const content = readFileSync(fullPath, \"utf-8\");\n markPluginDirty(profilePlugin.id);\n const updated = upsertResource(\n {\n type: attached.type,\n name: attached.name,\n namespace: attached.namespace,\n description: attached.description,\n content,\n metadata: attached.metadata,\n source: attached.source,\n origin_kind: \"local_snapshot\",\n origin_ref: attached.origin_ref || originRef,\n },\n { policy: \"overwrite\" },\n );\n if (updated.action === \"skipped\") {\n throw new Error(`Could not update resource: ${resourceType}:${resourceName}`);\n }\n return toContentsResource(updated.resource);\n }\n throw new Error(\n `Resource not found on disk: ${resourceType}:${resourceName}`,\n );\n }\n\n markPluginDirty(profilePlugin.id);\n const persisted = persistScanResults(matching, {\n conflictPolicy: \"overwrite\",\n originRef,\n });\n const resource =\n persisted.resolved.find(\n (entry) => entry.type === resourceType && entry.name === resourceName,\n )\n ?? findResourceByKey(\n resourceType as ResourceType,\n resourceName,\n attached.namespace,\n );\n if (!resource) {\n throw new Error(\n `Could not commit resource: ${resourceType}:${resourceName}`,\n );\n }\n if (resource.type === \"skill\") {\n mirrorCommittedSkillContent(originRef, resource.name, resource.content);\n }\n return toContentsResource(resource);\n}\n\nfunction mirrorCommittedSkillContent(\n originRef: string,\n name: string,\n content: string,\n): void {\n const dirs = collectManagedSkillPlacements(originRef).get(name) ?? [];\n for (const dir of dirs) {\n const fullPath = join(originRef, `${dir}${name}/SKILL.md`);\n if (!existsSync(fullPath)) {\n continue;\n }\n writeFileSync(fullPath, content, \"utf-8\");\n }\n}\n\n/**\n * Commit a managed path from live disk into the profile library.\n * Supports 1:1 material paths and aggregate harness config files.\n */\nexport async function commitManagedPathFromLive(input: {\n profileSelector: string;\n path: string;\n scope: ProfileApplyPreviewScope;\n projectPath?: string;\n harness?: string;\n resourceType?: string;\n resourceName?: string;\n}): Promise<ProfileContentsResource[]> {\n const mapped =\n input.resourceType && input.resourceName\n ? { type: input.resourceType, name: input.resourceName }\n : resourceKeyFromManagedPath(input.path);\n\n if (mapped) {\n const resource = await commitManagedResourceFromLive({\n profileSelector: input.profileSelector,\n resourceType: mapped.type,\n resourceName: mapped.name,\n scope: input.scope,\n path: input.path,\n ...(input.projectPath ? { projectPath: input.projectPath } : {}),\n ...(input.harness ? { harness: input.harness } : {}),\n });\n return [resource];\n }\n\n if (isSourceBoundCommitPath(input.path)) {\n return commitAggregateConfigFromLive({\n profileSelector: input.profileSelector,\n path: input.path,\n scope: input.scope,\n ...(input.projectPath ? { projectPath: input.projectPath } : {}),\n ...(input.harness ? { harness: input.harness } : {}),\n });\n }\n\n throw new Error(`Cannot map path to a resource for commit: ${input.path}`);\n}\n","import { getPluginById, mergePluginsById, type MergedPluginContent } from \"../models/plugin-model.js\";\nimport { getEnvironmentResources } from \"../models/environment.js\";\nimport type { ClaudePluginConfig, Resource } from \"../types.js\";\nimport {\n applyIncomingHarnessScope,\n incomingScopeByPluginId,\n} from \"./harness-scope-graph.js\";\n\nfunction resourceKey(resource: Pick<Resource, \"type\" | \"name\">): string {\n return `${resource.type}:${resource.name}`;\n}\n\nfunction mergeResources(base: Resource[], next: Resource[]): Resource[] {\n const order: string[] = [];\n const byKey = new Map<string, Resource>();\n for (const resource of [...base, ...next]) {\n const key = resourceKey(resource);\n if (!byKey.has(key)) {\n order.push(key);\n }\n byKey.set(key, resource);\n }\n return order\n .map((key) => byKey.get(key))\n .filter((r): r is Resource => r !== undefined);\n}\n\nfunction mergeClaudeConfig(\n base: ClaudePluginConfig | undefined,\n next: ClaudePluginConfig | undefined,\n): ClaudePluginConfig | undefined {\n if (!base && !next) return undefined;\n const marketplaces = {\n ...(base?.marketplaces ?? {}),\n ...(next?.marketplaces ?? {}),\n };\n const pluginMap = new Map(\n [...(base?.plugins ?? []), ...(next?.plugins ?? [])].map((p) => [p.id, p]),\n );\n const plugins = [...pluginMap.values()];\n return {\n ...(Object.keys(marketplaces).length > 0 ? { marketplaces } : {}),\n ...(plugins.length > 0 ? { plugins } : {}),\n };\n}\n\nfunction mergeMergedContent(\n base: MergedPluginContent,\n next: MergedPluginContent,\n): MergedPluginContent {\n const pinMap = new Map(base.pluginPins.map((pin) => [pin.ref, pin]));\n for (const pin of next.pluginPins) {\n pinMap.set(pin.ref, pin);\n }\n return {\n plugins: [...base.plugins, ...next.plugins],\n resources: mergeResources(base.resources, next.resources),\n claude: mergeClaudeConfig(base.claude, next.claude),\n pluginPins: [...pinMap.values()],\n };\n}\n\n/**\n * Merge plugins in apply order, including each plugin's default environment resources.\n */\nexport function mergePluginsForApply(pluginIds: string[]): MergedPluginContent {\n let merged: MergedPluginContent = {\n plugins: [],\n resources: [],\n pluginPins: [],\n };\n const incoming = incomingScopeByPluginId(pluginIds);\n\n for (const pluginId of pluginIds) {\n const plugin = getPluginById(pluginId);\n if (!plugin) {\n throw new Error(`Plugin not found: ${pluginId}`);\n }\n\n const own = mergePluginsById([pluginId]);\n const parentIncoming = incoming.get(pluginId);\n merged = mergeMergedContent(merged, {\n ...own,\n resources: parentIncoming\n ? applyIncomingHarnessScope(own.resources, parentIncoming)\n : own.resources,\n });\n\n if (plugin.default_environment_id) {\n const envResources = getEnvironmentResources(plugin.default_environment_id);\n merged = {\n ...merged,\n resources: mergeResources(\n merged.resources,\n parentIncoming\n ? applyIncomingHarnessScope(envResources, parentIncoming)\n : envResources,\n ),\n };\n }\n }\n\n return merged;\n}\n","import {\n existsSync,\n mkdirSync,\n readFileSync,\n realpathSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { dirname, isAbsolute, join, resolve } from \"node:path\";\nimport { getHarnesstapDir } from \"../db/connection.js\";\nimport { resolveResource } from \"../models/resource.js\";\nimport type { Resource } from \"../types.js\";\nimport { resolveHomeRoot } from \"../utils/home-root.js\";\nimport { listExistingInstallRoots } from \"./resource-sync.js\";\nimport { isUntrackedResourceSelector } from \"./untracked-resource.js\";\n\nfunction expandUserPath(candidate: string): string {\n const trimmed = candidate.trim();\n if (trimmed.startsWith(\"~/\")) {\n return join(resolveHomeRoot(), trimmed.slice(2));\n }\n if (trimmed === \"~\") {\n return resolveHomeRoot();\n }\n return resolve(trimmed);\n}\n\nfunction isOpenableFile(path: string): boolean {\n if (!existsSync(path)) {\n return false;\n }\n try {\n return statSync(path).isFile();\n } catch {\n return false;\n }\n}\n\nfunction isExistingDirectory(path: string): boolean {\n if (!existsSync(path)) {\n return false;\n }\n try {\n return statSync(path).isDirectory();\n } catch {\n return false;\n }\n}\n\nfunction uniquePaths(paths: string[]): string[] {\n const seen = new Set<string>();\n const out: string[] = [];\n for (const path of paths) {\n if (!path || seen.has(path)) {\n continue;\n }\n seen.add(path);\n out.push(path);\n }\n return out;\n}\n\nfunction extensionForResourceType(type: string): string {\n switch (type) {\n case \"skill\":\n case \"instruction\":\n case \"rule\":\n case \"agent\":\n case \"command\":\n return \".md\";\n case \"hook\":\n return \".json\";\n default:\n return \".txt\";\n }\n}\n\nfunction scratchPathForResource(resource: Resource): string {\n const safeName = resource.name.replace(/[^a-zA-Z0-9._-]+/g, \"-\");\n return join(\n getHarnesstapDir(),\n \"editor-scratch\",\n resource.type,\n `${safeName}${extensionForResourceType(resource.type)}`,\n );\n}\n\nfunction candidatePaths(\n resource: Pick<Resource, \"source\" | \"origin_ref\">,\n pathHint?: string | null,\n): string[] {\n const candidates: string[] = [];\n if (pathHint?.trim()) {\n candidates.push(pathHint.trim());\n }\n if (resource.source?.trim() && resource.source !== \"manual\") {\n candidates.push(resource.source.trim());\n }\n if (resource.origin_ref?.trim()) {\n candidates.push(resource.origin_ref.trim());\n }\n return candidates;\n}\n\nfunction isPluginRefHint(candidate: string): boolean {\n return candidate.includes(\"@\") && !candidate.includes(\"/\") && !candidate.includes(\"\\\\\");\n}\n\nfunction looksLikeFilesystemSource(candidate: string): boolean {\n const trimmed = candidate.trim();\n if (!trimmed || trimmed === \"manual\" || trimmed.startsWith(\"composition:\")) {\n return false;\n }\n return true;\n}\n\nfunction isBareRelativePath(candidate: string): boolean {\n const trimmed = candidate.trim();\n if (!looksLikeFilesystemSource(trimmed)) {\n return false;\n }\n if (trimmed.startsWith(\"~\") || isAbsolute(trimmed) || isPluginRefHint(trimmed)) {\n return false;\n }\n return true;\n}\n\nfunction installRootsForResource(\n resource: Pick<Resource, \"origin_ref\">,\n): string[] {\n const originRef = resource.origin_ref?.trim();\n if (!originRef) {\n return [];\n }\n return listExistingInstallRoots(originRef);\n}\n\nfunction originDirectory(\n resource: Pick<Resource, \"origin_ref\">,\n): string | null {\n const originRef = resource.origin_ref?.trim();\n if (!originRef || !looksLikeFilesystemSource(originRef) || isPluginRefHint(originRef)) {\n return null;\n }\n const expanded = expandUserPath(originRef);\n return isExistingDirectory(expanded) ? expanded : null;\n}\n\n/** Plugin install trees, origin dir, then the shared `~/.agents` hub. */\nfunction lookupRootsForResource(\n resource: Pick<Resource, \"origin_ref\">,\n): string[] {\n const roots = [...installRootsForResource(resource)];\n const originDir = originDirectory(resource);\n if (originDir) {\n roots.push(originDir);\n roots.push(join(originDir, \".agents\"));\n }\n roots.push(join(resolveHomeRoot(), \".agents\"));\n return uniquePaths(roots);\n}\n\nfunction canonicalizeExistingPath(path: string): string {\n try {\n return realpathSync(path);\n } catch {\n return path;\n }\n}\n\nfunction openableFileOrSkill(path: string): string | null {\n if (isOpenableFile(path)) {\n return canonicalizeExistingPath(path);\n }\n const skillMarkdown = join(path, \"SKILL.md\");\n if (isOpenableFile(skillMarkdown)) {\n return canonicalizeExistingPath(skillMarkdown);\n }\n return null;\n}\n\nfunction resolveExistingEditorPath(\n candidate: string,\n roots: string[] = [],\n): string | null {\n const trimmed = candidate.trim();\n if (!trimmed) {\n return null;\n }\n\n if (isBareRelativePath(trimmed)) {\n for (const root of roots) {\n const fromRoot = openableFileOrSkill(resolve(root, trimmed));\n if (fromRoot) {\n return fromRoot;\n }\n }\n }\n\n return openableFileOrSkill(expandUserPath(trimmed));\n}\n\nexport function resolveExistingResourceFilesystemPath(\n resource: Pick<Resource, \"source\" | \"origin_ref\">,\n pathHint?: string | null,\n): string | null {\n const roots = lookupRootsForResource(resource);\n for (const candidate of candidatePaths(resource, pathHint)) {\n const resolved = resolveExistingEditorPath(candidate, roots);\n if (resolved) {\n return resolved;\n }\n }\n return null;\n}\n\nexport function readResourceContentFromPathHint(pathHint: string): {\n path: string;\n content: string;\n updatedAt: string;\n} {\n const resolved = resolveExistingEditorPath(pathHint);\n if (!resolved) {\n throw new Error(`Path is not an openable file: ${pathHint}`);\n }\n const stat = statSync(resolved);\n return {\n path: resolved,\n content: readFileSync(resolved, \"utf-8\"),\n updatedAt: new Date(stat.mtimeMs).toISOString(),\n };\n}\n\nexport function resolveResourceEditorPath(input: {\n selector: string;\n pathHint?: string | null;\n}): string {\n const trimmedSelector = input.selector.trim();\n if (!trimmedSelector) {\n throw new Error(\"Resource selector is required\");\n }\n\n if (isUntrackedResourceSelector(trimmedSelector)) {\n if (!input.pathHint?.trim()) {\n throw new Error(`Resource not found: ${trimmedSelector}`);\n }\n return resolveEditorPath(input.pathHint);\n }\n\n const result = resolveResource(trimmedSelector);\n if (result.status === \"not_found\") {\n throw new Error(`Resource not found: ${trimmedSelector}`);\n }\n if (result.status === \"ambiguous\") {\n throw new Error(`Ambiguous resource selector: ${trimmedSelector}`);\n }\n\n const resource = result.resource;\n const roots = lookupRootsForResource(resource);\n const candidates = candidatePaths(resource, input.pathHint);\n for (const candidate of candidates) {\n const resolved = resolveExistingEditorPath(candidate, roots);\n if (resolved) {\n return resolved;\n }\n }\n\n const diskHint = candidates.find((candidate) => looksLikeFilesystemSource(candidate));\n if (diskHint) {\n throw new Error(`Path is not an openable file: ${diskHint}`);\n }\n\n const scratchPath = scratchPathForResource(resource);\n mkdirSync(dirname(scratchPath), { recursive: true });\n writeFileSync(scratchPath, resource.content, \"utf-8\");\n return scratchPath;\n}\n\nexport function resolveEditorPath(path: string): string {\n const trimmed = path.trim();\n if (!trimmed) {\n throw new Error(\"Path is required\");\n }\n const resolved = resolveExistingEditorPath(trimmed);\n if (!resolved) {\n throw new Error(`Path is not an openable file: ${path}`);\n }\n return resolved;\n}\n","import { getHarnessPreference } from \"../models/harness.js\";\nimport type { Resource } from \"../types.js\";\nimport {\n type HarnessScope,\n HARNESS_SCOPE_ALL,\n resourceHarnessScope,\n} from \"./harness-scope.js\";\nimport {\n registeredHarnessesOf,\n uniqueHarnessTargets,\n} from \"./harness-targets.js\";\n\n/**\n * Where this resource applies: resource harness scope intersected with the\n * registered harness set, in registered order. Sidecar and CLI share this\n * selector so Desktop hover cards, Use on, Preview, and apply agree.\n */\nexport type ResourceApplySelector = {\n registered: readonly string[];\n harnesses: string[];\n notSetUp: boolean;\n};\n\nexport function registeredHarnessIds(): string[] {\n return registeredHarnessesOf(getHarnessPreference());\n}\n\nexport function whereResourceApplies(\n scope: HarnessScope,\n registered: readonly string[],\n): ResourceApplySelector {\n const ordered = uniqueHarnessTargets(registered);\n if (ordered.length === 0) {\n return { registered: ordered, harnesses: [], notSetUp: true };\n }\n if (scope.kind === \"all\") {\n return { registered: ordered, harnesses: [...ordered], notSetUp: false };\n }\n const allowed = new Set(scope.harnesses);\n return {\n registered: ordered,\n harnesses: ordered.filter((id) => allowed.has(id)),\n notSetUp: false,\n };\n}\n\nexport function whereResourceAppliesNow(\n resource: Pick<Resource, \"harness_scope\"> | { harness_scope?: HarnessScope },\n registered: readonly string[] = registeredHarnessIds(),\n): ResourceApplySelector {\n return whereResourceApplies(\n resourceHarnessScope(resource as Pick<Resource, \"harness_scope\">),\n registered,\n );\n}\n\nexport function allHarnessApplySelector(\n registered: readonly string[] = registeredHarnessIds(),\n): ResourceApplySelector {\n return whereResourceApplies(HARNESS_SCOPE_ALL, registered);\n}\n","import { isEmptyBuiltinProfile, isProfilePlugin } from \"../constants/profile.js\";\nimport {\n getPluginById,\n getPluginResources,\n resolvePluginSelector,\n} from \"../models/plugin-model.js\";\nimport { getEnvironmentResources } from \"../models/environment.js\";\nimport type { Resource } from \"../types.js\";\nimport { hookInventoryWireFromResource } from \"../ui/hook-display.js\";\nimport { mergePluginsForApply } from \"./plugin-apply-merge.js\";\nimport { formatResourceTypeSummary } from \"./project-status-payload.js\";\nimport { collectProfilePluginIds } from \"./profile-apply.js\";\nimport { resolveExistingResourceFilesystemPath } from \"./resource-editor-path.js\";\nimport { harnessScopeWire, resourceHarnessScope } from \"./harness-scope.js\";\nimport {\n registeredHarnessIds,\n type ResourceApplySelector,\n whereResourceAppliesNow,\n} from \"./resource-apply-selector.js\";\n\nfunction optionalScopeWire(\n resource: Resource | undefined,\n): { harness_scope: \"all\" | string[] } | Record<string, never> {\n if (!resource) return {};\n const scope = resourceHarnessScope(resource);\n return scope.kind === \"all\" ? {} : { harness_scope: harnessScopeWire(scope) };\n}\n\nexport interface ProfileContentsResource {\n id: string;\n type: string;\n name: string;\n /** On-disk path or import origin label (hover target in desktop). */\n source: string;\n /** Canonical live file when `source` is a hub symlink or scan alias. */\n filesystem_path?: string | null;\n origin_kind?: string;\n origin_ref?: string;\n hook?: {\n event: string;\n script: string;\n matcher?: string;\n type?: string;\n };\n /** Present on not-staged rows: add is missing from the profile; update differs on disk. */\n not_staged_kind?: \"add\" | \"update\";\n /** `all` sentinel or a subset of harness slugs. Missing means All. */\n harness_scope?: \"all\" | string[];\n /**\n * Resource scope intersected with registered harnesses (registered order).\n * Empty when no harness is registered (`apply_not_set_up`).\n */\n apply_harnesses?: string[];\n apply_not_set_up?: boolean;\n}\n\nexport interface ProfileContentsPlugin {\n id: string;\n name: string;\n version: string;\n resources: ProfileContentsResource[];\n harness_scope?: \"all\" | string[];\n attachment_id?: string;\n}\n\nexport interface ProfileContentsPin {\n ref: string;\n version_constraint: string;\n harness_scope?: \"all\" | string[];\n attachment_id?: string;\n}\n\nexport interface ProfileContents {\n plugins: ProfileContentsPlugin[];\n stack_resource_count: number;\n stack_summary: string | null;\n /** Counts by resource type, plus `plugin` and `plugin_pin`. */\n type_counts: Record<string, number>;\n resources: ProfileContentsResource[];\n plugin_pins: ProfileContentsPin[];\n mcp_servers: string[];\n}\n\nfunction materialResources(resources: Resource[]): Resource[] {\n return resources.filter(\n (resource) => resource.type !== \"plugin\",\n );\n}\n\nfunction applySelectorFields(selector: ResourceApplySelector): {\n apply_harnesses: string[];\n apply_not_set_up: boolean;\n} {\n return {\n apply_harnesses: selector.harnesses,\n apply_not_set_up: selector.notSetUp,\n };\n}\n\nexport function toContentsResource(\n resource: Resource,\n registered?: readonly string[],\n): ProfileContentsResource {\n const filesystemPath = resolveExistingResourceFilesystemPath(resource);\n const hook = hookInventoryWireFromResource(resource);\n const scope = resourceHarnessScope(resource);\n const apply = whereResourceAppliesNow(resource, registered);\n return {\n id: resource.id,\n type: resource.type,\n name: resource.name,\n source: resource.source,\n ...(resource.origin_kind ? { origin_kind: resource.origin_kind } : {}),\n ...(resource.origin_ref ? { origin_ref: resource.origin_ref } : {}),\n ...(filesystemPath ? { filesystem_path: filesystemPath } : {}),\n ...(hook ? { hook } : {}),\n ...(scope.kind === \"all\" ? {} : { harness_scope: harnessScopeWire(scope) }),\n ...applySelectorFields(apply),\n };\n}\n\nexport function toNotStagedContentsResource(\n resource: Resource,\n kind: \"add\" | \"update\",\n): ProfileContentsResource {\n return {\n ...toContentsResource(resource),\n not_staged_kind: kind,\n };\n}\n\nfunction toContentsResources(resources: Resource[]): ProfileContentsResource[] {\n const registered = registeredHarnessIds();\n const order: string[] = [];\n const byKey = new Map<string, ProfileContentsResource>();\n for (const resource of materialResources(resources)) {\n const key = `${resource.type}:${resource.name}`;\n if (!byKey.has(key)) {\n order.push(key);\n byKey.set(key, toContentsResource(resource, registered));\n }\n }\n return order\n .map((key) => byKey.get(key))\n .filter((entry): entry is ProfileContentsResource => entry !== undefined);\n}\n\nfunction resourcesForPlugin(pluginId: string): ProfileContentsResource[] {\n const plugin = getPluginById(pluginId);\n const attached = getPluginResources(pluginId);\n const fromEnv = plugin?.default_environment_id\n ? getEnvironmentResources(plugin.default_environment_id)\n : [];\n return toContentsResources([...attached, ...fromEnv]);\n}\n\nfunction buildTypeCounts(\n plugins: ProfileContentsPlugin[],\n resources: ProfileContentsResource[],\n pluginPins: ProfileContentsPin[],\n): Record<string, number> {\n const counts: Record<string, number> = {};\n if (plugins.length > 0) {\n counts.plugin = plugins.length;\n }\n for (const resource of resources) {\n counts[resource.type] = (counts[resource.type] ?? 0) + 1;\n }\n if (pluginPins.length > 0) {\n counts.plugin_pin = pluginPins.length;\n }\n return counts;\n}\n\nexport function buildProfileContents(profileName: string): ProfileContents | null {\n if (isEmptyBuiltinProfile(profileName)) {\n return {\n plugins: [],\n stack_resource_count: 0,\n stack_summary: null,\n type_counts: {},\n resources: [],\n plugin_pins: [],\n mcp_servers: [],\n };\n }\n\n const plugin = resolvePluginSelector(profileName);\n if (!plugin || !isProfilePlugin(plugin)) {\n return null;\n }\n\n const pluginIds = collectProfilePluginIds(plugin);\n const merged = mergePluginsForApply(pluginIds);\n const resources = materialResources(merged.resources);\n const summary = formatResourceTypeSummary(resources);\n const rootAttached = getPluginResources(plugin.id);\n const plugins = merged.plugins.map((entry) => {\n const attachment = rootAttached.find(\n (resource) => resource.type === \"plugin\" && resource.name === entry.name,\n );\n return {\n id: entry.id,\n name: entry.name,\n version: entry.version,\n resources: resourcesForPlugin(entry.id),\n ...(attachment?.id ? { attachment_id: attachment.id } : {}),\n ...optionalScopeWire(attachment),\n };\n });\n const pluginPins = merged.pluginPins.map((pin) => {\n const attachment = rootAttached.find(\n (resource) => resource.name === pin.ref || resource.origin_ref === pin.ref,\n );\n return {\n ref: pin.ref,\n version_constraint: pin.version_constraint,\n ...(attachment?.id ? { attachment_id: attachment.id } : {}),\n ...optionalScopeWire(attachment),\n };\n });\n const contentsResources = resources.map((resource) =>\n toContentsResource(resource, registeredHarnessIds()),\n );\n\n return {\n plugins,\n stack_resource_count: resources.length,\n stack_summary: summary.length > 0 ? summary : null,\n type_counts: buildTypeCounts(plugins, contentsResources, pluginPins),\n resources: contentsResources,\n plugin_pins: pluginPins,\n mcp_servers: resources\n .filter((resource) => resource.type === \"mcp_server\")\n .map((resource) => resource.name),\n };\n}\n","import {\n addResourceToPlugin,\n getPluginResources,\n removeResourceFromPlugin,\n resolvePluginSelector,\n touchPluginUpdatedAt,\n} from \"../models/plugin-model.js\";\nimport { getHarnessPreference } from \"../models/harness.js\";\nimport { isProfilePlugin } from \"../constants/profile.js\";\nimport {\n MATERIAL_RESOURCE_TYPES,\n type MaterialResourceType,\n type Resource,\n type ResourceCreateInput,\n} from \"../types.js\";\nimport { mergePluginsForApply } from \"./plugin-apply-merge.js\";\nimport { collectProfilePluginIds } from \"./profile-apply.js\";\nimport {\n detectHomePlatforms,\n persistScanResults,\n scanHomeDefaults,\n} from \"./scanner.js\";\nimport {\n assertSupportedHarnessTargets,\n parsePlatformFilter,\n registeredHarnessesOf,\n uniqueHarnessTargets,\n} from \"./harness-targets.js\";\nimport { resolveHomeRoot } from \"../utils/home-root.js\";\nimport { diskCaptureHarnessScope } from \"./harness-scope.js\";\nimport { getActiveProfileName } from \"./active-profile.js\";\n\nexport interface ProfileHarnessSyncChange {\n resource_type: string;\n resource_name: string;\n change: \"added\" | \"removed\" | \"modified\";\n}\n\nexport interface ProfileHarnessSyncStatus {\n active_profile: string;\n registered_harnesses: string[];\n in_sync: boolean;\n changes: ProfileHarnessSyncChange[];\n warning?: string;\n}\n\nexport interface UpdateProfileFromHarnessResult {\n profile_name: string;\n registered_harnesses: string[];\n attached_resources: number;\n removed_resources: number;\n updated_resources: number;\n}\n\nconst MATERIAL_RESOURCE_TYPE_SET = new Set<string>(MATERIAL_RESOURCE_TYPES);\n\nfunction isMaterialResource(\n resource: Pick<Resource, \"type\"> | Pick<ResourceCreateInput, \"type\">,\n): resource is Resource & { type: MaterialResourceType } {\n return MATERIAL_RESOURCE_TYPE_SET.has(resource.type);\n}\n\nfunction profileResourceKey(\n resource: Pick<Resource, \"type\" | \"name\"> | Pick<ResourceCreateInput, \"type\" | \"name\">,\n): string {\n return `${resource.type}:${resource.name}`;\n}\n\nexport function resolveRegisteredScanTargets(\n harnessOption?: string,\n homeRoot = resolveHomeRoot(),\n): string[] {\n const explicitTargets = uniqueHarnessTargets(parsePlatformFilter(harnessOption) ?? []);\n if (explicitTargets.length > 0) {\n assertSupportedHarnessTargets(explicitTargets);\n return explicitTargets;\n }\n\n const registered = registeredHarnessesOf(getHarnessPreference());\n if (registered.length > 0) {\n assertSupportedHarnessTargets(registered);\n return registered;\n }\n\n const detected = detectHomePlatforms(homeRoot).map((entry) => entry.platformId);\n if (detected.length === 0) {\n throw new Error(\n \"No harnesses configured. Run ht harness set or pass --harness <slugs>.\",\n );\n }\n return detected;\n}\n\n/** First registered or explicit target. Prefer `resolveRegisteredScanTargets`. */\nexport function resolveMainHarnessTarget(\n harnessOption?: string,\n homeRoot = resolveHomeRoot(),\n): string {\n const [first] = resolveRegisteredScanTargets(harnessOption, homeRoot);\n if (!first) {\n throw new Error(\"No harness targets provided.\");\n }\n return first;\n}\n\nfunction compareMaterialResources(\n profileResources: Resource[],\n harnessResources: ResourceCreateInput[],\n): ProfileHarnessSyncChange[] {\n const profileMap = new Map(\n profileResources\n .filter(isMaterialResource)\n .map((resource) => [profileResourceKey(resource), resource] as const),\n );\n const harnessMap = new Map(\n harnessResources\n .filter(isMaterialResource)\n .map((resource) => [profileResourceKey(resource), resource] as const),\n );\n\n const changes: ProfileHarnessSyncChange[] = [];\n for (const [key, harnessResource] of harnessMap) {\n const profileResource = profileMap.get(key);\n if (!profileResource) {\n changes.push({\n resource_type: harnessResource.type,\n resource_name: harnessResource.name,\n change: \"added\",\n });\n continue;\n }\n if (profileResource.content !== harnessResource.content) {\n changes.push({\n resource_type: harnessResource.type,\n resource_name: harnessResource.name,\n change: \"modified\",\n });\n }\n }\n\n for (const [key, profileResource] of profileMap) {\n if (!harnessMap.has(key)) {\n changes.push({\n resource_type: profileResource.type,\n resource_name: profileResource.name,\n change: \"removed\",\n });\n }\n }\n\n return changes;\n}\n\nasync function scanRegisteredHome(harnessOption?: string) {\n const targets = resolveRegisteredScanTargets(harnessOption);\n const homeRoot = resolveHomeRoot();\n const scanned = await scanHomeDefaults(undefined, homeRoot);\n const wanted = new Set(targets);\n const filtered = scanned.filter((result) => wanted.has(result.platformId));\n return { targets, scanned: filtered.length > 0 ? filtered : scanned };\n}\n\nexport async function detectProfileHarnessSyncStatus(input: {\n profileSelector: string;\n harness?: string;\n}): Promise<ProfileHarnessSyncStatus> {\n const profilePlugin = resolvePluginSelector(input.profileSelector);\n if (!profilePlugin) {\n throw new Error(`Profile not found: ${input.profileSelector}`);\n }\n if (!isProfilePlugin(profilePlugin)) {\n throw new Error(`Plugin \"${profilePlugin.name}\" is not tagged as a profile`);\n }\n\n const { targets, scanned } = await scanRegisteredHome(input.harness);\n let profileResources: Resource[];\n try {\n profileResources = mergePluginsForApply(\n collectProfilePluginIds(profilePlugin),\n ).resources;\n } catch (error) {\n return {\n active_profile: profilePlugin.name,\n registered_harnesses: targets,\n in_sync: false,\n changes: [],\n warning: error instanceof Error ? error.message : String(error),\n };\n }\n\n const harnessResources = scanned.flatMap((result) => result.resources);\n const changes = compareMaterialResources(profileResources, harnessResources);\n\n return {\n active_profile: profilePlugin.name,\n registered_harnesses: targets,\n in_sync: changes.length === 0,\n changes,\n };\n}\n\nexport async function updateProfileFromMainHarness(input: {\n profileSelector: string;\n harness?: string;\n}): Promise<UpdateProfileFromHarnessResult> {\n const profilePlugin = resolvePluginSelector(input.profileSelector);\n if (!profilePlugin) {\n throw new Error(`Profile not found: ${input.profileSelector}`);\n }\n if (!isProfilePlugin(profilePlugin)) {\n throw new Error(`Plugin \"${profilePlugin.name}\" is not tagged as a profile`);\n }\n\n const { targets, scanned } = await scanRegisteredHome(input.harness);\n const beforeSync = getPluginResources(profilePlugin.id).filter(isMaterialResource);\n const harnessResources = scanned.flatMap((result) => result.resources);\n const pendingChanges = compareMaterialResources(beforeSync, harnessResources);\n const homeRoot = resolveHomeRoot();\n const persisted = persistScanResults(scanned, {\n conflictPolicy: \"overwrite\",\n originRef: homeRoot,\n });\n const scannedResources = persisted.resolved.filter(isMaterialResource);\n const scannedKeys = new Set(scannedResources.map((resource) => profileResourceKey(resource)));\n\n let removedResources = 0;\n for (const resource of beforeSync) {\n if (!scannedKeys.has(profileResourceKey(resource))) {\n removeResourceFromPlugin(profilePlugin.id, resource.id);\n removedResources += 1;\n }\n }\n\n let attachedResources = 0;\n for (const resource of scannedResources) {\n const existingAttachment = beforeSync.some(\n (attached) => attached.id === resource.id,\n );\n addResourceToPlugin(\n profilePlugin.id,\n resource.id,\n diskCaptureHarnessScope(resource),\n );\n if (!existingAttachment) {\n attachedResources += 1;\n }\n }\n\n touchPluginUpdatedAt(profilePlugin.id);\n\n return {\n profile_name: profilePlugin.name,\n registered_harnesses: targets,\n attached_resources: attachedResources,\n removed_resources: removedResources,\n updated_resources: pendingChanges.filter((change) => change.change === \"modified\").length,\n };\n}\n\nexport async function detectActiveProfileHarnessSyncBeforeSwitch(input: {\n targetProfileName: string;\n harness?: string;\n}): Promise<ProfileHarnessSyncStatus | null> {\n const activeProfile = getActiveProfileName();\n if (!activeProfile || activeProfile === input.targetProfileName) {\n return null;\n }\n\n return detectProfileHarnessSyncStatus({\n profileSelector: activeProfile,\n harness: input.harness,\n });\n}\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\nimport { harnesstapDirForHomeRoot } from \"../db/connection.js\";\nimport {\n addResourceToPlugin,\n resolvePluginSelector,\n touchPluginUpdatedAt,\n} from \"../models/plugin-model.js\";\nimport { isProfilePlugin } from \"../constants/profile.js\";\nimport { isCursorHostManagedSkillsPath } from \"./cursor-host-managed-skills.js\";\nimport { PACKAGES_CACHE_ROOT } from \"./package-cache/paths.js\";\nimport {\n MATERIAL_RESOURCE_TYPES,\n type MaterialResourceType,\n type Resource,\n type ResourceCreateInput,\n} from \"../types.js\";\nimport { mergePluginsForApply } from \"./plugin-apply-merge.js\";\nimport { markPluginDirty } from \"./plugin-versioning.js\";\nimport { collectProfilePluginIds } from \"./profile-apply.js\";\nimport {\n type ProfileContents,\n type ProfileContentsResource,\n toContentsResource,\n toNotStagedContentsResource,\n} from \"./profile-contents.js\";\nimport type { ProfileApplyPreviewScope } from \"./profile-apply-preview.js\";\nimport { resolveRegisteredScanTargets } from \"./profile-harness-sync.js\";\nimport { assessProjectScanStatus } from \"./project-scan-status.js\";\nimport { generateFiles, removeGlobalMaterializedFiles } from \"./applier.js\";\nimport { ensureLiveLibraryRef, isLiveLibraryRef } from \"./live-library-ref.js\";\nimport {\n persistScanResults,\n reconcileLocalSnapshotScan,\n scanHomeDefaults,\n scanProject,\n type ScanResult,\n} from \"./scanner.js\";\nimport { resolveHomeRoot } from \"../utils/home-root.js\";\nimport { diskCaptureHarnessScope } from \"./harness-scope.js\";\nimport type { DriftFileChange } from \"./project-drift.js\";\n\nconst MATERIAL_RESOURCE_TYPE_SET = new Set<string>(MATERIAL_RESOURCE_TYPES);\n\nfunction isMaterialResource(\n resource: Pick<Resource, \"type\"> | Pick<ResourceCreateInput, \"type\">,\n): resource is Resource & { type: MaterialResourceType } {\n return MATERIAL_RESOURCE_TYPE_SET.has(resource.type);\n}\n\nfunction profileResourceKey(\n resource: Pick<Resource, \"type\" | \"name\"> | Pick<ResourceCreateInput, \"type\" | \"name\">,\n): string {\n return `${resource.type}:${resource.name}`;\n}\n\n/** Keys attached to the given profile stack (including nested plugins). */\nfunction trackedResourceKeys(profileSelector: string): Set<string> {\n return new Set(trackedResourceMap(profileSelector).keys());\n}\n\nfunction trackedResourceMap(profileSelector: string): Map<string, Resource> {\n const profilePlugin = resolvePluginSelector(profileSelector);\n if (!profilePlugin) {\n return new Map();\n }\n const profileResources = mergePluginsForApply(\n collectProfilePluginIds(profilePlugin),\n ).resources;\n const map = new Map<string, Resource>();\n for (const resource of profileResources) {\n if (!isMaterialResource(resource)) {\n continue;\n }\n map.set(profileResourceKey(resource), resource);\n }\n return map;\n}\n\nfunction stripLiveMetadata(metadata: Resource[\"metadata\"] | undefined): unknown {\n if (!metadata || typeof metadata !== \"object\") {\n return {};\n }\n const record = { ...(metadata as Record<string, unknown>) };\n delete record.content_status;\n return record;\n}\n\nfunction materialFingerprint(\n resource: Pick<Resource, \"description\" | \"content\" | \"metadata\"> | ResourceCreateInput,\n): string {\n const description = (resource.description ?? \"\").trim();\n const content = (resource.content ?? \"\").replace(/\\r\\n/g, \"\\n\").trim();\n return `${description}\\n${content}\\n${JSON.stringify(stripLiveMetadata(resource.metadata))}`;\n}\n\nfunction liveDiffersFromTracked(\n live: ResourceCreateInput,\n tracked: Resource | undefined,\n): boolean {\n if (!tracked) {\n return true;\n }\n if (isLiveLibraryRef(tracked)) {\n return false;\n }\n return materialFingerprint(live) !== materialFingerprint(tracked);\n}\n\n\n/** Normalize on-disk / expected paths for ownership comparisons. */\nexport function normalizeManagedPath(path: string, rootPath?: string): string {\n let normalized = path.replace(/\\\\/g, \"/\");\n if (normalized.startsWith(\"~/\")) {\n normalized = normalized.slice(2);\n }\n if (rootPath) {\n const root = rootPath.replace(/\\\\/g, \"/\").replace(/\\/$/, \"\");\n if (normalized === root || normalized.startsWith(`${root}/`)) {\n normalized = normalized.slice(root.length).replace(/^\\//, \"\");\n }\n }\n return normalized.replace(/^\\.\\//, \"\");\n}\n\nconst MERGED_CONTAINER_RESOURCE_TYPES = new Set([\n \"permission\",\n \"env_var\",\n \"hook\",\n]);\n\nfunction isClaudeSettingsPath(normalizedPath: string): boolean {\n const path = normalizedPath.replace(/^~\\//, \"\");\n return path === \".claude/settings.json\" || path.endsWith(\"/.claude/settings.json\");\n}\n\nfunction isClaudeUserJsonPath(normalizedPath: string): boolean {\n const path = normalizedPath.replace(/^~\\//, \"\");\n if (path.includes(\"#\")) {\n return false;\n }\n return path === \".claude.json\" || path.endsWith(\"/.claude.json\");\n}\n\nfunction isMuseSettingsPath(normalizedPath: string): boolean {\n const path = normalizedPath.replace(/^~\\//, \"\");\n return (\n path === \".config/muse/settings.json\"\n || path.endsWith(\"/.config/muse/settings.json\")\n );\n}\n\nfunction isMinimaxMcpPath(normalizedPath: string): boolean {\n const path = normalizedPath.replace(/^~\\//, \"\");\n return path === \".minimax/mcp.json\" || path.endsWith(\"/.minimax/mcp.json\");\n}\n\nfunction isMcpConfigPath(normalizedPath: string): boolean {\n return /(^|\\/)(\\.?mcp\\.json|mcp[-_]config\\.json)$/i.test(\n normalizedPath.replace(/^~\\//, \"\"),\n );\n}\n\nfunction isMergedContainerResource(\n resource: Pick<Resource, \"type\" | \"source\"> | Pick<ResourceCreateInput, \"type\" | \"source\">,\n rootPath: string,\n): boolean {\n const sourcePath = normalizeManagedPath(resource.source ?? \"\", rootPath);\n if (!sourcePath) {\n return false;\n }\n if (resource.type === \"mcp_server\") {\n return (\n isMcpConfigPath(sourcePath)\n || isClaudeUserJsonPath(sourcePath)\n || isMuseSettingsPath(sourcePath)\n || isMinimaxMcpPath(sourcePath)\n );\n }\n if (!MERGED_CONTAINER_RESOURCE_TYPES.has(resource.type)) {\n return false;\n }\n return isClaudeSettingsPath(sourcePath) || isMuseSettingsPath(sourcePath);\n}\n\nasync function profileOwnedPaths(\n profileSelector: string,\n rootPath: string,\n platformIds: string[],\n target: \"global\" | \"project\",\n): Promise<Set<string>> {\n const profilePlugin = resolvePluginSelector(profileSelector);\n if (!profilePlugin || !isProfilePlugin(profilePlugin) || platformIds.length === 0) {\n return new Set();\n }\n const merged = mergePluginsForApply(collectProfilePluginIds(profilePlugin));\n const material = merged.resources.filter(isMaterialResource);\n if (material.length === 0) {\n return new Set();\n }\n try {\n const generated = await generateFiles(material, platformIds, rootPath, {\n target,\n claudeConfig: merged.claude,\n });\n const paths = new Set<string>();\n for (const result of generated) {\n for (const file of result.files) {\n paths.add(normalizeManagedPath(file.path, rootPath));\n }\n }\n return paths;\n } catch {\n return new Set();\n }\n}\n\nfunction sortContentsResources(\n resources: ProfileContentsResource[],\n): ProfileContentsResource[] {\n return resources.sort((a, b) => {\n const typeOrder = a.type.localeCompare(b.type);\n return typeOrder !== 0 ? typeOrder : a.name.localeCompare(b.name);\n });\n}\n\nasync function notStagedFromHomeScan(\n profileSelector: string,\n harness?: string,\n): Promise<ProfileContentsResource[]> {\n const profilePlugin = resolvePluginSelector(profileSelector);\n if (!profilePlugin || !isProfilePlugin(profilePlugin)) {\n return [];\n }\n\n const committed = trackedResourceMap(profileSelector);\n const homeRoot = resolveHomeRoot();\n // Scan all detected harnesses unless a specific harness filter is requested.\n const scanned = await scanHomeDefaults(\n harness ? resolveRegisteredScanTargets(harness)[0] : undefined,\n homeRoot,\n );\n const platformIds = scanned.map((result) => result.platformId);\n const ownedPaths = await profileOwnedPaths(\n profileSelector,\n homeRoot,\n platformIds,\n \"global\",\n );\n const notStaged: ProfileContentsResource[] = [];\n const seen = new Set<string>();\n\n for (const result of scanned) {\n for (const resource of result.resources) {\n if (!isMaterialResource(resource)) {\n continue;\n }\n const key = profileResourceKey(resource);\n const tracked = committed.get(key);\n if (tracked && !liveDiffersFromTracked(resource, tracked)) {\n continue;\n }\n if (seen.has(key)) {\n continue;\n }\n const sourcePath = normalizeManagedPath(resource.source ?? \"\", homeRoot);\n if (\n sourcePath &&\n ownedPaths.has(sourcePath) &&\n !isMergedContainerResource(resource, homeRoot)\n && !tracked\n ) {\n // Singleton file materialized by the profile (e.g. CLAUDE.md).\n continue;\n }\n seen.add(key);\n const live = ensureLiveLibraryRef(resource, homeRoot);\n notStaged.push(\n toNotStagedContentsResource(live, tracked ? \"update\" : \"add\"),\n );\n }\n }\n\n return sortContentsResources(notStaged);\n}\n\nasync function notStagedFromProjectScan(\n profileSelector: string,\n projectPath: string,\n): Promise<ProfileContentsResource[]> {\n const profilePlugin = resolvePluginSelector(profileSelector);\n if (!profilePlugin || !isProfilePlugin(profilePlugin)) {\n return [];\n }\n\n const committed = trackedResourceMap(profileSelector);\n const resolvedRoot = resolve(projectPath);\n const scanStatus = await assessProjectScanStatus(resolvedRoot);\n const platformIds = scanStatus.on_disk.platforms;\n const ownedPaths = await profileOwnedPaths(\n profileSelector,\n resolvedRoot,\n platformIds,\n \"project\",\n );\n const notStaged: ProfileContentsResource[] = [];\n const seen = new Set<string>();\n\n for (const resource of scanStatus.on_disk.resources) {\n if (!isMaterialResource(resource)) {\n continue;\n }\n const key = profileResourceKey(resource);\n const tracked = committed.get(key);\n if (tracked && !liveDiffersFromTracked(resource, tracked)) {\n continue;\n }\n if (seen.has(key)) {\n continue;\n }\n const sourcePath = normalizeManagedPath(resource.source ?? \"\", resolvedRoot);\n if (\n sourcePath &&\n ownedPaths.has(sourcePath) &&\n !isMergedContainerResource(resource, resolvedRoot)\n && !tracked\n ) {\n continue;\n }\n seen.add(key);\n const live = ensureLiveLibraryRef(\n {\n type: resource.type,\n name: resource.name,\n description: resource.description,\n content: resource.content,\n metadata: resource.metadata,\n source: resource.source,\n namespace: resource.namespace,\n },\n resolvedRoot,\n );\n notStaged.push(\n toNotStagedContentsResource(live, tracked ? \"update\" : \"add\"),\n );\n }\n\n return sortContentsResources(notStaged);\n}\n\n/** @deprecated Prefer detectNotStagedProfileResources: same behavior. */\nexport async function detectUntrackedProfileResources(input: {\n profileSelector: string;\n scope: ProfileApplyPreviewScope;\n projectPath?: string;\n harness?: string;\n}): Promise<ProfileContentsResource[]> {\n return detectNotStagedProfileResources(input);\n}\n\nexport async function detectNotStagedProfileResources(input: {\n profileSelector: string;\n scope: ProfileApplyPreviewScope;\n projectPath?: string;\n harness?: string;\n}): Promise<ProfileContentsResource[]> {\n if (input.scope === \"project\") {\n if (!input.projectPath) {\n return [];\n }\n return notStagedFromProjectScan(input.profileSelector, input.projectPath);\n }\n return notStagedFromHomeScan(input.profileSelector, input.harness);\n}\n\nfunction filterScanResultsForResourceKeys(\n results: ScanResult[],\n keys: ReadonlySet<string>,\n): ScanResult[] {\n if (keys.size === 0) {\n return [];\n }\n const filtered: ScanResult[] = [];\n for (const result of results) {\n const resources = result.resources.filter((resource) =>\n keys.has(profileResourceKey(resource)),\n );\n if (resources.length === 0) {\n continue;\n }\n filtered.push({ ...result, resources });\n }\n return filtered;\n}\n\nfunction filterScanResultsForResource(\n results: ScanResult[],\n resourceType: string,\n resourceName: string,\n): ScanResult[] {\n return filterScanResultsForResourceKeys(\n results,\n new Set([`${resourceType}:${resourceName}`]),\n );\n}\n\nexport async function addResourceToProfile(input: {\n profileSelector: string;\n resourceType: string;\n resourceName: string;\n scope: ProfileApplyPreviewScope;\n projectPath?: string;\n harness?: string;\n}): Promise<ProfileContentsResource> {\n const profilePlugin = resolvePluginSelector(input.profileSelector);\n if (!profilePlugin) {\n throw new Error(`Profile not found: ${input.profileSelector}`);\n }\n if (!isProfilePlugin(profilePlugin)) {\n throw new Error(`Plugin \"${profilePlugin.name}\" is not tagged as a profile`);\n }\n if (!MATERIAL_RESOURCE_TYPE_SET.has(input.resourceType)) {\n throw new Error(`Unsupported resource type: ${input.resourceType}`);\n }\n\n const trackedKeys = trackedResourceKeys(input.profileSelector);\n const key = `${input.resourceType}:${input.resourceName}`;\n const alreadyInProfile = trackedKeys.has(key);\n\n const { originRef, scanResults } = await resolveUntrackedScanResults(input);\n const matchingResults = filterScanResultsForResource(\n scanResults,\n input.resourceType,\n input.resourceName,\n );\n if (matchingResults.length === 0) {\n throw new Error(\n `Resource not found on disk: ${input.resourceType}:${input.resourceName}`,\n );\n }\n\n const persisted = persistScanResults(matchingResults, {\n conflictPolicy: \"overwrite\",\n originRef,\n });\n const resource = persisted.resolved.find(\n (entry) =>\n entry.type === input.resourceType && entry.name === input.resourceName,\n );\n if (!resource) {\n throw new Error(\n `Could not import resource: ${input.resourceType}:${input.resourceName}`,\n );\n }\n\n markPluginDirty(profilePlugin.id);\n if (!alreadyInProfile) {\n addResourceToPlugin(profilePlugin.id, resource.id, diskCaptureHarnessScope(resource));\n }\n touchPluginUpdatedAt(profilePlugin.id);\n\n return toNotStagedContentsResource(resource, alreadyInProfile ? \"update\" : \"add\");\n}\n\nfunction isHarnessTapPackageCachePath(normalized: string, originRef: string): boolean {\n const posix = normalized.replace(/\\\\/g, \"/\");\n if (\n posix.includes(\"/.harnesstap/cache/\")\n || posix.startsWith(\".harnesstap/cache/\")\n || posix.includes(`/${PACKAGES_CACHE_ROOT}/`)\n || posix.startsWith(`${PACKAGES_CACHE_ROOT}/`)\n ) {\n return true;\n }\n const htDir = harnesstapDirForHomeRoot(originRef).replace(/\\\\/g, \"/\").replace(/\\/$/, \"\");\n const origin = originRef.replace(/\\\\/g, \"/\").replace(/\\/$/, \"\");\n const absolute =\n posix.startsWith(\"/\") || /^[A-Za-z]:/.test(posix)\n ? posix\n : `${origin}/${posix}`;\n return (\n absolute.startsWith(`${htDir}/cache/packages/`)\n || absolute === `${htDir}/cache/packages`\n || absolute.startsWith(`${htDir}/cache/`)\n );\n}\n\n/** Unique scanned on-disk sources across every harness, relative to origin. */\nfunction collectDiscardSourcePaths(\n scanResults: ScanResult[],\n originRef: string,\n): string[] {\n const seen = new Set<string>();\n const paths: string[] = [];\n for (const result of scanResults) {\n for (const resource of result.resources) {\n if (!isMaterialResource(resource)) {\n continue;\n }\n const source = resource.source?.trim() ?? \"\";\n if (!source || source === \"manual\") {\n continue;\n }\n const normalized = normalizeManagedPath(source, originRef);\n if (!normalized || seen.has(normalized)) {\n continue;\n }\n if (isMergedContainerResource(resource, originRef)) {\n continue;\n }\n if (isHarnessTapPackageCachePath(normalized, originRef)) {\n continue;\n }\n if (isCursorHostManagedSkillsPath(normalized) || isCursorHostManagedSkillsPath(source)) {\n continue;\n }\n seen.add(normalized);\n paths.push(normalized);\n }\n }\n return paths;\n}\n\nfunction discardedContentsFromScan(\n scanResults: ScanResult[],\n): ProfileContentsResource[] {\n const seen = new Set<string>();\n const resources: ProfileContentsResource[] = [];\n for (const result of scanResults) {\n for (const resource of result.resources) {\n if (!isMaterialResource(resource)) {\n continue;\n }\n const key = profileResourceKey(resource);\n if (seen.has(key)) {\n continue;\n }\n seen.add(key);\n resources.push({\n id: \"\",\n type: resource.type,\n name: resource.name,\n source: resource.source,\n ...(resource.origin_kind ? { origin_kind: resource.origin_kind } : {}),\n ...(resource.origin_ref ? { origin_ref: resource.origin_ref } : {}),\n });\n }\n }\n return resources;\n}\n\nasync function discardableNotInProfileScanResults(input: {\n profileSelector: string;\n scope: ProfileApplyPreviewScope;\n projectPath?: string;\n harness?: string;\n}): Promise<{ originRef: string; scanResults: ScanResult[] }> {\n const trackedKeys = trackedResourceKeys(input.profileSelector);\n const { originRef, scanResults } = await resolveUntrackedScanResults({\n ...input,\n // Equal discard: every detected harness, not the main-harness filter.\n harness: undefined,\n });\n const filtered = scanResults\n .map((result) => ({\n ...result,\n resources: result.resources.filter((resource) => {\n if (!isMaterialResource(resource)) {\n return false;\n }\n if (isCursorHostManagedSkillsPath(resource.source ?? \"\")) {\n return false;\n }\n return !trackedKeys.has(profileResourceKey(resource));\n }),\n }))\n .filter((result) => result.resources.length > 0);\n return { originRef, scanResults: filtered };\n}\n\nasync function discardScanResultsFromHarness(input: {\n profileSelector: string;\n scope: ProfileApplyPreviewScope;\n projectPath?: string;\n harness?: string;\n originRef: string;\n scanResults: ScanResult[];\n}): Promise<{\n removed_paths: string[];\n discarded_count: number;\n resources: ProfileContentsResource[];\n}> {\n if (input.scanResults.length === 0) {\n throw new Error(\"No live resources to discard.\");\n }\n\n const resources = discardedContentsFromScan(input.scanResults);\n if (resources.length === 0) {\n throw new Error(\"No live resources to discard.\");\n }\n\n const paths = collectDiscardSourcePaths(input.scanResults, input.originRef);\n if (paths.length === 0) {\n throw new Error(\"No managed files to remove for discard.\");\n }\n removeGlobalMaterializedFiles(input.originRef, paths, { mode: \"listed\" });\n\n if (input.scope === \"project\") {\n const rescanned = await scanProject(input.originRef);\n reconcileLocalSnapshotScan(input.originRef, rescanned);\n } else {\n const rescanned = await scanHomeDefaults(undefined, input.originRef);\n reconcileLocalSnapshotScan(input.originRef, rescanned);\n }\n\n return {\n removed_paths: paths,\n discarded_count: resources.length,\n resources,\n };\n}\n\n/** Remove one on-disk resource that is not in the profile stack (Not in profile). */\nexport async function discardLiveResourceFromHarness(input: {\n profileSelector: string;\n resourceType: string;\n resourceName: string;\n scope: ProfileApplyPreviewScope;\n projectPath?: string;\n harness?: string;\n}): Promise<{\n removed_paths: string[];\n resource: ProfileContentsResource;\n}> {\n if (!MATERIAL_RESOURCE_TYPE_SET.has(input.resourceType)) {\n throw new Error(`Unsupported resource type: ${input.resourceType}`);\n }\n const trackedKeys = trackedResourceKeys(input.profileSelector);\n const key = `${input.resourceType}:${input.resourceName}`;\n if (trackedKeys.has(key)) {\n throw new Error(`Resource is in profile: ${input.resourceType}:${input.resourceName}`);\n }\n\n const { originRef, scanResults } = await discardableNotInProfileScanResults(input);\n const matching = filterScanResultsForResource(\n scanResults,\n input.resourceType,\n input.resourceName,\n );\n if (matching.length === 0) {\n throw new Error(\n `Resource not found on disk: ${input.resourceType}:${input.resourceName}`,\n );\n }\n\n const result = await discardScanResultsFromHarness({\n ...input,\n originRef,\n scanResults: matching,\n });\n const resource = result.resources.find(\n (entry) => entry.type === input.resourceType && entry.name === input.resourceName,\n );\n if (!resource) {\n throw new Error(\n `Could not discard resource: ${input.resourceType}:${input.resourceName}`,\n );\n }\n return { removed_paths: result.removed_paths, resource };\n}\n\nexport type DiscardLiveResourceSelector = {\n resourceType: string;\n resourceName: string;\n};\n\n/** Remove every on-disk resource that is not in the profile stack (Not in profile). */\nexport async function discardAllLiveResourcesFromHarness(input: {\n profileSelector: string;\n scope: ProfileApplyPreviewScope;\n projectPath?: string;\n harness?: string;\n resources?: DiscardLiveResourceSelector[];\n}): Promise<{\n removed_paths: string[];\n discarded_count: number;\n resources: ProfileContentsResource[];\n}> {\n const { originRef, scanResults } = await discardableNotInProfileScanResults(input);\n const selected = input.resources?.length\n ? filterScanResultsForResourceKeys(\n scanResults,\n new Set(\n input.resources.map(\n (resource) => `${resource.resourceType}:${resource.resourceName}`,\n ),\n ),\n )\n : scanResults;\n return discardScanResultsFromHarness({\n ...input,\n originRef,\n scanResults: selected,\n });\n}\n\n/** Not-staged lists adds and live updates; stash only captures resources not already on the profile. */\ntype UntrackedScanMode = \"not-staged\" | \"stash-untracked\";\n\nasync function resolveUntrackedScanResults(input: {\n profileSelector: string;\n scope: ProfileApplyPreviewScope;\n projectPath?: string;\n harness?: string;\n mode?: UntrackedScanMode;\n}): Promise<{ originRef: string; scanResults: ScanResult[] }> {\n const profilePlugin = resolvePluginSelector(input.profileSelector);\n if (!profilePlugin || !isProfilePlugin(profilePlugin)) {\n throw new Error(`Profile not found: ${input.profileSelector}`);\n }\n\n const committed = trackedResourceMap(input.profileSelector);\n const mode = input.mode ?? \"not-staged\";\n\n if (input.scope === \"project\") {\n if (!input.projectPath) {\n throw new Error(\"projectPath is required for project scope\");\n }\n const originRef = resolve(input.projectPath);\n const scanned = await scanProject(originRef);\n const ownedPaths = await profileOwnedPaths(\n input.profileSelector,\n originRef,\n scanned.map((result) => result.platformId),\n \"project\",\n );\n return {\n originRef,\n scanResults: filterScanResultsToNotStaged(\n scanned,\n committed,\n ownedPaths,\n originRef,\n mode,\n ),\n };\n }\n\n const originRef = resolveHomeRoot();\n const scanned = await scanHomeDefaults(\n input.harness ? resolveRegisteredScanTargets(input.harness)[0] : undefined,\n originRef,\n );\n const ownedPaths = await profileOwnedPaths(\n input.profileSelector,\n originRef,\n scanned.map((result) => result.platformId),\n \"global\",\n );\n return {\n originRef,\n scanResults: filterScanResultsToNotStaged(\n scanned,\n committed,\n ownedPaths,\n originRef,\n mode,\n ),\n };\n}\n\nexport async function addAllUntrackedResourcesToProfile(input: {\n profileSelector: string;\n scope: ProfileApplyPreviewScope;\n projectPath?: string;\n harness?: string;\n}): Promise<{ resources: ProfileContentsResource[]; added_count: number }> {\n const profilePlugin = resolvePluginSelector(input.profileSelector);\n if (!profilePlugin) {\n throw new Error(`Profile not found: ${input.profileSelector}`);\n }\n if (!isProfilePlugin(profilePlugin)) {\n throw new Error(`Plugin \"${profilePlugin.name}\" is not tagged as a profile`);\n }\n\n const { originRef, scanResults } = await resolveUntrackedScanResults(input);\n if (scanResults.length === 0) {\n throw new Error(\"No untracked resources to add to profile.\");\n }\n\n const persisted = persistScanResults(scanResults, {\n conflictPolicy: \"overwrite\",\n originRef,\n });\n const materialResources = persisted.resolved.filter(isMaterialResource);\n if (materialResources.length === 0) {\n throw new Error(\"No untracked resources to add to profile.\");\n }\n\n markPluginDirty(profilePlugin.id);\n for (const resource of materialResources) {\n addResourceToPlugin(profilePlugin.id, resource.id, diskCaptureHarnessScope(resource));\n }\n touchPluginUpdatedAt(profilePlugin.id);\n\n const resources = materialResources.map((resource) => toContentsResource(resource));\n return {\n resources,\n added_count: resources.length,\n };\n}\n\nexport interface StashedFileSnapshot {\n path: string;\n content: string;\n platform?: string;\n}\n\nexport interface UntrackedStashCapture {\n resources: ProfileContentsResource[];\n files: StashedFileSnapshot[];\n}\n\nfunction filterScanResultsToNotStaged(\n results: ScanResult[],\n committed: ReadonlyMap<string, Resource>,\n ownedPaths: ReadonlySet<string>,\n rootPath: string,\n mode: UntrackedScanMode,\n): ScanResult[] {\n const filtered: ScanResult[] = [];\n for (const result of results) {\n const resources = result.resources.filter((resource) => {\n if (!isMaterialResource(resource)) {\n return false;\n }\n const key = profileResourceKey(resource);\n const tracked = committed.get(key);\n switch (mode) {\n case \"stash-untracked\":\n if (tracked) {\n return false;\n }\n break;\n case \"not-staged\":\n if (tracked && !liveDiffersFromTracked(resource, tracked)) {\n return false;\n }\n break;\n default: {\n const exhaustive: never = mode;\n throw new Error(`Unhandled untracked scan mode: ${exhaustive}`);\n }\n }\n const sourcePath = normalizeManagedPath(resource.source ?? \"\", rootPath);\n if (\n sourcePath &&\n ownedPaths.has(sourcePath) &&\n !isMergedContainerResource(resource, rootPath)\n && !tracked\n ) {\n return false;\n }\n return true;\n });\n if (resources.length > 0) {\n filtered.push({ ...result, resources });\n }\n }\n return filtered;\n}\n\nfunction readHomeFile(homeRoot: string, relativePath: string): string | null {\n const fullPath = resolve(homeRoot, relativePath);\n if (!existsSync(fullPath)) {\n return null;\n }\n try {\n return readFileSync(fullPath, \"utf-8\");\n } catch {\n return null;\n }\n}\n\nexport function buildContentsFromResources(\n resources: ProfileContentsResource[],\n): ProfileContents {\n const typeCounts: Record<string, number> = {};\n for (const resource of resources) {\n typeCounts[resource.type] = (typeCounts[resource.type] ?? 0) + 1;\n }\n const summaryParts = Object.entries(typeCounts)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([type, count]) => `${count} ${type}${count === 1 ? \"\" : \"s\"}`);\n return {\n plugins: [],\n stack_resource_count: resources.length,\n stack_summary: summaryParts.join(\", \") || null,\n type_counts: typeCounts,\n resources,\n plugin_pins: [],\n mcp_servers: [],\n };\n}\n\nexport async function captureUntrackedResourcesForStash(input: {\n profileSelector: string;\n harness?: string;\n}): Promise<UntrackedStashCapture> {\n const profilePlugin = resolvePluginSelector(input.profileSelector);\n if (!profilePlugin || !isProfilePlugin(profilePlugin)) {\n throw new Error(`Profile not found: ${input.profileSelector}`);\n }\n\n const harnesses = resolveRegisteredScanTargets(input.harness);\n const homeRoot = resolveHomeRoot();\n const { scanResults: untrackedScanResults } = await resolveUntrackedScanResults({\n profileSelector: input.profileSelector,\n scope: \"home\",\n harness: input.harness,\n mode: \"stash-untracked\",\n });\n if (untrackedScanResults.length === 0) {\n throw new Error(\"No untracked resources to stash.\");\n }\n\n const persisted = persistScanResults(untrackedScanResults, {\n conflictPolicy: \"overwrite\",\n originRef: homeRoot,\n });\n const resources = persisted.resolved\n .filter(isMaterialResource)\n .map((resource) => toContentsResource(resource));\n\n const generated = await generateFiles(\n persisted.resolved.filter(isMaterialResource),\n harnesses,\n homeRoot,\n { target: \"global\" },\n );\n\n const files: StashedFileSnapshot[] = [];\n const seenPaths = new Set<string>();\n for (const result of generated) {\n for (const file of result.files) {\n if (seenPaths.has(file.path)) {\n continue;\n }\n if (isCursorHostManagedSkillsPath(file.path)) {\n continue;\n }\n seenPaths.add(file.path);\n const current = readHomeFile(homeRoot, file.path);\n if (current === null) {\n continue;\n }\n files.push({\n path: file.path,\n content: current,\n platform: result.platformId,\n });\n }\n }\n\n if (resources.length === 0) {\n throw new Error(\"No untracked resources to stash.\");\n }\n\n return { resources, files };\n}\n\nexport function removeUntrackedStashFiles(\n homeRoot: string,\n files: StashedFileSnapshot[],\n dryRun = false,\n): string[] {\n const paths = files.map((file) => file.path);\n if (!dryRun) {\n removeGlobalMaterializedFiles(homeRoot, paths, { mode: \"listed\" });\n }\n return paths;\n}\n\nexport function restoreUntrackedStashFiles(\n homeRoot: string,\n files: StashedFileSnapshot[],\n dryRun = false,\n): string[] {\n const restored: string[] = [];\n for (const file of files) {\n if (dryRun) {\n restored.push(file.path);\n continue;\n }\n const fullPath = resolve(homeRoot, file.path);\n mkdirSync(dirname(fullPath), { recursive: true });\n writeFileSync(fullPath, file.content, \"utf-8\");\n restored.push(file.path);\n }\n return restored;\n}\n\nexport function stashedFilesToDriftChanges(\n files: StashedFileSnapshot[],\n): DriftFileChange[] {\n return files.map((file) => ({\n path: file.path,\n type: \"added\" as const,\n ...(file.platform ? { platform: file.platform } : {}),\n }));\n}\n","import { resolve } from \"node:path\";\nimport {\n detectPlatforms,\n hasPluginSourceLayout,\n scanProject,\n type ScanResult,\n} from \"./scanner.js\";\nimport { scanPluginSourceForMerge } from \"./plugin-source-import.js\";\nimport { dropHarnessSkillsDuplicatingPluginSource } from \"./scan-dedup.js\";\nimport { listResourcesByOriginRef, normalizeResourceInput } from \"../models/resource.js\";\nimport { hashResourceBody } from \"./resource-hash.js\";\nimport type { Resource, ResourceCreateInput, ResourceType } from \"../types.js\";\n\nexport type ProjectScanComparisonStatus =\n | \"no_harness_files\"\n | \"not_scanned\"\n | \"up_to_date\"\n | \"stale\";\n\nexport interface ProjectScanStatus {\n on_disk: {\n resources: Resource[];\n harness_resource_count: number;\n plugin_source: boolean;\n platforms: string[];\n };\n in_library: {\n resources: Resource[];\n };\n comparison: {\n status: ProjectScanComparisonStatus;\n new_count: number;\n changed_count: number;\n removed_count: number;\n };\n}\n\nfunction resourceDedupKey(\n resource: Pick<Resource, \"type\" | \"name\" | \"namespace\">,\n): string {\n return `${resource.type}:${resource.name}:${resource.namespace ?? \"\"}`;\n}\n\nfunction scanInputToComparableResource(\n input: ResourceCreateInput,\n projectRoot: string,\n persistNamespace = \"\",\n): Resource {\n const normalized = normalizeResourceInput({\n ...input,\n namespace: input.namespace ?? persistNamespace,\n origin_kind: \"local_snapshot\",\n origin_ref: projectRoot,\n });\n const namespace = normalized.namespace ?? \"\";\n const contentHash = hashResourceBody({\n type: normalized.type,\n content: normalized.content,\n metadata: normalized.metadata,\n });\n const now = new Date(0).toISOString();\n return {\n id: `scan:${resourceDedupKey({ ...normalized, namespace })}`,\n type: normalized.type,\n name: normalized.name,\n description: normalized.description,\n content: normalized.content,\n metadata: normalized.metadata,\n source: normalized.source,\n namespace,\n origin_kind: normalized.origin_kind ?? \"local_snapshot\",\n origin_ref: normalized.origin_ref ?? projectRoot,\n content_hash: contentHash,\n content_blob_ref: \"\",\n created_at: now,\n updated_at: now,\n };\n}\n\nfunction flattenHarnessScanResults(\n projectRoot: string,\n results: ScanResult[],\n): Resource[] {\n const seen = new Set<string>();\n const resources: Resource[] = [];\n\n for (const result of results) {\n for (const resource of result.resources) {\n const comparable = scanInputToComparableResource(resource, projectRoot, \"project\");\n const key = resourceDedupKey(comparable);\n if (seen.has(key)) {\n continue;\n }\n seen.add(key);\n resources.push(comparable);\n }\n }\n\n return resources;\n}\n\nfunction flattenPluginScanResults(\n projectRoot: string,\n plugin: Awaited<ReturnType<typeof scanPluginSourceForMerge>>,\n): Resource[] {\n const seen = new Set<string>();\n const resources: Resource[] = [];\n\n for (const result of plugin) {\n for (const resource of result.resources) {\n const comparable = scanInputToComparableResource(resource, projectRoot);\n const key = resourceDedupKey(comparable);\n if (seen.has(key)) {\n continue;\n }\n seen.add(key);\n resources.push(comparable);\n }\n }\n\n return resources;\n}\n\nfunction compareHarnessResources(\n onDisk: Resource[],\n inLibrary: Resource[],\n): Pick<ProjectScanStatus[\"comparison\"], \"status\" | \"new_count\" | \"changed_count\" | \"removed_count\"> {\n const libraryByKey = new Map(\n inLibrary.map((resource) => [resourceDedupKey(resource), resource]),\n );\n const onDiskKeys = new Set<string>();\n\n let newCount = 0;\n let changedCount = 0;\n\n for (const resource of onDisk) {\n const key = resourceDedupKey(resource);\n onDiskKeys.add(key);\n const existing = libraryByKey.get(key);\n if (!existing) {\n newCount += 1;\n continue;\n }\n if (existing.content_hash !== resource.content_hash) {\n changedCount += 1;\n }\n }\n\n let removedCount = 0;\n for (const resource of inLibrary) {\n const key = resourceDedupKey(resource);\n if (!onDiskKeys.has(key)) {\n removedCount += 1;\n }\n }\n\n if (onDisk.length === 0) {\n if (inLibrary.length > 0) {\n return {\n status: \"stale\",\n new_count: 0,\n changed_count: 0,\n removed_count: inLibrary.length,\n };\n }\n return {\n status: \"no_harness_files\",\n new_count: 0,\n changed_count: 0,\n removed_count: 0,\n };\n }\n\n if (inLibrary.length === 0) {\n return {\n status: \"not_scanned\",\n new_count: onDisk.length,\n changed_count: 0,\n removed_count: 0,\n };\n }\n\n if (newCount > 0 || changedCount > 0 || removedCount > 0) {\n return {\n status: \"stale\",\n new_count: newCount,\n changed_count: changedCount,\n removed_count: removedCount,\n };\n }\n\n return {\n status: \"up_to_date\",\n new_count: 0,\n changed_count: 0,\n removed_count: 0,\n };\n}\n\nexport function countResourcesByType(\n resources: Pick<Resource, \"type\">[],\n): Partial<Record<ResourceType, number>> {\n const counts: Partial<Record<ResourceType, number>> = {};\n for (const resource of resources) {\n counts[resource.type] = (counts[resource.type] ?? 0) + 1;\n }\n return counts;\n}\n\nexport async function assessProjectScanStatus(\n projectRoot: string,\n): Promise<ProjectScanStatus> {\n const resolvedRoot = resolve(projectRoot);\n const rawHarness = await scanProject(resolvedRoot);\n let plugin: Awaited<ReturnType<typeof scanPluginSourceForMerge>> = [];\n if (hasPluginSourceLayout(resolvedRoot)) {\n try {\n plugin = await scanPluginSourceForMerge(resolvedRoot);\n } catch {\n plugin = [];\n }\n }\n\n const harness = dropHarnessSkillsDuplicatingPluginSource(rawHarness, plugin);\n const harnessOnDisk = flattenHarnessScanResults(resolvedRoot, harness);\n const pluginOnDisk = flattenPluginScanResults(resolvedRoot, plugin);\n const onDiskResources = [...harnessOnDisk, ...pluginOnDisk];\n const inLibraryResources = listResourcesByOriginRef(resolvedRoot);\n let comparison = compareHarnessResources(harnessOnDisk, inLibraryResources);\n\n if (\n comparison.status === \"no_harness_files\"\n && pluginOnDisk.length > 0\n && inLibraryResources.length === 0\n ) {\n comparison = {\n status: \"not_scanned\",\n new_count: onDiskResources.length,\n changed_count: 0,\n removed_count: 0,\n };\n }\n\n return {\n on_disk: {\n resources: onDiskResources,\n harness_resource_count: harnessOnDisk.length,\n plugin_source: hasPluginSourceLayout(resolvedRoot),\n platforms: detectPlatforms(resolvedRoot),\n },\n in_library: {\n resources: inLibraryResources,\n },\n comparison,\n };\n}\n","import {\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n rmdirSync,\n rmSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { basename, dirname, join, resolve, sep } from \"node:path\";\nimport { ulid } from \"ulid\";\nimport { getHarnesstapDir } from \"../db/connection.js\";\nimport {\n listApplyRemovalBackups,\n recordApplyRemovalBackup,\n} from \"../models/apply-removal-backup.js\";\nimport { isPreexistingPath } from \"../models/preexisting-path.js\";\nimport {\n deleteMaterializationsForRootPaths,\n listMaterializationsForRootPath,\n} from \"../models/resource-materialization.js\";\nimport { hashGeneratedContent } from \"./materialization-ownership.js\";\n\nconst APPLY_TRASH_KEEP = 10;\nconst CONTAINER_DIR_NAMES = new Set([\n \"skills\",\n \"agents\",\n \"commands\",\n \"hooks\",\n \"rules\",\n \"plugins\",\n]);\n\nexport type SafeRemovalSkipReason =\n | \"preexisting\"\n | \"unmanaged\"\n | \"modified\"\n | \"missing\";\n\nexport interface SafeRemovalSkip {\n path: string;\n reason: SafeRemovalSkipReason;\n message: string;\n}\n\nexport interface SafeRemovalPlan {\n remove: string[];\n skip: SafeRemovalSkip[];\n}\n\nexport interface SafeFileRemovalOptions {\n applyId?: string;\n snapshotId?: string | null;\n forceRemove?: boolean;\n dryRun?: boolean;\n /**\n * `owned` (default): only remove HarnessTap-tracked files whose hash still\n * matches, unless `forceRemove` is set. `listed` deletes the exact listed\n * files (explicit user actions such as stash) after backing them up.\n */\n mode?: \"owned\" | \"listed\";\n}\n\nexport interface SafeFileRemovalResult {\n applyId: string;\n backupDir: string;\n removed: string[];\n skipped: SafeRemovalSkip[];\n warnings: string[];\n}\n\nexport function applyTrashRoot(): string {\n return join(getHarnesstapDir(), \"trash\");\n}\n\nexport function isApplyTrashTarget(target: string): boolean {\n const root = resolve(applyTrashRoot());\n const resolved = resolve(String(target));\n return resolved === root || resolved.startsWith(`${root}${sep}`);\n}\n\nexport function hashOnDiskFile(fullPath: string): string | undefined {\n try {\n const bytes = readFileSync(fullPath);\n return hashGeneratedContent(bytes.toString(\"utf-8\"));\n } catch {\n return undefined;\n }\n}\n\nfunction normalizeRelative(path: string): string {\n return path.replace(/\\\\/g, \"/\").replace(/^\\.\\//, \"\");\n}\n\nexport type ManagedPathOwnership = \"unowned\" | \"owned\" | \"modified\";\n\n/**\n * Ownership is manifest row plus current hash. A tracked path whose bytes no\n * longer match what HarnessTap last wrote is `modified` and is never owned\n * again until a later apply actually writes the file.\n */\nexport function classifyManagedPathOwnership(\n rootPath: string,\n relativePath: string,\n): ManagedPathOwnership {\n const normalized = normalizeRelative(relativePath);\n const owned = listMaterializationsForRootPath(rootPath, normalized);\n if (owned.length === 0) {\n return \"unowned\";\n }\n const fullPath = resolve(rootPath, normalized);\n const diskHash = hashOnDiskFile(fullPath);\n if (owned.some((row) => row.generated_hash === diskHash)) {\n return \"owned\";\n }\n return \"modified\";\n}\n\nexport function hasHarnessTapMaterialization(\n rootPath: string,\n relativePath: string,\n): boolean {\n return listMaterializationsForRootPath(rootPath, normalizeRelative(relativePath)).length > 0;\n}\n\nexport function isHarnessTapOwnedPath(rootPath: string, relativePath: string): boolean {\n return classifyManagedPathOwnership(rootPath, relativePath) === \"owned\";\n}\n\nexport function skippedWriteKeepsForOwnership(\n rootPath: string,\n skippedFiles: readonly string[],\n): SafeRemovalSkip[] {\n const seen = new Set<string>();\n const skips: SafeRemovalSkip[] = [];\n for (const rawPath of skippedFiles) {\n const relativePath = normalizeRelative(rawPath);\n if (!relativePath || seen.has(relativePath)) {\n continue;\n }\n seen.add(relativePath);\n if (classifyManagedPathOwnership(rootPath, relativePath) !== \"modified\") {\n continue;\n }\n skips.push({\n path: relativePath,\n reason: \"modified\",\n message: skipMessage(relativePath, \"modified\"),\n });\n }\n return skips;\n}\n\nexport function mergeSafeRemovalSkips(\n ...lists: Array<readonly SafeRemovalSkip[] | undefined>\n): SafeRemovalSkip[] {\n const seen = new Set<string>();\n const merged: SafeRemovalSkip[] = [];\n for (const list of lists) {\n for (const skip of list ?? []) {\n const key = `${skip.path}:${skip.reason}`;\n if (seen.has(key)) {\n continue;\n }\n seen.add(key);\n merged.push(skip);\n }\n }\n return merged;\n}\n\nfunction skipMessage(path: string, reason: SafeRemovalSkipReason): string {\n switch (reason) {\n case \"preexisting\":\n return `Skipped removing ${path} (present before HarnessTap managed it).`;\n case \"unmanaged\":\n return `Skipped removing ${path} (not managed by HarnessTap).`;\n case \"modified\":\n return `Skipped removing ${path} (modified since HarnessTap wrote it).`;\n case \"missing\":\n return `Skipped removing ${path} (already missing).`;\n default: {\n const _exhaustive: never = reason;\n return _exhaustive;\n }\n }\n}\n\nexport function planSafeFileRemovals(\n rootPath: string,\n relativePaths: readonly string[],\n options: SafeFileRemovalOptions = {},\n): SafeRemovalPlan {\n const remove: string[] = [];\n const skip: SafeRemovalSkip[] = [];\n const mode = options.mode ?? \"owned\";\n const seen = new Set<string>();\n\n for (const rawPath of relativePaths) {\n const relativePath = normalizeRelative(rawPath);\n if (!relativePath || seen.has(relativePath)) {\n continue;\n }\n seen.add(relativePath);\n\n const fullPath = resolve(rootPath, relativePath);\n if (!existsSync(fullPath)) {\n skip.push({\n path: relativePath,\n reason: \"missing\",\n message: skipMessage(relativePath, \"missing\"),\n });\n continue;\n }\n\n if (mode === \"listed\") {\n remove.push(relativePath);\n continue;\n }\n\n if (isPreexistingPath(rootPath, relativePath)) {\n skip.push({\n path: relativePath,\n reason: \"preexisting\",\n message: skipMessage(relativePath, \"preexisting\"),\n });\n continue;\n }\n\n const ownership = classifyManagedPathOwnership(rootPath, relativePath);\n if (ownership === \"unowned\") {\n if (options.forceRemove) {\n remove.push(relativePath);\n continue;\n }\n skip.push({\n path: relativePath,\n reason: \"unmanaged\",\n message: skipMessage(relativePath, \"unmanaged\"),\n });\n continue;\n }\n\n if (ownership === \"owned\" || options.forceRemove) {\n remove.push(relativePath);\n continue;\n }\n skip.push({\n path: relativePath,\n reason: \"modified\",\n message: skipMessage(relativePath, \"modified\"),\n });\n }\n\n return { remove, skip };\n}\n\nfunction copyToTrash(applyId: string, relativePath: string, bytes: Buffer): string {\n const dest = join(applyTrashRoot(), applyId, ...relativePath.split(\"/\"));\n mkdirSync(dirname(dest), { recursive: true });\n writeFileSync(dest, bytes);\n return dest;\n}\n\nexport function pruneApplyTrash(keepLast = APPLY_TRASH_KEEP): void {\n const root = applyTrashRoot();\n if (!existsSync(root)) {\n return;\n }\n let entries: string[];\n try {\n entries = readdirSync(root);\n } catch {\n return;\n }\n const dirs = entries\n .map((name) => {\n const full = join(root, name);\n try {\n const stat = statSync(full);\n return { full, mtime: stat.mtimeMs, isDir: stat.isDirectory() };\n } catch {\n return undefined;\n }\n })\n .filter((entry): entry is { full: string; mtime: number; isDir: boolean } =>\n Boolean(entry?.isDir),\n )\n .sort((a, b) => b.mtime - a.mtime);\n for (const extra of dirs.slice(keepLast)) {\n rmSync(extra.full, { recursive: true, force: true });\n }\n}\n\nconst EMPTY_DIR_PRUNE_STOP = new Set(CONTAINER_DIR_NAMES);\n\nexport function pruneEmptyAncestors(filePath: string, stopAt: string): void {\n const stop = resolve(stopAt);\n let current = dirname(filePath);\n while (current !== stop) {\n if (resolve(current) === stop) {\n break;\n }\n const base = basename(current);\n if (EMPTY_DIR_PRUNE_STOP.has(base)) {\n break;\n }\n try {\n if (!existsSync(current)) {\n current = dirname(current);\n continue;\n }\n if (readdirSync(current).length > 0) {\n break;\n }\n rmdirSync(current);\n } catch {\n break;\n }\n current = dirname(current);\n }\n}\n\nfunction backupOnDiskFile(input: {\n rootPath: string;\n relativePath: string;\n applyId: string;\n snapshotId?: string | null;\n}): Buffer {\n const fullPath = resolve(input.rootPath, input.relativePath);\n const bytes = readFileSync(fullPath);\n let mode = 0;\n try {\n mode = statSync(fullPath).mode;\n } catch {\n mode = 0;\n }\n recordApplyRemovalBackup({\n apply_id: input.applyId,\n snapshot_id: input.snapshotId,\n relative_path: input.relativePath,\n content: bytes,\n mode,\n });\n copyToTrash(input.applyId, input.relativePath, bytes);\n return bytes;\n}\n\nfunction backupAndUnlink(input: {\n rootPath: string;\n relativePath: string;\n applyId: string;\n snapshotId?: string | null;\n}): void {\n const fullPath = resolve(input.rootPath, input.relativePath);\n backupOnDiskFile(input);\n rmSync(fullPath, { force: true });\n pruneEmptyAncestors(fullPath, input.rootPath);\n}\n\nexport function backupAndRewriteFile(input: {\n rootPath: string;\n relativePath: string;\n nextContent: string | null;\n applyId: string;\n snapshotId?: string | null;\n}): void {\n const fullPath = resolve(input.rootPath, input.relativePath);\n backupOnDiskFile(input);\n if (input.nextContent === null) {\n rmSync(fullPath, { force: true });\n pruneEmptyAncestors(fullPath, input.rootPath);\n deleteMaterializationsForRootPaths(input.rootPath, [input.relativePath]);\n return;\n }\n writeFileSync(fullPath, input.nextContent);\n}\n\nexport function executeSafeFileRemovals(\n rootPath: string,\n relativePaths: readonly string[],\n options: SafeFileRemovalOptions = {},\n): SafeFileRemovalResult {\n const applyId = options.applyId ?? ulid();\n const plan = planSafeFileRemovals(rootPath, relativePaths, options);\n const warnings = plan.skip\n .filter((entry) => entry.reason !== \"missing\")\n .map((entry) => entry.message);\n const backupDir = join(applyTrashRoot(), applyId);\n\n if (options.dryRun) {\n return {\n applyId,\n backupDir,\n removed: plan.remove,\n skipped: plan.skip,\n warnings,\n };\n }\n\n for (const relativePath of plan.remove) {\n backupAndUnlink({\n rootPath,\n relativePath,\n applyId,\n snapshotId: options.snapshotId,\n });\n }\n deleteMaterializationsForRootPaths(rootPath, plan.remove);\n pruneApplyTrash();\n\n return {\n applyId,\n backupDir,\n removed: plan.remove,\n skipped: plan.skip,\n warnings,\n };\n}\n\nexport function restoreSafeRemovalBackup(input: {\n applyId?: string;\n snapshotId?: string;\n rootPath: string;\n}): string[] {\n const backups = listApplyRemovalBackups({\n apply_id: input.applyId,\n snapshot_id: input.snapshotId,\n });\n const restored: string[] = [];\n for (const backup of backups) {\n const fullPath = resolve(input.rootPath, backup.relative_path);\n mkdirSync(dirname(fullPath), { recursive: true });\n writeFileSync(fullPath, backup.content);\n restored.push(backup.relative_path);\n }\n if (restored.length > 0) {\n return restored;\n }\n\n const applyId = input.applyId;\n if (!applyId) {\n return restored;\n }\n const trashDir = join(applyTrashRoot(), applyId);\n if (!existsSync(trashDir)) {\n return restored;\n }\n const walk = (dir: string, prefix: string): void => {\n for (const name of readdirSync(dir)) {\n const full = join(dir, name);\n const rel = prefix ? `${prefix}/${name}` : name;\n if (statSync(full).isDirectory()) {\n walk(full, rel);\n continue;\n }\n const dest = resolve(input.rootPath, rel);\n mkdirSync(dirname(dest), { recursive: true });\n writeFileSync(dest, readFileSync(full));\n restored.push(rel);\n }\n };\n walk(trashDir, \"\");\n return restored;\n}\n\nexport interface PlannedRemovals {\n owned_unmodified: string[];\n owned_modified: string[];\n unmanaged: string[];\n}\n\nexport type PlannedRemovalGroup = keyof PlannedRemovals;\n\nexport function emptyPlannedRemovals(): PlannedRemovals {\n return { owned_unmodified: [], owned_modified: [], unmanaged: [] };\n}\n\nexport function groupPlannedRemovals(plan: SafeRemovalPlan): PlannedRemovals {\n const groups = emptyPlannedRemovals();\n groups.owned_unmodified.push(...plan.remove);\n for (const skip of plan.skip) {\n switch (skip.reason) {\n case \"modified\":\n groups.owned_modified.push(skip.path);\n break;\n case \"unmanaged\":\n case \"preexisting\":\n groups.unmanaged.push(skip.path);\n break;\n case \"missing\":\n break;\n default: {\n const _exhaustive: never = skip.reason;\n return _exhaustive;\n }\n }\n }\n return groups;\n}\n\nexport function plannedRemovalsFromApplyFields(input: {\n removed_files?: string[];\n skipped_removals?: SafeRemovalSkip[];\n}): PlannedRemovals {\n return groupPlannedRemovals({\n remove: input.removed_files ?? [],\n skip: input.skipped_removals ?? [],\n });\n}\n\nexport function riskyRemovalPaths(groups: PlannedRemovals): string[] {\n return [...groups.owned_modified, ...groups.unmanaged];\n}\n\nexport function formatRemovalBackupNotice(\n result: SafeFileRemovalResult,\n homeRoot: string,\n): string | undefined {\n if (result.removed.length === 0) {\n return undefined;\n }\n const relativeTrash = result.backupDir.startsWith(homeRoot)\n ? result.backupDir.slice(homeRoot.length).replace(/^[\\\\/]/, \"\")\n : result.backupDir;\n const count = result.removed.length;\n const noun = count === 1 ? \"file\" : \"files\";\n return `Removed ${count} ${noun}. Backup: ~/${relativeTrash.replace(/\\\\/g, \"/\")}`;\n}\n","import { ulid } from \"ulid\";\nimport { getDb } from \"../db/connection.js\";\n\ninterface ApplyRemovalBackupRow {\n id: string;\n apply_id: string;\n snapshot_id: string | null;\n relative_path: string;\n content: Buffer | Uint8Array | string;\n mode: number;\n created_at: string;\n}\n\nexport interface ApplyRemovalBackup {\n id: string;\n apply_id: string;\n snapshot_id: string | null;\n relative_path: string;\n content: Buffer;\n mode: number;\n created_at: string;\n}\n\nfunction toBuffer(value: Buffer | Uint8Array | string): Buffer {\n if (Buffer.isBuffer(value)) {\n return value;\n }\n if (typeof value === \"string\") {\n return Buffer.from(value, \"utf-8\");\n }\n return Buffer.from(value);\n}\n\nfunction rowToBackup(row: ApplyRemovalBackupRow): ApplyRemovalBackup {\n return {\n id: row.id,\n apply_id: row.apply_id,\n snapshot_id: row.snapshot_id,\n relative_path: row.relative_path,\n content: toBuffer(row.content),\n mode: row.mode,\n created_at: row.created_at,\n };\n}\n\nexport function recordApplyRemovalBackup(input: {\n apply_id: string;\n snapshot_id?: string | null;\n relative_path: string;\n content: Buffer;\n mode: number;\n}): ApplyRemovalBackup {\n const db = getDb();\n const row: ApplyRemovalBackup = {\n id: ulid(),\n apply_id: input.apply_id,\n snapshot_id: input.snapshot_id ?? null,\n relative_path: input.relative_path,\n content: input.content,\n mode: input.mode,\n created_at: new Date().toISOString(),\n };\n db.prepare(\n `INSERT INTO apply_removal_backups (\n id, apply_id, snapshot_id, relative_path, content, mode, created_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?)`,\n ).run(\n row.id,\n row.apply_id,\n row.snapshot_id,\n row.relative_path,\n row.content,\n row.mode,\n row.created_at,\n );\n return row;\n}\n\nexport function listApplyRemovalBackups(input: {\n apply_id?: string;\n snapshot_id?: string;\n}): ApplyRemovalBackup[] {\n const db = getDb();\n if (input.snapshot_id) {\n const rows = db\n .prepare(\n `SELECT * FROM apply_removal_backups\n WHERE snapshot_id = ?\n ORDER BY relative_path ASC`,\n )\n .all(input.snapshot_id) as ApplyRemovalBackupRow[];\n return rows.map(rowToBackup);\n }\n if (input.apply_id) {\n const rows = db\n .prepare(\n `SELECT * FROM apply_removal_backups\n WHERE apply_id = ?\n ORDER BY relative_path ASC`,\n )\n .all(input.apply_id) as ApplyRemovalBackupRow[];\n return rows.map(rowToBackup);\n }\n return [];\n}\n","import { existsSync, readFileSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { Plugin, Resource, SerializedFile, SnapshotState } from \"../types.js\";\n\nexport function emptySnapshotState(): SnapshotState {\n return {\n plugins: [],\n resources: [],\n platform_files: {},\n };\n}\n\nexport function flattenSnapshotFiles(state: SnapshotState): SerializedFile[] {\n const files: SerializedFile[] = [];\n const seen = new Set<string>();\n const push = (path: string, content: string): void => {\n if (seen.has(path)) {\n return;\n }\n seen.add(path);\n files.push({ path, content });\n };\n for (const bucket of Object.values(state.platform_files)) {\n for (const [path, content] of Object.entries(bucket)) {\n push(path, content);\n }\n }\n if (state.harness_files) {\n for (const bucket of Object.values(state.harness_files)) {\n for (const [path, content] of Object.entries(bucket)) {\n push(path, content);\n }\n }\n }\n if (state.disk_files) {\n for (const [path, content] of Object.entries(state.disk_files)) {\n push(path, content);\n }\n }\n return files;\n}\n\n/** Live bytes to restore on revert. New captures store those in disk_files. */\nexport function flattenLiveRestoreFiles(state: SnapshotState): SerializedFile[] {\n const hasLiveCapture =\n (state.disk_files !== undefined && Object.keys(state.disk_files).length > 0)\n || (state.absent_paths?.length ?? 0) > 0;\n if (!hasLiveCapture) {\n return flattenSnapshotFiles(state);\n }\n const files: SerializedFile[] = [];\n for (const [path, content] of Object.entries(state.disk_files ?? {})) {\n files.push({ path, content });\n }\n return files;\n}\n\nexport function snapshotAbsentPaths(state: SnapshotState): string[] {\n return [...new Set(state.absent_paths ?? [])];\n}\n\nfunction readLiveFile(rootPath: string, relativePath: string): string | undefined {\n const fullPath = join(rootPath, relativePath);\n try {\n if (!existsSync(fullPath) || !statSync(fullPath).isFile()) {\n return undefined;\n }\n return readFileSync(fullPath, \"utf-8\");\n } catch {\n return undefined;\n }\n}\n\nexport function captureManagedSnapshotState(input: {\n rootPath: string;\n plugins?: Plugin[];\n resources?: Resource[];\n generated: ReadonlyArray<{\n platformId: string;\n files: ReadonlyArray<{ path: string; content?: string }>;\n }>;\n extraPaths?: readonly string[];\n}): SnapshotState {\n const platform_files: Record<string, Record<string, string>> = {};\n const disk_files: Record<string, string> = {};\n const absent: string[] = [];\n const seen = new Set<string>();\n\n for (const result of input.generated) {\n const bucket: Record<string, string> = { ...platform_files[result.platformId] };\n for (const file of result.files) {\n if (seen.has(file.path)) {\n continue;\n }\n seen.add(file.path);\n const live = readLiveFile(input.rootPath, file.path);\n if (live === undefined) {\n absent.push(file.path);\n } else {\n disk_files[file.path] = live;\n }\n const expected = file.content ?? live;\n if (expected !== undefined) {\n bucket[file.path] = expected;\n }\n }\n if (Object.keys(bucket).length > 0) {\n platform_files[result.platformId] = bucket;\n }\n }\n\n for (const extra of input.extraPaths ?? []) {\n if (!extra || seen.has(extra)) {\n continue;\n }\n seen.add(extra);\n const live = readLiveFile(input.rootPath, extra);\n if (live === undefined) {\n absent.push(extra);\n continue;\n }\n disk_files[extra] = live;\n }\n\n return {\n plugins: input.plugins ?? [],\n resources: input.resources ?? [],\n platform_files,\n ...(Object.keys(disk_files).length > 0 ? { disk_files } : {}),\n ...(absent.length > 0 ? { absent_paths: absent } : {}),\n };\n}\n","import { parse as parseToml } from \"smol-toml\";\nimport { mcpConfigContentsEquivalent } from \"./mcp-config-bridge.js\";\nimport { isMcpConfigManagedPath } from \"./profile-commit-resource.js\";\nimport { jsonContentsEquivalent } from \"../utils/json-equal.js\";\n\nfunction trailingNewlineEquivalent(left: string, right: string): boolean {\n const normalize = (value: string) => value.replace(/\\r\\n/g, \"\\n\").replace(/\\n+$/u, \"\");\n return normalize(left) === normalize(right);\n}\n\nfunction tomlContentsEquivalent(left: string, right: string): boolean {\n try {\n return jsonContentsEquivalent(\n JSON.stringify(parseToml(left)),\n JSON.stringify(parseToml(right)),\n );\n } catch {\n return false;\n }\n}\n\n/**\n * Drift and apply-skip equivalence: byte match first, then trailing-newline\n * only, then parsed JSON/TOML, then MCP semantic compare for harness\n * serialization noise (type: stdio, tools).\n */\nexport function fileContentsEquivalentForDrift(\n path: string,\n current: string,\n expected: string,\n): boolean {\n if (current === expected) {\n return true;\n }\n if (trailingNewlineEquivalent(current, expected)) {\n return true;\n }\n if (/\\.jsonc?$/i.test(path) && jsonContentsEquivalent(current, expected)) {\n return true;\n }\n if (/\\.toml$/i.test(path) && tomlContentsEquivalent(current, expected)) {\n return true;\n }\n // Copilot (and similar) emit extra fields (type/tools) that parse as different JSON\n // but map to the same mcp_server metadata.\n if (isMcpConfigManagedPath(path) && mcpConfigContentsEquivalent(current, expected)) {\n return true;\n }\n return false;\n}\n","function jsonValuesEqual(left: unknown, right: unknown): boolean {\n if (Object.is(left, right)) {\n return true;\n }\n if (left === null || right === null) {\n return left === right;\n }\n if (typeof left !== typeof right) {\n return false;\n }\n if (Array.isArray(left) || Array.isArray(right)) {\n if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) {\n return false;\n }\n return left.every((item, index) => jsonValuesEqual(item, right[index]));\n }\n if (typeof left === \"object\" && typeof right === \"object\") {\n const leftRecord = left as Record<string, unknown>;\n const rightRecord = right as Record<string, unknown>;\n const leftKeys = Object.keys(leftRecord).sort();\n const rightKeys = Object.keys(rightRecord).sort();\n if (leftKeys.length !== rightKeys.length) {\n return false;\n }\n return leftKeys.every((key, index) => {\n const otherKey = rightKeys[index];\n return (\n otherKey !== undefined\n && key === otherKey\n && jsonValuesEqual(leftRecord[key], rightRecord[key])\n );\n });\n }\n return false;\n}\n\n/** True when both strings parse as JSON and the values are deeply equal. */\nexport function jsonContentsEquivalent(left: string, right: string): boolean {\n try {\n return jsonValuesEqual(JSON.parse(left) as unknown, JSON.parse(right) as unknown);\n } catch {\n return false;\n }\n}\n","import { existsSync, readdirSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n listGlobalApplySnapshotInstalls,\n listGlobalApplySnapshots,\n} from \"../models/global-apply-snapshot.js\";\nimport { getPlatform } from \"../platforms/registry.js\";\nimport { isCursorHostManagedSkillsPath } from \"./cursor-host-managed-skills.js\";\nimport { isMergeableHostConfigPath } from \"./merged-host-config.js\";\nimport { isHarnessTapOwnedPath } from \"./safe-file-removal.js\";\n\nexport function collectOtherProfilesSnapshotTrackedFiles(\n incomingProfileName: string,\n): string[] {\n const tracked = new Set<string>();\n const seenProfiles = new Set<string>();\n\n for (const snapshot of listGlobalApplySnapshots()) {\n if (snapshot.profile_name === incomingProfileName) {\n continue;\n }\n if (seenProfiles.has(snapshot.profile_name)) {\n continue;\n }\n seenProfiles.add(snapshot.profile_name);\n for (const install of listGlobalApplySnapshotInstalls(snapshot.id)) {\n for (const filePath of install.files) {\n tracked.add(filePath);\n }\n }\n }\n\n return [...tracked];\n}\n\nconst SHARED_GLOBAL_SKILL_HUB = \".agents/skills\";\nconst SKILL_FILE_RE = /(?:^|\\/)skills\\/([^/]+)\\/SKILL\\.md$/i;\n\nexport function collectOrphanSkillFilesOnDisk(\n homeRoot: string,\n platformIds: string[],\n desiredFiles: ReadonlySet<string>,\n): string[] {\n const orphans = new Set<string>();\n\n for (const platformId of platformIds) {\n const platform = getPlatform(platformId);\n const configuredSkills = platform?.globalPaths.skills;\n if (!configuredSkills?.startsWith(\"~/\")) {\n continue;\n }\n\n if (isCursorHostManagedSkillsPath(configuredSkills)) {\n continue;\n }\n const relativeSkillsRoot = configuredSkills.slice(2).replace(/\\/$/, \"\");\n const skillsDir = join(homeRoot, relativeSkillsRoot);\n let entries: string[];\n try {\n entries = readdirSync(skillsDir);\n } catch {\n continue;\n }\n\n for (const entry of entries) {\n if (entry.startsWith(\".\")) {\n continue;\n }\n const entryPath = join(skillsDir, entry);\n try {\n if (!statSync(entryPath).isDirectory()) {\n continue;\n }\n } catch {\n continue;\n }\n\n const skillRelative = `${relativeSkillsRoot}/${entry}/SKILL.md`;\n if (desiredFiles.has(skillRelative)) {\n continue;\n }\n if (existsSync(join(homeRoot, skillRelative))) {\n orphans.add(skillRelative);\n }\n }\n }\n\n return [...orphans];\n}\n\n/**\n * Skill-package installs keep a canonical copy under `~/.agents/skills/{name}/`\n * and fan out to harness-specific skill dirs. Profile apply historically tracked\n * only the harness paths, so switching away left the shared hub active for\n * tools that still read it (Cursor, Codex, ...). Map removed managed skill files\n * onto the hub path when the incoming profile does not keep that skill.\n */\nexport function expandStaleSkillHubMirrors(\n staleFiles: readonly string[],\n desiredFiles: ReadonlySet<string>,\n): string[] {\n const expanded = new Set(staleFiles);\n const desiredSkillNames = new Set<string>();\n for (const desiredPath of desiredFiles) {\n const desiredMatch = desiredPath.match(SKILL_FILE_RE);\n const skillName = desiredMatch?.[1];\n if (skillName) {\n desiredSkillNames.add(skillName);\n }\n }\n\n for (const filePath of staleFiles) {\n const match = filePath.match(SKILL_FILE_RE);\n const skillName = match?.[1];\n if (!skillName || desiredSkillNames.has(skillName)) {\n continue;\n }\n expanded.add(`${SHARED_GLOBAL_SKILL_HUB}/${skillName}/SKILL.md`);\n }\n\n return [...expanded];\n}\n\nconst DEDICATED_MCP_CONFIG_RE =\n /(^|\\/)(\\.?mcp\\.json|mcp[-_]config\\.json)$/i;\n\nfunction isDedicatedMcpConfigPath(path: string): boolean {\n return DEDICATED_MCP_CONFIG_RE.test(path.replace(/^~\\//, \"\"));\n}\n\n/**\n * Global dedicated MCP config paths for the harnesses in this apply\n * (e.g. `.cursor/mcp.json`, `.copilot/mcp-config.json`). Excludes aggregate\n * settings files that embed MCP among other keys (config.toml, settings.json).\n */\nexport function collectGlobalDedicatedMcpConfigPaths(\n platformIds: readonly string[],\n): string[] {\n const paths = new Set<string>();\n for (const platformId of platformIds) {\n const platform = getPlatform(platformId);\n if (!platform) {\n continue;\n }\n for (const candidate of [\n platform.globalPaths.mcp,\n platform.globalPaths.settings,\n ]) {\n if (!candidate?.startsWith(\"~/\")) {\n continue;\n }\n const relative = candidate.slice(2).replace(/\\/$/, \"\");\n if (!isDedicatedMcpConfigPath(relative)) {\n continue;\n }\n paths.add(relative);\n }\n }\n return [...paths];\n}\n\n/**\n * MCP resources are often path-bound to one harness file (e.g. `~/.cursor/mcp.json`)\n * and intentionally not cross-written. Switching away still needs to clear other\n * harness MCP configs that may hold the same servers from earlier installs.\n */\nfunction isOwnedOrUnknown(homeRoot: string, relativePath: string): boolean {\n try {\n return isHarnessTapOwnedPath(homeRoot, relativePath);\n } catch {\n return false;\n }\n}\n\nexport function expandStaleMcpConfigMirrors(\n staleFiles: readonly string[],\n desiredFiles: ReadonlySet<string>,\n harnesses: readonly string[],\n homeRoot = \"\",\n): string[] {\n const expanded = new Set(staleFiles);\n const staleHasMcp = staleFiles.some((filePath) =>\n isDedicatedMcpConfigPath(filePath),\n );\n if (!staleHasMcp) {\n return [...expanded];\n }\n\n for (const mcpPath of collectGlobalDedicatedMcpConfigPaths(harnesses)) {\n if (desiredFiles.has(mcpPath) || expanded.has(mcpPath)) {\n continue;\n }\n if (homeRoot && !isOwnedOrUnknown(homeRoot, mcpPath)) {\n continue;\n }\n if (!homeRoot) {\n continue;\n }\n expanded.add(mcpPath);\n }\n return [...expanded];\n}\n\nexport function planStaleMergeableHostConfigFiles(\n homeRoot: string,\n desiredFiles: readonly string[],\n previousTrackedFiles: readonly string[],\n harnesses: readonly string[] = [],\n): string[] {\n const desired = new Set(desiredFiles);\n const mergeFiles = new Set(\n previousTrackedFiles.filter(\n (filePath) =>\n !desired.has(filePath)\n && isMergeableHostConfigPath(filePath)\n && !isCursorHostManagedSkillsPath(filePath),\n ),\n );\n const leavingMcp = [...mergeFiles].some((filePath) =>\n isDedicatedMcpConfigPath(filePath),\n );\n if (leavingMcp && homeRoot) {\n for (const mcpPath of collectGlobalDedicatedMcpConfigPaths(harnesses)) {\n if (desired.has(mcpPath) || mergeFiles.has(mcpPath)) {\n continue;\n }\n if (!isOwnedOrUnknown(homeRoot, mcpPath)) {\n continue;\n }\n if (isMergeableHostConfigPath(mcpPath)) {\n mergeFiles.add(mcpPath);\n }\n }\n }\n return [...mergeFiles];\n}\n\n/**\n * Plan whole-file removals for profile switch/re-apply.\n * Shared configs and instruction files are excluded (key/block rewrite\n * happens separately). Skill removals also drop the shared hub mirror.\n * Dedicated MCP configs on other harnesses are added only when HarnessTap\n * has an ownership record for that path.\n */\nexport function planStaleGlobalProfileFiles(\n homeRoot: string,\n desiredFiles: readonly string[],\n previousTrackedFiles: readonly string[],\n harnesses: string[],\n): string[] {\n const desired = new Set(desiredFiles);\n const stale = previousTrackedFiles.filter(\n (filePath) =>\n !desired.has(filePath)\n && !isMergeableHostConfigPath(filePath)\n && !isCursorHostManagedSkillsPath(filePath),\n );\n return expandStaleMcpConfigMirrors(\n expandStaleSkillHubMirrors(stale, desired),\n desired,\n harnesses,\n homeRoot,\n );\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { parse as parseToml } from \"smol-toml\";\nimport {\n applyJsonObjectUpdatePreservingFormat,\n applyTomlObjectUpdatePreservingFormat,\n} from \"./format-preserving-config.js\";\nimport { getResource } from \"../models/resource.js\";\nimport { listMaterializationsForRootPath } from \"../models/resource-materialization.js\";\nimport { isPreexistingPath } from \"../models/preexisting-path.js\";\nimport type { Resource } from \"../types.js\";\nimport { isMergeableHostConfigPath } from \"./merged-host-config.js\";\nimport { backupAndRewriteFile } from \"./safe-file-removal.js\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && Array.isArray(value) === false;\n}\n\nfunction pluginRegistryKeys(resource: Pick<Resource, \"name\" | \"namespace\" | \"origin_ref\">): string[] {\n const keys = new Set<string>();\n if (resource.origin_ref) {\n keys.add(resource.origin_ref);\n }\n if (resource.namespace) {\n keys.add(`${resource.name}@${resource.namespace}`);\n }\n return [...keys];\n}\n\nfunction matchingRecordKeys(\n record: Record<string, unknown>,\n resource: Pick<Resource, \"name\" | \"namespace\" | \"origin_ref\">,\n): string[] {\n const wanted = new Set(pluginRegistryKeys(resource));\n return Object.keys(record).filter((key) => wanted.has(key));\n}\n\nfunction isInstalledPluginsRegistry(obj: Record<string, unknown>): boolean {\n if (!obj.plugins || typeof obj.plugins !== \"object\" || Array.isArray(obj.plugins)) {\n return false;\n }\n const values = Object.values(obj.plugins as Record<string, unknown>);\n return values.length === 0 || values.every((value) => Array.isArray(value));\n}\n\nconst MCP_WRAPPERS = [\"mcpServers\", \"mcp_servers\", \"mcp\"] as const;\n\nfunction stripMcpServer(\n obj: Record<string, unknown>,\n resource: Pick<Resource, \"name\">,\n): Record<string, unknown> | null {\n for (const wrapper of MCP_WRAPPERS) {\n const raw = obj[wrapper];\n if (!isRecord(raw) || !(resource.name in raw)) {\n continue;\n }\n const servers = { ...raw };\n delete servers[resource.name];\n const next = { ...obj };\n if (Object.keys(servers).length === 0) {\n delete next[wrapper];\n } else {\n next[wrapper] = servers;\n }\n return next;\n }\n return null;\n}\n\nfunction stripJsonObject(\n obj: Record<string, unknown>,\n resource: Resource,\n): Record<string, unknown> | null {\n const mcpNext = stripMcpServer(obj, resource);\n if (mcpNext) {\n return mcpNext;\n }\n\n if (isInstalledPluginsRegistry(obj)) {\n const plugins = { ...(obj.plugins as Record<string, unknown>) };\n const keys = matchingRecordKeys(plugins, resource);\n if (keys.length === 0) {\n return null;\n }\n for (const key of keys) {\n delete plugins[key];\n }\n return { ...obj, plugins };\n }\n\n if (isRecord(obj.enabledPlugins)) {\n const enabled = { ...obj.enabledPlugins };\n const keys = matchingRecordKeys(enabled, resource);\n if (keys.length > 0) {\n for (const key of keys) {\n delete enabled[key];\n }\n const next = { ...obj };\n if (Object.keys(enabled).length === 0) {\n delete next.enabledPlugins;\n } else {\n next.enabledPlugins = enabled;\n }\n return next;\n }\n }\n\n if (resource.type === \"env_var\" && isRecord(obj.env) && resource.name in obj.env) {\n const env = { ...obj.env };\n delete env[resource.name];\n const next = { ...obj };\n if (Object.keys(env).length === 0) {\n delete next.env;\n } else {\n next.env = env;\n }\n return next;\n }\n\n if (resource.name in obj && (resource.type === \"mcp_server\" || resource.type === \"plugin\")) {\n const next = { ...obj };\n delete next[resource.name];\n return next;\n }\n\n return null;\n}\n\nexport function tryEditAggregateContent(\n content: string,\n resource: Resource,\n): { ok: true; content: string; emptied: boolean } | { ok: false; reason: string } {\n const trimmed = content.trimStart();\n if (trimmed.startsWith(\"{\") || trimmed.startsWith(\"[\")) {\n try {\n const parsed: unknown = JSON.parse(content);\n if (!isRecord(parsed)) {\n return { ok: false, reason: \"Shared file section cannot be identified\" };\n }\n const next = stripJsonObject(parsed, resource);\n if (!next) {\n return { ok: false, reason: \"Shared file section cannot be identified\" };\n }\n return {\n ok: true,\n content: applyJsonObjectUpdatePreservingFormat(content, next),\n emptied: Object.keys(next).length === 0,\n };\n } catch {\n return { ok: false, reason: \"Shared file section cannot be identified\" };\n }\n }\n\n try {\n const parsed: unknown = parseToml(content);\n if (!isRecord(parsed)) {\n return { ok: false, reason: \"Shared file section cannot be identified\" };\n }\n const next = stripJsonObject(parsed, resource);\n if (!next) {\n return { ok: false, reason: \"Shared file section cannot be identified\" };\n }\n return {\n ok: true,\n content: applyTomlObjectUpdatePreservingFormat(content, next),\n emptied: Object.keys(next).length === 0,\n };\n } catch {\n return { ok: false, reason: \"Shared file section cannot be identified\" };\n }\n}\n\nexport interface HostConfigRewriteResult {\n rewritten: string[];\n removed: string[];\n skipped: string[];\n}\n\n/**\n * Remove HarnessTap-owned keys/servers from shared config files. Instruction\n * files and preexisting configs are left on disk. The file is deleted only when\n * it is empty, HarnessTap created it, and no keys remain.\n */\nexport function rewriteStaleMergeableHostConfigs(\n rootPath: string,\n relativePaths: readonly string[],\n options: {\n applyId: string;\n snapshotId?: string | null;\n dryRun?: boolean;\n },\n): HostConfigRewriteResult {\n const rewritten: string[] = [];\n const removed: string[] = [];\n const skipped: string[] = [];\n\n for (const relativePath of [...new Set(relativePaths)]) {\n if (isMergeableHostConfigPath(relativePath) && /\\.(md|mdc)$/i.test(relativePath)) {\n skipped.push(relativePath);\n continue;\n }\n const fullPath = resolve(rootPath, relativePath);\n if (!existsSync(fullPath)) {\n skipped.push(relativePath);\n continue;\n }\n if (isPreexistingPath(rootPath, relativePath)) {\n skipped.push(relativePath);\n continue;\n }\n let content: string;\n try {\n content = readFileSync(fullPath, \"utf-8\");\n } catch {\n skipped.push(relativePath);\n continue;\n }\n\n const rows = listMaterializationsForRootPath(rootPath, relativePath);\n let next = content;\n let emptied = false;\n let changed = false;\n for (const row of rows) {\n const resource = getResource(row.resource_id);\n if (!resource) {\n continue;\n }\n const edit = tryEditAggregateContent(next, resource);\n if (!edit.ok) {\n continue;\n }\n next = edit.content;\n emptied = edit.emptied;\n changed = true;\n }\n\n if (!changed) {\n skipped.push(relativePath);\n continue;\n }\n\n const preexisting = isPreexistingPath(rootPath, relativePath);\n if (emptied && !preexisting) {\n if (!options.dryRun) {\n backupAndRewriteFile({\n rootPath,\n relativePath,\n nextContent: null,\n applyId: options.applyId,\n snapshotId: options.snapshotId,\n });\n }\n removed.push(relativePath);\n continue;\n }\n\n if (!options.dryRun) {\n backupAndRewriteFile({\n rootPath,\n relativePath,\n nextContent: next,\n applyId: options.applyId,\n snapshotId: options.snapshotId,\n });\n }\n rewritten.push(relativePath);\n }\n\n return { rewritten, removed, skipped };\n}\n","import {\n getPlugin,\n isSamePublishedPluginIdentity,\n} from \"../models/plugin-model.js\";\nimport type { Plugin } from \"../types.js\";\nimport type { ResolvedRemotePluginSelector } from \"./plugin-selector.js\";\n\nexport function resolveInstallLocalName(\n parsed: ResolvedRemotePluginSelector,\n as?: string,\n): string {\n return as ?? parsed.plugin_slug;\n}\n\nexport function findInstallNameConflict(\n parsed: ResolvedRemotePluginSelector,\n opts: { as?: string },\n): Plugin | undefined {\n const localName = resolveInstallLocalName(parsed, opts.as);\n const existing = getPlugin(localName);\n if (!existing || opts.as) {\n return undefined;\n }\n if (isSamePublishedPluginIdentity(existing, parsed)) {\n return undefined;\n }\n return existing;\n}\n\nexport function formatInstallNameConflictMessage(\n localName: string,\n existing: Plugin,\n): string {\n const publishedLabel = existing.org_slug && existing.catalog_slug\n ? `${existing.org_slug}/${existing.catalog_slug}/${existing.name}`\n : existing.name;\n return `Plugin name already exists: ${localName} (published as ${publishedLabel}). Use --as to install under a different name.`;\n}\n\nexport function assertInstallPluginNameAvailable(\n parsed: ResolvedRemotePluginSelector,\n opts: { as?: string },\n): void {\n const conflict = findInstallNameConflict(parsed, opts);\n if (!conflict) {\n return;\n }\n throw new Error(\n formatInstallNameConflictMessage(resolveInstallLocalName(parsed, opts.as), conflict),\n );\n}\n","import { downloadCatalogPackage, fetchCatalogPlugin } from \"./catalog-client.js\";\nimport {\n CatalogDependencyVersionError,\n CatalogPackageNotFoundError,\n} from \"./catalog-package-errors.js\";\nimport { importApPackageFiles } from \"./agent-plugins/import.js\";\nimport {\n findPluginForCatalogInstall,\n getPluginById,\n getPluginByName,\n listPluginVersions,\n stampPluginOrigin,\n updatePluginPublishedIdentity,\n} from \"../models/plugin-model.js\";\nimport {\n formatCanonicalPublishedSelectorWithVersion,\n formatPublishedSelectorWithVersion,\n parsePluginSelector,\n resolveRemotePluginSelector,\n type ResolvedRemotePluginSelector,\n} from \"./plugin-selector.js\";\nimport { assertInstallPluginNameAvailable } from \"./plugin-install-conflicts.js\";\nimport { trackPluginInstalled } from \"../telemetry/index.js\";\nimport { listDependencies } from \"./plugin-dependency.js\";\nimport {\n parseVersionConstraint,\n satisfiesConstraint,\n} from \"./plugin-constraints.js\";\nimport type { Plugin } from \"../types.js\";\n\nexport interface InstallPluginFromCatalogOptions {\n as?: string;\n account?: string;\n baseUrl?: string;\n onFetched?: (sourceLabel: string) => void;\n}\n\nexport interface InstallPluginFromCatalogResult {\n pluginId: string;\n pluginName: string;\n version: string;\n sourceLabel: string;\n}\n\nfunction catalogIdentity(\n plugin: Plugin,\n): { org: string; catalog: string } | undefined {\n if (plugin.org_slug && plugin.catalog_slug) {\n return { org: plugin.org_slug, catalog: plugin.catalog_slug };\n }\n return undefined;\n}\n\nfunction findLocalSatisfyingPlugin(\n name: string,\n constraint: string,\n): Plugin | undefined {\n const trimmed = constraint.trim();\n const versions = listPluginVersions(name);\n if (versions.length === 0) {\n return undefined;\n }\n if (!trimmed || trimmed === \"*\" || trimmed === \"latest\") {\n return getPluginByName(name);\n }\n const matching = versions.find((version) =>\n satisfiesConstraint(trimmed, version),\n );\n return matching ? getPluginByName(name, matching) : undefined;\n}\n\nfunction exactPinnedVersion(constraint: string): string | undefined {\n const trimmed = constraint.trim();\n if (!trimmed || trimmed === \"*\" || trimmed === \"latest\") {\n return undefined;\n }\n try {\n const parsed = parseVersionConstraint(trimmed);\n return parsed.kind === \"exact\" ? parsed.version : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction catalogTargetForDependency(\n parent: Plugin,\n depName: string,\n depRef: string,\n sourceKind: string,\n): { org: string; catalog: string; slug: string } | undefined {\n if (sourceKind === \"catalog\") {\n try {\n const parsed = parsePluginSelector(depRef);\n if (parsed.scope === \"published\") {\n return { org: parsed.org, catalog: parsed.catalog, slug: parsed.name };\n }\n } catch {\n // Fall through to parent catalog identity.\n }\n }\n if (sourceKind === \"marketplace\" || sourceKind === \"git\") {\n return undefined;\n }\n if (depRef.startsWith(\"./\") || depRef.startsWith(\"../\")) {\n return undefined;\n }\n const parentCatalog = catalogIdentity(parent);\n if (!parentCatalog) {\n return undefined;\n }\n return { ...parentCatalog, slug: depName };\n}\n\nasync function resolveCatalogFetchVersion(input: {\n org: string;\n catalog: string;\n slug: string;\n constraint: string;\n account?: string;\n baseUrl?: string;\n}): Promise<{ version: string; available: string[] }> {\n const pinned = exactPinnedVersion(input.constraint);\n let available: string[] = [];\n let latest: string | null = null;\n try {\n const listed = await fetchCatalogPlugin(\n {\n orgSlug: input.org,\n catalogSlug: input.catalog,\n slug: input.slug,\n },\n { account: input.account, baseUrl: input.baseUrl },\n );\n latest = listed.latestVersion;\n if (listed.latestVersion) {\n available = [listed.latestVersion];\n }\n } catch {\n // Listing can fail independently of a later package download.\n }\n\n if (pinned) {\n return { version: pinned, available };\n }\n if (latest && (\n !input.constraint.trim()\n || input.constraint.trim() === \"*\"\n || input.constraint.trim() === \"latest\"\n || satisfiesConstraint(input.constraint, latest)\n )) {\n return { version: latest, available };\n }\n throw new CatalogDependencyVersionError({\n pluginName: input.slug,\n version: input.constraint.trim() || \"*\",\n catalog: `${input.org}/${input.catalog}`,\n available,\n requirer: \"\",\n });\n}\n\n/**\n * Fetch missing library dependencies from the same catalog the parent\n * package came from (including `source: \"local\"` edges in catalog packages).\n * Recurses through transitive deps. Marketplace/git/path refs are left to\n * their existing apply paths.\n */\nexport async function ensureMissingCatalogDependencies(\n pluginIds: string[],\n opts: InstallPluginFromCatalogOptions = {},\n seen: Set<string> = new Set(),\n): Promise<InstallPluginFromCatalogResult[]> {\n const pulled: InstallPluginFromCatalogResult[] = [];\n const queue = [...pluginIds];\n\n while (queue.length > 0) {\n const pluginId = queue.shift();\n if (!pluginId || seen.has(pluginId)) {\n continue;\n }\n seen.add(pluginId);\n const plugin = getPluginById(pluginId);\n if (!plugin) {\n continue;\n }\n\n for (const dependency of listDependencies(pluginId)) {\n const local = findLocalSatisfyingPlugin(\n dependency.name,\n dependency.version_constraint,\n );\n if (local) {\n queue.push(local.id);\n continue;\n }\n\n const target = catalogTargetForDependency(\n plugin,\n dependency.name,\n dependency.ref,\n dependency.source_kind,\n );\n if (!target) {\n continue;\n }\n\n const requirer = `${plugin.name}@${plugin.version}`;\n let fetchVersion: string;\n let available: string[] = [];\n try {\n const resolved = await resolveCatalogFetchVersion({\n org: target.org,\n catalog: target.catalog,\n slug: target.slug,\n constraint: dependency.version_constraint,\n account: opts.account,\n baseUrl: opts.baseUrl,\n });\n fetchVersion = resolved.version;\n available = resolved.available;\n } catch (error) {\n if (error instanceof CatalogDependencyVersionError) {\n throw new CatalogDependencyVersionError({\n pluginName: target.slug,\n version: error.version,\n catalog: `${target.org}/${target.catalog}`,\n available: error.available,\n requirer,\n });\n }\n throw error;\n }\n\n const fetchKey = formatCanonicalPublishedSelectorWithVersion({\n org: target.org,\n catalog: target.catalog,\n name: target.slug,\n version: fetchVersion,\n });\n if (seen.has(`fetch:${fetchKey}`)) {\n continue;\n }\n seen.add(`fetch:${fetchKey}`);\n\n try {\n const installed = await installPluginFromCatalog(\n resolveRemotePluginSelector(fetchKey, {}),\n opts,\n seen,\n );\n opts.onFetched?.(installed.sourceLabel);\n pulled.push(installed);\n queue.push(installed.pluginId);\n } catch (error) {\n if (!(error instanceof CatalogPackageNotFoundError)) {\n throw error;\n }\n if (available.length > 0) {\n throw new CatalogDependencyVersionError({\n pluginName: target.slug,\n version: fetchVersion,\n catalog: `${target.org}/${target.catalog}`,\n available,\n requirer,\n });\n }\n try {\n const listed = await fetchCatalogPlugin(\n {\n orgSlug: target.org,\n catalogSlug: target.catalog,\n slug: target.slug,\n },\n { account: opts.account, baseUrl: opts.baseUrl },\n );\n throw new CatalogDependencyVersionError({\n pluginName: target.slug,\n version: fetchVersion,\n catalog: `${target.org}/${target.catalog}`,\n available: listed.latestVersion ? [listed.latestVersion] : [],\n requirer,\n });\n } catch (listedError) {\n if (listedError instanceof CatalogDependencyVersionError) {\n throw listedError;\n }\n // Plugin is not in that catalog: leave it for local-inventory errors.\n }\n }\n }\n }\n\n return pulled;\n}\n\nexport async function installPluginFromCatalog(\n parsed: ResolvedRemotePluginSelector,\n opts: InstallPluginFromCatalogOptions = {},\n seen: Set<string> = new Set(),\n): Promise<InstallPluginFromCatalogResult> {\n assertInstallPluginNameAvailable(parsed, opts);\n\n const downloaded = await downloadCatalogPackage({\n orgSlug: parsed.org_slug,\n catalogSlug: parsed.catalog_slug,\n pluginSlug: parsed.plugin_slug,\n version: parsed.version,\n account: opts.account,\n baseUrl: opts.baseUrl,\n });\n\n const sourceLabel = formatPublishedSelectorWithVersion({\n org: parsed.org_slug,\n catalog: parsed.catalog_slug,\n name: parsed.plugin_slug,\n version: downloaded.version,\n });\n\n const locator = `${parsed.org_slug}/${parsed.catalog_slug}/${parsed.plugin_slug}`;\n\n // Reuse this catalog plugin version. Do not treat a sibling package that\n // happens to share org/catalog/version (e.g. two 1.0.0 plugins) as a hit.\n const existing = findPluginForCatalogInstall({\n org: parsed.org_slug,\n catalog: parsed.catalog_slug,\n pluginSlug: parsed.plugin_slug,\n version: downloaded.version,\n });\n if (existing && !opts.as) {\n stampPluginOrigin(existing.id, { locator });\n await ensureMissingCatalogDependencies([existing.id], opts, seen);\n return {\n pluginId: existing.id,\n pluginName: existing.name,\n version: downloaded.version,\n sourceLabel,\n };\n }\n\n const imported = importApPackageFiles(downloaded.files, {\n as: opts.as,\n origin: \"catalog\",\n });\n updatePluginPublishedIdentity(imported.id, {\n org_slug: parsed.org_slug,\n catalog_slug: parsed.catalog_slug,\n version: downloaded.version,\n });\n stampPluginOrigin(imported.id, { locator });\n trackPluginInstalled({\n pluginSlug: parsed.plugin_slug,\n source: \"catalog\",\n });\n\n await ensureMissingCatalogDependencies([imported.id], opts, seen);\n\n return {\n pluginId: imported.id,\n pluginName: imported.name,\n version: downloaded.version,\n sourceLabel,\n };\n}\n","import { join } from \"node:path\";\nimport { getSourcesToRefresh, markSourceRefreshed } from \"../refresh-cache.js\";\nimport {\n claudePluginsDir,\n loadInstalled,\n parsePluginRef,\n readJsonFile,\n type InstalledPluginsFile,\n} from \"../claude-installed.js\";\nimport {\n findInstalledRefForCatalogPin,\n marketplaceIsConfigured,\n resolveCatalogPluginMarketplaceBootstrap,\n resolveClaudeInstallRefCandidates,\n} from \"../claude-plugin-ref.js\";\nimport {\n defaultRunCommand,\n type CommandResult,\n type RunCommand,\n} from \"../run-command.js\";\nimport type {\n PluginCheckOptions,\n PluginCheckResult,\n PluginContext,\n PluginInstall,\n PluginInstallOptions,\n PluginInstallResult,\n PluginProvider,\n PluginScope,\n PluginUpdateOptions,\n PluginUpdateResult,\n} from \"../types.js\";\n\ninterface MarketplacePluginEntry {\n name: string;\n version?: string;\n source?: string | { sha?: string; ref?: string; url?: string };\n}\n\ninterface MarketplaceFile {\n name: string;\n plugins?: MarketplacePluginEntry[];\n}\n\nexport interface ClaudeCodeProviderDeps {\n runCommand?: RunCommand;\n claudeBinary?: string;\n}\n\nfunction marketplaceSourceKey(marketplace: string): string {\n return `claude:marketplace:${marketplace}`;\n}\n\nfunction resolveLatestFromMarketplace(\n homeRoot: string,\n marketplace: string,\n pluginName: string,\n): { latestVersion?: string; latestSha?: string } {\n const marketplacePath = join(\n claudePluginsDir(homeRoot),\n \"marketplaces\",\n marketplace,\n \".claude-plugin\",\n \"marketplace.json\",\n );\n const file = readJsonFile<MarketplaceFile>(marketplacePath);\n const entry = file?.plugins?.find((p) => p.name === pluginName);\n if (!entry) return {};\n if (entry.version) return { latestVersion: entry.version };\n if (typeof entry.source === \"object\" && entry.source.sha) {\n return { latestVersion: entry.source.sha.slice(0, 12), latestSha: entry.source.sha };\n }\n if (typeof entry.source === \"object\" && entry.source.ref) {\n return { latestVersion: entry.source.ref };\n }\n return {};\n}\n\nexport class ClaudeCodePluginProvider implements PluginProvider {\n readonly platformId = \"claude-code\";\n readonly capabilities = {\n inventory: true,\n check: true,\n update: true,\n install: true,\n updateMethod: \"native-cli\" as const,\n installMethod: \"native-cli\" as const,\n };\n\n constructor(private readonly deps: ClaudeCodeProviderDeps = {}) {}\n\n private runClaude(args: string[], ctx?: PluginContext): CommandResult {\n const run = this.deps.runCommand ?? defaultRunCommand;\n const binary = this.deps.claudeBinary ?? \"claude\";\n return run(binary, [\"plugin\", ...args], {\n cwd: ctx?.projectRoot,\n });\n }\n\n private ensureMarketplace(ctx: PluginContext, marketplace: string, repo: string): void {\n if (marketplaceIsConfigured(ctx.homeRoot, marketplace)) {\n return;\n }\n this.runClaude([\"marketplace\", \"add\", repo], ctx);\n }\n\n private bootstrapMarketplacesForRef(ctx: PluginContext, catalogRef: string): void {\n for (const marketplace of resolveCatalogPluginMarketplaceBootstrap(catalogRef) ?? []) {\n this.ensureMarketplace(ctx, marketplace.name, marketplace.repo);\n }\n }\n\n async list(ctx: PluginContext): Promise<PluginInstall[]> {\n return loadInstalled(ctx.homeRoot);\n }\n\n async check(\n ctx: PluginContext,\n opts: PluginCheckOptions,\n ): Promise<PluginCheckResult[]> {\n const installs = loadInstalled(ctx.homeRoot);\n const marketplaces = new Set(\n installs.map((i) => parsePluginRef(i.ref).marketplace).filter(Boolean),\n );\n\n const toRefresh = getSourcesToRefresh(\n [...marketplaces].map(marketplaceSourceKey),\n opts.refreshCache,\n opts.maxAgeHours,\n opts.forceRefresh,\n );\n\n for (const key of toRefresh) {\n const marketplace = key.replace(\"claude:marketplace:\", \"\");\n const result = this.runClaude([\"marketplace\", \"update\", marketplace], ctx);\n if (result.exitCode === 0) {\n Object.assign(\n opts.refreshCache,\n markSourceRefreshed(opts.refreshCache, key),\n );\n }\n }\n\n const results: PluginCheckResult[] = [];\n for (const install of installs) {\n if (opts.scopes && !opts.scopes.includes(install.scope)) continue;\n const { name, marketplace } = parsePluginRef(install.ref);\n const latest = resolveLatestFromMarketplace(\n ctx.homeRoot,\n marketplace,\n name,\n );\n let status: PluginCheckResult[\"status\"] = \"unknown\";\n if (latest.latestSha) {\n const installed = readJsonFile<InstalledPluginsFile>(\n join(claudePluginsDir(ctx.homeRoot), \"installed_plugins.json\"),\n );\n const sha =\n installed?.plugins[install.ref]?.[0]?.gitCommitSha?.slice(0, 12);\n status =\n sha && latest.latestSha.startsWith(sha) ? \"current\" : \"outdated\";\n } else if (latest.latestVersion) {\n status =\n install.version === latest.latestVersion ? \"current\" : \"outdated\";\n }\n results.push({\n ...install,\n status,\n latestVersion: latest.latestVersion ?? latest.latestSha,\n latestSource: marketplaceSourceKey(marketplace),\n refreshSkipped: !toRefresh.includes(marketplaceSourceKey(marketplace)),\n });\n }\n return results;\n }\n\n async update(\n ctx: PluginContext,\n opts: PluginUpdateOptions,\n ): Promise<PluginUpdateResult[]> {\n const targets = opts.ref\n ? loadInstalled(ctx.homeRoot).filter((i) => i.ref === opts.ref)\n : loadInstalled(ctx.homeRoot);\n\n const results: PluginUpdateResult[] = [];\n for (const install of targets) {\n if (opts.scopes && !opts.scopes.includes(install.scope)) continue;\n if (install.scope === \"managed\" && !opts.yes) {\n results.push({\n ref: install.ref,\n platformId: this.platformId,\n scope: install.scope,\n status: \"skipped\",\n message: \"Managed scope updates require --yes\",\n });\n continue;\n }\n const args = [\"update\", install.ref, \"--scope\", install.scope];\n const result = this.runClaude(args, ctx);\n if (result.exitCode === 0) {\n results.push({\n ref: install.ref,\n platformId: this.platformId,\n scope: install.scope,\n status: \"updated\",\n previousVersion: install.version,\n message: result.stdout.trim() || \"Updated via claude plugin\",\n });\n } else {\n results.push({\n ref: install.ref,\n platformId: this.platformId,\n scope: install.scope,\n status: \"failed\",\n previousVersion: install.version,\n message: result.stderr.trim() || result.stdout.trim() || \"Update failed\",\n });\n }\n }\n return results;\n }\n\n async install(\n ctx: PluginContext,\n opts: PluginInstallOptions,\n ): Promise<PluginInstallResult> {\n const scope: PluginScope = opts.scope ?? \"user\";\n const candidates = resolveClaudeInstallRefCandidates(opts.ref, ctx.homeRoot);\n\n const installedRef = findInstalledRefForCatalogPin(opts.ref, ctx.homeRoot, scope);\n if (installedRef) {\n const install = loadInstalled(ctx.homeRoot).find(\n (row) => row.ref === installedRef && row.scope === scope,\n );\n return {\n ref: opts.ref,\n platformId: this.platformId,\n scope,\n status: \"already_installed\",\n install,\n message:\n installedRef === opts.ref\n ? `Already installed (${scope})`\n : `Already installed as ${installedRef} (${scope})`,\n };\n }\n\n this.bootstrapMarketplacesForRef(ctx, opts.ref);\n\n let lastMessage = \"claude plugin install failed\";\n for (const candidate of candidates) {\n const { marketplace } = parsePluginRef(candidate);\n if (marketplace) {\n this.runClaude([\"marketplace\", \"update\", marketplace], ctx);\n }\n\n const args = [\"install\", candidate, \"--scope\", scope];\n const result = this.runClaude(args, ctx);\n if (result.exitCode !== 0) {\n lastMessage = result.stderr.trim() || result.stdout.trim() || lastMessage;\n continue;\n }\n\n const install = loadInstalled(ctx.homeRoot).find(\n (row) => row.ref === candidate && row.scope === scope,\n );\n if (!install) {\n return {\n ref: opts.ref,\n platformId: this.platformId,\n scope,\n status: \"failed\",\n message:\n \"Install command succeeded but plugin was not registered in installed_plugins.json\",\n };\n }\n\n return {\n ref: opts.ref,\n platformId: this.platformId,\n scope,\n status: \"installed\",\n install,\n message:\n candidate === opts.ref\n ? result.stdout.trim() || \"Installed via claude plugin\"\n : `Installed as ${candidate}`,\n };\n }\n\n return {\n ref: opts.ref,\n platformId: this.platformId,\n scope,\n status: \"failed\",\n message: lastMessage,\n };\n }\n}\n","import { parsePluginRef } from \"../claude-installed.js\";\nimport {\n loadInstalledCopilotPlugins,\n} from \"../copilot-installed.js\";\nimport { defaultRunCommand, type CommandResult, type RunCommand } from \"../run-command.js\";\nimport type {\n PluginCheckOptions,\n PluginCheckResult,\n PluginContext,\n PluginInstall,\n PluginInstallOptions,\n PluginInstallResult,\n PluginProvider,\n PluginScope,\n PluginUpdateOptions,\n PluginUpdateResult,\n} from \"../types.js\";\n\nexport interface CopilotProviderDeps {\n runCommand?: RunCommand;\n copilotBinary?: string;\n}\n\nfunction findInstall(\n installs: PluginInstall[],\n ref: string,\n): PluginInstall | undefined {\n return installs.find(\n (install) => install.ref === ref || install.name === ref,\n );\n}\n\nexport class CopilotPluginProvider implements PluginProvider {\n readonly platformId = \"copilot-cli\";\n readonly capabilities = {\n inventory: true,\n check: true,\n update: true,\n install: true,\n updateMethod: \"native-cli\" as const,\n installMethod: \"native-cli\" as const,\n };\n\n constructor(private readonly deps: CopilotProviderDeps = {}) {}\n\n private runCopilot(args: string[], ctx?: PluginContext): CommandResult {\n const run = this.deps.runCommand ?? defaultRunCommand;\n const binary = this.deps.copilotBinary ?? \"copilot\";\n return run(binary, [\"plugin\", ...args], {\n cwd: ctx?.projectRoot,\n });\n }\n\n async list(ctx: PluginContext): Promise<PluginInstall[]> {\n return loadInstalledCopilotPlugins(ctx.homeRoot);\n }\n\n async check(\n ctx: PluginContext,\n opts: PluginCheckOptions,\n ): Promise<PluginCheckResult[]> {\n const installs = loadInstalledCopilotPlugins(ctx.homeRoot);\n return installs\n .filter((install) => !opts.scopes || opts.scopes.includes(install.scope))\n .map((install) => ({\n ...install,\n status: \"unknown\" as const,\n message: \"Use copilot plugin update to refresh Copilot CLI plugins\",\n refreshSkipped: true,\n }));\n }\n\n async update(\n ctx: PluginContext,\n opts: PluginUpdateOptions,\n ): Promise<PluginUpdateResult[]> {\n const installs = loadInstalledCopilotPlugins(ctx.homeRoot);\n const targets = opts.ref\n ? installs.filter(\n (install) => install.ref === opts.ref || install.name === opts.ref,\n )\n : installs;\n const results: PluginUpdateResult[] = [];\n\n for (const install of targets) {\n if (opts.scopes && !opts.scopes.includes(install.scope)) continue;\n const result = this.runCopilot([\"update\", install.ref], ctx);\n if (result.exitCode === 0) {\n const refreshed = findInstall(\n loadInstalledCopilotPlugins(ctx.homeRoot),\n install.ref,\n );\n results.push({\n ref: install.ref,\n platformId: this.platformId,\n scope: install.scope,\n status: \"updated\",\n previousVersion: install.version,\n newVersion: refreshed?.version,\n message: result.stdout.trim() || \"Updated via copilot plugin update\",\n });\n } else {\n results.push({\n ref: install.ref,\n platformId: this.platformId,\n scope: install.scope,\n status: \"failed\",\n previousVersion: install.version,\n message:\n result.stderr.trim() || result.stdout.trim() || \"Update failed\",\n });\n }\n }\n\n return results;\n }\n\n async install(\n ctx: PluginContext,\n opts: PluginInstallOptions,\n ): Promise<PluginInstallResult> {\n const scope: PluginScope = opts.scope ?? \"user\";\n const existing = findInstall(\n loadInstalledCopilotPlugins(ctx.homeRoot),\n opts.ref,\n );\n if (existing) {\n return {\n ref: opts.ref,\n platformId: this.platformId,\n scope,\n status: \"already_installed\",\n install: existing,\n message: `Already installed (${existing.scope})`,\n };\n }\n\n const { marketplace } = parsePluginRef(opts.ref);\n if (marketplace) {\n this.runCopilot([\"marketplace\", \"update\", marketplace], ctx);\n }\n\n const result = this.runCopilot([\"install\", opts.ref], ctx);\n if (result.exitCode !== 0) {\n return {\n ref: opts.ref,\n platformId: this.platformId,\n scope,\n status: \"failed\",\n message:\n result.stderr.trim()\n || result.stdout.trim()\n || \"copilot plugin install failed\",\n };\n }\n\n const install = findInstall(\n loadInstalledCopilotPlugins(ctx.homeRoot),\n opts.ref,\n );\n if (!install) {\n return {\n ref: opts.ref,\n platformId: this.platformId,\n scope,\n status: \"failed\",\n message:\n \"Install command succeeded but plugin was not found under ~/.copilot/installed-plugins/\",\n };\n }\n\n return {\n ref: opts.ref,\n platformId: this.platformId,\n scope,\n status: \"installed\",\n install,\n message: result.stdout.trim() || \"Installed via copilot plugin install\",\n };\n }\n}\n","import { existsSync, readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { defaultRunCommand, type CommandResult, type RunCommand } from \"../run-command.js\";\nimport type {\n PluginCheckOptions,\n PluginCheckResult,\n PluginContext,\n PluginInstall,\n PluginInstallOptions,\n PluginInstallResult,\n PluginProvider,\n PluginScope,\n PluginUpdateOptions,\n PluginUpdateResult,\n} from \"../types.js\";\n\ninterface GoosePluginManifest {\n name: string;\n version?: string;\n description?: string;\n repository?: string;\n}\n\nexport interface GooseProviderDeps {\n runCommand?: RunCommand;\n gooseBinary?: string;\n}\n\nfunction readJson<T>(path: string): T | null {\n if (!existsSync(path)) return null;\n try {\n return JSON.parse(readFileSync(path, \"utf-8\")) as T;\n } catch {\n return null;\n }\n}\n\nfunction isDirectory(path: string): boolean {\n try {\n return statSync(path).isDirectory();\n } catch {\n return false;\n }\n}\n\nfunction readPluginManifest(installPath: string): GoosePluginManifest | null {\n const candidates = [\n join(installPath, \"plugin.json\"),\n join(installPath, \".goose-plugin\", \"plugin.json\"),\n join(installPath, \".plugin\", \"plugin.json\"),\n ];\n for (const manifestPath of candidates) {\n const manifest = readJson<GoosePluginManifest>(manifestPath);\n if (manifest?.name) return manifest;\n }\n return null;\n}\n\nexport function goosePluginsDir(homeRoot: string): string {\n return join(homeRoot, \".agents\", \"plugins\");\n}\n\nfunction scanGoosePlugins(homeRoot: string): PluginInstall[] {\n const pluginsRoot = goosePluginsDir(homeRoot);\n if (!isDirectory(pluginsRoot)) return [];\n\n const installs: PluginInstall[] = [];\n for (const entry of readdirSync(pluginsRoot)) {\n if (entry.startsWith(\".\")) continue;\n const installPath = join(pluginsRoot, entry);\n if (!isDirectory(installPath)) continue;\n\n const manifest = readPluginManifest(installPath);\n const name = manifest?.name ?? entry;\n installs.push({\n ref: name,\n platformId: \"goose\",\n name,\n version: manifest?.version ?? \"0.0.0\",\n versionSource: manifest?.version ? \"manifest\" : \"unknown\",\n scope: \"user\",\n enabled: true,\n installPath,\n metadata: {\n description: manifest?.description,\n repository: manifest?.repository,\n },\n });\n }\n return installs;\n}\n\nexport class GoosePluginProvider implements PluginProvider {\n readonly platformId = \"goose\";\n readonly capabilities = {\n inventory: true,\n check: true,\n update: true,\n install: true,\n updateMethod: \"native-cli\" as const,\n installMethod: \"native-cli\" as const,\n };\n\n constructor(private readonly deps: GooseProviderDeps = {}) {}\n\n private runGoose(args: string[], ctx?: PluginContext): CommandResult {\n const run = this.deps.runCommand ?? defaultRunCommand;\n const binary = this.deps.gooseBinary ?? \"goose\";\n return run(binary, args, { cwd: ctx?.projectRoot });\n }\n\n async list(ctx: PluginContext): Promise<PluginInstall[]> {\n return scanGoosePlugins(ctx.homeRoot);\n }\n\n async check(\n ctx: PluginContext,\n opts: PluginCheckOptions,\n ): Promise<PluginCheckResult[]> {\n const installs = scanGoosePlugins(ctx.homeRoot);\n return installs\n .filter((install) => !opts.scopes || opts.scopes.includes(install.scope))\n .map((install) => ({\n ...install,\n status: \"unknown\" as const,\n message: \"Use goose plugin update to refresh git-backed plugins\",\n refreshSkipped: true,\n }));\n }\n\n async update(\n ctx: PluginContext,\n opts: PluginUpdateOptions,\n ): Promise<PluginUpdateResult[]> {\n const installs = scanGoosePlugins(ctx.homeRoot);\n const targets = opts.ref\n ? installs.filter((install) => install.ref === opts.ref)\n : installs;\n const results: PluginUpdateResult[] = [];\n\n for (const install of targets) {\n const result = this.runGoose([\"plugin\", \"update\", install.name], ctx);\n if (result.exitCode === 0) {\n const refreshed = scanGoosePlugins(ctx.homeRoot).find(\n (row) => row.name === install.name,\n );\n results.push({\n ref: install.ref,\n platformId: this.platformId,\n scope: install.scope,\n status: \"updated\",\n previousVersion: install.version,\n newVersion: refreshed?.version,\n message: result.stdout.trim() || \"Updated via goose plugin update\",\n });\n } else {\n results.push({\n ref: install.ref,\n platformId: this.platformId,\n scope: install.scope,\n status: \"failed\",\n previousVersion: install.version,\n message: result.stderr.trim() || result.stdout.trim() || \"Update failed\",\n });\n }\n }\n\n return results;\n }\n\n async install(\n ctx: PluginContext,\n opts: PluginInstallOptions,\n ): Promise<PluginInstallResult> {\n const scope: PluginScope = opts.scope ?? \"user\";\n const existing = scanGoosePlugins(ctx.homeRoot).find(\n (install) => install.ref === opts.ref || install.name === opts.ref,\n );\n if (existing) {\n return {\n ref: opts.ref,\n platformId: this.platformId,\n scope,\n status: \"already_installed\",\n install: existing,\n message: `Already installed (${scope})`,\n };\n }\n\n const result = this.runGoose([\"plugin\", \"install\", opts.ref], ctx);\n if (result.exitCode !== 0) {\n return {\n ref: opts.ref,\n platformId: this.platformId,\n scope,\n status: \"failed\",\n message: result.stderr.trim() || result.stdout.trim() || \"goose plugin install failed\",\n };\n }\n\n const install = scanGoosePlugins(ctx.homeRoot).find(\n (row) => row.ref === opts.ref || row.name === opts.ref,\n );\n if (!install) {\n const byName = scanGoosePlugins(ctx.homeRoot).at(-1);\n if (byName) {\n return {\n ref: opts.ref,\n platformId: this.platformId,\n scope,\n status: \"installed\",\n install: byName,\n message: result.stdout.trim() || \"Installed via goose plugin install\",\n };\n }\n return {\n ref: opts.ref,\n platformId: this.platformId,\n scope,\n status: \"failed\",\n message:\n \"Install command succeeded but plugin was not found under ~/.agents/plugins/\",\n };\n }\n\n return {\n ref: opts.ref,\n platformId: this.platformId,\n scope,\n status: \"installed\",\n install,\n message: result.stdout.trim() || \"Installed via goose plugin install\",\n };\n }\n}\n","import type { PluginProvider } from \"./types.js\";\nimport { ClaudeCodePluginProvider } from \"./providers/claude-code.js\";\nimport { CopilotPluginProvider } from \"./providers/copilot-cli.js\";\nimport { CursorPluginProvider } from \"./providers/cursor.js\";\nimport { DeepSeekHarnessPluginProvider } from \"./providers/deepseek-harness.js\";\nimport { GoosePluginProvider } from \"./providers/goose.js\";\n\nconst providers = new Map<string, PluginProvider>([\n [\"claude-code\", new ClaudeCodePluginProvider()],\n [\"cursor\", new CursorPluginProvider()],\n [\"goose\", new GoosePluginProvider()],\n [\"copilot-cli\", new CopilotPluginProvider()],\n [\"deepseek-harness\", new DeepSeekHarnessPluginProvider()],\n]);\n\nexport function getPluginProvider(platformId: string): PluginProvider | undefined {\n return providers.get(platformId);\n}\n\nexport function getPluginProviders(platformIds?: string[]): PluginProvider[] {\n const ids = platformIds ?? [...providers.keys()];\n return ids\n .map((id) => getPluginProvider(id))\n .filter((p): p is PluginProvider => p !== undefined);\n}\n\nexport function getRegisteredPluginPlatformIds(): string[] {\n return [...providers.keys()];\n}\n","import { getHarnesstapDir } from \"../db/connection.js\";\nimport { parsePluginRef } from \"../plugins/claude-installed.js\";\nimport { getPluginProvider } from \"../plugins/registry.js\";\nimport type { PluginScope } from \"../plugins/types.js\";\nimport { resolveHomeRoot } from \"../utils/home-root.js\";\nimport type { PluginConstraintPin } from \"./plugin-apply-validation.js\";\nimport { installMarketplacePinIntoCache } from \"./marketplace-pin-cache.js\";\n\nexport interface InstallPluginPinOptions {\n ref: string;\n scope: PluginScope;\n installPlatformId?: string;\n homeRoot: string;\n projectRoot: string;\n versionConstraint?: string;\n}\n\nexport interface InstallPluginPinResult {\n ref: string;\n platformId: string;\n scope: PluginScope;\n status: \"installed\" | \"already_installed\" | \"failed\" | \"unsupported\";\n message: string;\n}\n\nexport async function installPluginPinAsync(\n options: InstallPluginPinOptions,\n): Promise<InstallPluginPinResult> {\n const platformId = options.installPlatformId ?? \"claude-code\";\n const { marketplace } = parsePluginRef(options.ref);\n if (marketplace) {\n try {\n const cached = installMarketplacePinIntoCache({\n originRef: options.ref,\n versionConstraint: options.versionConstraint,\n homeRoot: options.homeRoot,\n harnesstapDir: getHarnesstapDir(),\n });\n return {\n ref: options.ref,\n platformId,\n scope: options.scope,\n status: \"installed\",\n message: `Cached ${options.ref}@${cached.version}`,\n };\n } catch {\n // Fall through to the host provider when the package cache cannot\n // resolve the pin from a marketplace checkout.\n }\n }\n const provider = getPluginProvider(platformId);\n if (!provider) {\n return {\n ref: options.ref,\n platformId,\n scope: options.scope,\n status: \"unsupported\",\n message: `No plugin provider registered for ${platformId}`,\n };\n }\n\n const result = await provider.install(\n {\n projectRoot: options.projectRoot,\n homeRoot: options.homeRoot,\n harnesstapDir: getHarnesstapDir(),\n },\n {\n ref: options.ref,\n scope: options.scope,\n },\n );\n\n return {\n ref: result.ref,\n platformId: result.platformId,\n scope: result.scope,\n status: result.status,\n message: result.message,\n };\n}\n\nexport function resolveDefaultPluginInstallScope(projectRoot: string): PluginScope {\n return projectRoot ? \"project\" : \"user\";\n}\n\nexport function resolvePluginInstallScope(\n projectRoot: string,\n hasGitOrigin: boolean,\n): PluginScope {\n return hasGitOrigin ? \"project\" : resolveDefaultPluginInstallScope(projectRoot);\n}\n\nexport interface InstallPluginPinsProgress {\n onInstallStart?: (ref: string) => void;\n onInstallComplete?: (result: InstallPluginPinResult) => void;\n}\n\nexport async function installPluginPins(\n pins: PluginConstraintPin[],\n options: {\n homeRoot?: string;\n projectRoot: string;\n scope: PluginScope;\n installPlatformId?: string;\n progress?: InstallPluginPinsProgress;\n },\n): Promise<InstallPluginPinResult[]> {\n const homeRoot = options.homeRoot ?? resolveHomeRoot();\n const results: InstallPluginPinResult[] = [];\n\n for (const pin of pins) {\n if (!pin.version_constraint) {\n continue;\n }\n options.progress?.onInstallStart?.(pin.ref);\n const result = await installPluginPinAsync({\n ref: pin.ref,\n scope: options.scope,\n installPlatformId: options.installPlatformId,\n homeRoot,\n projectRoot: options.projectRoot,\n versionConstraint: pin.version_constraint,\n });\n options.progress?.onInstallComplete?.(result);\n results.push(result);\n }\n\n return results;\n}\n","import { findPluginResourceByPin } from \"./plugin-composition.js\";\nimport { satisfiesConstraint } from \"./plugin-constraints.js\";\nimport type { PluginPinMetadata } from \"../types.js\";\n\nexport interface PluginValidationIssue {\n ref: string;\n constraint: string;\n installed: string;\n message: string;\n}\n\nexport interface PluginConstraintPin {\n ref: string;\n version_constraint: string;\n}\n\nfunction validatePluginConstraintPins(\n rows: PluginConstraintPin[],\n): PluginValidationIssue[] {\n const issues: PluginValidationIssue[] = [];\n\n for (const row of rows) {\n if (!row.version_constraint) {\n continue;\n }\n\n const resource = findPluginResourceByPin(row.ref, row.version_constraint);\n const metadata = (resource?.metadata ?? {}) as PluginPinMetadata;\n const resolved = metadata.resolved_version;\n\n if (!resolved) {\n issues.push({\n ref: row.ref,\n constraint: row.version_constraint,\n installed: \"never_synced\",\n message: `Plugin pin ${row.ref} has no resolved version. Run: harnesstap resource sync plugin_pin:${row.ref}`,\n });\n continue;\n }\n\n if (satisfiesConstraint(row.version_constraint, resolved)) {\n continue;\n }\n\n issues.push({\n ref: row.ref,\n constraint: row.version_constraint,\n installed: resolved,\n message: `Plugin pin version mismatch: ${row.ref} requires ${row.version_constraint}, library has ${resolved}. Run: harnesstap resource sync plugin_pin:${row.ref}`,\n });\n }\n\n return issues;\n}\n\nexport function validatePluginPinsAgainstInventory(\n pins: PluginConstraintPin[],\n): PluginValidationIssue[] {\n return validatePluginConstraintPins(pins);\n}\n","import {\n addResourceToPlugin,\n createPlugin,\n getPluginByName,\n getPluginResources,\n stampPluginOrigin,\n} from \"../models/plugin-model.js\";\nimport { listResourcesByOriginRef } from \"../models/resource.js\";\nimport { MATERIAL_RESOURCE_TYPES } from \"../types.js\";\nimport { getPluginOrigin, setPluginOrigin } from \"./plugin-origin.js\";\nimport type { Plugin, MaterialResourceType } from \"../types.js\";\n\nfunction isMaterial(type: string): type is MaterialResourceType {\n return (MATERIAL_RESOURCE_TYPES as readonly string[]).includes(type);\n}\n\nexport interface MaterializeUpstreamInput {\n /** The dependency ref that produced the install, e.g. `web-search@anthropics`. */\n ref: string;\n /** Plugin name; becomes the plugin name and therefore the graph node key. */\n name: string;\n /** Resolved version from the install tree. */\n version: string;\n}\n\n/**\n * Turn an installed plugin tree into a real plugin row so the resolver can\n * treat it as an ordinary graph node.\n *\n * The install's material resources are already stored with\n * `origin_kind = 'marketplace_link'` and `origin_ref` set to the dependency\n * ref; this attaches exactly those to a plugin tagged `upstream`.\n */\nexport function materializeUpstreamPlugin(\n input: MaterializeUpstreamInput,\n): Plugin {\n const existing = getPluginByName(input.name, input.version);\n if (existing) {\n if (getPluginOrigin(existing.id) !== \"upstream\") {\n throw new Error(\n `${input.name}@${input.version} is an authored plugin; ` +\n `rename it or fork the upstream plugin under a different name.`,\n );\n }\n syncAttachments(existing.id, input.ref);\n stampPluginOrigin(existing.id, { locator: input.ref });\n return existing;\n }\n\n const plugin = createPlugin({\n name: input.name,\n version: input.version,\n description: `Upstream plugin ${input.ref}`,\n origin: \"upstream\",\n });\n setPluginOrigin(plugin.id, \"upstream\");\n syncAttachments(plugin.id, input.ref);\n stampPluginOrigin(plugin.id, { locator: input.ref });\n return plugin;\n}\n\nfunction syncAttachments(pluginId: string, ref: string): void {\n const attached = new Set(getPluginResources(pluginId).map((resource) => resource.id));\n for (const resource of listResourcesByOriginRef(ref, \"marketplace_link\")) {\n if (!isMaterial(resource.type)) continue;\n if (attached.has(resource.id)) continue;\n addResourceToPlugin(pluginId, resource.id);\n }\n}\n","import { marketplaceIsConfigured } from \"../plugins/claude-plugin-ref.js\";\nimport { defaultRunCommand } from \"../plugins/run-command.js\";\nimport type { ClaudePluginConfig } from \"../types.js\";\n\nexport interface MarketplaceRepoEntry {\n name: string;\n repo: string;\n}\n\nexport function marketplaceRepoKey(repo: string): string {\n return repo.trim().replace(/\\.git$/, \"\");\n}\n\nexport function extractMarketplaceRepos(\n config: ClaudePluginConfig | undefined,\n): MarketplaceRepoEntry[] {\n if (!config?.marketplaces) {\n return [];\n }\n\n const entries: MarketplaceRepoEntry[] = [];\n const seen = new Set<string>();\n\n for (const [name, entry] of Object.entries(config.marketplaces)) {\n const source = entry.source;\n if (source.source !== \"github\" || !source.repo) {\n continue;\n }\n const repo = marketplaceRepoKey(source.repo);\n if (seen.has(name)) {\n continue;\n }\n seen.add(name);\n entries.push({ name, repo });\n }\n\n return entries;\n}\n\nexport interface EnsureMarketplacesOptions {\n homeRoot: string;\n projectRoot: string;\n runClaudePlugin?: (args: string[]) => { exitCode: number };\n}\n\nexport function ensureClaudeMarketplacesFromConfig(\n config: ClaudePluginConfig | undefined,\n options: EnsureMarketplacesOptions,\n): string[] {\n const run =\n options.runClaudePlugin ??\n ((args) => {\n const result = defaultRunCommand(\"claude\", [\"plugin\", ...args], {\n cwd: options.projectRoot,\n });\n return { exitCode: result.exitCode };\n });\n const added: string[] = [];\n for (const { name, repo } of extractMarketplaceRepos(config)) {\n if (marketplaceIsConfigured(options.homeRoot, name)) continue;\n const result = run([\"marketplace\", \"add\", repo]);\n if (result.exitCode === 0) added.push(name);\n }\n return added;\n}\n","import type { PluginMarketplaceEntry } from \"../config/settings.js\";\nimport { parsePluginRef } from \"../plugins/claude-installed.js\";\nimport { defaultRunCommand, type CommandResult } from \"../plugins/run-command.js\";\nimport {\n CURSOR_PUBLIC_MARKETPLACE,\n isCursorPublicMarketplace,\n} from \"./builtin-marketplaces.js\";\n\nexport const CURSOR_BUILTIN_MARKETPLACE = CURSOR_PUBLIC_MARKETPLACE;\n\nexport interface CursorMarketplaceToEnsure {\n name: string;\n url: string;\n}\n\nexport interface CursorHostMarketplace {\n name: string;\n gitUrl: string;\n}\n\nexport interface EnsureCursorMarketplacesOptions {\n projectRoot: string;\n homeRoot?: string;\n runAgentPlugin?: (args: string[]) => CommandResult;\n agentBinary?: string;\n}\n\nexport interface EnsureCursorMarketplacesResult {\n added: string[];\n skipped: string[];\n listFailed?: string;\n}\n\nexport function cursorMarketplaceGitUrlKey(url: string): string {\n let value = url.trim().replace(/\\.git$/i, \"\").replace(/\\/+$/, \"\");\n const scp = value.match(/^git@github\\.com:(.+)$/i);\n if (scp?.[1]) {\n value = `https://github.com/${scp[1]}`;\n }\n const ssh = value.match(/^ssh:\\/\\/git@github\\.com\\/(.+)$/i);\n if (ssh?.[1]) {\n value = `https://github.com/${ssh[1]}`;\n }\n return value.toLowerCase();\n}\n\nexport function isCursorBuiltinMarketplace(name: string): boolean {\n return isCursorPublicMarketplace(name);\n}\n\nexport function cursorMarketplaceIsRegistered(\n listed: readonly CursorHostMarketplace[],\n wanted: CursorMarketplaceToEnsure,\n): boolean {\n if (listed.some((entry) => entry.name === wanted.name)) {\n return true;\n }\n const wantedKey = cursorMarketplaceGitUrlKey(wanted.url);\n if (!wantedKey) return false;\n return listed.some((entry) => {\n if (!entry.gitUrl) return false;\n return cursorMarketplaceGitUrlKey(entry.gitUrl) === wantedKey;\n });\n}\n\nexport function selectCursorMarketplacesToEnsure(\n entries: readonly PluginMarketplaceEntry[],\n pinRefs: readonly string[],\n): CursorMarketplaceToEnsure[] {\n const names = new Set(\n pinRefs\n .map((ref) => parsePluginRef(ref).marketplace)\n .filter((marketplace) => marketplace.length > 0),\n );\n return entries\n .filter(\n (entry) =>\n entry.platforms.includes(\"cursor\") && names.has(entry.name),\n )\n .map((entry) => ({ name: entry.name, url: entry.url }));\n}\n\nfunction parseCursorMarketplaceList(\n stdout: string,\n): CursorHostMarketplace[] | null {\n const trimmed = stdout.trim();\n if (!trimmed) return null;\n try {\n const parsed = JSON.parse(trimmed) as unknown;\n if (!Array.isArray(parsed)) return null;\n const listed: CursorHostMarketplace[] = [];\n for (const row of parsed) {\n if (typeof row !== \"object\" || row === null) continue;\n const record = row as Record<string, unknown>;\n if (typeof record.name !== \"string\" || record.name.length === 0) continue;\n listed.push({\n name: record.name,\n gitUrl: typeof record.gitUrl === \"string\" ? record.gitUrl : \"\",\n });\n }\n return listed;\n } catch {\n return null;\n }\n}\n\nfunction resolveAgentRunner(\n options: EnsureCursorMarketplacesOptions,\n): (args: string[]) => CommandResult {\n if (options.runAgentPlugin) {\n return options.runAgentPlugin;\n }\n const binary = options.agentBinary ?? process.env.CURSOR_AGENT ?? \"agent\";\n return (args) =>\n defaultRunCommand(binary, [\"plugin\", ...args], {\n cwd: options.projectRoot,\n });\n}\n\nexport function ensureCursorMarketplaces(\n entries: readonly CursorMarketplaceToEnsure[],\n options: EnsureCursorMarketplacesOptions,\n): EnsureCursorMarketplacesResult {\n const candidates = entries.filter(\n (entry) => !isCursorBuiltinMarketplace(entry.name),\n );\n const skipped = entries\n .filter((entry) => isCursorBuiltinMarketplace(entry.name))\n .map((entry) => entry.name);\n\n if (candidates.length === 0) {\n return { added: [], skipped };\n }\n\n const run = resolveAgentRunner(options);\n const list = run([\"marketplace\", \"list\", \"--format\", \"json\"]);\n const listed = list.exitCode === 0 ? parseCursorMarketplaceList(list.stdout) : null;\n if (!listed) {\n return {\n added: [],\n skipped: [...skipped, ...candidates.map((entry) => entry.name)],\n listFailed:\n list.stderr.trim() ||\n list.stdout.trim() ||\n \"agent plugin marketplace list failed\",\n };\n }\n\n const added: string[] = [];\n for (const entry of candidates) {\n if (cursorMarketplaceIsRegistered(listed, entry)) {\n skipped.push(entry.name);\n continue;\n }\n const add = run([\"marketplace\", \"add\", entry.url]);\n if (add.exitCode === 0) {\n added.push(entry.name);\n listed.push({ name: entry.name, gitUrl: entry.url });\n }\n }\n\n return { added, skipped };\n}\n","import { getDb, getHarnesstapDir } from \"../db/connection.js\";\nimport {\n ensurePluginResource,\n findPluginResourceByPin,\n} from \"./plugin-composition.js\";\nimport { parseVersionConstraint } from \"./plugin-constraints.js\";\nimport {\n listDependencies,\n parseDependencyRef,\n} from \"./plugin-dependency.js\";\nimport {\n installPluginPins,\n type InstallPluginPinResult,\n type InstallPluginPinsProgress,\n} from \"./plugin-install.js\";\nimport { syncPluginResource } from \"./resource-sync.js\";\nimport {\n validatePluginPinsAgainstInventory,\n type PluginConstraintPin,\n type PluginValidationIssue,\n} from \"./plugin-apply-validation.js\";\nimport { materializeUpstreamPlugin } from \"./upstream-plugin.js\";\nimport { getResource, listResources } from \"../models/resource.js\";\nimport {\n MATERIAL_RESOURCE_TYPES,\n type ClaudePluginConfig,\n type DependencySourceKind,\n type PluginPinMetadata,\n type Resource,\n} from \"../types.js\";\nimport type { PluginScope } from \"../plugins/types.js\";\nimport { resolveHomeRoot } from \"../utils/home-root.js\";\nimport {\n ensureClaudeMarketplacesFromConfig,\n} from \"./claude-marketplace-bootstrap.js\";\nimport {\n ensureCursorMarketplaces,\n selectCursorMarketplacesToEnsure,\n} from \"./cursor-marketplace-bootstrap.js\";\nimport { listMarketplaces } from \"./marketplace-registry.js\";\nimport {\n installPinnedPluginsHint,\n installPinnedPluginsNeedsYes,\n} from \"../copy/cli.js\";\n\nexport type { PluginConstraintPin, PluginValidationIssue };\n\n/** Dependency sources that need install/sync before composition can see them. */\nconst PREPARE_BEFORE_RESOLVE_SOURCES = new Set<DependencySourceKind>([\n \"marketplace\",\n \"git\",\n]);\n\n/**\n * Collect marketplace/git pins attached directly to the given plugins.\n * Used to materialize upstream plugins before the first composition resolve.\n */\nexport function collectPluginPinsForPrepare(\n pluginIds: string[],\n): PluginConstraintPin[] {\n const pins = new Map<string, PluginConstraintPin>();\n for (const pluginId of pluginIds) {\n for (const dependency of listDependencies(pluginId)) {\n if (!PREPARE_BEFORE_RESOLVE_SOURCES.has(dependency.source_kind)) {\n continue;\n }\n pins.set(dependency.ref, {\n ref: dependency.ref,\n version_constraint: dependency.version_constraint,\n });\n }\n }\n return [...pins.values()];\n}\n\nexport interface SyncPluginPinsForApplyProgress extends InstallPluginPinsProgress {\n onSyncStart?: (ref: string) => void;\n onSyncComplete?: (ref: string) => void;\n}\n\nexport class PinnedPluginInstallConsentError extends Error {\n readonly hint: string;\n\n constructor(profileName?: string) {\n super(installPinnedPluginsNeedsYes());\n this.name = \"PinnedPluginInstallConsentError\";\n this.hint = installPinnedPluginsHint(profileName);\n }\n}\n\nexport interface SyncPluginPinsForApplyOptions {\n pins: PluginConstraintPin[];\n /** When true, refresh every pinned plugin (--sync-plugins). */\n syncAll?: boolean;\n homeRoot?: string;\n projectRoot: string;\n scope?: PluginScope;\n installPlatformId?: string;\n /** When true, stamp exact constraints without a local install tree. */\n ignoreMissingInstall?: boolean;\n yes?: boolean;\n interactive?: boolean;\n profileName?: string;\n progress?: SyncPluginPinsForApplyProgress;\n}\n\nexport interface SyncPluginPinsForApplyResult {\n installs: InstallPluginPinResult[];\n syncedResourceCount: number;\n unresolvedPins: string[];\n}\n\nexport interface PreparePluginPinsForApplyOptions {\n pins: PluginConstraintPin[];\n baseResources: Resource[];\n projectRoot: string;\n claudeConfig?: ClaudePluginConfig;\n /** When true, skip install/sync and only expand resources + validate pins. */\n skipSync?: boolean;\n syncAll?: boolean;\n homeRoot?: string;\n scope?: PluginScope;\n installPlatformId?: string;\n ignoreMissingInstall?: boolean;\n yes?: boolean;\n interactive?: boolean;\n profileName?: string;\n progress?: SyncPluginPinsForApplyProgress;\n}\n\nexport interface PreparePluginPinsForApplyResult extends SyncPluginPinsForApplyResult {\n applyResources: Resource[];\n extraMaterialized: number;\n validationIssues: PluginValidationIssue[];\n}\n\nconst materialTypes = new Set<string>(MATERIAL_RESOURCE_TYPES);\n\nfunction materialResourceKey(resource: Pick<Resource, \"type\" | \"name\">): string {\n return `${resource.type}:${resource.name}`;\n}\n\nfunction stampResolvedVersionFromExactConstraint(\n resource: Resource,\n constraint: string,\n): Resource | null {\n try {\n const parsed = parseVersionConstraint(constraint);\n if (parsed.kind !== \"exact\") {\n return null;\n }\n\n const metadata: PluginPinMetadata = {\n ...(resource.metadata as PluginPinMetadata),\n resolved_version: parsed.version,\n sync_status: \"synced\",\n };\n const updatedAt = new Date().toISOString();\n getDb()\n .prepare(\"UPDATE resources SET metadata = ?, updated_at = ? WHERE id = ?\")\n .run(JSON.stringify(metadata), updatedAt, resource.id);\n\n return { ...resource, metadata, updated_at: updatedAt };\n } catch {\n return null;\n }\n}\n\nexport async function syncPluginPinsForApply(\n options: SyncPluginPinsForApplyOptions,\n): Promise<SyncPluginPinsForApplyResult> {\n const homeRoot = options.homeRoot ?? resolveHomeRoot();\n const scope = options.scope ?? \"user\";\n const pinsToInstall = options.pins.filter((pin) => pin.version_constraint);\n\n if (\n pinsToInstall.length > 0\n && !options.ignoreMissingInstall\n && options.interactive === false\n && !options.yes\n ) {\n throw new PinnedPluginInstallConsentError(options.profileName);\n }\n\n // --ignore-plugin-versions stamps exact constraints locally; skip marketplace\n // install attempts that can hang or fail without a real host install.\n const installs =\n options.ignoreMissingInstall && !options.syncAll\n ? []\n : await installPluginPins(pinsToInstall, {\n homeRoot,\n projectRoot: options.projectRoot,\n scope,\n installPlatformId: options.installPlatformId,\n progress: options.progress,\n });\n\n let syncedResourceCount = 0;\n const unresolvedPins: string[] = [];\n\n for (const pin of options.pins) {\n if (!pin.version_constraint) {\n continue;\n }\n\n const selector = pin.ref.includes(\":\") ? pin.ref : `plugin_pin:${pin.ref}`;\n const constraint =\n pin.version_constraint === \"latest\" || pin.version_constraint === \"*\"\n ? undefined\n : pin.version_constraint;\n\n let resource =\n findPluginResourceByPin(pin.ref, pin.version_constraint) ??\n ensurePluginResource(selector, { versionConstraint: constraint });\n\n const metadata = (resource.metadata ?? {}) as PluginPinMetadata;\n const needsSync = options.syncAll || !metadata.resolved_version;\n if (!needsSync) {\n // Already resolved: still ensure the upstream plugin exists so the\n // graph can treat the install as an ordinary node without a re-sync.\n if (metadata.resolved_version) {\n const parsed = parseDependencyRef(pin.ref);\n materializeUpstreamPlugin({\n ref: pin.ref,\n name: parsed.name,\n version: metadata.resolved_version,\n });\n }\n continue;\n }\n\n // --ignore-plugin-versions: stamp exact constraints into upstream stubs\n // without contacting marketplaces (avoids hangs / missing installs).\n if (options.ignoreMissingInstall && !options.syncAll) {\n const stamped = stampResolvedVersionFromExactConstraint(\n resource,\n pin.version_constraint,\n );\n if (stamped) {\n const stampedMetadata = (stamped.metadata ?? {}) as PluginPinMetadata;\n const parsed = parseDependencyRef(pin.ref);\n if (stampedMetadata.resolved_version) {\n materializeUpstreamPlugin({\n ref: pin.ref,\n name: parsed.name,\n version: stampedMetadata.resolved_version,\n });\n }\n continue;\n }\n }\n\n options.progress?.onSyncStart?.(pin.ref);\n const syncResult = await syncPluginResource(resource, {\n policy: \"overwrite\",\n onConflict: \"overwrite\",\n homeRoot,\n });\n syncedResourceCount += syncResult.updated.length;\n options.progress?.onSyncComplete?.(pin.ref);\n\n resource =\n findPluginResourceByPin(pin.ref, pin.version_constraint) ??\n findPluginResourceByPin(pin.ref) ??\n (resource.id ? getResource(resource.id) : undefined) ??\n resource;\n const syncedMetadata = (resource.metadata ?? {}) as PluginPinMetadata;\n const parsed = parseDependencyRef(pin.ref);\n if (syncedMetadata.resolved_version) {\n materializeUpstreamPlugin({\n ref: pin.ref,\n name: parsed.name,\n version: syncedMetadata.resolved_version,\n });\n continue;\n }\n\n if (options.ignoreMissingInstall) {\n const stamped = stampResolvedVersionFromExactConstraint(\n resource,\n pin.version_constraint,\n );\n if (stamped) {\n const stampedMetadata = (stamped.metadata ?? {}) as PluginPinMetadata;\n if (stampedMetadata.resolved_version) {\n materializeUpstreamPlugin({\n ref: pin.ref,\n name: parsed.name,\n version: stampedMetadata.resolved_version,\n });\n }\n }\n continue;\n }\n\n unresolvedPins.push(pin.ref);\n }\n\n return { installs, syncedResourceCount, unresolvedPins };\n}\n\n/**\n * Collect marketplace-linked material resources imported from pinned plugin\n * install trees.\n *\n * @deprecated Resolution owns the resource set via upstream plugins. Prefer\n * materializeUpstreamPlugin + resolveComposition. Remove in Stage 3.\n */\nexport function expandPluginPinMaterialResources(\n pins: PluginConstraintPin[],\n baseResources: Resource[] = [],\n): Resource[] {\n if (pins.length === 0) {\n return baseResources;\n }\n\n const pinRefs = new Set(pins.map((pin) => pin.ref));\n const order: string[] = [];\n const byKey = new Map<string, Resource>();\n\n for (const resource of baseResources) {\n const key = materialResourceKey(resource);\n if (!byKey.has(key)) {\n order.push(key);\n }\n byKey.set(key, resource);\n }\n\n for (const resource of listResources({ origin_kind: \"marketplace_link\" })) {\n if (!resource.origin_ref || !pinRefs.has(resource.origin_ref)) {\n continue;\n }\n if (!materialTypes.has(resource.type)) {\n continue;\n }\n const key = materialResourceKey(resource);\n if (!byKey.has(key)) {\n order.push(key);\n }\n byKey.set(key, resource);\n }\n\n return order\n .map((key) => byKey.get(key))\n .filter((resource): resource is Resource => resource !== undefined);\n}\n\n/**\n * @deprecated Resolution owns the resource set via upstream plugins. Remove in Stage 3.\n */\nexport function countPluginPinMaterialResources(\n pins: PluginConstraintPin[],\n baseResources: Resource[] = [],\n): number {\n const expanded = expandPluginPinMaterialResources(pins, baseResources);\n return Math.max(0, expanded.length - baseResources.length);\n}\n\nexport async function preparePluginPinsForApply(\n options: PreparePluginPinsForApplyOptions,\n): Promise<PreparePluginPinsForApplyResult> {\n let syncResult: SyncPluginPinsForApplyResult = {\n installs: [],\n syncedResourceCount: 0,\n unresolvedPins: [],\n };\n\n if (!options.skipSync && options.claudeConfig) {\n ensureClaudeMarketplacesFromConfig(options.claudeConfig, {\n homeRoot: options.homeRoot ?? resolveHomeRoot(),\n projectRoot: options.projectRoot,\n });\n }\n\n if (!options.skipSync && options.pins.length > 0) {\n const cursorEntries = selectCursorMarketplacesToEnsure(\n listMarketplaces(getHarnesstapDir()),\n options.pins.map((pin) => pin.ref),\n );\n ensureCursorMarketplaces(cursorEntries, {\n homeRoot: options.homeRoot ?? resolveHomeRoot(),\n projectRoot: options.projectRoot,\n });\n\n syncResult = await syncPluginPinsForApply({\n pins: options.pins,\n syncAll: options.syncAll,\n homeRoot: options.homeRoot,\n projectRoot: options.projectRoot,\n scope: options.scope,\n installPlatformId: options.installPlatformId,\n ignoreMissingInstall: options.ignoreMissingInstall,\n yes: options.yes,\n interactive: options.interactive,\n profileName: options.profileName,\n progress: options.progress,\n });\n }\n\n // Resolution owns the resource set. Install/sync still materializes upstream\n // plugins; expandPluginPinMaterialResources is no longer consulted here.\n const validationIssues = validatePluginPinsAgainstInventory(options.pins);\n\n return {\n ...syncResult,\n applyResources: options.baseResources,\n extraMaterialized: 0,\n validationIssues,\n };\n}\n","import { closeSync, mkdirSync, openSync, unlinkSync, writeSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { getHarnesstapDir } from \"../db/connection.js\";\n\nexport const PROFILE_APPLY_LOCK_FILE = \"profile-apply.lock\";\n\nexport class ProfileApplyLockBusyError extends Error {\n readonly lockPath: string;\n\n constructor(lockPath: string) {\n super(\n `Another profile apply or switch is in progress (${lockPath}). Wait for it to finish, or remove the lock file if no other HarnessTap process is running.`,\n );\n this.name = \"ProfileApplyLockBusyError\";\n this.lockPath = lockPath;\n }\n}\n\nexport interface ProfileApplyLockHandle {\n release(): void;\n}\n\nfunction getLockPath(): string {\n return join(getHarnesstapDir(), PROFILE_APPLY_LOCK_FILE);\n}\n\nlet lockDepth = 0;\nlet lockFd: number | undefined;\n\nexport function acquireProfileApplyLock(): ProfileApplyLockHandle {\n if (lockDepth > 0) {\n lockDepth += 1;\n return {\n release() {\n lockDepth -= 1;\n },\n };\n }\n\n const harnesstapDir = getHarnesstapDir();\n mkdirSync(harnesstapDir, { recursive: true });\n const lockPath = getLockPath();\n try {\n lockFd = openSync(lockPath, \"wx\");\n writeSync(lockFd, `${process.pid}\\n`);\n lockDepth = 1;\n } catch (error) {\n const errno = error as NodeJS.ErrnoException;\n if (errno.code === \"EEXIST\") {\n throw new ProfileApplyLockBusyError(lockPath);\n }\n throw error;\n }\n\n return {\n release() {\n if (lockDepth <= 0) {\n return;\n }\n lockDepth -= 1;\n if (lockDepth > 0) {\n return;\n }\n const fd = lockFd;\n lockFd = undefined;\n if (fd === undefined) {\n return;\n }\n try {\n closeSync(fd);\n } finally {\n try {\n unlinkSync(lockPath);\n } catch {\n // Ignore races with another process replacing the lock file.\n }\n }\n },\n };\n}\n\nexport async function withProfileApplyLock<T>(fn: () => Promise<T>): Promise<T> {\n const lock = acquireProfileApplyLock();\n try {\n return await fn();\n } finally {\n lock.release();\n }\n}\n","import { listPluginDependencies } from \"../models/plugin-model.js\";\nimport {\n createPlugin,\n getPluginByName,\n resolvePluginSelector,\n setPluginTags,\n updatePluginName,\n} from \"../models/plugin-model.js\";\nimport { renameGlobalApplySnapshotsProfile } from \"../models/global-apply-snapshot.js\";\nimport { renamePluginTypedResources } from \"../models/resource.js\";\nimport {\n CLEARED_GLOBAL_PROFILE_NAME,\n PROFILE_PLUGIN_TAG,\n isEmptyBuiltinProfile,\n isProfilePlugin,\n isReservedProfileName,\n listProfilePlugins,\n} from \"../constants/profile.js\";\nimport type { Plugin } from \"../types.js\";\nimport {\n clearActiveProfileName,\n getActiveProfileName,\n setActiveProfileName,\n} from \"./active-profile.js\";\nimport { applyProfilePlugin, type ApplyProfilePluginOptions } from \"./profile-apply.js\";\nimport { withProfileApplyLock } from \"./profile-apply-lock.js\";\n\nexport interface CreateProfileResult {\n plugin: Plugin;\n created: boolean;\n promoted: boolean;\n}\n\nexport class ProfileRenameError extends Error {\n readonly code: \"invalid_name\" | \"not_found\" | \"plugin_exists\" | \"not_a_profile\" | \"reserved_name\";\n\n constructor(\n code: ProfileRenameError[\"code\"],\n message: string,\n ) {\n super(message);\n this.name = \"ProfileRenameError\";\n this.code = code;\n }\n}\n\nexport class ProfileReservedNameError extends Error {\n constructor(name: string) {\n super(\n `\"${name}\" is a reserved profile name and cannot be created, renamed to, or deleted`,\n );\n this.name = \"ProfileReservedNameError\";\n }\n}\n\nfunction assertNotReservedProfileName(name: string): void {\n if (isReservedProfileName(name)) {\n throw new ProfileReservedNameError(name);\n }\n}\n\nexport function listProfilePluginsCommand() {\n const names = new Set<string>();\n for (const plugin of listProfilePlugins()) {\n names.add(plugin.name);\n }\n return [...names]\n .map((name) => getPluginByName(name))\n .filter((plugin): plugin is Plugin => plugin !== undefined && isProfilePlugin(plugin));\n}\n\nexport function showProfileCommand(selector: string): {\n profile: Plugin;\n dependencies: ReturnType<typeof listPluginDependencies>;\n active: boolean;\n} {\n if (isEmptyBuiltinProfile(selector)) {\n throw new ProfileReservedNameError(CLEARED_GLOBAL_PROFILE_NAME);\n }\n\n const profile = resolvePluginSelector(selector);\n if (!profile) {\n throw new Error(`Profile not found: ${selector}`);\n }\n if (!isProfilePlugin(profile)) {\n throw new Error(`Plugin \"${profile.name}\" is not tagged as a profile`);\n }\n const activeProfile = getActiveProfileName();\n return {\n profile,\n dependencies: listPluginDependencies(profile.id),\n active: activeProfile === profile.name,\n };\n}\n\nexport function getActiveProfilePayload(): {\n active_profile: string | null;\n plugin_id?: string;\n exists: boolean;\n} {\n const activeProfile = getActiveProfileName();\n if (!activeProfile) {\n return {\n active_profile: null,\n exists: false,\n };\n }\n const plugin = resolvePluginSelector(activeProfile);\n return {\n active_profile: activeProfile,\n ...(plugin ? { plugin_id: plugin.id } : {}),\n exists: Boolean(plugin && isProfilePlugin(plugin)),\n };\n}\n\nexport async function useProfileCommandUnlocked(\n selector: string,\n options: ApplyProfilePluginOptions,\n) {\n const result = await applyProfilePlugin(selector, options);\n if (!result.cancelled && !result.dry_run) {\n setActiveProfileName(result.profile_name);\n }\n return result;\n}\n\nexport async function useProfileCommand(\n selector: string,\n options: ApplyProfilePluginOptions,\n) {\n return withProfileApplyLock(() => useProfileCommandUnlocked(selector, options));\n}\n\nexport function createProfileCommand(input: {\n name: string;\n description?: string;\n version?: string;\n}): CreateProfileResult {\n assertNotReservedProfileName(input.name);\n const version = input.version ?? \"1.0.0\";\n const existing = getPluginByName(input.name, version);\n if (existing) {\n if (isProfilePlugin(existing)) {\n return {\n plugin: existing,\n created: false,\n promoted: false,\n };\n }\n const tags = [...new Set([...existing.tags, PROFILE_PLUGIN_TAG])];\n setPluginTags(existing.id, tags);\n const refreshed = resolvePluginSelector(existing.name);\n if (!refreshed) {\n throw new Error(`Plugin not found after tagging: ${input.name}`);\n }\n return {\n plugin: refreshed,\n created: false,\n promoted: true,\n };\n }\n\n const plugin = createPlugin({\n name: input.name,\n description: input.description,\n version,\n tags: [PROFILE_PLUGIN_TAG],\n });\n return {\n plugin,\n created: true,\n promoted: true,\n };\n}\n\nexport function tagProfileCommand(selector: string): {\n plugin_id: string;\n tags: string[];\n} {\n if (isEmptyBuiltinProfile(selector)) {\n throw new ProfileReservedNameError(CLEARED_GLOBAL_PROFILE_NAME);\n }\n const plugin = resolvePluginSelector(selector);\n if (!plugin) {\n throw new Error(`Plugin not found: ${selector}`);\n }\n const tags = [...new Set([...plugin.tags, PROFILE_PLUGIN_TAG])];\n setPluginTags(plugin.id, tags);\n return { plugin_id: plugin.id, tags };\n}\n\nexport function untagProfileCommand(selector: string): {\n plugin_id: string;\n tags: string[];\n} {\n if (isEmptyBuiltinProfile(selector)) {\n throw new ProfileReservedNameError(CLEARED_GLOBAL_PROFILE_NAME);\n }\n const plugin = resolvePluginSelector(selector);\n if (!plugin) {\n throw new Error(`Plugin not found: ${selector}`);\n }\n const tags = plugin.tags.filter((tag) => tag !== PROFILE_PLUGIN_TAG);\n setPluginTags(plugin.id, tags);\n const activeProfile = getActiveProfileName();\n if (activeProfile === plugin.name) {\n clearActiveProfileName();\n }\n return { plugin_id: plugin.id, tags };\n}\n\nexport function deleteProfileCommand(selector: string): {\n plugin_id: string;\n plugin_name: string;\n tags: string[];\n was_active: boolean;\n} {\n if (isEmptyBuiltinProfile(selector)) {\n throw new ProfileReservedNameError(CLEARED_GLOBAL_PROFILE_NAME);\n }\n const plugin = resolvePluginSelector(selector);\n if (!plugin) {\n throw new Error(`Profile not found: ${selector}`);\n }\n if (!isProfilePlugin(plugin)) {\n throw new Error(`Plugin \"${plugin.name}\" is not tagged as a profile`);\n }\n const wasActive = getActiveProfileName() === plugin.name;\n const untagged = untagProfileCommand(selector);\n return {\n plugin_id: untagged.plugin_id,\n plugin_name: plugin.name,\n tags: untagged.tags,\n was_active: wasActive,\n };\n}\n\nexport function renameProfileCommand(\n selector: string,\n nextNameInput: string,\n): {\n old_name: string;\n name: string;\n plugin_id: string;\n was_active: boolean;\n} {\n if (isEmptyBuiltinProfile(selector)) {\n throw new ProfileRenameError(\n \"reserved_name\",\n `\"${CLEARED_GLOBAL_PROFILE_NAME}\" is a reserved profile name and cannot be renamed`,\n );\n }\n\n const nextName = nextNameInput.trim();\n if (!nextName) {\n throw new ProfileRenameError(\"invalid_name\", \"Profile name is required\");\n }\n if (isReservedProfileName(nextName)) {\n throw new ProfileRenameError(\n \"reserved_name\",\n `\"${CLEARED_GLOBAL_PROFILE_NAME}\" is a reserved profile name`,\n );\n }\n\n const plugin = resolvePluginSelector(selector);\n if (!plugin) {\n throw new ProfileRenameError(\"not_found\", `Profile not found: ${selector}`);\n }\n if (!isProfilePlugin(plugin)) {\n throw new ProfileRenameError(\n \"not_a_profile\",\n `Plugin \"${plugin.name}\" is not tagged as a profile`,\n );\n }\n\n const oldName = plugin.name;\n if (nextName === oldName) {\n const wasActive = getActiveProfileName() === oldName;\n return {\n old_name: oldName,\n name: oldName,\n plugin_id: plugin.id,\n was_active: wasActive,\n };\n }\n\n const conflicting = getPluginByName(nextName);\n if (conflicting && conflicting.id !== plugin.id) {\n throw new ProfileRenameError(\n \"plugin_exists\",\n `Plugin already exists: ${nextName}`,\n );\n }\n\n if (!updatePluginName(plugin.id, nextName)) {\n throw new ProfileRenameError(\"not_found\", `Profile not found: ${selector}`);\n }\n\n renamePluginTypedResources(oldName, nextName);\n renameGlobalApplySnapshotsProfile(oldName, nextName);\n\n const wasActive = getActiveProfileName() === oldName;\n if (wasActive) {\n setActiveProfileName(nextName);\n }\n\n return {\n old_name: oldName,\n name: nextName,\n plugin_id: plugin.id,\n was_active: wasActive,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,kBAAkB;;;ACC3B,SAAS,YAAY;AAuBrB,SAAS,qBACP,KACyB;AACzB,SAAO;AAAA,IACL,GAAG;AAAA,IACH,mBAAmB,IAAI,sBAAsB;AAAA,EAC/C;AACF;AAEA,SAAS,sBACP,KACA,QAC8B;AAC9B,MAAI;AACF,WAAO,MAAM,EAAE,QAAQ,GAAG,EAAE,IAAI,GAAG,MAAM;AAAA,EAC3C,QAAQ;AACN,WAAO,CAAC;AAAA,EACV;AACF;AAEO,SAAS,8BAA8B,OAWlB;AAC1B,QAAM,KAAK,MAAM;AACjB,QAAM,OAAM,oBAAI,KAAK,GAAE,YAAY;AACnC,QAAM,YAAY,MAAM,cAAc;AACtC,QAAM,mBAAmB,MAAM,oBAAoB,IAAI;AAEvD,QAAM,WAAW,GACd;AAAA,IACC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQF,EACC;AAAA,IACC,MAAM;AAAA,IACN,MAAM;AAAA,IACN;AAAA,IACA,MAAM;AAAA,IACN,MAAM;AAAA,IACN,MAAM;AAAA,IACN,MAAM;AAAA,EACR;AAEF,MAAI,UAAU;AACZ,OAAG;AAAA,MACD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAMF,EAAE;AAAA,MACA,MAAM;AAAA,MACN,MAAM;AAAA,MACN;AAAA,MACA;AAAA,MACA,SAAS;AAAA,IACX;AAEA,UAAM,MAAM,GACT,QAAQ,sDAA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EAAE,eAAe,CAAC,KAAK,IAAI,EAAE,CAAC;AAAA,MACnD;AAAA,IACF,QAAQ;AAEN,aAAO;AAAA,QACL,OAAO;AAAA,QACP,MAAM,KAAK;AAAA,QACX,SAAS,CAAC;AAAA,QACV,OAAO,CAAC;AAAA,QACR,SAAS,KAAK,QAAQ,IAAI,CAAC,UAAU,MAAM,IAAI;AAAA,MACjD;AAAA,IACF;AAAA,EACF,GAAG,IACH;AAEJ,SAAO;AAAA,IACL,cAAc;AAAA,IACd,YAAY;AAAA,IACZ,gBAAgB,gBAAgB;AAAA,IAChC,WAAW,gBAAgB,YAAY;AAAA,IACvC;AAAA,IACA,OAAO;AAAA,IACP,iBAAiB,UAAU,cAAc,QAAQ,EAAE,EAAE,SAAS;AAAA,IAC9D,qBAAqB;AAAA,IACrB,SAAS,oBAAoB;AAAA,IAC7B,iBAAiB;AAAA,IACjB;AAAA,IACA,mBAAmB;AAAA,IACnB,GAAI,cAAc,EAAE,MAAM,YAAY,IAAI,CAAC;AAAA,EAC7C;AACF;","names":["ulid","ulid","existsSync","readFileSync","join","existsSync","readFileSync","join","existsSync","readFileSync","join","readActiveEnvironmentName","existsSync","readFileSync","join","existsSync","readFileSync","join","join","existsSync","readFileSync","resolve","ulid","ulid","existsSync","mkdirSync","readFileSync","writeFileSync","join","join","existsSync","readFileSync","mkdirSync","writeFileSync","mkdirSync","writeFileSync","join","existsSync","mkdirSync","readFileSync","realpathSync","writeFileSync","dirname","resolve","sep","readFileSync","existsSync","join","join","existsSync","readFileSync","existsSync","readFileSync","join","join","existsSync","readFileSync","existsSync","dirname","join","existsSync","readFileSync","join","join","existsSync","readFileSync","writeFileSync","mkdirSync","join","join","join","existsSync","readFileSync","existsSync","mkdirSync","readdirSync","rmSync","dirname","join","join","dirname","existsSync","existsSync","readFileSync","writeFileSync","join","resolve","resourceKey","existsSync","mkdirSync","readFileSync","statSync","writeFileSync","dirname","join","resolve","join","resolve","existsSync","statSync","join","resolve","existsSync","mkdirSync","readFileSync","writeFileSync","dirname","resolve","resolve","resolve","MATERIAL_RESOURCE_TYPE_SET","resolve","MATERIAL_RESOURCE_TYPE_SET","originRef","resolve","scanned","ownedPaths","materialResources","existsSync","readFileSync","mkdirSync","dirname","writeFileSync","basename","resolve","resource","join","existsSync","readFileSync","writeFileSync","existsSync","mkdirSync","readdirSync","readFileSync","rmSync","statSync","writeFileSync","basename","dirname","join","resolve","ulid","ulid","ulid","join","readFileSync","resolve","existsSync","join","mkdirSync","dirname","writeFileSync","readdirSync","statSync","rmSync","basename","ulid","existsSync","readFileSync","statSync","join","join","existsSync","statSync","readFileSync","resolve","sep","realpathSync","existsSync","dirname","readFileSync","mkdirSync","writeFileSync","existsSync","readdirSync","statSync","join","SKILL_FILE_RE","SKILL_FILE_RE","existsSync","readFileSync","resolve","parseToml","parseToml","resolve","existsSync","readFileSync","join","join","existsSync","readdirSync","readFileSync","statSync","join","existsSync","readFileSync","statSync","join","readdirSync","install","parsed","mkdirSync","join","writeFileSync","previousTrackedFiles","writeKeeps","mkdirSync","join","join","mkdirSync","wasActive","materialResources","resolve"]}
|