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.
Files changed (202) hide show
  1. package/README.md +33 -16
  2. package/dist/apply-QSS4242W.js +67 -0
  3. package/dist/apply-QSS4242W.js.map +1 -0
  4. package/dist/approve-CNYQY6DC.js +181 -0
  5. package/dist/approve-CNYQY6DC.js.map +1 -0
  6. package/dist/audit-V4SUV7KA.js +434 -0
  7. package/dist/audit-V4SUV7KA.js.map +1 -0
  8. package/dist/auth-63FOHIQ3.js +220 -0
  9. package/dist/auth-63FOHIQ3.js.map +1 -0
  10. package/dist/bin.js +166 -0
  11. package/dist/bin.js.map +1 -0
  12. package/dist/chunk-2H7UOFLK.js +11 -0
  13. package/dist/chunk-2H7UOFLK.js.map +1 -0
  14. package/dist/chunk-2NE3QYMP.js +103 -0
  15. package/dist/chunk-2NE3QYMP.js.map +1 -0
  16. package/dist/chunk-2P2EOYEW.js +1140 -0
  17. package/dist/chunk-2P2EOYEW.js.map +1 -0
  18. package/dist/chunk-37E5M4JX.js +34 -0
  19. package/dist/chunk-37E5M4JX.js.map +1 -0
  20. package/dist/chunk-37LQQWMF.js +496 -0
  21. package/dist/chunk-37LQQWMF.js.map +1 -0
  22. package/dist/chunk-3FIWOI3H.js +98 -0
  23. package/dist/chunk-3FIWOI3H.js.map +1 -0
  24. package/dist/chunk-3PGC6OA3.js +540 -0
  25. package/dist/chunk-3PGC6OA3.js.map +1 -0
  26. package/dist/chunk-4IHKBIY3.js +118 -0
  27. package/dist/chunk-4IHKBIY3.js.map +1 -0
  28. package/dist/chunk-4ZUBRLSP.js +17 -0
  29. package/dist/chunk-4ZUBRLSP.js.map +1 -0
  30. package/dist/chunk-5F3LNDZG.js +9 -0
  31. package/dist/chunk-5F3LNDZG.js.map +1 -0
  32. package/dist/chunk-5TXI6BI2.js +1359 -0
  33. package/dist/chunk-5TXI6BI2.js.map +1 -0
  34. package/dist/chunk-6P5IO4BX.js +235 -0
  35. package/dist/chunk-6P5IO4BX.js.map +1 -0
  36. package/dist/chunk-ABXUKHAU.js +571 -0
  37. package/dist/chunk-ABXUKHAU.js.map +1 -0
  38. package/dist/chunk-AOUDSNRK.js +1357 -0
  39. package/dist/chunk-AOUDSNRK.js.map +1 -0
  40. package/dist/chunk-BNDJJAEI.js +311 -0
  41. package/dist/chunk-BNDJJAEI.js.map +1 -0
  42. package/dist/chunk-C2IWSFF5.js +818 -0
  43. package/dist/chunk-C2IWSFF5.js.map +1 -0
  44. package/dist/chunk-CHQGE2HF.js +283 -0
  45. package/dist/chunk-CHQGE2HF.js.map +1 -0
  46. package/dist/chunk-DEJLP7QJ.js +681 -0
  47. package/dist/chunk-DEJLP7QJ.js.map +1 -0
  48. package/dist/chunk-DJ6FN6EW.js +532 -0
  49. package/dist/chunk-DJ6FN6EW.js.map +1 -0
  50. package/dist/chunk-E4WRTRMH.js +1173 -0
  51. package/dist/chunk-E4WRTRMH.js.map +1 -0
  52. package/dist/chunk-E5QXNU3K.js +238 -0
  53. package/dist/chunk-E5QXNU3K.js.map +1 -0
  54. package/dist/chunk-EMTBGOR3.js +2959 -0
  55. package/dist/chunk-EMTBGOR3.js.map +1 -0
  56. package/dist/chunk-FFWYIGQ4.js +18 -0
  57. package/dist/chunk-FFWYIGQ4.js.map +1 -0
  58. package/dist/chunk-I6XFZLTJ.js +9 -0
  59. package/dist/chunk-I6XFZLTJ.js.map +1 -0
  60. package/dist/chunk-IHWAOIAU.js +172 -0
  61. package/dist/chunk-IHWAOIAU.js.map +1 -0
  62. package/dist/chunk-IHZUYG66.js +583 -0
  63. package/dist/chunk-IHZUYG66.js.map +1 -0
  64. package/dist/chunk-JQOKQKQT.js +158 -0
  65. package/dist/chunk-JQOKQKQT.js.map +1 -0
  66. package/dist/chunk-JRFUTIEH.js +426 -0
  67. package/dist/chunk-JRFUTIEH.js.map +1 -0
  68. package/dist/chunk-KCBI6JQC.js +115 -0
  69. package/dist/chunk-KCBI6JQC.js.map +1 -0
  70. package/dist/chunk-KDUQMINL.js +60 -0
  71. package/dist/chunk-KDUQMINL.js.map +1 -0
  72. package/dist/chunk-KLR2DURP.js +656 -0
  73. package/dist/chunk-KLR2DURP.js.map +1 -0
  74. package/dist/chunk-KRI4R7EM.js +25 -0
  75. package/dist/chunk-KRI4R7EM.js.map +1 -0
  76. package/dist/chunk-LYQMK6SV.js +87 -0
  77. package/dist/chunk-LYQMK6SV.js.map +1 -0
  78. package/dist/chunk-MK3Q37ZN.js +183 -0
  79. package/dist/chunk-MK3Q37ZN.js.map +1 -0
  80. package/dist/chunk-MSGAGV7B.js +346 -0
  81. package/dist/chunk-MSGAGV7B.js.map +1 -0
  82. package/dist/chunk-MZQRSERO.js +430 -0
  83. package/dist/chunk-MZQRSERO.js.map +1 -0
  84. package/dist/chunk-N3WIJXXM.js +691 -0
  85. package/dist/chunk-N3WIJXXM.js.map +1 -0
  86. package/dist/chunk-NAGAJ5UM.js +145 -0
  87. package/dist/chunk-NAGAJ5UM.js.map +1 -0
  88. package/dist/chunk-NFYPBTKO.js +302 -0
  89. package/dist/chunk-NFYPBTKO.js.map +1 -0
  90. package/dist/chunk-NPO2IG6G.js +491 -0
  91. package/dist/chunk-NPO2IG6G.js.map +1 -0
  92. package/dist/chunk-OS6NUIBJ.js +38 -0
  93. package/dist/chunk-OS6NUIBJ.js.map +1 -0
  94. package/dist/chunk-PFUK3HJ4.js +296 -0
  95. package/dist/chunk-PFUK3HJ4.js.map +1 -0
  96. package/dist/chunk-PMQ55GDB.js +115 -0
  97. package/dist/chunk-PMQ55GDB.js.map +1 -0
  98. package/dist/chunk-QIVE2YFJ.js +514 -0
  99. package/dist/chunk-QIVE2YFJ.js.map +1 -0
  100. package/dist/chunk-QKXD3EUF.js +691 -0
  101. package/dist/chunk-QKXD3EUF.js.map +1 -0
  102. package/dist/chunk-RNQYUWF6.js +32 -0
  103. package/dist/chunk-RNQYUWF6.js.map +1 -0
  104. package/dist/chunk-S2E4SSQV.js +41 -0
  105. package/dist/chunk-S2E4SSQV.js.map +1 -0
  106. package/dist/chunk-SN4BXX3B.js +186 -0
  107. package/dist/chunk-SN4BXX3B.js.map +1 -0
  108. package/dist/chunk-SNVAMWB7.js +40 -0
  109. package/dist/chunk-SNVAMWB7.js.map +1 -0
  110. package/dist/chunk-T5VRREN4.js +696 -0
  111. package/dist/chunk-T5VRREN4.js.map +1 -0
  112. package/dist/chunk-TKBMHZTS.js +10945 -0
  113. package/dist/chunk-TKBMHZTS.js.map +1 -0
  114. package/dist/chunk-TNJPTUE4.js +35 -0
  115. package/dist/chunk-TNJPTUE4.js.map +1 -0
  116. package/dist/chunk-TQ2NA4Z4.js +24 -0
  117. package/dist/chunk-TQ2NA4Z4.js.map +1 -0
  118. package/dist/chunk-TXXDMDPN.js +998 -0
  119. package/dist/chunk-TXXDMDPN.js.map +1 -0
  120. package/dist/chunk-UWXUBU7V.js +184 -0
  121. package/dist/chunk-UWXUBU7V.js.map +1 -0
  122. package/dist/chunk-UYRK2H24.js +141 -0
  123. package/dist/chunk-UYRK2H24.js.map +1 -0
  124. package/dist/chunk-V4IXIM3C.js +806 -0
  125. package/dist/chunk-V4IXIM3C.js.map +1 -0
  126. package/dist/chunk-VFHVXXP4.js +6438 -0
  127. package/dist/chunk-VFHVXXP4.js.map +1 -0
  128. package/dist/chunk-VQVUJYYY.js +244 -0
  129. package/dist/chunk-VQVUJYYY.js.map +1 -0
  130. package/dist/chunk-VZQG2JDV.js +9 -0
  131. package/dist/chunk-VZQG2JDV.js.map +1 -0
  132. package/dist/chunk-W7HQ5X3S.js +610 -0
  133. package/dist/chunk-W7HQ5X3S.js.map +1 -0
  134. package/dist/chunk-WMSQAFK5.js +65 -0
  135. package/dist/chunk-WMSQAFK5.js.map +1 -0
  136. package/dist/chunk-WMYTBJPB.js +364 -0
  137. package/dist/chunk-WMYTBJPB.js.map +1 -0
  138. package/dist/chunk-WNLFNCOH.js +7795 -0
  139. package/dist/chunk-WNLFNCOH.js.map +1 -0
  140. package/dist/chunk-WRX7CB2M.js +6448 -0
  141. package/dist/chunk-WRX7CB2M.js.map +1 -0
  142. package/dist/chunk-XGTTOO4R.js +84 -0
  143. package/dist/chunk-XGTTOO4R.js.map +1 -0
  144. package/dist/chunk-YSXRBUR4.js +682 -0
  145. package/dist/chunk-YSXRBUR4.js.map +1 -0
  146. package/dist/chunk-YTC2EG64.js +1759 -0
  147. package/dist/chunk-YTC2EG64.js.map +1 -0
  148. package/dist/compile-J3UGQSS3.js +161 -0
  149. package/dist/compile-J3UGQSS3.js.map +1 -0
  150. package/dist/config-5BPSZND3.js +438 -0
  151. package/dist/config-5BPSZND3.js.map +1 -0
  152. package/dist/doctor-BVFKLJVO.js +111 -0
  153. package/dist/doctor-BVFKLJVO.js.map +1 -0
  154. package/dist/environment-3RI5H32O.js +2745 -0
  155. package/dist/environment-3RI5H32O.js.map +1 -0
  156. package/dist/github-YFJQVH5K.js +114 -0
  157. package/dist/github-YFJQVH5K.js.map +1 -0
  158. package/dist/harness-ECGHPEKA.js +746 -0
  159. package/dist/harness-ECGHPEKA.js.map +1 -0
  160. package/dist/help-ELPNPPEM.js +2079 -0
  161. package/dist/help-ELPNPPEM.js.map +1 -0
  162. package/dist/help-UL5XLY3I.js +1892 -0
  163. package/dist/help-UL5XLY3I.js.map +1 -0
  164. package/dist/index.d.ts +164 -1
  165. package/dist/index.js +50 -54362
  166. package/dist/index.js.map +1 -1
  167. package/dist/init-UJQTDHW7.js +873 -0
  168. package/dist/init-UJQTDHW7.js.map +1 -0
  169. package/dist/lock-XUMJ63NZ.js +455 -0
  170. package/dist/lock-XUMJ63NZ.js.map +1 -0
  171. package/dist/marketplace-ZUMOLVXE.js +495 -0
  172. package/dist/marketplace-ZUMOLVXE.js.map +1 -0
  173. package/dist/mcp-RZA5O2ND.js +202 -0
  174. package/dist/mcp-RZA5O2ND.js.map +1 -0
  175. package/dist/migrate-CYQI2FH6.js +1043 -0
  176. package/dist/migrate-CYQI2FH6.js.map +1 -0
  177. package/dist/open-AWOAWLKO.js +32 -0
  178. package/dist/open-AWOAWLKO.js.map +1 -0
  179. package/dist/pack-2QD5ZUIO.js +99 -0
  180. package/dist/pack-2QD5ZUIO.js.map +1 -0
  181. package/dist/plugin-GQSSSFX4.js +64 -0
  182. package/dist/plugin-GQSSSFX4.js.map +1 -0
  183. package/dist/plugin-from-project-SIQUFYIO.js +16 -0
  184. package/dist/plugin-from-project-SIQUFYIO.js.map +1 -0
  185. package/dist/policy-CT4JRCJI.js +105 -0
  186. package/dist/policy-CT4JRCJI.js.map +1 -0
  187. package/dist/profile-4JQ6LECP.js +1886 -0
  188. package/dist/profile-4JQ6LECP.js.map +1 -0
  189. package/dist/project-JG7QWXRG.js +1392 -0
  190. package/dist/project-JG7QWXRG.js.map +1 -0
  191. package/dist/resource-QRMR6CSD.js +555 -0
  192. package/dist/resource-QRMR6CSD.js.map +1 -0
  193. package/dist/version-LZ5POOXY.js +17 -0
  194. package/dist/version-LZ5POOXY.js.map +1 -0
  195. package/package.json +25 -14
  196. package/schemas/ap-package.v1.json +36 -0
  197. package/schemas/fixtures/catalog-missing-schema.ap.json +13 -0
  198. package/schemas/fixtures/confidence.ap.json +13 -0
  199. package/schemas/fixtures/context7.ap.json +13 -0
  200. package/schemas/fixtures/minimal-with-schema.ap.json +13 -0
  201. package/schemas/fixtures/superpowers.ap.json +13 -0
  202. package/schemas/fixtures/third-party-skills.ap.json +13 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/models/imported-snapshot.ts","../src/platforms/claude-code.ts","../src/platforms/base-serializer.ts","../src/services/merge-skill-markdown.ts","../src/services/claude-local-mcp.ts","../src/services/mcp-target.ts","../src/services/instruction-target.ts","../src/platforms/cursor.ts","../src/platforms/codex.ts","../src/platforms/goose.ts","../src/platforms/opencode.ts","../src/platforms/copilot.ts","../src/platforms/gemini-cli.ts","../src/platforms/grok-build.ts","../src/platforms/deepseek-harness.ts","../src/platforms/deepseek-harness-home.ts","../src/plugins/providers/deepseek-harness.ts","../src/plugins/run-command.ts","../src/platforms/muse-code.ts","../src/platforms/minimax-code.ts","../src/platforms/generic-agents.ts","../src/services/platform-serializers.ts","../src/services/scan-dedup.ts","../src/services/scanner.ts","../src/services/scanner-ignore.ts","../src/services/plugin-translation-marker.ts","../src/services/reference-resources.ts","../src/services/harness-resource-union.ts","../src/models/plugin-pin-materialization.ts","../src/services/plugin-translation-source.ts","../src/services/live-library-ref.ts"],"sourcesContent":["import { ulid } from \"ulid\";\nimport { getDb } from \"../db/connection.js\";\nimport type {\n ImportedSnapshot,\n ImportedSnapshotInstall,\n ImportedSnapshotMetadata,\n} from \"../types.js\";\n\ninterface ImportedSnapshotRow {\n id: string;\n source_kind: ImportedSnapshot[\"source_kind\"];\n source_label: string;\n plugin_name: string;\n plugin_version: string | null;\n resource_ids: string;\n metadata: string;\n created_at: string;\n}\n\ninterface ImportedSnapshotInstallRow {\n snapshot_id: string;\n platform_id: string;\n files: string;\n installed_at: string;\n}\n\nexport interface ImportedSnapshotFileOwner {\n snapshot_id: string;\n platform_id: string;\n plugin_name: string;\n plugin_version?: string;\n}\n\nfunction rowToImportedSnapshot(row: ImportedSnapshotRow): ImportedSnapshot {\n return {\n ...row,\n plugin_version: row.plugin_version ?? undefined,\n resource_ids: JSON.parse(row.resource_ids) as string[],\n metadata: JSON.parse(row.metadata) as ImportedSnapshotMetadata,\n };\n}\n\nfunction rowToImportedSnapshotInstall(\n row: ImportedSnapshotInstallRow,\n): ImportedSnapshotInstall {\n return {\n ...row,\n files: JSON.parse(row.files) as string[],\n };\n}\n\nexport function createImportedSnapshot(input: {\n source_kind: ImportedSnapshot[\"source_kind\"];\n source_label: string;\n plugin_name: string;\n plugin_version?: string;\n resource_ids: string[];\n metadata: ImportedSnapshotMetadata;\n}): ImportedSnapshot {\n const db = getDb();\n const snapshot: ImportedSnapshot = {\n id: ulid(),\n source_kind: input.source_kind,\n source_label: input.source_label,\n plugin_name: input.plugin_name,\n plugin_version: input.plugin_version,\n resource_ids: input.resource_ids,\n metadata: input.metadata,\n created_at: new Date().toISOString(),\n };\n\n db.prepare(\n `INSERT INTO imported_snapshots (\n id,\n source_kind,\n source_label,\n plugin_name,\n plugin_version,\n resource_ids,\n metadata,\n created_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,\n ).run(\n snapshot.id,\n snapshot.source_kind,\n snapshot.source_label,\n snapshot.plugin_name,\n snapshot.plugin_version ?? null,\n JSON.stringify(snapshot.resource_ids),\n JSON.stringify(snapshot.metadata),\n snapshot.created_at,\n );\n\n return snapshot;\n}\n\nexport function listImportedSnapshots(): ImportedSnapshot[] {\n const db = getDb();\n const rows = db\n .prepare(\n \"SELECT * FROM imported_snapshots ORDER BY created_at DESC, id DESC\",\n )\n .all() as ImportedSnapshotRow[];\n return rows.map(rowToImportedSnapshot);\n}\n\nexport function getImportedSnapshot(snapshotId: string): ImportedSnapshot | undefined {\n const db = getDb();\n const row = db\n .prepare(\"SELECT * FROM imported_snapshots WHERE id = ?\")\n .get(snapshotId) as ImportedSnapshotRow | undefined;\n return row ? rowToImportedSnapshot(row) : undefined;\n}\n\nexport function recordImportedSnapshotInstall(input: {\n snapshot_id: string;\n platform_id: string;\n files: string[];\n}): ImportedSnapshotInstall {\n const db = getDb();\n const install: ImportedSnapshotInstall = {\n ...input,\n installed_at: new Date().toISOString(),\n };\n\n db.prepare(\n `INSERT INTO imported_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\n return install;\n}\n\nexport function removeImportedSnapshotOwnershipForFiles(\n filePaths: string[],\n excludeSnapshotId?: string,\n): void {\n if (filePaths.length === 0) return;\n\n const db = getDb();\n const rows = db\n .prepare(\n `SELECT snapshot_id, platform_id, files, installed_at\n FROM imported_snapshot_installs`,\n )\n .all() as ImportedSnapshotInstallRow[];\n const fileSet = new Set(filePaths);\n const now = new Date().toISOString();\n\n for (const row of rows) {\n if (excludeSnapshotId && row.snapshot_id === excludeSnapshotId) continue;\n\n const files = JSON.parse(row.files) as string[];\n const remainingFiles = files.filter((file) => !fileSet.has(file));\n if (remainingFiles.length === files.length) continue;\n\n if (remainingFiles.length === 0) {\n db.prepare(\n `DELETE FROM imported_snapshot_installs\n WHERE snapshot_id = ? AND platform_id = ?`,\n ).run(row.snapshot_id, row.platform_id);\n continue;\n }\n\n db.prepare(\n `UPDATE imported_snapshot_installs\n SET files = ?, installed_at = ?\n WHERE snapshot_id = ? AND platform_id = ?`,\n ).run(\n JSON.stringify(remainingFiles),\n now,\n row.snapshot_id,\n row.platform_id,\n );\n }\n}\n\nexport function listImportedSnapshotInstalls(\n snapshotId: string,\n): ImportedSnapshotInstall[] {\n const db = getDb();\n const rows = db\n .prepare(\n `SELECT snapshot_id, platform_id, files, installed_at\n FROM imported_snapshot_installs\n WHERE snapshot_id = ?\n ORDER BY installed_at DESC, platform_id ASC`,\n )\n .all(snapshotId) as ImportedSnapshotInstallRow[];\n return rows.map(rowToImportedSnapshotInstall);\n}\n\nexport function findImportedSnapshotOwnersByFile(\n filePath: string,\n): ImportedSnapshotFileOwner[] {\n const db = getDb();\n const rows = db\n .prepare(\n `SELECT installs.snapshot_id, installs.platform_id, snapshots.plugin_name, snapshots.plugin_version\n FROM imported_snapshot_installs installs\n JOIN imported_snapshots snapshots ON snapshots.id = installs.snapshot_id`,\n )\n .all() as Array<{\n snapshot_id: string;\n platform_id: string;\n plugin_name: string;\n plugin_version: string | null;\n }>;\n\n return rows.filter((row) => {\n const install = db\n .prepare(\n `SELECT files\n FROM imported_snapshot_installs\n WHERE snapshot_id = ? AND platform_id = ?`,\n )\n .get(row.snapshot_id, row.platform_id) as { files: string } | undefined;\n if (!install) return false;\n const files = JSON.parse(install.files) as string[];\n return files.includes(filePath);\n }).map((row) => ({\n snapshot_id: row.snapshot_id,\n platform_id: row.platform_id,\n plugin_name: row.plugin_name,\n plugin_version: row.plugin_version ?? undefined,\n }));\n}\n","import { join } from \"node:path\";\nimport { BaseSerializer } from \"./base-serializer.js\";\nimport { getPlatform } from \"./registry.js\";\nimport { listInstalledPluginPinCreateInputs } from \"../plugins/claude-installed.js\";\nimport { emitHostPluginTrees } from \"../services/host-plugin-serialize.js\";\nimport { serializedAgentDocument } from \"../services/agent-bridge.js\";\nimport { buildHooksJson, scanHooksFile } from \"../services/hook-serialization.js\";\nimport { localMcpCreateInputsFromDocument } from \"../services/claude-local-mcp.js\";\nimport { parseMcpServersDocument } from \"../services/mcp-config-bridge.js\";\nimport {\n CLAUDE_USER_JSON_RELATIVE,\n mergeClaudeSettingsContent,\n mergeClaudeUserJsonContent,\n} from \"../services/merged-host-config.js\";\nimport { filterInstructionsForTargetPath } from \"../services/instruction-target.js\";\nimport { resolveHomeRoot } from \"../utils/home-root.js\";\nimport type {\n AgentMetadata,\n HookMetadata,\n PlatformDefinition,\n ResourceCreateInput,\n Resource,\n SerializedFile,\n RuleMetadata,\n McpServerMetadata,\n ModelConfigMetadata,\n PermissionMetadata,\n SerializeOptions,\n} from \"../types.js\";\n\nconst CLAUDE_PERMISSION_ACTIONS = [\"allow\", \"deny\", \"ask\"] as const;\n\nfunction claudePermissionInputs(\n settings: {\n permissions?: {\n allow?: string[];\n deny?: string[];\n ask?: string[];\n };\n },\n source: string,\n): ResourceCreateInput[] {\n const resources: ResourceCreateInput[] = [];\n for (const action of CLAUDE_PERMISSION_ACTIONS) {\n for (const pattern of settings.permissions?.[action] ?? []) {\n resources.push({\n type: \"permission\",\n name: `${action}-${pattern}`,\n description: \"\",\n content: \"\",\n source,\n metadata: { action, pattern } satisfies PermissionMetadata,\n });\n }\n }\n return resources;\n}\n\nfunction claudeModelConfigInput(\n settings: { model?: unknown },\n source: string,\n): ResourceCreateInput[] {\n if (typeof settings.model !== \"string\" || settings.model.trim().length === 0) {\n return [];\n }\n return [\n {\n type: \"model_config\",\n name: \"default\",\n description: \"\",\n content: \"\",\n source,\n metadata: { model: settings.model } satisfies ModelConfigMetadata,\n },\n ];\n}\n\nfunction emitClaudeMcpServerEntry(meta: McpServerMetadata): Record<string, unknown> {\n const entry: Record<string, unknown> = {};\n if (meta.transport === \"http\" && meta.url) {\n entry[\"type\"] = \"http\";\n entry[\"url\"] = meta.url;\n if (meta.headers && Object.keys(meta.headers).length > 0) {\n entry[\"headers\"] = meta.headers;\n }\n } else {\n if (meta.command) entry[\"command\"] = meta.command;\n if (meta.args) entry[\"args\"] = meta.args;\n }\n if (meta.env && Object.keys(meta.env).length > 0) {\n entry[\"env\"] = meta.env;\n }\n return entry;\n}\n\nexport class ClaudeCodeSerializer extends BaseSerializer {\n readonly platformId = \"claude-code\";\n readonly platform: PlatformDefinition;\n\n constructor() {\n super();\n const p = getPlatform(\"claude-code\");\n if (!p) throw new Error(\"claude-code platform not found in registry\");\n this.platform = p;\n }\n\n // ── Scan ────────────────────────────────────────────────────────────\n\n async scan(projectRoot: string): Promise<ResourceCreateInput[]> {\n const resources: ResourceCreateInput[] = [];\n\n // 1. Instructions: CLAUDE.md or .claude/CLAUDE.md\n for (const path of [\"CLAUDE.md\", \".claude/CLAUDE.md\"]) {\n const content = this.readFile(join(projectRoot, path));\n if (content) {\n resources.push(\n this.makeResource(\n \"instruction\",\n \"claude-instructions\",\n content,\n path,\n ),\n );\n break; // only take the first found\n }\n }\n\n // 2. Rules: .claude/rules/*.md\n const rulesDir = join(projectRoot, \".claude\", \"rules\");\n for (const file of this.listDir(rulesDir)) {\n if (!file.endsWith(\".md\")) continue;\n const raw = this.readFile(join(rulesDir, file));\n if (!raw) continue;\n\n const parsed = this.tryParseFrontmatter(raw);\n if (!parsed) continue;\n\n const { data, content } = parsed;\n const name = file.replace(/\\.md$/, \"\");\n const metadata: RuleMetadata = {\n globs: Array.isArray(data[\"paths\"]) ? (data[\"paths\"] as string[]) : [],\n always_apply:\n !data[\"paths\"] || (data[\"paths\"] as string[]).length === 0,\n };\n\n resources.push(\n this.makeResource(\n \"rule\",\n name,\n content.trim(),\n `.claude/rules/${file}`,\n metadata,\n ),\n );\n }\n\n // 3. Skills: .claude/skills/*/SKILL.md\n resources.push(...this.scanSkillsDir(projectRoot, \".claude/skills\"));\n\n // 4. MCP servers: project-scope .mcp.json (not ~/.claude.json local scope)\n const projectMcp = this.scanMcpServersAt(\n join(projectRoot, \".mcp.json\"),\n \".mcp.json\",\n );\n resources.push(...projectMcp);\n\n // Local-scope MCP for this project lives in ~/.claude.json projects[absPath].\n // Inventory/scan only: serialize never promotes these into .mcp.json.\n const homeClaudeJson = this.readFile(\n join(resolveHomeRoot(), CLAUDE_USER_JSON_RELATIVE),\n );\n if (homeClaudeJson) {\n try {\n resources.push(\n ...localMcpCreateInputsFromDocument(\n JSON.parse(homeClaudeJson) as unknown,\n projectRoot,\n new Set(projectMcp.map((resource) => resource.name)),\n ),\n );\n } catch {\n // invalid JSON: skip\n }\n }\n\n // 5. Settings: .claude/settings.json (permissions, hooks, env)\n const settingsContent = this.readFile(\n join(projectRoot, \".claude\", \"settings.json\"),\n );\n if (settingsContent) {\n try {\n const settings = JSON.parse(settingsContent) as {\n permissions?: { allow?: string[]; deny?: string[]; ask?: string[] };\n env?: Record<string, string>;\n hooks?: Record<string, unknown>;\n model?: unknown;\n };\n\n resources.push(\n ...claudePermissionInputs(settings, \".claude/settings.json\"),\n ...claudeModelConfigInput(settings, \".claude/settings.json\"),\n );\n\n // Env vars\n for (const [key, value] of Object.entries(settings.env ?? {})) {\n resources.push(\n this.makeResource(\"env_var\", key, \"\", \".claude/settings.json\", {\n key,\n value,\n }),\n );\n }\n\n // Hooks\n resources.push(\n ...scanHooksFile(\n join(projectRoot, \".claude\", \"settings.json\"),\n \".claude/settings.json\",\n ),\n );\n } catch {\n // invalid JSON: skip\n }\n }\n\n // 6. Agents: .claude/agents/*.md\n resources.push(\n ...this.scanAgentFilesAt(\n join(projectRoot, \".claude\", \"agents\"),\n \".claude/agents/\",\n [\".md\"],\n ),\n );\n\n // 7. Commands: .claude/commands/*.md\n const commandsDir = join(projectRoot, \".claude\", \"commands\");\n for (const file of this.listDir(commandsDir)) {\n if (!file.endsWith(\".md\")) continue;\n const content = this.readFile(join(commandsDir, file));\n if (!content) continue;\n const name = file.replace(/\\.md$/, \"\");\n resources.push(\n this.makeResource(\"command\", name, content, `.claude/commands/${file}`),\n );\n }\n\n // Cast through the model plugin (add ids + timestamps on import)\n return resources;\n }\n\n async scanGlobal(homeRoot: string): Promise<ResourceCreateInput[]> {\n const resources: ResourceCreateInput[] = [];\n\n const instructionsPath = join(homeRoot, \".claude\", \"CLAUDE.md\");\n const instructionsContent = this.readFile(instructionsPath);\n if (instructionsContent) {\n resources.push(\n this.makeResource(\n \"instruction\",\n \"claude-instructions\",\n instructionsContent,\n \"~/.claude/CLAUDE.md\",\n ),\n );\n }\n\n const rulesDir = join(homeRoot, \".claude\", \"rules\");\n for (const file of this.listDir(rulesDir)) {\n if (!file.endsWith(\".md\")) continue;\n const raw = this.readFile(join(rulesDir, file));\n if (!raw) continue;\n\n const parsed = this.tryParseFrontmatter(raw);\n if (!parsed) continue;\n\n const { data, content } = parsed;\n const name = file.replace(/\\.md$/, \"\");\n const metadata: RuleMetadata = {\n globs: Array.isArray(data[\"paths\"]) ? (data[\"paths\"] as string[]) : [],\n always_apply:\n !data[\"paths\"] || (data[\"paths\"] as string[]).length === 0,\n };\n\n resources.push(\n this.makeResource(\n \"rule\",\n name,\n content.trim(),\n `~/.claude/rules/${file}`,\n metadata,\n ),\n );\n }\n\n resources.push(\n ...this.scanSkillsDirAt(\n join(homeRoot, \".claude\", \"skills\"),\n \"~/.claude/skills\",\n ),\n );\n\n // User-scope MCP only at top-level mcpServers. Local-scope servers live\n // under projects[<absPath>].mcpServers and are inventoried separately.\n const userJsonPath = join(homeRoot, CLAUDE_USER_JSON_RELATIVE);\n const userJsonContent = this.readFile(userJsonPath);\n const userMcp = this.scanMcpServersAt(userJsonPath, \"~/.claude.json\");\n resources.push(...userMcp);\n if (userJsonContent) {\n try {\n resources.push(\n ...localMcpCreateInputsFromDocument(\n JSON.parse(userJsonContent) as unknown,\n undefined,\n new Set(userMcp.map((resource) => resource.name)),\n ),\n );\n } catch {\n // invalid JSON: skip\n }\n }\n\n const settingsContent = this.readFile(\n join(homeRoot, \".claude\", \"settings.json\"),\n );\n if (settingsContent) {\n try {\n const settings = JSON.parse(settingsContent) as {\n permissions?: { allow?: string[]; deny?: string[]; ask?: string[] };\n env?: Record<string, string>;\n model?: unknown;\n };\n\n resources.push(\n ...claudePermissionInputs(settings, \"~/.claude/settings.json\"),\n ...claudeModelConfigInput(settings, \"~/.claude/settings.json\"),\n );\n\n for (const [key, value] of Object.entries(settings.env ?? {})) {\n resources.push(\n this.makeResource(\"env_var\", key, \"\", \"~/.claude/settings.json\", {\n key,\n value,\n }),\n );\n }\n\n resources.push(\n ...scanHooksFile(\n join(homeRoot, \".claude\", \"settings.json\"),\n \"~/.claude/settings.json\",\n ),\n );\n } catch {\n // invalid JSON: skip\n }\n }\n\n resources.push(\n ...this.scanAgentFilesAt(\n join(homeRoot, \".claude\", \"agents\"),\n \"~/.claude/agents/\",\n [\".md\"],\n ),\n );\n\n const commandsDir = join(homeRoot, \".claude\", \"commands\");\n for (const file of this.listDir(commandsDir)) {\n if (!file.endsWith(\".md\")) continue;\n const content = this.readFile(join(commandsDir, file));\n if (!content) continue;\n const name = file.replace(/\\.md$/, \"\");\n resources.push(\n this.makeResource(\n \"command\",\n name,\n content,\n `~/.claude/commands/${file}`,\n ),\n );\n }\n\n resources.push(...listInstalledPluginPinCreateInputs(homeRoot));\n\n return resources;\n }\n\n private scanMcpServersAt(\n configPath: string,\n displayPath: string,\n ): ResourceCreateInput[] {\n const resources: ResourceCreateInput[] = [];\n const mcpContent = this.readFile(configPath);\n if (!mcpContent) {\n return resources;\n }\n\n try {\n const document = JSON.parse(mcpContent) as unknown;\n for (const [name, metadata] of Object.entries(\n parseMcpServersDocument(document),\n )) {\n resources.push(\n this.makeResource(\"mcp_server\", name, \"\", displayPath, metadata),\n );\n }\n } catch {\n // invalid JSON: skip\n }\n\n return resources;\n }\n\n // ── Serialize ───────────────────────────────────────────────────────\n\n async serialize(\n resources: Resource[],\n projectRoot: string,\n options: SerializeOptions = {},\n ): Promise<SerializedFile[]> {\n const files: SerializedFile[] = [];\n const target = options.target ?? \"project\";\n const serializeOptions: SerializeOptions = { ...options, projectRoot };\n const targetPaths = this.getTargetPaths(target);\n const instructionsPath =\n this.toTargetRelativePath(targetPaths.instructions, target) ??\n (target === \"project\" ? \"CLAUDE.md\" : undefined);\n const rulesPath = this.toTargetRelativePath(targetPaths.rules, target);\n const skillsPath = this.toTargetRelativePath(targetPaths.skills, target);\n const mcpPath = this.toTargetRelativePath(targetPaths.mcp, target);\n const settingsPath = this.toTargetRelativePath(targetPaths.settings, target);\n const agentsPath = this.toTargetRelativePath(targetPaths.agents, target);\n const commandsPath = this.toTargetRelativePath(targetPaths.commands, target);\n\n // Group resources by type\n const byType = new Map<string, Resource[]>();\n for (const r of resources) {\n const list = byType.get(r.type) ?? [];\n list.push(r);\n byType.set(r.type, list);\n }\n\n // Instructions → CLAUDE.md (skip instructions imported from other harness files)\n const instructions = filterInstructionsForTargetPath(\n byType.get(\"instruction\") ?? [],\n instructionsPath ? [instructionsPath, \"CLAUDE.md\"] : [\"CLAUDE.md\"],\n );\n if (instructions.length > 0 && instructionsPath) {\n const combined = instructions.map((r) => r.content).join(\"\\n\\n\");\n files.push({ path: instructionsPath, content: combined });\n }\n\n // Rules → .claude/rules/{name}.md\n for (const r of byType.get(\"rule\") ?? []) {\n if (!rulesPath) continue;\n const meta = r.metadata as RuleMetadata;\n const frontmatter: Record<string, unknown> = {};\n if (meta.globs.length > 0) {\n frontmatter[\"paths\"] = meta.globs;\n }\n const content = this.emitFrontmatter(frontmatter, r.content);\n files.push({ path: `${rulesPath}${r.name}.md`, content });\n }\n\n // Skills → .claude/skills/{name}/SKILL.md\n for (const r of byType.get(\"skill\") ?? []) {\n if (!skillsPath) continue;\n files.push(\n ...this.emitSkillWithAuxiliary(\n r,\n `${skillsPath}${r.name}/SKILL.md`,\n serializeOptions,\n ),\n );\n }\n\n // MCP servers → project `.mcp.json` or user `~/.claude.json`\n const mcpServers = this.mcpServersForTarget(\n byType.get(\"mcp_server\") ?? [],\n mcpPath,\n );\n if (mcpServers.length > 0 && mcpPath) {\n const mcpConfig: Record<string, Record<string, unknown>> = {};\n for (const r of mcpServers) {\n mcpConfig[r.name] = emitClaudeMcpServerEntry(r.metadata as McpServerMetadata);\n }\n const generated = JSON.stringify({ mcpServers: mcpConfig }, null, 2);\n const existing = this.readFile(join(projectRoot, mcpPath));\n files.push({\n path: mcpPath,\n content: mergeClaudeUserJsonContent(existing, generated),\n });\n }\n\n // Permissions + env + hooks + model → .claude/settings.json\n const permissions = byType.get(\"permission\") ?? [];\n const envVars = byType.get(\"env_var\") ?? [];\n const hooks = byType.get(\"hook\") ?? [];\n const modelConfigs = byType.get(\"model_config\") ?? [];\n if (\n (permissions.length > 0 ||\n envVars.length > 0 ||\n hooks.length > 0 ||\n modelConfigs.length > 0) &&\n settingsPath\n ) {\n const settings: Record<string, unknown> = {};\n if (permissions.length > 0) {\n const allow: string[] = [];\n const deny: string[] = [];\n const ask: string[] = [];\n for (const r of permissions) {\n const meta = r.metadata as PermissionMetadata;\n switch (meta.action) {\n case \"allow\":\n allow.push(meta.pattern);\n break;\n case \"deny\":\n deny.push(meta.pattern);\n break;\n case \"ask\":\n ask.push(meta.pattern);\n break;\n default: {\n const neverAction: never = meta.action;\n throw new Error(`Unsupported permission action: ${String(neverAction)}`);\n }\n }\n }\n if (allow.length > 0 || deny.length > 0 || ask.length > 0) {\n settings[\"permissions\"] = {\n ...(allow.length > 0 ? { allow } : {}),\n ...(deny.length > 0 ? { deny } : {}),\n ...(ask.length > 0 ? { ask } : {}),\n };\n }\n }\n if (envVars.length > 0) {\n const env: Record<string, string> = {};\n for (const r of envVars) {\n const meta = r.metadata as { key: string; value: string };\n env[meta.key] = meta.value;\n }\n settings[\"env\"] = env;\n }\n if (hooks.length > 0) {\n settings[\"hooks\"] = buildHooksJson(\n hooks.map((r) => ({\n ...(r.metadata as HookMetadata),\n name: r.name,\n })),\n ).hooks;\n }\n if (modelConfigs.length > 0) {\n const metadata = modelConfigs[0]?.metadata as ModelConfigMetadata;\n if (metadata?.model) {\n settings[\"model\"] = metadata.model;\n }\n }\n if (Object.keys(settings).length > 0) {\n const generated = JSON.stringify(settings, null, 2);\n const existing = this.readFile(join(projectRoot, settingsPath));\n files.push({\n path: settingsPath,\n content: mergeClaudeSettingsContent(existing, generated),\n });\n }\n }\n\n // Agents → .claude/agents/{name}.md\n for (const r of byType.get(\"agent\") ?? []) {\n if (!agentsPath) continue;\n const content = serializedAgentDocument(\n {\n name: r.name,\n description: r.description,\n content: r.content,\n metadata: r.metadata as AgentMetadata,\n },\n \"claude\",\n );\n files.push({ path: `${agentsPath}${r.name}.md`, content });\n }\n\n // Commands → .claude/commands/{name}.md\n for (const r of byType.get(\"command\") ?? []) {\n if (!commandsPath) continue;\n files.push({ path: `${commandsPath}${r.name}.md`, content: r.content });\n }\n\n // Claude Code loads host plugins from ~/.claude/plugins/installed_plugins.json\n // plus enabledPlugins keyed plugin@marketplace\n // (https://code.claude.com/docs/en/plugins/loading). Emit that registry at\n // both global and project apply. Project apply from HOME is the usual\n // `ht apply <plugin>` path; Claude does not also load standalone skill\n // copies of the same plugin.\n return emitHostPluginTrees(byType.get(\"plugin\") ?? [], {\n layout: \"claude-code\",\n homeRoot: options.projectRoot ?? projectRoot,\n files,\n surfaceWarnings: options?.surfaceWarnings,\n });\n }\n}\n","import { readFileSync, existsSync, readdirSync, statSync } from \"node:fs\";\nimport { dirname, join, relative, sep } from \"node:path\";\nimport matter from \"gray-matter\";\nimport { normalizeAgentInput } from \"../services/agent-bridge.js\";\nimport { mergeSkillMarkdown } from \"../services/merge-skill-markdown.js\";\nimport { emitSkillAuxiliaryFiles, skillMetadataFromDir } from \"../services/skill-auxiliary.js\";\nimport { scanSkillCommandMetadataResources } from \"../services/skill-command-metadata.js\";\nimport { filterMcpServersForTargetPath } from \"../services/mcp-target.js\";\nimport type {\n PlatformSerializer,\n Resource,\n ResourceCreateInput,\n ResourceMetadata,\n SerializedFile,\n PlatformDefinition,\n ResourceType,\n PlatformPaths,\n SerializerTarget,\n SerializeOptions,\n} from \"../types.js\";\n\n/**\n * Base class for platform serializers.\n * Provides common filesystem helpers: subclasses implement scan() and serialize().\n */\nexport abstract class BaseSerializer implements PlatformSerializer {\n abstract readonly platformId: string;\n abstract readonly platform: PlatformDefinition;\n\n abstract scan(projectRoot: string): Promise<ResourceCreateInput[]>;\n async scanGlobal(homeRoot: string): Promise<ResourceCreateInput[]> {\n return this.scan(homeRoot);\n }\n\n abstract serialize(\n resources: Resource[],\n projectRoot: string,\n options?: SerializeOptions,\n ): Promise<SerializedFile[]>;\n\n // ── Filesystem helpers ──────────────────────────────────────────────\n\n protected readFile(filePath: string): string | undefined {\n try {\n return readFileSync(filePath, \"utf-8\");\n } catch {\n return undefined;\n }\n }\n\n protected fileExists(filePath: string): boolean {\n return existsSync(filePath);\n }\n\n protected listDir(dirPath: string): string[] {\n try {\n return readdirSync(dirPath);\n } catch {\n return [];\n }\n }\n\n protected isDirectory(filePath: string): boolean {\n try {\n return statSync(filePath).isDirectory();\n } catch {\n return false;\n }\n }\n\n protected relativePath(projectRoot: string, filePath: string): string {\n return relative(projectRoot, filePath);\n }\n\n protected resolveHomePath(homeRoot: string, configuredPath: string): string {\n return configuredPath.startsWith(\"~/\")\n ? join(homeRoot, configuredPath.slice(2))\n : join(homeRoot, configuredPath);\n }\n\n protected getTargetPaths(target: SerializerTarget = \"project\"): PlatformPaths {\n return target === \"global\" ? this.platform.globalPaths : this.platform.projectPaths;\n }\n\n /** MCP servers that belong on this harness MCP path (path-matched + portable). */\n protected mcpServersForTarget(\n resources: Resource[],\n targetMcpPath: string | undefined,\n ): Resource[] {\n return filterMcpServersForTargetPath(\n resources,\n targetMcpPath,\n \"\",\n this.platformId,\n );\n }\n\n protected toTargetRelativePath(\n configuredPath: string | undefined,\n target: SerializerTarget = \"project\",\n ): string | undefined {\n if (!configuredPath) return undefined;\n if (target === \"global\" && configuredPath.startsWith(\"~/\")) {\n return configuredPath.slice(2);\n }\n return configuredPath;\n }\n\n protected prefixedRelativePath(\n rootPath: string,\n filePath: string,\n prefix: string,\n ): string {\n const relativePath = relative(rootPath, filePath).split(sep).join(\"/\");\n const normalizedPrefix = prefix.replace(/\\/$/, \"\");\n\n if (!relativePath) return normalizedPrefix;\n return `${normalizedPrefix}/${relativePath}`;\n }\n\n // ── Frontmatter helpers ─────────────────────────────────────────────\n\n protected parseFrontmatter(content: string): {\n data: Record<string, unknown>;\n content: string;\n } {\n const parsed = matter(content);\n return {\n data: parsed.data as Record<string, unknown>,\n content: parsed.content,\n };\n }\n\n protected tryParseFrontmatter(content: string):\n | {\n data: Record<string, unknown>;\n content: string;\n }\n | undefined {\n try {\n const parsed = this.parseFrontmatter(content);\n\n // gray-matter can return the original content unchanged when a file starts\n // with malformed frontmatter. Treat that as an invalid parse so scanners\n // skip the broken resource instead of importing raw frontmatter text.\n if (content.startsWith(\"---\") && parsed.content === content) {\n return undefined;\n }\n\n return parsed;\n } catch {\n return undefined;\n }\n }\n\n protected emitFrontmatter(\n data: Record<string, unknown>,\n content: string,\n ): string {\n // Only emit frontmatter if there are non-empty fields\n const nonEmpty = Object.entries(data).filter(\n ([, v]) => v !== undefined && v !== null && v !== \"\",\n );\n if (nonEmpty.length === 0) return content;\n return matter.stringify(content, Object.fromEntries(nonEmpty));\n }\n\n // ── Resource builder helpers ────────────────────────────────────────\n\n protected makeResource(\n type: ResourceType,\n name: string,\n content: string,\n source: string,\n metadata: ResourceMetadata = {},\n description = \"\",\n ): ResourceCreateInput {\n return { type, name, description, content, metadata, source };\n }\n\n protected scanAgentFilesAt(\n fullPath: string,\n displayPath: string,\n extensions: string[],\n ): ResourceCreateInput[] {\n const resources: ResourceCreateInput[] = [];\n if (!displayPath.endsWith(\"/\")) return resources;\n\n for (const file of this.listDir(fullPath)) {\n if (!extensions.some((ext) => file.endsWith(ext))) continue;\n const raw = this.readFile(join(fullPath, file));\n if (!raw) continue;\n const source = `${displayPath}${file}`;\n const fallbackName = file.replace(/\\.(agent\\.)?(md|toml)$/, \"\");\n const normalized = normalizeAgentInput({\n name: fallbackName,\n content: raw,\n source,\n });\n if (normalized) {\n resources.push(\n this.makeResource(\n \"agent\",\n normalized.name,\n raw,\n source,\n normalized.metadata,\n normalized.description,\n ),\n );\n continue;\n }\n resources.push(this.makeResource(\"agent\", fallbackName, raw, source));\n }\n\n return resources;\n }\n\n protected scanSkillsDir(\n projectRoot: string,\n skillsDir: string,\n ): ResourceCreateInput[] {\n const fullPath = join(projectRoot, skillsDir);\n const sourcePrefix = skillsDir.replace(/\\/$/, \"\");\n const resources = this.scanSkillsDirAt(fullPath, sourcePrefix);\n\n if (!this.isDirectory(fullPath)) {\n return resources;\n }\n\n for (const entry of this.listDir(fullPath)) {\n const entryPath = join(fullPath, entry);\n const skillMd = join(entryPath, \"SKILL.md\");\n if (!this.isDirectory(entryPath) || !this.fileExists(skillMd)) continue;\n\n const raw = this.readFile(skillMd);\n if (!raw) continue;\n\n const parsed = this.tryParseFrontmatter(raw);\n if (!parsed) continue;\n\n const skillName = (parsed.data[\"name\"] as string) || entry;\n resources.push(\n ...scanSkillCommandMetadataResources({\n skillDir: entryPath,\n skillName,\n rootPath: projectRoot,\n relativePath: (rootPath, filePath) =>\n relative(rootPath, filePath).split(sep).join(\"/\"),\n }),\n );\n }\n\n return resources;\n }\n\n protected scanSkillsDirAt(\n fullPath: string,\n sourcePrefix: string,\n ): ResourceCreateInput[] {\n if (!this.isDirectory(fullPath)) return [];\n\n const resources: ResourceCreateInput[] = [];\n\n for (const entry of this.listDir(fullPath)) {\n const entryPath = join(fullPath, entry);\n const skillMd = join(entryPath, \"SKILL.md\");\n\n if (this.isDirectory(entryPath) && this.fileExists(skillMd)) {\n const raw = this.readFile(skillMd);\n if (!raw) continue;\n\n const parsed = this.tryParseFrontmatter(raw);\n if (!parsed) continue;\n\n const { data } = parsed;\n resources.push(\n this.makeResource(\n \"skill\",\n (data[\"name\"] as string) || entry,\n raw,\n this.prefixedRelativePath(fullPath, skillMd, sourcePrefix),\n skillMetadataFromDir(entryPath),\n (data[\"description\"] as string) || \"\",\n ),\n );\n }\n }\n\n return resources;\n }\n\n /**\n * Append scanned skills, skipping names already seen so native + compat\n * trees do not double-count the same skill.\n */\n protected appendUniqueSkills(\n resources: ResourceCreateInput[],\n seenSkillNames: Set<string>,\n incoming: ResourceCreateInput[],\n ): void {\n for (const resource of incoming) {\n if (resource.type !== \"skill\") continue;\n if (seenSkillNames.has(resource.name)) continue;\n seenSkillNames.add(resource.name);\n resources.push(resource);\n }\n }\n\n protected resolveSkillSourceDir(\n resource: Resource,\n sourceRoot: string,\n ): string | undefined {\n const source = resource.source.replace(/\\\\/g, \"/\");\n const relativeSource = source.startsWith(\"~/\") ? source.slice(2) : source;\n const candidates = [\n dirname(join(sourceRoot, resource.source)),\n dirname(join(sourceRoot, relativeSource)),\n ];\n for (const dir of candidates) {\n if (existsSync(join(dir, \"SKILL.md\"))) {\n return dir;\n }\n }\n return undefined;\n }\n\n protected emitSkillWithAuxiliary(\n resource: Resource,\n skillMdPath: string,\n options: SerializeOptions,\n ): SerializedFile[] {\n const fm: Record<string, unknown> = {\n name: resource.name,\n description: resource.description,\n };\n const generated = resource.content.startsWith(\"---\")\n ? resource.content\n : this.emitFrontmatter(fm, resource.content);\n const liveRoot = options.projectRoot;\n const mergeLive = options.mergeLiveSkillMarkdown !== false;\n const live = mergeLive && liveRoot\n ? this.readFile(join(liveRoot, skillMdPath))\n : undefined;\n const files: SerializedFile[] = [\n {\n path: skillMdPath,\n content: mergeLive ? mergeSkillMarkdown(live, generated) : generated,\n },\n ];\n\n const sourceRoots = [options.skillSourceRoot, options.projectRoot].filter(\n (root): root is string => typeof root === \"string\" && root.length > 0,\n );\n if (sourceRoots.length === 0) {\n return files;\n }\n\n let sourceSkillDir: string | undefined;\n for (const root of sourceRoots) {\n const resolved = this.resolveSkillSourceDir(resource, root);\n if (resolved) {\n sourceSkillDir = resolved;\n break;\n }\n }\n if (!sourceSkillDir) return files;\n\n const targetPrefix = skillMdPath.replace(/\\/SKILL\\.md$/, \"\");\n files.push(\n ...emitSkillAuxiliaryFiles({\n sourceSkillDir,\n targetPrefix,\n }),\n );\n return files;\n }\n}\n","import matter from \"gray-matter\";\n\nfunction normalizeNewlines(text: string): string {\n return text.replace(/\\r\\n/g, \"\\n\");\n}\n\nfunction generatedIsLiveSubset(live: string, generated: string): boolean {\n const liveNorm = normalizeNewlines(live);\n const generatedNorm = normalizeNewlines(generated).replace(/\\s+$/u, \"\");\n if (generatedNorm.length === 0) {\n return true;\n }\n if (liveNorm.startsWith(generatedNorm) || liveNorm.includes(generatedNorm)) {\n return true;\n }\n const liveParsed = matter(liveNorm);\n const generatedParsed = matter(generatedNorm);\n const generatedBody = generatedParsed.content.trim();\n if (generatedBody.length === 0) {\n return true;\n }\n return liveParsed.content.includes(generatedBody);\n}\n\n/**\n * Merge a thin profile SKILL.md snapshot into a richer live file:\n * extra live frontmatter keys and body are kept when the generated file is a\n * subset (prefix / contained body). Profile name/description overlay live.\n * A true body rewrite (generated body not contained in live) replaces the body.\n */\nexport function mergeSkillMarkdown(\n live: string | null | undefined,\n generated: string,\n): string {\n if (!live) {\n return generated;\n }\n if (normalizeNewlines(live) === normalizeNewlines(generated)) {\n return live;\n }\n const liveParsed = matter(normalizeNewlines(live));\n const generatedParsed = matter(normalizeNewlines(generated));\n const data: Record<string, unknown> = {\n ...(liveParsed.data as Record<string, unknown>),\n ...(generatedParsed.data as Record<string, unknown>),\n };\n const keepLiveBody = generatedIsLiveSubset(live, generated);\n const body = keepLiveBody ? liveParsed.content : generatedParsed.content;\n const nonEmpty = Object.fromEntries(\n Object.entries(data).filter(\n ([, value]) => value !== undefined && value !== null && value !== \"\",\n ),\n );\n if (Object.keys(nonEmpty).length === 0) {\n return body.startsWith(\"\\n\") ? body.slice(1) : body;\n }\n return matter.stringify(body.replace(/^\\n/, \"\"), nonEmpty);\n}\n","import { resolve } from \"node:path\";\nimport type { McpServerMetadata, ResourceCreateInput } from \"../types.js\";\nimport { parseMcpServersDocument } from \"./mcp-config-bridge.js\";\n\nexport const CLAUDE_USER_MCP_SOURCE = \"~/.claude.json\";\nexport const CLAUDE_LOCAL_MCP_SOURCE_PREFIX = \"~/.claude.json#local:\";\n\nexport function claudeLocalMcpSource(projectAbsPath: string): string {\n return `${CLAUDE_LOCAL_MCP_SOURCE_PREFIX}${resolve(projectAbsPath)}`;\n}\n\nexport function parseClaudeLocalMcpProjectPath(\n source: string | undefined,\n): string | null {\n if (!source?.startsWith(CLAUDE_LOCAL_MCP_SOURCE_PREFIX)) {\n return null;\n }\n const rest = source.slice(CLAUDE_LOCAL_MCP_SOURCE_PREFIX.length);\n return rest.length > 0 ? rest : null;\n}\n\nexport function isClaudeLocalMcpSource(source: string | undefined): boolean {\n return parseClaudeLocalMcpProjectPath(source) !== null;\n}\n\nexport function isClaudeLocalMcpResource(resource: {\n source?: string;\n metadata?: unknown;\n}): boolean {\n if (isClaudeLocalMcpSource(resource.source)) {\n return true;\n }\n const metadata = resource.metadata;\n if (\n metadata !== null\n && typeof metadata === \"object\"\n && !Array.isArray(metadata)\n && (metadata as { claude_mcp_scope?: unknown }).claude_mcp_scope === \"local\"\n ) {\n return true;\n }\n return false;\n}\n\n/** Strip the local-scope fragment so inventory groups under `~/.claude.json`. */\nexport function inventorySourceForMatching(source: string): string {\n return isClaudeLocalMcpSource(source) ? CLAUDE_USER_MCP_SOURCE : source;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport interface ClaudeLocalMcpServer {\n projectPath: string;\n name: string;\n metadata: McpServerMetadata;\n}\n\nfunction projectKeysMatch(left: string, right: string): boolean {\n return resolve(left) === resolve(right);\n}\n\n/**\n * Local-scope servers from `projects[<absPath>].mcpServers`.\n * When `projectRoot` is set, only that project's entry is returned.\n */\nexport function listClaudeLocalMcpServers(\n document: unknown,\n projectRoot?: string,\n): ClaudeLocalMcpServer[] {\n if (!isRecord(document) || !isRecord(document.projects)) {\n return [];\n }\n\n const wanted = projectRoot ? resolve(projectRoot) : undefined;\n const listed: ClaudeLocalMcpServer[] = [];\n\n for (const [projectPath, entry] of Object.entries(document.projects)) {\n if (wanted && !projectKeysMatch(projectPath, wanted)) {\n continue;\n }\n if (!isRecord(entry)) {\n continue;\n }\n const servers = parseMcpServersDocument({ mcpServers: entry.mcpServers });\n for (const [name, metadata] of Object.entries(servers)) {\n listed.push({\n projectPath,\n name,\n metadata: {\n ...metadata,\n claude_mcp_scope: \"local\",\n claude_project_path: resolve(projectPath),\n },\n });\n }\n }\n\n return listed;\n}\n\nexport function localMcpCreateInputsFromDocument(\n document: unknown,\n projectRoot: string | undefined,\n takenNames: ReadonlySet<string>,\n): ResourceCreateInput[] {\n const taken = new Set(takenNames);\n const resources: ResourceCreateInput[] = [];\n\n for (const server of listClaudeLocalMcpServers(document, projectRoot)) {\n let name = server.name;\n if (taken.has(name)) {\n name = `${server.name}@local`;\n let suffix = 2;\n while (taken.has(name)) {\n name = `${server.name}@local${suffix}`;\n suffix += 1;\n }\n }\n taken.add(name);\n resources.push({\n type: \"mcp_server\",\n name,\n description: \"\",\n content: \"\",\n metadata: server.metadata,\n source: claudeLocalMcpSource(server.projectPath),\n });\n }\n\n return resources;\n}\n","import { getAllPlatforms } from \"../platforms/registry.js\";\nimport type { McpServerMetadata, Resource } from \"../types.js\";\nimport { isClaudeLocalMcpResource } from \"./claude-local-mcp.js\";\nimport {\n resourceAppliesToHarness,\n resourceHarnessScope,\n} from \"./harness-scope.js\";\n\nfunction normalizePath(path: string, rootPath = \"\"): 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\nexport function sourceMatchesManagedPath(\n source: string | undefined,\n managedPath: string,\n rootPath = \"\",\n): boolean {\n if (!source) {\n return false;\n }\n const normalizedSource = normalizePath(source, rootPath);\n const normalizedManaged = normalizePath(managedPath, rootPath);\n return (\n normalizedSource === normalizedManaged\n || normalizedSource === `~/${normalizedManaged}`\n || normalizedManaged === `~/${normalizedSource}`\n || normalizedSource.replace(/^~\\//, \"\") === normalizedManaged.replace(/^~\\//, \"\")\n );\n}\n\nfunction stripHomePrefix(path: string): string {\n return normalizePath(path).replace(/^~\\//, \"\");\n}\n\nfunction collectKnownMcpConfigPaths(): string[] {\n const paths: string[] = [];\n const looksLikeMcpConfig = (path: string): boolean =>\n /(^|\\/)(\\.?mcp\\.json|mcp[-_]config\\.json|opencode\\.json)$/i.test(path);\n\n for (const platform of getAllPlatforms()) {\n for (const candidate of [\n platform.projectPaths.mcp,\n platform.globalPaths.mcp,\n platform.globalPaths.settings,\n platform.projectPaths.settings,\n ]) {\n if (!candidate) {\n continue;\n }\n const normalized = stripHomePrefix(candidate);\n if (\n candidate === platform.projectPaths.mcp\n || candidate === platform.globalPaths.mcp\n || looksLikeMcpConfig(normalized)\n ) {\n paths.push(normalized);\n }\n }\n }\n return [...new Set(paths)];\n}\n\nfunction sourcePointsAtKnownMcpPath(source: string, rootPath = \"\"): boolean {\n const known = collectKnownMcpConfigPaths();\n return known.some((path) => sourceMatchesManagedPath(source, path, rootPath));\n}\n\nfunction isPortableMcpSource(source: string | undefined): boolean {\n const trimmed = source?.trim();\n if (!trimmed || trimmed === \"manual\") {\n return true;\n }\n const normalized = trimmed.replace(/\\\\/g, \"/\");\n // Manifest and package identities are not bound to a harness MCP file.\n return (\n normalized === \"apm.yml\" ||\n normalized.endsWith(\"/apm.yml\") ||\n normalized === \"plugin.json\" ||\n normalized === \"mcp.json\"\n );\n}\n\nexport function harnessIdsForMcpPath(\n targetMcpPath: string,\n rootPath = \"\",\n): string[] {\n const ids: string[] = [];\n for (const platform of getAllPlatforms()) {\n const candidates = [\n platform.projectPaths.mcp,\n platform.globalPaths.mcp,\n platform.globalPaths.settings,\n platform.projectPaths.settings,\n ];\n if (candidates.some((candidate) => sourceMatchesManagedPath(candidate, targetMcpPath, rootPath))) {\n ids.push(platform.id);\n }\n }\n return ids;\n}\n\nexport function isPortableMcpResource(resource: Pick<Resource, \"type\" | \"metadata\">): boolean {\n if (resource.type !== \"mcp_server\") {\n return false;\n }\n const meta = resource.metadata as McpServerMetadata;\n if (meta.transport !== \"stdio\" && meta.transport !== \"http\") {\n return false;\n }\n if (meta.connection_type || meta.framing || meta.claude_mcp_scope === \"local\") {\n return false;\n }\n for (const key of Object.keys(meta.env ?? {})) {\n if (/claude|codex|opencode|cursor/i.test(key)) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * MCP servers to emit into a harness MCP config path.\n * Subset harness_scope wins. Unscoped resources keep source-path binding so\n * disk-captured servers stay on their origin until the user adds scope.\n * - Path-matched sources stay on that file.\n * - `manual` / empty / `apm.yml` / package `mcp.json` sources stay portable (all targets).\n * - Sources pointing at a *different* known MCP file are excluded.\n */\nexport function filterMcpServersForTargetPath(\n resources: Resource[],\n targetMcpPath: string | undefined,\n rootPath = \"\",\n platformId?: string,\n): Resource[] {\n const mcps = resources.filter(\n (resource) =>\n resource.type === \"mcp_server\" && !isClaudeLocalMcpResource(resource),\n );\n if (!targetMcpPath) {\n return mcps;\n }\n\n const targetHarnesses = platformId\n ? [platformId]\n : harnessIdsForMcpPath(targetMcpPath, rootPath);\n\n return mcps.filter((resource) => {\n const scope = resourceHarnessScope(resource);\n if (scope.kind === \"subset\") {\n if (targetHarnesses.length === 0) {\n return false;\n }\n return targetHarnesses.some((id) => resourceAppliesToHarness(resource, id));\n }\n if (isPortableMcpSource(resource.source)) {\n return true;\n }\n if (sourceMatchesManagedPath(resource.source, targetMcpPath, rootPath)) {\n return true;\n }\n if (sourcePointsAtKnownMcpPath(resource.source ?? \"\", rootPath)) {\n return false;\n }\n return true;\n });\n}\n","import { getAllPlatforms } from \"../platforms/registry.js\";\nimport type { Resource } from \"../types.js\";\nimport { sourceMatchesManagedPath } from \"./mcp-target.js\";\n\nfunction stripHomePrefix(path: string): string {\n return path.replace(/\\\\/g, \"/\").replace(/^~\\//, \"\");\n}\n\nfunction collectKnownInstructionPaths(): string[] {\n const paths: string[] = [\"~/.agents/AGENTS.md\", \".agents/AGENTS.md\"];\n for (const platform of getAllPlatforms()) {\n for (const candidate of [\n platform.projectPaths.instructions,\n platform.projectPaths.legacy_instructions,\n platform.globalPaths.instructions,\n ]) {\n if (candidate) {\n paths.push(candidate);\n }\n }\n for (const related of platform.relatedLocations ?? []) {\n if (related.surfaces.includes(\"instructions\")) {\n paths.push(related.path);\n }\n }\n }\n return [...new Set(paths.map(stripHomePrefix))];\n}\n\nfunction sourcePointsAtKnownInstructionPath(source: string): boolean {\n return collectKnownInstructionPaths().some((path) =>\n sourceMatchesManagedPath(source, path),\n );\n}\n\nfunction isPortableInstructionSource(source: string | undefined): boolean {\n const trimmed = source?.trim();\n return !trimmed || trimmed === \"manual\";\n}\n\n/** Project-root CLAUDE.md and AGENTS.md are the same shared instruction file. */\nfunction instructionPathAliases(path: string): string[] {\n const normalized = path.replace(/\\\\/g, \"/\");\n const aliases = [normalized];\n if (normalized.endsWith(\"AGENTS.md\")) {\n aliases.push(`${normalized.slice(0, -\"AGENTS.md\".length)}CLAUDE.md`);\n } else if (normalized.endsWith(\"CLAUDE.md\")) {\n aliases.push(`${normalized.slice(0, -\"CLAUDE.md\".length)}AGENTS.md`);\n }\n return aliases;\n}\n\nfunction expandAllowedInstructionPaths(allowedPaths: string[]): string[] {\n return [...new Set(allowedPaths.flatMap(instructionPathAliases))];\n}\n\n/** Instructions that belong on this harness instruction path. */\nexport function filterInstructionsForTargetPath(\n resources: Resource[],\n allowedPaths: string[],\n): Resource[] {\n const allowed = expandAllowedInstructionPaths(allowedPaths);\n return resources.filter((resource) => {\n if (resource.type !== \"instruction\") {\n return false;\n }\n if (isPortableInstructionSource(resource.source)) {\n return true;\n }\n if (allowed.some((path) => sourceMatchesManagedPath(resource.source, path))) {\n return true;\n }\n if (sourcePointsAtKnownInstructionPath(resource.source ?? \"\")) {\n return false;\n }\n return true;\n });\n}\n","import { join } from \"node:path\";\nimport { BaseSerializer } from \"./base-serializer.js\";\nimport { getPlatform } from \"./registry.js\";\nimport { listCursorPluginPinCreateInputs } from \"../plugins/cursor-installed.js\";\nimport { isHostPluginPinResource, emitHostPluginTrees } from \"../services/host-plugin-serialize.js\";\nimport { serializedAgentDocument } from \"../services/agent-bridge.js\";\nimport { buildHooksJson, scanHooksFile } from \"../services/hook-serialization.js\";\nimport { overlayJsonPreservingFormat } from \"../services/format-preserving-config.js\";\nimport {\n emitCursorMcpServerEntry,\n parseMcpServersDocument,\n} from \"../services/mcp-config-bridge.js\";\nimport { filterInstructionsForTargetPath } from \"../services/instruction-target.js\";\nimport type {\n AgentMetadata,\n HookMetadata,\n McpServerMetadata,\n PlatformDefinition,\n Resource,\n ResourceCreateInput,\n SerializedFile,\n RuleMetadata,\n SerializeOptions,\n} from \"../types.js\";\n\nexport class CursorSerializer extends BaseSerializer {\n readonly platformId = \"cursor\";\n readonly platform: PlatformDefinition;\n\n constructor() {\n super();\n const p = getPlatform(\"cursor\");\n if (!p) throw new Error(\"cursor platform not found in registry\");\n this.platform = p;\n }\n\n async scan(projectRoot: string): Promise<ResourceCreateInput[]> {\n const resources: ResourceCreateInput[] = [];\n\n // 1. Legacy .cursorrules\n const legacyContent = this.readFile(join(projectRoot, \".cursorrules\"));\n if (legacyContent) {\n resources.push(\n this.makeResource(\n \"instruction\",\n \"cursorrules\",\n legacyContent,\n \".cursorrules\",\n ),\n );\n }\n\n // 2. AGENTS.md\n const agentsMd = this.readFile(join(projectRoot, \"AGENTS.md\"));\n if (agentsMd && !legacyContent) {\n resources.push(\n this.makeResource(\n \"instruction\",\n \"agents-instructions\",\n agentsMd,\n \"AGENTS.md\",\n ),\n );\n }\n\n // 3. .cursor/rules/*.mdc and *.md\n const rulesDir = join(projectRoot, \".cursor\", \"rules\");\n for (const file of this.listDir(rulesDir)) {\n if (!file.endsWith(\".mdc\") && !file.endsWith(\".md\")) continue;\n const raw = this.readFile(join(rulesDir, file));\n if (!raw) continue;\n\n const parsed = this.tryParseFrontmatter(raw);\n if (!parsed) continue;\n\n const { data, content } = parsed;\n const name = file.replace(/\\.(mdc|md)$/, \"\");\n const alwaysApply = data[\"alwaysApply\"] === true;\n const globs = data[\"globs\"]\n ? typeof data[\"globs\"] === \"string\"\n ? (data[\"globs\"] as string).split(\",\").map((s: string) => s.trim())\n : (data[\"globs\"] as string[])\n : [];\n\n // Determine if this is an instruction or a rule\n if (alwaysApply && globs.length === 0) {\n resources.push(\n this.makeResource(\n \"instruction\",\n name,\n content.trim(),\n `.cursor/rules/${file}`,\n {},\n (data[\"description\"] as string) || \"\",\n ),\n );\n } else {\n const metadata: RuleMetadata = { globs, always_apply: alwaysApply };\n resources.push(\n this.makeResource(\n \"rule\",\n name,\n content.trim(),\n `.cursor/rules/${file}`,\n metadata,\n (data[\"description\"] as string) || \"\",\n ),\n );\n }\n }\n\n // 4. Skills\n resources.push(...this.scanSkillsDir(projectRoot, \".agents/skills\"));\n\n // 5. Agents: .cursor/agents/*.md\n resources.push(\n ...this.scanAgentFilesAt(\n join(projectRoot, \".cursor\", \"agents\"),\n \".cursor/agents/\",\n [\".md\"],\n ),\n );\n\n // 6. Hooks: .cursor/hooks.json\n resources.push(\n ...scanHooksFile(\n join(projectRoot, \".cursor\", \"hooks.json\"),\n \".cursor/hooks.json\",\n ),\n );\n\n // 7. MCP servers: .cursor/mcp.json\n resources.push(\n ...this.scanMcpConfig(join(projectRoot, \".cursor\", \"mcp.json\"), \".cursor/mcp.json\"),\n );\n\n return resources;\n }\n\n async scanGlobal(homeRoot: string): Promise<ResourceCreateInput[]> {\n const resources: ResourceCreateInput[] = [];\n\n const rulesDir = join(homeRoot, \".cursor\", \"rules\");\n for (const file of this.listDir(rulesDir)) {\n if (!file.endsWith(\".mdc\") && !file.endsWith(\".md\")) continue;\n const raw = this.readFile(join(rulesDir, file));\n if (!raw) continue;\n\n const parsed = this.tryParseFrontmatter(raw);\n if (!parsed) continue;\n\n const { data, content } = parsed;\n const name = file.replace(/\\.(mdc|md)$/, \"\");\n const alwaysApply = data[\"alwaysApply\"] === true;\n const globs = data[\"globs\"]\n ? typeof data[\"globs\"] === \"string\"\n ? (data[\"globs\"] as string)\n .split(\",\")\n .map((value: string) => value.trim())\n : (data[\"globs\"] as string[])\n : [];\n\n if (alwaysApply && globs.length === 0) {\n resources.push(\n this.makeResource(\n \"instruction\",\n name,\n content.trim(),\n `~/.cursor/rules/${file}`,\n {},\n (data[\"description\"] as string) || \"\",\n ),\n );\n } else {\n const metadata: RuleMetadata = { globs, always_apply: alwaysApply };\n resources.push(\n this.makeResource(\n \"rule\",\n name,\n content.trim(),\n `~/.cursor/rules/${file}`,\n metadata,\n (data[\"description\"] as string) || \"\",\n ),\n );\n }\n }\n\n resources.push(\n ...this.scanSkillsDirAt(\n join(homeRoot, \".cursor\", \"skills\"),\n \"~/.cursor/skills\",\n ),\n );\n\n resources.push(\n ...this.scanAgentFilesAt(\n join(homeRoot, \".cursor\", \"agents\"),\n \"~/.cursor/agents/\",\n [\".md\"],\n ),\n );\n\n if (this.platform.globalPaths.settings) {\n resources.push(\n ...this.scanMcpConfig(\n this.resolveHomePath(homeRoot, this.platform.globalPaths.settings),\n this.platform.globalPaths.settings,\n ),\n );\n }\n\n resources.push(...listCursorPluginPinCreateInputs(homeRoot));\n\n return resources;\n }\n\n private scanMcpConfig(\n configPath: string,\n displayPath: string,\n ): ResourceCreateInput[] {\n const resources: ResourceCreateInput[] = [];\n const configContent = this.readFile(configPath);\n if (!configContent) {\n return resources;\n }\n\n try {\n const document = JSON.parse(configContent) as unknown;\n for (const [name, metadata] of Object.entries(parseMcpServersDocument(document))) {\n resources.push(this.makeResource(\"mcp_server\", name, \"\", displayPath, metadata));\n }\n } catch {\n // invalid JSON: skip\n }\n\n return resources;\n }\n\n async serialize(\n resources: Resource[],\n projectRoot: string,\n options: SerializeOptions = {},\n ): Promise<SerializedFile[]> {\n const files: SerializedFile[] = [];\n const target = options.target ?? \"project\";\n const skillCursorMode = options.skillCursorMode ?? \"agents-skills\";\n const targetPaths = this.getTargetPaths(target);\n const rulesPath = this.toTargetRelativePath(targetPaths.rules, target);\n const skillsPath = this.toTargetRelativePath(targetPaths.skills, target);\n const agentsPath = this.toTargetRelativePath(targetPaths.agents, target);\n const hooksPath = this.toTargetRelativePath(targetPaths.hooks, target);\n const mcpPath = this.toTargetRelativePath(\n target === \"global\" ? targetPaths.settings : targetPaths.mcp,\n target,\n );\n\n for (const r of resources) {\n switch (r.type) {\n case \"instruction\": {\n if (!rulesPath) break;\n if (\n filterInstructionsForTargetPath([r], [\"AGENTS.md\", \".cursorrules\"]).length === 0\n ) {\n break;\n }\n // Emit as always-apply .mdc rule\n const fm: Record<string, unknown> = {\n description: r.description || r.name,\n alwaysApply: true,\n };\n files.push({\n path: join(rulesPath, `${r.name}.mdc`),\n content: this.emitFrontmatter(fm, r.content),\n });\n break;\n }\n case \"rule\": {\n if (!rulesPath) break;\n const meta = r.metadata as RuleMetadata;\n const fm: Record<string, unknown> = {\n description: r.description || r.name,\n alwaysApply: meta.always_apply,\n };\n if (meta.globs.length > 0) {\n fm[\"globs\"] = meta.globs.join(\",\");\n }\n files.push({\n path: join(rulesPath, `${r.name}.mdc`),\n content: this.emitFrontmatter(fm, r.content),\n });\n break;\n }\n case \"skill\": {\n if ((target === \"global\" || skillCursorMode === \"agents-skills\") && skillsPath) {\n files.push(\n ...this.emitSkillWithAuxiliary(\n r,\n join(skillsPath, r.name, \"SKILL.md\"),\n options,\n ),\n );\n break;\n }\n if (!rulesPath) break;\n const alwaysApply = skillCursorMode === \"always-on\";\n const fm: Record<string, unknown> = {\n description: r.description || `Skill: ${r.name}`,\n alwaysApply,\n };\n files.push({\n path: join(rulesPath, `${r.name}.mdc`),\n content: this.emitFrontmatter(fm, r.content),\n });\n break;\n }\n case \"agent\": {\n if (!agentsPath) break;\n files.push({\n path: join(agentsPath, `${r.name}.md`),\n content: serializedAgentDocument(\n {\n name: r.name,\n description: r.description,\n content: r.content,\n metadata: r.metadata as AgentMetadata,\n },\n \"cursor\",\n ),\n });\n break;\n }\n case \"hook\":\n break;\n default:\n break;\n }\n }\n\n const hooks = resources.filter((r) => r.type === \"hook\");\n if (hooksPath && hooks.length > 0) {\n const generated = buildHooksJson(\n hooks.map((r) => ({\n ...(r.metadata as HookMetadata),\n name: r.name,\n })),\n { version: 1, shape: \"flat\" },\n );\n files.push({\n path: hooksPath,\n content: overlayJsonPreservingFormat(\n this.readFile(join(projectRoot, hooksPath)),\n generated as unknown as Record<string, unknown>,\n { mergeObjectKeys: [\"hooks\"] },\n ),\n });\n }\n\n const mcps = this.mcpServersForTarget(resources, mcpPath);\n if (mcps.length > 0 && mcpPath) {\n const mcpServers: Record<string, Record<string, unknown>> = {};\n for (const resource of mcps) {\n mcpServers[resource.name] = emitCursorMcpServerEntry(\n resource.metadata as McpServerMetadata,\n );\n }\n files.push({\n path: mcpPath,\n content: overlayJsonPreservingFormat(\n this.readFile(join(projectRoot, mcpPath)),\n { mcpServers },\n { mergeObjectKeys: [\"mcpServers\"] },\n ),\n });\n }\n\n if (target === \"global\") {\n return emitHostPluginTrees(resources, {\n layout: \"cursor\",\n homeRoot: options.projectRoot ?? projectRoot,\n files,\n surfaceWarnings: options?.surfaceWarnings,\n });\n }\n\n if (resources.some(isHostPluginPinResource)) {\n options?.surfaceWarnings?.push({\n harness: \"cursor\",\n path: \".cursor/plugins/local\",\n category: \"cursor-local-plugin\",\n message:\n \"Cursor local plugins are user-wide. Project apply does not copy them into ~/.cursor/plugins/local.\",\n alias_harnesses: [],\n });\n }\n\n return files;\n }\n}\n","import { join } from \"node:path\";\nimport { parse } from \"smol-toml\";\nimport { BaseSerializer } from \"./base-serializer.js\";\nimport { getPlatform } from \"./registry.js\";\nimport {\n overlayJsonPreservingFormat,\n overlayTomlPreservingFormat,\n} from \"../services/format-preserving-config.js\";\nimport { buildHooksJson, scanHooksFile } from \"../services/hook-serialization.js\";\nimport { serializedAgentDocument } from \"../services/agent-bridge.js\";\nimport { filterInstructionsForTargetPath } from \"../services/instruction-target.js\";\nimport type {\n AgentMetadata,\n EnvVarMetadata,\n HookMetadata,\n McpServerMetadata,\n ModelConfigMetadata,\n PermissionMetadata,\n PlatformDefinition,\n ResourceCreateInput,\n Resource,\n SerializedFile,\n SerializeOptions,\n} from \"../types.js\";\n\ninterface CodexMcpServerEntry {\n command?: string;\n args?: string[];\n url?: string;\n env?: Record<string, string>;\n}\n\ninterface CodexPermissionProfile {\n filesystem?: Record<string, unknown>;\n network?: {\n domains?: Record<string, string>;\n };\n}\n\ntype CodexConfigDocument = Record<string, unknown>;\n\nconst FILESYSTEM_PERMISSION_PREFIX = \"filesystem:\";\nconst NETWORK_PERMISSION_PREFIX = \"network:\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction parseCodexConfig(content: string): CodexConfigDocument | undefined {\n try {\n const parsed = parse(content);\n if (!isRecord(parsed)) return undefined;\n return parsed;\n } catch {\n return undefined;\n }\n}\n\nfunction collectFilesystemRules(\n filesystem: Record<string, unknown>,\n profile: string,\n scopePrefix = \"\",\n): Array<{ profile: string; path: string; mode: string }> {\n const rules: Array<{ profile: string; path: string; mode: string }> = [];\n\n for (const [key, value] of Object.entries(filesystem)) {\n if (key === \"glob_scan_max_depth\") continue;\n if (typeof value === \"string\") {\n const path = scopePrefix ? `${scopePrefix}:${key}` : key;\n rules.push({ profile, path, mode: value });\n continue;\n }\n if (isRecord(value)) {\n rules.push(...collectFilesystemRules(value, profile, key));\n }\n }\n\n return rules;\n}\n\nfunction permissionActionFromMode(mode: string): PermissionMetadata[\"action\"] {\n return mode === \"deny\" ? \"deny\" : \"allow\";\n}\n\nfunction permissionName(\n action: PermissionMetadata[\"action\"],\n profile: string,\n target: string,\n): string {\n const slug = target.replace(/[^a-zA-Z0-9]+/g, \"-\").replace(/^-|-$/g, \"\");\n return `${action}-${profile}-${slug}`;\n}\n\nfunction encodePermissionPattern(\n prefix: string,\n profile: string,\n mode: string,\n target: string,\n): string {\n return `${prefix}${profile}:${mode}:${target}`;\n}\n\nfunction decodePermissionPattern(\n pattern: string,\n prefix: string,\n): { profile: string; mode: string; target: string } | undefined {\n if (!pattern.startsWith(prefix)) return undefined;\n const body = pattern.slice(prefix.length);\n const first = body.indexOf(\":\");\n const second = body.indexOf(\":\", first + 1);\n if (first === -1 || second === -1) return undefined;\n return {\n profile: body.slice(0, first),\n mode: body.slice(first + 1, second),\n target: body.slice(second + 1),\n };\n}\n\nfunction setNestedFilesystemRule(\n target: Record<string, unknown>,\n path: string,\n mode: string,\n): void {\n const segments = path.split(\":\");\n let current = target;\n for (let index = 0; index < segments.length - 1; index += 1) {\n const segment = segments[index] ?? \"\";\n const next = current[segment];\n if (!isRecord(next)) {\n current[segment] = {};\n }\n current = current[segment] as Record<string, unknown>;\n }\n const leaf = segments[segments.length - 1] ?? path;\n current[leaf] = mode;\n}\n\nfunction buildPermissionProfiles(\n permissions: Resource[],\n): Record<string, CodexPermissionProfile> {\n const profiles: Record<string, CodexPermissionProfile> = {};\n\n for (const resource of permissions) {\n const metadata = resource.metadata as PermissionMetadata;\n const filesystemRule = decodePermissionPattern(\n metadata.pattern,\n FILESYSTEM_PERMISSION_PREFIX,\n );\n if (filesystemRule) {\n const profileConfig = profiles[filesystemRule.profile] ?? {};\n if (!profileConfig.filesystem) {\n profileConfig.filesystem = {};\n }\n const filesystem = profileConfig.filesystem;\n setNestedFilesystemRule(\n filesystem,\n filesystemRule.target,\n filesystemRule.mode,\n );\n profiles[filesystemRule.profile] = profileConfig;\n continue;\n }\n\n const networkRule = decodePermissionPattern(\n metadata.pattern,\n NETWORK_PERMISSION_PREFIX,\n );\n if (networkRule) {\n const profileConfig = profiles[networkRule.profile] ?? {};\n if (!profileConfig.network) {\n profileConfig.network = {};\n }\n const network = profileConfig.network;\n if (!network.domains) {\n network.domains = {};\n }\n const domains = network.domains;\n domains[networkRule.target] = networkRule.mode;\n profiles[networkRule.profile] = profileConfig;\n }\n }\n\n return profiles;\n}\n\nfunction buildMcpServers(\n mcps: Resource[],\n): Record<string, Record<string, unknown>> {\n const mcpServers: Record<string, Record<string, unknown>> = {};\n\n for (const resource of mcps) {\n const metadata = resource.metadata as McpServerMetadata;\n const entry: Record<string, unknown> = {};\n if (metadata.transport === \"http\" || metadata.url) {\n if (metadata.url) entry.url = metadata.url;\n } else {\n if (metadata.command) entry.command = metadata.command;\n if (metadata.args && metadata.args.length > 0) entry.args = metadata.args;\n if (metadata.env && Object.keys(metadata.env).length > 0) {\n entry.env = metadata.env;\n }\n }\n mcpServers[resource.name] = entry;\n }\n\n return mcpServers;\n}\n\nfunction mergeConfigDocuments(\n existing: CodexConfigDocument,\n overlay: CodexConfigDocument,\n): CodexConfigDocument {\n const merged: CodexConfigDocument = { ...existing };\n\n for (const [key, value] of Object.entries(overlay)) {\n if (key === \"permissions\" && isRecord(value) && isRecord(merged.permissions)) {\n merged.permissions = { ...merged.permissions, ...value };\n continue;\n }\n if (\n key === \"shell_environment_policy\" &&\n isRecord(value) &&\n isRecord(merged.shell_environment_policy)\n ) {\n const existingPolicy = merged.shell_environment_policy;\n const overlayPolicy = value;\n const existingSet = isRecord(existingPolicy.set) ? existingPolicy.set : {};\n const overlaySet = isRecord(overlayPolicy.set) ? overlayPolicy.set : {};\n merged.shell_environment_policy = {\n ...existingPolicy,\n ...overlayPolicy,\n set: { ...existingSet, ...overlaySet },\n };\n continue;\n }\n merged[key] = value;\n }\n\n return merged;\n}\n\nexport class CodexSerializer extends BaseSerializer {\n readonly platformId = \"codex\";\n readonly platform: PlatformDefinition;\n\n constructor() {\n super();\n const p = getPlatform(\"codex\");\n if (!p) throw new Error(\"codex platform not found in registry\");\n this.platform = p;\n }\n\n private scanConfigResources(\n config: CodexConfigDocument,\n source: string,\n ): ResourceCreateInput[] {\n const resources: ResourceCreateInput[] = [];\n\n const mcpServers = config.mcp_servers;\n if (isRecord(mcpServers)) {\n for (const [name, entryValue] of Object.entries(mcpServers)) {\n if (!isRecord(entryValue)) continue;\n const entry = entryValue as CodexMcpServerEntry;\n const metadata: McpServerMetadata = {\n transport: entry.url ? \"http\" : \"stdio\",\n command: entry.command,\n args: entry.args,\n url: entry.url,\n env: entry.env,\n };\n resources.push(\n this.makeResource(\"mcp_server\", name, \"\", source, metadata),\n );\n }\n }\n\n const permissions = config.permissions;\n if (isRecord(permissions)) {\n for (const [profile, profileValue] of Object.entries(permissions)) {\n if (!isRecord(profileValue)) continue;\n const profileConfig = profileValue as CodexPermissionProfile;\n\n if (isRecord(profileConfig.filesystem)) {\n for (const rule of collectFilesystemRules(\n profileConfig.filesystem,\n profile,\n )) {\n const action = permissionActionFromMode(rule.mode);\n const pattern = encodePermissionPattern(\n FILESYSTEM_PERMISSION_PREFIX,\n rule.profile,\n rule.mode,\n rule.path,\n );\n resources.push(\n this.makeResource(\n \"permission\",\n permissionName(action, rule.profile, rule.path),\n \"\",\n source,\n { action, pattern } satisfies PermissionMetadata,\n ),\n );\n }\n }\n\n const domains = profileConfig.network?.domains;\n if (isRecord(domains)) {\n for (const [domain, mode] of Object.entries(domains)) {\n if (typeof mode !== \"string\") continue;\n const action = permissionActionFromMode(mode);\n const pattern = encodePermissionPattern(\n NETWORK_PERMISSION_PREFIX,\n profile,\n mode,\n domain,\n );\n resources.push(\n this.makeResource(\n \"permission\",\n permissionName(action, profile, domain),\n \"\",\n source,\n { action, pattern } satisfies PermissionMetadata,\n ),\n );\n }\n }\n }\n }\n\n const shellPolicy = config.shell_environment_policy;\n if (isRecord(shellPolicy) && isRecord(shellPolicy.set)) {\n for (const [key, value] of Object.entries(shellPolicy.set)) {\n if (typeof value !== \"string\") continue;\n resources.push(\n this.makeResource(\"env_var\", key, \"\", source, {\n key,\n value,\n } satisfies EnvVarMetadata),\n );\n }\n }\n\n if (typeof config.model === \"string\" && config.model.length > 0) {\n const metadata: ModelConfigMetadata = {\n model: config.model,\n provider:\n typeof config.model_provider === \"string\"\n ? config.model_provider\n : undefined,\n };\n resources.push(\n this.makeResource(\"model_config\", \"default\", \"\", source, metadata),\n );\n }\n\n return resources;\n }\n\n private scanMarkdownCommandsAt(\n dirPath: string,\n sourcePrefix: string,\n ): ResourceCreateInput[] {\n const resources: ResourceCreateInput[] = [];\n const prefix = sourcePrefix.endsWith(\"/\") ? sourcePrefix : `${sourcePrefix}/`;\n for (const file of this.listDir(dirPath)) {\n if (!file.endsWith(\".md\")) continue;\n const content = this.readFile(join(dirPath, file));\n if (!content) continue;\n resources.push(\n this.makeResource(\"command\", file.replace(/\\.md$/, \"\"), content, `${prefix}${file}`),\n );\n }\n return resources;\n }\n\n private scanConfigAt(\n configPath: string,\n source: string,\n ): ResourceCreateInput[] {\n const configContent = this.readFile(configPath);\n if (!configContent) return [];\n const config = parseCodexConfig(configContent);\n if (!config) return [];\n return this.scanConfigResources(config, source);\n }\n\n async scan(projectRoot: string): Promise<ResourceCreateInput[]> {\n const resources: ResourceCreateInput[] = [];\n\n // 1. AGENTS.md\n const agentsMd = this.readFile(join(projectRoot, \"AGENTS.md\"));\n if (agentsMd) {\n resources.push(\n this.makeResource(\n \"instruction\",\n \"codex-instructions\",\n agentsMd,\n \"AGENTS.md\",\n ),\n );\n }\n\n // 2. Skills: .agents/skills/*/SKILL.md\n resources.push(...this.scanSkillsDir(projectRoot, \".agents/skills\"));\n\n // 3. Agents: .codex/agents/*.toml\n resources.push(\n ...this.scanAgentFilesAt(\n join(projectRoot, \".codex\", \"agents\"),\n \".codex/agents/\",\n [\".toml\"],\n ),\n );\n\n // 4. Settings: .codex/config.toml\n resources.push(\n ...this.scanConfigAt(\n join(projectRoot, \".codex\", \"config.toml\"),\n \".codex/config.toml\",\n ),\n );\n\n // 5. Hooks: .codex/hooks.json\n resources.push(\n ...scanHooksFile(\n join(projectRoot, \".codex\", \"hooks.json\"),\n \".codex/hooks.json\",\n ),\n );\n\n // 6. Prompts (commands): .codex/prompts/*.md\n resources.push(\n ...this.scanMarkdownCommandsAt(\n join(projectRoot, \".codex\", \"prompts\"),\n \".codex/prompts/\",\n ),\n );\n\n return resources;\n }\n\n async scanGlobal(homeRoot: string): Promise<ResourceCreateInput[]> {\n const resources: ResourceCreateInput[] = [];\n\n const instructionsPath = join(homeRoot, \".codex\", \"AGENTS.md\");\n const instructions = this.readFile(instructionsPath);\n if (instructions) {\n resources.push(\n this.makeResource(\n \"instruction\",\n \"codex-instructions\",\n instructions,\n \"~/.codex/AGENTS.md\",\n ),\n );\n }\n\n resources.push(\n ...this.scanSkillsDirAt(\n join(homeRoot, \".agents\", \"skills\"),\n \"~/.agents/skills\",\n ),\n );\n\n resources.push(\n ...this.scanAgentFilesAt(\n join(homeRoot, \".codex\", \"agents\"),\n \"~/.codex/agents/\",\n [\".toml\"],\n ),\n );\n\n resources.push(\n ...this.scanConfigAt(\n join(homeRoot, \".codex\", \"config.toml\"),\n \"~/.codex/config.toml\",\n ),\n );\n\n resources.push(\n ...this.scanMarkdownCommandsAt(\n join(homeRoot, \".codex\", \"prompts\"),\n \"~/.codex/prompts/\",\n ),\n );\n\n return resources;\n }\n\n async serialize(\n resources: Resource[],\n projectRoot: string,\n options: SerializeOptions = {},\n ): Promise<SerializedFile[]> {\n const files: SerializedFile[] = [];\n const target = options.target ?? \"project\";\n const targetPaths = this.getTargetPaths(target);\n const instructionsPath =\n this.toTargetRelativePath(targetPaths.instructions, target) ??\n (target === \"project\" ? \"AGENTS.md\" : undefined);\n const skillsPath =\n this.toTargetRelativePath(targetPaths.skills, target) ??\n (target === \"project\" ? \".agents/skills/\" : undefined);\n const agentsPath = this.toTargetRelativePath(targetPaths.agents, target);\n const configPath = this.toTargetRelativePath(\n targetPaths.settings ?? targetPaths.mcp,\n target,\n );\n const hooksPath = this.toTargetRelativePath(targetPaths.hooks, target);\n const commandsPath = this.toTargetRelativePath(targetPaths.commands, target);\n\n const instructions = filterInstructionsForTargetPath(\n resources,\n instructionsPath ? [instructionsPath, \"AGENTS.md\"] : [\"AGENTS.md\"],\n );\n const mcps = this.mcpServersForTarget(resources, configPath);\n const permissions = resources.filter((r) => r.type === \"permission\");\n const envVars = resources.filter((r) => r.type === \"env_var\");\n const modelConfigs = resources.filter((r) => r.type === \"model_config\");\n\n // Instructions → AGENTS.md\n if (instructions.length > 0 && instructionsPath) {\n files.push({\n path: instructionsPath,\n content: instructions.map((r) => r.content).join(\"\\n\\n\"),\n });\n }\n\n // Skills → .agents/skills/{name}/SKILL.md\n for (const r of resources.filter((r) => r.type === \"skill\")) {\n if (!skillsPath) continue;\n files.push(\n ...this.emitSkillWithAuxiliary(\n r,\n `${skillsPath}${r.name}/SKILL.md`,\n options,\n ),\n );\n }\n\n // Agents → .codex/agents/{name}.toml\n for (const r of resources.filter((r) => r.type === \"agent\")) {\n if (!agentsPath) continue;\n files.push({\n path: `${agentsPath}${r.name}.toml`,\n content: serializedAgentDocument(\n {\n name: r.name,\n description: r.description,\n content: r.content,\n metadata: r.metadata as AgentMetadata,\n },\n \"codex-toml\",\n ),\n });\n }\n\n // Rules → append to AGENTS.md (Codex doesn't have a native rules system)\n const rules = resources.filter((r) => r.type === \"rule\");\n if (rules.length > 0 && instructions.length > 0 && instructionsPath) {\n const rulesSections = rules\n .map((r) => `## ${r.name}\\n\\n${r.content}`)\n .join(\"\\n\\n\");\n const existing = files.find((f) => f.path === instructionsPath);\n if (existing) {\n existing.content += `\\n\\n${rulesSections}`;\n }\n } else if (rules.length > 0 && instructionsPath) {\n files.push({\n path: instructionsPath,\n content: rules.map((r) => `## ${r.name}\\n\\n${r.content}`).join(\"\\n\\n\"),\n });\n }\n\n const managedResourceCount =\n mcps.length + permissions.length + envVars.length + modelConfigs.length;\n if (managedResourceCount > 0 && configPath) {\n const existingContent = this.readFile(join(projectRoot, configPath));\n const overlay: CodexConfigDocument = {};\n\n if (mcps.length > 0) {\n overlay.mcp_servers = buildMcpServers(mcps);\n }\n\n if (permissions.length > 0) {\n overlay.permissions = buildPermissionProfiles(permissions);\n }\n\n if (envVars.length > 0) {\n const set: Record<string, string> = {};\n for (const resource of envVars) {\n const metadata = resource.metadata as EnvVarMetadata;\n set[metadata.key] = metadata.value;\n }\n overlay.shell_environment_policy = { set };\n }\n\n if (modelConfigs.length > 0) {\n const metadata = modelConfigs[0]?.metadata as ModelConfigMetadata;\n overlay.model = metadata.model;\n if (metadata.provider) {\n overlay.model_provider = metadata.provider;\n }\n }\n\n files.push({\n path: configPath,\n content: overlayTomlPreservingFormat(\n existingContent,\n overlay,\n mergeConfigDocuments,\n ),\n });\n }\n\n if (commandsPath) {\n for (const resource of resources.filter((r) => r.type === \"command\")) {\n files.push({\n path: `${commandsPath}${resource.name}.md`,\n content: resource.content,\n });\n }\n }\n\n const hooks = resources.filter((r) => r.type === \"hook\");\n if (hooksPath && hooks.length > 0) {\n const generated = buildHooksJson(\n hooks.map((r) => ({\n ...(r.metadata as HookMetadata),\n name: r.name,\n })),\n );\n files.push({\n path: hooksPath,\n content: overlayJsonPreservingFormat(\n this.readFile(join(projectRoot, hooksPath)),\n generated as unknown as Record<string, unknown>,\n { mergeObjectKeys: [\"hooks\"] },\n ),\n });\n }\n\n return files;\n }\n}\n","import { existsSync, readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { join, relative } from \"node:path\";\nimport { parse, stringify } from \"yaml\";\nimport { BaseSerializer } from \"./base-serializer.js\";\nimport { getPlatform } from \"./registry.js\";\nimport { buildHooksJson, scanHooksFile } from \"../services/hook-serialization.js\";\nimport { scanPluginSource } from \"../services/plugin-source-import.js\";\nimport type {\n HookMetadata,\n McpServerMetadata,\n PlatformDefinition,\n Resource,\n ResourceCreateInput,\n SerializedFile,\n SerializeOptions,\n} from \"../types.js\";\n\nconst GOOSE_CONFIG_FILES = [\"config.yaml\", \"profiles.yaml\"] as const;\nconst GOOSE_PLUGIN_PLUGIN_NAME = \"harnesstap-plugin\";\nconst SKIP_WALK_DIRS = new Set([\n \".git\",\n \"node_modules\",\n \"dist\",\n \"build\",\n \".next\",\n \"target\",\n]);\n\ninterface GooseExtensionEntry {\n type?: string;\n name?: string;\n cmd?: string;\n args?: string[];\n uri?: string;\n envs?: Record<string, string>;\n env_keys?: string[];\n enabled?: boolean;\n timeout?: number;\n description?: string;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction parseGooseYaml(content: string): Record<string, unknown> {\n try {\n const doc = parse(content);\n return isRecord(doc) ? doc : {};\n } catch {\n return {};\n }\n}\n\nfunction extensionToMcpMetadata(\n _name: string,\n entry: GooseExtensionEntry,\n): McpServerMetadata | null {\n const type = entry.type ?? \"stdio\";\n if (type === \"builtin\" || type === \"platform\") {\n return null;\n }\n if (type === \"stdio\") {\n return {\n transport: \"stdio\",\n command: entry.cmd,\n args: Array.isArray(entry.args) ? entry.args : undefined,\n env: isRecord(entry.envs) ? (entry.envs as Record<string, string>) : undefined,\n };\n }\n if (type === \"sse\" || type === \"streamable_http\") {\n return {\n transport: \"http\",\n url: typeof entry.uri === \"string\" ? entry.uri : undefined,\n };\n }\n if (entry.cmd) {\n return {\n transport: \"stdio\",\n command: entry.cmd,\n args: Array.isArray(entry.args) ? entry.args : undefined,\n env: isRecord(entry.envs) ? (entry.envs as Record<string, string>) : undefined,\n };\n }\n if (entry.uri) {\n return {\n transport: \"http\",\n url: entry.uri,\n };\n }\n return null;\n}\n\nfunction mcpToExtension(name: string, meta: McpServerMetadata): GooseExtensionEntry {\n if (meta.transport === \"http\") {\n return {\n name,\n type: \"streamable_http\",\n uri: meta.url,\n enabled: true,\n description: \"\",\n timeout: 300,\n };\n }\n const env = meta.env ?? {};\n return {\n name,\n type: \"stdio\",\n cmd: meta.command ?? \"\",\n args: meta.args ?? [],\n envs: env,\n env_keys: Object.keys(env),\n enabled: true,\n description: \"\",\n timeout: 300,\n };\n}\n\nfunction mergeGooseExtensions(\n existing: Record<string, unknown>,\n overlay: Record<string, GooseExtensionEntry>,\n): Record<string, unknown> {\n const merged = { ...existing };\n const currentExtensions = isRecord(existing.extensions)\n ? { ...(existing.extensions as Record<string, GooseExtensionEntry>) }\n : {};\n for (const [name, entry] of Object.entries(overlay)) {\n currentExtensions[name] = entry;\n }\n merged.extensions = currentExtensions;\n return merged;\n}\n\nfunction instructionNameForPath(relativePath: string): string {\n if (relativePath === \"AGENTS.md\") return \"agents-instructions\";\n if (relativePath === \".goosehints\") return \"goosehints\";\n if (relativePath.endsWith(\"/.goosehints\")) {\n const dir = relativePath.slice(0, -\"/.goosehints\".length);\n return `goosehints:${dir.replace(/\\//g, \"-\")}`;\n }\n return `goose-instructions:${relativePath}`;\n}\n\nfunction isDirectory(path: string): boolean {\n try {\n return statSync(path).isDirectory();\n } catch {\n return false;\n }\n}\n\nfunction walkGoosehints(\n projectRoot: string,\n currentDir: string,\n results: Array<{ relativePath: string; content: string }>,\n): void {\n if (!isDirectory(currentDir)) return;\n\n const hintsPath = join(currentDir, \".goosehints\");\n if (existsSync(hintsPath)) {\n try {\n const content = readFileSync(hintsPath, \"utf-8\");\n const relativePath =\n currentDir === projectRoot\n ? \".goosehints\"\n : `${relative(projectRoot, currentDir).split(\"\\\\\").join(\"/\")}/.goosehints`;\n results.push({ relativePath, content });\n } catch {\n // skip unreadable hints\n }\n }\n\n for (const entry of readdirSync(currentDir)) {\n if (entry.startsWith(\".\") && entry !== \".goosehints\") continue;\n if (SKIP_WALK_DIRS.has(entry)) continue;\n walkGoosehints(projectRoot, join(currentDir, entry), results);\n }\n}\n\nexport class GooseSerializer extends BaseSerializer {\n readonly platformId = \"goose\";\n readonly platform: PlatformDefinition;\n\n constructor() {\n super();\n const platform = getPlatform(\"goose\");\n if (!platform) throw new Error(\"goose platform not found in registry\");\n this.platform = platform;\n }\n\n private scanConfigExtensionsAt(\n configPath: string,\n displayPath: string,\n ): ResourceCreateInput[] {\n const resources: ResourceCreateInput[] = [];\n let content: string | undefined;\n try {\n content = readFileSync(configPath, \"utf-8\");\n } catch {\n return resources;\n }\n\n const doc = parseGooseYaml(content);\n const extensions = doc.extensions;\n if (!isRecord(extensions)) return resources;\n\n for (const [name, entryValue] of Object.entries(extensions)) {\n if (!isRecord(entryValue)) continue;\n const metadata = extensionToMcpMetadata(name, entryValue as GooseExtensionEntry);\n if (!metadata) continue;\n resources.push(\n this.makeResource(\"mcp_server\", name, \"\", displayPath, metadata),\n );\n }\n return resources;\n }\n\n private scanGooseConfigDir(\n configDir: string,\n pathPrefix: string,\n ): ResourceCreateInput[] {\n const resources: ResourceCreateInput[] = [];\n for (const fileName of GOOSE_CONFIG_FILES) {\n const configPath = join(configDir, fileName);\n if (!existsSync(configPath)) continue;\n resources.push(\n ...this.scanConfigExtensionsAt(configPath, `${pathPrefix}${fileName}`),\n );\n }\n return resources;\n }\n\n private scanInstructionsAt(\n rootPath: string,\n relativePath: string,\n ): ResourceCreateInput[] {\n const fullPath = join(rootPath, relativePath);\n if (!existsSync(fullPath)) return [];\n try {\n const content = readFileSync(fullPath, \"utf-8\");\n return [\n this.makeResource(\n \"instruction\",\n instructionNameForPath(relativePath),\n content,\n relativePath,\n ),\n ];\n } catch {\n return [];\n }\n }\n\n private scanSkillsAt(rootPath: string, skillsPath: string): ResourceCreateInput[] {\n return this.scanSkillsDir(rootPath, skillsPath);\n }\n\n private scanRecipesAt(projectRoot: string): ResourceCreateInput[] {\n const recipesDir = join(projectRoot, \"recipes\");\n if (!isDirectory(recipesDir)) return [];\n\n const resources: ResourceCreateInput[] = [];\n for (const entry of this.listDir(recipesDir)) {\n if (!entry.endsWith(\".yaml\") && !entry.endsWith(\".yml\")) continue;\n const recipePath = join(recipesDir, entry);\n const content = this.readFile(recipePath);\n if (!content) continue;\n const name = entry.replace(/\\.(yaml|yml)$/, \"\");\n resources.push(\n this.makeResource(\"command\", name, content.trim(), `recipes/${entry}`, {\n recipe: true,\n }),\n );\n }\n return resources;\n }\n\n private async scanPluginsAt(\n pluginsDir: string,\n displayPrefix: string,\n ): Promise<ResourceCreateInput[]> {\n if (!isDirectory(pluginsDir)) return [];\n\n const resources: ResourceCreateInput[] = [];\n for (const entry of readdirSync(pluginsDir)) {\n if (entry.startsWith(\".\")) continue;\n const pluginRoot = join(pluginsDir, entry);\n if (!isDirectory(pluginRoot)) continue;\n\n try {\n const imports = await scanPluginSource(pluginRoot);\n for (const resource of imports[0]?.resources ?? []) {\n resources.push({\n ...resource,\n source: resource.source.startsWith(displayPrefix)\n ? resource.source\n : `${displayPrefix}${entry}/${resource.source}`,\n });\n }\n } catch {\n const hooksPath = join(pluginRoot, \"hooks\", \"hooks.json\");\n if (existsSync(hooksPath)) {\n resources.push(\n ...scanHooksFile(hooksPath, `${displayPrefix}${entry}/hooks/hooks.json`),\n );\n }\n }\n }\n return resources;\n }\n\n async scan(projectRoot: string): Promise<ResourceCreateInput[]> {\n const resources: ResourceCreateInput[] = [];\n\n resources.push(...this.scanInstructionsAt(projectRoot, \"AGENTS.md\"));\n\n const goosehints: Array<{ relativePath: string; content: string }> = [];\n walkGoosehints(projectRoot, projectRoot, goosehints);\n for (const hint of goosehints) {\n resources.push(\n this.makeResource(\n \"instruction\",\n instructionNameForPath(hint.relativePath),\n hint.content,\n hint.relativePath,\n ),\n );\n }\n\n const skillsPath = this.platform.projectPaths.skills;\n if (skillsPath) {\n resources.push(...this.scanSkillsAt(projectRoot, skillsPath));\n }\n for (const alternate of this.platform.projectPaths.pathAlternates?.skills ?? []) {\n resources.push(...this.scanSkillsAt(projectRoot, alternate));\n }\n\n resources.push(...this.scanRecipesAt(projectRoot));\n resources.push(\n ...(await this.scanPluginsAt(join(projectRoot, \".agents\", \"plugins\"), \".agents/plugins/\")),\n );\n resources.push(\n ...this.scanGooseConfigDir(join(projectRoot, \".config\", \"goose\"), \".config/goose/\"),\n );\n\n return resources;\n }\n\n async scanGlobal(homeRoot: string): Promise<ResourceCreateInput[]> {\n const resources: ResourceCreateInput[] = [];\n\n resources.push(\n ...this.scanInstructionsAt(join(homeRoot, \".config\", \"goose\"), \".goosehints\"),\n );\n\n const skillsPath = this.platform.globalPaths.skills;\n if (skillsPath) {\n resources.push(\n ...this.scanSkillsDirAt(\n this.resolveHomePath(homeRoot, skillsPath),\n skillsPath.replace(/\\/$/, \"\"),\n ),\n );\n }\n\n resources.push(\n ...(await this.scanPluginsAt(\n join(homeRoot, \".agents\", \"plugins\"),\n \"~/.agents/plugins/\",\n )),\n );\n resources.push(\n ...this.scanGooseConfigDir(\n join(homeRoot, \".config\", \"goose\"),\n \"~/.config/goose/\",\n ),\n );\n\n return resources;\n }\n\n async serialize(\n resources: Resource[],\n projectRoot: string,\n options: SerializeOptions = {},\n ): Promise<SerializedFile[]> {\n const files: SerializedFile[] = [];\n const target = options.target ?? \"project\";\n const targetPaths = this.getTargetPaths(target);\n\n const instructionPath =\n this.toTargetRelativePath(targetPaths.instructions, target) ?? \"AGENTS.md\";\n const skillsPath =\n this.toTargetRelativePath(targetPaths.skills, target) ?? \".agents/skills/\";\n const recipesPath = this.toTargetRelativePath(targetPaths.commands, target);\n const configPath =\n target === \"global\"\n ? this.toTargetRelativePath(targetPaths.settings, target)\n : this.toTargetRelativePath(targetPaths.mcp, target);\n\n const instructions = resources.filter((r) => r.type === \"instruction\");\n const agentsMd = instructions.find(\n (r) => r.name === \"agents-instructions\" || r.source === \"AGENTS.md\",\n );\n if (agentsMd && instructionPath) {\n files.push({ path: instructionPath, content: agentsMd.content });\n }\n\n for (const hint of instructions.filter((r) => r.name.startsWith(\"goosehints\"))) {\n const outputPath =\n hint.source && hint.source.endsWith(\".goosehints\")\n ? hint.source\n : hint.name === \"goosehints\"\n ? \".goosehints\"\n : undefined;\n if (outputPath) {\n files.push({ path: outputPath, content: hint.content });\n }\n }\n\n const skills = resources.filter((r) => r.type === \"skill\");\n if (skillsPath && skills.length > 0) {\n for (const skill of skills) {\n files.push(\n ...this.emitSkillWithAuxiliary(\n skill,\n `${skillsPath}${skill.name}/SKILL.md`,\n options,\n ),\n );\n }\n }\n\n const recipes = resources.filter((r) => r.type === \"command\");\n if (recipesPath && recipes.length > 0) {\n for (const recipe of recipes) {\n const extension = recipe.source?.endsWith(\".yml\") ? \"yml\" : \"yaml\";\n const outputName = recipe.source?.includes(\"/\")\n ? recipe.source\n : `${recipesPath}${recipe.name}.${extension}`;\n files.push({ path: outputName, content: recipe.content });\n }\n }\n\n const hooks = resources.filter((r) => r.type === \"hook\");\n if (hooks.length > 0 && target === \"project\") {\n const pluginRoot = `.agents/plugins/${GOOSE_PLUGIN_PLUGIN_NAME}`;\n files.push({\n path: `${pluginRoot}/plugin.json`,\n content: `${JSON.stringify(\n {\n name: GOOSE_PLUGIN_PLUGIN_NAME,\n version: \"0.0.0\",\n description: \"Hooks materialized by HarnessTap plugin apply\",\n },\n null,\n 2,\n )}\\n`,\n });\n files.push({\n path: `${pluginRoot}/hooks/hooks.json`,\n content: JSON.stringify(\n buildHooksJson(\n hooks.map((r) => ({\n ...(r.metadata as HookMetadata),\n name: r.name,\n })),\n { version: 1 },\n ),\n null,\n 2,\n ),\n });\n }\n\n const mcpServers = this.mcpServersForTarget(resources, configPath);\n if (mcpServers.length > 0 && configPath) {\n const fullConfigPath = join(projectRoot, configPath);\n const existingContent = this.readFile(fullConfigPath);\n const existing = existingContent ? parseGooseYaml(existingContent) : {};\n const overlay: Record<string, GooseExtensionEntry> = {};\n for (const resource of mcpServers) {\n const metadata = resource.metadata as McpServerMetadata;\n if (!metadata) continue;\n overlay[resource.name] = mcpToExtension(resource.name, metadata);\n }\n files.push({\n path: configPath,\n content: `${stringify(mergeGooseExtensions(existing, overlay))}\\n`,\n });\n }\n\n return files;\n }\n}\n","import { join } from \"node:path\";\nimport { BaseSerializer } from \"./base-serializer.js\";\nimport { getPlatform } from \"./registry.js\";\nimport { overlayJsonPreservingFormat } from \"../services/format-preserving-config.js\";\nimport { serializedAgentDocument } from \"../services/agent-bridge.js\";\nimport { filterInstructionsForTargetPath } from \"../services/instruction-target.js\";\nimport type {\n AgentMetadata,\n PlatformDefinition,\n ResourceCreateInput,\n Resource,\n SerializedFile,\n McpServerMetadata,\n SerializeOptions,\n SerializerTarget,\n} from \"../types.js\";\n\ninterface OpenCodeMcpConfigEntry {\n type?: string;\n command?: string | string[];\n url?: string;\n environment?: Record<string, string>;\n env?: Record<string, string>;\n}\n\ninterface OpenCodeConfig {\n mcp?: Record<string, OpenCodeMcpConfigEntry>;\n}\n\ninterface OpenCodeSerializedMcpEntry {\n type: \"remote\" | \"local\";\n enabled: true;\n url?: string;\n command?: string | string[];\n environment?: Record<string, string>;\n}\n\n/** Claude-compat project tree; kept off pathAlternates so Claude Code detection stays unique. */\nconst PROJECT_SKILL_COMPAT = [\".claude/skills/\"] as const;\n\nexport class OpenCodeSerializer extends BaseSerializer {\n readonly platformId = \"opencode\";\n readonly platform: PlatformDefinition;\n\n constructor() {\n super();\n const p = getPlatform(\"opencode\");\n if (!p) throw new Error(\"opencode platform not found in registry\");\n this.platform = p;\n }\n\n private scanCommandsAt(\n projectRoot: string,\n relativeDir: string,\n ): ResourceCreateInput[] {\n const resources: ResourceCreateInput[] = [];\n const commandsDir = join(projectRoot, relativeDir);\n const sourcePrefix = relativeDir.endsWith(\"/\")\n ? relativeDir\n : `${relativeDir}/`;\n\n for (const file of this.listDir(commandsDir)) {\n if (!file.endsWith(\".md\")) continue;\n const content = this.readFile(join(commandsDir, file));\n if (!content) continue;\n const name = file.replace(/\\.md$/, \"\");\n resources.push(\n this.makeResource(\n \"command\",\n name,\n content,\n `${sourcePrefix}${file}`,\n ),\n );\n }\n\n return resources;\n }\n\n /** Home-relative OpenCode paths must not leak into a project tree. */\n private projectOpenCodePath(path: string, target: SerializerTarget): string {\n if (target === \"project\" && path.startsWith(\".config/opencode/\")) {\n return `.opencode/${path.slice(\".config/opencode/\".length)}`;\n }\n return path;\n }\n\n private commandOutputPath(\n resource: Resource,\n defaultCommandsPath: string,\n target: SerializerTarget,\n ): string {\n if (resource.source.includes(\".opencode/command/\")) {\n return `.opencode/command/${resource.name}.md`;\n }\n if (resource.source.includes(\".opencode/commands/\")) {\n return `.opencode/commands/${resource.name}.md`;\n }\n if (resource.source.includes(\"/opencode/command/\")) {\n return this.projectOpenCodePath(\n `.config/opencode/command/${resource.name}.md`,\n target,\n );\n }\n return `${defaultCommandsPath}${resource.name}.md`;\n }\n\n private agentOutputPath(\n resource: Resource,\n defaultAgentsPath: string,\n target: SerializerTarget,\n ): string {\n if (resource.source.includes(\".opencode/agent/\")) {\n return `.opencode/agent/${resource.name}.md`;\n }\n if (resource.source.includes(\".opencode/agents/\")) {\n return `.opencode/agents/${resource.name}.md`;\n }\n if (resource.source.includes(\"/opencode/agent/\")) {\n return this.projectOpenCodePath(\n `.config/opencode/agent/${resource.name}.md`,\n target,\n );\n }\n return `${defaultAgentsPath}${resource.name}.md`;\n }\n\n async scan(projectRoot: string): Promise<ResourceCreateInput[]> {\n const resources: ResourceCreateInput[] = [];\n\n // 1. Instructions: AGENTS.md\n const agentsMd = this.readFile(join(projectRoot, \"AGENTS.md\"));\n if (agentsMd) {\n resources.push(\n this.makeResource(\n \"instruction\",\n \"opencode-instructions\",\n agentsMd,\n \"AGENTS.md\",\n ),\n );\n }\n\n // 2. Skills: native `.opencode/skills/` then OpenCode compat trees\n const seenSkillNames = new Set<string>();\n this.appendUniqueSkills(\n resources,\n seenSkillNames,\n this.scanSkillsDir(\n projectRoot,\n this.platform.projectPaths.skills ?? \".opencode/skills/\",\n ),\n );\n for (const alternate of this.platform.projectPaths.pathAlternates?.skills ?? []) {\n this.appendUniqueSkills(\n resources,\n seenSkillNames,\n this.scanSkillsDir(projectRoot, alternate),\n );\n }\n for (const compatDir of PROJECT_SKILL_COMPAT) {\n this.appendUniqueSkills(\n resources,\n seenSkillNames,\n this.scanSkillsDir(projectRoot, compatDir),\n );\n }\n\n // 2.1 Agents: .opencode/agents/ and .opencode/agent/\n const seenAgentNames = new Set<string>();\n for (const agentsDir of [\n this.platform.projectPaths.agents ?? \".opencode/agents/\",\n ...(this.platform.projectPaths.pathAlternates?.agents ?? []),\n ]) {\n const prefix = agentsDir.endsWith(\"/\") ? agentsDir : `${agentsDir}/`;\n for (const resource of this.scanAgentFilesAt(\n join(projectRoot, agentsDir),\n prefix,\n [\".md\"],\n )) {\n if (seenAgentNames.has(resource.name)) continue;\n seenAgentNames.add(resource.name);\n resources.push(resource);\n }\n }\n\n // 2.2 Commands: .opencode/commands/ and .opencode/command/\n for (const commandsDir of [\".opencode/commands\", \".opencode/command\"]) {\n resources.push(...this.scanCommandsAt(projectRoot, commandsDir));\n }\n\n // 3. MCP servers: opencode.json\n const configPath = join(projectRoot, \"opencode.json\");\n const configContent = this.readFile(configPath);\n if (configContent) {\n try {\n const config = JSON.parse(configContent) as OpenCodeConfig;\n if (config.mcp) {\n for (const [name, mcp] of Object.entries(config.mcp)) {\n const metadata: McpServerMetadata = {\n transport: mcp.type === \"remote\" ? \"http\" : \"stdio\",\n command: Array.isArray(mcp.command) ? mcp.command[0] : mcp.command,\n args: Array.isArray(mcp.command) ? mcp.command.slice(1) : undefined,\n url: mcp.url,\n env: mcp.environment || mcp.env,\n };\n resources.push(\n this.makeResource(\n \"mcp_server\",\n name,\n \"\",\n \"opencode.json\",\n metadata,\n ),\n );\n }\n }\n } catch {\n // ignore invalid JSON\n }\n }\n\n return resources;\n }\n\n async scanGlobal(homeRoot: string): Promise<ResourceCreateInput[]> {\n const resources: ResourceCreateInput[] = [];\n\n const seenSkillNames = new Set<string>();\n const globalSkills = this.platform.globalPaths.skills ?? \"~/.config/opencode/skills/\";\n this.appendUniqueSkills(\n resources,\n seenSkillNames,\n this.scanSkillsDirAt(\n this.resolveHomePath(homeRoot, globalSkills),\n globalSkills.replace(/\\/$/, \"\"),\n ),\n );\n for (const alternate of this.platform.globalPaths.pathAlternates?.skills ?? []) {\n this.appendUniqueSkills(\n resources,\n seenSkillNames,\n this.scanSkillsDirAt(\n this.resolveHomePath(homeRoot, alternate),\n alternate.replace(/\\/$/, \"\"),\n ),\n );\n }\n for (const related of this.platform.relatedLocations ?? []) {\n if (!related.surfaces.includes(\"skills\")) continue;\n this.appendUniqueSkills(\n resources,\n seenSkillNames,\n this.scanSkillsDirAt(\n this.resolveHomePath(homeRoot, related.path),\n related.path.replace(/\\/$/, \"\"),\n ),\n );\n }\n\n const seenAgentNames = new Set<string>();\n for (const agentsDir of [\n this.platform.globalPaths.agents ?? \"~/.config/opencode/agents/\",\n ...(this.platform.globalPaths.pathAlternates?.agents ?? []),\n ]) {\n const prefix = agentsDir.endsWith(\"/\") ? agentsDir : `${agentsDir}/`;\n for (const resource of this.scanAgentFilesAt(\n this.resolveHomePath(homeRoot, agentsDir),\n prefix,\n [\".md\"],\n )) {\n if (seenAgentNames.has(resource.name)) continue;\n seenAgentNames.add(resource.name);\n resources.push(resource);\n }\n }\n\n const seenCommandNames = new Set<string>();\n for (const commandsDir of [\n this.platform.globalPaths.commands ?? \"~/.config/opencode/commands/\",\n ...(this.platform.globalPaths.pathAlternates?.commands ?? []),\n ]) {\n const prefix = commandsDir.endsWith(\"/\") ? commandsDir : `${commandsDir}/`;\n for (const file of this.listDir(this.resolveHomePath(homeRoot, commandsDir))) {\n if (!file.endsWith(\".md\")) continue;\n const content = this.readFile(\n join(this.resolveHomePath(homeRoot, commandsDir), file),\n );\n if (!content) continue;\n const name = file.replace(/\\.md$/, \"\");\n if (seenCommandNames.has(name)) continue;\n seenCommandNames.add(name);\n resources.push(\n this.makeResource(\"command\", name, content, `${prefix}${file}`),\n );\n }\n }\n\n for (const related of this.platform.relatedLocations ?? []) {\n if (!related.surfaces.includes(\"instructions\")) continue;\n const content = this.readFile(this.resolveHomePath(homeRoot, related.path));\n if (!content) continue;\n resources.push(\n this.makeResource(\"instruction\", \"agents-instructions\", content, related.path),\n );\n }\n\n // Global config\n const configPath = join(homeRoot, \".config\", \"opencode\", \"opencode.json\");\n const configContent = this.readFile(configPath);\n if (configContent) {\n try {\n const config = JSON.parse(configContent) as OpenCodeConfig;\n if (config.mcp) {\n for (const [name, mcp] of Object.entries(config.mcp)) {\n const metadata: McpServerMetadata = {\n transport: mcp.type === \"remote\" ? \"http\" : \"stdio\",\n command: Array.isArray(mcp.command) ? mcp.command[0] : mcp.command,\n args: Array.isArray(mcp.command) ? mcp.command.slice(1) : undefined,\n url: mcp.url,\n env: mcp.environment || mcp.env,\n };\n resources.push(\n this.makeResource(\n \"mcp_server\",\n name,\n \"\",\n \"~/.config/opencode/opencode.json\",\n metadata,\n ),\n );\n }\n }\n } catch {\n // ignore invalid JSON\n }\n }\n\n return resources;\n }\n\n async serialize(\n resources: Resource[],\n projectRoot: string,\n options: SerializeOptions = {},\n ): Promise<SerializedFile[]> {\n const files: SerializedFile[] = [];\n const target = options.target ?? \"project\";\n const targetPaths = this.getTargetPaths(target);\n const instructionsPath =\n this.toTargetRelativePath(targetPaths.instructions, target) ??\n (target === \"project\" ? \"AGENTS.md\" : undefined);\n const skillsPath = this.toTargetRelativePath(targetPaths.skills, target);\n const mcpPath = this.toTargetRelativePath(\n target === \"global\" ? targetPaths.settings : targetPaths.mcp,\n target,\n );\n const agentsPath = this.toTargetRelativePath(targetPaths.agents, target);\n const commandsPath = this.toTargetRelativePath(targetPaths.commands, target);\n\n // Group by type\n const instructions = filterInstructionsForTargetPath(\n resources,\n instructionsPath ? [instructionsPath, \"AGENTS.md\"] : [\"AGENTS.md\"],\n );\n const skills = resources.filter((r) => r.type === \"skill\");\n const mcps = this.mcpServersForTarget(resources, mcpPath);\n const agents = resources.filter((r) => r.type === \"agent\");\n const commands = resources.filter((r) => r.type === \"command\");\n\n // AGENTS.md\n if (instructions.length > 0 && instructionsPath) {\n files.push({\n path: instructionsPath,\n content: instructions.map((r) => r.content).join(\"\\n\\n\"),\n });\n }\n\n // .opencode/skills/\n if (skillsPath) {\n for (const r of skills) {\n files.push(\n ...this.emitSkillWithAuxiliary(\n r,\n `${skillsPath}${r.name}/SKILL.md`,\n options,\n ),\n );\n }\n }\n\n // .opencode/agents/ or .opencode/agent/\n if (agentsPath) {\n for (const r of agents) {\n files.push({\n path: this.agentOutputPath(r, agentsPath, target),\n content: serializedAgentDocument(\n {\n name: r.name,\n description: r.description,\n content: r.content,\n metadata: r.metadata as AgentMetadata,\n },\n \"generic\",\n ),\n });\n }\n }\n\n // .opencode/commands/ or .opencode/command/\n if (commandsPath) {\n for (const r of commands) {\n files.push({\n path: this.commandOutputPath(r, commandsPath, target),\n content: r.content,\n });\n }\n }\n\n // opencode.json\n if (mcps.length > 0 && mcpPath) {\n const mcpConfig: Record<string, OpenCodeSerializedMcpEntry> = {};\n for (const r of mcps) {\n const meta = r.metadata as McpServerMetadata;\n if (meta.transport === \"http\" || meta.url) {\n mcpConfig[r.name] = {\n type: \"remote\",\n url: meta.url,\n enabled: true,\n };\n } else {\n const command = meta.command ? [meta.command] : [];\n if (meta.args) command.push(...meta.args);\n mcpConfig[r.name] = {\n type: \"local\",\n command: command.length <= 1 ? command[0] : command,\n environment: meta.env,\n enabled: true,\n };\n }\n }\n files.push({\n path: mcpPath,\n content: overlayJsonPreservingFormat(\n this.readFile(join(projectRoot, mcpPath)),\n {\n $schema: \"https://opencode.ai/config.json\",\n mcp: mcpConfig,\n },\n { mergeObjectKeys: [\"mcp\"] },\n ),\n });\n }\n\n return files;\n }\n}\n","import { join } from \"node:path\";\nimport { BaseSerializer } from \"./base-serializer.js\";\nimport { getPlatform } from \"./registry.js\";\nimport { listInstalledCopilotPluginPinCreateInputs } from \"../plugins/copilot-installed.js\";\nimport { serializedAgentDocument } from \"../services/agent-bridge.js\";\nimport { parseMcpServersDocument } from \"../services/mcp-config-bridge.js\";\nimport type {\n AgentMetadata,\n PlatformDefinition,\n ResourceCreateInput,\n Resource,\n SerializedFile,\n McpServerMetadata,\n SerializeOptions,\n} from \"../types.js\";\n\ninterface CopilotSerializedMcpEntry {\n type: \"http\" | \"local\";\n tools: string[];\n url?: string;\n command?: string;\n args?: string[];\n env?: Record<string, string>;\n headers?: Record<string, string>;\n}\n\nexport class CopilotSerializer extends BaseSerializer {\n constructor(readonly platformId: \"github-copilot\" | \"copilot-cli\") {\n super();\n const p = getPlatform(platformId);\n if (!p) throw new Error(`${platformId} platform not found in registry`);\n this.platform = p;\n }\n\n readonly platform: PlatformDefinition;\n\n async scan(projectRoot: string): Promise<ResourceCreateInput[]> {\n const resources: ResourceCreateInput[] = [];\n\n // 1. Instructions\n if (this.platform.projectPaths.instructions) {\n const instrPath = join(\n projectRoot,\n this.platform.projectPaths.instructions,\n );\n const content = this.readFile(instrPath);\n if (content) {\n resources.push(\n this.makeResource(\n \"instruction\",\n `${this.platformId}-instructions`,\n content,\n this.platform.projectPaths.instructions,\n ),\n );\n }\n }\n\n // 2. Skills\n if (this.platform.projectPaths.skills) {\n resources.push(\n ...this.scanSkillsDir(projectRoot, this.platform.projectPaths.skills),\n );\n }\n\n // 3. Agents\n if (this.platform.projectPaths.agents) {\n const agentsPath = this.platform.projectPaths.agents;\n resources.push(\n ...this.scanAgentFilesAt(\n join(projectRoot, agentsPath),\n agentsPath.endsWith(\"/\") ? agentsPath : `${agentsPath}/`,\n [\".md\"],\n ),\n );\n }\n\n // 4. MCP servers\n if (this.platform.projectPaths.mcp) {\n const configPathValue = this.platform.projectPaths.mcp;\n const configPath = join(projectRoot, configPathValue);\n const configContent = this.readFile(configPath);\n if (configContent) {\n try {\n const document = JSON.parse(configContent) as unknown;\n for (const [name, metadata] of Object.entries(\n parseMcpServersDocument(document),\n )) {\n resources.push(\n this.makeResource(\n \"mcp_server\",\n name,\n \"\",\n configPathValue,\n metadata,\n ),\n );\n }\n } catch {\n // ignore invalid JSON\n }\n }\n }\n\n return resources;\n }\n\n async scanGlobal(homeRoot: string): Promise<ResourceCreateInput[]> {\n const resources: ResourceCreateInput[] = [];\n\n // Global skills\n if (this.platform.globalPaths.skills) {\n const skillsDir = this.resolveHomePath(\n homeRoot,\n this.platform.globalPaths.skills,\n );\n resources.push(\n ...this.scanSkillsDirAt(skillsDir, this.platform.globalPaths.skills),\n );\n }\n\n // Global config (MCP)\n if (this.platform.globalPaths.settings) {\n const settingsPath = this.platform.globalPaths.settings;\n const configPath = this.resolveHomePath(homeRoot, settingsPath);\n const configContent = this.readFile(configPath);\n if (configContent) {\n try {\n const document = JSON.parse(configContent) as unknown;\n for (const [name, metadata] of Object.entries(\n parseMcpServersDocument(document),\n )) {\n resources.push(\n this.makeResource(\n \"mcp_server\",\n name,\n \"\",\n settingsPath,\n metadata,\n ),\n );\n }\n } catch {\n // ignore invalid JSON\n }\n }\n }\n\n if (this.platform.globalPaths.plugins) {\n resources.push(...listInstalledCopilotPluginPinCreateInputs(homeRoot));\n }\n\n return resources;\n }\n\n async serialize(\n resources: Resource[],\n _projectRoot: string,\n options: SerializeOptions = {},\n ): Promise<SerializedFile[]> {\n const files: SerializedFile[] = [];\n const target = options.target ?? \"project\";\n const targetPaths = this.getTargetPaths(target);\n const instructionsPath = this.toTargetRelativePath(targetPaths.instructions, target);\n const skillsPath = this.toTargetRelativePath(targetPaths.skills, target);\n const agentsPath = this.toTargetRelativePath(targetPaths.agents, target);\n const mcpPath = this.toTargetRelativePath(\n target === \"global\" ? targetPaths.settings : targetPaths.mcp,\n target,\n );\n\n // Instructions (and instruction-only skills merged for copilot)\n const instructions = resources.filter((r) => r.type === \"instruction\");\n const skills = resources.filter((r) => r.type === \"skill\");\n const instructionOnlySkills =\n this.platform.skillEmission === \"instruction-only\";\n const instructionOnlySink = Boolean(instructionsPath);\n\n if (instructions.length > 0 && instructionsPath) {\n const parts: string[] = instructions.map((r) => r.content);\n if (instructionOnlySkills) {\n for (const r of skills) {\n parts.push(`## ${r.name}\\n\\n${r.content}`);\n }\n }\n files.push({\n path: instructionsPath,\n content: parts.join(\"\\n\\n\"),\n });\n } else if (instructionOnlySkills && skills.length > 0 && instructionsPath) {\n const parts = skills.map((r) => `## ${r.name}\\n\\n${r.content}`);\n files.push({\n path: instructionsPath,\n content: parts.join(\"\\n\\n\"),\n });\n }\n\n // Skills (native emission when not instruction-only, or no instruction sink)\n if (\n skillsPath &&\n (!instructionOnlySkills || !instructionOnlySink) &&\n skills.length > 0\n ) {\n for (const r of skills) {\n files.push(\n ...this.emitSkillWithAuxiliary(\n r,\n join(skillsPath, r.name, \"SKILL.md\"),\n options,\n ),\n );\n }\n }\n\n // Agents\n const agents = resources.filter((r) => r.type === \"agent\");\n if (agentsPath && agents.length > 0) {\n const agentsDir = agentsPath.endsWith(\"/\") ? agentsPath : `${agentsPath}/`;\n for (const r of agents) {\n files.push({\n path: join(agentsDir, `${r.name}.md`),\n content: serializedAgentDocument(\n {\n name: r.name,\n description: r.description,\n content: r.content,\n metadata: r.metadata as AgentMetadata,\n },\n \"generic\",\n ),\n });\n }\n }\n\n // MCP servers\n const mcps = this.mcpServersForTarget(resources, mcpPath);\n if (mcps.length > 0 && mcpPath) {\n const mcpServers: Record<string, CopilotSerializedMcpEntry> = {};\n for (const r of mcps) {\n const meta = r.metadata as McpServerMetadata;\n if (meta.transport === \"http\" || meta.url) {\n mcpServers[r.name] = {\n type: \"http\",\n url: meta.url,\n tools: [\"*\"],\n ...(meta.headers && Object.keys(meta.headers).length > 0\n ? { headers: meta.headers }\n : {}),\n };\n } else {\n mcpServers[r.name] = {\n type: \"local\",\n command: meta.command,\n args: meta.args,\n env: meta.env,\n tools: [\"*\"],\n };\n }\n }\n files.push({\n path: mcpPath,\n content: JSON.stringify({ mcpServers }, null, 2),\n });\n }\n\n return files;\n }\n}\n","import { join } from \"node:path\";\nimport { parse as parseToml, stringify as stringifyToml } from \"smol-toml\";\nimport { BaseSerializer } from \"./base-serializer.js\";\nimport { getPlatform } from \"./registry.js\";\nimport type {\n PlatformDefinition,\n ResourceCreateInput,\n Resource,\n SerializedFile,\n SerializeOptions,\n} from \"../types.js\";\n\ninterface GeminiExtensionManifest {\n name?: string;\n version?: string;\n description?: string;\n contextFileName?: string;\n}\n\ninterface GeminiInstructionMetadata {\n contextFileName?: string;\n extension?: GeminiExtensionManifest;\n}\n\ninterface GeminiCommandMetadata {\n format?: \"toml\" | \"md\";\n}\n\nexport class GeminiCliSerializer extends BaseSerializer {\n readonly platformId = \"gemini-cli\";\n readonly platform: PlatformDefinition;\n\n constructor() {\n super();\n const p = getPlatform(\"gemini-cli\");\n if (!p) throw new Error(\"gemini-cli platform not found in registry\");\n this.platform = p;\n }\n\n private scanCommandsAt(\n projectRoot: string,\n relativeDir: string,\n ): ResourceCreateInput[] {\n const resources: ResourceCreateInput[] = [];\n const commandsDir = join(projectRoot, relativeDir);\n const sourcePrefix = relativeDir.endsWith(\"/\")\n ? relativeDir\n : `${relativeDir}/`;\n\n for (const file of this.listDir(commandsDir)) {\n const commandPath = join(commandsDir, file);\n const name = file.replace(/\\.(md|toml)$/, \"\");\n if (name === file) continue;\n\n if (file.endsWith(\".md\")) {\n const content = this.readFile(commandPath);\n if (!content) continue;\n resources.push(\n this.makeResource(\n \"command\",\n name,\n content.trim(),\n `${sourcePrefix}${file}`,\n { format: \"md\" } satisfies GeminiCommandMetadata,\n ),\n );\n continue;\n }\n\n if (!file.endsWith(\".toml\")) continue;\n\n const raw = this.readFile(commandPath);\n if (!raw) continue;\n\n let parsed: { description?: string; prompt?: string };\n try {\n parsed = parseToml(raw) as { description?: string; prompt?: string };\n } catch {\n continue;\n }\n\n const description =\n typeof parsed.description === \"string\" ? parsed.description : \"\";\n const content =\n typeof parsed.prompt === \"string\" ? parsed.prompt : raw.trim();\n\n resources.push(\n this.makeResource(\n \"command\",\n name,\n content,\n `${sourcePrefix}${file}`,\n { format: \"toml\" } satisfies GeminiCommandMetadata,\n description,\n ),\n );\n }\n\n return resources;\n }\n\n private commandOutputPath(\n resource: Resource,\n defaultCommandsPath: string,\n ): string {\n const metadata = resource.metadata as GeminiCommandMetadata;\n const extension = metadata.format === \"toml\" ? \"toml\" : \"md\";\n\n if (resource.source.includes(\"commands/\")) {\n return `commands/${resource.name}.${extension}`;\n }\n\n return `${defaultCommandsPath}${resource.name}.${extension}`;\n }\n\n private emitCommandContent(resource: Resource): string {\n const metadata = resource.metadata as GeminiCommandMetadata;\n if (metadata.format === \"toml\") {\n const payload: Record<string, string> = {\n prompt: resource.content,\n };\n if (resource.description) {\n payload.description = resource.description;\n }\n return `${stringifyToml(payload)}\\n`;\n }\n\n return resource.content;\n }\n\n async scan(projectRoot: string): Promise<ResourceCreateInput[]> {\n const resources: ResourceCreateInput[] = [];\n\n const manifestPath = join(projectRoot, \"gemini-extension.json\");\n const manifestContent = this.readFile(manifestPath);\n let manifest: GeminiExtensionManifest | undefined;\n let instructionImported = false;\n\n if (manifestContent) {\n try {\n manifest = JSON.parse(manifestContent) as GeminiExtensionManifest;\n } catch {\n manifest = undefined;\n }\n }\n\n if (manifest?.contextFileName) {\n const contextPath = join(projectRoot, manifest.contextFileName);\n const content = this.readFile(contextPath);\n if (content) {\n resources.push(\n this.makeResource(\n \"instruction\",\n \"gemini-instructions\",\n content,\n manifest.contextFileName,\n {\n contextFileName: manifest.contextFileName,\n extension: manifest,\n } satisfies GeminiInstructionMetadata,\n ),\n );\n instructionImported = true;\n }\n }\n\n if (!instructionImported) {\n const agentsMd = this.readFile(join(projectRoot, \"AGENTS.md\"));\n if (agentsMd) {\n resources.push(\n this.makeResource(\n \"instruction\",\n \"gemini-instructions\",\n agentsMd,\n \"AGENTS.md\",\n manifest\n ? ({\n contextFileName: \"AGENTS.md\",\n extension: manifest,\n } satisfies GeminiInstructionMetadata)\n : {},\n ),\n );\n }\n }\n\n resources.push(...this.scanSkillsDir(projectRoot, \".agents/skills\"));\n resources.push(...this.scanSkillsDir(projectRoot, \"skills\"));\n\n resources.push(...this.scanCommandsAt(projectRoot, \"commands\"));\n\n return resources;\n }\n\n async scanGlobal(homeRoot: string): Promise<ResourceCreateInput[]> {\n const resources: ResourceCreateInput[] = [];\n\n if (this.platform.globalPaths.skills) {\n const skillsDir = this.resolveHomePath(\n homeRoot,\n this.platform.globalPaths.skills,\n );\n resources.push(\n ...this.scanSkillsDirAt(\n skillsDir,\n this.platform.globalPaths.skills.replace(/\\/$/, \"\"),\n ),\n );\n }\n\n return resources;\n }\n\n async serialize(\n resources: Resource[],\n _projectRoot: string,\n options: SerializeOptions = {},\n ): Promise<SerializedFile[]> {\n const files: SerializedFile[] = [];\n const target = options.target ?? \"project\";\n const targetPaths = this.getTargetPaths(target);\n const instructionsPath =\n this.toTargetRelativePath(targetPaths.instructions, target) ??\n (target === \"project\" ? \"AGENTS.md\" : undefined);\n const skillsPath =\n this.toTargetRelativePath(targetPaths.skills, target) ??\n (target === \"project\" ? \".agents/skills/\" : undefined);\n const commandsPath = this.toTargetRelativePath(targetPaths.commands, target);\n\n const instructions = resources.filter((r) => r.type === \"instruction\");\n const skills = resources.filter((r) => r.type === \"skill\");\n const commands = resources.filter((r) => r.type === \"command\");\n const instructionOnlySkills =\n this.platform.skillEmission === \"instruction-only\";\n const instructionOnlySink = Boolean(instructionsPath);\n\n if (instructions.length > 0 && instructionsPath) {\n const parts: string[] = instructions.map((r) => r.content);\n if (instructionOnlySkills) {\n for (const r of skills) {\n parts.push(`## ${r.name}\\n\\n${r.content}`);\n }\n }\n files.push({\n path: instructionsPath,\n content: parts.join(\"\\n\\n\"),\n });\n\n if (target === \"project\") {\n const firstMeta = instructions[0]?.metadata as GeminiInstructionMetadata;\n const extension = firstMeta.extension ?? {};\n const contextFileName =\n firstMeta.contextFileName ?? instructionsPath;\n\n const manifest: GeminiExtensionManifest = {\n ...extension,\n contextFileName,\n };\n\n files.push({\n path: \"gemini-extension.json\",\n content: `${JSON.stringify(manifest, null, 2)}\\n`,\n });\n }\n } else if (instructionOnlySkills && skills.length > 0 && instructionsPath) {\n const parts = skills.map((r) => `## ${r.name}\\n\\n${r.content}`);\n files.push({\n path: instructionsPath,\n content: parts.join(\"\\n\\n\"),\n });\n\n if (target === \"project\") {\n files.push({\n path: \"gemini-extension.json\",\n content: `${JSON.stringify({ contextFileName: instructionsPath }, null, 2)}\\n`,\n });\n }\n }\n\n if (\n skillsPath &&\n (!instructionOnlySkills || !instructionOnlySink) &&\n skills.length > 0\n ) {\n for (const r of skills) {\n files.push(\n ...this.emitSkillWithAuxiliary(\n r,\n `${skillsPath}${r.name}/SKILL.md`,\n options,\n ),\n );\n }\n }\n\n if (commandsPath) {\n for (const r of commands) {\n files.push({\n path: this.commandOutputPath(r, commandsPath),\n content: this.emitCommandContent(r),\n });\n }\n }\n\n return files;\n }\n}\n","import { join } from \"node:path\";\nimport { parse } from \"smol-toml\";\nimport { BaseSerializer } from \"./base-serializer.js\";\nimport { getPlatform } from \"./registry.js\";\nimport {\n overlayJsonPreservingFormat,\n overlayTomlPreservingFormat,\n} from \"../services/format-preserving-config.js\";\nimport { buildHooksJson, scanHooksFile } from \"../services/hook-serialization.js\";\nimport { serializedAgentDocument } from \"../services/agent-bridge.js\";\nimport type {\n AgentMetadata,\n HookMetadata,\n McpServerMetadata,\n ModelConfigMetadata,\n PermissionMetadata,\n PlatformDefinition,\n Resource,\n ResourceCreateInput,\n SerializedFile,\n SerializeOptions,\n} from \"../types.js\";\n\ntype GrokConfigDocument = Record<string, unknown>;\n\n/** Claude-compat project tree; kept off pathAlternates so Claude Code detection stays unique. */\nconst PROJECT_SKILL_COMPAT = [\".claude/skills/\"] as const;\n\ninterface GrokMcpServerEntry {\n command?: string;\n args?: string[];\n url?: string;\n env?: Record<string, string>;\n headers?: Record<string, string>;\n enabled?: boolean;\n cwd?: string;\n bearer_token_env_var?: string;\n startup_timeout_sec?: number;\n tool_timeout_sec?: number;\n}\n\ninterface GrokPermissionRule {\n action?: string;\n tool?: string;\n pattern?: string;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction parseGrokConfig(content: string): GrokConfigDocument | undefined {\n try {\n const parsed = parse(content);\n if (!isRecord(parsed)) return undefined;\n return parsed;\n } catch {\n return undefined;\n }\n}\n\nfunction permissionName(action: PermissionMetadata[\"action\"], pattern: string): string {\n const slug = pattern.replace(/[^a-zA-Z0-9]+/g, \"-\").replace(/^-|-$/g, \"\");\n return `${action}-${slug || \"rule\"}`;\n}\n\nfunction compactPermissionPattern(tool: string, pattern?: string): string {\n if (!pattern || pattern.length === 0) return tool;\n return `${tool}(${pattern})`;\n}\n\nfunction mergeConfigDocuments(\n existing: GrokConfigDocument,\n overlay: GrokConfigDocument,\n): GrokConfigDocument {\n const merged: GrokConfigDocument = { ...existing };\n\n for (const [key, value] of Object.entries(overlay)) {\n if (key === \"mcp_servers\" && isRecord(value) && isRecord(merged.mcp_servers)) {\n merged.mcp_servers = { ...merged.mcp_servers, ...value };\n continue;\n }\n if (key === \"permission\" && isRecord(value) && isRecord(merged.permission)) {\n merged.permission = { ...merged.permission, ...value };\n continue;\n }\n if (key === \"models\" && isRecord(value) && isRecord(merged.models)) {\n merged.models = { ...merged.models, ...value };\n continue;\n }\n merged[key] = value;\n }\n\n return merged;\n}\n\nfunction buildMcpServers(\n mcps: Resource[],\n): Record<string, Record<string, unknown>> {\n const mcpServers: Record<string, Record<string, unknown>> = {};\n\n for (const resource of mcps) {\n const metadata = resource.metadata as McpServerMetadata;\n const entry: Record<string, unknown> = {};\n if (metadata.transport === \"http\" || metadata.url) {\n if (metadata.url) entry.url = metadata.url;\n if (metadata.headers && Object.keys(metadata.headers).length > 0) {\n entry.headers = metadata.headers;\n }\n } else {\n if (metadata.command) entry.command = metadata.command;\n if (metadata.args && metadata.args.length > 0) entry.args = metadata.args;\n if (metadata.env && Object.keys(metadata.env).length > 0) {\n entry.env = metadata.env;\n }\n }\n mcpServers[resource.name] = entry;\n }\n\n return mcpServers;\n}\n\nfunction buildPermissionSection(\n permissions: Resource[],\n): Record<string, unknown> {\n const allow: string[] = [];\n const deny: string[] = [];\n const ask: string[] = [];\n\n for (const resource of permissions) {\n const metadata = resource.metadata as PermissionMetadata;\n switch (metadata.action) {\n case \"allow\":\n allow.push(metadata.pattern);\n break;\n case \"deny\":\n deny.push(metadata.pattern);\n break;\n case \"ask\":\n ask.push(metadata.pattern);\n break;\n default: {\n const _exhaustive: never = metadata.action;\n void _exhaustive;\n break;\n }\n }\n }\n\n const section: Record<string, unknown> = {};\n if (allow.length > 0) section.allow = allow;\n if (deny.length > 0) section.deny = deny;\n if (ask.length > 0) section.ask = ask;\n return section;\n}\n\nfunction hooksOutputPath(hooksPath: string): string {\n if (hooksPath.endsWith(\"/\")) {\n return `${hooksPath}harnesstap.json`;\n }\n return hooksPath;\n}\n\nfunction resolveGlobalPath(homeRoot: string, configuredPath: string): string {\n return configuredPath.startsWith(\"~/\")\n ? join(homeRoot, configuredPath.slice(2))\n : configuredPath;\n}\n\n/**\n * Native serializer for Grok Build (`.grok/` layout + `config.toml`).\n */\nexport class GrokBuildSerializer extends BaseSerializer {\n readonly platformId = \"grok-build\";\n readonly platform: PlatformDefinition;\n\n constructor() {\n super();\n const platform = getPlatform(\"grok-build\");\n if (!platform) throw new Error(\"grok-build platform not found in registry\");\n this.platform = platform;\n }\n\n private scanConfigResources(\n config: GrokConfigDocument,\n source: string,\n options: { includeModels: boolean },\n ): ResourceCreateInput[] {\n const resources: ResourceCreateInput[] = [];\n\n const mcpServers = config.mcp_servers;\n if (isRecord(mcpServers)) {\n for (const [name, entryValue] of Object.entries(mcpServers)) {\n if (!isRecord(entryValue)) continue;\n const entry = entryValue as GrokMcpServerEntry;\n const metadata: McpServerMetadata = {\n transport: entry.url ? \"http\" : \"stdio\",\n command: entry.command,\n args: entry.args,\n url: entry.url,\n env: entry.env,\n headers: entry.headers,\n };\n resources.push(\n this.makeResource(\"mcp_server\", name, \"\", source, metadata),\n );\n }\n }\n\n const permission = config.permission;\n if (isRecord(permission)) {\n for (const action of [\"allow\", \"deny\", \"ask\"] as const) {\n const patterns = permission[action];\n if (!Array.isArray(patterns)) continue;\n for (const pattern of patterns) {\n if (typeof pattern !== \"string\" || pattern.length === 0) continue;\n resources.push(\n this.makeResource(\n \"permission\",\n permissionName(action, pattern),\n \"\",\n source,\n { action, pattern } satisfies PermissionMetadata,\n ),\n );\n }\n }\n\n const rules = permission.rules;\n if (Array.isArray(rules)) {\n for (const ruleValue of rules) {\n if (!isRecord(ruleValue)) continue;\n const rule = ruleValue as GrokPermissionRule;\n if (\n rule.action !== \"allow\" &&\n rule.action !== \"deny\" &&\n rule.action !== \"ask\"\n ) {\n continue;\n }\n if (typeof rule.tool !== \"string\" || rule.tool.length === 0) continue;\n const pattern = compactPermissionPattern(rule.tool, rule.pattern);\n resources.push(\n this.makeResource(\n \"permission\",\n permissionName(rule.action, pattern),\n \"\",\n source,\n { action: rule.action, pattern } satisfies PermissionMetadata,\n ),\n );\n }\n }\n }\n\n if (options.includeModels && isRecord(config.models)) {\n const defaultModel = config.models.default;\n if (typeof defaultModel === \"string\" && defaultModel.length > 0) {\n resources.push(\n this.makeResource(\"model_config\", \"default\", \"\", source, {\n model: defaultModel,\n } satisfies ModelConfigMetadata),\n );\n }\n }\n\n return resources;\n }\n\n private scanConfigAt(\n fullPath: string,\n displayPath: string,\n options: { includeModels: boolean },\n ): ResourceCreateInput[] {\n const content = this.readFile(fullPath);\n if (!content) return [];\n const config = parseGrokConfig(content);\n if (!config) return [];\n return this.scanConfigResources(config, displayPath, options);\n }\n\n private scanHooksDir(\n fullPath: string,\n displayPath: string,\n ): ResourceCreateInput[] {\n const resources: ResourceCreateInput[] = [];\n const prefix = displayPath.endsWith(\"/\") ? displayPath : `${displayPath}/`;\n\n for (const file of this.listDir(fullPath)) {\n if (!file.endsWith(\".json\")) continue;\n resources.push(\n ...scanHooksFile(join(fullPath, file), `${prefix}${file}`),\n );\n }\n\n return resources;\n }\n\n private scanCommandsAt(\n fullPath: string,\n displayPath: string,\n ): ResourceCreateInput[] {\n const resources: ResourceCreateInput[] = [];\n const prefix = displayPath.endsWith(\"/\") ? displayPath : `${displayPath}/`;\n\n for (const file of this.listDir(fullPath)) {\n if (!file.endsWith(\".md\")) continue;\n const content = this.readFile(join(fullPath, file));\n if (!content) continue;\n resources.push(\n this.makeResource(\n \"command\",\n file.replace(/\\.md$/, \"\"),\n content,\n `${prefix}${file}`,\n ),\n );\n }\n\n return resources;\n }\n\n async scan(projectRoot: string): Promise<ResourceCreateInput[]> {\n const resources: ResourceCreateInput[] = [];\n\n const instructionPath = this.platform.projectPaths.instructions ?? \"AGENTS.md\";\n const instructions = this.readFile(join(projectRoot, instructionPath));\n if (instructions) {\n resources.push(\n this.makeResource(\n \"instruction\",\n \"grok-build-instructions\",\n instructions,\n instructionPath,\n ),\n );\n } else {\n for (const alternate of this.platform.projectPaths.pathAlternates?.instructions ?? []) {\n const content = this.readFile(join(projectRoot, alternate));\n if (!content) continue;\n resources.push(\n this.makeResource(\n \"instruction\",\n \"grok-build-instructions\",\n content,\n alternate,\n ),\n );\n break;\n }\n }\n\n const seenSkillNames = new Set<string>();\n const skillsPath = this.platform.projectPaths.skills ?? \".grok/skills/\";\n this.appendUniqueSkills(\n resources,\n seenSkillNames,\n this.scanSkillsDir(projectRoot, skillsPath),\n );\n for (const alternate of this.platform.projectPaths.pathAlternates?.skills ?? []) {\n this.appendUniqueSkills(\n resources,\n seenSkillNames,\n this.scanSkillsDir(projectRoot, alternate),\n );\n }\n for (const compatDir of PROJECT_SKILL_COMPAT) {\n this.appendUniqueSkills(\n resources,\n seenSkillNames,\n this.scanSkillsDir(projectRoot, compatDir),\n );\n }\n\n const agentsPath = this.platform.projectPaths.agents ?? \".grok/agents/\";\n resources.push(\n ...this.scanAgentFilesAt(\n join(projectRoot, agentsPath),\n agentsPath,\n [\".md\"],\n ),\n );\n\n const hooksPath = this.platform.projectPaths.hooks ?? \".grok/hooks/\";\n resources.push(\n ...this.scanHooksDir(join(projectRoot, hooksPath), hooksPath),\n );\n\n const commandsPath = this.platform.projectPaths.commands;\n if (commandsPath) {\n resources.push(\n ...this.scanCommandsAt(join(projectRoot, commandsPath), commandsPath),\n );\n }\n\n const configPath =\n this.platform.projectPaths.settings ??\n this.platform.projectPaths.mcp ??\n \".grok/config.toml\";\n resources.push(\n ...this.scanConfigAt(join(projectRoot, configPath), configPath, {\n includeModels: false,\n }),\n );\n\n return resources;\n }\n\n async scanGlobal(homeRoot: string): Promise<ResourceCreateInput[]> {\n const resources: ResourceCreateInput[] = [];\n\n const seenSkillNames = new Set<string>();\n const skillsPath = this.platform.globalPaths.skills ?? \"~/.grok/skills/\";\n this.appendUniqueSkills(\n resources,\n seenSkillNames,\n this.scanSkillsDirAt(\n resolveGlobalPath(homeRoot, skillsPath),\n skillsPath.replace(/\\/$/, \"\"),\n ),\n );\n for (const alternate of this.platform.globalPaths.pathAlternates?.skills ?? []) {\n this.appendUniqueSkills(\n resources,\n seenSkillNames,\n this.scanSkillsDirAt(\n resolveGlobalPath(homeRoot, alternate),\n alternate.replace(/\\/$/, \"\"),\n ),\n );\n }\n for (const related of this.platform.relatedLocations ?? []) {\n if (!related.surfaces.includes(\"skills\")) continue;\n this.appendUniqueSkills(\n resources,\n seenSkillNames,\n this.scanSkillsDirAt(\n resolveGlobalPath(homeRoot, related.path),\n related.path.replace(/\\/$/, \"\"),\n ),\n );\n }\n\n const agentsPath = this.platform.globalPaths.agents ?? \"~/.grok/agents/\";\n resources.push(\n ...this.scanAgentFilesAt(\n resolveGlobalPath(homeRoot, agentsPath),\n agentsPath,\n [\".md\"],\n ),\n );\n\n const hooksPath = this.platform.globalPaths.hooks ?? \"~/.grok/hooks/\";\n resources.push(\n ...this.scanHooksDir(resolveGlobalPath(homeRoot, hooksPath), hooksPath),\n );\n\n const commandsPath = this.platform.globalPaths.commands;\n if (commandsPath) {\n resources.push(\n ...this.scanCommandsAt(\n resolveGlobalPath(homeRoot, commandsPath),\n commandsPath,\n ),\n );\n }\n\n const configPath =\n this.platform.globalPaths.settings ?? \"~/.grok/config.toml\";\n resources.push(\n ...this.scanConfigAt(\n resolveGlobalPath(homeRoot, configPath),\n configPath,\n { includeModels: true },\n ),\n );\n\n return resources;\n }\n\n async serialize(\n resources: Resource[],\n projectRoot: string,\n options: SerializeOptions = {},\n ): Promise<SerializedFile[]> {\n const files: SerializedFile[] = [];\n const target = options.target ?? \"project\";\n const targetPaths = this.getTargetPaths(target);\n const instructionsPath =\n this.toTargetRelativePath(targetPaths.instructions, target) ??\n (target === \"project\" ? \"AGENTS.md\" : undefined);\n const skillsPath =\n this.toTargetRelativePath(targetPaths.skills, target) ??\n (target === \"project\" ? \".grok/skills/\" : undefined);\n const agentsPath = this.toTargetRelativePath(targetPaths.agents, target);\n const hooksPath = this.toTargetRelativePath(targetPaths.hooks, target);\n const commandsPath = this.toTargetRelativePath(targetPaths.commands, target);\n const configPath = this.toTargetRelativePath(\n targetPaths.settings ?? targetPaths.mcp,\n target,\n );\n\n const instructions = resources.filter((r) => r.type === \"instruction\");\n if (instructions.length > 0 && instructionsPath) {\n files.push({\n path: instructionsPath,\n content: instructions.map((r) => r.content).join(\"\\n\\n\"),\n });\n }\n\n for (const r of resources.filter((r) => r.type === \"skill\")) {\n if (!skillsPath) continue;\n files.push(\n ...this.emitSkillWithAuxiliary(\n r,\n `${skillsPath}${r.name}/SKILL.md`,\n options,\n ),\n );\n }\n\n for (const r of resources.filter((r) => r.type === \"agent\")) {\n if (!agentsPath) continue;\n files.push({\n path: `${agentsPath}${r.name}.md`,\n content: serializedAgentDocument(\n {\n name: r.name,\n description: r.description,\n content: r.content,\n metadata: r.metadata as AgentMetadata,\n },\n \"generic\",\n ),\n });\n }\n\n const commands = resources.filter((r) => r.type === \"command\");\n if (commandsPath && commands.length > 0) {\n const prefix = commandsPath.endsWith(\"/\")\n ? commandsPath\n : `${commandsPath}/`;\n for (const r of commands) {\n files.push({\n path: `${prefix}${r.name}.md`,\n content: r.content,\n });\n }\n }\n\n const mcps = this.mcpServersForTarget(resources, configPath);\n const permissions = resources.filter((r) => r.type === \"permission\");\n const modelConfigs = resources.filter((r) => r.type === \"model_config\");\n const managedCount =\n mcps.length +\n permissions.length +\n (target === \"global\" ? modelConfigs.length : 0);\n\n if (managedCount > 0 && configPath) {\n const existingContent = this.readFile(join(projectRoot, configPath));\n const overlay: GrokConfigDocument = {};\n\n if (mcps.length > 0) {\n overlay.mcp_servers = buildMcpServers(mcps);\n }\n if (permissions.length > 0) {\n overlay.permission = buildPermissionSection(permissions);\n }\n if (target === \"global\" && modelConfigs.length > 0) {\n const metadata = modelConfigs[0]?.metadata as ModelConfigMetadata;\n overlay.models = { default: metadata.model };\n }\n\n files.push({\n path: configPath,\n content: overlayTomlPreservingFormat(\n existingContent,\n overlay,\n mergeConfigDocuments,\n ),\n });\n }\n\n const hooks = resources.filter((r) => r.type === \"hook\");\n if (hooksPath && hooks.length > 0) {\n const relativeHooksPath = hooksOutputPath(hooksPath);\n const generated = buildHooksJson(\n hooks.map((r) => ({\n ...(r.metadata as HookMetadata),\n name: r.name,\n })),\n );\n files.push({\n path: relativeHooksPath,\n content: overlayJsonPreservingFormat(\n this.readFile(join(projectRoot, relativeHooksPath)),\n generated as unknown as Record<string, unknown>,\n { mergeObjectKeys: [\"hooks\"] },\n ),\n });\n }\n\n return files;\n }\n}\n","import { isAbsolute, join, relative, sep } from \"node:path\";\nimport { parse, stringify } from \"yaml\";\nimport { BaseSerializer } from \"./base-serializer.js\";\nimport {\n hooksBridgeInsertItem,\n mergeCordisPatch,\n mergeSettingsYaml,\n mcpResourceToInsertItem,\n parseCordisMcpServers,\n parseSettingsResources,\n resolveDshHome,\n sanitizePresetId,\n type CordisInsertItem,\n type SettingsOverlay,\n} from \"./deepseek-harness-home.js\";\nimport { listDshBundlePluginPinInputs } from \"../plugins/providers/deepseek-harness.js\";\nimport { getPlatform } from \"./registry.js\";\nimport { buildHooksJson, scanHooksFile } from \"../services/hook-serialization.js\";\nimport type {\n HookMetadata,\n McpServerMetadata,\n ModelConfigMetadata,\n PermissionMetadata,\n PlatformDefinition,\n Resource,\n ResourceCreateInput,\n SerializedFile,\n SerializeOptions,\n} from \"../types.js\";\n\nconst PROJECT_INSTRUCTION_CANDIDATES = [\n \"AGENTS.md\",\n \"CLAUDE.md\",\n \"AGENTS.local.md\",\n \"CLAUDE.local.md\",\n] as const;\n\nconst PERSONA_PLUGIN_NAME = \"@deepseek-ai/dsh-persona\";\nconst LEGAL_PERMISSION_PRESETS = new Set([\"workspace-write\", \"danger-full-access\"]);\n\nfunction instructionResourceName(path: string): string {\n if (path === \"AGENTS.md\") {\n return \"deepseek-harness-instructions\";\n }\n return `${path.slice(0, -\".md\".length)}-instructions`;\n}\n\nfunction hooksOutputPath(hooksPath: string): string {\n if (hooksPath.endsWith(\"/\")) {\n return `${hooksPath}harnesstap.json`;\n }\n return hooksPath;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction personaTextFromCordis(content: string): string | undefined {\n try {\n const parsed: unknown = parse(content);\n if (!Array.isArray(parsed)) return undefined;\n for (const item of parsed) {\n if (!isRecord(item) || item.name !== PERSONA_PLUGIN_NAME) continue;\n if (!isRecord(item.config) || typeof item.config.text !== \"string\") continue;\n return item.config.text;\n }\n } catch {\n return undefined;\n }\n return undefined;\n}\n\nfunction presetDescription(content: string | undefined): string {\n if (!content) return \"\";\n try {\n const parsed: unknown = parse(content);\n if (isRecord(parsed) && typeof parsed.description === \"string\") {\n return parsed.description;\n }\n } catch {\n return \"\";\n }\n return \"\";\n}\n\nfunction dshRelative(homeRoot: string, dshHome: string, subpath: string): string {\n const rel = relative(homeRoot, join(dshHome, subpath));\n if (isAbsolute(rel) || rel.startsWith(\"..\")) {\n throw new Error(\"$DSH_HOME must be inside the home directory for apply\");\n }\n return rel.split(sep).join(\"/\");\n}\n\n/**\n * Native serializer for DeepSeek Harness (`.dsh/` layout).\n * Project scan/apply writes portable files; global scan/apply owns `$DSH_HOME`.\n */\nexport class DeepSeekHarnessSerializer extends BaseSerializer {\n readonly platformId = \"deepseek-harness\";\n readonly platform: PlatformDefinition;\n\n constructor() {\n super();\n const platform = getPlatform(\"deepseek-harness\");\n if (!platform) throw new Error(\"deepseek-harness platform not found in registry\");\n this.platform = platform;\n }\n\n private scanHooksDir(\n fullPath: string,\n displayPath: string,\n ): ResourceCreateInput[] {\n const resources: ResourceCreateInput[] = [];\n const prefix = displayPath.endsWith(\"/\") ? displayPath : `${displayPath}/`;\n\n for (const file of this.listDir(fullPath)) {\n if (!file.endsWith(\".json\")) continue;\n resources.push(\n ...scanHooksFile(join(fullPath, file), `${prefix}${file}`),\n );\n }\n\n return resources;\n }\n\n private appendSkillsFrom(\n projectRoot: string,\n skillsDir: string,\n resources: ResourceCreateInput[],\n seenSkillNames: Set<string>,\n ): void {\n for (const resource of this.scanSkillsDir(projectRoot, skillsDir)) {\n if (resource.type !== \"skill\") continue;\n if (seenSkillNames.has(resource.name)) continue;\n seenSkillNames.add(resource.name);\n resources.push(resource);\n }\n }\n\n async scan(projectRoot: string): Promise<ResourceCreateInput[]> {\n const resources: ResourceCreateInput[] = [];\n const seenSkillNames = new Set<string>();\n\n const seenInstructionContent = new Set<string>();\n for (const candidate of PROJECT_INSTRUCTION_CANDIDATES) {\n const content = this.readFile(join(projectRoot, candidate));\n if (!content) continue;\n const trimmed = content.trim();\n if (trimmed.length === 0 || seenInstructionContent.has(trimmed)) continue;\n seenInstructionContent.add(trimmed);\n resources.push(\n this.makeResource(\n \"instruction\",\n instructionResourceName(candidate),\n content,\n candidate,\n ),\n );\n }\n\n const skillsPath = this.platform.projectPaths.skills ?? \".dsh/skills/\";\n this.appendSkillsFrom(projectRoot, skillsPath, resources, seenSkillNames);\n for (const alternate of this.platform.projectPaths.pathAlternates?.skills ?? []) {\n this.appendSkillsFrom(projectRoot, alternate, resources, seenSkillNames);\n }\n\n const hooksPath = this.platform.projectPaths.hooks ?? \".dsh/hooks/\";\n resources.push(\n ...this.scanHooksDir(join(projectRoot, hooksPath), hooksPath),\n );\n\n return resources;\n }\n\n async scanGlobal(homeRoot: string): Promise<ResourceCreateInput[]> {\n const resources: ResourceCreateInput[] = [];\n const dshHome = resolveDshHome(homeRoot);\n\n const instructions = this.readFile(join(dshHome, \"AGENTS.md\"));\n if (instructions && instructions.trim().length > 0) {\n resources.push(\n this.makeResource(\n \"instruction\",\n \"deepseek-harness-instructions\",\n instructions,\n \"~/.dsh/AGENTS.md\",\n ),\n );\n }\n\n for (const resource of this.scanSkillsDirAt(join(dshHome, \"skills\"), \"~/.dsh/skills\")) {\n if (resource.type !== \"skill\") continue;\n resources.push(resource);\n }\n\n const patchContent = this.readFile(join(dshHome, \"cordis.patch.yml\"));\n if (patchContent) {\n resources.push(...parseCordisMcpServers(patchContent, \"~/.dsh/cordis.patch.yml\"));\n }\n\n resources.push(...this.scanHooksDir(join(dshHome, \"hooks\"), \"~/.dsh/hooks/\"));\n\n const settingsContent = this.readFile(join(dshHome, \"settings.yaml\"));\n if (settingsContent) {\n resources.push(...parseSettingsResources(settingsContent, \"~/.dsh/settings.yaml\"));\n }\n\n const presetsRoot = join(dshHome, \".agent-presets\");\n for (const entry of this.listDir(presetsRoot)) {\n const presetDir = join(presetsRoot, entry);\n if (!this.isDirectory(presetDir)) continue;\n const description = presetDescription(this.readFile(join(presetDir, \"preset.yml\")));\n const cordisYml = this.readFile(join(presetDir, \"agent.cordis.yml\"));\n const personaText = cordisYml ? personaTextFromCordis(cordisYml) : undefined;\n resources.push(\n this.makeResource(\n \"agent\",\n entry,\n personaText ?? description,\n `~/.dsh/.agent-presets/${entry}`,\n {},\n description,\n ),\n );\n }\n\n resources.push(...listDshBundlePluginPinInputs(homeRoot));\n\n return resources;\n }\n\n async serialize(\n resources: Resource[],\n projectRoot: string,\n options: SerializeOptions = {},\n ): Promise<SerializedFile[]> {\n const target = options.target ?? \"project\";\n if (target === \"global\") {\n return this.serializeGlobal(resources, projectRoot, options);\n }\n\n const files: SerializedFile[] = [];\n const targetPaths = this.getTargetPaths(target);\n const instructionsPath =\n this.toTargetRelativePath(targetPaths.instructions, target) ?? \"AGENTS.md\";\n const skillsPath =\n this.toTargetRelativePath(targetPaths.skills, target) ?? \".dsh/skills/\";\n const hooksPath =\n this.toTargetRelativePath(targetPaths.hooks, target) ?? \".dsh/hooks/\";\n\n const instructions = resources.filter((r) => r.type === \"instruction\");\n if (instructions.length > 0 && instructionsPath) {\n files.push({\n path: instructionsPath,\n content: instructions.map((r) => r.content).join(\"\\n\\n\"),\n });\n }\n\n for (const r of resources.filter((r) => r.type === \"skill\")) {\n if (!skillsPath) continue;\n files.push(\n ...this.emitSkillWithAuxiliary(\n r,\n `${skillsPath}${r.name}/SKILL.md`,\n options,\n ),\n );\n }\n\n const hooks = resources.filter((r) => r.type === \"hook\");\n if (hooksPath && hooks.length > 0) {\n files.push({\n path: hooksOutputPath(hooksPath),\n content: JSON.stringify(\n buildHooksJson(\n hooks.map((r) => ({\n ...(r.metadata as HookMetadata),\n name: r.name,\n })),\n ),\n null,\n 2,\n ),\n });\n }\n\n return files;\n }\n\n private serializeGlobal(\n resources: Resource[],\n projectRoot: string,\n options: SerializeOptions,\n ): SerializedFile[] {\n const dshHome = resolveDshHome(projectRoot);\n const rel = (subpath: string) => dshRelative(projectRoot, dshHome, subpath);\n\n const mcpServers = this.mcpServersForTarget(\n resources,\n this.platform.globalPaths.mcp,\n );\n const hooks = resources.filter((r) => r.type === \"hook\");\n const rows: CordisInsertItem[] = [];\n for (const server of mcpServers) {\n const item = mcpResourceToInsertItem(\n server.name,\n server.metadata as McpServerMetadata,\n );\n if (item) {\n rows.push(item);\n } else {\n console.warn(\n `Skipping MCP server \"${server.name}\": serverName must match [A-Za-z0-9_-]{1,32}`,\n );\n }\n }\n if (hooks.length > 0) {\n rows.push(hooksBridgeInsertItem(join(dshHome, \"hooks/harnesstap.json\")));\n }\n\n const patchPath = join(dshHome, \"cordis.patch.yml\");\n const existingPatch = this.readFile(patchPath);\n let patchYaml: string | undefined;\n if (rows.length > 0 || this.fileExists(patchPath)) {\n patchYaml = mergeCordisPatch(existingPatch, rows);\n }\n\n const modelConfig = resources.find((r) => r.type === \"model_config\");\n const permissionPreset = resources\n .filter((r) => r.type === \"permission\")\n .map((r) => (r.metadata as PermissionMetadata).pattern)\n .find((pattern) => LEGAL_PERMISSION_PRESETS.has(pattern));\n\n const settingsPath = join(dshHome, \"settings.yaml\");\n const existingSettings = this.readFile(settingsPath);\n let settingsYaml: string | undefined;\n if (modelConfig || permissionPreset) {\n const overlay: SettingsOverlay = {};\n if (modelConfig) {\n const meta = modelConfig.metadata as ModelConfigMetadata;\n overlay.model = { model: meta.model, provider: meta.provider };\n }\n if (permissionPreset) overlay.permissionPreset = permissionPreset;\n settingsYaml = mergeSettingsYaml(existingSettings, overlay);\n } else if (this.fileExists(settingsPath)) {\n settingsYaml = existingSettings ?? \"\";\n }\n\n const files: SerializedFile[] = [];\n\n const instructions = resources.filter((r) => r.type === \"instruction\");\n if (instructions.length > 0) {\n files.push({\n path: rel(\"AGENTS.md\"),\n content: instructions.map((r) => r.content).join(\"\\n\\n\"),\n });\n }\n\n for (const r of resources.filter((r) => r.type === \"skill\")) {\n files.push(\n ...this.emitSkillWithAuxiliary(r, rel(`skills/${r.name}/SKILL.md`), options),\n );\n }\n\n if (patchYaml !== undefined) {\n files.push({ path: rel(\"cordis.patch.yml\"), content: patchYaml });\n }\n\n if (hooks.length > 0) {\n files.push({\n path: rel(\"hooks/harnesstap.json\"),\n content: JSON.stringify(\n buildHooksJson(\n hooks.map((r) => ({\n ...(r.metadata as HookMetadata),\n name: r.name,\n })),\n ),\n null,\n 2,\n ),\n });\n }\n\n if (settingsYaml !== undefined) {\n files.push({ path: rel(\"settings.yaml\"), content: settingsYaml });\n }\n\n const agentsById = new Map<string, Resource>();\n for (const r of resources.filter((r) => r.type === \"agent\")) {\n agentsById.set(sanitizePresetId(r.name), r);\n }\n for (const [id, r] of agentsById) {\n files.push({\n path: rel(`.agent-presets/${id}/preset.yml`),\n content: stringify({\n name: r.description || r.name,\n description: r.description ?? \"\",\n }),\n });\n files.push({\n path: rel(`.agent-presets/${id}/agent.cordis.yml`),\n content: stringify([\n {\n id: \"persona\",\n name: PERSONA_PLUGIN_NAME,\n config: { text: r.content, complete: false },\n },\n ]),\n });\n }\n\n return files;\n }\n}\n","import { join } from \"node:path\";\nimport { Document, parse, Scalar, visit } from \"yaml\";\nimport type { McpServerMetadata, ResourceCreateInput } from \"../types.js\";\n\nexport const HARNESSTAP_PATCH_PREFIX = \"harnesstap-\";\nexport const MCP_CLIENT_PLUGIN_NAME = \"@deepseek-ai/dsh-mcp-client\";\nexport const HOOKS_CLAUDE_CODE_PLUGIN_NAME = \"@deepseek-ai/dsh-hooks-claude-code\";\nexport const MCP_SERVER_NAME_RE = /^[A-Za-z0-9_-]{1,32}$/;\n\nexport interface CordisInsertItem {\n id: string;\n name: string;\n config: Record<string, unknown>;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction yamlErrorSummary(error: unknown): string {\n const message = error instanceof Error ? error.message : String(error);\n const firstLine = message.split(\"\\n\")[0];\n return firstLine && firstLine.length > 0 ? firstLine : message;\n}\n\nfunction parseYamlOrSkip(content: string): unknown {\n try {\n return parse(content);\n } catch {\n return undefined;\n }\n}\n\nfunction parseYamlDocument(content: string, label: string): unknown {\n try {\n return parse(content);\n } catch (error) {\n throw new Error(`Malformed ${label}: ${yamlErrorSummary(error)}`);\n }\n}\n\nfunction stringifyYaml(value: unknown): string {\n const document = new Document(value);\n visit(document, {\n Scalar(_key, node) {\n if (typeof node.value === \"string\" && /\\s/.test(node.value)) {\n node.type = Scalar.QUOTE_DOUBLE;\n }\n },\n });\n return document.toString();\n}\n\nexport function resolveDshHome(homeRoot: string): string {\n const fromEnv = process.env.DSH_HOME?.trim();\n if (fromEnv) return fromEnv;\n return join(homeRoot, \".dsh\");\n}\n\nexport function sanitizePresetId(name: string): string {\n const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\");\n if (!slug || !/^[a-z0-9][a-z0-9-]*$/.test(slug)) return \"agent\";\n return slug;\n}\n\nexport function mcpResourceToInsertItem(\n serverName: string,\n metadata: McpServerMetadata,\n): CordisInsertItem | null {\n if (!MCP_SERVER_NAME_RE.test(serverName)) return null;\n const config: Record<string, unknown> = { serverName };\n if (metadata.transport === \"http\" || metadata.url) {\n config.transport = \"streamable-http\";\n if (metadata.url) config.url = metadata.url;\n if (metadata.headers && Object.keys(metadata.headers).length > 0) {\n config.headers = metadata.headers;\n }\n } else {\n config.transport = \"stdio\";\n if (metadata.command) config.command = metadata.command;\n if (metadata.args && metadata.args.length > 0) config.args = metadata.args;\n if (metadata.env && Object.keys(metadata.env).length > 0) config.env = metadata.env;\n }\n return {\n id: `${HARNESSTAP_PATCH_PREFIX}mcp-${serverName}`,\n name: MCP_CLIENT_PLUGIN_NAME,\n config,\n };\n}\n\nexport function hooksBridgeInsertItem(absoluteConfigPath: string): CordisInsertItem {\n return {\n id: `${HARNESSTAP_PATCH_PREFIX}hooks-claude-code`,\n name: HOOKS_CLAUDE_CODE_PLUGIN_NAME,\n config: { configPath: absoluteConfigPath },\n };\n}\n\nfunction isHarnessTapInsert(item: unknown): boolean {\n return isRecord(item) && typeof item.id === \"string\" && item.id.startsWith(HARNESSTAP_PATCH_PREFIX);\n}\n\nexport function mergeCordisPatch(\n existing: string | undefined,\n rows: CordisInsertItem[],\n): string {\n if (!existing || existing.trim().length === 0) {\n return stringifyYaml(rows.length > 0 ? [{ insert: rows }] : []);\n }\n const parsed: unknown = parseYamlDocument(existing, \"cordis.patch.yml\");\n if (!Array.isArray(parsed)) {\n throw new Error(\"Invalid cordis.patch.yml: expected a YAML list of patch operations\");\n }\n const nextOps: unknown[] = [];\n for (const op of parsed) {\n if (!isRecord(op) || !Array.isArray(op.insert)) {\n nextOps.push(op);\n continue;\n }\n const kept = op.insert.filter((item) => !isHarnessTapInsert(item));\n if (kept.length > 0) {\n nextOps.push({ ...op, insert: kept });\n }\n }\n if (rows.length > 0) {\n nextOps.push({ insert: rows });\n }\n return stringifyYaml(nextOps);\n}\n\nfunction mcpMetadataFromConfig(config: Record<string, unknown>): McpServerMetadata {\n const transport = config.transport === \"streamable-http\" ? \"http\" : \"stdio\";\n const headers = isRecord(config.headers)\n ? Object.fromEntries(\n Object.entries(config.headers).filter((entry): entry is [string, string] => typeof entry[1] === \"string\"),\n )\n : undefined;\n const env = isRecord(config.env)\n ? Object.fromEntries(\n Object.entries(config.env).filter((entry): entry is [string, string] => typeof entry[1] === \"string\"),\n )\n : undefined;\n const args = Array.isArray(config.args)\n ? config.args.filter((value): value is string => typeof value === \"string\")\n : undefined;\n return {\n transport,\n command: typeof config.command === \"string\" ? config.command : undefined,\n args,\n url: typeof config.url === \"string\" ? config.url : undefined,\n env,\n headers,\n };\n}\n\nfunction collectMcpItems(node: unknown, acc: ResourceCreateInput[], source: string): void {\n if (Array.isArray(node)) {\n for (const item of node) collectMcpItems(item, acc, source);\n return;\n }\n if (!isRecord(node)) return;\n if (Array.isArray(node.insert)) {\n collectMcpItems(node.insert, acc, source);\n return;\n }\n if (node.name !== MCP_CLIENT_PLUGIN_NAME || !isRecord(node.config)) return;\n const serverName = node.config.serverName;\n if (typeof serverName !== \"string\" || serverName.length === 0) return;\n acc.push({\n type: \"mcp_server\",\n name: serverName,\n description: \"\",\n content: \"\",\n metadata: mcpMetadataFromConfig(node.config),\n source,\n });\n}\n\nexport function parseCordisMcpServers(content: string, source: string): ResourceCreateInput[] {\n const parsed = parseYamlOrSkip(content);\n if (parsed === undefined) return [];\n const resources: ResourceCreateInput[] = [];\n collectMcpItems(parsed, resources, source);\n return resources;\n}\n\nexport interface SettingsOverlay {\n model?: { provider?: string; model: string };\n permissionPreset?: string;\n}\n\nexport function mergeSettingsYaml(existing: string | undefined, overlay: SettingsOverlay): string {\n let doc: Record<string, unknown> = {};\n if (existing && existing.trim().length > 0) {\n const parsed: unknown = parseYamlDocument(existing, \"settings.yaml\");\n if (!isRecord(parsed)) {\n throw new Error(\"Invalid settings.yaml: expected a YAML mapping\");\n }\n doc = { ...parsed };\n }\n if (overlay.model) {\n const previous = isRecord(doc[\"agent-default-model\"]) ? doc[\"agent-default-model\"] : {};\n doc[\"agent-default-model\"] = {\n ...previous,\n provider: overlay.model.provider ?? \"deepseek\",\n model: overlay.model.model,\n };\n }\n if (overlay.permissionPreset) {\n const previous = isRecord(doc.permission) ? doc.permission : {};\n doc.permission = { ...previous, defaultPreset: overlay.permissionPreset };\n }\n return stringifyYaml(doc);\n}\n\nexport function parseSettingsResources(content: string, source: string): ResourceCreateInput[] {\n const parsed = parseYamlOrSkip(content);\n if (!isRecord(parsed)) return [];\n const resources: ResourceCreateInput[] = [];\n const modelSection = parsed[\"agent-default-model\"];\n if (isRecord(modelSection) && typeof modelSection.model === \"string\") {\n resources.push({\n type: \"model_config\",\n name: \"default\",\n description: \"\",\n content: \"\",\n metadata: {\n model: modelSection.model,\n ...(typeof modelSection.provider === \"string\" ? { provider: modelSection.provider } : {}),\n },\n source,\n });\n }\n const permission = parsed.permission;\n if (isRecord(permission) && typeof permission.defaultPreset === \"string\") {\n resources.push({\n type: \"permission\",\n name: \"default\",\n description: \"\",\n content: \"\",\n metadata: { action: \"allow\", pattern: permission.defaultPreset },\n source,\n });\n }\n return resources;\n}\n","import { existsSync, readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { resolveDshHome } from \"../../platforms/deepseek-harness-home.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\";\nimport type { ResourceCreateInput } from \"../../types.js\";\n\nconst DSH_MISSING_MESSAGE = \"Install DeepSeek Harness (dsh) to manage plugins.\";\nconst REFRESH_MESSAGE =\n \"Use dsh plugin --profile web update to refresh DeepSeek Harness plugins\";\n\ninterface DshPackageJson {\n name?: string;\n version?: string;\n description?: string;\n dsh?: {\n bundle?: {\n patch?: unknown;\n };\n };\n}\n\nexport interface DeepSeekHarnessProviderDeps {\n runCommand?: RunCommand;\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\nexport function webProfileDir(homeRoot: string): string {\n return join(resolveDshHome(homeRoot), \"profiles\", \"web\");\n}\n\nfunction packageDirs(nodeModules: string): string[] {\n const dirs: string[] = [];\n for (const entry of readdirSync(nodeModules)) {\n if (entry.startsWith(\".\")) continue;\n const entryPath = join(nodeModules, entry);\n if (!isDirectory(entryPath)) continue;\n if (entry.startsWith(\"@\")) {\n for (const nested of readdirSync(entryPath)) {\n if (nested.startsWith(\".\")) continue;\n const nestedPath = join(entryPath, nested);\n if (isDirectory(nestedPath)) dirs.push(nestedPath);\n }\n continue;\n }\n dirs.push(entryPath);\n }\n return dirs;\n}\n\nfunction scanDshBundlePlugins(homeRoot: string): PluginInstall[] {\n const nodeModules = join(webProfileDir(homeRoot), \"node_modules\");\n if (!isDirectory(nodeModules)) return [];\n\n const installs: PluginInstall[] = [];\n for (const installPath of packageDirs(nodeModules)) {\n const pkg = readJson<DshPackageJson>(join(installPath, \"package.json\"));\n if (!pkg || typeof pkg.dsh?.bundle?.patch !== \"string\") continue;\n if (typeof pkg.name !== \"string\" || pkg.name.length === 0) continue;\n\n const name = pkg.name;\n const version = pkg.version;\n installs.push({\n ref: name,\n platformId: \"deepseek-harness\",\n name,\n version: version ?? \"0.0.0\",\n versionSource: version ? \"manifest\" : \"unknown\",\n scope: \"user\",\n enabled: true,\n installPath,\n metadata: {\n description: pkg.description,\n },\n });\n }\n return installs;\n}\n\nexport function listDshBundlePluginPinInputs(homeRoot: string): ResourceCreateInput[] {\n return scanDshBundlePlugins(homeRoot).map((install) => ({\n type: \"plugin\",\n name: install.name,\n description: install.metadata?.description ?? \"\",\n content: \"{}\",\n metadata: {\n source_kind: \"local\",\n sync_status: \"never_synced\",\n portable: \"reference\",\n },\n source: \"~/.dsh/profiles/web/\",\n origin_kind: \"manual\",\n origin_ref: install.name,\n }));\n}\n\nexport class DeepSeekHarnessPluginProvider implements PluginProvider {\n readonly platformId = \"deepseek-harness\";\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: DeepSeekHarnessProviderDeps = {}) {}\n\n private run(args: string[], ctx?: PluginContext): CommandResult {\n const run = this.deps.runCommand ?? defaultRunCommand;\n return run(\"dsh\", args, { cwd: ctx?.projectRoot });\n }\n\n async list(ctx: PluginContext): Promise<PluginInstall[]> {\n return scanDshBundlePlugins(ctx.homeRoot);\n }\n\n async check(\n ctx: PluginContext,\n opts: PluginCheckOptions,\n ): Promise<PluginCheckResult[]> {\n const installs = scanDshBundlePlugins(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: REFRESH_MESSAGE,\n refreshSkipped: true,\n }));\n }\n\n async update(\n ctx: PluginContext,\n opts: PluginUpdateOptions,\n ): Promise<PluginUpdateResult[]> {\n const installs = scanDshBundlePlugins(ctx.homeRoot);\n const targets = opts.ref\n ? installs.filter((install) => install.ref === opts.ref)\n : installs;\n return targets.map((install) => ({\n ref: install.ref,\n platformId: this.platformId,\n scope: install.scope,\n status: \"unsupported\" as const,\n previousVersion: install.version,\n message: REFRESH_MESSAGE,\n }));\n }\n\n async install(\n ctx: PluginContext,\n opts: PluginInstallOptions,\n ): Promise<PluginInstallResult> {\n const scope: PluginScope = opts.scope ?? \"user\";\n const result = this.run(\n [\"plugin\", \"--profile\", \"web\", \"add\", opts.ref],\n ctx,\n );\n if (result.exitCode === 0) {\n return {\n ref: opts.ref,\n platformId: this.platformId,\n scope,\n status: \"installed\",\n message: result.stdout.trim() || \"Installed via dsh plugin --profile web add\",\n };\n }\n if (result.exitCode === 127 || /not found/i.test(result.stderr)) {\n return {\n ref: opts.ref,\n platformId: this.platformId,\n scope,\n status: \"failed\",\n message: DSH_MISSING_MESSAGE,\n };\n }\n return {\n ref: opts.ref,\n platformId: this.platformId,\n scope,\n status: \"failed\",\n message: result.stderr.trim() || result.stdout.trim() || \"dsh plugin add failed\",\n };\n }\n}\n","import { spawnSync } from \"node:child_process\";\n\nexport interface CommandResult {\n stdout: string;\n stderr: string;\n exitCode: number;\n}\n\nexport interface RunCommandOptions {\n cwd?: string;\n timeoutMs?: number;\n}\n\nexport type RunCommand = (\n command: string,\n args: string[],\n options?: RunCommandOptions,\n) => CommandResult;\n\nexport const defaultRunCommand: RunCommand = (command, args, options) => {\n const result = spawnSync(command, args, {\n encoding: \"utf-8\",\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n cwd: options?.cwd,\n env: command === \"git\"\n ? { ...process.env, GIT_TERMINAL_PROMPT: \"0\", GCM_INTERACTIVE: \"never\" }\n : process.env,\n });\n return {\n stdout: result.stdout?.toString() ?? \"\",\n stderr: result.stderr?.toString() ?? \"\",\n exitCode: result.status ?? 1,\n };\n};\n","import { join } from \"node:path\";\nimport { BaseSerializer } from \"./base-serializer.js\";\nimport { getPlatform } from \"./registry.js\";\nimport { buildHooksJson, parseHooksJsonContent, scanHooksFile } from \"../services/hook-serialization.js\";\nimport { parseMcpServerEntry, parseMcpServersDocument } from \"../services/mcp-config-bridge.js\";\nimport { mergeMuseSettingsContent } from \"../services/merged-host-config.js\";\nimport type {\n HookMetadata,\n McpServerMetadata,\n PlatformDefinition,\n Resource,\n ResourceCreateInput,\n SerializedFile,\n SerializeOptions,\n} from \"../types.js\";\n\nconst PROJECT_INSTRUCTION_CANDIDATES = [\n \"AGENTS.md\",\n \"CLAUDE.md\",\n \".agents/AGENTS.md\",\n \".claude/CLAUDE.md\",\n] as const;\n\nconst PROJECT_SKILL_DIRS = [\".agents/skills/\", \".claude/skills/\", \".codex/skills/\"] as const;\n\nconst GLOBAL_SKILL_DIRS = [\n { full: (home: string) => join(home, \".config/muse/skills\"), source: \"~/.config/muse/skills\" },\n { full: (home: string) => join(home, \".agents/skills\"), source: \"~/.agents/skills\" },\n { full: (home: string) => join(home, \".claude/skills\"), source: \"~/.claude/skills\" },\n { full: (home: string) => join(home, \".codex/skills\"), source: \"~/.codex/skills\" },\n] as const;\n\nconst MUSE_SETTINGS_RELATIVE = \".config/muse/settings.json\";\nconst MUSE_SETTINGS_DISPLAY = \"~/.config/muse/settings.json\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction museMcpMetadata(entry: unknown): McpServerMetadata | null {\n const metadata = parseMcpServerEntry(entry);\n if (!metadata || !isRecord(entry)) return null;\n if (typeof entry.enabled === \"boolean\") {\n metadata.enabled = entry.enabled;\n }\n if (typeof entry.mode === \"string\") {\n metadata.mode = entry.mode;\n }\n if (typeof entry.framing === \"string\") {\n metadata.framing = entry.framing;\n }\n return metadata;\n}\n\nfunction emitMuseMcpServer(meta: McpServerMetadata): Record<string, unknown> {\n const enabled = meta.enabled ?? true;\n const mode = meta.mode ?? \"required\";\n if (meta.transport === \"http\" || Boolean(meta.url)) {\n const entry: Record<string, unknown> = {\n transport: \"streamable_http\",\n enabled,\n mode,\n };\n if (meta.url) entry.url = meta.url;\n if (meta.headers && Object.keys(meta.headers).length > 0) {\n entry.headers = meta.headers;\n }\n return entry;\n }\n\n const entry: Record<string, unknown> = {\n transport: \"stdio\",\n enabled,\n mode,\n };\n if (meta.command) entry.command = meta.command;\n entry.args = meta.args ?? [];\n if (meta.env && Object.keys(meta.env).length > 0) {\n entry.env = meta.env;\n }\n if (typeof meta.framing === \"string\" && meta.framing.length > 0) {\n entry.framing = meta.framing;\n }\n return entry;\n}\n\n/**\n * Native serializer for Muse Code (Meta).\n * Project: AGENTS.md, `.agents/skills/`, `.muse/hooks.json`.\n * Home: merge-safe `~/.config/muse/settings.json` (`schema_version`, `mcp_servers`, hooks).\n */\nexport class MuseCodeSerializer extends BaseSerializer {\n readonly platformId = \"muse-code\";\n readonly platform: PlatformDefinition;\n\n constructor() {\n super();\n const platform = getPlatform(\"muse-code\");\n if (!platform) throw new Error(\"muse-code platform not found in registry\");\n this.platform = platform;\n }\n\n private appendSkillsFrom(\n projectRoot: string,\n skillsDir: string,\n resources: ResourceCreateInput[],\n seenSkillNames: Set<string>,\n ): void {\n for (const resource of this.scanSkillsDir(projectRoot, skillsDir)) {\n if (resource.type !== \"skill\") continue;\n if (seenSkillNames.has(resource.name)) continue;\n seenSkillNames.add(resource.name);\n resources.push(resource);\n }\n }\n\n async scan(projectRoot: string): Promise<ResourceCreateInput[]> {\n const resources: ResourceCreateInput[] = [];\n\n for (const candidate of PROJECT_INSTRUCTION_CANDIDATES) {\n const content = this.readFile(join(projectRoot, candidate));\n if (!content || content.trim().length === 0) continue;\n resources.push(\n this.makeResource(\"instruction\", \"muse-code-instructions\", content, candidate),\n );\n break;\n }\n\n const seenSkillNames = new Set<string>();\n for (const skillsDir of PROJECT_SKILL_DIRS) {\n this.appendSkillsFrom(projectRoot, skillsDir, resources, seenSkillNames);\n }\n\n const hooksPath = this.platform.projectPaths.hooks ?? \".muse/hooks.json\";\n resources.push(...scanHooksFile(join(projectRoot, hooksPath), hooksPath));\n\n return resources;\n }\n\n async scanGlobal(homeRoot: string): Promise<ResourceCreateInput[]> {\n const resources: ResourceCreateInput[] = [];\n const seenSkillNames = new Set<string>();\n\n for (const dir of GLOBAL_SKILL_DIRS) {\n for (const resource of this.scanSkillsDirAt(dir.full(homeRoot), dir.source)) {\n if (resource.type !== \"skill\") continue;\n if (seenSkillNames.has(resource.name)) continue;\n seenSkillNames.add(resource.name);\n resources.push(resource);\n }\n }\n\n const settingsPath = join(homeRoot, MUSE_SETTINGS_RELATIVE);\n const settingsContent = this.readFile(settingsPath);\n if (settingsContent) {\n let parsed: unknown;\n try {\n parsed = JSON.parse(settingsContent) as unknown;\n } catch {\n parsed = undefined;\n }\n const servers = parseMcpServersDocument(parsed);\n const rawServers =\n isRecord(parsed) && isRecord(parsed.mcp_servers) ? parsed.mcp_servers : {};\n for (const [name, metadata] of Object.entries(servers)) {\n const extras = museMcpMetadata(rawServers[name]);\n resources.push(\n this.makeResource(\n \"mcp_server\",\n name,\n \"\",\n MUSE_SETTINGS_DISPLAY,\n extras ?? metadata,\n ),\n );\n }\n resources.push(...parseHooksJsonContent(settingsContent, MUSE_SETTINGS_DISPLAY));\n }\n\n return resources;\n }\n\n async serialize(\n resources: Resource[],\n projectRoot: string,\n options: SerializeOptions = {},\n ): Promise<SerializedFile[]> {\n const target = options.target ?? \"project\";\n if (target === \"global\") {\n return this.serializeGlobal(resources, projectRoot, options);\n }\n\n const files: SerializedFile[] = [];\n const targetPaths = this.getTargetPaths(target);\n const instructionsPath =\n this.toTargetRelativePath(targetPaths.instructions, target) ?? \"AGENTS.md\";\n const skillsPath =\n this.toTargetRelativePath(targetPaths.skills, target) ?? \".agents/skills/\";\n const hooksPath =\n this.toTargetRelativePath(targetPaths.hooks, target) ?? \".muse/hooks.json\";\n\n const instructions = resources.filter((r) => r.type === \"instruction\");\n if (instructions.length > 0) {\n files.push({\n path: instructionsPath,\n content: instructions.map((r) => r.content).join(\"\\n\\n\"),\n });\n }\n\n for (const r of resources.filter((r) => r.type === \"skill\")) {\n files.push(\n ...this.emitSkillWithAuxiliary(r, `${skillsPath}${r.name}/SKILL.md`, options),\n );\n }\n\n const hooks = resources.filter((r) => r.type === \"hook\");\n if (hooks.length > 0) {\n files.push({\n path: hooksPath,\n content: JSON.stringify(\n buildHooksJson(\n hooks.map((r) => ({\n ...(r.metadata as HookMetadata),\n name: r.name,\n })),\n ),\n null,\n 2,\n ),\n });\n }\n\n return files;\n }\n\n private serializeGlobal(\n resources: Resource[],\n homeRoot: string,\n options: SerializeOptions,\n ): SerializedFile[] {\n const files: SerializedFile[] = [];\n const skillsPath =\n this.toTargetRelativePath(this.platform.globalPaths.skills, \"global\")\n ?? \".config/muse/skills/\";\n\n for (const r of resources.filter((resource) => resource.type === \"skill\")) {\n files.push(\n ...this.emitSkillWithAuxiliary(\n r,\n `${skillsPath}${r.name}/SKILL.md`,\n options,\n ),\n );\n }\n\n const mcpPath = this.platform.globalPaths.mcp ?? MUSE_SETTINGS_DISPLAY;\n const mcpServers = this.mcpServersForTarget(resources, mcpPath);\n const hooks = resources.filter((resource) => resource.type === \"hook\");\n if (mcpServers.length === 0 && hooks.length === 0) {\n return files;\n }\n\n const overlay: Record<string, unknown> = { schema_version: 1 };\n if (mcpServers.length > 0) {\n const servers: Record<string, Record<string, unknown>> = {};\n for (const server of mcpServers) {\n servers[server.name] = emitMuseMcpServer(server.metadata as McpServerMetadata);\n }\n overlay.mcp_servers = servers;\n }\n if (hooks.length > 0) {\n overlay.hooks = buildHooksJson(\n hooks.map((r) => ({\n ...(r.metadata as HookMetadata),\n name: r.name,\n })),\n ).hooks;\n }\n\n const existing = this.readFile(join(homeRoot, MUSE_SETTINGS_RELATIVE));\n files.push({\n path: MUSE_SETTINGS_RELATIVE,\n content: mergeMuseSettingsContent(existing, JSON.stringify(overlay)),\n });\n\n return files;\n }\n}\n","import { join } from \"node:path\";\nimport { BaseSerializer } from \"./base-serializer.js\";\nimport { getPlatform } from \"./registry.js\";\nimport { parseMcpServerEntry, parseMcpServersDocument } from \"../services/mcp-config-bridge.js\";\nimport { mergeMinimaxMcpContent } from \"../services/merged-host-config.js\";\nimport type {\n McpServerMetadata,\n PlatformDefinition,\n Resource,\n ResourceCreateInput,\n SerializedFile,\n SerializeOptions,\n} from \"../types.js\";\n\nconst PROJECT_INSTRUCTION_CANDIDATES = [\n \"AGENTS.md\",\n \"CLAUDE.md\",\n \".agents/AGENTS.md\",\n] as const;\n\nconst PROJECT_SKILL_DIRS = [\".minimax/skills/\", \".agents/skills/\", \".claude/skills/\"] as const;\n\nconst GLOBAL_SKILL_DIRS = [\n { full: (home: string) => join(home, \".minimax/skills\"), source: \"~/.minimax/skills\" },\n { full: (home: string) => join(home, \".agents/skills\"), source: \"~/.agents/skills\" },\n { full: (home: string) => join(home, \".claude/skills\"), source: \"~/.claude/skills\" },\n { full: (home: string) => join(home, \".codex/skills\"), source: \"~/.codex/skills\" },\n] as const;\n\nconst PROJECT_MCP_PATH = \".mcp.json\";\nconst MINIMAX_MCP_RELATIVE = \".minimax/mcp.json\";\nconst MINIMAX_MCP_DISPLAY = \"~/.minimax/mcp.json\";\nconst MINIMAX_MCP_LEGACY_RELATIVE = \".minimax/mcp/mcp.json\";\nconst MINIMAX_MCP_LEGACY_DISPLAY = \"~/.minimax/mcp/mcp.json\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction minimaxMcpMetadata(entry: unknown): McpServerMetadata | null {\n const metadata = parseMcpServerEntry(entry);\n if (!metadata || !isRecord(entry)) return null;\n if (typeof entry.enabled === \"boolean\") {\n metadata.enabled = entry.enabled;\n }\n if (typeof entry.type === \"string\") {\n metadata.connection_type = entry.type;\n }\n return metadata;\n}\n\nfunction emitMinimaxMcpServer(meta: McpServerMetadata): Record<string, unknown> {\n const enabled = meta.enabled ?? true;\n if (meta.transport === \"http\" || Boolean(meta.url)) {\n const type = remoteTransportType(meta);\n const entry: Record<string, unknown> = { type, enabled };\n if (meta.url) entry.url = meta.url;\n if (meta.headers && Object.keys(meta.headers).length > 0) {\n entry.headers = meta.headers;\n }\n return entry;\n }\n\n const entry: Record<string, unknown> = {\n type: \"stdio\",\n enabled,\n };\n if (meta.command) entry.command = meta.command;\n entry.args = meta.args ?? [];\n if (meta.env && Object.keys(meta.env).length > 0) {\n entry.env = meta.env;\n }\n return entry;\n}\n\nfunction remoteTransportType(meta: McpServerMetadata): string {\n const raw = meta.connection_type?.toLowerCase();\n if (raw === \"sse\") return \"sse\";\n if (raw === \"http\") return \"http\";\n if (raw === \"streamable-http\" || raw === \"streamable_http\") return \"streamable-http\";\n return \"streamable-http\";\n}\n\n/**\n * Native serializer for MiniMax Code (`mcode`).\n * Project: AGENTS.md, `.minimax/skills/`, `.mcp.json`.\n * Home: merge-safe `~/.minimax/mcp.json`. Install dir `~/.minimax-code` is not user data.\n */\nexport class MiniMaxCodeSerializer extends BaseSerializer {\n readonly platformId = \"minimax-code\";\n readonly platform: PlatformDefinition;\n\n constructor() {\n super();\n const platform = getPlatform(\"minimax-code\");\n if (!platform) throw new Error(\"minimax-code platform not found in registry\");\n this.platform = platform;\n }\n\n private appendSkillsFrom(\n projectRoot: string,\n skillsDir: string,\n resources: ResourceCreateInput[],\n seenSkillNames: Set<string>,\n ): void {\n for (const resource of this.scanSkillsDir(projectRoot, skillsDir)) {\n if (resource.type !== \"skill\") continue;\n if (seenSkillNames.has(resource.name)) continue;\n seenSkillNames.add(resource.name);\n resources.push(resource);\n }\n }\n\n private scanMcpFile(\n fullPath: string,\n displayPath: string,\n resources: ResourceCreateInput[],\n seenNames: Set<string>,\n ): void {\n const content = this.readFile(fullPath);\n if (!content) return;\n let parsed: unknown;\n try {\n parsed = JSON.parse(content) as unknown;\n } catch {\n return;\n }\n const servers = parseMcpServersDocument(parsed);\n const rawServers =\n isRecord(parsed) && isRecord(parsed.mcpServers) ? parsed.mcpServers : {};\n for (const [name, metadata] of Object.entries(servers)) {\n if (seenNames.has(name)) continue;\n seenNames.add(name);\n const extras = minimaxMcpMetadata(rawServers[name]);\n resources.push(\n this.makeResource(\n \"mcp_server\",\n name,\n \"\",\n displayPath,\n extras ?? metadata,\n ),\n );\n }\n }\n\n async scan(projectRoot: string): Promise<ResourceCreateInput[]> {\n const resources: ResourceCreateInput[] = [];\n\n for (const candidate of PROJECT_INSTRUCTION_CANDIDATES) {\n const content = this.readFile(join(projectRoot, candidate));\n if (!content || content.trim().length === 0) continue;\n resources.push(\n this.makeResource(\"instruction\", \"minimax-code-instructions\", content, candidate),\n );\n break;\n }\n\n const seenSkillNames = new Set<string>();\n for (const skillsDir of PROJECT_SKILL_DIRS) {\n this.appendSkillsFrom(projectRoot, skillsDir, resources, seenSkillNames);\n }\n\n this.scanMcpFile(\n join(projectRoot, PROJECT_MCP_PATH),\n PROJECT_MCP_PATH,\n resources,\n new Set(),\n );\n\n return resources;\n }\n\n async scanGlobal(homeRoot: string): Promise<ResourceCreateInput[]> {\n const resources: ResourceCreateInput[] = [];\n const seenSkillNames = new Set<string>();\n\n for (const dir of GLOBAL_SKILL_DIRS) {\n for (const resource of this.scanSkillsDirAt(dir.full(homeRoot), dir.source)) {\n if (resource.type !== \"skill\") continue;\n if (seenSkillNames.has(resource.name)) continue;\n seenSkillNames.add(resource.name);\n resources.push(resource);\n }\n }\n\n const seenMcpNames = new Set<string>();\n this.scanMcpFile(\n join(homeRoot, MINIMAX_MCP_RELATIVE),\n MINIMAX_MCP_DISPLAY,\n resources,\n seenMcpNames,\n );\n this.scanMcpFile(\n join(homeRoot, MINIMAX_MCP_LEGACY_RELATIVE),\n MINIMAX_MCP_LEGACY_DISPLAY,\n resources,\n seenMcpNames,\n );\n\n return resources;\n }\n\n async serialize(\n resources: Resource[],\n projectRoot: string,\n options: SerializeOptions = {},\n ): Promise<SerializedFile[]> {\n const target = options.target ?? \"project\";\n if (target === \"global\") {\n return this.serializeGlobal(resources, projectRoot, options);\n }\n\n const files: SerializedFile[] = [];\n const targetPaths = this.getTargetPaths(target);\n const instructionsPath =\n this.toTargetRelativePath(targetPaths.instructions, target) ?? \"AGENTS.md\";\n const skillsPath =\n this.toTargetRelativePath(targetPaths.skills, target) ?? \".minimax/skills/\";\n\n const instructions = resources.filter((r) => r.type === \"instruction\");\n if (instructions.length > 0) {\n files.push({\n path: instructionsPath,\n content: instructions.map((r) => r.content).join(\"\\n\\n\"),\n });\n }\n\n for (const r of resources.filter((r) => r.type === \"skill\")) {\n files.push(\n ...this.emitSkillWithAuxiliary(r, `${skillsPath}${r.name}/SKILL.md`, options),\n );\n }\n\n const mcpServers = this.mcpServersForTarget(resources, PROJECT_MCP_PATH);\n if (mcpServers.length > 0) {\n const servers: Record<string, Record<string, unknown>> = {};\n for (const server of mcpServers) {\n servers[server.name] = emitMinimaxMcpServer(server.metadata as McpServerMetadata);\n }\n const existing = this.readFile(join(projectRoot, PROJECT_MCP_PATH));\n files.push({\n path: PROJECT_MCP_PATH,\n content: mergeMinimaxMcpContent(existing, JSON.stringify({ mcpServers: servers })),\n });\n }\n\n return files;\n }\n\n private serializeGlobal(\n resources: Resource[],\n homeRoot: string,\n options: SerializeOptions,\n ): SerializedFile[] {\n const files: SerializedFile[] = [];\n const skillsPath =\n this.toTargetRelativePath(this.platform.globalPaths.skills, \"global\")\n ?? \".minimax/skills/\";\n\n for (const r of resources.filter((resource) => resource.type === \"skill\")) {\n files.push(\n ...this.emitSkillWithAuxiliary(\n r,\n `${skillsPath}${r.name}/SKILL.md`,\n options,\n ),\n );\n }\n\n const mcpPath = this.platform.globalPaths.mcp ?? MINIMAX_MCP_DISPLAY;\n const mcpServers = this.mcpServersForTarget(resources, mcpPath);\n if (mcpServers.length === 0) {\n return files;\n }\n\n const servers: Record<string, Record<string, unknown>> = {};\n for (const server of mcpServers) {\n servers[server.name] = emitMinimaxMcpServer(server.metadata as McpServerMetadata);\n }\n\n const existing = this.readFile(join(homeRoot, MINIMAX_MCP_RELATIVE));\n files.push({\n path: MINIMAX_MCP_RELATIVE,\n content: mergeMinimaxMcpContent(existing, JSON.stringify({ mcpServers: servers })),\n });\n\n return files;\n }\n}\n","import { join } from \"node:path\";\nimport { BaseSerializer } from \"./base-serializer.js\";\nimport { getPlatform } from \"./registry.js\";\nimport { serializedAgentDocument } from \"../services/agent-bridge.js\";\nimport { buildHooksJson, scanHooksFile } from \"../services/hook-serialization.js\";\nimport { parseMcpServersDocument } from \"../services/mcp-config-bridge.js\";\nimport type {\n AgentMetadata,\n PlatformDefinition,\n ResourceCreateInput,\n Resource,\n SerializedFile,\n RuleMetadata,\n McpServerMetadata,\n HookMetadata,\n SerializeOptions,\n} from \"../types.js\";\n\ninterface GenericSerializedMcpEntry {\n url?: string;\n protocol?: string;\n command?: string;\n args?: string[];\n env?: Record<string, string>;\n headers?: Record<string, string>;\n}\n\nfunction resolveGlobalPath(homeRoot: string, configuredPath: string): string {\n return configuredPath.startsWith(\"~/\")\n ? join(homeRoot, configuredPath.slice(2))\n : configuredPath;\n}\n\n/**\n * Generic serializer for platforms that follow standard configurations\n * including AGENTS.md, skills, mcp_config.json, rules, and hooks natively.\n */\nexport class GenericAgentsSerializer extends BaseSerializer {\n readonly platformId: string;\n readonly platform: PlatformDefinition;\n\n constructor(platformId: string) {\n super();\n this.platformId = platformId;\n const p = getPlatform(platformId);\n if (!p) throw new Error(`${platformId} platform not found in registry`);\n this.platform = p;\n }\n\n private scanRulesAt(fullPath: string, displayPath: string): ResourceCreateInput[] {\n const resources: ResourceCreateInput[] = [];\n if (displayPath.endsWith(\"/\")) {\n for (const file of this.listDir(fullPath)) {\n if (!file.endsWith(\".md\") && !file.endsWith(\".mdc\")) continue;\n const raw = this.readFile(join(fullPath, file));\n if (!raw) continue;\n const parsed = this.tryParseFrontmatter(raw);\n if (!parsed) continue;\n const { data, content } = parsed;\n const metadata: RuleMetadata = {\n globs: Array.isArray(data[\"paths\"])\n ? (data[\"paths\"] as string[])\n : [],\n always_apply:\n !data[\"paths\"] || (data[\"paths\"] as string[]).length === 0,\n };\n resources.push(\n this.makeResource(\n \"rule\",\n file.replace(/\\.md[c]?$/, \"\"),\n content.trim(),\n `${displayPath}${file}`,\n metadata,\n ),\n );\n }\n } else {\n const content = this.readFile(fullPath);\n if (content) {\n resources.push(\n this.makeResource(\"rule\", \"rule\", content.trim(), displayPath, {\n globs: [],\n always_apply: true,\n }),\n );\n }\n }\n return resources;\n }\n\n private scanAgentsAt(fullPath: string, displayPath: string): ResourceCreateInput[] {\n return this.scanAgentFilesAt(fullPath, displayPath, [\".md\"]);\n }\n\n private scanHooksAt(fullPath: string, displayPath: string): ResourceCreateInput[] {\n return scanHooksFile(fullPath, displayPath);\n }\n\n private scanMcpAt(fullPath: string, displayPath: string): ResourceCreateInput[] {\n const resources: ResourceCreateInput[] = [];\n const content = this.readFile(fullPath);\n if (content) {\n try {\n const document = JSON.parse(content) as unknown;\n for (const [name, metadata] of Object.entries(\n parseMcpServersDocument(document),\n )) {\n resources.push(\n this.makeResource(\"mcp_server\", name, \"\", displayPath, metadata),\n );\n }\n } catch {\n // skip invalid json\n }\n }\n return resources;\n }\n\n private scanCommandsAt(\n projectRoot: string,\n relativeDir: string,\n ): ResourceCreateInput[] {\n const resources: ResourceCreateInput[] = [];\n const commandsDir = join(projectRoot, relativeDir);\n const sourcePrefix = relativeDir.endsWith(\"/\")\n ? relativeDir\n : `${relativeDir}/`;\n\n for (const file of this.listDir(commandsDir)) {\n if (!file.endsWith(\".md\")) continue;\n const content = this.readFile(join(commandsDir, file));\n if (!content) continue;\n const name = file.replace(/\\.md$/, \"\");\n resources.push(\n this.makeResource(\"command\", name, content, `${sourcePrefix}${file}`),\n );\n }\n\n return resources;\n }\n\n async scan(projectRoot: string): Promise<ResourceCreateInput[]> {\n const resources: ResourceCreateInput[] = [];\n\n // Instructions\n const instructionPath = this.platform.projectPaths.instructions;\n if (instructionPath) {\n const content = this.readFile(join(projectRoot, instructionPath));\n if (content) {\n resources.push(\n this.makeResource(\n \"instruction\",\n `${this.platformId}-instructions`,\n content,\n instructionPath,\n ),\n );\n }\n }\n\n // Skills\n const skillsPath = this.platform.projectPaths.skills;\n if (skillsPath) {\n resources.push(...this.scanSkillsDir(projectRoot, skillsPath));\n }\n\n // Rules\n const rulesPath = this.platform.projectPaths.rules;\n if (rulesPath) {\n resources.push(\n ...this.scanRulesAt(join(projectRoot, rulesPath), rulesPath),\n );\n }\n const legacyRulesPath = this.platform.projectPaths.legacy_rules;\n if (legacyRulesPath) {\n resources.push(\n ...this.scanRulesAt(\n join(projectRoot, legacyRulesPath),\n legacyRulesPath,\n ),\n );\n }\n\n // Agents\n const agentsPath = this.platform.projectPaths.agents;\n if (agentsPath) {\n resources.push(\n ...this.scanAgentsAt(join(projectRoot, agentsPath), agentsPath),\n );\n }\n\n // Commands (markdown workflows / slash prompts)\n const commandsPath = this.platform.projectPaths.commands;\n if (commandsPath) {\n resources.push(...this.scanCommandsAt(projectRoot, commandsPath));\n }\n\n // Hooks\n const hooksPath = this.platform.projectPaths.hooks;\n if (hooksPath) {\n resources.push(\n ...this.scanHooksAt(join(projectRoot, hooksPath), hooksPath),\n );\n }\n\n // MCP\n const mcpPath = this.platform.projectPaths.mcp;\n if (mcpPath) {\n resources.push(...this.scanMcpAt(join(projectRoot, mcpPath), mcpPath));\n }\n\n return resources;\n }\n\n async scanGlobal(homeRoot: string): Promise<ResourceCreateInput[]> {\n const resources: ResourceCreateInput[] = [];\n\n const instructionPath = this.platform.globalPaths.instructions;\n if (instructionPath) {\n const content = this.readFile(\n resolveGlobalPath(homeRoot, instructionPath),\n );\n if (content) {\n resources.push(\n this.makeResource(\n \"instruction\",\n `${this.platformId}-instructions`,\n content,\n instructionPath,\n ),\n );\n }\n }\n\n const skillsPath = this.platform.globalPaths.skills;\n if (skillsPath) {\n resources.push(\n ...this.scanSkillsDirAt(\n resolveGlobalPath(homeRoot, skillsPath),\n skillsPath.replace(/\\/$/, \"\"),\n ),\n );\n }\n\n const rulesPath = this.platform.globalPaths.rules;\n if (rulesPath) {\n resources.push(\n ...this.scanRulesAt(\n resolveGlobalPath(homeRoot, rulesPath),\n rulesPath,\n ),\n );\n }\n\n const agentsPath = this.platform.globalPaths.agents;\n if (agentsPath) {\n resources.push(\n ...this.scanAgentsAt(\n resolveGlobalPath(homeRoot, agentsPath),\n agentsPath,\n ),\n );\n }\n\n const commandsPath = this.platform.globalPaths.commands;\n if (commandsPath) {\n const resolved = resolveGlobalPath(homeRoot, commandsPath);\n const displayPath = commandsPath.endsWith(\"/\")\n ? commandsPath\n : `${commandsPath}/`;\n for (const file of this.listDir(resolved)) {\n if (!file.endsWith(\".md\")) continue;\n const content = this.readFile(join(resolved, file));\n if (!content) continue;\n resources.push(\n this.makeResource(\n \"command\",\n file.replace(/\\.md$/, \"\"),\n content,\n `${displayPath}${file}`,\n ),\n );\n }\n }\n\n const hooksPath = this.platform.globalPaths.hooks;\n if (hooksPath) {\n resources.push(\n ...this.scanHooksAt(\n resolveGlobalPath(homeRoot, hooksPath),\n hooksPath,\n ),\n );\n }\n\n const mcpPath = this.platform.globalPaths.settings;\n if (mcpPath) {\n resources.push(\n ...this.scanMcpAt(resolveGlobalPath(homeRoot, mcpPath), mcpPath),\n );\n }\n\n return resources;\n }\n\n async serialize(\n resources: Resource[],\n _projectRoot: string,\n options: SerializeOptions = {},\n ): Promise<SerializedFile[]> {\n const files: SerializedFile[] = [];\n const target = options.target ?? \"project\";\n const targetPaths = this.getTargetPaths(target);\n const skillsPath =\n this.toTargetRelativePath(targetPaths.skills, target) ??\n (target === \"project\" ? \".agents/skills/\" : undefined);\n const rulesPath = this.toTargetRelativePath(targetPaths.rules, target);\n const mcpPath = this.toTargetRelativePath(\n target === \"global\" ? targetPaths.settings : targetPaths.mcp,\n target,\n );\n const agentsPath = this.toTargetRelativePath(targetPaths.agents, target);\n const hooksPath = this.toTargetRelativePath(targetPaths.hooks, target);\n const commandsPath = this.toTargetRelativePath(targetPaths.commands, target);\n const instructionPath =\n this.toTargetRelativePath(targetPaths.instructions, target) ??\n (target === \"project\" ? \"AGENTS.md\" : undefined);\n\n // Instructions\n const instructions = resources.filter((r) => r.type === \"instruction\");\n // Only embed rules into AGENTS.md if there is natively no rules feature support\n const rules = resources.filter((r) => r.type === \"rule\");\n\n if ((instructions.length > 0 || (!rulesPath && rules.length > 0)) && instructionPath) {\n const parts: string[] = [];\n for (const r of instructions) parts.push(r.content);\n if (!rulesPath) {\n for (const r of rules) parts.push(`## ${r.name}\\n\\n${r.content}`);\n }\n files.push({\n path: instructionPath,\n content: parts.join(\"\\n\\n\"),\n });\n }\n\n // Rules native files\n if (rulesPath && rules.length > 0) {\n if (rulesPath.endsWith(\"/\")) {\n for (const r of rules) {\n const md = r.metadata as RuleMetadata;\n const fm: Record<string, unknown> = {\n description: r.description || `Rule ${r.name}`,\n };\n if (md?.globs && md.globs.length > 0) {\n fm[\"paths\"] = md.globs;\n }\n files.push({\n path: `${rulesPath}${r.name}.md`,\n content: this.emitFrontmatter(fm, r.content),\n });\n }\n } else {\n const parts: string[] = [];\n for (const r of rules) parts.push(`## ${r.name}\\n\\n${r.content}`);\n files.push({ path: rulesPath, content: parts.join(\"\\n\\n\") });\n }\n }\n\n // Agents\n const agents = resources.filter((r) => r.type === \"agent\");\n if (agentsPath && agents.length > 0 && agentsPath.endsWith(\"/\")) {\n for (const r of agents) {\n files.push({\n path: `${agentsPath}${r.name}.md`,\n content: serializedAgentDocument(\n {\n name: r.name,\n description: r.description,\n content: r.content,\n metadata: r.metadata as AgentMetadata,\n },\n \"generic\",\n ),\n });\n }\n }\n\n // Commands / workflows\n const commands = resources.filter((r) => r.type === \"command\");\n if (commandsPath && commands.length > 0) {\n const commandPrefix = commandsPath.endsWith(\"/\")\n ? commandsPath\n : `${commandsPath}/`;\n for (const r of commands) {\n files.push({\n path: `${commandPrefix}${r.name}.md`,\n content: r.content,\n });\n }\n }\n\n // Hooks\n const hooks = resources.filter((r) => r.type === \"hook\");\n if (hooksPath && hooks.length > 0) {\n files.push({\n path: hooksPath,\n content: JSON.stringify(\n buildHooksJson(\n hooks.map((r) => ({\n ...(r.metadata as HookMetadata),\n name: r.name,\n })),\n { version: 1 },\n ),\n null,\n 2,\n ),\n });\n }\n\n // Skills\n const skills = resources.filter((r) => r.type === \"skill\");\n const instructionOnlySkills =\n this.platform.skillEmission === \"instruction-only\";\n const instructionOnlySink = Boolean(rulesPath || instructionPath);\n\n if (instructionOnlySkills && instructionOnlySink && rulesPath && skills.length > 0) {\n if (rulesPath.endsWith(\"/\")) {\n for (const r of skills) {\n const fm: Record<string, unknown> = {\n description: r.description || `Skill ${r.name}`,\n };\n files.push({\n path: `${rulesPath}${r.name}.md`,\n content: this.emitFrontmatter(fm, r.content),\n });\n }\n } else {\n const parts: string[] = [];\n for (const r of skills) {\n parts.push(`## ${r.name}\\n\\n${r.content}`);\n }\n files.push({ path: rulesPath, content: parts.join(\"\\n\\n\") });\n }\n } else if (\n skillsPath &&\n (!instructionOnlySkills || !instructionOnlySink) &&\n skills.length > 0\n ) {\n for (const r of skills) {\n files.push(\n ...this.emitSkillWithAuxiliary(\n r,\n `${skillsPath}${r.name}/SKILL.md`,\n options,\n ),\n );\n }\n }\n\n // MCP\n const mcpServers = this.mcpServersForTarget(resources, mcpPath);\n if (mcpPath && mcpServers.length > 0) {\n const servers: Record<string, GenericSerializedMcpEntry> = {};\n for (const r of mcpServers) {\n const meta = r.metadata as McpServerMetadata;\n if (!meta) continue;\n if (meta.transport === \"http\") {\n servers[r.name] = {\n url: meta.url,\n protocol: \"sse\",\n env: meta.env,\n ...(meta.headers && Object.keys(meta.headers).length > 0\n ? { headers: meta.headers }\n : {}),\n };\n } else {\n servers[r.name] = {\n command: meta.command,\n args: meta.args,\n env: meta.env,\n };\n }\n }\n files.push({\n path: mcpPath,\n content: JSON.stringify({ mcpServers: servers }, null, 2),\n });\n }\n\n return files;\n }\n}\n","import { ClaudeCodeSerializer } from \"../platforms/claude-code.js\";\nimport { CursorSerializer } from \"../platforms/cursor.js\";\nimport { CodexSerializer } from \"../platforms/codex.js\";\nimport { GooseSerializer } from \"../platforms/goose.js\";\nimport { OpenCodeSerializer } from \"../platforms/opencode.js\";\nimport { CopilotSerializer } from \"../platforms/copilot.js\";\nimport { GeminiCliSerializer } from \"../platforms/gemini-cli.js\";\nimport { GrokBuildSerializer } from \"../platforms/grok-build.js\";\nimport { DeepSeekHarnessSerializer } from \"../platforms/deepseek-harness.js\";\nimport { MuseCodeSerializer } from \"../platforms/muse-code.js\";\nimport { MiniMaxCodeSerializer } from \"../platforms/minimax-code.js\";\nimport { GenericAgentsSerializer } from \"../platforms/generic-agents.js\";\nimport type { PlatformSerializer } from \"../types.js\";\n\nexport const DEDICATED_SERIALIZER_PLATFORM_IDS = [\n \"claude-code\",\n \"cursor\",\n \"codex\",\n \"goose\",\n \"opencode\",\n \"github-copilot\",\n \"copilot-cli\",\n \"gemini-cli\",\n \"grok-build\",\n \"deepseek-harness\",\n \"muse-code\",\n \"minimax-code\",\n] as const;\n\nconst dedicatedSerializerPlatformIds = new Set<string>(\n DEDICATED_SERIALIZER_PLATFORM_IDS,\n);\n\nexport function getDedicatedSerializerPlatformIds(): string[] {\n return [...DEDICATED_SERIALIZER_PLATFORM_IDS];\n}\n\nexport function getPlatformSerializer(platformId: string): PlatformSerializer {\n switch (platformId) {\n case \"claude-code\":\n return new ClaudeCodeSerializer();\n case \"cursor\":\n return new CursorSerializer();\n case \"codex\":\n return new CodexSerializer();\n case \"goose\":\n return new GooseSerializer();\n case \"opencode\":\n return new OpenCodeSerializer();\n case \"github-copilot\":\n return new CopilotSerializer(\"github-copilot\");\n case \"copilot-cli\":\n return new CopilotSerializer(\"copilot-cli\");\n case \"gemini-cli\":\n return new GeminiCliSerializer();\n case \"grok-build\":\n return new GrokBuildSerializer();\n case \"deepseek-harness\":\n return new DeepSeekHarnessSerializer();\n case \"muse-code\":\n return new MuseCodeSerializer();\n case \"minimax-code\":\n return new MiniMaxCodeSerializer();\n default:\n return new GenericAgentsSerializer(platformId);\n }\n}\n\nexport function hasDedicatedPlatformSerializer(platformId: string): boolean {\n return dedicatedSerializerPlatformIds.has(platformId);\n}\n","import type { PluginSourceScanResult } from \"../types.js\";\nimport type { ScanResult } from \"./scanner.js\";\n\nfunction normalizeSource(source: string): string {\n return source.replace(/^\\.\\//, \"\");\n}\n\nexport function dropHarnessSkillsDuplicatingPluginSource(\n harness: ScanResult[],\n plugin: PluginSourceScanResult[],\n): ScanResult[] {\n const pluginSkillSources = new Set(\n plugin\n .flatMap((entry) => entry.resources)\n .filter((r) => r.type === \"skill\")\n .map((r) => normalizeSource(r.source)),\n );\n\n if (pluginSkillSources.size === 0) {\n return harness;\n }\n\n return harness.map((result) => ({\n ...result,\n resources: result.resources.filter((resource) => {\n if (resource.type !== \"skill\") return true;\n return !pluginSkillSources.has(normalizeSource(resource.source));\n }),\n }));\n}\n","import { existsSync, lstatSync, readdirSync, readFileSync } from \"node:fs\";\nimport { basename, dirname, join } from \"node:path\";\nimport { getAllPlatforms } from \"../platforms/registry.js\";\nimport type { PlatformPaths, Resource } from \"../types.js\";\nimport {\n deleteResource,\n listResources,\n listResourcesMatchingOriginRef,\n normalizeResourceInput,\n upsertResource,\n type ImportConflictPolicy,\n type ResourceCreateInput,\n type UpsertResourceInput,\n type UpsertResult,\n} from \"../models/resource.js\";\nimport {\n createImportedSnapshot,\n} from \"../models/imported-snapshot.js\";\nimport { getPlatformSerializer } from \"./platform-serializers.js\";\nimport { scanPluginSource, scanPluginSourceForMerge } from \"./plugin-source-import.js\";\nimport { resolveHomeRoot } from \"../utils/home-root.js\";\nimport { loadScanIgnore } from \"./scanner-ignore.js\";\nimport { dropHarnessSkillsDuplicatingPluginSource } from \"./scan-dedup.js\";\nimport { dropPluginTranslatedResources } from \"./plugin-translation-marker.js\";\nimport { isLiveLibraryRef } from \"./live-library-ref.js\";\nimport type { ImportedSnapshot, PluginSourceScanResult } from \"../types.js\";\n\nexport function resolveConfiguredPath(\n rootPath: string,\n configuredPath: string,\n): string {\n return configuredPath.startsWith(\"~/\")\n ? join(rootPath, configuredPath.slice(2))\n : join(rootPath, configuredPath);\n}\n\nfunction configuredProjectPaths(paths: PlatformPaths): string[] {\n const result: string[] = [];\n for (const [key, value] of Object.entries(paths)) {\n if (key === \"pathAlternates\" || typeof value !== \"string\" || !value) {\n continue;\n }\n result.push(value);\n }\n for (const alternates of Object.values(paths.pathAlternates ?? {})) {\n if (alternates) {\n result.push(...alternates);\n }\n }\n return result;\n}\n\n/**\n * Primary global paths used to decide whether a harness is \"shared-path only\".\n * Plugin inventory is optional evidence: it can detect a harness when present,\n * but must not block detection of shared MCP/skills.\n */\nfunction configuredRequiredGlobalPaths(paths: PlatformPaths): string[] {\n const result: string[] = [];\n for (const [key, value] of Object.entries(paths)) {\n if (\n key === \"pathAlternates\"\n || key === \"plugins\"\n || typeof value !== \"string\"\n || !value\n ) {\n continue;\n }\n result.push(value);\n }\n return result;\n}\n\nfunction existingPaths(paths: PlatformPaths, rootPath: string): string[] {\n return configuredProjectPaths(paths).filter((configuredPath) =>\n existsSync(resolveConfiguredPath(rootPath, configuredPath)),\n );\n}\n\n// ── Platform detection ─────────────────────────────────────────────────\n\nfunction pathHasExactConfiguredName(fullPath: string, configuredPath: string): boolean {\n const expectedName = basename(configuredPath.replace(/\\/+$/, \"\"));\n if (!expectedName || expectedName === \".\" || expectedName === \"..\") {\n return true;\n }\n try {\n return readdirSync(dirname(fullPath)).includes(expectedName);\n } catch {\n return false;\n }\n}\n\nfunction pathCountsForPlatformDetection(\n projectRoot: string,\n configuredPath: string,\n): boolean {\n const fullPath = join(projectRoot, configuredPath);\n if (!existsSync(fullPath)) {\n return false;\n }\n // existsSync is case-insensitive on macOS; grok-build's AGENT.md / Agents.md\n // alternates must not count as evidence for a shared AGENTS.md file.\n if (!pathHasExactConfiguredName(fullPath, configuredPath)) {\n return false;\n }\n if (configuredPath === \"AGENTS.md\" && lstatSync(fullPath).isSymbolicLink()) {\n return false;\n }\n return true;\n}\n\nfunction platformHasConfiguredPath(projectRoot: string, configuredPath: string): boolean {\n return pathCountsForPlatformDetection(projectRoot, configuredPath);\n}\n\nfunction buildSharedProjectPathSet(): Set<string> {\n const platformCounts = new Map<string, number>();\n for (const platform of getAllPlatforms()) {\n const uniquePaths = new Set(configuredProjectPaths(platform.projectPaths));\n for (const path of uniquePaths) {\n platformCounts.set(path, (platformCounts.get(path) ?? 0) + 1);\n }\n }\n\n return new Set(\n [...platformCounts.entries()]\n .filter(([, count]) => count > 1)\n .map(([path]) => path),\n );\n}\n\nfunction detectionPathsExist(\n paths: readonly string[] | undefined,\n rootPath: string,\n): string[] {\n if (!paths || paths.length === 0) {\n return [];\n }\n return paths.filter((configuredPath) => {\n const relative = configuredPath.startsWith(\"~/\")\n ? configuredPath.slice(2)\n : configuredPath;\n return pathCountsForPlatformDetection(rootPath, relative);\n });\n}\n\n/** Check if a platform has harness-specific files in a project directory. */\nfunction platformHasFiles(platformId: string, projectRoot: string): boolean {\n const platform = getAllPlatforms().find((p) => p.id === platformId);\n if (!platform) return false;\n\n if (detectionPathsExist(platform.detectionPaths?.project, projectRoot).length > 0) {\n return true;\n }\n\n const sharedProjectPaths = buildSharedProjectPathSet();\n const existingPaths = configuredProjectPaths(platform.projectPaths).filter(\n (configuredPath) => platformHasConfiguredPath(projectRoot, configuredPath),\n );\n if (existingPaths.length === 0) return false;\n\n return existingPaths.some((configuredPath) => !sharedProjectPaths.has(configuredPath));\n}\n\n/** Detect all platforms with configuration in a project directory. */\nexport function detectPlatforms(projectRoot: string): string[] {\n return getAllPlatforms()\n .filter((p) => platformHasFiles(p.id, projectRoot))\n .map((p) => p.id);\n}\n\nexport interface DetectedHomePlatform {\n platformId: string;\n discoveredPaths: string[];\n}\n\nexport function buildSharedGlobalPathSet(): Set<string> {\n const platformCounts = new Map<string, number>();\n for (const platform of getAllPlatforms()) {\n const uniquePaths = new Set(configuredProjectPaths(platform.globalPaths));\n for (const path of uniquePaths) {\n platformCounts.set(path, (platformCounts.get(path) ?? 0) + 1);\n }\n }\n\n return new Set(\n [...platformCounts.entries()]\n .filter(([, count]) => count > 1)\n .map(([path]) => path),\n );\n}\n\n/**\n * Detect harnesses with home-directory configuration.\n *\n * Platforms that share a global path (e.g. codex, warp, and cline all use\n * `~/.agents/skills/`) are only reported when they have platform-specific\n * evidence on disk. Warp and Jules require their own markers (`~/.warp`,\n * `~/.jules` / `~/JULES.md`), not a plain `~/.agents` hub.\n */\nexport function detectHomePlatforms(\n homeRoot = resolveHomeRoot(),\n): DetectedHomePlatform[] {\n const sharedGlobalPaths = buildSharedGlobalPathSet();\n\n return getAllPlatforms()\n .map((platform) => {\n const configured = configuredRequiredGlobalPaths(platform.globalPaths);\n const discoveredPaths = existingPaths(platform.globalPaths, homeRoot);\n const detectionHits = detectionPathsExist(\n platform.detectionPaths?.global,\n homeRoot,\n );\n if (discoveredPaths.length === 0 && detectionHits.length === 0) {\n return { platformId: platform.id, discoveredPaths: [] };\n }\n\n const discriminativePaths = discoveredPaths.filter(\n (path) => !sharedGlobalPaths.has(path),\n );\n const onlySharedPathsConfigured =\n configured.length > 0\n && configured.every((path) => sharedGlobalPaths.has(path));\n // Warp/Jules declare detectionPaths so a shared ~/.agents hub is not enough.\n const requiresOwnMarkers = Boolean(platform.detectionPaths);\n const isDetected =\n discriminativePaths.length > 0\n || detectionHits.length > 0\n || (!requiresOwnMarkers && onlySharedPathsConfigured && discoveredPaths.length > 0);\n if (!isDetected) {\n return { platformId: platform.id, discoveredPaths: [] };\n }\n\n const reported = [...new Set([\n ...discriminativePaths,\n ...detectionHits,\n ...(requiresOwnMarkers ? [] : discoveredPaths),\n ])];\n return {\n platformId: platform.id,\n discoveredPaths: reported.length > 0 ? reported : discoveredPaths,\n };\n })\n .filter((result) => result.discoveredPaths.length > 0);\n}\n\nexport function isPluginSourcePath(sourcePath: string): boolean {\n if (!existsSync(sourcePath)) {\n return false;\n }\n\n if (basename(sourcePath) === \"marketplace.json\") {\n return true;\n }\n\n return (\n existsSync(join(sourcePath, \".goose-plugin\", \"plugin.json\")) ||\n existsSync(join(sourcePath, \".plugin\", \"plugin.json\")) ||\n existsSync(join(sourcePath, \"plugin.json\")) ||\n existsSync(join(sourcePath, \".cursor-plugin\", \"plugin.json\")) ||\n existsSync(join(sourcePath, \".claude-plugin\", \"plugin.json\")) ||\n existsSync(join(sourcePath, \".codex-plugin\", \"plugin.json\")) ||\n existsSync(join(sourcePath, \".github\", \"plugin\", \"plugin.json\"))\n );\n}\n\nexport function hasPluginSourceLayout(projectRoot: string): boolean {\n return isPluginSourcePath(projectRoot);\n}\n\n// ── Scanning ───────────────────────────────────────────────────────────\n\nexport interface ScanResult {\n platformId: string;\n resources: ResourceCreateInput[];\n}\n\nexport interface HomeScanResult extends ScanResult {\n discoveredPaths: string[];\n}\n\nexport interface ScanConflict {\n platformId: string;\n existing: Resource;\n incoming: UpsertResourceInput;\n}\n\nexport interface PersistScanOptions {\n conflictPolicy?: ImportConflictPolicy;\n namespace?: string;\n originRef?: string;\n}\n\nexport interface PersistedScanResults {\n /** Newly created or updated resources from this import run. */\n resources: Resource[];\n /** All resources matching the scan batch, including unchanged rows. */\n resolved: Resource[];\n importedCounts: Map<string, number>;\n conflicts: ScanConflict[];\n}\n\nexport interface PersistedPluginSourceResults {\n imports: Awaited<ReturnType<typeof scanPluginSource>>;\n resources: Resource[];\n snapshots: ImportedSnapshot[];\n}\n\nconst SHARED_PROJECT_INSTRUCTION_NAMES = new Map<string, string>([\n [\"AGENTS.md\", \"agents-instructions\"],\n]);\n\nconst SHARED_HOME_AGENTS_MD = \"~/.agents/AGENTS.md\";\n\nconst SHARED_PROJECT_SKILL_ROOT = \".agents/skills/\";\n\nexport const SHARED_SCAN_PLATFORM_ID = \"shared\";\n\nconst SYNTHETIC_INSTRUCTION_NAMES = new Set(\n getAllPlatforms().map((platform) => `${platform.id}-instructions`),\n);\n\nexport function hasSharedProjectInstructionFiles(projectRoot: string): boolean {\n const ignore = loadScanIgnore(projectRoot);\n for (const source of SHARED_PROJECT_INSTRUCTION_NAMES.keys()) {\n if (!platformHasConfiguredPath(projectRoot, source)) continue;\n if (ignore.ignores(source)) continue;\n return true;\n }\n return false;\n}\n\nexport function hasSharedProjectResourceFiles(projectRoot: string): boolean {\n if (hasSharedProjectInstructionFiles(projectRoot)) {\n return true;\n }\n return existsSync(join(projectRoot, SHARED_PROJECT_SKILL_ROOT));\n}\n\nfunction isSharedProjectSkillSource(source: string): boolean {\n return (\n source === SHARED_PROJECT_SKILL_ROOT\n || source.startsWith(SHARED_PROJECT_SKILL_ROOT)\n );\n}\n\nasync function readSharedProjectSkills(\n projectRoot: string,\n): Promise<ResourceCreateInput[]> {\n const skillsDir = join(projectRoot, SHARED_PROJECT_SKILL_ROOT);\n if (!existsSync(skillsDir)) {\n return [];\n }\n\n const serializer = getPlatformSerializer(\"codex\");\n const resources = await serializer.scan(projectRoot);\n return resources.filter(\n (resource) =>\n resource.type === \"skill\" && isSharedProjectSkillSource(resource.source),\n );\n}\n\nasync function readSharedProjectResources(\n projectRoot: string,\n): Promise<ResourceCreateInput[]> {\n return [\n ...readSharedProjectInstructions(projectRoot),\n ...await readSharedProjectSkills(projectRoot),\n ];\n}\n\nfunction readSharedHomeInstructions(homeRoot: string): ResourceCreateInput[] {\n const fullPath = join(homeRoot, \".agents\", \"AGENTS.md\");\n if (!existsSync(fullPath)) {\n return [];\n }\n let content: string;\n try {\n content = readFileSync(fullPath, \"utf-8\");\n } catch {\n return [];\n }\n if (!content.trim()) {\n return [];\n }\n return [\n {\n type: \"instruction\",\n name: \"agents-instructions\",\n description: \"\",\n content,\n metadata: {},\n source: SHARED_HOME_AGENTS_MD,\n },\n ];\n}\n\nfunction readSharedProjectInstructions(\n projectRoot: string,\n): ResourceCreateInput[] {\n const ignore = loadScanIgnore(projectRoot);\n const resources: ResourceCreateInput[] = [];\n\n for (const [source, canonicalName] of SHARED_PROJECT_INSTRUCTION_NAMES) {\n if (!platformHasConfiguredPath(projectRoot, source)) continue;\n if (ignore.ignores(source)) continue;\n\n const fullPath = join(projectRoot, source);\n let content: string;\n try {\n content = readFileSync(fullPath, \"utf-8\");\n } catch {\n continue;\n }\n if (!content.trim()) continue;\n\n resources.push({\n type: \"instruction\",\n name: canonicalName,\n description: \"\",\n content,\n metadata: {},\n source,\n });\n }\n\n return resources;\n}\n\n/** Scan a single platform in a project directory. */\nexport async function scanPlatform(\n platformId: string,\n projectRoot: string,\n): Promise<ScanResult> {\n const serializer = getPlatformSerializer(platformId);\n const resources = dropPluginTranslatedResources(\n projectRoot,\n await serializer.scan(projectRoot),\n );\n return { platformId, resources };\n}\n\n/** Scan all detected platforms in a project directory. */\nexport async function scanProject(\n projectRoot: string,\n platformFilter?: string,\n): Promise<ScanResult[]> {\n const platforms = platformFilter\n ? [platformFilter]\n : detectPlatforms(projectRoot);\n\n const results: ScanResult[] = [];\n\n if (!platformFilter) {\n const sharedResources = await readSharedProjectResources(projectRoot);\n if (sharedResources.length > 0) {\n results.push({\n platformId: SHARED_SCAN_PLATFORM_ID,\n resources: sharedResources,\n });\n }\n }\n\n for (const pid of platforms) {\n results.push(await scanPlatform(pid, projectRoot));\n }\n return normalizeProjectScanResults(projectRoot, results);\n}\n\nexport async function scanProjectWithPluginSource(\n projectRoot: string,\n platformFilter?: string,\n): Promise<{\n harness: ScanResult[];\n plugin: PluginSourceScanResult[];\n}> {\n const harness = await scanProject(projectRoot, platformFilter);\n const plugin = hasPluginSourceLayout(projectRoot)\n ? await scanPluginSourceForMerge(projectRoot)\n : [];\n return { harness, plugin };\n}\n\nexport async function scanHomeDefaults(\n platformFilter?: string,\n homeRoot = resolveHomeRoot(),\n): Promise<HomeScanResult[]> {\n const detected = detectHomePlatforms(homeRoot);\n const platforms = platformFilter\n ? detected.filter((result) => result.platformId === platformFilter)\n : detected;\n\n const results: HomeScanResult[] = [];\n if (!platformFilter) {\n const sharedHome = readSharedHomeInstructions(homeRoot);\n if (sharedHome.length > 0) {\n results.push({\n platformId: SHARED_SCAN_PLATFORM_ID,\n discoveredPaths: [SHARED_HOME_AGENTS_MD],\n resources: sharedHome,\n });\n }\n }\n for (const result of platforms) {\n const serializer = getPlatformSerializer(result.platformId);\n try {\n const resources = serializer.scanGlobal\n ? await serializer.scanGlobal(homeRoot)\n : await serializer.scan(homeRoot);\n results.push({\n platformId: result.platformId,\n discoveredPaths: result.discoveredPaths,\n resources: dropPluginTranslatedResources(homeRoot, resources),\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n const firstLine = message.split(\"\\n\")[0];\n console.warn(\n `Skipping home scan for ${result.platformId}: ${firstLine && firstLine.length > 0 ? firstLine : message}`,\n );\n results.push({\n platformId: result.platformId,\n discoveredPaths: result.discoveredPaths,\n resources: [],\n });\n }\n }\n\n return results;\n}\n\nfunction resourceDedupKey(\n resource: Pick<Resource, \"type\" | \"name\" | \"namespace\">,\n): string {\n return `${resource.type}:${resource.name}:${resource.namespace ?? \"\"}`;\n}\n\nfunction pluginImportIdentity(result: {\n source_kind: string;\n source_label: string;\n plugin_name: string;\n metadata: Record<string, unknown>;\n}): {\n namespace: string;\n origin_kind: \"marketplace_link\";\n origin_ref: string;\n} {\n const marketplaceName = String(\n result.metadata.marketplace_name ?? result.source_label ?? result.plugin_name,\n );\n return {\n namespace: result.plugin_name,\n origin_kind: \"marketplace_link\",\n origin_ref:\n result.source_kind === \"marketplace\"\n ? `${result.plugin_name}@${marketplaceName}`\n : `${result.plugin_name}@${result.plugin_name}`,\n };\n}\n\nfunction canonicalInstructionNameForSource(source: string): string | undefined {\n return SHARED_PROJECT_INSTRUCTION_NAMES.get(source);\n}\n\nfunction normalizeProjectScanResults(\n projectRoot: string,\n results: ScanResult[],\n): ScanResult[] {\n const ignore = loadScanIgnore(projectRoot);\n const sharedSources = new Set(SHARED_PROJECT_INSTRUCTION_NAMES.keys());\n const hasDedicatedSharedScan = results.some(\n (result) => result.platformId === SHARED_SCAN_PLATFORM_ID,\n );\n const sharedScanIncludesSkills =\n hasDedicatedSharedScan\n && results.some((result) =>\n result.platformId === SHARED_SCAN_PLATFORM_ID\n && result.resources.some(\n (resource) =>\n resource.type === \"skill\" && isSharedProjectSkillSource(resource.source),\n ),\n );\n const seenSharedSources = new Set<string>();\n\n return results.map((result) => ({\n ...result,\n resources: result.resources.flatMap((resource) => {\n if (ignore.ignores(resource.source)) {\n return [];\n }\n\n const canonicalName =\n resource.type === \"instruction\"\n ? canonicalInstructionNameForSource(resource.source)\n : undefined;\n\n const isSharedInstruction =\n resource.type === \"instruction\" && sharedSources.has(resource.source);\n\n if (\n isSharedInstruction\n && hasDedicatedSharedScan\n && result.platformId !== SHARED_SCAN_PLATFORM_ID\n ) {\n return [];\n }\n\n if (\n resource.type === \"skill\"\n && isSharedProjectSkillSource(resource.source)\n && sharedScanIncludesSkills\n && result.platformId !== SHARED_SCAN_PLATFORM_ID\n ) {\n return [];\n }\n\n if (!canonicalName) {\n return [resource];\n }\n\n if (!hasDedicatedSharedScan) {\n if (seenSharedSources.has(resource.source)) {\n return [];\n }\n seenSharedSources.add(resource.source);\n }\n\n return [{ ...resource, name: canonicalName }];\n }),\n }));\n}\n\nfunction cleanupSharedInstructionDuplicates(resources: Resource[]): void {\n const existing = listResources();\n\n for (const resource of resources) {\n if (resource.type !== \"instruction\") continue;\n\n const canonicalName = canonicalInstructionNameForSource(resource.source);\n if (!canonicalName) continue;\n\n for (const duplicate of existing) {\n if (duplicate.type !== \"instruction\") continue;\n if (duplicate.source !== resource.source) continue;\n if (duplicate.content !== resource.content) continue;\n if (!SYNTHETIC_INSTRUCTION_NAMES.has(duplicate.name)) continue;\n if (duplicate.name === canonicalName) continue;\n\n deleteResource(duplicate.id);\n }\n }\n}\n\nexport function persistScanResults(\n results: ScanResult[],\n options?: PersistScanOptions,\n): PersistedScanResults {\n const seen = new Set<string>();\n const persisted: Resource[] = [];\n const resolved: Resource[] = [];\n const importedCounts = new Map<string, number>();\n const conflicts: ScanConflict[] = [];\n const conflictPolicy = options?.conflictPolicy ?? \"skip\";\n const namespace = options?.namespace ?? \"\";\n const originRef = options?.originRef ?? \"\";\n\n for (const result of results) {\n for (const r of result.resources) {\n const incoming = normalizeResourceInput({\n ...r,\n // Preserve explicit identity from scanners (e.g. marketplace plugin pins).\n namespace: r.namespace ?? namespace,\n origin_kind: r.origin_kind ?? \"local_snapshot\",\n origin_ref: r.origin_ref ?? (originRef || r.source),\n });\n const key = resourceDedupKey({\n type: incoming.type,\n name: incoming.name,\n namespace: incoming.namespace ?? \"\",\n });\n if (seen.has(key)) continue;\n seen.add(key);\n\n let upsertResult: UpsertResult;\n try {\n upsertResult = upsertResource(incoming, {\n policy: conflictPolicy === \"prompt\" ? \"fail\" : conflictPolicy,\n });\n } catch {\n const existing = listResources().find(\n (resource) =>\n resource.type === incoming.type &&\n resource.name === incoming.name &&\n resource.namespace === (incoming.namespace ?? \"\"),\n );\n if (existing) {\n conflicts.push({ platformId: result.platformId, existing, incoming });\n continue;\n }\n throw new Error(\n `Resource conflict: ${incoming.type}:${incoming.name}${namespace ? `@${namespace}` : \"\"}`,\n );\n }\n\n const savedResource =\n upsertResult.action === \"skipped\"\n ? upsertResult.existing\n : upsertResult.resource;\n resolved.push(savedResource);\n\n if (upsertResult.action === \"skipped\") {\n if (conflictPolicy === \"prompt\" || conflictPolicy === \"fail\") {\n conflicts.push({\n platformId: result.platformId,\n existing: upsertResult.existing,\n incoming,\n });\n }\n continue;\n }\n\n if (upsertResult.action === \"unchanged\") {\n continue;\n }\n\n persisted.push(savedResource);\n importedCounts.set(\n result.platformId,\n (importedCounts.get(result.platformId) ?? 0) + 1,\n );\n }\n }\n\n cleanupSharedInstructionDuplicates(persisted);\n\n return { resources: persisted, resolved, importedCounts, conflicts };\n}\n\n/**\n * Drop `local_snapshot` and live-library-ref rows for `originRef` that no\n * longer appear in a fresh harness scan (removed MCP servers, deleted agent\n * files, and Not in profile live refs stored as origin_kind manual).\n */\nexport function reconcileLocalSnapshotScan(\n originRef: string,\n results: readonly ScanResult[],\n namespace = \"\",\n): Resource[] {\n const freshKeys = new Set<string>();\n for (const result of results) {\n for (const resource of result.resources) {\n const normalized = normalizeResourceInput({\n ...resource,\n namespace: resource.namespace ?? namespace,\n origin_kind: resource.origin_kind ?? \"local_snapshot\",\n origin_ref: resource.origin_ref ?? originRef,\n });\n freshKeys.add(\n resourceDedupKey({\n type: normalized.type,\n name: normalized.name,\n namespace: normalized.namespace ?? \"\",\n }),\n );\n }\n }\n\n const removed: Resource[] = [];\n for (const resource of listResourcesMatchingOriginRef(originRef)) {\n const reconcileable =\n resource.origin_kind === \"local_snapshot\" || isLiveLibraryRef(resource);\n if (!reconcileable) {\n continue;\n }\n if (freshKeys.has(resourceDedupKey(resource))) {\n continue;\n }\n if (deleteResource(resource.id)) {\n removed.push(resource);\n }\n }\n return removed;\n}\n\nexport function applyScanConflicts(\n conflicts: ScanConflict[],\n resolution: \"overwrite\" | \"skip\",\n): Resource[] {\n const updated: Resource[] = [];\n for (const conflict of conflicts) {\n const result = upsertResource(conflict.incoming, {\n policy: resolution === \"overwrite\" ? \"overwrite\" : \"skip\",\n });\n if (result.action === \"created\" || result.action === \"updated\") {\n updated.push(result.resource);\n }\n if (result.action === \"unchanged\") {\n updated.push(result.resource);\n }\n }\n return updated;\n}\n\n/**\n * Scan and persist: scan all platforms and save unique resources to the database.\n * Deduplicates by name+type to avoid re-importing the same resource.\n */\nexport async function scanAndPersist(\n projectRoot: string,\n platformFilter?: string,\n options?: PersistScanOptions,\n): Promise<Resource[]> {\n const originRef = options?.originRef ?? projectRoot;\n const results = await scanProject(projectRoot, platformFilter);\n const namespace = options?.namespace ?? \"project\";\n const persisted = persistScanResults(results, {\n ...options,\n originRef,\n namespace,\n });\n reconcileLocalSnapshotScan(originRef, results, namespace);\n return persisted.resolved;\n}\n\nexport function persistPluginSourceScanResults(\n imports: PluginSourceScanResult[],\n): PersistedPluginSourceResults {\n const resources: Resource[] = [];\n const snapshots: ImportedSnapshot[] = [];\n const returnedResourceIds = new Set<string>();\n\n for (const result of imports) {\n const resourceIds: string[] = [];\n\n const identity = pluginImportIdentity(result);\n\n for (const resource of result.resources) {\n const upserted = upsertResource(\n normalizeResourceInput({\n ...resource,\n ...identity,\n }),\n { policy: \"overwrite\" },\n );\n\n const saved =\n upserted.action === \"skipped\"\n ? upserted.existing\n : upserted.resource;\n\n resourceIds.push(saved.id);\n if (!returnedResourceIds.has(saved.id)) {\n returnedResourceIds.add(saved.id);\n resources.push(saved);\n }\n }\n\n snapshots.push(\n createImportedSnapshot({\n source_kind: result.source_kind,\n source_label: result.source_label,\n plugin_name: result.plugin_name,\n plugin_version: result.plugin_version,\n resource_ids: resourceIds,\n metadata: result.metadata,\n }),\n );\n }\n\n return { imports, resources, snapshots };\n}\n\nexport async function scanAndPersistPluginSource(\n sourcePath: string,\n): Promise<PersistedPluginSourceResults> {\n const imports = await scanPluginSource(sourcePath);\n return persistPluginSourceScanResults(imports);\n}\n\nexport interface PersistMergedProjectScanOptions extends PersistScanOptions {}\n\nexport interface PersistMergedProjectScanResults {\n harness: PersistedScanResults;\n plugin: PersistedPluginSourceResults;\n resources: Resource[];\n scan: {\n harness: ScanResult[];\n plugin: PluginSourceScanResult[];\n };\n}\n\nexport async function persistMergedProjectScan(\n projectRoot: string,\n platformFilter?: string,\n options?: PersistMergedProjectScanOptions,\n): Promise<PersistMergedProjectScanResults> {\n const { harness: rawHarness, plugin } = await scanProjectWithPluginSource(\n projectRoot,\n platformFilter,\n );\n const harness = dropHarnessSkillsDuplicatingPluginSource(rawHarness, plugin);\n\n const originRef = options?.originRef ?? projectRoot;\n const namespace = options?.namespace ?? \"project\";\n const harnessPersisted = persistScanResults(harness, {\n ...options,\n originRef,\n namespace,\n });\n reconcileLocalSnapshotScan(originRef, harness, namespace);\n\n const pluginPersisted =\n plugin.length > 0\n ? persistPluginSourceScanResults(plugin)\n : { imports: [], resources: [], snapshots: [] };\n\n const seen = new Set<string>();\n const resources: Resource[] = [];\n for (const resource of [\n ...harnessPersisted.resolved,\n ...pluginPersisted.resources,\n ]) {\n const key = resourceDedupKey(resource);\n if (seen.has(key)) continue;\n seen.add(key);\n resources.push(resource);\n }\n\n return {\n harness: harnessPersisted,\n plugin: pluginPersisted,\n resources,\n scan: { harness, plugin },\n };\n}\n\n/** @deprecated Plugin inventory is declared via composition `plugin` resources and `resource sync`. */\nexport async function persistClaudePluginInventoryForProject(_opts: {\n projectRoot: string;\n projectId: string;\n scannedPlatformIds: readonly string[];\n homeRoot?: string;\n}): Promise<null> {\n return null;\n}\n\nexport async function scanAndPersistHomeDefaults(\n platformFilter?: string,\n homeRoot = resolveHomeRoot(),\n): Promise<{\n detected: DetectedHomePlatform[];\n results: Array<HomeScanResult & { importedCount: number }>;\n resources: Resource[];\n resolved: Resource[];\n}> {\n const detected = detectHomePlatforms(homeRoot);\n const results = await scanHomeDefaults(platformFilter, homeRoot);\n const persisted = persistScanResults(results, {\n conflictPolicy: \"skip\",\n originRef: homeRoot,\n });\n reconcileLocalSnapshotScan(homeRoot, results);\n\n return {\n detected: platformFilter\n ? detected.filter((result) => result.platformId === platformFilter)\n : detected,\n results: results.map((result) => ({\n ...result,\n importedCount: persisted.importedCounts.get(result.platformId) ?? 0,\n })),\n resources: persisted.resources,\n resolved: persisted.resolved,\n };\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport picomatch from \"picomatch\";\n\nexport interface ScanIgnoreMatcher {\n ignores(source: string): boolean;\n}\n\ninterface ScanIgnoreRule {\n include: boolean;\n match: (source: string) => boolean;\n}\n\nfunction candidatePaths(source: string): string[] {\n const paths = [source];\n let currentPath = source;\n let current = dirname(currentPath);\n\n while (current !== \".\" && current !== currentPath) {\n paths.push(current);\n currentPath = current;\n current = dirname(currentPath);\n }\n\n return paths;\n}\n\nexport function loadScanIgnore(projectRoot: string): ScanIgnoreMatcher {\n const ignorePath = join(projectRoot, \".harnesstapignore\");\n if (!existsSync(ignorePath)) {\n return { ignores: () => false };\n }\n\n const rules: ScanIgnoreRule[] = readFileSync(ignorePath, \"utf-8\")\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter((line) => line.length > 0 && !line.startsWith(\"#\"))\n .map((line) => ({\n include: line.startsWith(\"!\"),\n pattern: line.startsWith(\"!\") ? line.slice(1) : line,\n }))\n .filter((rule) => rule.pattern.length > 0)\n .map((line) => {\n return {\n include: line.include,\n match: picomatch(line.pattern, { dot: true }),\n };\n });\n\n return {\n ignores(source: string): boolean {\n let ignored = false;\n const paths = candidatePaths(source);\n\n for (const rule of rules) {\n if (!paths.some((path) => rule.match(path))) continue;\n ignored = !rule.include;\n }\n\n return ignored;\n },\n };\n}\n","import { existsSync, lstatSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport type { ResourceCreateInput } from \"../types.js\";\nimport type { ApplyResult } from \"./applier.js\";\nimport type { SkillHubPlan } from \"./host-plugin-material.js\";\nimport type { ExtractHostPluginMaterialResult } from \"./host-plugin-material.js\";\nimport { getPlatformSerializer } from \"./platform-serializers.js\";\nimport { resourceIdentity } from \"./reference-resources.js\";\nimport type { SerializerTarget, SerializeOptions } from \"../types.js\";\nimport { toPortableEmitResources } from \"./harness-resource-union.js\";\nimport {\n findPluginPinResourceIdByOriginRef,\n matchesPluginPinMaterialization,\n upsertPluginPinMaterialization,\n} from \"../models/plugin-pin-materialization.js\";\nimport type { MaterializationScope } from \"../types.js\";\nimport {\n PLUGIN_TRANSLATION_SCHEMA,\n type PluginTranslationMarkerEntry,\n type PluginTranslationMarkerFile,\n} from \"./plugin-translation-source.js\";\n\nfunction resolveConfiguredPath(rootPath: string, configuredPath: string): string {\n return configuredPath.startsWith(\"~/\")\n ? join(rootPath, configuredPath.slice(2))\n : join(rootPath, configuredPath);\n}\n\nexport {\n PLUGIN_TRANSLATION_SCHEMA,\n type PluginTranslationMarkerEntry,\n type PluginTranslationMarkerFile,\n type PluginTranslationSource,\n pluginTranslationSourceFromPin,\n} from \"./plugin-translation-source.js\";\n\nfunction parseMarkerFile(raw: string): PluginTranslationMarkerFile | null {\n try {\n const parsed = JSON.parse(raw) as Partial<PluginTranslationMarkerFile>;\n if (parsed.schema !== PLUGIN_TRANSLATION_SCHEMA) return null;\n if (!Array.isArray(parsed.entries)) return null;\n return {\n schema: PLUGIN_TRANSLATION_SCHEMA,\n entries: parsed.entries.filter(\n (entry): entry is PluginTranslationMarkerEntry =>\n typeof entry === \"object\"\n && entry !== null\n && typeof entry.type === \"string\"\n && typeof entry.name === \"string\"\n && typeof entry.plugin === \"string\"\n && typeof entry.marketplace === \"string\"\n && typeof entry.origin_ref === \"string\",\n ),\n };\n } catch {\n return null;\n }\n}\n\nexport function readPluginTranslationMarker(\n markerPath: string,\n): PluginTranslationMarkerFile | null {\n if (!existsSync(markerPath)) return null;\n try {\n if (!lstatSync(markerPath).isFile()) return null;\n return parseMarkerFile(readFileSync(markerPath, \"utf8\"));\n } catch {\n return null;\n }\n}\n\nfunction entryKey(entry: Pick<PluginTranslationMarkerEntry, \"type\" | \"name\">): string {\n return `${entry.type}:${entry.name}`;\n}\n\nfunction writeMarkerFile(markerPath: string, entries: PluginTranslationMarkerEntry[]): void {\n mkdirSync(dirname(markerPath), { recursive: true });\n const file: PluginTranslationMarkerFile = {\n schema: PLUGIN_TRANSLATION_SCHEMA,\n entries,\n };\n writeFileSync(markerPath, `${JSON.stringify(file, null, 2)}\\n`, \"utf8\");\n}\n\n/** Skill directories get an exclusive marker; shared parent dirs merge entries. */\nexport function writePluginTranslationMarker(\n markerDirectory: string,\n entry: PluginTranslationMarkerEntry,\n options?: { exclusive?: boolean },\n): void {\n const markerPath = join(markerDirectory, \".harnesstap\");\n if (options?.exclusive) {\n writeMarkerFile(markerPath, [entry]);\n return;\n }\n const existing = readPluginTranslationMarker(markerPath);\n const byKey = new Map<string, PluginTranslationMarkerEntry>();\n for (const prior of existing?.entries ?? []) {\n byKey.set(entryKey(prior), prior);\n }\n byKey.set(entryKey(entry), entry);\n writeMarkerFile(markerPath, [...byKey.values()]);\n}\n\nfunction markerDirectoryForSource(\n rootPath: string,\n resource: Pick<ResourceCreateInput, \"type\" | \"source\">,\n): string | null {\n const source = resource.source?.trim();\n if (!source) return null;\n const absolute = resolveConfiguredPath(rootPath, source);\n if (resource.type === \"skill\") {\n const normalized = source.replace(/\\\\/g, \"/\");\n if (normalized.endsWith(\"/SKILL.md\") || normalized.endsWith(\"SKILL.md\")) {\n return dirname(absolute);\n }\n return absolute;\n }\n return dirname(absolute);\n}\n\nfunction resourceMatchesMarkerEntry(\n resource: Pick<ResourceCreateInput, \"type\" | \"name\">,\n entry: PluginTranslationMarkerEntry,\n): boolean {\n return entry.type === resource.type && entry.name === resource.name;\n}\n\nexport function isPluginTranslatedResource(\n rootPath: string,\n resource: ResourceCreateInput,\n): boolean {\n if (matchesPluginPinMaterialization(rootPath, resource)) {\n return true;\n }\n const markerDir = markerDirectoryForSource(rootPath, resource);\n if (!markerDir) return false;\n const marker = readPluginTranslationMarker(join(markerDir, \".harnesstap\"));\n if (!marker) return false;\n return marker.entries.some((entry) => resourceMatchesMarkerEntry(resource, entry));\n}\n\nexport function dropPluginTranslatedResources(\n rootPath: string,\n resources: readonly ResourceCreateInput[],\n): ResourceCreateInput[] {\n return resources.filter((resource) => !isPluginTranslatedResource(rootPath, resource));\n}\n\nfunction recordTranslationProvenance(input: {\n scope: MaterializationScope;\n rootPath: string;\n relativePath: string;\n entry: PluginTranslationMarkerEntry;\n}): void {\n const pinId = findPluginPinResourceIdByOriginRef(input.entry.origin_ref);\n upsertPluginPinMaterialization({\n scope: input.scope,\n root_path: input.rootPath,\n relative_path: input.relativePath.replace(/\\\\/g, \"/\"),\n origin_ref: input.entry.origin_ref,\n resource_type: input.entry.type,\n resource_name: input.entry.name,\n plugin_pin_resource_id: pinId,\n });\n}\n\nexport async function writeHarnessSyncPluginTranslationMarkers(input: {\n rootPath: string;\n scope: MaterializationScope;\n extracted: ExtractHostPluginMaterialResult;\n skillHubPlans: readonly SkillHubPlan[];\n extraResults: readonly ApplyResult[];\n portablePlatforms: readonly string[];\n target: SerializerTarget;\n serializeOptions?: Omit<SerializeOptions, \"target\">;\n}): Promise<void> {\n const skillPluginByName = new Map(\n input.extracted.skills.map((skill) => [skill.name, skill.plugin]),\n );\n\n for (const plan of input.skillHubPlans) {\n const skillName = plan.destDir.replace(/\\\\/g, \"/\").split(\"/\").pop() ?? \"\";\n const plugin = skillPluginByName.get(skillName);\n if (!plugin || !skillName) continue;\n const entry: PluginTranslationMarkerEntry = {\n ...plugin,\n type: \"skill\",\n name: skillName,\n };\n writePluginTranslationMarker(join(input.rootPath, plan.destDir), entry, {\n exclusive: true,\n });\n recordTranslationProvenance({\n scope: input.scope,\n rootPath: input.rootPath,\n relativePath: plan.destDir,\n entry,\n });\n recordTranslationProvenance({\n scope: input.scope,\n rootPath: input.rootPath,\n relativePath: plan.skillMdPath,\n entry,\n });\n }\n\n const serializedPaths = new Set<string>();\n for (const result of input.extraResults) {\n for (const file of result.files) {\n serializedPaths.add(file.path.replace(/\\\\/g, \"/\"));\n }\n }\n\n for (const resource of input.extracted.resources) {\n const plugin = input.extracted.resourcePlugins.get(resourceIdentity(resource));\n if (!plugin) continue;\n const portable = toPortableEmitResources([resource]);\n for (const platformId of input.portablePlatforms) {\n const serializer = getPlatformSerializer(platformId);\n const files = await serializer.serialize(\n portable,\n input.rootPath,\n { target: input.target, ...input.serializeOptions },\n );\n for (const file of files) {\n const relative = file.path.replace(/\\\\/g, \"/\");\n if (!serializedPaths.has(relative)) continue;\n const absolute = join(input.rootPath, relative);\n const markerDir = relative.endsWith(\"/SKILL.md\")\n ? dirname(absolute)\n : dirname(absolute);\n const entry: PluginTranslationMarkerEntry = {\n ...plugin,\n type: resource.type,\n name: resource.name,\n };\n writePluginTranslationMarker(markerDir, entry, {\n exclusive: relative.endsWith(\"/SKILL.md\"),\n });\n recordTranslationProvenance({\n scope: input.scope,\n rootPath: input.rootPath,\n relativePath: relative,\n entry,\n });\n }\n }\n }\n}\n","import type { ResourceCreateInput } from \"../types.js\";\n\nexport function resourceIdentity(\n resource: Pick<ResourceCreateInput, \"type\" | \"name\" | \"namespace\">,\n): string {\n return `${resource.type}:${resource.name}:${resource.namespace ?? \"\"}`;\n}\n\n/** Merge plugin resources into main scan without duplicate type:name:namespace keys. */\nexport function mergeReferenceResourceInputs(\n main: ResourceCreateInput[],\n supplemental: ResourceCreateInput[],\n): ResourceCreateInput[] {\n const seen = new Set(main.map(resourceIdentity));\n const merged = [...main];\n for (const resource of supplemental) {\n const key = resourceIdentity(resource);\n if (seen.has(key)) continue;\n seen.add(key);\n merged.push(resource);\n }\n return merged;\n}\n\nexport function mainScanLacksPluginSkills(\n main: ResourceCreateInput[],\n plugin: ResourceCreateInput[],\n): boolean {\n const mainHasSkills = main.some((r) => r.type === \"skill\");\n const pluginHasSkills = plugin.some((r) => r.type === \"skill\");\n return !mainHasSkills && pluginHasSkills;\n}\n","import { hashResourceBody } from \"./resource-hash.js\";\nimport { resourceIdentity } from \"./reference-resources.js\";\nimport type { Resource, ResourceCreateInput } from \"../types.js\";\nimport { isClaudeLocalMcpResource } from \"./claude-local-mcp.js\";\n\nexport interface HarnessScanSlice {\n platformId: string;\n resources: ResourceCreateInput[];\n /** identity → mtime ms; used by last-write conflict policy. */\n mtimesMs?: ReadonlyMap<string, number>;\n}\n\nexport interface UnionConflict {\n identity: string;\n winnerPlatformId: string;\n loserPlatformId: string;\n}\n\nexport interface UnionHarnessResourcesResult {\n resources: ResourceCreateInput[];\n conflicts: UnionConflict[];\n}\n\nexport type HarnessUnionConflictPolicy = \"last-write\";\n\nexport function resourceFingerprint(resource: ResourceCreateInput): string {\n return hashResourceBody({\n type: resource.type,\n content: resource.content,\n metadata: resource.metadata,\n });\n}\n\nfunction mtimeOf(\n slice: HarnessScanSlice,\n identity: string,\n): number {\n return slice.mtimesMs?.get(identity) ?? Number.NEGATIVE_INFINITY;\n}\n\n/**\n * Union on-disk resources from every configured harness.\n * Same `type:name:namespace` keeps the newest mtime; equal/missing mtimes\n * keep the later slice (registered-set order).\n */\nexport function unionHarnessResources(\n slices: readonly HarnessScanSlice[],\n _conflictPolicy: HarnessUnionConflictPolicy = \"last-write\",\n): UnionHarnessResourcesResult {\n const byIdentity = new Map<\n string,\n { resource: ResourceCreateInput; platformId: string; mtime: number }\n >();\n const conflicts: UnionConflict[] = [];\n\n for (const slice of slices) {\n for (const resource of slice.resources) {\n const identity = resourceIdentity(resource);\n const existing = byIdentity.get(identity);\n const mtime = mtimeOf(slice, identity);\n if (!existing) {\n byIdentity.set(identity, {\n resource,\n platformId: slice.platformId,\n mtime,\n });\n continue;\n }\n if (resourceFingerprint(existing.resource) === resourceFingerprint(resource)) {\n if (mtime > existing.mtime) {\n existing.mtime = mtime;\n existing.platformId = slice.platformId;\n }\n continue;\n }\n const takeIncoming = mtime >= existing.mtime;\n if (takeIncoming) {\n conflicts.push({\n identity,\n winnerPlatformId: slice.platformId,\n loserPlatformId: existing.platformId,\n });\n byIdentity.set(identity, {\n resource,\n platformId: slice.platformId,\n mtime,\n });\n } else {\n conflicts.push({\n identity,\n winnerPlatformId: existing.platformId,\n loserPlatformId: slice.platformId,\n });\n }\n }\n }\n\n return {\n resources: [...byIdentity.values()].map((entry) => entry.resource),\n conflicts,\n };\n}\n\n/** MCP path-binding must not block cross-harness emit.\n * Claude local-scope MCP is inventory-only and is never rewritten as portable.\n */\nexport function toPortableEmitResources(\n resources: ResourceCreateInput[],\n): Resource[] {\n return resources\n .filter((resource) => !isClaudeLocalMcpResource(resource))\n .map((resource) => {\n const portableSource =\n resource.type === \"mcp_server\" ? \"manual\" : resource.source;\n return {\n ...resource,\n id: `sync:${resourceIdentity(resource)}`,\n namespace: resource.namespace ?? \"\",\n origin_kind: resource.origin_kind ?? \"manual\",\n origin_ref: resource.origin_ref ?? resource.source,\n content_hash: resourceFingerprint(resource),\n content_blob_ref: resource.content_blob_ref ?? \"\",\n source: portableSource,\n created_at: \"\",\n updated_at: \"\",\n };\n });\n}\n","import type { SqliteDatabase } from \"../db/types.js\";\nimport { getDb } from \"../db/connection.js\";\nimport { ulid } from \"ulid\";\nimport type { MaterializationScope } from \"../types.js\";\n\nfunction pluginPinMaterializationTableExists(db: SqliteDatabase): boolean {\n try {\n const row = db\n .prepare(\n `SELECT 1 as ok FROM sqlite_master\n WHERE type = 'table' AND name = 'plugin_pin_materializations'\n LIMIT 1`,\n )\n .get() as { ok: number } | undefined;\n return row !== undefined;\n } catch {\n return false;\n }\n}\n\nexport interface PluginPinMaterialization {\n id: string;\n scope: MaterializationScope;\n root_path: string;\n relative_path: string;\n origin_ref: string;\n resource_type: string;\n resource_name: string;\n plugin_pin_resource_id: string | null;\n created_at: string;\n updated_at: string;\n}\n\nfunction normalizeRelativePath(path: string): string {\n return path.replace(/\\\\/g, \"/\").replace(/^\\.\\//, \"\");\n}\n\nexport function upsertPluginPinMaterialization(input: {\n scope: MaterializationScope;\n root_path: string;\n relative_path: string;\n origin_ref: string;\n resource_type: string;\n resource_name: string;\n plugin_pin_resource_id?: string | null;\n}): void {\n const db = getDb();\n const now = new Date().toISOString();\n const relative = normalizeRelativePath(input.relative_path);\n const existing = db\n .prepare(\n `SELECT id FROM plugin_pin_materializations\n WHERE scope = ? AND root_path = ? AND relative_path = ?`,\n )\n .get(input.scope, input.root_path, relative) as { id: string } | undefined;\n\n if (existing) {\n db.prepare(\n `UPDATE plugin_pin_materializations\n SET origin_ref = ?,\n resource_type = ?,\n resource_name = ?,\n plugin_pin_resource_id = ?,\n updated_at = ?\n WHERE id = ?`,\n ).run(\n input.origin_ref,\n input.resource_type,\n input.resource_name,\n input.plugin_pin_resource_id ?? null,\n now,\n existing.id,\n );\n return;\n }\n\n const id = ulid();\n db.prepare(\n `INSERT INTO plugin_pin_materializations (\n id, scope, root_path, relative_path, origin_ref,\n resource_type, resource_name, plugin_pin_resource_id,\n created_at, updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n ).run(\n id,\n input.scope,\n input.root_path,\n relative,\n input.origin_ref,\n input.resource_type,\n input.resource_name,\n input.plugin_pin_resource_id ?? null,\n now,\n now,\n );\n}\n\nfunction relativePathCandidates(\n resource: { type: string; name: string; source?: string },\n): string[] {\n const source = resource.source?.trim();\n if (!source) {\n return [];\n }\n const configured = source.startsWith(\"~/\")\n ? source.slice(2)\n : source;\n const relative = normalizeRelativePath(configured);\n const candidates = [relative];\n if (resource.type === \"skill\" && relative.endsWith(\"/SKILL.md\")) {\n candidates.push(dirnameSkillDir(relative));\n }\n return candidates;\n}\n\nfunction dirnameSkillDir(skillMdPath: string): string {\n const normalized = skillMdPath.replace(/\\\\/g, \"/\");\n if (!normalized.endsWith(\"/SKILL.md\")) {\n return normalized;\n }\n return normalized.slice(0, -\"/SKILL.md\".length);\n}\n\nexport function matchesPluginPinMaterialization(\n rootPath: string,\n resource: { type: string; name: string; source?: string },\n): boolean {\n const paths = relativePathCandidates(resource);\n if (paths.length === 0) {\n return false;\n }\n const expanded = new Set<string>();\n for (const relative of paths) {\n expanded.add(relative);\n if (relative.endsWith(\"/SKILL.md\")) {\n expanded.add(dirnameSkillDir(relative));\n } else if (resource.type === \"skill\") {\n expanded.add(`${relative}/SKILL.md`);\n }\n }\n try {\n const db = getDb();\n if (!pluginPinMaterializationTableExists(db)) {\n return false;\n }\n for (const relative of expanded) {\n const row = db\n .prepare(\n `SELECT 1 as ok FROM plugin_pin_materializations\n WHERE root_path = ?\n AND relative_path = ?\n AND resource_type = ?\n AND resource_name = ?\n LIMIT 1`,\n )\n .get(rootPath, relative, resource.type, resource.name) as\n | { ok: number }\n | undefined;\n if (row !== undefined) {\n return true;\n }\n }\n } catch {\n return false;\n }\n return false;\n}\n\nexport function findPluginPinResourceIdByOriginRef(\n originRef: string,\n): string | null {\n const db = getDb();\n const row = db\n .prepare(\n `SELECT id FROM resources\n WHERE type = 'plugin'\n AND origin_ref = ?\n ORDER BY updated_at DESC\n LIMIT 1`,\n )\n .get(originRef) as { id: string } | undefined;\n return row?.id ?? null;\n}\n","import { parsePluginRef } from \"../plugins/host-plugin-manifest.js\";\nimport type { PluginDependencyMetadata, ResourceCreateInput } from \"../types.js\";\nimport { isHostPluginPinResource } from \"./host-plugin-serialize.js\";\n\nexport const PLUGIN_TRANSLATION_SCHEMA = \"urn:harnesstap:plugin-translation:v1\" as const;\n\nexport interface PluginTranslationSource {\n plugin: string;\n marketplace: string;\n origin_ref: string;\n version?: string;\n}\n\nexport interface PluginTranslationMarkerEntry extends PluginTranslationSource {\n type: string;\n name: string;\n}\n\nexport interface PluginTranslationMarkerFile {\n schema: typeof PLUGIN_TRANSLATION_SCHEMA;\n entries: PluginTranslationMarkerEntry[];\n}\n\nexport function pluginTranslationSourceFromPin(\n pin: ResourceCreateInput,\n): PluginTranslationSource | undefined {\n if (\n !isHostPluginPinResource({\n type: pin.type,\n metadata: pin.metadata,\n origin_ref: pin.origin_ref ?? \"\",\n })\n ) {\n return undefined;\n }\n const metadata = (pin.metadata ?? {}) as PluginDependencyMetadata;\n const originRef = pin.origin_ref?.trim() || pin.name;\n const parsed = parsePluginRef(\n originRef.includes(\"@\")\n ? originRef\n : `${pin.name}@${metadata.marketplace_name ?? \"local\"}`,\n );\n const marketplace =\n parsed.marketplace || metadata.marketplace_name?.trim() || \"local\";\n const pluginName = parsed.name || pin.name;\n const resolvedOrigin = originRef.includes(\"@\")\n ? originRef\n : `${pluginName}@${marketplace}`;\n const version = metadata.resolved_version?.trim();\n return {\n plugin: pluginName,\n marketplace,\n origin_ref: resolvedOrigin,\n ...(version ? { version } : {}),\n };\n}\n","import {\n createResource,\n findResourceByKey,\n upsertResource,\n} from \"../models/resource.js\";\nimport type {\n Resource,\n ResourceCreateInput,\n ResourceMetadata,\n ResourceType,\n} from \"../types.js\";\n\nexport const LIVE_CONTENT_STATUS = \"live\";\n\nexport function isLiveLibraryRef(\n resource: Pick<Resource, \"metadata\">,\n): boolean {\n const metadata = resource.metadata as Record<string, unknown>;\n return metadata.content_status === LIVE_CONTENT_STATUS;\n}\n\nfunction withLiveMetadata(metadata: ResourceMetadata | undefined): ResourceMetadata {\n return {\n ...(metadata && typeof metadata === \"object\" ? metadata : {}),\n content_status: LIVE_CONTENT_STATUS,\n };\n}\n\n/**\n * Ensure a library row exists for an on-disk resource without snapshotting content.\n * Existing snapshotted (non-live) rows are left unchanged.\n */\nexport function ensureLiveLibraryRef(\n input: ResourceCreateInput,\n originRef: string,\n): Resource {\n const namespace = input.namespace ?? \"\";\n const existing = findResourceByKey(\n input.type as ResourceType,\n input.name,\n namespace,\n );\n if (existing) {\n if (!isLiveLibraryRef(existing)) {\n return existing;\n }\n const nextOrigin = originRef || existing.origin_ref;\n const nextSource = input.source || existing.source;\n if (nextOrigin === existing.origin_ref && nextSource === existing.source) {\n return existing;\n }\n const updated = upsertResource(\n {\n type: existing.type,\n name: existing.name,\n namespace: existing.namespace,\n description: existing.description,\n content: existing.content,\n metadata: withLiveMetadata(existing.metadata),\n source: nextSource,\n origin_kind: \"manual\",\n origin_ref: nextOrigin,\n },\n { policy: \"overwrite\" },\n );\n return updated.action === \"skipped\" ? existing : updated.resource;\n }\n\n return createResource({\n type: input.type,\n name: input.name,\n namespace,\n description: input.description ?? \"\",\n content: \"\",\n metadata: withLiveMetadata(input.metadata),\n source: input.source,\n origin_kind: \"manual\",\n origin_ref: originRef || input.source,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAY;AAiCrB,SAAS,sBAAsB,KAA4C;AACzE,SAAO;AAAA,IACL,GAAG;AAAA,IACH,gBAAgB,IAAI,kBAAkB;AAAA,IACtC,cAAc,KAAK,MAAM,IAAI,YAAY;AAAA,IACzC,UAAU,KAAK,MAAM,IAAI,QAAQ;AAAA,EACnC;AACF;AAEA,SAAS,6BACP,KACyB;AACzB,SAAO;AAAA,IACL,GAAG;AAAA,IACH,OAAO,KAAK,MAAM,IAAI,KAAK;AAAA,EAC7B;AACF;AAEO,SAAS,uBAAuB,OAOlB;AACnB,QAAM,KAAK,MAAM;AACjB,QAAM,WAA6B;AAAA,IACjC,IAAI,KAAK;AAAA,IACT,aAAa,MAAM;AAAA,IACnB,cAAc,MAAM;AAAA,IACpB,aAAa,MAAM;AAAA,IACnB,gBAAgB,MAAM;AAAA,IACtB,cAAc,MAAM;AAAA,IACpB,UAAU,MAAM;AAAA,IAChB,aAAY,oBAAI,KAAK,GAAE,YAAY;AAAA,EACrC;AAEA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AAAA,MAChC,GAAG;AAAA,MACH,eAAe,UAAU,eAAe,IAAI,OAAO,UAAU,KAAK;AAAA,IACpE,EAAE;AAAA,IACF,WAAW,UAAU;AAAA,IACrB,UAAU,UAAU;AAAA,EACtB;AACF;","names":["join","matter","matter","stripHomePrefix","join","join","join","join","isRecord","join","r","existsSync","readdirSync","readFileSync","statSync","join","relative","parse","isRecord","parse","statSync","join","existsSync","readFileSync","relative","readdirSync","join","join","join","join","join","join","content","join","parse","PROJECT_SKILL_COMPAT","isRecord","parse","permissionName","mergeConfigDocuments","buildMcpServers","join","r","join","relative","sep","parse","stringify","join","parse","isRecord","existsSync","readdirSync","readFileSync","statSync","join","existsSync","readFileSync","isDirectory","statSync","join","readdirSync","hooksOutputPath","isRecord","parse","relative","join","sep","r","stringify","join","PROJECT_INSTRUCTION_CANDIDATES","join","isRecord","entry","r","join","PROJECT_INSTRUCTION_CANDIDATES","PROJECT_SKILL_DIRS","GLOBAL_SKILL_DIRS","join","isRecord","entry","r","join","resolveGlobalPath","join","existsSync","lstatSync","readdirSync","readFileSync","dirname","join","existsSync","readFileSync","dirname","join","existsSync","readFileSync","dirname","join","ulid","relative","join","existsSync","readFileSync","dirname","relative","resolveConfiguredPath","join","existsSync","readdirSync","dirname","lstatSync","relative","existingPaths","readFileSync"]}