agents-inc 0.170.1 → 0.170.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +9 -0
- package/dist/{chunk-BMRUNMPV.js → chunk-2YA4DDRM.js} +35 -35
- package/dist/chunk-2YA4DDRM.js.map +1 -0
- package/dist/{chunk-44TE3RKH.js → chunk-3ED3KHHD.js} +5 -4
- package/dist/chunk-3ED3KHHD.js.map +1 -0
- package/dist/{chunk-3G7X2WKI.js → chunk-5BNX73OU.js} +18 -38
- package/dist/chunk-5BNX73OU.js.map +1 -0
- package/dist/{chunk-7RDMTR64.js → chunk-66AEVERM.js} +785 -256
- package/dist/chunk-66AEVERM.js.map +1 -0
- package/dist/{chunk-PJWGTNOX.js → chunk-7C3PFRBU.js} +144 -186
- package/dist/chunk-7C3PFRBU.js.map +1 -0
- package/dist/{chunk-52HDHJ7I.js → chunk-AUNRHWH4.js} +32 -21
- package/dist/chunk-AUNRHWH4.js.map +1 -0
- package/dist/{chunk-KOLDW6SF.js → chunk-BBDGYJHX.js} +2 -2
- package/dist/chunk-BBDGYJHX.js.map +1 -0
- package/dist/{chunk-SZYQISA2.js → chunk-ELV5WDS3.js} +43 -29
- package/dist/chunk-ELV5WDS3.js.map +1 -0
- package/dist/{chunk-MQ6CGZNJ.js → chunk-GAKVZNTX.js} +1879 -2019
- package/dist/chunk-GAKVZNTX.js.map +1 -0
- package/dist/chunk-GEMW5RQ2.js +1169 -0
- package/dist/chunk-GEMW5RQ2.js.map +1 -0
- package/dist/{chunk-NQW25DCF.js → chunk-GHHJYNAN.js} +1 -7
- package/dist/chunk-GHHJYNAN.js.map +1 -0
- package/dist/{chunk-WTWMGH2C.js → chunk-HACRR422.js} +2 -2
- package/dist/chunk-HACRR422.js.map +1 -0
- package/dist/{chunk-F2BHT5C4.js → chunk-IWY5IR4F.js} +129 -151
- package/dist/chunk-IWY5IR4F.js.map +1 -0
- package/dist/{chunk-JFLVEFFP.js → chunk-KIK5EZYD.js} +1 -1
- package/dist/chunk-KIK5EZYD.js.map +1 -0
- package/dist/{chunk-USVBYQSQ.js → chunk-O4LN3HFI.js} +16 -6
- package/dist/chunk-O4LN3HFI.js.map +1 -0
- package/dist/{chunk-RIPSGNLU.js → chunk-OCAVW6N5.js} +3 -3
- package/dist/chunk-OCAVW6N5.js.map +1 -0
- package/dist/{chunk-4AAOOAIN.js → chunk-P6CYS4JK.js} +2 -2
- package/dist/chunk-P6CYS4JK.js.map +1 -0
- package/dist/chunk-PLFANHRZ.js +35 -0
- package/dist/chunk-PLFANHRZ.js.map +1 -0
- package/dist/{chunk-6ZRH5RHC.js → chunk-PMUZR4XO.js} +4 -4
- package/dist/chunk-PMUZR4XO.js.map +1 -0
- package/dist/{chunk-F5EBEATU.js → chunk-PSUTNOQ2.js} +34 -46
- package/dist/chunk-PSUTNOQ2.js.map +1 -0
- package/dist/chunk-RIK45Q4I.js +103 -0
- package/dist/chunk-RIK45Q4I.js.map +1 -0
- package/dist/{chunk-HED2DAXZ.js → chunk-THO7LO5B.js} +5 -5
- package/dist/chunk-THO7LO5B.js.map +1 -0
- package/dist/{chunk-OYJQUA3D.js → chunk-YGDWHDOY.js} +31 -13
- package/dist/chunk-YGDWHDOY.js.map +1 -0
- package/dist/{chunk-NCWDK6L7.js → chunk-YXKTY5WM.js} +254 -379
- package/dist/chunk-YXKTY5WM.js.map +1 -0
- package/dist/{chunk-NEZ4OAOL.js → chunk-ZEGM3MVR.js} +3 -5
- package/dist/chunk-ZEGM3MVR.js.map +1 -0
- package/dist/commands/build/marketplace.js +46 -46
- package/dist/commands/build/marketplace.js.map +1 -1
- package/dist/commands/build/plugins.js +25 -28
- package/dist/commands/build/plugins.js.map +1 -1
- package/dist/commands/compile.js +87 -178
- package/dist/commands/compile.js.map +1 -1
- package/dist/commands/doctor.js +510 -360
- package/dist/commands/doctor.js.map +1 -1
- package/dist/commands/edit.js +451 -357
- package/dist/commands/edit.js.map +1 -1
- package/dist/commands/eject.js +144 -125
- package/dist/commands/eject.js.map +1 -1
- package/dist/commands/init.js +20 -27
- package/dist/commands/list.js +39 -55
- package/dist/commands/list.js.map +1 -1
- package/dist/commands/new/marketplace.js +6 -11
- package/dist/commands/new/marketplace.js.map +1 -1
- package/dist/commands/search.js +35 -32
- package/dist/commands/search.js.map +1 -1
- package/dist/commands/share.js +17 -77
- package/dist/commands/share.js.map +1 -1
- package/dist/commands/uninstall.js +159 -222
- package/dist/commands/uninstall.js.map +1 -1
- package/dist/commands/update.js +9 -32
- package/dist/commands/update.js.map +1 -1
- package/dist/components/common/prompt-confirm.js +2 -2
- package/dist/components/common/removal-plan-confirm.js +2 -2
- package/dist/components/common/scroll-affordance.js +2 -2
- package/dist/components/common/select-list.js +2 -2
- package/dist/components/common/skill-agent-summary.js +4 -4
- package/dist/components/common/spinner.js +2 -4
- package/dist/components/common/summary-panel.js +5 -5
- package/dist/components/common/summary-panel.js.map +1 -1
- package/dist/config-exports.js +7 -3
- package/dist/config-exports.js.map +1 -1
- package/dist/hooks/init.js +18 -19
- package/dist/hooks/init.js.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/load-agent-defs-6QUUMGHK.js +14 -0
- package/dist/recompile-project-agents-I33KQJFB.js +65 -0
- package/dist/recompile-project-agents-I33KQJFB.js.map +1 -0
- package/dist/{source-loader-C5SQXZXI.js → source-loader-TTJVW2ER.js} +5 -5
- package/dist/src/agents/developer/ai-developer/playbook.md +2 -5
- package/dist/src/agents/developer/api-developer/playbook.md +2 -5
- package/dist/src/agents/developer/cli-developer/playbook.md +2 -5
- package/dist/src/agents/developer/web-developer/playbook.md +2 -5
- package/dist/src/agents/meta/agent-summoner/output.md +2 -2
- package/dist/src/agents/meta/agent-summoner/playbook.md +1 -13
- package/dist/src/agents/meta/codex-keeper/critical-requirements.md +2 -5
- package/dist/src/agents/meta/convention-keeper/critical-requirements.md +2 -4
- package/dist/src/agents/tester/ai-tester/critical-requirements.md +1 -2
- package/dist/src/agents/tester/ai-tester/playbook.md +2 -0
- package/dist/src/agents/tester/api-tester/critical-requirements.md +1 -2
- package/dist/src/agents/tester/api-tester/playbook.md +2 -0
- package/dist/src/agents/tester/cli-tester/critical-requirements.md +1 -2
- package/dist/src/agents/tester/cli-tester/playbook.md +2 -0
- package/dist/src/agents/tester/web-tester/critical-requirements.md +1 -2
- package/dist/src/agents/tester/web-tester/playbook.md +2 -0
- package/package.json +9 -8
- package/src/agents/developer/ai-developer/playbook.md +2 -5
- package/src/agents/developer/api-developer/playbook.md +2 -5
- package/src/agents/developer/cli-developer/playbook.md +2 -5
- package/src/agents/developer/web-developer/playbook.md +2 -5
- package/src/agents/meta/agent-summoner/output.md +2 -2
- package/src/agents/meta/agent-summoner/playbook.md +1 -13
- package/src/agents/meta/codex-keeper/critical-requirements.md +2 -5
- package/src/agents/meta/convention-keeper/critical-requirements.md +2 -4
- package/src/agents/tester/ai-tester/critical-requirements.md +1 -2
- package/src/agents/tester/ai-tester/playbook.md +2 -0
- package/src/agents/tester/api-tester/critical-requirements.md +1 -2
- package/src/agents/tester/api-tester/playbook.md +2 -0
- package/src/agents/tester/cli-tester/critical-requirements.md +1 -2
- package/src/agents/tester/cli-tester/playbook.md +2 -0
- package/src/agents/tester/web-tester/critical-requirements.md +1 -2
- package/src/agents/tester/web-tester/playbook.md +2 -0
- package/src/schemas/project-config.schema.json +0 -3
- package/src/schemas/project-source-config.schema.json +0 -6
- package/dist/chunk-3G7X2WKI.js.map +0 -1
- package/dist/chunk-44TE3RKH.js.map +0 -1
- package/dist/chunk-4AAOOAIN.js.map +0 -1
- package/dist/chunk-52HDHJ7I.js.map +0 -1
- package/dist/chunk-6HNXYYVF.js +0 -373
- package/dist/chunk-6HNXYYVF.js.map +0 -1
- package/dist/chunk-6ZRH5RHC.js.map +0 -1
- package/dist/chunk-7RDMTR64.js.map +0 -1
- package/dist/chunk-BMRUNMPV.js.map +0 -1
- package/dist/chunk-CLPUWOSA.js +0 -46
- package/dist/chunk-CLPUWOSA.js.map +0 -1
- package/dist/chunk-F2BHT5C4.js.map +0 -1
- package/dist/chunk-F5EBEATU.js.map +0 -1
- package/dist/chunk-HED2DAXZ.js.map +0 -1
- package/dist/chunk-JFLVEFFP.js.map +0 -1
- package/dist/chunk-KOLDW6SF.js.map +0 -1
- package/dist/chunk-MQ6CGZNJ.js.map +0 -1
- package/dist/chunk-NCWDK6L7.js.map +0 -1
- package/dist/chunk-NEZ4OAOL.js.map +0 -1
- package/dist/chunk-NIHUOWE4.js +0 -106
- package/dist/chunk-NIHUOWE4.js.map +0 -1
- package/dist/chunk-NQW25DCF.js.map +0 -1
- package/dist/chunk-OYJQUA3D.js.map +0 -1
- package/dist/chunk-PJWGTNOX.js.map +0 -1
- package/dist/chunk-RIPSGNLU.js.map +0 -1
- package/dist/chunk-SZYQISA2.js.map +0 -1
- package/dist/chunk-USVBYQSQ.js.map +0 -1
- package/dist/chunk-V3KTSP3Q.js +0 -940
- package/dist/chunk-V3KTSP3Q.js.map +0 -1
- package/dist/chunk-WTWMGH2C.js.map +0 -1
- package/dist/load-agent-defs-YMDWBFDP.js +0 -14
- package/dist/recompile-project-agents-SZ76WNTW.js +0 -18
- package/dist/source-loader-C5SQXZXI.js.map +0 -1
- /package/dist/{load-agent-defs-YMDWBFDP.js.map → load-agent-defs-6QUUMGHK.js.map} +0 -0
- /package/dist/{recompile-project-agents-SZ76WNTW.js.map → source-loader-TTJVW2ER.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cli/lib/loading/source-loader.ts","../src/cli/lib/installation/is-home-directory.ts","../src/cli/lib/metadata-keys.ts","../src/cli/utils/errors.ts","../src/cli/utils/fs.ts","../src/cli/lib/installation/install-layout.ts","../../compile/src/providers/codex/agent-role-toml.ts","../../compile/src/providers/codex/roster.ts","../../compile/src/agent-source.ts","../src/cli/lib/config-gate/gate-token.ts","../src/cli/utils/logger.ts","../src/cli/lib/validate-kebab-name.ts","../src/cli/utils/messages.ts","../src/cli/types/generated/source-types.ts","../src/cli/utils/type-guards.ts","../src/cli/utils/typed-object.ts","../src/cli/lib/configuration/config.ts","../src/cli/lib/schemas.ts","../src/cli/lib/schema-validator.ts","../src/cli/types/matrix.ts","../src/cli/lib/configuration/config-loader.ts","../src/cli/lib/installation/install-base-dir.ts","../src/cli/lib/installation/provider-to-name.ts","../src/cli/lib/compile-seat.ts","../../compile/src/seed-to-config.ts","../../compile/src/config-source.ts","../../compile/src/installed-format.ts","../../compile/src/typed-object.ts","../src/cli/lib/configuration/config-merger.ts","../src/cli/lib/configuration/project-config.ts","../src/cli/lib/stacks/stacks-loader.ts","../src/cli/lib/skills/skill-metadata.ts","../src/cli/lib/versioning.ts","../src/cli/utils/yaml-schema.ts","../src/cli/lib/skills/skill-copier.ts","../src/cli/lib/skills/skill-plugin-compiler.ts","../src/cli/lib/plugins/plugin-manifest.ts","../src/cli/lib/plugins/plugin-finder.ts","../src/cli/lib/plugins/plugin-ref.ts","../src/cli/lib/plugins/plugin-info.ts","../src/cli/lib/installation/installation.ts","../src/cli/lib/installation/local-installer.ts","../src/cli/lib/loading/loader.ts","../src/cli/utils/frontmatter.ts","../src/cli/lib/loading/source-fetcher.ts","../src/cli/lib/marketplace-generator.ts","../src/cli/lib/loading/multi-source-loader.ts","../src/cli/lib/resolver.ts","../src/cli/lib/installation/source-scopes.ts","../src/cli/lib/installation/detect-installations.ts","../src/cli/lib/hosts/claude-host.ts","../src/cli/utils/exec.ts","../src/cli/lib/plugins/plugin-settings.ts","../src/cli/lib/hosts/codex-host.ts","../src/cli/lib/hosts/offered-placements.ts","../src/cli/lib/hosts/host-for.ts","../src/cli/lib/installation/mode-migrator.ts","../src/cli/lib/plugins/plugin-validator.ts","../src/cli/lib/validation-result.ts","../src/cli/lib/plugins/plugin-discovery.ts","../src/cli/lib/skills/local-skill-loader.ts","../src/cli/lib/skills/unresolved-skill-entries.ts","../src/cli/lib/skills/local-skill-mover.ts","../src/cli/lib/matrix/matrix-loader.ts","../src/cli/lib/matrix/skill-resolution.ts","../src/cli/lib/configuration/skill-audit.ts","../src/cli/lib/matrix/matrix-health-check.ts"],"sourcesContent":["import os from \"os\";\nimport { partition, unique } from \"remeda\";\nimport path from \"path\";\nimport {\n EJECT_SOURCE,\n MARKETPLACE_JSON,\n PROJECT_ROOT,\n SKILL_CATEGORIES_PATH,\n SKILL_RULES_PATH,\n SKILLS_DIR_PATH,\n LOCAL_PSEUDO_CATEGORY,\n STANDARD_FILES,\n type Provider,\n} from \"../../consts\";\nimport { defaultCategories } from \"../configuration/default-categories\";\nimport { defaultStacks } from \"../configuration/default-stacks\";\nimport { isHomeDirectory } from \"../installation/is-home-directory\";\nimport { LOCAL_DEFAULTS, METADATA_KEYS } from \"../metadata-keys\";\nimport type {\n AgentName,\n CategoryDefinition,\n CategoryMap,\n CategoryPath,\n Domain,\n ExtractedSkillMetadata,\n MergedSkillsMatrix,\n ResolvedSkill,\n ResolvedStack,\n SkillAssignment,\n SkillConfig,\n SkillId,\n SkillRulesConfig,\n SkillScope,\n Stack,\n StackAgentConfig,\n Category,\n} from \"../../types\";\nimport { getErrorMessage } from \"../../utils/errors\";\nimport { fileExists } from \"../../utils/fs\";\nimport { sayingEachWarningOnce, verbose, warn } from \"../../utils/logger\";\nimport { marketplaceManifestMissing, marketplaceManifestUnreadable } from \"../../utils/messages\";\nimport { isAgentName } from \"../../utils/type-guards\";\nimport { typedEntries, typedFromEntries, typedKeys, typedValues } from \"../../utils/typed-object\";\nimport {\n isDefaultSource,\n isLocalSource,\n isPublicCatalogueCheckout,\n loadGlobalSourceConfig,\n loadSourceRepoConfig,\n offersBuiltInStacks,\n resolveSource,\n type ResolvedConfig,\n type SourceCaller,\n} from \"../configuration\";\nimport { discoverLocalSkills, type LocalSkillDiscoveryResult } from \"../skills\";\nimport {\n checkMatrixHealth,\n claimSlug,\n extractAllSkills,\n loadSkillCategories,\n loadSkillRules,\n mergeMatrixWithSkills,\n relationshipsForSource,\n} from \"../matrix\";\nimport { validateLoadedMarketplaceName } from \"../marketplace-generator\";\nimport {\n fetchFromSource,\n fetchMarketplace,\n MarketplaceManifestAbsentError,\n MarketplaceNameRefusedError,\n} from \"./source-fetcher\";\nimport { loadSkillsFromAllSources, marketplaceSource } from \"./multi-source-loader\";\nimport { loadStacks, resolveAgentConfigToSkills } from \"../stacks\";\nimport { initializeMatrix, matrix as currentMatrix } from \"../matrix/matrix-provider\";\nimport { BUILT_IN_MATRIX } from \"../../types/generated/matrix\";\n\n/** `\"fetch\"` refuses a non-default marketplace without a valid manifest; `\"upkeep\"` goes on. */\ntype SourceLoadPurpose = \"fetch\" | \"upkeep\";\n\ntype SourceLoadOptions = {\n /** Defaults to `\"fetch\"`. */\n purpose?: SourceLoadPurpose;\n /** Defaults to `\"stored\"`, so the environment rung is never reached by omission. */\n caller?: SourceCaller;\n sourceFlag?: string;\n projectDir?: string;\n /** Whose config names the marketplace, where a scope holds two installations. */\n provider?: Provider;\n devMode?: boolean;\n skipExtraSources?: boolean;\n /** For the default source, skips the clone so the load stays offline; `sourcePath` is empty. */\n matrixOnly?: boolean;\n};\n\nexport type SourceLoadResult = {\n matrix: MergedSkillsMatrix;\n sourceConfig: ResolvedConfig;\n sourcePath: string;\n isLocal: boolean;\n /** The marketplace could not be reached, so `sourcePath` is its cached copy, of unknown age. */\n unreachable: boolean;\n marketplace?: string;\n /** The only skills `sourcePath` has files for; the matrix also holds local and global ones. */\n marketplaceSkillIds: ReadonlySet<SkillId>;\n};\n\n/** A marketplace's catalogue as read, before anything on this machine joins its matrix. */\ntype CatalogueRead = Omit<SourceLoadResult, \"marketplaceSkillIds\">;\n\n/** Says each warning once per run: a global change reloads the same files per project. */\nexport function loadSkillsMatrixFromSource(\n options: SourceLoadOptions = {},\n): Promise<SourceLoadResult> {\n return sayingEachWarningOnce(() => loadCatalogue(options));\n}\n\nasync function loadCatalogue(options: SourceLoadOptions): Promise<SourceLoadResult> {\n const {\n purpose = \"fetch\",\n caller = \"stored\",\n sourceFlag,\n projectDir,\n provider,\n devMode = false,\n matrixOnly = false,\n } = options;\n\n // Aborts on an unreadable config: every skill resolves against the marketplace named here.\n const sourceConfig = await resolveSource({ caller, flag: sourceFlag, projectDir, provider });\n const { source } = sourceConfig;\n\n verbose(`Loading skills from source: ${source}`);\n\n const catalogue = await resolveBaseResult(sourceConfig, { purpose, devMode, matrixOnly });\n\n const resolvedProjectDir = projectDir || process.cwd();\n\n // Read before any local merge, after which a skill's provenance is no longer legible.\n const result: SourceLoadResult = {\n ...catalogue,\n marketplaceSkillIds: new Set(typedKeys<SkillId>(catalogue.matrix.skills)),\n };\n\n result.matrix = await mergeLocalSkills(result.matrix, resolvedProjectDir);\n await seatGlobalInstallationSkills(result.matrix, source, purpose);\n\n if (!options.skipExtraSources) {\n await loadSkillsFromAllSources(\n result.matrix,\n sourceConfig,\n resolvedProjectDir,\n result.marketplace,\n idsOutsideMarketplace(result.matrix, result.marketplaceSkillIds),\n );\n }\n\n checkMatrixHealth(result.matrix);\n initializeMatrix(result.matrix);\n\n return result;\n}\n\n/**\n * Seats the global installation's plugin skills this catalogue lacks, from the marketplace that\n * installation was made from (a plugin leaves no local copy to merge). Seated entries carry no\n * relationships: they are shown and compiled, never picked against.\n */\nasync function seatGlobalInstallationSkills(\n matrix: MergedSkillsMatrix,\n loadedSource: string,\n purpose: SourceLoadPurpose,\n): Promise<void> {\n const uncarried = await globalPluginSkillsUncarried(matrix);\n if (uncarried.length === 0) return;\n\n const globalCatalogue = await loadGlobalInstallationCatalogue(loadedSource, purpose);\n if (globalCatalogue === null) return;\n\n for (const id of uncarried) seatFromCatalogue(matrix, globalCatalogue, id);\n}\n\n/** Degrades on an unreadable global config: its skills simply stay unseated. */\nasync function globalPluginSkillsUncarried(matrix: MergedSkillsMatrix): Promise<SkillId[]> {\n try {\n const globalConfig = await loadGlobalSourceConfig();\n return (globalConfig?.skills ?? [])\n .filter(isActivePlugin)\n .filter((skill) => matrix.skills[skill.id] === undefined)\n .map((skill) => skill.id);\n } catch (error) {\n verbose(`Global installation's skills not seated — ${getErrorMessage(error)}`);\n return [];\n }\n}\n\n/** An entry still configured, installed as a marketplace's plugin rather than ejected. */\nfunction isActivePlugin(skill: SkillConfig): boolean {\n return !skill.excluded && skill.origin !== EJECT_SOURCE;\n}\n\n/**\n * Null when it is the one already loaded, or when it cannot load (the skills then stay unseated).\n */\nasync function loadGlobalInstallationCatalogue(\n loadedSource: string,\n purpose: SourceLoadPurpose,\n): Promise<CatalogueRead | null> {\n try {\n const globalSourceConfig = await resolveSource({ caller: \"stored\", projectDir: os.homedir() });\n if (globalSourceConfig.source === loadedSource) return null;\n return await resolveBaseResult(globalSourceConfig, {\n purpose,\n devMode: false,\n matrixOnly: true,\n });\n } catch (error) {\n verbose(`Global installation's marketplace not loaded — ${getErrorMessage(error)}`);\n return null;\n }\n}\n\n/** One global skill, as its own catalogue holds it, carried under its own marketplace's name. */\nfunction seatFromCatalogue(\n matrix: MergedSkillsMatrix,\n catalogue: CatalogueRead,\n id: SkillId,\n): void {\n const skill = catalogue.matrix.skills[id];\n // Withdrawn from its own marketplace too, so absent is the truth and the session says so.\n if (!skill) return;\n\n matrix.skills[id] = asSeatedGlobalSkill(skill, catalogue);\n claimSlug(matrix.slugMap, skill.slug, id);\n carryCategory(matrix, catalogue.matrix, skill.category);\n}\n\n/** The entry as a session here shows and compiles it: none of its relationships, its own name. */\nfunction asSeatedGlobalSkill(skill: ResolvedSkill, catalogue: CatalogueRead): ResolvedSkill {\n return {\n ...skill,\n conflictsWith: [],\n requires: [],\n alternatives: [],\n discourages: [],\n availableSources: [marketplaceSource(catalogue.sourceConfig, catalogue.marketplace)],\n };\n}\n\n/** A category the matrix lacks arrives with the skill placed in it; `local` is never defined. */\nfunction carryCategory(\n matrix: MergedSkillsMatrix,\n from: MergedSkillsMatrix,\n categoryId: CategoryPath,\n): void {\n if (categoryId === LOCAL_PSEUDO_CATEGORY || matrix.categories[categoryId]) return;\n const category = from.categories[categoryId];\n if (category) matrix.categories[categoryId] = category;\n}\n\n/**\n * Merged-in skills the marketplace never offered, which the tagging pass must leave its entry off.\n */\nfunction idsOutsideMarketplace(\n matrix: MergedSkillsMatrix,\n marketplaceSkillIds: ReadonlySet<SkillId>,\n): ReadonlySet<SkillId> {\n return new Set(typedKeys<SkillId>(matrix.skills).filter((id) => !marketplaceSkillIds.has(id)));\n}\n\n/**\n * Copies every collection the local merge writes to, so `BUILT_IN_MATRIX` itself is never mutated.\n */\nfunction copyOfBuiltInMatrix(): MergedSkillsMatrix {\n return {\n ...BUILT_IN_MATRIX,\n skills: { ...BUILT_IN_MATRIX.skills },\n categories: { ...BUILT_IN_MATRIX.categories },\n suggestedStacks: [...BUILT_IN_MATRIX.suggestedStacks],\n slugMap: {\n slugToId: { ...BUILT_IN_MATRIX.slugMap.slugToId },\n },\n };\n}\n\ntype BaseLoadOptions = Required<Pick<SourceLoadOptions, \"purpose\" | \"devMode\" | \"matrixOnly\">>;\n\n/** A `matrixOnly` load of the default source reads the built-in matrix and fetches nothing. */\nconst NOTHING_FETCHED = { path: \"\", unreachable: false } as const;\n\nasync function resolveBaseResult(\n sourceConfig: ResolvedConfig,\n { purpose, devMode, matrixOnly }: BaseLoadOptions,\n): Promise<CatalogueRead> {\n refuseReservedRecordedName(sourceConfig);\n const { source } = sourceConfig;\n if (isDefaultSource(source) && !devMode) {\n // Default source: BUILT_IN_MATRIX, still fetching (cached) for sourcePath unless matrixOnly.\n const fetched = matrixOnly ? NOTHING_FETCHED : await fetchFromSource(source);\n return {\n matrix: copyOfBuiltInMatrix(),\n sourceConfig,\n sourcePath: fetched.path,\n isLocal: false,\n unreachable: fetched.unreachable,\n ...(sourceConfig.marketplace !== undefined && { marketplace: sourceConfig.marketplace }),\n };\n }\n\n const isLocal = isLocalSource(source) || devMode;\n return isLocal\n ? loadFromLocal(source, sourceConfig, purpose)\n : loadFromRemote(source, sourceConfig, purpose);\n}\n\n/** The file to correct is the config that recorded the name, not the manifest. */\nfunction recordedNameWayOut(configPath: string): string {\n return `set this installation up again, or correct the marketplaceName it recorded in '${configPath}'`;\n}\n\n/** The recorded name outranks the manifest's, so it is checked against the reserved list too. */\nfunction refuseReservedRecordedName({ marketplace, marketplaceRecordedIn }: ResolvedConfig): void {\n if (marketplace === undefined) return;\n const reservedName = validateLoadedMarketplaceName(\n marketplace,\n recordedNameWayOut(marketplaceRecordedIn),\n );\n if (reservedName) throw new MarketplaceNameRefusedError(reservedName);\n}\n\ntype MarketplaceLabels = Pick<SourceLoadResult, \"marketplace\">;\n\n/** Absent and unreadable stay apart so a refusal can carry the reason; a refused name too. */\ntype ManifestState =\n | { kind: \"absent\" }\n | { kind: \"refused\"; reason: string }\n | { kind: \"unreadable\"; reason: string }\n | { kind: \"named\"; name: string };\n\n/** Read off the throw's type, never its text. */\nasync function readManifestState(source: string): Promise<ManifestState> {\n try {\n const { marketplace } = await fetchMarketplace(source);\n return { kind: \"named\", name: marketplace.name };\n } catch (error) {\n if (error instanceof MarketplaceManifestAbsentError) return { kind: \"absent\" };\n if (error instanceof MarketplaceNameRefusedError) {\n return { kind: \"refused\", reason: getErrorMessage(error) };\n }\n return { kind: \"unreadable\", reason: getErrorMessage(error) };\n }\n}\n\n/** A type, so `doctor` can file it at the reader's severity without matching text. */\nexport class MarketplaceManifestRequiredError extends Error {}\n\n/** A manifest this load could not name the marketplace from. */\ntype ManifestUnusable = Extract<ManifestState, { kind: \"absent\" | \"unreadable\" }>;\n\n/** A recorded `marketplace` wins. All but `named` abort a `\"fetch\"` of a non-default one. */\nasync function resolveMarketplaceLabels(\n manifestRoot: string,\n sourceConfig: ResolvedConfig,\n purpose: SourceLoadPurpose,\n): Promise<MarketplaceLabels> {\n const state = await readManifestState(manifestRoot);\n\n switch (state.kind) {\n case \"named\": {\n const marketplace = sourceConfig.marketplace ?? state.name;\n verbose(`Using marketplace name from ${MARKETPLACE_JSON}: ${marketplace}`);\n return { marketplace };\n }\n case \"refused\":\n throw new MarketplaceNameRefusedError(state.reason);\n case \"absent\":\n case \"unreadable\":\n return labelWithoutManifest(state, sourceConfig, purpose);\n default: {\n const exhaustive: never = state;\n return exhaustive;\n }\n }\n}\n\n/** Keeps the recorded label when the load may go on; otherwise refuses, naming the builds. */\nfunction labelWithoutManifest(\n state: ManifestUnusable,\n sourceConfig: ResolvedConfig,\n purpose: SourceLoadPurpose,\n): MarketplaceLabels {\n const { source } = sourceConfig;\n if (goesOnWithoutManifest(source, purpose)) {\n verbose(`'${source}' has no usable ${MARKETPLACE_JSON}; keeping the label its config recorded`);\n return configuredLabel(sourceConfig);\n }\n\n throw new MarketplaceManifestRequiredError(\n state.kind === \"absent\"\n ? marketplaceManifestMissing(source)\n : marketplaceManifestUnreadable(source, state.reason),\n );\n}\n\n/** The default catalogue (dev mode reads `PROJECT_ROOT`, which ships none) and `\"upkeep\"`. */\nfunction goesOnWithoutManifest(source: string, purpose: SourceLoadPurpose): boolean {\n return isDefaultSource(source) || purpose === \"upkeep\";\n}\n\n/** The label a config already recorded, which outlives a manifest this load could not name. */\nfunction configuredLabel(sourceConfig: ResolvedConfig): MarketplaceLabels {\n return sourceConfig.marketplace === undefined ? {} : { marketplace: sourceConfig.marketplace };\n}\n\n/** Global local skills first, then the project's, so the project's win on conflict. */\nasync function mergeLocalSkills(\n matrix: MergedSkillsMatrix,\n projectDir: string,\n): Promise<MergedSkillsMatrix> {\n const withGlobal = isHomeDirectory(projectDir)\n ? matrix\n : await mergeDiscoveredLocalSkills(matrix, os.homedir(), \"global\");\n return mergeDiscoveredLocalSkills(withGlobal, projectDir, \"project\");\n}\n\n/** Merges any discovered local skills for `dir` into the matrix, logging the find. */\nasync function mergeDiscoveredLocalSkills(\n matrix: MergedSkillsMatrix,\n dir: string,\n label: SkillScope,\n): Promise<MergedSkillsMatrix> {\n const discovered = await discoverLocalSkills(dir);\n if (!discovered || discovered.skills.length === 0) return matrix;\n verbose(\n `Found ${discovered.skills.length} ${label} local skill(s) in ${discovered.localSkillsPath}`,\n );\n return mergeLocalSkillsIntoMatrix(matrix, discovered);\n}\n\nasync function loadFromLocal(\n source: string,\n sourceConfig: ResolvedConfig,\n purpose: SourceLoadPurpose,\n): Promise<CatalogueRead> {\n // Through `fetchFromSource`, so an unreadable named path is refused rather than read as empty.\n const skillsPath = isLocalSource(source) ? (await fetchFromSource(source)).path : PROJECT_ROOT;\n\n verbose(`Loading skills from local path: ${skillsPath}`);\n\n const mergedMatrix = await loadAndMergeFromBasePath(skillsPath, source);\n const labels = await resolveMarketplaceLabels(skillsPath, sourceConfig, purpose);\n\n return {\n matrix: mergedMatrix,\n sourceConfig,\n sourcePath: skillsPath,\n isLocal: true,\n unreachable: false,\n ...labels,\n };\n}\n\nasync function loadFromRemote(\n source: string,\n sourceConfig: ResolvedConfig,\n purpose: SourceLoadPurpose,\n): Promise<CatalogueRead> {\n verbose(`Fetching skills from remote source: ${source}`);\n\n const fetchResult = await fetchFromSource(source);\n\n verbose(`Fetched to: ${fetchResult.path}`);\n\n const mergedMatrix = await loadAndMergeFromBasePath(fetchResult.path, source);\n const labels = await resolveMarketplaceLabels(source, sourceConfig, purpose);\n\n return {\n matrix: mergedMatrix,\n sourceConfig,\n sourcePath: fetchResult.path,\n isLocal: false,\n unreachable: fetchResult.unreachable,\n ...labels,\n };\n}\n\n/** An author's load: no local merge, or the catalogue would carry one machine's skills. */\nexport async function loadMarketplaceMatrix(marketplaceDir: string): Promise<MergedSkillsMatrix> {\n const matrix = await loadAndMergeFromBasePath(marketplaceDir, marketplaceDir);\n return { ...matrix, categories: categoriesTheseSkillsAreIn(matrix) };\n}\n\n/** Read off the skills, so the catalogue claims no category the marketplace ships nothing in. */\nfunction categoriesTheseSkillsAreIn(matrix: MergedSkillsMatrix): CategoryMap {\n const occupied = new Set<CategoryPath>(typedValues(matrix.skills).map((skill) => skill.category));\n\n return typedFromEntries(\n typedEntries<Category, CategoryDefinition>(matrix.categories).filter(([id]) =>\n occupied.has(id),\n ),\n );\n}\n\n/** `source` is the string `basePath` stands for: the only word for which marketplace it is. */\nasync function loadAndMergeFromBasePath(\n basePath: string,\n source: string,\n): Promise<MergedSkillsMatrix> {\n // Aborts on an unreadable config: it declares where the skills and stacks live.\n const sourceProjectConfig = await loadSourceRepoConfig(basePath);\n\n const skillsDirRelPath = sourceProjectConfig?.skillsDir ?? SKILLS_DIR_PATH;\n const stacksRelFile = sourceProjectConfig?.stacksFile;\n\n const { categories, sourceRules } = await loadSourceTaxonomy(basePath);\n\n const skillsDir = path.join(basePath, skillsDirRelPath);\n verbose(`Skills from source: ${skillsDir}`);\n\n const skills = await extractAllSkills(skillsDir);\n await refuseCatalogueCollisions(basePath, source, skills);\n\n const relationships = relationshipsForSource(skills, sourceRules);\n const mergedMatrix = mergeMatrixWithSkills(categories, relationships, skills);\n initializeMatrix(mergedMatrix);\n\n // Assigned unconditionally: a source offering no stacks is a matrix carrying none.\n const stacks = await resolveOfferedStacks(basePath, stacksRelFile, source);\n mergedMatrix.suggestedStacks = stacks.map((stack) => convertStackToResolvedStack(stack));\n\n return mergedMatrix;\n}\n\n/** What a source declares about its skills' taxonomy, beside the CLI's own. */\ntype SourceTaxonomy = {\n /** The CLI's built-in categories, with the source's own layered over them where it has any. */\n categories: CategoryMap;\n /** The source's own relationship rules, unmerged. */\n sourceRules: SkillRulesConfig | undefined;\n};\n\n/** Either file may be absent; categories layer over the built-ins, rules come back as they are. */\nasync function loadSourceTaxonomy(basePath: string): Promise<SourceTaxonomy> {\n const sourceCategories = await loadSourceCategories(basePath);\n const sourceRules = await loadSourceRules(basePath);\n\n if (sourceCategories !== undefined || sourceRules !== undefined) {\n verbose(`Matrix merged: CLI (${typedKeys(defaultCategories).length} categories) + source`);\n } else {\n verbose(`Matrix from CLI only (source has no categories/rules files)`);\n }\n\n const categories: CategoryMap = sourceCategories\n ? { ...defaultCategories, ...sourceCategories }\n : defaultCategories;\n return { categories, sourceRules };\n}\n\n/** Undefined when the source ships no categories file. */\nasync function loadSourceCategories(basePath: string): Promise<CategoryMap | undefined> {\n const categoriesPath = path.join(basePath, SKILL_CATEGORIES_PATH);\n if (!(await fileExists(categoriesPath))) return undefined;\n\n const categories = await loadSkillCategories(categoriesPath);\n verbose(\n `Loaded source categories: ${categoriesPath} (${typedKeys(categories).length} categories)`,\n );\n return categories;\n}\n\n/** Undefined when the source ships no rules file. */\nasync function loadSourceRules(basePath: string): Promise<SkillRulesConfig | undefined> {\n const rulesPath = path.join(basePath, SKILL_RULES_PATH);\n if (!(await fileExists(rulesPath))) return undefined;\n\n const rules = await loadSkillRules(rulesPath);\n verbose(`Loaded source rules: ${rulesPath}`);\n return rules;\n}\n\n/** Every skill id the shipped catalogue owns — the ids no other marketplace may take. */\nconst CATALOGUE_SKILL_IDS: ReadonlySet<SkillId> = new Set(typedKeys(BUILT_IN_MATRIX.skills));\n\n/** How many colliding ids a refusal lists before summarising the rest. */\nconst MAX_REPORTED_COLLISIONS = 10;\n\n/** Refuses the whole source: colliding ids would silently shadow the catalogue's on disk. */\nasync function refuseCatalogueCollisions(\n basePath: string,\n source: string,\n skills: ExtractedSkillMetadata[],\n): Promise<void> {\n const collidingIds = skills.map((skill) => skill.id).filter((id) => CATALOGUE_SKILL_IDS.has(id));\n if (collidingIds.length === 0) return;\n if (await isPublicCatalogueCheckout(basePath)) return;\n\n throw new Error(catalogueCollisionError(collidingIds, source));\n}\n\nfunction catalogueCollisionError(collidingIds: SkillId[], source: string): string {\n const listed = collidingIds.slice(0, MAX_REPORTED_COLLISIONS).map((id) => ` ${id}`);\n const unlisted = collidingIds.length - listed.length;\n\n return [\n `Marketplace '${source}' ships ${collidingIds.length} skill id(s) the public catalogue ` +\n `already owns:`,\n ...listed,\n ...(unlisted > 0 ? [` ... and ${unlisted} more`] : []),\n `A skill id is the directory the skill installs into, so these would shadow the public ` +\n `catalogue's own skills. Every id must carry its marketplace's name as a namespace — ` +\n `'<marketplace>-<id>'. Rename each skill and the 'name' in its SKILL.md, then re-run ` +\n `'build marketplace', which refuses the same ids before they are published.`,\n ].join(\"\\n\");\n}\n\n/** Built-in stacks stand in for the public catalogue only; others offer their own or none. */\nasync function resolveOfferedStacks(\n basePath: string,\n stacksFile: string | undefined,\n source: string,\n): Promise<Stack[]> {\n const sourceStacks = await loadStacks(basePath, stacksFile);\n if (sourceStacks.length > 0) {\n verbose(`Offering the ${sourceStacks.length} stacks the source ships`);\n return sourceStacks;\n }\n\n if (await offersBuiltInStacks(basePath, source)) {\n verbose(\n `The public catalogue ships no stacks — offering the ${defaultStacks.length} built-in stacks`,\n );\n return defaultStacks;\n }\n\n verbose(`Marketplace '${source}' ships no stacks, and gets no built-in stand-in — offering none`);\n return [];\n}\n\n/** Keys arrive unnarrowed from a stacks file, so `isAgentName` is a real test, not a cast. */\nfunction declaredAgentsIn(stack: Stack): { declared: AgentName[]; undeclared: string[] } {\n const named: string[] = typedKeys<AgentName>(stack.agents);\n return {\n declared: named.filter(isAgentName),\n undeclared: named.filter((name) => !isAgentName(name)),\n };\n}\n\n/** The stack is dropped from, not refused (it is a suggestion), but never silently. */\nfunction undeclaredAgentsWarning(stack: Stack, undeclared: readonly string[]): string {\n const named = undeclared.map((name) => `'${name}'`).join(\", \");\n return (\n `Stack '${stack.id}' names ${undeclared.length} sub-agent(s) this CLI does not define: ` +\n `${named}. Left out of the stack — a sub-agent must be one the CLI ships.`\n );\n}\n\n/** A stack outliving one of its skills is an ordinary authoring mistake, not a corrupt file. */\nfunction withdrawnSkillsWarning(stack: Stack, withdrawn: readonly string[]): string {\n const named = withdrawn.map((id) => `'${id}'`).join(\", \");\n return (\n `Stack '${stack.id}' names ${withdrawn.length} skill(s) this marketplace's catalogue does ` +\n `not carry: ${named}. Left out of the stack — selecting it would install nothing.`\n );\n}\n\nexport function convertStackToResolvedStack(stack: Stack): ResolvedStack {\n const { declared, undeclared } = declaredAgentsIn(stack);\n if (undeclared.length > 0) warn(undeclaredAgentsWarning(stack, undeclared));\n\n const agentConfigs = agentConfigsFor(stack, declared);\n const [allSkillIds, withdrawn] = partition(namedSkillIds(agentConfigs), isInCurrentCatalogue);\n if (withdrawn.length > 0) warn(withdrawnSkillsWarning(stack, withdrawn));\n\n verbose(\n `Stack '${stack.id}' has ${allSkillIds.length} skills from ${agentConfigs.length} agents`,\n );\n\n return {\n id: stack.id,\n name: stack.name,\n description: stack.description,\n skills: skillsByAgent(agentConfigs),\n allSkillIds,\n philosophy: stack.philosophy || \"\",\n };\n}\n\ntype StackAgentEntry = { agentId: AgentName; agentConfig: StackAgentConfig };\n\nfunction agentConfigsFor(stack: Stack, declared: readonly AgentName[]): StackAgentEntry[] {\n return declared.flatMap((agentId) => {\n const agentConfig = stack.agents[agentId];\n return agentConfig ? [{ agentId, agentConfig }] : [];\n });\n}\n\n/** First-seen order. */\nfunction namedSkillIds(agentConfigs: StackAgentEntry[]): SkillId[] {\n return unique(\n agentConfigs.flatMap(({ agentConfig }) =>\n resolveAgentConfigToSkills(agentConfig).map((ref) => ref.id),\n ),\n );\n}\n\n/** The one question a stack's skills are filtered by, for the stack and for each agent's rows. */\nfunction isInCurrentCatalogue(id: SkillId): boolean {\n return id in currentMatrix.skills;\n}\n\nfunction skillsByAgent(agentConfigs: StackAgentEntry[]): ResolvedStack[\"skills\"] {\n return typedFromEntries(\n agentConfigs.map(\n ({ agentId, agentConfig }) => [agentId, resolveStackAgentSkills(agentConfig)] as const,\n ),\n );\n}\n\n/** A category left with no carried skill is dropped. */\nfunction resolveStackAgentSkills(\n agentConfig: Partial<Record<Category, SkillAssignment[]>>,\n): Partial<Record<Category, SkillId[]>> {\n const carriedByCategory = typedEntries<Category, SkillAssignment[]>(agentConfig).map(\n ([category, assignments]) =>\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- Object.entries drops the `| undefined` a Partial<Record> admits\n [category, (assignments ?? []).map((a) => a.id).filter(isInCurrentCatalogue)] as const,\n );\n return typedFromEntries(carriedByCategory.filter(([, ids]) => ids.length > 0));\n}\n\n/** `local` is never a defined category. */\nfunction declaresCategory(matrix: MergedSkillsMatrix, category: CategoryPath): boolean {\n return category !== LOCAL_PSEUDO_CATEGORY && matrix.categories[category] !== undefined;\n}\n\n/**\n * Does not list the categories on offer: there are a hundred, and the picker already shows them.\n */\nfunction undeclaredCategoryRefusal(\n metadata: ExtractedSkillMetadata,\n category: CategoryPath,\n): string {\n const metadataPath = path.join(metadata.path, STANDARD_FILES.METADATA_YAML);\n return (\n `Skipping local skill '${metadata.id}': ${METADATA_KEYS.CATEGORY} '${category}' is not one this ` +\n `installation declares, so the skill belongs in no grid tab and can be given to no sub-agent. ` +\n `Set ${METADATA_KEYS.CATEGORY} in ${metadataPath} to a category that already exists — a skill ` +\n `is placed in the taxonomy, it does not extend it.`\n );\n}\n\nexport function mergeLocalSkillsIntoMatrix(\n matrix: MergedSkillsMatrix,\n localResult: LocalSkillDiscoveryResult,\n): MergedSkillsMatrix {\n for (const metadata of localResult.skills) {\n const existingSkill = matrix.skills[metadata.id];\n\n // An overriding local skill inherits the remote skill's category.\n const category = existingSkill?.category ?? metadata.category;\n\n // A custom skill's category must exist; synthesizing one would fake a placement.\n if (metadata.custom === true && !declaresCategory(matrix, category)) {\n warn(undeclaredCategoryRefusal(metadata, category));\n continue;\n }\n\n const resolvedSkill = toLocalResolvedSkill(metadata, existingSkill, category);\n matrix.skills[metadata.id] = resolvedSkill;\n\n // Completes the slug map over the matrix this merge is building.\n claimSlug(matrix.slugMap, resolvedSkill.slug, metadata.id);\n\n ensureCategoryDefined(matrix, category, metadata.domain);\n\n verbose(`Added local skill: ${metadata.id} (category: ${category})`);\n }\n\n return matrix;\n}\n\n/** An override inherits the source skill's slug, name and relations; a new one has none. */\nfunction toLocalResolvedSkill(\n metadata: ExtractedSkillMetadata,\n existingSkill: ResolvedSkill | undefined,\n category: CategoryPath,\n): ResolvedSkill {\n return {\n id: metadata.id,\n slug: existingSkill?.slug ?? metadata.slug,\n displayName: existingSkill?.displayName ?? metadata.displayName,\n description: metadata.description,\n ...(metadata.activationDescription !== undefined && {\n activationDescription: metadata.activationDescription,\n }),\n ...(metadata.usageGuidance !== undefined && { usageGuidance: metadata.usageGuidance }),\n\n category,\n\n author: LOCAL_DEFAULTS.AUTHOR,\n\n conflictsWith: existingSkill?.conflictsWith ?? [],\n requires: existingSkill?.requires ?? [],\n alternatives: existingSkill?.alternatives ?? [],\n discourages: existingSkill?.discourages ?? [],\n\n path: metadata.path,\n\n local: true,\n ...(metadata.localPath !== undefined && { localPath: metadata.localPath }),\n ...(metadata.custom !== undefined && { custom: metadata.custom }),\n };\n}\n\n/**\n * Synthesizes a definition so config-types generation finds the domain; never judges the category.\n */\nfunction ensureCategoryDefined(\n matrix: MergedSkillsMatrix,\n category: CategoryPath,\n domain: Domain,\n): void {\n if (category === LOCAL_PSEUDO_CATEGORY) return;\n if (matrix.categories[category]) return;\n\n matrix.categories[category] = {\n id: category,\n displayName: category,\n description: `Local skill category`,\n domain,\n exclusive: false,\n order: 0,\n };\n verbose(`Added local category: ${category} (domain: ${domain})`);\n}\n","import fs from \"fs\";\nimport os from \"os\";\n\n/** Compares real paths so a symlinked $HOME matches; plain compare when either cannot resolve. */\nexport function isHomeDirectory(dir: string): boolean {\n try {\n return fs.realpathSync(dir) === fs.realpathSync(os.homedir());\n } catch {\n return dir === os.homedir();\n }\n}\n","import { STANDARD_FILES, STANDARD_DIRS } from \"../consts\";\n\nexport const METADATA_KEYS = {\n DISPLAY_NAME: \"displayName\",\n CLI_DESCRIPTION: \"cliDescription\",\n CATEGORY: \"category\",\n FORKED_FROM: \"forkedFrom\",\n CONTENT_HASH: \"contentHash\",\n USAGE_GUIDANCE: \"usageGuidance\",\n CUSTOM: \"custom\",\n} as const;\n\n/** Forced over whatever the file says: a local skill answers to its machine, not a handle. */\nexport const LOCAL_DEFAULTS = {\n AUTHOR: \"@dummy-author\",\n} as const;\n\nexport const SKILL_CONTENT_FILES = [STANDARD_FILES.SKILL_MD, STANDARD_FILES.REFERENCE_MD] as const;\n\nexport const SKILL_CONTENT_DIRS = [STANDARD_DIRS.EXAMPLES, STANDARD_DIRS.SCRIPTS] as const;\n","import { stripTerminalControls } from \"./string\";\n\n/**\n * Sanitised because parsers quote the offending input into their messages, so an Error from\n * Node can still carry foreign terminal escapes.\n */\nexport function getErrorMessage(error: unknown): string {\n return stripTerminalControls(error instanceof Error ? error.message : String(error));\n}\n","import fs from \"fs-extra\";\nimport fg from \"fast-glob\";\nimport os from \"os\";\nimport path from \"path\";\nimport { PROVIDERS, STANDARD_FILES } from \"../consts\";\nimport { sourceDir } from \"../lib/installation/install-layout.js\";\nimport { bytewise } from \"./string.js\";\n// Private gate module, allowed here by an eslint exception: this is the write choke point.\nimport { assertGateToken } from \"../lib/config-gate/gate-token.js\";\n\n/** Purely lexical: no symlink resolution. */\nexport function isPathWithin(child: string, parent: string): boolean {\n const resolvedChild = path.resolve(child);\n const resolvedParent = path.resolve(parent);\n return resolvedChild === resolvedParent || resolvedChild.startsWith(resolvedParent + path.sep);\n}\n\nexport async function readFile(filePath: string): Promise<string> {\n return fs.readFile(filePath, \"utf-8\");\n}\n\nexport async function readFileSafe(filePath: string, maxSizeBytes: number): Promise<string> {\n const stats = await fs.stat(filePath);\n if (stats.size > maxSizeBytes) {\n throw new Error(\n `File too large: '${filePath}' is ${stats.size} bytes (limit: ${maxSizeBytes} bytes)`,\n );\n }\n return fs.readFile(filePath, \"utf-8\");\n}\n\nexport async function readFileOptional(filePath: string, fallback = \"\"): Promise<string> {\n try {\n return await fs.readFile(filePath, \"utf-8\");\n } catch {\n return fallback;\n }\n}\n\nexport async function fileExists(filePath: string): Promise<boolean> {\n return fs.pathExists(filePath);\n}\n\nexport async function directoryExists(dirPath: string): Promise<boolean> {\n try {\n const stat = await fs.stat(dirPath);\n return stat.isDirectory();\n } catch {\n return false;\n }\n}\n\n/** Asks of the path's last part itself, where `fileExists` and `directoryExists` follow a link. */\nexport async function isSymlink(filePath: string): Promise<boolean> {\n try {\n const entry = await fs.lstat(filePath);\n return entry.isSymbolicLink();\n } catch {\n return false;\n }\n}\n\n/** Sorted bytewise: readdir answers in the file system's order, which differs between runtimes. */\nexport async function listDirectories(dirPath: string): Promise<string[]> {\n try {\n const entries = await fs.readdir(dirPath, { withFileTypes: true });\n return entries\n .filter((e) => e.isDirectory())\n .map((e) => e.name)\n .toSorted(bytewise);\n } catch {\n return [];\n }\n}\n\n/**\n * Sorted bytewise, because fast-glob answers in the order its concurrent directory reads finish,\n * which changes from run to run.\n * @param dot Off for scans; on for reads that must reproduce a directory faithfully.\n */\nexport async function glob(\n pattern: string,\n cwd: string,\n { dot = false }: { dot?: boolean } = {},\n): Promise<string[]> {\n const matches = await fg(pattern, { cwd, onlyFiles: true, dot });\n return matches.toSorted(bytewise);\n}\n\nconst PAIR_HALVES = [STANDARD_FILES.CONFIG_TS, STANDARD_FILES.CONFIG_TYPES_TS];\n\n// Every provider's folder, not just the one in use, so an unexpected write is still caught.\nfunction globalPairFolders(): string[] {\n const home = os.homedir();\n return PROVIDERS.map((provider) => sourceDir(home, provider));\n}\n\nfunction everyGlobalPairPath(): string[] {\n return globalPairFolders().flatMap((folder) =>\n PAIR_HALVES.map((half) => path.join(folder, half)),\n );\n}\n\nexport async function writeFile(filePath: string, content: string): Promise<void> {\n // Runtime tripwire: a global pair write without the gate's token throws. Resolved, so any\n // spelling of the path is caught.\n const resolvedPath = path.resolve(filePath);\n if (everyGlobalPairPath().includes(resolvedPath)) assertGateToken(resolvedPath);\n\n await fs.ensureDir(path.dirname(filePath));\n await fs.writeFile(filePath, content, \"utf-8\");\n}\n\nexport async function ensureDir(dirPath: string): Promise<void> {\n await fs.ensureDir(dirPath);\n}\n\nexport async function remove(filePath: string): Promise<void> {\n await fs.remove(filePath);\n}\n\n/** An unreadable or absent directory counts as empty. */\nexport async function isDirectoryEmpty(dirPath: string): Promise<boolean> {\n try {\n const entries = await fs.readdir(dirPath);\n return entries.length === 0;\n } catch {\n return true;\n }\n}\n\n/** Filesystem emptiness, not roster emptiness: any user-owned file keeps the directory. */\nexport async function removeDirIfEmpty(dir: string): Promise<boolean> {\n if (!(await directoryExists(dir))) return false;\n if (!(await isDirectoryEmpty(dir))) return false;\n await remove(dir);\n return true;\n}\n\n/**\n * Adds the owner's write bit after copying (mode otherwise preserved), so an ejected copy\n * from a read-only source stays editable.\n */\nexport async function copy(src: string, dest: string): Promise<void> {\n await fs.copy(src, dest);\n await grantOwnerWrite(dest);\n}\n\nconst OWNER_WRITE = 0o200;\n\nasync function grantOwnerWrite(target: string): Promise<void> {\n const entry = await fs.stat(target);\n await fs.chmod(target, entry.mode | OWNER_WRITE);\n\n if (!entry.isDirectory()) return;\n\n const children = await fs.readdir(target);\n await Promise.all(children.map((child) => grantOwnerWrite(path.join(target, child))));\n}\n","import fs from \"fs\";\nimport os from \"os\";\nimport path from \"path\";\n\nimport {\n compilesForCodex,\n hasCodexRoleMarker,\n hasProvenanceMarker,\n} from \"@workspace/compile/agent-source\";\n\nimport {\n CLAUDE_DIR,\n PLUGINS_SUBDIR,\n PROVIDERS,\n SOURCE_ROOT_DIR,\n sourceDirName,\n STANDARD_DIRS,\n STANDARD_FILES,\n type Provider,\n} from \"../../consts.js\";\nimport type { AgentName } from \"../../types/agents.js\";\nimport type { SkillScope } from \"../../types/config.js\";\n\n/**\n * Where each (provider, scope) keeps its agents-inc source (`.agents-inc/<provider>/`) and the\n * host directories it writes into.\n */\n\nexport type SourceFolder = {\n dir: string;\n /** As a user writes it: `.agents-inc/claude`. */\n relName: string;\n};\n\nexport function sourceDir(root: string, provider: Provider): string {\n return path.join(root, SOURCE_ROOT_DIR, provider);\n}\n\nexport type SourceRoot = {\n dir: string;\n relName: string;\n};\n\nexport function sourceRootOf(root: string): SourceRoot {\n return { dir: path.join(root, SOURCE_ROOT_DIR), relName: SOURCE_ROOT_DIR };\n}\n\nexport const RETIRED_SOURCE_FOLDER = \".claude-src\";\n\n/**\n * Where the retired folder's contents belong now when any root holds it, else `null`. The folder\n * was Claude's, so the answer is Claude's.\n */\nexport function retiredSourceFolderIn(roots: readonly string[]): string | null {\n if (!roots.some(holdsTheRetiredSourceFolder)) return null;\n return sourceDirName(\"claude\");\n}\n\nfunction holdsTheRetiredSourceFolder(root: string): boolean {\n return directoryExists(path.join(root, RETIRED_SOURCE_FOLDER));\n}\n\n/** Reachable only through {@link providerInUse}, so no call site defaults a provider silently. */\nconst PROVIDER_OF_A_NEW_INSTALLATION: Provider = \"claude\";\n\n/**\n * The provider `--provider` named for this run. Process state rather than a parameter because\n * path builders deep below the command must all see it; set before any path is read, never after.\n */\nlet providerChosenForThisRun: Provider | undefined;\n\nexport function chooseProviderForThisRun(provider: Provider): void {\n providerChosenForThisRun = provider;\n}\n\n/** For test processes that outlive one run. */\nexport function forgetTheProviderChosenForThisRun(): void {\n providerChosenForThisRun = undefined;\n}\n\n/**\n * The provider a run over `root` is about: the run's `--provider` if given, else read off the\n * disk (a folder holding `config.ts` beats a merely non-empty one; an empty folder decides\n * nothing). A root holding live installations of both providers answers by roster order.\n */\nexport function providerInUse(root: string | undefined): Provider {\n if (providerChosenForThisRun !== undefined) return providerChosenForThisRun;\n if (root === undefined) return PROVIDER_OF_A_NEW_INSTALLATION;\n return providerOnDisk(root);\n}\n\nfunction providerOnDisk(root: string): Provider {\n const live = PROVIDERS.find((provider) => holdsAnInstallation(root, provider));\n if (live !== undefined) return live;\n\n const started = PROVIDERS.find((provider) => holdsASourceFolder(root, provider));\n return started ?? PROVIDER_OF_A_NEW_INSTALLATION;\n}\n\nfunction holdsAnInstallation(root: string, provider: Provider): boolean {\n return holdsAConfig(sourceDir(root, provider));\n}\n\nfunction holdsASourceFolder(root: string, provider: Provider): boolean {\n return holdsAnything(sourceDir(root, provider));\n}\n\nexport function sourceFolderInUse(root: string, provider: Provider): SourceFolder {\n return { dir: sourceDir(root, provider), relName: sourceDirName(provider) };\n}\n\n/** `.agents-inc/<provider>/config.ts`, relative to the scope root. */\nexport function relativeConfigPath(root: string, provider: Provider): string {\n return `${sourceFolderInUse(root, provider).relName}/${STANDARD_FILES.CONFIG_TS}`;\n}\n\n/** With no project, names the folder a new installation would be created in. */\nexport function sourceFolderName(root: string | undefined, provider: Provider): string {\n if (root === undefined) return sourceDirName(provider);\n return sourceFolderInUse(root, provider).relName;\n}\n\n/**\n * Home for `\"global\"`, the project otherwise. `os.homedir()` is read at call time so tests that\n * repoint HOME are honoured. Declared here (not `install-base-dir.ts`) to avoid an import cycle.\n */\nexport function installBaseDir(projectDir: string, scope: SkillScope | undefined): string {\n return scope === \"global\" ? os.homedir() : projectDir;\n}\n\nconst CODEX_DIR = \".codex\";\n\n/** Exported so `e2e-runner-environment.test.ts` imports the name rather than restating it. */\nexport const CODEX_HOME_VAR = \"CODEX_HOME\";\n\n/** Committed to the repository, which is why it is not under `.codex/`. */\nconst CODEX_PROJECT_SKILLS_PATH = \".agents/skills\";\n\nconst CODEX_CONFIG_FILE = \"config.toml\";\n\n/** Claude Code's own state file; only ever read by this CLI. */\nconst CLAUDE_STATE_FILE = \".claude.json\";\n\n/** Exported for `e2e-runner-environment.test.ts`, as {@link CODEX_HOME_VAR} is. */\nexport const CLAUDE_CONFIG_DIR_VAR = \"CLAUDE_CONFIG_DIR\";\n\nexport const INSTALLED_PLUGINS_FILE = \"installed_plugins.json\";\n\n/**\n * Where one (provider, scope) puts everything the host reads. `null` is a role the host does not\n * have at that scope.\n */\ntype HostRoles = {\n userConfigRoot: string;\n agentsDir: string;\n skillsDir: string;\n pluginsDir: string | null;\n pluginRegistry: string | null;\n permissionFiles: string[];\n};\n\nfunction hostRoles(provider: Provider, scope: SkillScope, projectDir: string): HostRoles {\n switch (provider) {\n case \"claude\":\n return claudeRoles(installBaseDir(projectDir, scope));\n case \"codex\":\n return scope === \"global\" ? codexGlobalRoles() : codexProjectRoles(projectDir);\n default: {\n const _exhaustive: never = provider;\n return _exhaustive;\n }\n }\n}\n\nfunction claudeRoles(scopeRoot: string): HostRoles {\n const root = path.join(scopeRoot, CLAUDE_DIR);\n const plugins = path.join(root, PLUGINS_SUBDIR);\n\n return {\n userConfigRoot: root,\n agentsDir: path.join(root, STANDARD_DIRS.AGENTS),\n skillsDir: path.join(root, STANDARD_DIRS.SKILLS),\n pluginsDir: plugins,\n pluginRegistry: path.join(plugins, INSTALLED_PLUGINS_FILE),\n // The developer's local overlay is read too, though never written.\n permissionFiles: [\n path.join(root, STANDARD_FILES.SETTINGS_JSON),\n path.join(root, STANDARD_FILES.SETTINGS_LOCAL_JSON),\n ],\n };\n}\n\n/** Codex records installed plugins in `config.toml`, so there is no registry file. */\nfunction codexGlobalRoles(): HostRoles {\n const root = codexUserRoot();\n\n return {\n userConfigRoot: root,\n agentsDir: path.join(root, STANDARD_DIRS.AGENTS),\n skillsDir: path.join(root, STANDARD_DIRS.SKILLS),\n pluginsDir: path.join(root, PLUGINS_SUBDIR),\n pluginRegistry: null,\n permissionFiles: [path.join(root, CODEX_CONFIG_FILE)],\n };\n}\n\n/**\n * Codex reads `<project>/.codex/agents/` only while the GLOBAL `$CODEX_HOME/config.toml` marks\n * this exact path `trust_level = \"trusted\"`, and silently ignores it otherwise. Codex installs\n * plugins per machine, so there is no project plugins dir. `$CODEX_HOME` does not apply here.\n */\nfunction codexProjectRoles(projectDir: string): HostRoles {\n const root = path.join(projectDir, CODEX_DIR);\n\n return {\n userConfigRoot: root,\n agentsDir: path.join(root, STANDARD_DIRS.AGENTS),\n skillsDir: path.join(projectDir, CODEX_PROJECT_SKILLS_PATH),\n pluginsDir: null,\n pluginRegistry: null,\n permissionFiles: [path.join(root, CODEX_CONFIG_FILE)],\n };\n}\n\n/** `$CODEX_HOME` or `~/.codex`, read at call time. */\nfunction codexUserRoot(): string {\n return relocatedTo(process.env[CODEX_HOME_VAR]) ?? path.join(os.homedir(), CODEX_DIR);\n}\n\n/**\n * Empty counts as unset, since `path.join(\"\", ...)` would root every path at the cwd. Takes the\n * value, not the name, so every read still names its variable where the environment gate looks.\n */\nfunction relocatedTo(variableValue: string | undefined): string | undefined {\n return variableValue === \"\" ? undefined : variableValue;\n}\n\n/** The global Codex config, which decides whether a project's role files are read at all. */\nexport function codexGlobalConfigFile(): string {\n return path.join(codexUserRoot(), CODEX_CONFIG_FILE);\n}\n\n/**\n * Where Claude Code records `projects[<path>].hasTrustDialogAccepted`; a project sub-agent's\n * frontmatter hooks are dropped until it is `true`. Read, never written.\n */\nexport function claudeStateFile(): string {\n return path.join(claudeStateRoot(), CLAUDE_STATE_FILE);\n}\n\n/** `$CLAUDE_CONFIG_DIR` or home, read at call time. */\nfunction claudeStateRoot(): string {\n return relocatedTo(process.env[CLAUDE_CONFIG_DIR_VAR]) ?? os.homedir();\n}\n\nexport function userConfigRoot(provider: Provider, scope: SkillScope, projectDir: string): string {\n return hostRoles(provider, scope, projectDir).userConfigRoot;\n}\n\n/** Where a role file goes, not a promise the host reads it — see {@link codexProjectRoles}. */\nexport function agentsDir(provider: Provider, scope: SkillScope, projectDir: string): string {\n return hostRoles(provider, scope, projectDir).agentsDir;\n}\n\n/** Where this host reads skills that are copied in rather than installed as a plugin. */\nexport function skillsDir(provider: Provider, scope: SkillScope, projectDir: string): string {\n return hostRoles(provider, scope, projectDir).skillsDir;\n}\n\nexport function pluginsDir(\n provider: Provider,\n scope: SkillScope,\n projectDir: string,\n): string | null {\n return hostRoles(provider, scope, projectDir).pluginsDir;\n}\n\nexport function pluginRegistry(\n provider: Provider,\n scope: SkillScope,\n projectDir: string,\n): string | null {\n return hostRoles(provider, scope, projectDir).pluginRegistry;\n}\n\n/** In precedence order. */\nexport function permissionFiles(\n provider: Provider,\n scope: SkillScope,\n projectDir: string,\n): string[] {\n return hostRoles(provider, scope, projectDir).permissionFiles;\n}\n\n/**\n * The skills directory relative to the scope root (`.claude/skills`, `.agents/skills`), or the\n * absolute path where it sits outside it (a relocated `$CODEX_HOME`).\n */\nexport function skillsPathPrefix(\n provider: Provider,\n scope: SkillScope,\n projectDir: string,\n): string {\n const skills = skillsDir(provider, scope, projectDir);\n const fromScopeRoot = pathUnder(installBaseDir(projectDir, scope), skills);\n\n return fromScopeRoot ?? skills;\n}\n\n/**\n * The roots that say which provider an installation belongs to — not a list of directories safe\n * to remove.\n */\nexport function ownedRoots(provider: Provider, scope: SkillScope, projectDir: string): string[] {\n const host = userConfigRoot(provider, scope, projectDir);\n const skills = skillsDir(provider, scope, projectDir);\n const source = sourceFolderInUse(installBaseDir(projectDir, scope), provider).dir;\n\n return [host, ...(isUnder(host, skills) ? [] : [skills]), source];\n}\n\n/** `dir` relative to `root`, POSIX-separated, or `null` where it is not under it. */\nfunction pathUnder(root: string, dir: string): string | null {\n const relative = path.relative(root, dir);\n const escapes = relative === \"..\" || relative.startsWith(`..${path.sep}`);\n\n if (relative === \"\" || escapes || path.isAbsolute(relative)) return null;\n return relative.split(path.sep).join(\"/\");\n}\n\n/** A root does not count as being under itself. */\nfunction isUnder(root: string, dir: string): boolean {\n return pathUnder(root, dir) !== null;\n}\n\nexport type AgentCodec = {\n extension: string;\n listGlob: string;\n /**\n * Whether this CLI compiled the content. Claude carries the marker as the first body line, Codex\n * as the first line of `developer_instructions`; a marker quoted elsewhere does not count.\n */\n hasMarker: (content: string) => boolean;\n};\n\n/** Fresh per call so no caller shares another's object. */\nexport function agentCodec(provider: Provider): AgentCodec {\n switch (provider) {\n case \"claude\":\n return agentFormat(\".md\", hasProvenanceMarker);\n case \"codex\":\n return agentFormat(\".toml\", hasCodexRoleMarker);\n default: {\n const _exhaustive: never = provider;\n return _exhaustive;\n }\n }\n}\n\nfunction agentFormat(extension: string, hasMarker: (content: string) => boolean): AgentCodec {\n return { extension, listGlob: `*${extension}`, hasMarker };\n}\n\nexport function hostCompilesAgent(provider: Provider, agent: AgentName): boolean {\n switch (provider) {\n case \"claude\":\n return true;\n case \"codex\":\n return compilesForCodex(agent);\n default: {\n const _exhaustive: never = provider;\n return _exhaustive;\n }\n }\n}\n\n/** Claude Code's `settings.json` advice; nothing is known to say for Codex. */\nexport function advisesOnPermissions(provider: Provider): boolean {\n switch (provider) {\n case \"claude\":\n return true;\n case \"codex\":\n return false;\n default: {\n const _exhaustive: never = provider;\n return _exhaustive;\n }\n }\n}\n\n/**\n * The probes below never throw: a fault such as EACCES points the CLI at the folder anyway, so the\n * later read or write there fails naming the real file.\n */\nfunction holdsAConfig(dir: string): boolean {\n return fs.existsSync(path.join(dir, STANDARD_FILES.CONFIG_TS));\n}\n\nfunction holdsAnything(dir: string): boolean {\n return directoryExists(dir) && isNotEmpty(dir);\n}\n\n/** An unlistable directory counts as non-empty, so a locked installation keeps its folder. */\nfunction isNotEmpty(dir: string): boolean {\n try {\n return fs.readdirSync(dir).length > 0;\n } catch {\n return true;\n }\n}\n\nfunction directoryExists(dir: string): boolean {\n try {\n return fs.statSync(dir, { throwIfNoEntry: false })?.isDirectory() ?? false;\n } catch {\n return false;\n }\n}\n","import type { AgentConfig, EffortLevel } from \"../../types.js\"\n\n/**\n * Codex's deserializer drops a whole role file for one unlisted key, so only accepted keys are\n * written; fields with no Codex expression are reported once by `./roster`.\n */\n\nexport const CODEX_REQUIRED_ROLE_KEYS = [\n \"name\",\n \"description\",\n \"developer_instructions\",\n] as const\n\nexport const CODEX_REJECTED_ROLE_KEYS = [\n \"reasoning_effort\",\n \"effort\",\n \"disallowed_tools\",\n \"tools\",\n \"permissionMode\",\n \"isolation\",\n \"experimental\",\n] as const\n\n/** The tool whose absence is the one per-agent limit Codex CAN express. */\nconst SHELL_TOOL = \"Bash\"\n\n/** `body` is the frontmatter-free render and becomes `developer_instructions` whole. */\nexport function renderAgentRoleToml(agent: AgentConfig, body: string): string {\n refuseBlankInstructions(agent.name, body)\n\n return [\n ...scalarLines(agent, body),\n // Last: every bare key after a table header belongs to that table.\n ...shellToolTable(agent),\n ].join(\"\\n\")\n}\n\n/** Exported so `hasCodexRoleMarker` in `../../agent-source.ts` finds the marker line after it. */\nexport const CODEX_DEVELOPER_INSTRUCTIONS_OPENER = `developer_instructions = \"\"\"`\n\n/** `effort = \"high\"` drops the file; this key registers. */\nconst CODEX_EFFORT_KEY = \"model_reasoning_effort\"\n\n/**\n * A pinned role with no effort inherits the parent's, which a small model may refuse at spawn.\n * Every offered Codex model accepts `medium`.\n */\nconst PINNED_MODEL_RESTING_EFFORT: EffortLevel = \"medium\"\n\nfunction scalarLines(agent: AgentConfig, body: string): string[] {\n return [\n `name = ${basicString(agent.name)}`,\n `description = ${basicString(agent.description)}`,\n ...modelLines(agent),\n developerInstructions(body),\n ]\n}\n\n// `agent.model` is a Claude selector and is never written: Codex cannot spawn a role naming one.\nfunction modelLines(agent: AgentConfig): string[] {\n if (agent.codexModel === undefined) {\n return agent.effort === undefined ? [] : [effortLine(agent.effort)]\n }\n\n return [\n `model = ${basicString(agent.codexModel)}`,\n effortLine(agent.effort ?? PINNED_MODEL_RESTING_EFFORT),\n ]\n}\n\nfunction effortLine(effort: EffortLevel): string {\n return `${CODEX_EFFORT_KEY} = ${basicString(effort)}`\n}\n\n/** TOML discards the opening delimiter's own newline. */\nfunction developerInstructions(body: string): string {\n return `${CODEX_DEVELOPER_INSTRUCTIONS_OPENER}\\n${asMultilineString(body)}\\n\"\"\"`\n}\n\nfunction shellToolTable(agent: AgentConfig): string[] {\n if (agent.tools.includes(SHELL_TOOL)) return []\n return [\"\", \"[features]\", \"shell_tool = false\"]\n}\n\n/** Codex drops a role whose `developer_instructions` is blank, so it is refused here instead. */\nfunction refuseBlankInstructions(name: string, body: string): void {\n if (body.trim() !== \"\") return\n throw new Error(\n `Cannot write a Codex agent role for \"${name}\": its compiled body is empty, and Codex refuses a blank developer_instructions.`\n )\n}\n\n// Read off the codepoint: a regex would need control characters in a class (`no-control-regex`).\nfunction isForbiddenRaw(codepoint: number): boolean {\n if (codepoint === 0x7f) return true\n if (codepoint <= 0x08) return true\n return codepoint >= 0x0b && codepoint <= 0x1f\n}\n\nconst A_CLOSING_DELIMITER = /\"{3,}/g\n\nconst EVERY_BACKSLASH = /\\\\/g\nconst EVERY_QUOTE = /\"/g\n\n/** A trailing backslash is TOML's line continuation and would eat a newline. */\nfunction escapeBackslashes(text: string): string {\n return text.replace(EVERY_BACKSLASH, \"\\\\\\\\\")\n}\n\nfunction escapeQuotes(text: string): string {\n return text.replace(EVERY_QUOTE, '\\\\\"')\n}\n\nfunction escapeClosingDelimiters(text: string): string {\n return text.replace(A_CLOSING_DELIMITER, (quotes) => escapeQuotes(quotes))\n}\n\nfunction escapeControlCharacters(text: string): string {\n return [...text].map(escapedWhereTomlRefusesItRaw).join(\"\")\n}\n\nfunction escapedWhereTomlRefusesItRaw(character: string): string {\n const codepoint = character.charCodeAt(0)\n if (!isForbiddenRaw(codepoint)) return character\n\n return `\\\\u${codepoint.toString(16).padStart(4, \"0\")}`\n}\n\nfunction basicString(value: string): string {\n const literalBackslashes = escapeBackslashes(value)\n const literalQuotes = escapeQuotes(literalBackslashes)\n const onOneLine = literalQuotes.replace(/\\n/g, \"\\\\n\").replace(/\\t/g, \"\\\\t\")\n\n return `\"${escapeControlCharacters(onOneLine)}\"`\n}\n\n/** Escapes only what would end the string early, so the markdown stays readable. */\nfunction asMultilineString(body: string): string {\n const literalBackslashes = escapeBackslashes(body)\n const safeDelimiters = escapeClosingDelimiters(literalBackslashes)\n\n return escapeControlCharacters(safeDelimiters)\n}\n","import { AGENT_NAMES } from \"@workspace/matrix\"\n\nimport { inAnEnglishList } from \"../../string.js\"\nimport type { AgentName } from \"../../types.js\"\n\n// Two separate lines: absent sub-agents, and unexpressible settings of present ones.\n\n/**\n * Left out of every Codex install for v1 because their roster mechanics on Codex are not proven.\n * Not a capability claim: both compile as roles.\n */\nexport const AGENTS_NOT_ON_CODEX = [\n \"agent-summoner\",\n \"skill-summoner\",\n] as const satisfies readonly AgentName[]\n\nconst leftOut: ReadonlySet<AgentName> = new Set(AGENTS_NOT_ON_CODEX)\n\nexport function compilesForCodex(agent: AgentName): boolean {\n return !leftOut.has(agent)\n}\n\nexport const CODEX_AGENT_ROSTER: readonly AgentName[] =\n AGENT_NAMES.filter(compilesForCodex)\n\n/** Reported because a user-authored agent setting one would otherwise lose it silently. */\nexport const UNEXPRESSIBLE_ON_CODEX = [\n \"Claude models\",\n \"tool allowlists\",\n \"permissionMode\",\n \"isolation\",\n \"experimental\",\n \"preloaded skills\",\n] as const\n\nexport function agentsLeftOutOfCodexMessage(): string {\n return (\n `Codex compiles ${CODEX_AGENT_ROSTER.length} of the ${AGENT_NAMES.length} sub-agents: ` +\n `${inAnEnglishList(AGENTS_NOT_ON_CODEX)} are left out for v1, because their roster ` +\n `mechanics on Codex are not proven.`\n )\n}\n\nexport function unexpressibleOnCodexMessage(): string {\n return (\n `Codex cannot express ${inAnEnglishList(UNEXPRESSIBLE_ON_CODEX)}, ` +\n `so the agent role files it wrote carry none of them.`\n )\n}\n","import type { AgentHookDefinition } from \"@workspace/matrix\"\nimport type { Liquid } from \"liquidjs\"\n\nimport { diagnostics } from \"./diagnostics.js\"\nimport { DEFAULT_PLUGIN_NAME, EJECT_SOURCE } from \"./paths.js\"\nimport { CODEX_DEVELOPER_INSTRUCTIONS_OPENER } from \"./providers/codex/agent-role-toml.js\"\nimport type {\n AgentConfig,\n CompiledAgentData,\n PluginSkillRef,\n Skill,\n} from \"./types.js\"\n\n// Turns a resolved sub-agent into installed markdown; file reads and the CLI version arrive as\n// data so a browser can render the same bytes. Codex is re-exported because `providers/codex/`\n// has no `exports` entry.\nexport {\n CODEX_DEVELOPER_INSTRUCTIONS_OPENER,\n CODEX_REJECTED_ROLE_KEYS,\n CODEX_REQUIRED_ROLE_KEYS,\n renderAgentRoleToml,\n} from \"./providers/codex/agent-role-toml.js\"\nexport {\n AGENTS_NOT_ON_CODEX,\n CODEX_AGENT_ROSTER,\n UNEXPRESSIBLE_ON_CODEX,\n agentsLeftOutOfCodexMessage,\n compilesForCodex,\n unexpressibleOnCodexMessage,\n} from \"./providers/codex/roster.js\"\n\nconst LIQUID_SYNTAX_PATTERN = /\\{\\{|\\}\\}|\\{%|%\\}/g\n\n/** Strips Liquid delimiters from author-supplied metadata to prevent template injection. */\nexport function sanitizeLiquidSyntax<T extends string>(\n value: T,\n fieldName: string\n): T {\n if (!LIQUID_SYNTAX_PATTERN.test(value)) return value\n LIQUID_SYNTAX_PATTERN.lastIndex = 0\n const sanitized = value.replace(LIQUID_SYNTAX_PATTERN, \"\")\n diagnostics().warn(\n `Stripped Liquid template syntax from '${fieldName}' — possible template injection attempt`\n )\n // Boundary cast: .replace() widens the branded T; stripping characters keeps it in T's domain.\n return sanitized as T\n}\n\nfunction sanitizeStringArray(values: string[], fieldName: string): string[] {\n return values.map((v) => sanitizeLiquidSyntax(v, fieldName))\n}\n\n/** Hook strings render into an executable (a `Stop` hook's command), so they are sanitised. */\nfunction sanitizeHooks(\n hooks: NonNullable<AgentConfig[\"hooks\"]>\n): NonNullable<AgentConfig[\"hooks\"]> {\n return Object.fromEntries(\n Object.entries(hooks).map(([event, definitions]) => [\n sanitizeLiquidSyntax(event, \"hook.event\"),\n definitions.map(sanitizeHookDefinition),\n ])\n )\n}\n\nfunction sanitizeHookDefinition(\n definition: AgentHookDefinition\n): AgentHookDefinition {\n return {\n ...definition,\n ...(definition.matcher !== undefined && {\n matcher: sanitizeLiquidSyntax(definition.matcher, \"hook.matcher\"),\n }),\n hooks: definition.hooks.map(sanitizeHookAction),\n }\n}\n\nfunction sanitizeHookAction(\n action: AgentHookDefinition[\"hooks\"][number]\n): AgentHookDefinition[\"hooks\"][number] {\n return {\n ...action,\n type: sanitizeLiquidSyntax(action.type, \"hook.type\"),\n ...(action.command !== undefined && {\n command: sanitizeLiquidSyntax(action.command, \"hook.command\"),\n }),\n ...(action.script !== undefined && {\n script: sanitizeLiquidSyntax(action.script, \"hook.script\"),\n }),\n ...(action.prompt !== undefined && {\n prompt: sanitizeLiquidSyntax(action.prompt, \"hook.prompt\"),\n }),\n }\n}\n\n// Rendered fields are sanitised even when closed vocabularies: the editor preview reaches here\n// unparsed.\nfunction sanitizeExperimental(\n experimental: NonNullable<AgentConfig[\"experimental\"]>\n): NonNullable<AgentConfig[\"experimental\"]> {\n return {\n ...experimental,\n ...(experimental.cacheTtl !== undefined && {\n cacheTtl: sanitizeLiquidSyntax(\n experimental.cacheTtl,\n \"agent.experimental.cacheTtl\"\n ),\n }),\n }\n}\n\nfunction sanitizeSkills(skills: Skill[]): Skill[] {\n return skills.map((s) => ({\n ...s,\n id: sanitizeLiquidSyntax(s.id, \"skill.id\"),\n description: sanitizeLiquidSyntax(s.description, \"skill.description\"),\n usage: sanitizeLiquidSyntax(s.usage, \"skill.usage\"),\n ...(s.pluginRef !== undefined && {\n pluginRef: sanitizeLiquidSyntax(s.pluginRef, \"skill.pluginRef\"),\n }),\n }))\n}\n\n/**\n * Strips Liquid delimiters from agent and skill metadata. The five prose partials pass through\n * unchanged: they are inlined verbatim, never evaluated (see {@link SOURCE_FOLDER_PLACEHOLDER}).\n */\nexport function sanitizeCompiledAgentData(\n data: CompiledAgentData\n): CompiledAgentData {\n return {\n agent: sanitizeAgent(data.agent),\n identity: data.identity,\n playbook: data.playbook,\n output: data.output,\n criticalRequirementsTop: data.criticalRequirementsTop,\n criticalReminders: data.criticalReminders,\n skills: sanitizeSkills(data.skills),\n preloadedSkills: sanitizeSkills(data.preloadedSkills),\n dynamicSkills: sanitizeSkills(data.dynamicSkills),\n preloadedSkillIds: data.preloadedSkillIds.map((id) =>\n sanitizeLiquidSyntax(id, \"preloadedSkillId\")\n ),\n }\n}\n\nfunction sanitizeAgent(agent: AgentConfig): AgentConfig {\n return {\n ...agent,\n name: sanitizeLiquidSyntax(agent.name, \"agent.name\"),\n title: sanitizeLiquidSyntax(agent.title, \"agent.title\"),\n description: sanitizeLiquidSyntax(agent.description, \"agent.description\"),\n tools: sanitizeStringArray(agent.tools, \"agent.tools\"),\n ...(agent.disallowedTools !== undefined && {\n disallowedTools: sanitizeStringArray(\n agent.disallowedTools,\n \"agent.disallowedTools\"\n ),\n }),\n ...(agent.model !== undefined && {\n model: sanitizeLiquidSyntax(agent.model, \"agent.model\"),\n }),\n ...(agent.effort !== undefined && {\n effort: sanitizeLiquidSyntax(agent.effort, \"agent.effort\"),\n }),\n ...(agent.permissionMode !== undefined && {\n permissionMode: sanitizeLiquidSyntax(\n agent.permissionMode,\n \"agent.permissionMode\"\n ),\n }),\n ...(agent.isolation !== undefined && {\n isolation: sanitizeLiquidSyntax(agent.isolation, \"agent.isolation\"),\n }),\n ...(agent.experimental !== undefined && {\n experimental: sanitizeExperimental(agent.experimental),\n }),\n ...(agent.hooks !== undefined && {\n hooks: sanitizeHooks(agent.hooks),\n }),\n }\n}\n\n/**\n * `tools:` is an allowlist and `skills:` grants no tool, so without this an agent cannot load a\n * skill. Granted to every agent: it is read-only.\n */\nconst SKILL_TOOL = \"Skill\"\n\n// Idempotent and order-stable, so recompiles do not diff frontmatter.\nfunction withSkillTool(agent: AgentConfig): AgentConfig {\n if (agent.tools.includes(SKILL_TOOL)) return agent\n return { ...agent, tools: [...agent.tools, SKILL_TOOL] }\n}\n\nexport type AgentFiles = Pick<\n CompiledAgentData,\n | \"identity\"\n | \"playbook\"\n | \"output\"\n | \"criticalRequirementsTop\"\n | \"criticalReminders\"\n>\n\n/**\n * The one assembly point for CLI writes and the editor preview, so user-authored agents get the\n * Skill grant too. Preserves `agent.skills` order, which decides the activation table's rows.\n */\nexport function buildAgentTemplateContext(\n name: string,\n agent: AgentConfig,\n files: AgentFiles,\n mapSkill: (skill: Skill) => Skill = (skill) => skill\n): CompiledAgentData {\n const skills = agent.skills.map(mapSkill)\n const preloadedSkills = skills.filter((s) => s.preloaded)\n const dynamicSkills = skills.filter((s) => !s.preloaded)\n const preloadedSkillIds = preloadedSkills.map((s) => s.pluginRef ?? s.id)\n\n diagnostics().verbose(\n `Skills for ${name}: ${preloadedSkills.length} preloaded, ${dynamicSkills.length} dynamic`\n )\n\n return {\n agent: withSkillTool(agent),\n ...files,\n skills,\n preloadedSkills,\n dynamicSkills,\n preloadedSkillIds,\n }\n}\n\n/** `${id}:${id}` only for a skill with an explicit non-eject source (a marketplace install). */\nexport function pluginRefFor(skill: Skill): { pluginRef?: PluginSkillRef } {\n if (skill.source === undefined || skill.source === EJECT_SOURCE) return {}\n return { pluginRef: `${skill.id}:${skill.id}` as const }\n}\n\n/**\n * A body comment, not a frontmatter field: Claude Code may reject unknown keys. Its bytes stay\n * constant across releases because it is the first cacheable byte of every sub-agent prompt; the\n * version goes in the trailing volatile block.\n */\nconst MARKER_OPEN = `<!-- Generated by ${DEFAULT_PLUGIN_NAME}`\nconst MARKER_NOTICE = \" — do not edit; compile rewrites this file\"\nconst MARKER_CLOSE = \" -->\"\n\nconst FRONTMATTER_FENCE = \"---\"\n\nexport function provenanceMarker(): string {\n return `${MARKER_OPEN}${MARKER_NOTICE}${MARKER_CLOSE}`\n}\n\nfunction isProvenanceMarker(line: string): boolean {\n return line.startsWith(MARKER_OPEN) && line.endsWith(MARKER_CLOSE)\n}\n\n// Top of file when there is no frontmatter (a template override may render none).\nfunction bodyStartIndex(lines: readonly string[]): number {\n if (lines[0] !== FRONTMATTER_FENCE) return 0\n const closingFence = lines.indexOf(FRONTMATTER_FENCE, 1)\n if (closingFence === -1) return 0\n return closingFence + 1\n}\n\n/** Position is part of the claim: a marker quoted further down belongs to the user's file. */\nexport function hasProvenanceMarker(content: string): boolean {\n const lines = content.split(\"\\n\")\n const firstBodyLine = lines[bodyStartIndex(lines)]\n return firstBodyLine !== undefined && isProvenanceMarker(firstBodyLine)\n}\n\n/** {@link hasProvenanceMarker} for a Codex role: the marker sits right after the TOML opener. */\nexport function hasCodexRoleMarker(content: string): boolean {\n const lines = content.split(\"\\n\")\n const opener = lines.indexOf(CODEX_DEVELOPER_INSTRUCTIONS_OPENER)\n const markerLine = opener === -1 ? undefined : lines[opener + 1]\n\n return markerLine !== undefined && isProvenanceMarker(markerLine)\n}\n\n/** Replaces an existing marker rather than stacking a second, upgrading older stamps. */\nexport function stampProvenanceMarker(content: string): string {\n const lines = content.split(\"\\n\")\n const bodyStart = bodyStartIndex(lines)\n const replacedLines = hasProvenanceMarker(content) ? 1 : 0\n\n return [\n ...lines.slice(0, bodyStart),\n provenanceMarker(),\n ...lines.slice(bodyStart + replacedLines),\n ].join(\"\\n\")\n}\n\nconst AGENT_TEMPLATE = \"agent\"\n\n/**\n * The body after the frontmatter, which {@link AGENT_TEMPLATE} `{% include %}`s last; Codex roles\n * need it alone. `include` shares the parent's scope, and an ejected pre-split `agent.liquid` still\n * renders through its own copy.\n */\nconst AGENT_BODY_TEMPLATE = \"agent-body\"\n\n/**\n * The one substituted token in a partial: the install's source folder, which differs per provider.\n * Partials are otherwise prose, never rendered, so a partial without the token is returned by\n * identity. Find users with `grep -rn '@@SOURCE_FOLDER@@' packages/cli/src/agents`.\n */\nconst SOURCE_FOLDER_PLACEHOLDER = \"@@SOURCE_FOLDER@@\"\n\n/**\n * Compiles to the token itself, so a partial can name it. The backslash is stripped from the text\n * around it, so `\\\\` before the token yields a backslash and the token.\n */\nconst SOURCE_FOLDER_ESCAPE = `\\\\${SOURCE_FOLDER_PLACEHOLDER}`\n\n// The only string ever handed to the engine here; both engine builders set `sourceFolder`.\nconst SOURCE_FOLDER_EXPRESSION = \"{{ sourceFolder }}\"\n\nconst NO_SOURCE_FOLDER =\n `A partial names the install's source folder (${SOURCE_FOLDER_PLACEHOLDER}) and the engine ` +\n `rendering it carries no 'sourceFolder' global, so the name would compile away to nothing.`\n\nfunction sourceFolderOf(engine: Liquid): Promise<string> {\n // Boundary cast: liquidjs types parseAndRender as `Promise<any>`; this global is a `string`.\n return engine.parseAndRender(SOURCE_FOLDER_EXPRESSION) as Promise<string>\n}\n\n/**\n * Asking for the folder with none set throws: `strictVariables` is off, so it would compile to an\n * empty path. Merely naming the token (escaped) is allowed.\n */\nfunction substituteSourceFolder(partial: string, folder: string): string {\n if (!partial.includes(SOURCE_FOLDER_PLACEHOLDER)) return partial\n\n const aroundEscapes = partial.split(SOURCE_FOLDER_ESCAPE)\n const asksForTheFolder = aroundEscapes.some((text) =>\n text.includes(SOURCE_FOLDER_PLACEHOLDER)\n )\n if (asksForTheFolder && folder === \"\") throw new Error(NO_SOURCE_FOLDER)\n\n const folderNamedIn = (text: string): string =>\n text.split(SOURCE_FOLDER_PLACEHOLDER).join(folder)\n\n return aroundEscapes.map(folderNamedIn).join(SOURCE_FOLDER_PLACEHOLDER)\n}\n\n// An `AgentFiles` literal, not a spread, so a sixth partial forgotten here fails `tsc`.\nasync function withSourceFolder(\n engine: Liquid,\n data: CompiledAgentData\n): Promise<CompiledAgentData> {\n const folder = await sourceFolderOf(engine)\n const named = (partial: string): string =>\n substituteSourceFolder(partial, folder)\n\n const partials: AgentFiles = {\n identity: named(data.identity),\n playbook: named(data.playbook),\n output: named(data.output),\n criticalRequirementsTop: named(data.criticalRequirementsTop),\n criticalReminders: named(data.criticalReminders),\n }\n\n return { ...data, ...partials }\n}\n\n/**\n * Every compile path renders through here, so `uninstall` can always recognise its own agents.\n * `version` is an argument because a browser has no manifest to read.\n */\nexport async function renderAgent(\n engine: Liquid,\n data: CompiledAgentData,\n version: string\n): Promise<string> {\n return stampProvenanceMarker(\n await renderFromTemplate(engine, AGENT_TEMPLATE, data, version)\n )\n}\n\n/**\n * Exactly the tail of {@link renderAgent}, since `agent.liquid` includes\n * {@link AGENT_BODY_TEMPLATE}; stamped so the marker is on line one.\n */\nexport async function renderAgentBody(\n engine: Liquid,\n data: CompiledAgentData,\n version: string\n): Promise<string> {\n return stampProvenanceMarker(\n await renderFromTemplate(engine, AGENT_BODY_TEMPLATE, data, version)\n )\n}\n\nasync function renderFromTemplate(\n engine: Liquid,\n template: string,\n data: CompiledAgentData,\n version: string\n): Promise<string> {\n const prepared = await withSourceFolder(\n engine,\n sanitizeCompiledAgentData(data)\n )\n\n // Boundary cast: liquidjs types renderFile as `Promise<any>`; this template renders markdown.\n return (await engine.renderFile(template, {\n ...prepared,\n generatorVersion: sanitizeLiquidSyntax(version, \"generatorVersion\"),\n })) as string\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\n\n/** AsyncLocalStorage, not a flag: pair writes interleave, so a flag could clear while held. */\nconst gateToken = new AsyncLocalStorage<true>();\n\nexport class GlobalPairWriteViolation extends Error {\n constructor(targetPath: string) {\n super(\n `${targetPath} may only be written through config-gate — see src/cli/lib/config-gate/index.ts`,\n );\n this.name = \"GlobalPairWriteViolation\";\n }\n}\n\nexport function withGateToken<T>(fn: () => Promise<T>): Promise<T> {\n return gateToken.run(true, fn);\n}\n\nfunction hasGateToken(): boolean {\n return gateToken.getStore() === true;\n}\n\nexport function assertGateToken(targetPath: string): void {\n if (hasGateToken()) return;\n throw new GlobalPairWriteViolation(targetPath);\n}\n","// For lib/ modules without oclif command context; commands use this.log().\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nlet verboseMode = false;\n\nexport function setVerbose(enabled: boolean): void {\n verboseMode = enabled;\n}\n\nexport function verbose(msg: string): void {\n if (verboseMode) {\n console.log(` ${msg}`);\n }\n}\n\nexport function log(msg: string): void {\n console.log(msg);\n}\n\n// In buffer mode, warn() queues messages for the caller to drain instead of writing to stderr.\n\nexport type StartupMessage = {\n level: \"warn\";\n text: string;\n};\n\nlet bufferMode = false;\nlet messageBuffer: StartupMessage[] = [];\n\nconst alreadySaid = new Set<string>();\n\nconst eachWarningOnce = new AsyncLocalStorage<true>();\n\nexport function enableBuffering(): void {\n bufferMode = true;\n messageBuffer = [];\n}\n\nexport function drainBuffer(): StartupMessage[] {\n const messages = [...messageBuffer];\n messageBuffer = [];\n return messages;\n}\n\nexport function disableBuffering(): void {\n bufferMode = false;\n messageBuffer = [];\n}\n\n/** Adds the `Warning:` prefix itself; quote dynamic values in single quotes. */\nexport function warn(msg: string): void {\n if (isARepeatToHoldBack(msg)) return;\n if (bufferMode) {\n messageBuffer.push({ level: \"warn\", text: msg });\n return;\n }\n alreadySaid.add(msg);\n console.warn(` Warning: ${msg}`);\n}\n\nfunction isARepeatToHoldBack(msg: string): boolean {\n if (eachWarningOnce.getStore() !== true) return false;\n return alreadySaid.has(msg) || messageBuffer.some((message) => message.text === msg);\n}\n\n/**\n * Says each distinct warning `body` raises at most once per process (printed or buffered).\n * No reset: the scope is one CLI invocation, so specs asserting on these lines need unique text.\n */\nexport function sayingEachWarningOnce<T>(body: () => T): T {\n return eachWarningOnce.run(true, body);\n}\n\nexport function warnOnce(msg: string): void {\n sayingEachWarningOnce(() => warn(msg));\n}\n","import { unique } from \"remeda\";\n\nimport { KEBAB_CASE_PATTERN } from \"../consts.js\";\n\nconst KEBAB_CASE_CHARACTER = /[a-z0-9-]/;\n\n/** Empty when the name breaks the rule another way (e.g. `-thing`), so refusals state the rule. */\nexport function charactersOutsideKebabCase(name: string): string[] {\n return unique([...name].filter((character) => !KEBAB_CASE_CHARACTER.test(character)));\n}\n\nexport function validateKebabCaseName(name: string, noun: string): string | null {\n if (!name || name.trim() === \"\") {\n return `${noun} name is required`;\n }\n\n if (!KEBAB_CASE_PATTERN.test(name)) {\n return `${noun} name must be kebab-case (lowercase letters, numbers, and hyphens, starting with a letter)`;\n }\n\n return null;\n}\n","import {\n CLI_INVOKE_COMMAND,\n DEFAULT_BRANDING,\n DEFAULT_PLUGIN_NAME,\n EDITOR_URL,\n LOCAL_SKILLS_PATH,\n MARKETPLACE_JSON,\n PLUGIN_MANIFEST_DIR,\n STANDARD_FILES,\n editorConfigUrl,\n type Provider,\n} from \"../consts.js\";\nimport type { UnusableSkillMetadata } from \"../lib/loading/index.js\";\nimport type { ScopeKind } from \"../lib/installation/source-scopes.js\";\nimport type { ConfigLoadError } from \"../lib/configuration/project-config.js\";\nimport type { JoinedAgent } from \"../lib/seed/seed-apply.js\";\nimport type { SkippedSkillAgents } from \"@workspace/compile/seed-to-config\";\nimport { RETIRED_SOURCE_FOLDER } from \"../lib/installation/install-layout.js\";\nimport { charactersOutsideKebabCase } from \"../lib/validate-kebab-name.js\";\nimport { plural, stripTerminalControls } from \"./string.js\";\nimport type { AgentName, Category, SkillId } from \"../types/index.js\";\n\nexport const ERROR_MESSAGES = {\n UNKNOWN_ERROR: \"Unknown error occurred\",\n UNKNOWN_ERROR_SHORT: \"Unknown error\",\n NO_INSTALLATION: `No installation found. Run '${CLI_INVOKE_COMMAND} init' first to set up ${DEFAULT_BRANDING.NAME}`,\n FAILED_RESOLVE_SOURCE: \"Failed to resolve marketplace\",\n FAILED_LOAD_AGENT_PARTIALS: \"Failed to load agent partials\",\n FAILED_COMPILE_AGENTS: \"Failed to compile agents\",\n /** Names `init`, not `edit`: there are no installed skills to edit. */\n NO_SKILLS_TO_COMPILE: `No skills found. Run '${CLI_INVOKE_COMMAND} init' to choose skills, or add your own under ${LOCAL_SKILLS_PATH}/.`,\n} as const;\n\nexport const SUCCESS_MESSAGES = {\n UNINSTALL_COMPLETE: \"Uninstall complete!\",\n PLUGIN_COMPILE_COMPLETE: \"Plugin compile complete!\",\n} as const;\n\nconst HOST_CLI: Record<Provider, { name: string; install: string }> = {\n claude: { name: \"Claude CLI\", install: \"Install Claude Code first: https://claude.ai/code\" },\n codex: {\n name: \"Codex CLI\",\n install: \"Install the '@openai/codex' package first, so that 'codex' is on PATH\",\n },\n};\n\nexport function hostCliNotFound(provider: Provider): string {\n const cli = HOST_CLI[provider];\n return `${cli.name} not found — '${CLI_INVOKE_COMMAND} update' refreshes marketplaces through it. ${cli.install}`;\n}\n\nexport function pluginLeftRegistered(pluginRef: string, provider: Provider): string {\n const cli = HOST_CLI[provider];\n return `Could not unregister plugin '${pluginRef}': ${cli.name} not found, so it stays registered. ${cli.install}`;\n}\n\nexport function initSucceeded(brandingName: string): string {\n return `${brandingName} initialized successfully!`;\n}\n\nexport const STATUS_MESSAGES = {\n INSTALLING_PLUGINS: \"Installing skill plugins...\",\n LOADING_SKILLS: \"Loading skills...\",\n LOADING_MARKETPLACE_SOURCE: \"Loading marketplace...\",\n RECOMPILING_AGENTS: \"Recompiling agents...\",\n COMPILING_AGENTS: \"Compiling agents...\",\n DISCOVERING_SKILLS: \"Discovering skills...\",\n RESOLVING_SOURCE: \"Resolving marketplace...\",\n RESOLVING_MARKETPLACE_SOURCE: \"Resolving marketplace...\",\n LOADING_AGENT_PARTIALS: \"Loading agent partials...\",\n FETCHING_REPOSITORY: \"Fetching repository...\",\n COPYING_SKILLS: \"Copying skills...\",\n /** Printed before the download starts: the only sign this load is not a cache read. */\n MARKETPLACE_HAS_NEWER_CONTENT: \"Marketplace has newer content — fetching the update...\",\n} as const;\n\n/** The partials `readAgentFiles` compiles a sub-agent from, in read order. */\nconst AGENT_PARTIAL_FILES = [\n STANDARD_FILES.IDENTITY_MD,\n STANDARD_FILES.PLAYBOOK_MD,\n STANDARD_FILES.CRITICAL_REQUIREMENTS_MD,\n STANDARD_FILES.CRITICAL_REMINDERS_MD,\n STANDARD_FILES.OUTPUT_MD,\n];\n\nexport const INFO_MESSAGES = {\n NO_CHANGES_MADE: \"No changes made.\",\n RUN_COMPILE: `Run '${CLI_INVOKE_COMMAND} compile' to include imported skills in your agents.`,\n NO_AGENTS_TO_RECOMPILE: \"No agents to recompile\",\n NO_PLUGIN_INSTALLATION: \"No plugin installation found.\",\n NO_LOCAL_INSTALLATION: \"No local installation found.\",\n CONFIG_TYPES_REFRESHED: `Refreshed ${STANDARD_FILES.CONFIG_TYPES_TS}`,\n EJECTED_SKILLS_USER_OWNED: `Ejected skills are yours to own — '${CLI_INVOKE_COMMAND} update' does not change them.`,\n NO_PLUGIN_MARKETPLACES: \"No plugin marketplaces are configured — nothing to refresh.\",\n /** Printed under the destination already named, so it names files only. */\n AGENT_PARTIALS_CUSTOMIZABLE: `Each sub-agent directory there holds ${AGENT_PARTIAL_FILES.join(\", \")} — edit those to customize that sub-agent.`,\n} as const;\n\nexport function notInstalledHere(brandingName: string): string {\n return `${brandingName} is not installed in this project.`;\n}\n\nexport function pluginsInstalled(count: number): string {\n return `Installed ${plural(count, \"skill plugin\")}`;\n}\n\n/** No destination: the copies are split between project and home by each skill's scope. */\nexport function localSkillsCopied(count: number): string {\n return `Copied ${count} local skill(s)`;\n}\n\n/** `subject` is singular, pluralised against `rewritten`. */\nexport function recompileSummary(rewritten: number, unchanged: number, subject: string): string {\n return `${plural(rewritten, subject)} rewritten, ${unchanged} unchanged`;\n}\n\nexport function agentsNotCompiled(agentNames: readonly AgentName[]): string {\n return `${agentNames.length} sub-agent(s) did not compile: ${agentNames.join(\", \")}`;\n}\n\nexport type IncompleteWork = {\n what: string;\n recovery: string;\n};\n\n/** One sentence per kind of leftover state, not per failure site. */\nexport const INCOMPLETE_WORK_RECOVERY = {\n RECOMPILE: `Run '${CLI_INVOKE_COMMAND} compile' — the compiled agents on disk are stale until you do.`,\n INSPECT_INSTALLATION: `Run '${CLI_INVOKE_COMMAND} doctor' to see what this installation is left holding.`,\n DELETE_AGENT_FILE:\n \"Delete the file by hand — Claude Code loads a compiled sub-agent this project no longer configures.\",\n} as const;\n\n/** Restates warnings already printed: it is what explains a non-zero exit from a finished run. */\nexport function completedWithFailures(failures: readonly IncompleteWork[]): string {\n return [\n `Completed with ${failures.length} failure(s) — the changes above landed, these did not:`,\n ...failures.flatMap(failureLines),\n ].join(\"\\n\");\n}\n\nfunction failureLines({ what, recovery }: IncompleteWork): string[] {\n return [` ${what}`, ` ${recovery}`];\n}\n\n/** A project counts as rewritten when its config pair or its compiled sub-agents changed. */\nexport function propagatedRecompileSummary(\n rewritten: number,\n unchanged: number,\n failed: number,\n): string {\n const failureSuffix = failed > 0 ? ` (${failed} failed)` : \"\";\n return `Registered projects: ${rewritten} rewritten, ${unchanged} unchanged${failureSuffix}`;\n}\n\nexport function skillAssignedToNoAgent(skillId: SkillId): string {\n return `Skill '${skillId}' is assigned to no sub-agent — nothing will load it.`;\n}\n\nexport function scopeBlockedStackAssignment(agentNames: AgentName[], skillId: SkillId): string {\n const subject = agentNames.length === 1 ? \"Sub-agent\" : \"Sub-agents\";\n const named = agentNames.map((name) => `'${name}'`).join(\", \");\n return `${subject} ${named} cannot carry project-scoped skill '${skillId}' — global-scoped sub-agents only carry global-scoped skills.`;\n}\n\nexport function globalScopedAgentsHint(count: number): string {\n const [subject, object] = count === 1 ? [\"agent is\", \"it\"] : [\"agents are\", \"them\"];\n return `${count} ${subject} global-scoped — run '${CLI_INVOKE_COMMAND} compile' from your home directory to recompile ${object}.`;\n}\n\nexport function marketplacesRefreshed(count: number): string {\n return `Refreshed ${plural(count, \"marketplace listing\")}. Installed plugins were not changed.`;\n}\n\nexport function marketplaceRefreshFailed(marketplace: string, reason: string): string {\n return `Could not update marketplace ${marketplace}: ${reason}`;\n}\n\nexport function sourceUnreachableUsingCache(source: string): string {\n return `Could not reach ${source} — using the cached copy, which may be out of date.`;\n}\n\nexport function marketplacesRefreshFailed(marketplaces: string[]): string {\n return `${plural(marketplaces.length, \"marketplace\")} could not be updated: ${marketplaces.join(\", \")}`;\n}\n\nexport function marketplaceOwnerHasNoName(packageJsonPath: string): string {\n return [\n `A marketplace's owner must have a name, and no name could be read from 'author' in ${packageJsonPath}.`,\n `Nothing was written: a ${MARKETPLACE_JSON} whose 'owner.name' is empty is refused by this CLI's own reader, so the build would have reported success for a marketplace nobody can install from.`,\n `Set 'author' in that file — either \"Jane Doe <jane@example.com>\" or { \"name\": \"Jane Doe\" } — and build again.`,\n ].join(\"\\n\\n\");\n}\n\nexport function marketplaceHasNoVersion(packageJsonPath: string): string {\n return [\n `A marketplace must have a version, and 'version' in ${packageJsonPath} is empty.`,\n `Nothing was written: a ${MARKETPLACE_JSON} whose 'version' is empty is refused by this CLI's own reader, so the build would have reported success for a marketplace nobody can install from.`,\n `Set 'version' in that file — \"0.1.0\" if this is its first release — and build again.`,\n ].join(\"\\n\\n\");\n}\n\nexport function marketplaceNameNotPublishable(name: string, packageJsonPath: string): string {\n return [\n `Marketplace name '${name}', read from 'name' in ${packageJsonPath}, is not a name a marketplace may publish under.`,\n ...offendingCharactersStatement(name),\n `A marketplace name is kebab-case: lowercase letters, numbers and hyphens, starting with a letter.`,\n `Publish under a name of your own instead: '${CLI_INVOKE_COMMAND} build marketplace --name <your-marketplace>'.`,\n ].join(\"\\n\\n\");\n}\n\nfunction offendingCharactersStatement(name: string): string[] {\n const offenders = charactersOutsideKebabCase(name);\n if (offenders.length === 0) return [];\n\n const named = offenders.map((character) => `'${character}'`).join(\" and \");\n return [`It carries ${named}, which a marketplace name may not.`];\n}\n\nconst MARKETPLACE_MANIFEST = `${PLUGIN_MANIFEST_DIR}/${MARKETPLACE_JSON}`;\n\nconst MARKETPLACE_MANIFEST_REQUIRED = [\n `Every marketplace other than the default one must publish a valid ${MARKETPLACE_MANIFEST}.`,\n `Run '${CLI_INVOKE_COMMAND} build plugins' and then '${CLI_INVOKE_COMMAND} build marketplace' in that marketplace's repository, which write it.`,\n].join(\" \");\n\nexport function marketplaceManifestMissing(source: string): string {\n return [\n `'${source}' has no ${MARKETPLACE_MANIFEST}, so it is not a marketplace yet.`,\n MARKETPLACE_MANIFEST_REQUIRED,\n ].join(\"\\n\\n\");\n}\n\nexport function marketplaceManifestUnreadable(source: string, reason: string): string {\n return [\n `'${source}' has a ${MARKETPLACE_MANIFEST} this CLI cannot read:\\n${reason}`,\n MARKETPLACE_MANIFEST_REQUIRED,\n ].join(\"\\n\\n\");\n}\n\nexport function configTypesRefreshFailed(reason: string): string {\n return `Could not refresh ${STANDARD_FILES.CONFIG_TYPES_TS} — type unions may be stale: ${reason}`;\n}\n\nexport function registeredProjectsUpdated(count: number): string {\n return `Updated ${plural(count, \"registered project\")}`;\n}\n\nexport function registeredProjectUpdateSkipped(projectPath: string): string {\n return `Could not update registered project at ${projectPath} — its config may still reference the uninstalled global content`;\n}\n\nexport function registeredProjectConfigUnreadable(projectPath: string): string {\n return `Skipped ${projectPath}: its config.ts can't be read.`;\n}\n\nexport function registeredProjectGone(projectPath: string): string {\n return `Skipped ${projectPath}: nothing is installed there any more.`;\n}\n\nexport function registeredProjectOnAnotherProvider(projectPath: string): string {\n return `Skipped ${projectPath}: it is another provider's installation.`;\n}\n\nexport function registeredProjectUpdateFailed(projectPath: string): string {\n return `Skipped ${projectPath}: updating it failed.`;\n}\n\n/** Logged rather than put in the error: oclif hard-wraps error text, breaking copyable paths. */\nexport function skillMetadataUnusableDetail({\n skillDirName,\n metadataPath,\n reason,\n}: UnusableSkillMetadata): string {\n return ` ${skillDirName} — ${metadataPath}\\n ${reason}`;\n}\n\nfunction metadataUnusableOpening(entries: UnusableSkillMetadata[]): string {\n const named = entries.map(({ skillDirName }) => `'${skillDirName}'`).join(\", \");\n const subject = entries.length === 1 ? \"that skill\" : \"those skills\";\n return `The ${STANDARD_FILES.METADATA_YAML} of ${named} does not describe ${subject} — the file and the reason are named above.`;\n}\n\nconst METADATA_UNUSABLE_WAY_OUT = `Fix the file, or delete the skill directory — '${CLI_INVOKE_COMMAND} doctor' reports every skill in this state.`;\n\nexport function skillMetadataUnusableError(entries: UnusableSkillMetadata[]): string {\n return [\n metadataUnusableOpening(entries),\n `A skill this file cannot describe is skipped when ${STANDARD_FILES.CONFIG_TYPES_TS} is regenerated, so compiling it would write agents around a skill the generated types never carry.`,\n METADATA_UNUSABLE_WAY_OUT,\n ].join(\"\\n\");\n}\n\nexport function savedSkillMetadataUnusableError(entries: UnusableSkillMetadata[]): string {\n return [\n metadataUnusableOpening(entries),\n `A config entry naming a skill this file cannot describe is dropped as one this marketplace does not carry — and a file that can be repaired must not cost an install its record.`,\n METADATA_UNUSABLE_WAY_OUT,\n ].join(\"\\n\");\n}\n\nexport function editorSkillMetadataUnusableError(entries: UnusableSkillMetadata[]): string {\n return [\n metadataUnusableOpening(entries),\n `The editor opens on what these files describe, so no link is made until each one describes its skill.`,\n METADATA_UNUSABLE_WAY_OUT,\n ].join(\"\\n\");\n}\n\nconst SHARED_CONFIG_GREENFIELD_HINT =\n \"installing a shared configuration is a fresh setup, not a merge\";\n\nexport function sharedConfigDestinations(id: string): string[] {\n return [\n ` Install it: ${CLI_INVOKE_COMMAND} init --from ${id}`,\n ` Open it: ${editorConfigUrl(id)}`,\n ];\n}\n\nexport function applySharedConfigHere(\n id: string | undefined,\n installedHere: boolean,\n provider: Provider | undefined,\n): string {\n const command = `${CLI_INVOKE_COMMAND} ${installedHere ? \"edit\" : \"init\"} --from`;\n const verb = installedHere ? \"apply\" : \"install\";\n const named = providerArgument(provider);\n return id === undefined\n ? `Then ${verb} what it gives you with '${command} <id>${named}'.`\n : `To ${verb} it here instead, run '${command} ${id}${named}'.`;\n}\n\nexport function shareRefusesEjectedSkills(skillIds: readonly string[]): string {\n return [\n \"This installation holds ejected skills, and ejected skills cannot be shared:\",\n ...skillIds.map((id) => ` ${id}`),\n \"Only plugins can be shared.\",\n ].join(\"\\n\");\n}\n\nexport function sharedIdNamesAFolder(folder: string): string {\n return `This id names the marketplace folder ${folder}, so it installs only where that folder exists.`;\n}\n\nexport function sharedSkillsLeftBehind(skillIds: readonly string[]): string {\n return `A shared id names one marketplace, and these skill(s) come from another, so they will not install elsewhere: ${skillIds.join(\", \")}`;\n}\n\nexport function sharedConfigExistingInstall(\n configPath: string,\n id: string,\n provider: Provider | undefined,\n): string {\n return `An installation already exists at ${configPath}. Run '${CLI_INVOKE_COMMAND} uninstall${providerArgument(provider)}' first — ${SHARED_CONFIG_GREENFIELD_HINT}. ${applySharedConfigHere(id, true, provider)}`;\n}\n\nexport function sharedConfigProjectScopeAtHome(\n skillIds: readonly SkillId[],\n agentNames: readonly AgentName[],\n): string {\n return [\n \"This configuration cannot be installed here: the home directory is the global scope, and a \" +\n \"global installation holds only global-scoped content — so these project-scoped entries \" +\n \"have nowhere to be written:\",\n ...skillIds.map((id) => ` skill ${id} (scope: project)`),\n ...agentNames.map((name) => ` sub-agent ${name} (scope: project)`),\n \"Run this from inside a project directory, or re-share it with each entry above at global scope.\",\n ].join(\"\\n\");\n}\n\n/** A key no catalogue knows came off the wire as written, so it is printed inert. */\nfunction unknownKeys(keys: readonly string[]): string {\n return keys.map(stripTerminalControls).join(\", \");\n}\n\nexport function skippedUnknownSkills(\n skillIds: readonly string[],\n skippedWith: readonly SkippedSkillAgents[],\n): string {\n return [\n `Skipped ${skillIds.length} skill(s) this catalog does not know: ${unknownKeys(skillIds)}`,\n ...skippedWith.map(\n ({ skillId, agentNames }) =>\n ` sub-agent(s) skipped with ${unknownKeys([skillId])}, carrying nothing else this catalog knows: ${agentNames.join(\", \")}`,\n ),\n ].join(\"\\n\");\n}\n\nexport function skippedUnknownAgents(agentNames: readonly string[]): string {\n return `Skipped ${agentNames.length} unknown sub-agent(s): ${unknownKeys(agentNames)}`;\n}\n\nexport function carriedSkillsWritten(skillIds: readonly string[]): string {\n return `Wrote ${skillIds.length} skill(s) this configuration carries: ${skillIds.join(\", \")}`;\n}\n\nexport const SHARED_CONFIG_APPLY = {\n PREVIEW_HEADING: \"Applying this configuration will remove:\",\n SKILLS_HEADING: \"Skills:\",\n AGENTS_HEADING: \"Sub-agents:\",\n NOTHING_REMOVED: \"Nothing is removed — this configuration only adds and re-tunes.\",\n OVERWRITTEN_HEADING: \"Will be overwritten:\",\n CONFIRM: \"Apply this configuration?\",\n} as const;\n\nexport function projectCopyRemoved(subject: string): string {\n return `${subject}: this project's copy is removed; the global one takes over`;\n}\n\nexport function projectCopyMovedToGlobal(subject: string): string {\n return `${subject}: moves to the global install, so this project's copy is removed`;\n}\n\nexport function registeredProjectsRewritten(projectPaths: readonly string[]): string {\n return [\n \"Each project registered with this global install is rewritten to match:\",\n ...projectPaths.map((projectPath) => ` ${projectPath}`),\n ].join(\"\\n\");\n}\n\n/** `provider` is the one the run named, which its commands must name again. */\nexport function sharedConfigNeedsTerminal(id: string, provider: Provider | undefined): string {\n const named = providerArgument(provider);\n return [\n `Applying configuration '${id}' removes whatever it leaves out, so it has to be confirmed — and there is no terminal here to confirm it at.`,\n `Run '${CLI_INVOKE_COMMAND} edit --from ${id}${named}' from a terminal, or '${CLI_INVOKE_COMMAND} init --from ${id}${named}' in a clean directory, which installs without removing anything.`,\n ].join(\"\\n\");\n}\n\nexport function nothingInstalledToApplyTo(id: string, provider: Provider | undefined): string {\n return `No installation found. Run '${CLI_INVOKE_COMMAND} init --from ${id}${providerArgument(provider)}' to install configuration '${id}' here.`;\n}\n\n/** `provider` is the one the run named, which its commands must name again. */\nexport function uninstallNeedsTerminal(provider: Provider | undefined): string {\n const named = providerArgument(provider);\n return [\n \"Uninstalling removes files, so it has to be confirmed — and there is no terminal here to confirm it at.\",\n `Run '${CLI_INVOKE_COMMAND} uninstall${named}' from a terminal, or '${CLI_INVOKE_COMMAND} uninstall --yes${named}' to remove it without being asked.`,\n ].join(\"\\n\");\n}\n\nexport function addMarketplaceInTheEditor(ref: string, isFolder: boolean): string {\n return isFolder\n ? `${ref} is a folder on this machine, which the editor cannot read — push it to GitHub, then add it from the editor's Marketplace button.`\n : `Add ${ref} from the editor's Marketplace button.`;\n}\n\nexport const SHARED_CONFIG_ARRIVALS = {\n PROJECT_HEADING: \"Into this project:\",\n GLOBAL_HEADING: \"Into the global install:\",\n SKIPPED_HEADING: \"Skipped, already in the global install:\",\n INSTALL_CONFIRM: \"Install this configuration?\",\n} as const;\n\n/** `idAppliedAtHome` is the id only where a run from home would take the configuration. */\nexport function keptAsInstalledGlobally(\n skillIds: readonly SkillId[],\n agentNames: readonly AgentName[],\n idAppliedAtHome: string | undefined,\n): string {\n return [\n \"Kept as installed in the global install — this configuration states them differently or leaves them out, and a project run only adds to the global install:\",\n ...skillIds.map((id) => ` skill ${id}`),\n ...agentNames.map((name) => ` sub-agent ${name}`),\n ...(idAppliedAtHome === undefined\n ? []\n : [\n `Change them with '${CLI_INVOKE_COMMAND} edit --from ${idAppliedAtHome}' from your home directory.`,\n ]),\n ].join(\"\\n\");\n}\n\nexport function addedToGlobalSubAgents(joined: readonly JoinedAgent[]): string {\n return [\n \"Added to sub-agents in the global install — each keeps everything it already has, since a project run only adds to the global install:\",\n ...joined.map(\n ({ agentName, skillIds }) => ` sub-agent ${agentName}: + ${skillIds.join(\", \")}`,\n ),\n ].join(\"\\n\");\n}\n\nexport function authoredHereKept(skillIds: readonly SkillId[]): string {\n return [\n \"Kept — written here rather than installed, so a shared configuration never carried them:\",\n ...skillIds.map((id) => ` skill ${id}`),\n ].join(\"\\n\");\n}\n\nexport function unplaceableKept(skillIds: readonly SkillId[]): string {\n return [\n \"Kept — named by this configuration, and this catalogue cannot place them:\",\n ...skillIds.map((id) => ` skill ${id}`),\n `Run '${CLI_INVOKE_COMMAND} update' to refresh this installation's marketplace, then apply the configuration again.`,\n ].join(\"\\n\");\n}\n\nexport function keptUnassigned(skillId: SkillId, agentName: AgentName, category: Category): string {\n return `${skillId}: kept, no longer assigned to ${agentName}'s ${category}`;\n}\n\nfunction doctorReportsTheSame(count: number): string {\n return `'${CLI_INVOKE_COMMAND} doctor' reports the same ${count === 1 ? \"file\" : \"files\"}, alongside whatever else is wrong here.`;\n}\n\ntype UnreadableConfig = Pick<\n ConfigLoadError,\n \"configPath\" | \"reason\" | \"scope\" | \"scopeRoot\" | \"providerToName\"\n>;\n\nexport function installationConfigsUnreadable(failures: readonly UnreadableConfig[]): string {\n return [...failures.flatMap(whoseConfigAndItsWayOut), doctorReportsTheSame(failures.length)].join(\n \"\\n\",\n );\n}\n\nfunction whoseConfigAndItsWayOut(failure: UnreadableConfig): string[] {\n return [\n `${scopeLabel(failure.scope)}'s config at '${failure.configPath}' could not be loaded: ${failure.reason}`,\n `There is no automatic repair for this — fix the file, or recreate the configuration by running ${recreateConfigFrom(failure)}.`,\n ];\n}\n\nexport function uninstallConfigUnreadable(\n failure: Pick<ConfigLoadError, \"scope\" | \"message\">,\n): string {\n return `Could not read the ${failure.scope} config — plugins and compiled agents it lists may be left behind: ${failure.message}`;\n}\n\nexport function uninstallSkillMetadataUnreadable(metadataPath: string): string {\n return `Cannot read ${metadataPath}, so uninstall cannot tell whether it made that skill. Fix the file's permissions, or move the skill out, and run uninstall again.`;\n}\n\nexport function recreateConfigFrom({\n scopeRoot,\n providerToName,\n}: Pick<UnreadableConfig, \"scopeRoot\" | \"providerToName\">): string {\n const named = providerArgument(providerToName);\n return `'${CLI_INVOKE_COMMAND} uninstall${named}' from '${scopeRoot}', which still works on a config it cannot read, then '${CLI_INVOKE_COMMAND} init --from <id>${named}' with an id from ${EDITOR_URL}`;\n}\n\n/** Beside a second installation an acting command refuses until it is told which one. */\nexport function providerArgument(provider: Provider | undefined): string {\n return provider === undefined ? \"\" : ` --provider ${provider}`;\n}\n\nexport function configUnreadableError(configLoadFailure: string): string {\n return [\n configLoadFailure,\n \"This is the marketplace's own config rather than an installation's, so it is fixed in the marketplace repository it comes from.\",\n ].join(\"\\n\");\n}\n\nexport function registeredProjectsUpdateFailed(reason: string): string {\n return `Could not update registered projects — their configs may still reference the uninstalled global content: ${reason}`;\n}\n\nexport function unmarkedAgentsKept(agentsDir: string, count: number): string {\n const object = count === 1 ? \"it\" : \"them\";\n return `Kept ${plural(count, \"agent\")} in ${agentsDir}/ — no ${DEFAULT_PLUGIN_NAME} marker, so this CLI did not compile ${object}.`;\n}\n\nexport const UNINSTALL_PLAN = {\n PREVIEW_HEADING: \"The following will be removed:\",\n PLUGINS_HEADING: \"Plugins:\",\n CLI_MANAGED_FILES_HEADING: \"CLI-managed files:\",\n CONFIG_HEADING: \"Config:\",\n} as const;\n\nexport function localSkillsRemoval(skillsDir: string): string {\n return `${skillsDir}/ (matching the marketplace)`;\n}\n\nexport function compiledAgentsRemoval(agentsDir: string): string {\n return `${agentsDir}/ (CLI-compiled)`;\n}\n\nexport function scopeNoun(kind: ScopeKind): string {\n return kind === \"project\" ? \"this project\" : \"the global installation\";\n}\n\nexport function scopeLabel(kind: ScopeKind): string {\n return sentenceCase(scopeNoun(kind));\n}\n\nfunction sentenceCase(text: string): string {\n return `${text.slice(0, 1).toUpperCase()}${text.slice(1)}`;\n}\n\nexport function layoutIsCurrent(label: string, to: string): string {\n return `${label} is on ${to}/`;\n}\n\nexport function retiredSourceFolderUnsupported(replacement: string): string {\n return `${RETIRED_SOURCE_FOLDER}/ is no longer supported (agents-inc now serves Claude and Codex). Move it to ${replacement}/.`;\n}\n","// AUTO-GENERATED from skills source and agent metadata — do not edit manually\n// Run: bun run generate:types\n\n// ── Skill Map (slug → ID) ─────────────────────────────────────\n\nexport const SKILL_MAP = {\n \"ai-planning\": \"meta-planning-ai-planning\",\n \"ai-reviewing\": \"meta-reviewing-ai-reviewing\",\n \"angular-standalone\": \"web-framework-angular-standalone\",\n \"ant-design\": \"web-ui-ant-design\",\n \"anthropic-sdk\": \"ai-provider-anthropic-sdk\",\n \"api-performance\": \"api-performance-api-performance\",\n \"api-planning\": \"meta-planning-api-planning\",\n \"api-reviewing\": \"meta-reviewing-api-reviewing\",\n \"apollo-server\": \"api-graphql-apollo-server\",\n \"app-links\": \"mobile-deep-linking-app-links\",\n appwrite: \"api-baas-appwrite\",\n astro: \"web-meta-framework-astro\",\n \"auth-security\": \"shared-security-auth-security\",\n \"aws-sdk\": \"infra-platform-aws-sdk\",\n \"axiom-pino-sentry\": \"api-observability-axiom-pino-sentry\",\n \"base-ui\": \"web-ui-base-ui\",\n \"better-auth-drizzle-hono\": \"api-auth-better-auth-drizzle-hono\",\n biome: \"shared-tooling-biome\",\n \"ble-nfc\": \"mobile-hardware-ble-nfc\",\n bullmq: \"api-queue-bullmq\",\n \"chakra-ui\": \"web-ui-chakra-ui\",\n changesets: \"shared-tooling-changesets\",\n chroma: \"api-vector-db-chroma\",\n clack: \"cli-prompts-clack\",\n \"claude-vision\": \"ai-provider-claude-vision\",\n clerk: \"api-auth-clerk\",\n \"cli-commander\": \"cli-framework-cli-commander\",\n \"cli-planning\": \"meta-planning-cli-planning\",\n \"cli-reviewing\": \"meta-reviewing-cli-reviewing\",\n \"cloudflare-workers\": \"infra-platform-cloudflare-workers\",\n cockroachdb: \"api-database-cockroachdb\",\n \"cohere-sdk\": \"ai-provider-cohere-sdk\",\n \"component-library\": \"web-tooling-component-library\",\n \"composable-components\": \"meta-design-composable-components\",\n \"css-animations\": \"web-animation-css-animations\",\n cva: \"web-styling-cva\",\n \"cypress-e2e\": \"web-testing-cypress-e2e\",\n d3: \"web-dataviz-d3\",\n \"date-fns\": \"web-utilities-date-fns\",\n \"design-tokens\": \"web-styling-design-tokens\",\n detox: \"mobile-testing-detox\",\n \"dnd-kit\": \"web-dnd-dnd-kit\",\n docker: \"infra-ci-cd-docker\",\n docusaurus: \"web-meta-framework-docusaurus\",\n drizzle: \"api-database-drizzle\",\n eas: \"mobile-deployment-eas\",\n edgedb: \"api-database-edgedb\",\n elasticsearch: \"api-search-elasticsearch\",\n electron: \"desktop-framework-electron\",\n \"electron-forge\": \"desktop-packaging-electron-forge\",\n \"electron-ipc\": \"desktop-ipc-electron\",\n \"electron-multiwindow\": \"desktop-multiwindow-electron\",\n \"electron-security\": \"desktop-security-electron\",\n \"electron-storage\": \"desktop-storage-electron\",\n \"electron-testing\": \"desktop-testing-electron\",\n \"electron-ui\": \"desktop-ui-electron\",\n \"electron-updater\": \"desktop-updates-electron-updater\",\n elevenlabs: \"ai-provider-elevenlabs\",\n elysia: \"api-framework-elysia\",\n \"error-boundaries\": \"web-error-handling-error-boundaries\",\n \"eslint-prettier\": \"shared-tooling-eslint-prettier\",\n expo: \"mobile-framework-expo\",\n \"expo-router\": \"mobile-navigation-expo-router\",\n express: \"api-framework-express\",\n \"expressive-typescript\": \"meta-design-expressive-typescript\",\n fastify: \"api-framework-fastify\",\n \"file-upload-patterns\": \"web-files-file-upload-patterns\",\n firebase: \"api-baas-firebase\",\n \"framer-motion\": \"web-animation-framer-motion\",\n \"gesture-handler\": \"mobile-animation-gesture-handler\",\n \"git-hooks\": \"shared-tooling-git-hooks\",\n \"github-actions\": \"infra-ci-cd-github-actions\",\n \"google-gemini-sdk\": \"ai-provider-google-gemini-sdk\",\n \"graphql-apollo\": \"web-data-fetching-graphql-apollo\",\n \"graphql-urql\": \"web-data-fetching-graphql-urql\",\n \"headless-ui\": \"web-ui-headless-ui\",\n hono: \"api-framework-hono\",\n \"huggingface-inference\": \"ai-infrastructure-huggingface-inference\",\n \"image-handling\": \"web-files-image-handling\",\n \"infra-reviewing\": \"meta-reviewing-infra-reviewing\",\n jotai: \"web-state-jotai\",\n knex: \"api-database-knex\",\n kubernetes: \"infra-containers-kubernetes\",\n langchain: \"ai-orchestration-langchain\",\n langfuse: \"ai-observability-langfuse\",\n leaflet: \"web-maps-leaflet\",\n lexical: \"web-editor-lexical\",\n litellm: \"ai-infrastructure-litellm\",\n llamaindex: \"ai-orchestration-llamaindex\",\n maestro: \"mobile-testing-maestro\",\n mantine: \"web-ui-mantine\",\n mapbox: \"web-maps-mapbox\",\n meilisearch: \"api-search-meilisearch\",\n mercurius: \"api-graphql-mercurius\",\n \"mistral-sdk\": \"ai-provider-mistral-sdk\",\n mmkv: \"mobile-storage-mmkv\",\n mobx: \"web-state-mobx\",\n modal: \"ai-infrastructure-modal\",\n mongodb: \"api-database-mongodb\",\n mongoose: \"api-database-mongoose\",\n msw: \"web-mocks-msw\",\n mui: \"web-ui-mui\",\n mysql: \"api-database-mysql\",\n \"native-js\": \"web-utilities-native-js\",\n nativewind: \"mobile-styling-nativewind\",\n neon: \"api-baas-neon\",\n nestjs: \"api-framework-nestjs\",\n netlify: \"infra-platform-netlify\",\n \"next-intl\": \"web-i18n-next-intl\",\n nextauth: \"api-auth-nextauth\",\n nextjs: \"web-meta-framework-nextjs\",\n \"ngrx-signalstore\": \"web-state-ngrx-signalstore\",\n nuxt: \"web-meta-framework-nuxt\",\n nx: \"shared-monorepo-nx\",\n \"oclif-ink\": \"cli-framework-oclif-ink\",\n \"offline-first\": \"web-pwa-offline-first\",\n ollama: \"ai-infrastructure-ollama\",\n \"openai-sdk\": \"ai-provider-openai-sdk\",\n \"openai-whisper\": \"ai-provider-openai-whisper\",\n openapi: \"api-specs-openapi\",\n payload: \"api-cms-payload\",\n pinecone: \"api-vector-db-pinecone\",\n pinia: \"web-state-pinia\",\n planetscale: \"api-baas-planetscale\",\n \"playwright-e2e\": \"web-testing-playwright-e2e\",\n \"pnpm-workspaces\": \"shared-monorepo-pnpm-workspaces\",\n postgresql: \"api-database-postgresql\",\n \"posthog-analytics\": \"api-analytics-posthog-analytics\",\n \"posthog-flags\": \"api-flags-posthog-flags\",\n prisma: \"api-database-prisma\",\n promptfoo: \"ai-observability-promptfoo\",\n pulumi: \"infra-iac-pulumi\",\n push: \"mobile-notifications-push\",\n qdrant: \"api-vector-db-qdrant\",\n qwik: \"web-meta-framework-qwik\",\n \"radix-ui\": \"web-ui-radix-ui\",\n react: \"web-framework-react\",\n \"react-hook-form\": \"web-forms-react-hook-form\",\n \"react-intl\": \"web-i18n-react-intl\",\n \"react-native\": \"mobile-framework-react-native\",\n \"react-native-paper\": \"mobile-ui-components-react-native-paper\",\n \"react-native-performance\": \"mobile-performance-react-native\",\n \"react-native-security\": \"mobile-security-react-native\",\n \"react-navigation\": \"mobile-navigation-react-navigation\",\n \"react-query\": \"web-server-state-react-query\",\n \"react-router\": \"web-routing-react-router\",\n \"react-testing-library\": \"web-testing-react-testing-library\",\n \"react-three-fiber\": \"web-3d-react-three-fiber\",\n reanimated: \"mobile-animation-reanimated\",\n recharts: \"web-dataviz-recharts\",\n redis: \"api-database-redis\",\n \"redux-toolkit\": \"web-state-redux-toolkit\",\n remix: \"web-meta-framework-remix\",\n replicate: \"ai-infrastructure-replicate\",\n \"research-methodology\": \"meta-methodology-research-methodology\",\n \"resend-react-email\": \"api-email-resend-react-email\",\n \"result-types\": \"web-error-handling-result-types\",\n reviewing: \"meta-reviewing-reviewing\",\n rxjs: \"web-utilities-rxjs\",\n sanity: \"api-cms-sanity\",\n \"scss-modules\": \"web-styling-scss-modules\",\n sequelize: \"api-database-sequelize\",\n \"service-workers\": \"web-pwa-service-workers\",\n \"setup-axiom-pino-sentry\": \"api-observability-setup-axiom-pino-sentry\",\n \"setup-env\": \"infra-config-setup-env\",\n \"setup-posthog\": \"api-analytics-setup-posthog\",\n \"setup-resend\": \"api-email-setup-resend\",\n \"shadcn-ui\": \"web-ui-shadcn-ui\",\n skia: \"mobile-animation-skia\",\n \"socket-io\": \"web-realtime-socket-io\",\n solidjs: \"web-framework-solidjs\",\n \"sqlite-powersync\": \"mobile-storage-sqlite-powersync\",\n sse: \"web-realtime-sse\",\n sst: \"infra-iac-sst\",\n \"stack-detect\": \"meta-config-stack-detect\",\n storybook: \"web-tooling-storybook\",\n strapi: \"api-cms-strapi\",\n strategies: \"api-caching-strategies\",\n stripe: \"api-commerce-stripe\",\n supabase: \"api-baas-supabase\",\n surrealdb: \"api-database-surrealdb\",\n svelte: \"web-framework-svelte\",\n sveltekit: \"web-meta-framework-sveltekit\",\n swr: \"web-data-fetching-swr\",\n tailwind: \"web-styling-tailwind\",\n tamagui: \"mobile-ui-components-tamagui\",\n \"tanstack-form\": \"web-forms-tanstack-form\",\n \"tanstack-router\": \"web-routing-tanstack-router\",\n \"tanstack-table\": \"web-ui-tanstack-table\",\n tasks: \"mobile-background-tasks\",\n tauri: \"desktop-framework-tauri\",\n \"tauri-backend\": \"desktop-backend-tauri\",\n \"tauri-bundling\": \"desktop-packaging-tauri\",\n \"tauri-mobile\": \"desktop-mobile-tauri\",\n \"tauri-multiwindow\": \"desktop-multiwindow-tauri\",\n \"tauri-plugins\": \"desktop-plugins-tauri\",\n \"tauri-security\": \"desktop-security-tauri\",\n terraform: \"infra-iac-terraform\",\n theming: \"web-styling-theming\",\n tiptap: \"web-editor-tiptap\",\n \"together-ai\": \"ai-infrastructure-together-ai\",\n \"tool-use-patterns\": \"ai-patterns-tool-use-patterns\",\n trpc: \"web-data-fetching-trpc\",\n turborepo: \"shared-monorepo-turborepo\",\n \"turborepo-ci\": \"infra-ci-cd-turborepo-ci\",\n turso: \"api-baas-turso\",\n typeorm: \"api-database-typeorm\",\n \"typescript-config\": \"shared-tooling-typescript-config\",\n unistyles: \"mobile-styling-unistyles\",\n upstash: \"api-database-upstash\",\n \"vee-validate\": \"web-forms-vee-validate\",\n vercel: \"infra-platform-vercel\",\n \"vercel-ai-sdk\": \"ai-orchestration-vercel-ai-sdk\",\n \"vercel-kv\": \"api-database-vercel-kv\",\n \"vercel-postgres\": \"api-database-vercel-postgres\",\n \"view-transitions\": \"web-animation-view-transitions\",\n \"vision-camera\": \"mobile-camera-vision-camera\",\n \"visual-regression\": \"web-testing-visual-regression\",\n vite: \"web-tooling-vite\",\n vitepress: \"web-meta-framework-vitepress\",\n vitest: \"web-testing-vitest\",\n \"vue-composition-api\": \"web-framework-vue-composition-api\",\n \"vue-i18n\": \"web-i18n-vue-i18n\",\n \"vue-test-utils\": \"web-testing-vue-test-utils\",\n vuetify: \"web-ui-vuetify\",\n vueuse: \"web-utilities-vueuse\",\n watermelondb: \"mobile-storage-watermelondb\",\n weaviate: \"api-vector-db-weaviate\",\n \"web-accessibility\": \"web-accessibility-web-accessibility\",\n \"web-performance\": \"web-performance-web-performance\",\n \"web-planning\": \"meta-planning-web-planning\",\n \"web-reviewing\": \"meta-reviewing-web-reviewing\",\n webhooks: \"api-messaging-webhooks\",\n websockets: \"web-realtime-websockets\",\n xquik: \"api-search-xquik\",\n yoga: \"api-graphql-yoga\",\n \"zod-validation\": \"web-forms-zod-validation\",\n zustand: \"web-state-zustand\",\n} as const;\n\nexport type SkillSlug = keyof typeof SKILL_MAP;\nexport type SkillId = (typeof SKILL_MAP)[SkillSlug];\n\n// Derived arrays for Zod enum compatibility\n// (z.enum() requires a readonly tuple, not Object.keys/values)\nexport const SKILL_SLUGS = [\n \"ai-planning\",\n \"ai-reviewing\",\n \"angular-standalone\",\n \"ant-design\",\n \"anthropic-sdk\",\n \"api-performance\",\n \"api-planning\",\n \"api-reviewing\",\n \"apollo-server\",\n \"app-links\",\n \"appwrite\",\n \"astro\",\n \"auth-security\",\n \"aws-sdk\",\n \"axiom-pino-sentry\",\n \"base-ui\",\n \"better-auth-drizzle-hono\",\n \"biome\",\n \"ble-nfc\",\n \"bullmq\",\n \"chakra-ui\",\n \"changesets\",\n \"chroma\",\n \"clack\",\n \"claude-vision\",\n \"clerk\",\n \"cli-commander\",\n \"cli-planning\",\n \"cli-reviewing\",\n \"cloudflare-workers\",\n \"cockroachdb\",\n \"cohere-sdk\",\n \"component-library\",\n \"composable-components\",\n \"css-animations\",\n \"cva\",\n \"cypress-e2e\",\n \"d3\",\n \"date-fns\",\n \"design-tokens\",\n \"detox\",\n \"dnd-kit\",\n \"docker\",\n \"docusaurus\",\n \"drizzle\",\n \"eas\",\n \"edgedb\",\n \"elasticsearch\",\n \"electron\",\n \"electron-forge\",\n \"electron-ipc\",\n \"electron-multiwindow\",\n \"electron-security\",\n \"electron-storage\",\n \"electron-testing\",\n \"electron-ui\",\n \"electron-updater\",\n \"elevenlabs\",\n \"elysia\",\n \"error-boundaries\",\n \"eslint-prettier\",\n \"expo\",\n \"expo-router\",\n \"express\",\n \"expressive-typescript\",\n \"fastify\",\n \"file-upload-patterns\",\n \"firebase\",\n \"framer-motion\",\n \"gesture-handler\",\n \"git-hooks\",\n \"github-actions\",\n \"google-gemini-sdk\",\n \"graphql-apollo\",\n \"graphql-urql\",\n \"headless-ui\",\n \"hono\",\n \"huggingface-inference\",\n \"image-handling\",\n \"infra-reviewing\",\n \"jotai\",\n \"knex\",\n \"kubernetes\",\n \"langchain\",\n \"langfuse\",\n \"leaflet\",\n \"lexical\",\n \"litellm\",\n \"llamaindex\",\n \"maestro\",\n \"mantine\",\n \"mapbox\",\n \"meilisearch\",\n \"mercurius\",\n \"mistral-sdk\",\n \"mmkv\",\n \"mobx\",\n \"modal\",\n \"mongodb\",\n \"mongoose\",\n \"msw\",\n \"mui\",\n \"mysql\",\n \"native-js\",\n \"nativewind\",\n \"neon\",\n \"nestjs\",\n \"netlify\",\n \"next-intl\",\n \"nextauth\",\n \"nextjs\",\n \"ngrx-signalstore\",\n \"nuxt\",\n \"nx\",\n \"oclif-ink\",\n \"offline-first\",\n \"ollama\",\n \"openai-sdk\",\n \"openai-whisper\",\n \"openapi\",\n \"payload\",\n \"pinecone\",\n \"pinia\",\n \"planetscale\",\n \"playwright-e2e\",\n \"pnpm-workspaces\",\n \"postgresql\",\n \"posthog-analytics\",\n \"posthog-flags\",\n \"prisma\",\n \"promptfoo\",\n \"pulumi\",\n \"push\",\n \"qdrant\",\n \"qwik\",\n \"radix-ui\",\n \"react\",\n \"react-hook-form\",\n \"react-intl\",\n \"react-native\",\n \"react-native-paper\",\n \"react-native-performance\",\n \"react-native-security\",\n \"react-navigation\",\n \"react-query\",\n \"react-router\",\n \"react-testing-library\",\n \"react-three-fiber\",\n \"reanimated\",\n \"recharts\",\n \"redis\",\n \"redux-toolkit\",\n \"remix\",\n \"replicate\",\n \"research-methodology\",\n \"resend-react-email\",\n \"result-types\",\n \"reviewing\",\n \"rxjs\",\n \"sanity\",\n \"scss-modules\",\n \"sequelize\",\n \"service-workers\",\n \"setup-axiom-pino-sentry\",\n \"setup-env\",\n \"setup-posthog\",\n \"setup-resend\",\n \"shadcn-ui\",\n \"skia\",\n \"socket-io\",\n \"solidjs\",\n \"sqlite-powersync\",\n \"sse\",\n \"sst\",\n \"stack-detect\",\n \"storybook\",\n \"strapi\",\n \"strategies\",\n \"stripe\",\n \"supabase\",\n \"surrealdb\",\n \"svelte\",\n \"sveltekit\",\n \"swr\",\n \"tailwind\",\n \"tamagui\",\n \"tanstack-form\",\n \"tanstack-router\",\n \"tanstack-table\",\n \"tasks\",\n \"tauri\",\n \"tauri-backend\",\n \"tauri-bundling\",\n \"tauri-mobile\",\n \"tauri-multiwindow\",\n \"tauri-plugins\",\n \"tauri-security\",\n \"terraform\",\n \"theming\",\n \"tiptap\",\n \"together-ai\",\n \"tool-use-patterns\",\n \"trpc\",\n \"turborepo\",\n \"turborepo-ci\",\n \"turso\",\n \"typeorm\",\n \"typescript-config\",\n \"unistyles\",\n \"upstash\",\n \"vee-validate\",\n \"vercel\",\n \"vercel-ai-sdk\",\n \"vercel-kv\",\n \"vercel-postgres\",\n \"view-transitions\",\n \"vision-camera\",\n \"visual-regression\",\n \"vite\",\n \"vitepress\",\n \"vitest\",\n \"vue-composition-api\",\n \"vue-i18n\",\n \"vue-test-utils\",\n \"vuetify\",\n \"vueuse\",\n \"watermelondb\",\n \"weaviate\",\n \"web-accessibility\",\n \"web-performance\",\n \"web-planning\",\n \"web-reviewing\",\n \"webhooks\",\n \"websockets\",\n \"xquik\",\n \"yoga\",\n \"zod-validation\",\n \"zustand\",\n] as const satisfies readonly SkillSlug[];\n\nexport const SKILL_IDS = [\n \"ai-infrastructure-huggingface-inference\",\n \"ai-infrastructure-litellm\",\n \"ai-infrastructure-modal\",\n \"ai-infrastructure-ollama\",\n \"ai-infrastructure-replicate\",\n \"ai-infrastructure-together-ai\",\n \"ai-observability-langfuse\",\n \"ai-observability-promptfoo\",\n \"ai-orchestration-langchain\",\n \"ai-orchestration-llamaindex\",\n \"ai-orchestration-vercel-ai-sdk\",\n \"ai-patterns-tool-use-patterns\",\n \"ai-provider-anthropic-sdk\",\n \"ai-provider-claude-vision\",\n \"ai-provider-cohere-sdk\",\n \"ai-provider-elevenlabs\",\n \"ai-provider-google-gemini-sdk\",\n \"ai-provider-mistral-sdk\",\n \"ai-provider-openai-sdk\",\n \"ai-provider-openai-whisper\",\n \"api-analytics-posthog-analytics\",\n \"api-analytics-setup-posthog\",\n \"api-auth-better-auth-drizzle-hono\",\n \"api-auth-clerk\",\n \"api-auth-nextauth\",\n \"api-baas-appwrite\",\n \"api-baas-firebase\",\n \"api-baas-neon\",\n \"api-baas-planetscale\",\n \"api-baas-supabase\",\n \"api-baas-turso\",\n \"api-caching-strategies\",\n \"api-cms-payload\",\n \"api-cms-sanity\",\n \"api-cms-strapi\",\n \"api-commerce-stripe\",\n \"api-database-cockroachdb\",\n \"api-database-drizzle\",\n \"api-database-edgedb\",\n \"api-database-knex\",\n \"api-database-mongodb\",\n \"api-database-mongoose\",\n \"api-database-mysql\",\n \"api-database-postgresql\",\n \"api-database-prisma\",\n \"api-database-redis\",\n \"api-database-sequelize\",\n \"api-database-surrealdb\",\n \"api-database-typeorm\",\n \"api-database-upstash\",\n \"api-database-vercel-kv\",\n \"api-database-vercel-postgres\",\n \"api-email-resend-react-email\",\n \"api-email-setup-resend\",\n \"api-flags-posthog-flags\",\n \"api-framework-elysia\",\n \"api-framework-express\",\n \"api-framework-fastify\",\n \"api-framework-hono\",\n \"api-framework-nestjs\",\n \"api-graphql-apollo-server\",\n \"api-graphql-mercurius\",\n \"api-graphql-yoga\",\n \"api-messaging-webhooks\",\n \"api-observability-axiom-pino-sentry\",\n \"api-observability-setup-axiom-pino-sentry\",\n \"api-performance-api-performance\",\n \"api-queue-bullmq\",\n \"api-search-elasticsearch\",\n \"api-search-meilisearch\",\n \"api-search-xquik\",\n \"api-specs-openapi\",\n \"api-vector-db-chroma\",\n \"api-vector-db-pinecone\",\n \"api-vector-db-qdrant\",\n \"api-vector-db-weaviate\",\n \"cli-framework-cli-commander\",\n \"cli-framework-oclif-ink\",\n \"cli-prompts-clack\",\n \"desktop-backend-tauri\",\n \"desktop-framework-electron\",\n \"desktop-framework-tauri\",\n \"desktop-ipc-electron\",\n \"desktop-mobile-tauri\",\n \"desktop-multiwindow-electron\",\n \"desktop-multiwindow-tauri\",\n \"desktop-packaging-electron-forge\",\n \"desktop-packaging-tauri\",\n \"desktop-plugins-tauri\",\n \"desktop-security-electron\",\n \"desktop-security-tauri\",\n \"desktop-storage-electron\",\n \"desktop-testing-electron\",\n \"desktop-ui-electron\",\n \"desktop-updates-electron-updater\",\n \"infra-ci-cd-docker\",\n \"infra-ci-cd-github-actions\",\n \"infra-ci-cd-turborepo-ci\",\n \"infra-config-setup-env\",\n \"infra-containers-kubernetes\",\n \"infra-iac-pulumi\",\n \"infra-iac-sst\",\n \"infra-iac-terraform\",\n \"infra-platform-aws-sdk\",\n \"infra-platform-cloudflare-workers\",\n \"infra-platform-netlify\",\n \"infra-platform-vercel\",\n \"meta-config-stack-detect\",\n \"meta-design-composable-components\",\n \"meta-design-expressive-typescript\",\n \"meta-methodology-research-methodology\",\n \"meta-planning-ai-planning\",\n \"meta-planning-api-planning\",\n \"meta-planning-cli-planning\",\n \"meta-planning-web-planning\",\n \"meta-reviewing-ai-reviewing\",\n \"meta-reviewing-api-reviewing\",\n \"meta-reviewing-cli-reviewing\",\n \"meta-reviewing-infra-reviewing\",\n \"meta-reviewing-reviewing\",\n \"meta-reviewing-web-reviewing\",\n \"mobile-animation-gesture-handler\",\n \"mobile-animation-reanimated\",\n \"mobile-animation-skia\",\n \"mobile-background-tasks\",\n \"mobile-camera-vision-camera\",\n \"mobile-deep-linking-app-links\",\n \"mobile-deployment-eas\",\n \"mobile-framework-expo\",\n \"mobile-framework-react-native\",\n \"mobile-hardware-ble-nfc\",\n \"mobile-navigation-expo-router\",\n \"mobile-navigation-react-navigation\",\n \"mobile-notifications-push\",\n \"mobile-performance-react-native\",\n \"mobile-security-react-native\",\n \"mobile-storage-mmkv\",\n \"mobile-storage-sqlite-powersync\",\n \"mobile-storage-watermelondb\",\n \"mobile-styling-nativewind\",\n \"mobile-styling-unistyles\",\n \"mobile-testing-detox\",\n \"mobile-testing-maestro\",\n \"mobile-ui-components-react-native-paper\",\n \"mobile-ui-components-tamagui\",\n \"shared-monorepo-nx\",\n \"shared-monorepo-pnpm-workspaces\",\n \"shared-monorepo-turborepo\",\n \"shared-security-auth-security\",\n \"shared-tooling-biome\",\n \"shared-tooling-changesets\",\n \"shared-tooling-eslint-prettier\",\n \"shared-tooling-git-hooks\",\n \"shared-tooling-typescript-config\",\n \"web-3d-react-three-fiber\",\n \"web-accessibility-web-accessibility\",\n \"web-animation-css-animations\",\n \"web-animation-framer-motion\",\n \"web-animation-view-transitions\",\n \"web-data-fetching-graphql-apollo\",\n \"web-data-fetching-graphql-urql\",\n \"web-data-fetching-swr\",\n \"web-data-fetching-trpc\",\n \"web-dataviz-d3\",\n \"web-dataviz-recharts\",\n \"web-dnd-dnd-kit\",\n \"web-editor-lexical\",\n \"web-editor-tiptap\",\n \"web-error-handling-error-boundaries\",\n \"web-error-handling-result-types\",\n \"web-files-file-upload-patterns\",\n \"web-files-image-handling\",\n \"web-forms-react-hook-form\",\n \"web-forms-tanstack-form\",\n \"web-forms-vee-validate\",\n \"web-forms-zod-validation\",\n \"web-framework-angular-standalone\",\n \"web-framework-react\",\n \"web-framework-solidjs\",\n \"web-framework-svelte\",\n \"web-framework-vue-composition-api\",\n \"web-i18n-next-intl\",\n \"web-i18n-react-intl\",\n \"web-i18n-vue-i18n\",\n \"web-maps-leaflet\",\n \"web-maps-mapbox\",\n \"web-meta-framework-astro\",\n \"web-meta-framework-docusaurus\",\n \"web-meta-framework-nextjs\",\n \"web-meta-framework-nuxt\",\n \"web-meta-framework-qwik\",\n \"web-meta-framework-remix\",\n \"web-meta-framework-sveltekit\",\n \"web-meta-framework-vitepress\",\n \"web-mocks-msw\",\n \"web-performance-web-performance\",\n \"web-pwa-offline-first\",\n \"web-pwa-service-workers\",\n \"web-realtime-socket-io\",\n \"web-realtime-sse\",\n \"web-realtime-websockets\",\n \"web-routing-react-router\",\n \"web-routing-tanstack-router\",\n \"web-server-state-react-query\",\n \"web-state-jotai\",\n \"web-state-mobx\",\n \"web-state-ngrx-signalstore\",\n \"web-state-pinia\",\n \"web-state-redux-toolkit\",\n \"web-state-zustand\",\n \"web-styling-cva\",\n \"web-styling-design-tokens\",\n \"web-styling-scss-modules\",\n \"web-styling-tailwind\",\n \"web-styling-theming\",\n \"web-testing-cypress-e2e\",\n \"web-testing-playwright-e2e\",\n \"web-testing-react-testing-library\",\n \"web-testing-visual-regression\",\n \"web-testing-vitest\",\n \"web-testing-vue-test-utils\",\n \"web-tooling-component-library\",\n \"web-tooling-storybook\",\n \"web-tooling-vite\",\n \"web-ui-ant-design\",\n \"web-ui-base-ui\",\n \"web-ui-chakra-ui\",\n \"web-ui-headless-ui\",\n \"web-ui-mantine\",\n \"web-ui-mui\",\n \"web-ui-radix-ui\",\n \"web-ui-shadcn-ui\",\n \"web-ui-tanstack-table\",\n \"web-ui-vuetify\",\n \"web-utilities-date-fns\",\n \"web-utilities-native-js\",\n \"web-utilities-rxjs\",\n \"web-utilities-vueuse\",\n] as const satisfies readonly SkillId[];\n\n// ── Categories ─────────────────────────────────────────────────\n\nexport const CATEGORIES = [\n \"ai-infrastructure\",\n \"ai-observability\",\n \"ai-orchestration\",\n \"ai-patterns\",\n \"ai-provider\",\n \"api-analytics\",\n \"api-api\",\n \"api-auth\",\n \"api-baas\",\n \"api-caching\",\n \"api-cms\",\n \"api-commerce\",\n \"api-db-host\",\n \"api-document\",\n \"api-email\",\n \"api-graphql\",\n \"api-kv\",\n \"api-messaging\",\n \"api-observability\",\n \"api-orm\",\n \"api-performance\",\n \"api-queue\",\n \"api-search\",\n \"api-specs\",\n \"api-sql-engine\",\n \"api-vector-db\",\n \"cli-framework\",\n \"cli-prompts\",\n \"desktop-backend\",\n \"desktop-framework\",\n \"desktop-ipc\",\n \"desktop-mobile\",\n \"desktop-multiwindow\",\n \"desktop-packaging\",\n \"desktop-plugins\",\n \"desktop-security\",\n \"desktop-storage\",\n \"desktop-testing\",\n \"desktop-ui\",\n \"desktop-updates\",\n \"infra-ci-cd\",\n \"infra-config\",\n \"infra-containers\",\n \"infra-iac\",\n \"infra-platform\",\n \"meta-design\",\n \"meta-methodology\",\n \"meta-planning\",\n \"meta-reviewing\",\n \"mobile-animation\",\n \"mobile-background\",\n \"mobile-camera\",\n \"mobile-deep-linking\",\n \"mobile-deployment\",\n \"mobile-framework\",\n \"mobile-hardware\",\n \"mobile-navigation\",\n \"mobile-notifications\",\n \"mobile-performance\",\n \"mobile-security\",\n \"mobile-storage\",\n \"mobile-styling\",\n \"mobile-testing\",\n \"mobile-ui-components\",\n \"shared-lint\",\n \"shared-monorepo\",\n \"shared-security\",\n \"shared-task-runner\",\n \"shared-tooling\",\n \"web-3d\",\n \"web-accessibility\",\n \"web-animation\",\n \"web-client-state\",\n \"web-dataviz\",\n \"web-dnd\",\n \"web-docs\",\n \"web-e2e\",\n \"web-editor\",\n \"web-error-handling\",\n \"web-file-upload\",\n \"web-files\",\n \"web-form-library\",\n \"web-forms\",\n \"web-framework\",\n \"web-graphql-client\",\n \"web-i18n\",\n \"web-maps\",\n \"web-meta-framework\",\n \"web-mocking\",\n \"web-performance\",\n \"web-pwa\",\n \"web-realtime\",\n \"web-routing\",\n \"web-rpc\",\n \"web-server-state\",\n \"web-streaming\",\n \"web-styling\",\n \"web-testing\",\n \"web-tooling\",\n \"web-ui-components\",\n \"web-ui-kit\",\n \"web-utilities\",\n] as const;\n\nexport type Category = (typeof CATEGORIES)[number];\n\n// ── Domains ────────────────────────────────────────────────────\n\nexport const DOMAINS = [\n \"ai\",\n \"api\",\n \"cli\",\n \"desktop\",\n \"infra\",\n \"meta\",\n \"mobile\",\n \"shared\",\n \"web\",\n] as const;\n\nexport type Domain = (typeof DOMAINS)[number];\n\n// ── Agent Names ────────────────────────────────────────────────\n\nexport const AGENT_NAMES = [\n \"agent-summoner\",\n \"ai-developer\",\n \"ai-researcher\",\n \"ai-tester\",\n \"api-developer\",\n \"api-researcher\",\n \"api-tester\",\n \"cli-developer\",\n \"cli-researcher\",\n \"cli-tester\",\n \"codex-keeper\",\n \"convention-keeper\",\n \"pm\",\n \"reviewer\",\n \"skill-summoner\",\n \"web-developer\",\n \"web-researcher\",\n \"web-tester\",\n] as const;\n\nexport type AgentName = (typeof AGENT_NAMES)[number];\n","import { AGENT_NAMES, SKILL_IDS } from \"../types/generated/source-types\";\nimport type { AgentName, SkillId } from \"../types/generated/source-types\";\nimport type { SkillAssignment } from \"../types/skills\";\n\n/** Rejects arrays and primitives. */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport function isAgentName(value: string): value is AgentName {\n return (AGENT_NAMES as readonly string[]).includes(value);\n}\n\nexport function isSkillId(value: string): value is SkillId {\n return (SKILL_IDS as readonly string[]).includes(value);\n}\n\n/** The id is not union-checked: assignments may name skills outside the generated union. */\nexport function isSkillAssignment(value: unknown): value is SkillAssignment {\n if (typeof value !== \"object\" || value === null) return false;\n // Boundary cast: probing an unknown object's field\n return typeof (value as { id?: unknown }).id === \"string\";\n}\n","// Cast: Object.entries widens keys to string.\nexport function typedEntries<K extends string, V>(obj: Partial<Record<K, V>>): [K, V][] {\n return Object.entries(obj) as [K, V][];\n}\n\n// Cast: Object.keys widens keys to string.\nexport function typedKeys<K extends string>(obj: Partial<Record<K, unknown>>): K[] {\n return Object.keys(obj) as K[];\n}\n\n// Cast: Object.fromEntries widens keys to string.\nexport function typedFromEntries<K extends string, V>(\n entries: Iterable<readonly [K, V]>,\n): Partial<Record<K, V>> {\n return Object.fromEntries(entries) as Partial<Record<K, V>>;\n}\n\n// Filters the undefined slots a Partial admits.\nexport function typedValues<K extends string, V>(obj: Partial<Record<K, V>>): V[] {\n return Object.values(obj).filter((value): value is V => value !== undefined);\n}\n","import { BlockList, isIPv4 } from \"net\";\nimport os from \"os\";\nimport path from \"path\";\nimport { z } from \"zod\";\nimport { DEFAULT_SOURCE } from \"@workspace/compile\";\nimport { fileExists, readFileOptional } from \"../../utils/fs\";\nimport { verbose, warn } from \"../../utils/logger\";\nimport { getErrorMessage } from \"../../utils/errors\";\nimport {\n DEFAULT_BRANDING,\n GITHUB_SOURCE,\n PUBLIC_CATALOGUE_PACKAGE,\n SOURCE_ROOT_DIR,\n STANDARD_FILES,\n type Provider,\n} from \"../../consts\";\nimport { configUnreadableError, installationConfigsUnreadable } from \"../../utils/messages\";\nimport { formatZodIssues, projectConfigLoaderSchema, projectSourceConfigSchema } from \"../schemas\";\nimport type { ProjectConfig, SourceEntry } from \"../../types\";\nimport {\n ConfigDefaultExportError,\n ConfigSchemaError,\n loadConfig,\n NO_VALID_DEFAULT_EXPORT,\n} from \"./config-loader\";\nimport { getInstalledConfigPath, getProjectConfigPath } from \"../installation/install-base-dir\";\nimport { providerInUse } from \"../installation/install-layout\";\nimport { providerToNameAt } from \"../installation/provider-to-name\";\nimport { isHomeDirectory } from \"../installation/is-home-directory\";\nimport type { ScopeKind } from \"../installation/source-scopes\";\n\nexport { DEFAULT_SOURCE };\nexport const SOURCE_ENV_VAR = \"CC_MARKETPLACE\";\n\nexport type { SourceEntry } from \"../../types/config\";\n\n// Lives in install-base-dir.ts to avoid an import cycle.\nexport { getProjectConfigPath };\n\nexport type ResolvedConfig = {\n source: string;\n sourceOrigin: \"flag\" | \"env\" | \"project\" | \"global\" | \"default\";\n} & (RecordedMarketplaceName | { marketplace?: undefined; marketplaceRecordedIn?: undefined });\n\n/** A pair, because a refusal of the name sends the reader to the file holding it. */\ntype RecordedMarketplaceName = { marketplace: string; marketplaceRecordedIn: string };\n\n/**\n * Choosing a marketplace is install-time, so only `\"init\"` reads the environment rung. `\"stored\"`\n * callers get project, then global, then the default, though any caller may still name one to read.\n */\nexport type SourceCaller = \"init\" | \"stored\";\n\ntype ResolveSourceRequest = {\n caller: SourceCaller;\n /** The marketplace this run named, where it named one. */\n flag?: string | undefined;\n /** The project whose `config.ts` is the first stored rung. */\n projectDir?: string | undefined;\n /** Whose configs the stored rungs are, where a scope holds two; read off each folder otherwise. */\n provider?: Provider | undefined;\n};\n\n/**\n * `null` only when the file is absent. A present file that cannot load is raised, never reported as\n * absence, and is judged as the full-config reader judges it. Callers abort, except\n * `validateRegisteredSources`, which degrades.\n */\nasync function loadSourceConfig(\n dir: string,\n scope: ScopeKind,\n provider?: Provider,\n): Promise<Partial<ProjectConfig> | null> {\n const scopeLabel = scope === \"project\" ? \"Project\" : \"Global\";\n const configPath = storedConfigPath(dir, provider);\n\n if (!(await fileExists(configPath))) {\n verbose(`${scopeLabel} config not found at ${configPath}`);\n return null;\n }\n\n const unreadable = refuseInstallationConfig(\n configPath,\n scope,\n dir,\n provider ?? providerInUse(dir),\n );\n const installation = await readConfigOrRefuse(configPath, projectConfigLoaderSchema, unreadable);\n if (installation === null) throw unreadable(NO_VALID_DEFAULT_EXPORT);\n const settings = readSettings(configPath, installation);\n\n verbose(`Loaded ${scope} config from ${dir}`);\n return settings;\n}\n\n/** How a reader words a config that is there and will not load, from the reason it gives. */\ntype RefuseUnreadable = (reason: string, cause?: unknown) => Error;\n\n/** Worded as `ensureConfigReadable` words the same file. */\nfunction refuseInstallationConfig(\n configPath: string,\n scope: ScopeKind,\n scopeRoot: string,\n provider: Provider,\n): RefuseUnreadable {\n const providerToName = providerToNameAt(scopeRoot, provider);\n return (reason, cause) =>\n new Error(\n installationConfigsUnreadable([{ configPath, reason, scope, scopeRoot, providerToName }]),\n { cause },\n );\n}\n\n/** `null` when the config evaluated and declared nothing; every failure raises. */\nasync function readConfigOrRefuse<T>(\n configPath: string,\n schema: z.ZodType<T>,\n unreadable: RefuseUnreadable,\n): Promise<T | null> {\n try {\n return await loadConfig(configPath, schema);\n } catch (error) {\n if (describesItsOwnFault(error)) throw error;\n throw unreadable(getErrorMessage(error), error);\n }\n}\n\n/** Parsed, since the installation schema lets the settings-only fields through unread. */\nfunction readSettings(configPath: string, installation: unknown): Partial<ProjectConfig> {\n const settings = projectSourceConfigSchema.safeParse(installation);\n if (!settings.success) {\n throw new ConfigSchemaError(configPath, formatZodIssues(settings.error.issues));\n }\n return settings.data;\n}\n\n/** True for failures that already name the faulty field or export, which are passed on as-is. */\nfunction describesItsOwnFault(error: unknown): boolean {\n return error instanceof ConfigSchemaError || error instanceof ConfigDefaultExportError;\n}\n\n/** `loadConfig` already names the file and the parser's reason, so it is passed on as-is. */\nconst unreadableSourceRepoConfig: RefuseUnreadable = (reason, cause) =>\n new Error(configUnreadableError(reason), { cause });\n\n/**\n * A source repo's own config, with absence told apart from a file that declares nothing, which\n * `loadConfig` answers `null` for alike.\n */\nexport type SourceRepoConfigRead =\n | { kind: \"absent\" }\n | { kind: \"declares-nothing\"; configPath: string }\n | { kind: \"declared\"; config: Partial<ProjectConfig> };\n\n/** A source repo's own `<base>/.agents-inc/config.ts`, provider-neutral: layout has no provider. */\nexport async function readSourceRepoConfig(basePath: string): Promise<SourceRepoConfigRead> {\n const configPath = path.join(basePath, SOURCE_ROOT_DIR, STANDARD_FILES.CONFIG_TS);\n if (!(await fileExists(configPath))) {\n verbose(`Source config not found at ${configPath}`);\n return { kind: \"absent\" };\n }\n\n const config = await readConfigOrRefuse(\n configPath,\n projectSourceConfigSchema,\n unreadableSourceRepoConfig,\n );\n return config === null ? { kind: \"declares-nothing\", configPath } : { kind: \"declared\", config };\n}\n\n/** Null when the repo declares no layout of its own, whether the file is absent or empty. */\nexport async function loadSourceRepoConfig(\n basePath: string,\n): Promise<Partial<ProjectConfig> | null> {\n const read = await readSourceRepoConfig(basePath);\n return read.kind === \"declared\" ? read.config : null;\n}\n\n/** The scope it announces is derived: at the home root this file is the global config. */\nexport async function loadProjectSourceConfig(\n projectDir: string,\n): Promise<Partial<ProjectConfig> | null> {\n return loadSourceConfig(projectDir, isHomeDirectory(projectDir) ? \"global\" : \"project\");\n}\n\nexport async function loadGlobalSourceConfig(): Promise<Partial<ProjectConfig> | null> {\n return loadSourceConfig(os.homedir(), \"global\");\n}\n\n/** The effective source config, which scope it was actually loaded from, and its file. */\ntype EffectiveSourceConfig = {\n config: Partial<ProjectConfig>;\n origin: ScopeKind;\n configPath: string;\n};\n\nasync function loadEffectiveSourceConfig(\n projectDir?: string,\n provider?: Provider,\n): Promise<EffectiveSourceConfig | null> {\n const ownDir = ownProjectDir(projectDir);\n const own = ownDir === null ? null : await readStoredRung(ownDir, \"project\", provider);\n return own ?? (await readStoredRung(os.homedir(), \"global\", provider));\n}\n\n/** One stored rung: the config at `dir` and the file it was read from, or null when it has none. */\nasync function readStoredRung(\n dir: string,\n origin: ScopeKind,\n provider?: Provider,\n): Promise<EffectiveSourceConfig | null> {\n const config = await loadSourceConfig(dir, origin, provider);\n return config && { config, origin, configPath: storedConfigPath(dir, provider) };\n}\n\n/** The named installation's config, or the one the folder holds where none is named. */\nfunction storedConfigPath(dir: string, provider: Provider | undefined): string {\n return provider === undefined ? getInstalledConfigPath(dir) : getProjectConfigPath(dir, provider);\n}\n\n/** The directory whose config is a project's own, or null at the home root. */\nfunction ownProjectDir(projectDir: string | undefined): string | null {\n return projectDir === undefined || isHomeDirectory(projectDir) ? null : projectDir;\n}\n\n/** Nothing at the home root, whose config is the global one; the axis is which file was read. */\nasync function loadOwnProjectSourceConfig(\n projectDir: string | undefined,\n): Promise<Partial<ProjectConfig> | null> {\n const ownDir = ownProjectDir(projectDir);\n return ownDir === null ? null : loadProjectSourceConfig(ownDir);\n}\n\nfunction recordedMarketplaceName(\n effective: EffectiveSourceConfig | null,\n): RecordedMarketplaceName | undefined {\n if (effective?.config.marketplaceName === undefined) return undefined;\n return {\n marketplace: effective.config.marketplaceName,\n marketplaceRecordedIn: effective.configPath,\n };\n}\n\n/** Precedence: flag > env > project > global > default; the env rung is read for `init` only. */\nexport async function resolveSource(request: ResolveSourceRequest): Promise<ResolvedConfig> {\n const { caller, flag, projectDir, provider } = request;\n const effective = await loadEffectiveSourceConfig(projectDir, provider);\n const storedSource = effective?.config.marketplace ?? DEFAULT_SOURCE;\n // The stored name labels only the ref it was read beside.\n const recorded = recordedMarketplaceName(effective);\n const labelFor = (source: string) => source === storedSource && recorded;\n\n if (flag !== undefined) {\n assertNamedSourceUsable(flag);\n verbose(`Marketplace named by this run: ${flag}`);\n return { source: flag, sourceOrigin: \"flag\", ...labelFor(flag) };\n }\n\n const envSource = caller === \"init\" ? readEnvSource() : undefined;\n if (envSource !== undefined) {\n return { source: envSource, sourceOrigin: \"env\", ...labelFor(envSource) };\n }\n\n if (effective?.config.marketplace) {\n assertStoredSourceUsable(effective.config.marketplace, effective.configPath);\n verbose(`Marketplace from ${effective.origin} config: ${effective.config.marketplace}`);\n return {\n source: effective.config.marketplace,\n sourceOrigin: effective.origin,\n ...labelFor(effective.config.marketplace),\n };\n }\n\n verbose(`Using default marketplace: ${DEFAULT_SOURCE}`);\n return { source: DEFAULT_SOURCE, sourceOrigin: \"default\", ...labelFor(DEFAULT_SOURCE) };\n}\n\n/** Origin-neutral: a `\"stored\"` caller may name a marketplace too, without `--marketplace`. */\nconst NAMED_SOURCE_LABEL = \"The marketplace\";\n\n/** Whoever carried a marketplace value: a refusal names them, and writes its examples their way. */\nexport type MarketplaceCarrier = Readonly<{\n subject: string;\n writes: (marketplace: string) => string;\n}>;\n\n/** Named by this run, written as the flag a user names one with. */\nexport const NAMED_MARKETPLACE: MarketplaceCarrier = {\n subject: NAMED_SOURCE_LABEL,\n writes: (marketplace) => `--marketplace ${marketplace}`,\n};\n\n/** Recorded in a config file, quoted as the config the CLI writes quotes it. */\nfunction marketplaceInConfig(configPath: string): MarketplaceCarrier {\n return {\n subject: `${NAMED_SOURCE_LABEL} in ${configPath}`,\n writes: (marketplace) => `marketplace: '${marketplace}'`,\n };\n}\n\nconst ENVIRONMENT_MARKETPLACE: MarketplaceCarrier = {\n subject: SOURCE_ENV_VAR,\n writes: (marketplace) => `${SOURCE_ENV_VAR}=${marketplace}`,\n};\n\n/** Raised, not warned: somebody named this, so falling through would install from elsewhere. */\nexport function assertNamedSourceUsable(flag: string): void {\n if (flag.trim() === \"\") {\n throw new Error(\n `${NAMED_SOURCE_LABEL} cannot be empty. Provide a valid marketplace: a local directory path or a git repository URL (e.g., './my-skills' or 'https://github.com/user/repo')`,\n );\n }\n validateSourceFormat(flag.trim(), NAMED_MARKETPLACE);\n}\n\n/** Raised as a named one is, naming the file: whoever wrote it there chose it as surely. */\nfunction assertStoredSourceUsable(source: string, configPath: string): void {\n validateSourceFormat(source, marketplaceInConfig(configPath));\n}\n\n/** Unset, empty or unusable falls through with a warning: the environment is ambient. */\nfunction readEnvSource(): string | undefined {\n const envValue = process.env[SOURCE_ENV_VAR];\n if (!envValue) return undefined;\n\n const trimmed = envValue.trim();\n if (trimmed === \"\") {\n warn(`${SOURCE_ENV_VAR} is set but empty — ignoring and falling back to the next rung.`);\n return undefined;\n }\n\n try {\n validateSourceFormat(trimmed, ENVIRONMENT_MARKETPLACE);\n } catch (error) {\n warn(\n `${SOURCE_ENV_VAR} has an invalid value — ignoring and falling back to the next rung.\\n${getErrorMessage(error)}`,\n );\n return undefined;\n }\n\n verbose(`Marketplace from ${SOURCE_ENV_VAR} env var: ${trimmed}`);\n return trimmed;\n}\n\ntype ResolvedBranding = {\n name: string;\n};\n\n/** Per field, not per file: the project's, then the global one's, then the shipped default. */\nexport async function resolveBranding(projectDir?: string): Promise<ResolvedBranding> {\n const [own, global] = await Promise.all([\n loadOwnProjectSourceConfig(projectDir),\n loadGlobalSourceConfig(),\n ]);\n\n return {\n name: own?.branding?.name ?? global?.branding?.name ?? DEFAULT_BRANDING.NAME,\n };\n}\n\n/** As a `SourceEntry`, the shape the listing surfaces (`search`, `doctor`) want. */\nexport async function resolvePrimarySourceEntry(projectDir?: string): Promise<SourceEntry> {\n const resolvedConfig = await resolveSource({ caller: \"stored\", projectDir });\n return {\n name: \"marketplace\",\n url: resolvedConfig.source,\n description: \"Primary skills marketplace\",\n };\n}\n\nconst REMOTE_PROTOCOLS = [\n GITHUB_SOURCE.GITHUB_PREFIX,\n GITHUB_SOURCE.GH_PREFIX,\n \"gitlab:\",\n \"bitbucket:\",\n \"sourcehut:\",\n \"https://\",\n \"http://\",\n] as const;\n\nconst MIN_REMOTE_PATH_LENGTH = 3;\nconst MAX_SOURCE_LENGTH = 512;\n\n// A null byte truncates the string in downstream C-level tools.\nconst NULL_BYTE_PATTERN = /\\0/;\n\nconst PATH_TRAVERSAL_PATTERN = /\\.\\./;\n\n// A UNC path can trigger SMB authentication to an attacker's server, leaking credentials.\nconst UNC_PATH_PATTERN = /^(?:\\/\\/|\\\\\\\\)/;\n\ntype Subnet = { network: string; prefix: number };\n\n/**\n * Private and reserved ranges a marketplace URL must not target (SSRF via giget). Reads the URL's\n * text only: a redirect, a `.json` source naming another URL, a name resolving to a private\n * address, an operator's NAT64 prefix, and a URL read from anywhere but a marketplace value (a cache\n * record, a host-refreshed marketplace) are not checked; only a connect-time check of the resolved\n * address would see them, and there is none.\n */\nconst PRIVATE_IPV4_SUBNETS: readonly Subnet[] = [\n { network: \"127.0.0.0\", prefix: 8 },\n { network: \"10.0.0.0\", prefix: 8 },\n { network: \"172.16.0.0\", prefix: 12 },\n { network: \"192.168.0.0\", prefix: 16 },\n { network: \"169.254.0.0\", prefix: 16 },\n { network: \"0.0.0.0\", prefix: 8 }, // \"this network\"; 0.0.0.0 itself connects to the loopback\n { network: \"100.64.0.0\", prefix: 10 }, // shared carrier-grade NAT space\n { network: \"192.0.0.0\", prefix: 24 }, // IETF protocol assignments\n { network: \"198.18.0.0\", prefix: 15 }, // benchmarking\n { network: \"224.0.0.0\", prefix: 4 }, // multicast\n { network: \"240.0.0.0\", prefix: 4 }, // reserved, up to the broadcast 255.255.255.255\n];\n\nconst PRIVATE_IPV6_SUBNETS: readonly Subnet[] = [\n { network: \"::\", prefix: 128 }, // unspecified: 0.0.0.0's twin, and it too connects to the loopback\n { network: \"::1\", prefix: 128 },\n { network: \"fc00::\", prefix: 7 }, // unique local\n { network: \"fe80::\", prefix: 10 }, // link-local\n { network: \"ff00::\", prefix: 8 }, // multicast\n // NAT64 local use, whole: where it carries IPv4 depends on the prefix length (RFC 6052).\n { network: \"64:ff9b:1::\", prefix: 48 },\n];\n\n/** Where an IPv6 address holds the IPv4 one it carries: its lowest bit, and whether inverted. */\ntype CarriedIPv4 = Readonly<{ lowestBit: bigint; inverted: boolean }>;\n\nconst IN_THE_LAST_32_BITS: CarriedIPv4 = { lowestBit: 0n, inverted: false };\n\n/** IPv6 forms that carry an IPv4 address; a connection to one reaches the address it carries. */\nconst IPV4_CARRYING_FORMS: readonly (Subnet & { carries: readonly CarriedIPv4[] })[] = [\n { network: \"::ffff:0:0\", prefix: 96, carries: [IN_THE_LAST_32_BITS] }, // IPv4-mapped\n { network: \"::ffff:0:0:0\", prefix: 96, carries: [IN_THE_LAST_32_BITS] }, // IPv4-translated\n { network: \"::\", prefix: 96, carries: [IN_THE_LAST_32_BITS] }, // IPv4-compatible\n { network: \"64:ff9b::\", prefix: 96, carries: [IN_THE_LAST_32_BITS] }, // NAT64\n { network: \"2002::\", prefix: 16, carries: [{ lowestBit: 80n, inverted: false }] }, // 6to4\n // Teredo: the server that relays to the client, and the client, inverted.\n {\n network: \"2001::\",\n prefix: 32,\n carries: [\n { lowestBit: 64n, inverted: false },\n { lowestBit: 0n, inverted: true },\n ],\n },\n];\n\nconst PRIVATE_IPV4_ADDRESSES = blockListOf(PRIVATE_IPV4_SUBNETS, \"ipv4\");\nconst PRIVATE_IPV6_ADDRESSES = blockListOf(PRIVATE_IPV6_SUBNETS, \"ipv6\");\nconst IPV4_CARRIERS = IPV4_CARRYING_FORMS.map(({ carries, ...subnet }) => ({\n carries,\n addresses: blockListOf([subnet], \"ipv6\"),\n}));\n\nconst IPV6_GROUP_COUNT = 8;\nconst IPV6_GROUP_BITS = 16n;\nconst HEX_RADIX = 16;\nconst IPV4_BITS_MASK = 0xffff_ffffn;\nconst IPV4_OCTET_LOWEST_BITS = [24n, 16n, 8n, 0n];\nconst OCTET_MASK = 0xffn;\n\n/**\n * Thrown for a marketplace value the check refuses, so a refusal is told apart from a fault. Its\n * `name` stays `Error`: `eject` lets a refusal reach the binary, which prints `<name>: <message>`.\n */\nexport class MarketplaceRefusedError extends Error {}\n\n/** The examples each refusal offers, written out by the carrier of the value it refused. */\nconst LOCAL_OR_SHORTHAND_EXAMPLES = [\"./my-skills\", \"github:user/repo\"];\nconst REMOTE_EXAMPLES = [\"github:user/repo\", \"https://github.com/user/repo\"];\nconst URL_EXAMPLES = [\"https://github.com/user/repo\", \"https://gitlab.company.com/team/skills\"];\nconst SHORTHAND_EXAMPLES = [\"github:user/repo\", \"gh:organization/skills\"];\nconst LOCAL_EXAMPLES = [\"./my-skills\", \"/home/user/skills\"];\nconst LOCAL_OR_URL_EXAMPLES = [...LOCAL_EXAMPLES, \"https://github.com/user/repo\"];\n\n/** What is wrong with the value, why, and what to write instead, the way its carrier writes one. */\nfunction refusal(\n carrier: MarketplaceCarrier,\n problem: string,\n why: readonly string[],\n examples: readonly string[],\n): MarketplaceRefusedError {\n return new MarketplaceRefusedError(\n [\n `${carrier.subject} ${problem}`,\n \"\",\n ...why,\n \"Examples:\",\n ...examples.map((example) => ` ${carrier.writes(example)}`),\n ].join(\"\\n\"),\n );\n}\n\nexport function validateSourceFormat(source: string, carrier: MarketplaceCarrier): void {\n if (NULL_BYTE_PATTERN.test(source)) {\n throw refusal(\n carrier,\n \"contains invalid characters.\",\n [\"Marketplace values must not contain null bytes.\"],\n LOCAL_OR_SHORTHAND_EXAMPLES,\n );\n }\n\n if (source.length > MAX_SOURCE_LENGTH) {\n throw refusal(\n carrier,\n `value is too long (${source.length} characters, max ${MAX_SOURCE_LENGTH}).`,\n [\"Provide a shorter marketplace path or URL.\"],\n LOCAL_OR_SHORTHAND_EXAMPLES,\n );\n }\n\n const matchedProtocol = REMOTE_PROTOCOLS.find((prefix) => source.startsWith(prefix));\n\n if (matchedProtocol) {\n validateRemoteSource(source, matchedProtocol, carrier);\n } else {\n validateLocalPath(source, carrier);\n }\n}\n\nfunction validateRemoteSource(source: string, protocol: string, carrier: MarketplaceCarrier): void {\n const isHttp = protocol === \"https://\" || protocol === \"http://\";\n\n // First: every refusal below echoes the URL, and this one must not.\n if (isHttp) refuseCredentials(source, protocol, carrier);\n\n const pathAfterProtocol = source.slice(protocol.length).trim();\n\n if (pathAfterProtocol.length < MIN_REMOTE_PATH_LENGTH) {\n throw refusal(\n carrier,\n `has an incomplete URL: \"${source}\"`,\n [\"A repository path is required after the protocol prefix.\"],\n REMOTE_EXAMPLES,\n );\n }\n\n if (PATH_TRAVERSAL_PATTERN.test(pathAfterProtocol)) {\n throw refusal(\n carrier,\n `contains path traversal in URL: \"${source}\"`,\n [\"Remote marketplace URLs must not contain '..' sequences.\"],\n REMOTE_EXAMPLES,\n );\n }\n\n if (isHttp) {\n validateHttpUrl(source, carrier);\n return;\n }\n\n validateGitShorthand(source, pathAfterProtocol, carrier);\n}\n\n/** What the URL parser drops from a URL wherever it stands, before reading any of it. */\nconst TABS_AND_NEWLINES = /[\\t\\n\\r]/g;\n\n/** The run of `/` and `\\` the URL parser skips after a special scheme such as http(s). */\nconst SLASHES_BEFORE_AUTHORITY = /^[/\\\\]*/;\n\n/** Where the URL parser ends a URL's authority, for a special scheme such as http(s). */\nconst AUTHORITY_END = /[/?#\\\\]/;\n\nconst CREDENTIALS_MASK = \"***\";\n\n/**\n * Shown and refused without the username or password: an echo would put them in a log. Shown as\n * the URL parser reads it, since that reading is the text the mask is cut from.\n */\nfunction refuseCredentials(source: string, protocol: string, carrier: MarketplaceCarrier): void {\n const fromAuthority = fromAuthorityOn(source, protocol);\n const userinfo = userinfoOf(fromAuthority);\n if (userinfo === null) return;\n\n const shown = `${protocol}${CREDENTIALS_MASK}${fromAuthority.slice(userinfo.length)}`;\n throw refusal(\n carrier,\n `carries a username or password in its URL: \"${shown}\"`,\n [\n \"Credentials in a marketplace URL end up in config files, shared configurations and logs.\",\n \"For a private repository, set the GIGET_AUTH environment variable instead:\",\n \" export GIGET_AUTH=ghp_your_github_token\",\n ],\n URL_EXAMPLES,\n );\n}\n\n/**\n * The http(s) URL from its authority on, as the URL parser reaches it: tabs and newlines dropped,\n * then the slashes after the scheme skipped. Read off the text rather than through `new URL`, so a\n * URL the parser cannot read is caught too, before a refusal that echoes it.\n */\nfunction fromAuthorityOn(source: string, protocol: string): string {\n return source\n .replace(TABS_AND_NEWLINES, \"\")\n .slice(protocol.length)\n .replace(SLASHES_BEFORE_AUTHORITY, \"\");\n}\n\n/** As the URL parser reads it: everything in the authority before its last `@`; null if none. */\nfunction userinfoOf(fromAuthority: string): string | null {\n const authorityEnd = fromAuthority.search(AUTHORITY_END);\n const authority = authorityEnd === -1 ? fromAuthority : fromAuthority.slice(0, authorityEnd);\n const lastAt = authority.lastIndexOf(\"@\");\n return lastAt === -1 ? null : authority.slice(0, lastAt);\n}\n\nfunction validateHttpUrl(source: string, carrier: MarketplaceCarrier): void {\n const hostname = parsedHostname(source);\n\n if (hostname === null || !namesAcceptedHost(hostname)) {\n throw refusal(\n carrier,\n `has an invalid URL: \"${source}\"`,\n [\"The URL must include a valid hostname.\"],\n URL_EXAMPLES,\n );\n }\n\n if (namesPrivateAddress(hostname)) {\n throw refusal(\n carrier,\n `points to a private or reserved IP address: \"${source}\"`,\n [\n \"Marketplace URLs must not target private network addresses.\",\n \"Use a public hostname instead.\",\n ],\n URL_EXAMPLES,\n );\n }\n}\n\n/**\n * The host as giget's download reads it (`new URL`), with port, query and fragment stripped and an\n * IPv4 address in dotted decimal however it was spelled; null when unreadable.\n */\nfunction parsedHostname(source: string): string | null {\n return URL.canParse(source) ? new URL(source).hostname : null;\n}\n\n/**\n * A dotted hostname, localhost, or an IPv6 address. `localhost` passes on purpose: the e2e suite\n * and hand runs serve a remote, cached marketplace from it.\n */\nfunction namesAcceptedHost(hostname: string): boolean {\n return hostname.includes(\".\") || hostname === \"localhost\" || isIPv6Host(hostname);\n}\n\n/** A domain name is not an address, so it is never private by this check. */\nfunction namesPrivateAddress(hostname: string): boolean {\n if (isIPv6Host(hostname)) return isPrivateIPv6(hostname.slice(1, -1));\n return isIPv4(hostname) && isPrivateIPv4(hostname);\n}\n\nfunction isPrivateIPv4(address: string): boolean {\n return PRIVATE_IPV4_ADDRESSES.check(address, \"ipv4\");\n}\n\nfunction isPrivateIPv6(address: string): boolean {\n return (\n PRIVATE_IPV6_ADDRESSES.check(address, \"ipv6\") ||\n carriedIPv4Addresses(address).some(isPrivateIPv4)\n );\n}\n\n/** Every IPv4 address `address` carries, in each form it is written in. */\nfunction carriedIPv4Addresses(address: string): string[] {\n const bits = ipv6Bits(address);\n return formsWrittenIn(address).flatMap(({ carries }) =>\n carries.map((carried) => ipv4Carried(bits, carried)),\n );\n}\n\nfunction formsWrittenIn(address: string): typeof IPV4_CARRIERS {\n return IPV4_CARRIERS.filter(({ addresses }) => addresses.check(address, \"ipv6\"));\n}\n\nfunction ipv4Carried(bits: bigint, { lowestBit, inverted }: CarriedIPv4): string {\n const held = (bits >> lowestBit) & IPV4_BITS_MASK;\n return dottedQuad(inverted ? held ^ IPV4_BITS_MASK : held);\n}\n\nfunction dottedQuad(ipv4Bits: bigint): string {\n return IPV4_OCTET_LOWEST_BITS.map((octetBit) => (ipv4Bits >> octetBit) & OCTET_MASK).join(\".\");\n}\n\n/** The address as one 128-bit number. */\nfunction ipv6Bits(address: string): bigint {\n return ipv6Groups(address).reduce((bits, group) => (bits << IPV6_GROUP_BITS) | BigInt(group), 0n);\n}\n\n/** Read as the URL parser writes an IPv6 host: lowercase hex groups, one `::` at most, no IPv4 tail. */\nfunction ipv6Groups(address: string): number[] {\n const gap = address.indexOf(\"::\");\n if (gap === -1) return hexGroups(address);\n\n const head = hexGroups(address.slice(0, gap));\n const tail = hexGroups(address.slice(gap + \"::\".length));\n const zeros = Array.from({ length: IPV6_GROUP_COUNT - head.length - tail.length }, () => 0);\n return [...head, ...zeros, ...tail];\n}\n\nfunction hexGroups(part: string): number[] {\n if (part === \"\") return [];\n return part.split(\":\").map((group) => Number.parseInt(group, HEX_RADIX));\n}\n\n/** The URL parser writes an IPv6 host in brackets, and only an IPv6 host. */\nfunction isIPv6Host(hostname: string): boolean {\n return hostname.startsWith(\"[\");\n}\n\nfunction blockListOf(subnets: readonly Subnet[], family: \"ipv4\" | \"ipv6\"): BlockList {\n const blockList = new BlockList();\n subnets.forEach(({ network, prefix }) => blockList.addSubnet(network, prefix, family));\n return blockList;\n}\n\nfunction validateGitShorthand(source: string, repoPath: string, carrier: MarketplaceCarrier): void {\n if (!repoPath.includes(\"/\")) {\n throw refusal(\n carrier,\n `has an invalid repository reference: \"${source}\"`,\n [\"Git shorthand marketplaces require an owner/repo format.\"],\n SHORTHAND_EXAMPLES,\n );\n }\n}\n\nfunction validateLocalPath(source: string, carrier: MarketplaceCarrier): void {\n // eslint-disable-next-line no-control-regex -- control characters (bar common whitespace) are what this rejects\n const CONTROL_CHAR_PATTERN = /[\\x00-\\x08\\x0E-\\x1F\\x7F]/u;\n if (CONTROL_CHAR_PATTERN.test(source)) {\n throw refusal(\n carrier,\n `contains invalid characters: \"${source}\"`,\n [\"Marketplace paths must not contain control characters.\"],\n LOCAL_EXAMPLES,\n );\n }\n\n if (UNC_PATH_PATTERN.test(source)) {\n throw refusal(\n carrier,\n `contains a UNC network path: \"${source}\"`,\n [\n \"Network paths (\\\\\\\\server\\\\share or //server/share) are not allowed for security reasons.\",\n \"Use a local directory path or a remote URL instead.\",\n ],\n LOCAL_OR_URL_EXAMPLES,\n );\n }\n}\n\n/** Asked of the source string; where a directory is in hand, use `isPublicCatalogueCheckout`. */\nexport function isDefaultSource(source: string): boolean {\n return source === DEFAULT_SOURCE;\n}\n\n/** The only field of a repository's package.json this module reads. */\nconst packageIdentitySchema = z.object({ name: z.string() });\n\n/** Read off package identity, never off `marketplace.json`'s name, which the author writes. */\nexport async function isPublicCatalogueCheckout(basePath: string): Promise<boolean> {\n const raw = await readFileOptional(path.join(basePath, STANDARD_FILES.PACKAGE_JSON));\n return declaredPackageName(raw) === PUBLIC_CATALOGUE_PACKAGE;\n}\n\n/** The `name` a package.json declares, or null when there is none to read. */\nfunction declaredPackageName(raw: string): string | null {\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch {\n return null;\n }\n\n const parsed = packageIdentitySchema.safeParse(json);\n return parsed.success ? parsed.data.name : null;\n}\n\n/** Read by both stack lookups so offering and resolving agree; a catalogue checkout counts too. */\nexport async function offersBuiltInStacks(basePath: string, source: string): Promise<boolean> {\n return isDefaultSource(source) || (await isPublicCatalogueCheckout(basePath));\n}\n\nexport function isLocalSource(source: string): boolean {\n if (source.startsWith(\"/\") || source.startsWith(\".\")) {\n return true;\n }\n\n const hasRemoteProtocol = REMOTE_PROTOCOLS.some((prefix) => source.startsWith(prefix));\n if (hasRemoteProtocol) return false;\n\n if (source.includes(\"..\") || source.includes(\"~\")) {\n throw new Error(\n `Invalid marketplace path: ${source}. Path traversal patterns like '..' and '~' are not allowed for security reasons. Use absolute paths or remote URLs instead (e.g., '/home/user/skills' or 'https://github.com/user/repo').`,\n );\n }\n return true;\n}\n","import { z } from \"zod\";\nimport { partition } from \"remeda\";\nimport type { LocalSkillMetadata } from \"./skills/skill-metadata\";\nimport type { LocalRawMetadata } from \"./skills/local-skill-loader\";\nimport {\n AUTHOR_HANDLE_PATTERN,\n KEBAB_CASE_PATTERN,\n LOCAL_PSEUDO_CATEGORY,\n STANDARD_FILES,\n} from \"../consts\";\nimport { METADATA_KEYS } from \"./metadata-keys\";\nimport { formatZodIssue } from \"./schema-validator\";\nimport { isRecord } from \"../utils/type-guards\";\nimport { warn } from \"../utils/logger\";\nimport { SKILL_SLUGS, CATEGORIES } from \"../types/generated/source-types\";\nimport {\n AGENT_ISOLATIONS,\n CACHE_TTLS,\n CODEX_MODEL_NAMES,\n EFFORT_NAMES,\n MODEL_NAMES,\n PERMISSION_MODES,\n} from \"../types/matrix\";\nimport type {\n AgentHookAction,\n AgentHookDefinition,\n AgentIsolation,\n AgentName,\n AgentYamlConfig,\n AlternativeGroup,\n CategoryDefinition,\n CategoryPath,\n CodexModelName,\n ConflictRule,\n DiscourageRule,\n Domain,\n EffortLevel,\n Marketplace,\n MarketplaceMetadata,\n MarketplaceOwner,\n MarketplacePlugin,\n MarketplaceRemoteSource,\n ModelName,\n PermissionMode,\n PluginAuthor,\n PluginManifest,\n ProjectConfig,\n RelationshipDefinitions,\n RequireRule,\n SkillAssignment,\n SkillConfig,\n SkillId,\n SkillSlug,\n Category,\n} from \"../types\";\n\nconst modelNameSchema = z.enum(MODEL_NAMES) as z.ZodType<ModelName>;\n\nconst codexModelNameSchema = z.enum(CODEX_MODEL_NAMES) as z.ZodType<CodexModelName>;\n\nconst effortLevelSchema = z.enum(EFFORT_NAMES) as z.ZodType<EffortLevel>;\n\nconst permissionModeSchema = z.enum(PERMISSION_MODES) as z.ZodType<PermissionMode>;\n\nconst categoryPathSchema = z.string().refine(\n (val): val is CategoryPath => {\n if (val === LOCAL_PSEUDO_CATEGORY) return true;\n if ((CATEGORIES as readonly string[]).includes(val)) return true;\n return KEBAB_CASE_PATTERN.test(val);\n },\n {\n message: \"Must be a valid category path (e.g., 'web-framework', 'shared-testing', or 'local')\",\n },\n) as z.ZodType<CategoryPath>;\n\nconst agentHookActionSchema: z.ZodType<AgentHookAction> = z.object({\n type: z.enum([\"command\", \"script\", \"prompt\"]),\n command: z.string().exactOptional(),\n script: z.string().exactOptional(),\n prompt: z.string().exactOptional(),\n});\n\n/** `Partial`: nothing reads a manifest's hooks, and refusing one would drop the whole plugin. */\nconst agentHookDefinitionSchema: z.ZodType<Partial<AgentHookDefinition>> = z.object({\n matcher: z.string().exactOptional(),\n hooks: z.array(agentHookActionSchema).exactOptional(),\n});\n\nconst hooksRecordSchema = z.record(z.string(), z.array(agentHookDefinitionSchema));\n\n/**\n * `z.enum` rather than a cast literal, so it moves with the vocabulary: a narrower schema still\n * satisfies `z.ZodType<AgentIsolation>`, so `tsc` would not catch a missing mode.\n */\nconst agentIsolationSchema = z.enum(AGENT_ISOLATIONS) as z.ZodType<AgentIsolation>;\n\n/** `.strict()`: a plain object empties an unknown key to `{}`, leaving nothing to refuse. */\nconst agentExperimentalSchema = z\n .object({\n cacheTtl: z.enum(CACHE_TTLS).exactOptional(),\n })\n .strict();\n\nconst strictAgentHookDefinitionSchema = z.object({\n matcher: z.string().exactOptional(),\n hooks: z.array(agentHookActionSchema).min(1),\n});\n\nexport const strictHooksRecordSchema = z.record(\n z.string(),\n z.array(strictAgentHookDefinitionSchema),\n);\n\nconst skillAssignmentSchema: z.ZodType<SkillAssignment> = z.object({\n id: z.string() as z.ZodType<SkillId>,\n preloaded: z.boolean().exactOptional(),\n local: z.boolean().exactOptional(),\n path: z.string().exactOptional(),\n});\n\nexport const skillFrontmatterLoaderSchema = z.object({\n /** Lenient: local/custom skills have non-builtin IDs. */\n name: z.string() as z.ZodType<SkillId>,\n description: z.string(),\n model: modelNameSchema.exactOptional(),\n});\n\n/** Whether the category is declared is asked by `mergeLocalSkillsIntoMatrix`, not here. */\nexport const skillMetadataLoaderSchema = z\n .object({\n category: categoryPathSchema.exactOptional(),\n author: z.string().exactOptional(),\n domain: z.string() as z.ZodType<Domain>,\n custom: z.boolean().exactOptional(),\n })\n .passthrough();\n\nexport const matrixRawMetadataSchema = z.object({\n category: categoryPathSchema,\n author: z.string(),\n displayName: z.string().exactOptional(),\n slug: z.string() as z.ZodType<SkillSlug>,\n cliDescription: z.string().exactOptional(),\n usageGuidance: z.string().exactOptional(),\n // Boundary cast: domain is a string at the YAML parse boundary; narrowed to Domain type\n domain: z.string() as z.ZodType<Domain>,\n custom: z.boolean().exactOptional(),\n});\n\nconst pluginAuthorSchema: z.ZodType<PluginAuthor> = z.object({\n name: z.string().min(1),\n email: z.string().exactOptional(),\n});\n\nconst pluginManifestObjectSchema = z.object({\n name: z.string(),\n version: z.string().exactOptional(),\n description: z.string().exactOptional(),\n author: pluginAuthorSchema.exactOptional(),\n /** A plugin authored elsewhere may carry any category, or none. */\n category: z.string().exactOptional(),\n keywords: z.array(z.string()).exactOptional(),\n commands: z.union([z.string(), z.array(z.string())]).exactOptional(),\n agents: z.union([z.string(), z.array(z.string())]).exactOptional(),\n skills: z.union([z.string(), z.array(z.string())]).exactOptional(),\n hooks: z.union([z.string(), hooksRecordSchema]).exactOptional(),\n});\n\nexport const pluginManifestSchema: z.ZodType<PluginManifest> = pluginManifestObjectSchema;\n\nexport const pluginManifestValidationSchema = pluginManifestObjectSchema.strict();\n\nexport const agentYamlConfigSchema: z.ZodType<AgentYamlConfig> = z.object({\n id: z.string() as z.ZodType<AgentName>,\n title: z.string(),\n description: z.string(),\n model: modelNameSchema.exactOptional(),\n effort: effortLevelSchema.exactOptional(),\n tools: z.array(z.string()),\n disallowedTools: z.array(z.string()).exactOptional(),\n permissionMode: permissionModeSchema.exactOptional(),\n isolation: agentIsolationSchema.exactOptional(),\n /** Strict, like the frontmatter reader: a lenient read silently emptied malformed hooks. */\n hooks: strictHooksRecordSchema.exactOptional(),\n experimental: agentExperimentalSchema.exactOptional(),\n outputFormat: z.string().exactOptional(),\n domain: (z.string() as z.ZodType<Domain>).exactOptional(),\n custom: z.boolean().exactOptional(),\n});\n\nconst skillAssignmentElementSchema = z.union([\n z.string() as z.ZodType<SkillId>,\n skillAssignmentSchema,\n]);\n\n/** Lenient: a bare string, object or array from YAML; consumers normalize to SkillAssignment[]. */\nconst stackAgentConfigSchema = z.record(\n z.string(),\n z.union([skillAssignmentElementSchema, z.array(skillAssignmentElementSchema)]),\n);\n\n/** Pre-rename top-level keys, mapped to their new field; both loader schemas refuse them. */\nconst RENAMED_CONFIG_FIELDS = { source: \"marketplace\" } as const satisfies Record<\n string,\n keyof ProjectConfig\n>;\n\n/** The same, for skill entries. */\nconst RENAMED_SKILL_ENTRY_FIELDS = { source: \"origin\" } as const satisfies Record<\n string,\n keyof SkillConfig\n>;\n\nfunction renamedFieldMessage(oldKey: string, newKey: string): string {\n return `\"${oldKey}\" was renamed to \"${newKey}\". Rename the key in this config — the CLI does not read \"${oldKey}\" any more and will not fall back to it.`;\n}\n\nfunction reportRenamedKeys(\n record: Record<string, unknown>,\n renames: Record<string, string>,\n path: PropertyKey[],\n ctx: z.RefinementCtx,\n): void {\n for (const [oldKey, newKey] of Object.entries(renames)) {\n if (!(oldKey in record)) continue;\n ctx.addIssue({\n code: \"custom\",\n path: [...path, oldKey],\n message: renamedFieldMessage(oldKey, newKey),\n });\n }\n}\n\n/**\n * Reads the raw document: `.passthrough()` keeps a stale top-level key as unknown data and the\n * declared skills array strips one, so the run would silently use the default marketplace.\n */\nfunction refuseRenamedFields(config: unknown, ctx: z.RefinementCtx): void {\n if (!isRecord(config)) return;\n\n reportRenamedKeys(config, RENAMED_CONFIG_FIELDS, [], ctx);\n\n const { skills } = config;\n if (!Array.isArray(skills)) return;\n for (const [index, entry] of skills.entries()) {\n if (!isRecord(entry)) continue;\n reportRenamedKeys(entry, RENAMED_SKILL_ENTRY_FIELDS, [\"skills\", index], ctx);\n }\n}\n\n/** Piped so a stale key is answered with its rename rather than missing-field noise. */\nconst renamedFieldGuard = z.unknown().superRefine(refuseRenamedFields);\n\nconst projectConfigFields = z\n .object({\n name: z.string().exactOptional(),\n description: z.string().exactOptional(),\n agents: z\n .array(\n z.object({\n name: z.string(),\n scope: z.enum([\"project\", \"global\"]),\n model: modelNameSchema.exactOptional(),\n codexModel: codexModelNameSchema.exactOptional(),\n effort: effortLevelSchema.exactOptional(),\n excluded: z.boolean().exactOptional(),\n }),\n )\n .exactOptional(),\n skills: z\n .array(\n z.object({\n id: z.string() as z.ZodType<SkillId>,\n scope: z.enum([\"project\", \"global\"]),\n origin: z.string(),\n excluded: z.boolean().exactOptional(),\n }),\n )\n .exactOptional(),\n\n author: z.string().exactOptional(),\n selectedDomains: z.array(z.string() as z.ZodType<Domain>).exactOptional(),\n stack: z.record(z.string(), stackAgentConfigSchema).exactOptional(),\n /** A path or URL (e.g., \"github:my-org/skills\") */\n marketplace: z.string().exactOptional(),\n /** The name the marketplace's manifest gives it, which plugins are registered under */\n marketplaceName: z.string().exactOptional(),\n /** Global config only */\n projects: z.array(z.string()).exactOptional(),\n })\n .passthrough();\n\n/** Lenient: partial configs are valid at load time; validateProjectConfig() validates fully. */\nexport const projectConfigLoaderSchema = renamedFieldGuard.pipe(projectConfigFields);\n\nconst categoryDefinitionSchema: z.ZodType<CategoryDefinition> = z.object({\n id: z.string() as z.ZodType<Category>,\n displayName: z.string(),\n description: z.string(),\n domain: (z.string() as z.ZodType<Domain>).exactOptional(),\n exclusive: z.boolean(),\n order: z.number(),\n icon: z.string().exactOptional(),\n});\n\n/** The refused input as the author wrote it, where it is text at all. */\nfunction refusedInputNamed(input: unknown): string {\n return typeof input === \"string\" ? `'${input}'` : \"That value\";\n}\n\n/** Names the slug the author wrote: Zod's enum message lists ~250 options and never the input. */\nfunction unknownSkillSlugRefusal(input: unknown): string {\n const named = refusedInputNamed(input);\n return (\n `${named} is not a slug the public catalogue carries, and a relationship rule may only ` +\n `name skills the public catalogue carries — this marketplace's own skills cannot be named ` +\n `in one yet. Name a catalogue slug, or leave 'relationships' out: it is optional, and a ` +\n `marketplace shipping no relationship rules loads and installs like any other.`\n );\n}\n\n// Slugs, resolved to canonical IDs by matrix-loader\nconst skillRefInRules = z.enum(SKILL_SLUGS, {\n error: (issue) => unknownSkillSlugRefusal(issue.input),\n}) as z.ZodType<SkillSlug>;\n\nconst skillGroupRuleSchema = z.object({\n skills: z.array(skillRefInRules).min(2),\n reason: z.string(),\n});\n\nconst conflictRuleSchema: z.ZodType<ConflictRule> = skillGroupRuleSchema;\n\nconst discourageRuleSchema: z.ZodType<DiscourageRule> = skillGroupRuleSchema;\n\nconst requireRuleSchema: z.ZodType<RequireRule> = z.object({\n skill: skillRefInRules,\n needs: z.array(skillRefInRules).min(1),\n needsAny: z.boolean().exactOptional(),\n reason: z.string(),\n});\n\nconst alternativeGroupSchema: z.ZodType<AlternativeGroup> = z.object({\n purpose: z.string(),\n skills: z.array(skillRefInRules).min(1),\n});\n\nconst relationshipDefinitionsSchema: z.ZodType<RelationshipDefinitions> = z.object({\n conflicts: z.array(conflictRuleSchema),\n discourages: z.array(discourageRuleSchema),\n requires: z.array(requireRuleSchema),\n alternatives: z.array(alternativeGroupSchema),\n});\n\nexport const skillCategoriesFileSchema = z.object({\n version: z.string(),\n categories: z.record(z.string(), categoryDefinitionSchema),\n});\n\nexport const skillRulesFileSchema = z.object({\n version: z.string(),\n relationships: relationshipDefinitionsSchema.exactOptional(),\n});\n\nexport const localRawMetadataSchema = z\n .object({\n displayName: z.string(),\n slug: z.string() as z.ZodType<SkillSlug>,\n cliDescription: z.string().exactOptional(),\n category: categoryPathSchema,\n usageGuidance: z.string().exactOptional(),\n domain: z.string() as z.ZodType<Domain>,\n /** True if this skill was created outside the CLI's built-in vocabulary */\n custom: z.boolean().exactOptional(),\n })\n // Passthrough adds an index signature; LocalRawMetadata is the declared shape consumers read.\n .passthrough() as z.ZodType<LocalRawMetadata>;\n\n/** Metadata for local skills that were forked/copied from a marketplace skill */\nexport const localSkillMetadataSchema = z\n .object({\n forkedFrom: z\n .object({\n /** Lenient: custom and extra-source skills have non-builtin IDs */\n skillId: z.string() as z.ZodType<SkillId>,\n /** SHA hash of the original content at fork time (for diff detection) */\n contentHash: z.string(),\n date: z.string(),\n source: z.string().exactOptional(),\n /** Directory inside that repository, for a skill only its own bytes can install again */\n path: z.string().exactOptional(),\n })\n .exactOptional(),\n })\n // Passthrough adds an index signature, which LocalSkillMetadata declares too.\n .passthrough() as z.ZodType<LocalSkillMetadata>;\n\nconst stackSchema = z.object({\n id: z.string().min(1),\n name: z.string().min(1),\n description: z.string(),\n agents: z.record(z.string(), stackAgentConfigSchema),\n philosophy: z.string().exactOptional(),\n});\n\nexport const stacksConfigSchema = z.object({\n stacks: z.array(stackSchema).min(1),\n});\n\nconst marketplaceRemoteSourceSchema: z.ZodType<MarketplaceRemoteSource> = z.object({\n source: z.enum([\"github\", \"url\"]),\n repo: z.string().exactOptional(),\n url: z.string().exactOptional(),\n ref: z.string().exactOptional(),\n});\n\nconst marketplacePluginSchema: z.ZodType<MarketplacePlugin> = z.object({\n name: z.string().min(1),\n /** Local directory path (relative to pluginRoot) or remote source config */\n source: z.union([z.string(), marketplaceRemoteSourceSchema]),\n description: z.string().exactOptional(),\n version: z.string().exactOptional(),\n author: pluginAuthorSchema.exactOptional(),\n /** Lenient: external data may have any category string or none at all */\n category: z.string().exactOptional(),\n keywords: z.array(z.string()).exactOptional(),\n});\n\nconst marketplaceOwnerSchema: z.ZodType<MarketplaceOwner> = pluginAuthorSchema;\n\nconst marketplaceMetadataSchema: z.ZodType<MarketplaceMetadata> = z.object({\n /** Base directory for resolving plugin source paths (e.g., \"plugins/\") */\n pluginRoot: z.string().exactOptional(),\n});\n\n/** A `regex` message rather than a `refine`, so the generated JSON Schema keeps its `pattern`. */\nconst MARKETPLACE_NAME_REFUSAL =\n \"A marketplace name is kebab-case: lowercase letters, numbers and hyphens, starting with a letter (e.g. 'acme-skills'). Rename it in this manifest — Claude Code registers every plugin under it and accepts no other shape.\";\n\nexport const marketplaceSchema: z.ZodType<Marketplace> = z.object({\n $schema: z.string().exactOptional(),\n /** Kebab-case: the namespace Claude Code registers plugins under. */\n name: z.string().min(1).regex(KEBAB_CASE_PATTERN, { message: MARKETPLACE_NAME_REFUSAL }),\n version: z.string().min(1),\n description: z.string().exactOptional(),\n owner: marketplaceOwnerSchema,\n metadata: marketplaceMetadataSchema.exactOptional(),\n plugins: z.array(marketplacePluginSchema).min(1),\n});\n\n/**\n * Written beside a cached remote source so the next load can revalidate it in one request. No\n * `etag` means the host returned none, so the copy cannot be revalidated.\n */\nexport const sourceRevalidationSchema = z.object({\n /** The tarball URL giget resolved for this source. */\n tar: z.string().min(1),\n etag: z.string().min(1).exactOptional(),\n});\n\nconst permissionConfigSchema = z.object({\n allow: z.array(z.string()).exactOptional(),\n deny: z.array(z.string()).exactOptional(),\n});\n\n/** Settings file schema (.claude/settings.yaml) for project-level configuration */\nexport const settingsFileSchema = z\n .object({\n permissions: permissionConfigSchema.exactOptional(),\n })\n .passthrough();\n\nconst brandingConfigSchema = z.object({\n name: z.string().exactOptional(),\n});\n\nconst projectSourceConfigFields = z\n .object({\n /** A path or URL */\n marketplace: z.string().exactOptional(),\n author: z.string().exactOptional(),\n /** The name the marketplace's manifest gives it, which plugins are registered under */\n marketplaceName: z.string().exactOptional(),\n branding: brandingConfigSchema.exactOptional(),\n /** Custom skills directory override (default: \"src/skills\") */\n skillsDir: z.string().exactOptional(),\n /** Custom stacks file path override (default: \"config/stacks.ts\") */\n stacksFile: z.string().exactOptional(),\n /** Custom categories file path override (default: \"config/skill-categories.ts\") */\n categoriesFile: z.string().exactOptional(),\n /** Custom rules file path override (default: \"config/skill-rules.ts\") */\n rulesFile: z.string().exactOptional(),\n })\n .passthrough();\n\nexport const projectSourceConfigSchema = renamedFieldGuard.pipe(projectSourceConfigFields);\n\n/** A source agent's `metadata.yaml`; generates `agent.schema.json`. Custom ids allowed. */\nexport const agentYamlGenerationSchema = z\n .object({\n $schema: z.string().exactOptional(),\n id: z.string().min(1),\n title: z.string().min(1),\n description: z.string().min(1),\n model: modelNameSchema.exactOptional(),\n effort: effortLevelSchema.exactOptional(),\n tools: z.array(z.string()).min(1),\n disallowedTools: z.array(z.string()).exactOptional(),\n permissionMode: permissionModeSchema.exactOptional(),\n isolation: agentIsolationSchema.exactOptional(),\n hooks: strictHooksRecordSchema.exactOptional(),\n experimental: agentExperimentalSchema.exactOptional(),\n outputFormat: z.string().exactOptional(),\n domain: (z.string() as z.ZodType<Domain>).exactOptional(),\n custom: z.boolean().exactOptional(),\n })\n .strict();\n\n/** A compiled agent's frontmatter, sharing the loader's sub-schemas so whatever compiles reads. */\nexport const agentFrontmatterValidationSchema = z\n .object({\n /** Agent name in kebab-case (becomes the Task tool identifier) */\n name: z.string().regex(KEBAB_CASE_PATTERN).min(1),\n description: z.string().min(1),\n /** Comma-separated list of allowed tools */\n tools: z.string().exactOptional(),\n /** Comma-separated list of denied tools */\n disallowedTools: z.string().exactOptional(),\n model: modelNameSchema.exactOptional(),\n effort: effortLevelSchema.exactOptional(),\n permissionMode: permissionModeSchema.exactOptional(),\n isolation: agentIsolationSchema.exactOptional(),\n experimental: agentExperimentalSchema.exactOptional(),\n /** Skill names to preload (embed in agent prompt) */\n skills: z.array(z.string().min(1)).exactOptional(),\n hooks: strictHooksRecordSchema.exactOptional(),\n })\n .strict();\n\n/** Strict validation for SKILL.md frontmatter (matches Claude Code plugin spec) */\nexport const skillFrontmatterValidationSchema = z\n .object({\n name: z.string().min(1),\n description: z.string().min(1),\n /** If true, Claude cannot invoke this skill on its own */\n \"disable-model-invocation\": z.boolean().exactOptional(),\n /** If true, user can invoke this skill directly */\n \"user-invocable\": z.boolean().exactOptional(),\n /** Comma-separated list of tools this skill can use */\n \"allowed-tools\": z.string().exactOptional(),\n model: modelNameSchema.exactOptional(),\n /** \"fork\" means skill runs in a forked context (separate conversation) */\n context: z.enum([\"fork\"]).exactOptional(),\n /** Agent name this skill is scoped to */\n agent: z.string().exactOptional(),\n /** Hint text shown when user invokes the skill */\n \"argument-hint\": z.string().exactOptional(),\n })\n .strict();\n\n/** Not unified with localSkillMetadataSchema's forkedFrom, whose shape differs. */\nconst forkedFromSchema = z.object({\n skillId: z.string(),\n version: z.number().int().min(1).exactOptional(),\n contentHash: z.string(),\n source: z.string().exactOptional(),\n /** Directory inside that source, for a skill only its own bytes can install again */\n path: z.string().exactOptional(),\n date: z.string(),\n});\n\n/** Advisory: over-length is a warning; empty stays an error. */\nconst CLI_DESCRIPTION_MAX_LENGTH = 60;\n\n/** Shared by the strict and custom metadata schemas, which differ only in `category`/`slug`. */\nconst skillMetadataBaseSchema = z.object({\n author: z.string().regex(AUTHOR_HANDLE_PATTERN),\n displayName: z.string().min(1).max(30),\n cliDescription: z.string().min(1).max(CLI_DESCRIPTION_MAX_LENGTH),\n usageGuidance: z.string().min(10),\n contentHash: z\n .string()\n .regex(/^[a-f0-9]{7}$/)\n .exactOptional(),\n updated: z.string().exactOptional(),\n forkedFrom: forkedFromSchema.exactOptional(),\n domain: (z.string() as z.ZodType<Domain>).exactOptional(),\n /** True if this skill was created outside the CLI's built-in vocabulary */\n custom: z.boolean().exactOptional(),\n});\n\n/** As `unknownSkillSlugRefusal`, and points at `custom: true`. */\nfunction unknownMetadataSlugRefusal(input: unknown): string {\n const named = refusedInputNamed(input);\n return (\n `${named} is not a slug the public catalogue carries. A published skill's slug is held to ` +\n `that catalogue unless the skill declares it is not from it — add '${METADATA_KEYS.CUSTOM}: true' ` +\n `beside it in this ${STANDARD_FILES.METADATA_YAML} and the slug is read as your marketplace's ` +\n `own, any kebab-case name. That declaration is how a skill outside the catalogue's vocabulary ` +\n `is carried; a skill the catalogue does carry names its catalogue slug and leaves it off.`\n );\n}\n\nexport const metadataValidationSchema = skillMetadataBaseSchema\n .extend({\n category: z.enum(CATEGORIES),\n /** A known built-in slug, unless `custom: true` routes the file to the custom schema. */\n slug: z.enum(SKILL_SLUGS, {\n error: (issue) => unknownMetadataSlugRefusal(issue.input),\n }),\n })\n .strict();\n\nexport const customMetadataValidationSchema = skillMetadataBaseSchema.extend({\n category: z.string(),\n slug: z.string().regex(KEBAB_CASE_PATTERN).min(1).max(50),\n});\n\nconst stackSkillAssignmentSchema = z\n .object({\n id: z.string().min(1),\n /** If true, skill content is embedded in the compiled agent prompt */\n preloaded: z.boolean().exactOptional(),\n })\n .strict();\n\nexport const stackConfigValidationSchema = z\n .object({\n id: z.string().regex(KEBAB_CASE_PATTERN).exactOptional(),\n name: z.string().min(1),\n version: z.string(),\n author: z.string().min(1),\n description: z.string().exactOptional(),\n created: z.string().exactOptional(),\n updated: z.string().exactOptional(),\n framework: z.string().exactOptional(),\n skills: z.array(stackSkillAssignmentSchema).min(1),\n agents: z.array(z.string().regex(KEBAB_CASE_PATTERN)).min(1),\n agentSkills: z\n .record(z.string(), z.record(z.string(), z.array(stackSkillAssignmentSchema)))\n .exactOptional(),\n philosophy: z.string().exactOptional(),\n principles: z.array(z.string().min(1)).exactOptional(),\n tags: z.array(z.string().regex(KEBAB_CASE_PATTERN)).exactOptional(),\n overrides: z\n .record(\n z.string(),\n z\n .object({\n alternatives: z.array(z.string().min(1)).exactOptional(),\n locked: z.boolean().exactOptional(),\n })\n .strict(),\n )\n .exactOptional(),\n metrics: z\n .object({\n upvotes: z.number().int().min(0).exactOptional(),\n downloads: z.number().int().min(0).exactOptional(),\n })\n .strict()\n .exactOptional(),\n hooks: strictHooksRecordSchema.exactOptional(),\n })\n .strict();\n\nexport function formatZodIssues(issues: z.ZodIssue[]): string {\n return issues.map(formatZodIssue).join(\"; \");\n}\n\n/** The one place the custom-vs-strict schema choice lives. */\nexport function validateSkillMetadata(rawMetadata: unknown) {\n const schema = isCustomMetadata(rawMetadata)\n ? customMetadataValidationSchema\n : metadataValidationSchema;\n return schema.safeParse(rawMetadata);\n}\n\n/**\n * Lists absent required fields as missing, where Zod says \"expected string, received undefined\".\n */\nexport function describeMetadataSchemaFailure(\n issues: z.ZodIssue[],\n rawMetadata: Record<string, unknown>,\n): string {\n const [absent, malformed] = partition(issues, (issue) => isAbsentField(issue, rawMetadata));\n return [\n ...(absent.length > 0 ? [nameMissingFields(absent)] : []),\n ...malformed.map(formatZodIssue),\n ].join(\"; \");\n}\n\nfunction isAbsentField(issue: z.ZodIssue, rawMetadata: Record<string, unknown>): boolean {\n const [field, ...nested] = issue.path;\n return nested.length === 0 && typeof field === \"string\" && rawMetadata[field] === undefined;\n}\n\nfunction nameMissingFields(absent: z.ZodIssue[]): string {\n const fields = absent.map((issue) => issue.path.join(\".\"));\n return `missing required ${fields.length === 1 ? \"field\" : \"fields\"}: ${fields.join(\", \")}`;\n}\n\nexport type MetadataIssueSplit = {\n errors: string[];\n warnings: string[];\n};\n\nfunction isOverLengthCliDescription(issue: z.ZodIssue): boolean {\n return issue.code === \"too_big\" && issue.path.length === 1 && issue.path[0] === \"cliDescription\";\n}\n\nfunction readCliDescription(raw: unknown): string | undefined {\n if (!isRecord(raw)) return undefined;\n const value = raw.cliDescription;\n return typeof value === \"string\" ? value : undefined;\n}\n\n/** The undefined branch is defensive: too_big only fires on a string. */\nfunction formatOverLengthWarning(issue: z.ZodIssue, cliDescription: string | undefined): string {\n if (cliDescription === undefined) return formatZodIssue(issue);\n return `cliDescription is ${cliDescription.length} characters — exceeds the recommended maximum of ${CLI_DESCRIPTION_MAX_LENGTH}`;\n}\n\nexport function splitMetadataValidationIssues(\n error: z.ZodError,\n rawMetadata: unknown,\n): MetadataIssueSplit {\n const [overLength, hardFailures] = partition(error.issues, isOverLengthCliDescription);\n\n const cliDescription = readCliDescription(rawMetadata);\n const warnings = overLength.map((issue) => formatOverLengthWarning(issue, cliDescription));\n\n return { errors: hardFailures.map(formatZodIssue), warnings };\n}\n\nexport function validateNestingDepth(value: unknown, maxDepth: number): boolean {\n function check(val: unknown, depth: number): boolean {\n if (depth > maxDepth) return false;\n if (Array.isArray(val)) {\n return val.every((item) => check(item, depth + 1));\n }\n if (val !== null && typeof val === \"object\") {\n return Object.values(val).every((v) => check(v, depth + 1));\n }\n return true;\n }\n return check(value, 0);\n}\n\nfunction isCustomMetadata(raw: unknown): boolean {\n return isRecord(raw) && raw.custom === true;\n}\n\n/**\n * For files this CLI owns (marketplace.json), whose `.passthrough()` keeps forward compatibility.\n * Not for another tool's files: their unknown keys are that tool's business.\n */\nexport function warnUnknownFields(\n parsed: Record<string, unknown>,\n expectedKeys: readonly string[],\n context: string,\n): void {\n const expectedSet = new Set(expectedKeys);\n const unknownKeys = Object.keys(parsed).filter((k) => !expectedSet.has(k));\n if (unknownKeys.length > 0) {\n warn(`Unknown fields in ${context}: ${unknownKeys.join(\", \")}`);\n }\n}\n","import { z } from \"zod\";\n\nimport { stripTerminalControls } from \"../utils/string\";\n\n/** Sanitised here: every part of the rendered text comes from the refused, untrusted document. */\nexport function formatZodIssue(issue: z.ZodIssue): string {\n const path = stripTerminalControls(issue.path.join(\".\"));\n if (issue.code === \"unrecognized_keys\") {\n return `Unrecognized key: \"${stripTerminalControls(issue.keys.join('\", \"'))}\"`;\n }\n return path\n ? `${path}: ${stripTerminalControls(issue.message)}`\n : stripTerminalControls(issue.message);\n}\n\nexport function formatZodErrors(error: z.ZodError): string[] {\n return error.issues.map(formatZodIssue);\n}\n","// Vendored into packages/matrix/src/vendor/; any edit needs `bun run generate:matrix`.\n\nimport type { CategoryPath, SkillSlug, SkillId } from \"./skills\";\nimport type { AgentName } from \"./agents\";\n\nexport type { Category, Domain } from \"./generated/source-types\";\nexport { CATEGORIES } from \"./generated/source-types\";\n\nimport type { Category, Domain } from \"./generated/source-types\";\n\nexport const MODEL_NAMES = [\"sonnet\", \"opus\", \"haiku\", \"fable\", \"inherit\"] as const;\nexport type ModelName = (typeof MODEL_NAMES)[number];\n\n/** From `codex debug models --bundled`; `gpt-5.5` is left out because it refuses `max`. */\nexport const CODEX_MODEL_NAMES = [\n \"gpt-6-astra\",\n \"gpt-5.6-sol\",\n \"gpt-5.6-terra\",\n \"gpt-5.6-luna\",\n] as const;\nexport type CodexModelName = (typeof CODEX_MODEL_NAMES)[number];\n\nexport const EFFORT_NAMES = [\"low\", \"medium\", \"high\", \"xhigh\", \"max\"] as const;\nexport type EffortLevel = (typeof EFFORT_NAMES)[number];\n\nexport const PERMISSION_MODES = [\n \"default\",\n \"acceptEdits\",\n \"dontAsk\",\n \"bypassPermissions\",\n \"plan\",\n \"delegate\",\n] as const;\nexport type PermissionMode = (typeof PERMISSION_MODES)[number];\n\nexport const AGENT_ISOLATIONS = [\"worktree\"] as const;\nexport type AgentIsolation = (typeof AGENT_ISOLATIONS)[number];\n\n/** Never defaulted: `1h` bills cache writes at a higher rate. */\nexport const CACHE_TTLS = [\"5m\", \"1h\"] as const;\nexport type CacheTtl = (typeof CACHE_TTLS)[number];\n\n/** Partial: a marketplace may define only some categories. */\nexport type CategoryMap = Partial<Record<Category, CategoryDefinition>>;\n\nexport type CategoryDefinition = {\n id: Category;\n displayName: string;\n description: string;\n domain?: Domain;\n exclusive: boolean;\n /** Within domain, lower first. */\n order: number;\n icon?: string;\n};\n\nexport type RelationshipDefinitions = {\n conflicts: ConflictRule[];\n /** Warns but doesn't disable. */\n discourages: DiscourageRule[];\n requires: RequireRule[];\n alternatives: AlternativeGroup[];\n};\n\ntype SkillGroupRule = {\n skills: SkillSlug[];\n reason: string;\n};\n\nexport type ConflictRule = SkillGroupRule;\n\nexport type DiscourageRule = SkillGroupRule;\n\nexport type RequireRule = {\n skill: SkillSlug;\n needs: SkillSlug[];\n /** OR over `needs` when true; AND otherwise. */\n needsAny?: boolean;\n reason: string;\n};\n\nexport type AlternativeGroup = {\n purpose: string;\n skills: SkillSlug[];\n};\n\nexport type SkillRulesConfig = {\n version: string;\n relationships: RelationshipDefinitions;\n};\n\n/** Partial: only extracted skills are present. */\nexport type SkillSlugMap = {\n slugToId: Partial<Record<SkillSlug, SkillId>>;\n};\n\nexport type MergedSkillsMatrix = {\n version: string;\n categories: CategoryMap;\n skills: Partial<Record<SkillId, ResolvedSkill>>;\n suggestedStacks: ResolvedStack[];\n slugMap: SkillSlugMap;\n /** Rule slugs no skill carries, for `checkMatrixHealth`. */\n unresolvedSlugs?: SkillSlug[];\n generatedAt: string;\n};\n\ntype SkillCore = {\n id: SkillId;\n slug: SkillSlug;\n displayName: string;\n /** `cliDescription` from metadata.yaml when stated. */\n description: string;\n /** The SKILL.md frontmatter `description`. */\n activationDescription?: string;\n usageGuidance?: string;\n category: CategoryPath;\n author: string;\n /** Relative to src/. */\n path: string;\n /** From .claude/skills/ */\n local?: boolean;\n localPath?: string;\n /** Outside the CLI's built-in vocabulary. */\n custom?: boolean;\n};\n\nexport type ResolvedSkill = SkillCore & {\n conflictsWith: SkillRelation[];\n requires: SkillRequirement[];\n /** Informational, not enforced. */\n alternatives: SkillAlternative[];\n discourages: SkillRelation[];\n availableSources?: SkillSource[];\n activeSource?: SkillSource;\n};\n\nexport type SkillRelation = {\n skillId: SkillId;\n reason: string;\n};\n\nexport type SkillRequirement = {\n skillIds: SkillId[];\n /** OR when true; AND otherwise. */\n needsAny: boolean;\n reason: string;\n};\n\nexport type SkillAlternative = {\n skillId: SkillId;\n purpose: string;\n};\n\nexport type ResolvedStack = {\n id: string;\n name: string;\n description: string;\n skills: Partial<Record<AgentName, Partial<Record<Category, SkillId[]>>>>;\n allSkillIds: SkillId[];\n philosophy: string;\n group?: string;\n};\n\nexport type SkillSourceType = \"public\" | \"private\" | \"local\";\n\n/** Derived from SkillConfig.origin. */\nexport type InstallMode = \"eject\" | \"plugin\" | \"mixed\";\n\nexport type SkillSource = {\n /** \"public\", a marketplace name, or \"local\" */\n name: string;\n type: SkillSourceType;\n url?: string;\n installed: boolean;\n /** On-disk install mode, separate from provenance. */\n installMode?: Exclude<InstallMode, \"mixed\">;\n primary?: boolean;\n};\n\nexport type SelectionValidation = {\n valid: boolean;\n errors: ValidationError[];\n};\n\nexport type ValidationError = {\n type: \"conflict\" | \"missingRequirement\" | \"categoryExclusive\";\n message: string;\n skills: SkillId[];\n};\n\nexport type ExtractedSkillMetadata = SkillCore & {\n /** e.g. \"web/framework/react\" */\n directoryPath: string;\n domain: Domain;\n};\n","import path from \"path\";\nimport { fileURLToPath } from \"url\";\nimport { createJiti } from \"jiti\";\nimport { fileExists } from \"../../utils/fs\";\nimport { verbose } from \"../../utils/logger\";\nimport { getErrorMessage } from \"../../utils/errors\";\nimport { isRecord } from \"../../utils/type-guards\";\nimport { formatZodIssues } from \"../schemas\";\nimport type { z } from \"zod\";\n\n/** Resolve agents-inc/config to the source config-exports.ts so jiti can load it in dev. */\nconst CONFIG_EXPORTS_PATH = path.resolve(\n path.dirname(fileURLToPath(import.meta.url)),\n \"../../config-exports.ts\",\n);\n\n/** The config evaluated but the schema refused its shape; never report this as \"no config\". */\nexport class ConfigSchemaError extends Error {\n constructor(\n readonly configPath: string,\n readonly issues: string,\n ) {\n super(`Config validation failed at '${configPath}': ${issues}`);\n this.name = \"ConfigSchemaError\";\n }\n}\n\n/** The config evaluated but exports only named bindings, so its contents are not at fault. */\nexport class ConfigDefaultExportError extends Error {\n constructor(readonly configPath: string) {\n super(`Config at '${configPath}' has no default export`);\n this.name = \"ConfigDefaultExportError\";\n }\n}\n\n/**\n * Tells `export const x = {}` (named exports) from CommonJS `module.exports = { x }` (the default).\n */\nconst ES_MODULE_MARKER = \"__esModule\";\n\n/**\n * The default export, or the namespace when there is none; imported whole to tell the two apart.\n */\nfunction unwrapDefaultExport(namespace: unknown): unknown {\n if (isRecord(namespace) && namespace.default !== undefined) return namespace.default;\n return namespace;\n}\n\nfunction declaresNoDefaultExport(namespace: unknown): boolean {\n return isRecord(namespace) && ES_MODULE_MARKER in namespace && !(\"default\" in namespace);\n}\n\n/** Why a reader that found the file rejects one `loadConfig` answers `null` for. */\nexport const NO_VALID_DEFAULT_EXPORT = \"the file has no valid default export\";\n\n/** Nothing was exported: an empty file, `export {}`, or a default export with no keys. */\nfunction exportsNothing(value: unknown): boolean {\n return value == null || (typeof value === \"object\" && Object.keys(value).length === 0);\n}\n\n/** Null when absent or exporting nothing; throws for named-only exports, refusals and breakage. */\nexport async function loadConfig<T>(configPath: string, schema?: z.ZodType<T>): Promise<T | null> {\n if (!(await fileExists(configPath))) {\n verbose(`Config not found at ${configPath}`);\n return null;\n }\n\n const namespace = await importConfigModule(configPath);\n const raw = unwrapDefaultExport(namespace);\n\n // An empty file reads as missing, asked before the export question since it declares no exports.\n if (exportsNothing(raw)) {\n verbose(`Config at ${configPath} exports nothing`);\n return null;\n }\n\n if (declaresNoDefaultExport(namespace)) {\n throw new ConfigDefaultExportError(configPath);\n }\n\n if (schema) {\n const result = schema.safeParse(raw);\n if (!result.success) {\n throw new ConfigSchemaError(configPath, formatZodIssues(result.error.issues));\n }\n return result.data;\n }\n\n // Boundary cast: jiti returns unknown, caller provides expected type\n return raw as T;\n}\n\n/** A fresh engine and no module cache: one run writes a config and reads it back several times. */\nasync function importConfigModule(configPath: string): Promise<unknown> {\n try {\n const jiti = createJiti(import.meta.url, {\n moduleCache: false,\n interopDefault: true,\n alias: { \"agents-inc/config\": CONFIG_EXPORTS_PATH },\n });\n return await jiti.import(configPath);\n } catch (error) {\n throw new Error(`Failed to load config from '${configPath}': ${getErrorMessage(error)}`, {\n cause: error,\n });\n }\n}\n","import path from \"path\";\nimport type { Provider } from \"../../consts.js\";\nimport type { SkillScope } from \"../../types/config.js\";\nimport { STANDARD_FILES } from \"../../consts.js\";\nimport {\n agentsDir,\n installBaseDir,\n providerInUse,\n skillsDir,\n sourceFolderInUse,\n} from \"./install-layout.js\";\n\nexport { installBaseDir };\n\nexport function getProjectConfigPath(dir: string, provider: Provider): string {\n return path.join(sourceFolderInUse(dir, provider).dir, STANDARD_FILES.CONFIG_TS);\n}\n\nexport function getInstalledConfigPath(dir: string): string {\n return getProjectConfigPath(dir, providerInUse(dir));\n}\n\nexport type InstallPaths = {\n skillsDir: string;\n agentsDir: string;\n configPath: string;\n};\n\nexport function resolveInstallPaths(\n projectDir: string,\n scope: SkillScope = \"project\",\n): InstallPaths {\n const baseDir = installBaseDir(projectDir, scope);\n // Read once so all three paths name the same installation.\n const provider = providerInUse(baseDir);\n\n return {\n skillsDir: skillsDir(provider, scope, projectDir),\n agentsDir: agentsDir(provider, scope, projectDir),\n configPath: getProjectConfigPath(baseDir, provider),\n };\n}\n","import fs from \"fs\";\n\nimport { PROVIDERS, type Provider } from \"../../consts.js\";\nimport { getProjectConfigPath } from \"./install-base-dir.js\";\n\n/**\n * `provider`, where `root` also holds another provider's installation: there every acting command\n * refuses until it is told which, so a command handed out for this one must name it. Synchronous,\n * because the error that carries it is built where it is thrown.\n */\nexport function providerToNameAt(root: string, provider: Provider): Provider | undefined {\n const besideAnother = PROVIDERS.some(\n (other) => other !== provider && fs.existsSync(getProjectConfigPath(root, other)),\n );\n return besideAnother ? provider : undefined;\n}\n","import { seatDiagnostics } from \"@workspace/compile\";\n\nimport { verbose, warn } from \"../utils/logger\";\n\n/**\n * Hands `@workspace/compile` this CLI's console; the package runs in a browser and cannot import\n * `utils/logger`. A side-effect import, so a test's `vi.mock` of the logger still reaches the sink.\n */\nseatDiagnostics({ warn, verbose });\n","import {\n AGENT_NAMES,\n CODEX_MODEL_NAMES,\n isSeedScopePairWritable,\n resolveAssignment,\n resolveLoadState,\n seedAgentScope,\n SKILL_IDS,\n type LoadState,\n type SeedAgent,\n type SeedLoadState,\n type SeedPayload,\n type SeedSkill,\n type SkillTaxonomy,\n} from \"@workspace/matrix\"\nimport { groupBy, indexBy, isDefined, mapValues, omit, partition } from \"remeda\"\n\nimport {\n byCategoryDeclarationOrder,\n categoryDomain,\n type CatalogSkill,\n type CompileCatalog,\n} from \"./catalog.js\"\nimport { seatedCatalog } from \"./catalog-seat.js\"\nimport { HAND_WRITTEN_FIELDS } from \"./config-source.js\"\nimport { diagnostics } from \"./diagnostics.js\"\nimport { orderDomains } from \"./domain-order.js\"\nimport {\n CLI_INVOKE_COMMAND,\n DEFAULT_PUBLIC_SOURCE_NAME,\n EJECT_SOURCE,\n GLOBAL_CONFIG_NAME,\n LOCAL_PSEUDO_CATEGORY,\n} from \"./paths.js\"\nimport {\n activeAgentScopeMap,\n effectivelyExcludedSkillIds,\n isActiveAt,\n} from \"./scope-predicates.js\"\nimport { validateSelection } from \"./selection.js\"\nimport { inAnEnglishList } from \"./string.js\"\nimport { typedEntries, typedFromEntries, typedKeys } from \"./typed-object.js\"\nimport type {\n AgentName,\n AgentScopeConfig,\n Category,\n CodexModelName,\n CategoryPath,\n Domain,\n ProjectConfig,\n SelectionValidation,\n SkillAssignment,\n SkillConfig,\n SkillId,\n SkillScope,\n Stack,\n StackAgentConfig,\n} from \"./types.js\"\n\nexport type SplitConfigResult = {\n global: ProjectConfig\n project: ProjectConfig\n}\n\nexport type ProjectConfigOptions = {\n description?: string\n author?: string\n}\n\nconst MATRIX_SAMPLE_SIZE = 5\n\nconst SCOPE_CONFIG_NAMES = {\n skill: { list: \"skillConfigs\", entry: \"SkillConfig\" },\n agent: { list: \"agentConfigs\", entry: \"AgentScopeConfig\" },\n} as const\n\ntype StackBuildInputs = {\n agentList: AgentName[]\n activeSkillsByCategory: Map<Category, SkillId[]>\n skillScope: Map<SkillId, SkillScope>\n agentScope: Map<AgentName, SkillScope>\n existingStack: Partial<Record<AgentName, StackAgentConfig>>\n catalog: CompileCatalog\n newlyAddedSkillIds: ReadonlySet<SkillId> | undefined\n scopeEligibilityGained: ReadonlySet<string> | undefined\n}\n\ntype ResolvedSkillEntry = { skillId: SkillId; category: Category }\n\n/**\n * Rebuilds the stack (agent -> category -> SkillAssignment[]) from the current selection and any\n * prior stack. A triple lands when the agent and skill are selected and active, the skill's scope\n * reaches the agent, and it is either already in the prior stack or targeted by the shared\n * resolver. Prior triples keep their load state; new ones take the shared mapping's default.\n * The catalogue comes from {@link seatedCatalog}.\n */\nexport function generateProjectConfigFromSkills(\n name: string,\n selectedSkillIds: SkillId[],\n options?: ProjectConfigOptions & {\n selectedAgents?: AgentName[]\n skillConfigs?: SkillConfig[]\n agentConfigs?: AgentScopeConfig[]\n existingStack?: Partial<Record<AgentName, StackAgentConfig>>\n /**\n * Skills new to this session. Passing it, even empty, opts into per-agent curation\n * preservation; undefined seeds everything.\n */\n newlyAddedSkillIds?: readonly SkillId[]\n /**\n * Scope-compatibility gains `newlyAddedSkillIds` cannot express; see {@link\n * scopeEligibilityKey}.\n */\n scopeEligibilityGained?: ReadonlySet<string>\n }\n): ProjectConfig {\n const catalog = seatedCatalog()\n const agentList = options?.selectedAgents\n ? [...options.selectedAgents].sort()\n : []\n if (agentList.length > 0) {\n assertScopeConfigsGiven(options?.skillConfigs, options?.agentConfigs)\n }\n\n // Empty only when agentList is, and then no scope work runs.\n const skillConfigs = options?.skillConfigs ?? []\n const agentConfigs = options?.agentConfigs ?? []\n\n diagnostics().verbose(\n `generateProjectConfigFromSkills: ${selectedSkillIds.length} skills, ` +\n `matrix has ${typedKeys<SkillId>(catalog.skills).length} entries, ` +\n `agents=[${agentList.join(\", \")}]`\n )\n const { validSkills, foundCount, absentSkillIds } = resolveValidSkills(\n selectedSkillIds,\n skillConfigs,\n catalog\n )\n reportAbsentSkills(absentSkillIds, catalog)\n diagnostics().verbose(\n `generateProjectConfigFromSkills: ${foundCount} found, ${absentSkillIds.length} not found, ` +\n `${agentList.length} agents in stack`\n )\n\n const stack = buildStackForSelection({\n agentList,\n activeSkillsByCategory: skillIdsByCategory(validSkills),\n skillScope: buildSkillScopeMap(skillConfigs),\n agentScope: activeAgentScopeMap(agentConfigs),\n existingStack: options?.existingStack ?? {},\n catalog,\n newlyAddedSkillIds:\n options?.newlyAddedSkillIds === undefined\n ? undefined\n : new Set(options.newlyAddedSkillIds),\n scopeEligibilityGained: options?.scopeEligibilityGained,\n })\n\n return {\n name,\n agents: [\n ...resolveActiveAgentConfigs(agentList, options?.agentConfigs),\n ...agentConfigs.filter((ac) => ac.excluded),\n ],\n skills: options?.skillConfigs ?? asProjectCopies(selectedSkillIds),\n ...(stack && { stack }),\n ...(options?.description && { description: options.description }),\n ...(options?.author && { author: options.author }),\n }\n}\n\nexport function isScopePairCompatible(\n skillScope: SkillScope,\n agentScope: SkillScope\n): boolean {\n return isSeedScopePairWritable(skillScope, agentScope)\n}\n\nexport function scopeEligibilityKey(\n agent: AgentName,\n skillId: SkillId\n): string {\n return `${agent}|${skillId}`\n}\n\nfunction assertScopeConfigsGiven(\n skillConfigs: SkillConfig[] | undefined,\n agentConfigs: AgentScopeConfig[] | undefined\n): void {\n if (!skillConfigs) {\n throw new Error(\n `generateProjectConfigFromSkills: selectedAgents was passed without skillConfigs. ` +\n `Callers must pass a SkillConfig for every selected skill.`\n )\n }\n if (!agentConfigs) {\n throw new Error(\n `generateProjectConfigFromSkills: selectedAgents was passed without agentConfigs. ` +\n `Callers must pass an AgentScopeConfig for every selected agent.`\n )\n }\n}\n\nfunction resolveValidSkills(\n selectedSkillIds: SkillId[],\n skillConfigs: SkillConfig[],\n catalog: CompileCatalog\n): {\n validSkills: ResolvedSkillEntry[]\n foundCount: number\n absentSkillIds: SkillId[]\n} {\n const [found, absent] = partition(\n selectedSkillIds.map((skillId) => ({\n skillId,\n skill: catalog.skills[skillId],\n })),\n isInCatalog\n )\n\n const excludedSkillIds = effectivelyExcludedSkillIds(skillConfigs)\n const validSkills = found\n .map(({ skillId, skill }) => ({\n skillId,\n // Boundary cast: a catalogue category id is a CategoryPath.\n category: extractCategoryFromPath(skill.category as CategoryPath),\n }))\n .filter(hasCategory)\n .filter((entry) => !excludedSkillIds.has(entry.skillId))\n\n return {\n validSkills,\n foundCount: found.length,\n absentSkillIds: absent.map((entry) => entry.skillId),\n }\n}\n\nfunction isInCatalog(entry: {\n skillId: SkillId\n skill: CatalogSkill | undefined\n}): entry is { skillId: SkillId; skill: CatalogSkill } {\n return entry.skill != null\n}\n\nfunction hasCategory(entry: {\n skillId: SkillId\n category: Category | undefined\n}): entry is ResolvedSkillEntry {\n return entry.category != null\n}\n\nfunction extractCategoryFromPath(\n categoryPath: CategoryPath\n): Category | undefined {\n if (categoryPath === LOCAL_PSEUDO_CATEGORY) return undefined\n return categoryPath\n}\n\nfunction reportAbsentSkills(\n absentSkillIds: SkillId[],\n catalog: CompileCatalog\n): void {\n if (absentSkillIds.length === 0) return\n\n for (const skillId of absentSkillIds) {\n diagnostics().warn(absentSkillWarning(skillId))\n }\n\n const matrixSample = typedKeys<SkillId>(catalog.skills)\n .slice(0, MATRIX_SAMPLE_SIZE)\n .join(\", \")\n diagnostics().verbose(\n `${absentSkillIds.length} skills absent from the matrix. Matrix keys sample: [${matrixSample}]`\n )\n}\n\nfunction absentSkillWarning(skillId: SkillId): string {\n return (\n `Skill '${skillId}' is not in this marketplace — it stays in the configuration and no ` +\n `sub-agent is given it. Run '${CLI_INVOKE_COMMAND} update' to refresh the marketplace, or ` +\n `remove it with '${CLI_INVOKE_COMMAND} edit'.`\n )\n}\n\nfunction skillIdsByCategory(\n skills: ResolvedSkillEntry[]\n): Map<Category, SkillId[]> {\n return new Map(\n typedEntries(groupBy(skills, (entry) => entry.category)).map(\n ([category, entries]) => [category, entries.map((entry) => entry.skillId)]\n )\n )\n}\n\n/** Excluded entries spread first, so an active entry for the same skill wins. */\nfunction buildSkillScopeMap(\n skillConfigs: SkillConfig[]\n): Map<SkillId, SkillScope> {\n const [excludedConfigs, activeConfigs] = partition(skillConfigs, (s) =>\n Boolean(s.excluded)\n )\n return new Map(\n [...excludedConfigs, ...activeConfigs].map((s) => [s.id, s.scope])\n )\n}\n\nfunction buildStackForSelection(\n inputs: StackBuildInputs\n): Partial<Record<AgentName, StackAgentConfig>> | undefined {\n // No agents in play: `undefined` omits the key, so the merger keeps the existing stack.\n if (inputs.agentList.length === 0) {\n diagnostics().verbose(\n `buildStackForSelection: no agents — returning undefined (stack untouched)`\n )\n return undefined\n }\n\n // Agents in play: `{}` is a real \"nothing preloads\" result the merger trusts. `undefined`\n // would resurrect the stale stack.\n return typedFromEntries(\n inputs.agentList\n .map((agent) => [agent, buildAgentStack(agent, inputs)] as const)\n .filter(([, agentStack]) => hasCategories(agentStack))\n )\n}\n\nfunction buildAgentStack(\n agent: AgentName,\n inputs: StackBuildInputs\n): StackAgentConfig {\n return typedFromEntries(\n inCanonicalCategoryOrder(inputs.activeSkillsByCategory, inputs.catalog)\n .map(\n ([category, skillIds]) =>\n [category, assignmentsFor(agent, category, skillIds, inputs)] as const\n )\n .filter(([, assignments]) => assignments.length > 0)\n )\n}\n\nfunction hasCategories(agentStack: StackAgentConfig): boolean {\n return typedKeys<Category>(agentStack).length > 0\n}\n\n/**\n * Catalogue declaration order, so the same selection always emits the same bytes. The writer holds\n * the same rule for a stack it did not build.\n */\nfunction inCanonicalCategoryOrder(\n activeSkillsByCategory: Map<Category, SkillId[]>,\n catalog: CompileCatalog\n): [Category, SkillId[]][] {\n const byDeclaration = byCategoryDeclarationOrder(catalog)\n return [...activeSkillsByCategory].sort(([a], [b]) => byDeclaration(a, b))\n}\n\nfunction assignmentsFor(\n agent: AgentName,\n category: Category,\n skillIds: SkillId[],\n inputs: StackBuildInputs\n): SkillAssignment[] {\n return skillIds\n .filter((id) => isScopeCompatible(agent, id, inputs))\n .filter((id) => survivesCuration(agent, category, id, inputs))\n .filter((id) => isPreservedOrRelevant(agent, category, id, inputs))\n .map((id) => toStackAssignment(id, agent, category, inputs))\n}\n\nfunction isScopeCompatible(\n agent: AgentName,\n skillId: SkillId,\n inputs: StackBuildInputs\n): boolean {\n return isScopePairCompatible(\n getScopeOrThrow(inputs.skillScope, skillId, \"skill\"),\n getScopeOrThrow(inputs.agentScope, agent, \"agent\")\n )\n}\n\nfunction getScopeOrThrow<K>(\n map: Map<K, SkillScope>,\n key: K,\n kind: keyof typeof SCOPE_CONFIG_NAMES\n): SkillScope {\n const scope = map.get(key)\n if (scope !== undefined) return scope\n\n const { list, entry } = SCOPE_CONFIG_NAMES[kind]\n throw new Error(\n `generateProjectConfigFromSkills: ${kind} '${String(key)}' missing from ${list}. ` +\n `Caller must pass a ${entry} for every selected ${kind}.`\n )\n}\n\n/**\n * An existing agent keeps what its prior stack had, appends skills in `newlyAddedSkillIds` or\n * pairs in `scopeEligibilityGained`, and omits the rest (the user removed them).\n */\nfunction survivesCuration(\n agent: AgentName,\n category: Category,\n skillId: SkillId,\n inputs: StackBuildInputs\n): boolean {\n const { existingStack, newlyAddedSkillIds, scopeEligibilityGained } = inputs\n const isNewAgent = existingStack[agent] === undefined\n if (newlyAddedSkillIds === undefined || isNewAgent) return true\n\n return (\n isInPriorStack(existingStack, agent, category, skillId) ||\n newlyAddedSkillIds.has(skillId) ||\n scopeEligibilityGained?.has(scopeEligibilityKey(agent, skillId)) === true\n )\n}\n\nfunction isPreservedOrRelevant(\n agent: AgentName,\n category: Category,\n skillId: SkillId,\n inputs: StackBuildInputs\n): boolean {\n return (\n isInPriorStack(inputs.existingStack, agent, category, skillId) ||\n isRelevantPair(inputs.catalog, skillId, category, agent)\n )\n}\n\nfunction isRelevantPair(\n catalog: CompileCatalog,\n skillId: SkillId,\n category: Category,\n agent: AgentName\n): boolean {\n return resolveAssignment(taxonomyOrIdOf(catalog, skillId, category)).some(\n (target) => target.agentId === agent\n )\n}\n\n/**\n * Targeting reads a domain and category, not catalog membership, so a marketplace skill is placed\n * by the LOADED catalogue's taxonomy. A category with no domain sends the id alone.\n */\nfunction taxonomyOrIdOf(\n catalog: CompileCatalog,\n skillId: SkillId,\n category: Category\n): SkillId | SkillTaxonomy {\n // Boundary cast: a catalogue category's `domain` is a Domain, typed `string` on the narrow\n // catalogue shape so the wire `Matrix` satisfies it too.\n const domainId = categoryDomain(catalog, category) as Domain | undefined\n if (domainId === undefined) return skillId\n\n return { id: skillId, domainId, categoryId: category }\n}\n\nfunction toStackAssignment(\n id: SkillId,\n agent: AgentName,\n category: Category,\n inputs: StackBuildInputs\n): SkillAssignment {\n const prior = priorLoadState(inputs.existingStack, agent, category, id)\n const load = prior ?? mappedLoadState(id, agent)\n\n return load === \"preloaded\" ? { id, preloaded: true } : { id }\n}\n\n/**\n * The generator writes `preloaded` only where true, so a bare `{ id }` read back is the user's\n * curated lazy and outranks any default.\n */\nfunction priorLoadState(\n existingStack: Partial<Record<AgentName, StackAgentConfig>>,\n agent: AgentName,\n category: Category,\n skillId: SkillId\n): LoadState | undefined {\n const prior = existingStack[agent]?.[category]?.find((a) => a.id === skillId)\n if (prior === undefined) return undefined\n\n return prior.preloaded === true ? \"preloaded\" : \"lazy\"\n}\n\nfunction isInPriorStack(\n existingStack: Partial<Record<AgentName, StackAgentConfig>>,\n agent: AgentName,\n category: Category,\n skillId: SkillId\n): boolean {\n return priorLoadState(existingStack, agent, category, skillId) !== undefined\n}\n\n/**\n * The same table the editor's default assignments read. Only catalog skills on roster agents are\n * put to it: a local or marketplace skill, or a hand-written agent, is lazy by rule.\n * `resolveLoadState` throws on unknown ids, and catching that would be a silent fallback.\n */\nfunction mappedLoadState(skillId: SkillId, agent: AgentName): LoadState {\n if (!isSkillId(skillId) || !isAgentName(agent)) return \"lazy\"\n\n return resolveLoadState({ skillId, agentId: agent })\n}\n\nfunction isAgentName(value: string): value is AgentName {\n return (AGENT_NAMES as readonly string[]).includes(value)\n}\n\nfunction isSkillId(value: string): value is SkillId {\n return (SKILL_IDS as readonly string[]).includes(value)\n}\n\nfunction resolveActiveAgentConfigs(\n agentList: AgentName[],\n providedConfigs: AgentScopeConfig[] | undefined\n): AgentScopeConfig[] {\n if (providedConfigs === undefined) {\n return agentList.map((name) => ({ name, scope: \"project\" as const }))\n }\n\n const activeByName = indexBy(\n providedConfigs.filter((a) => !a.excluded),\n (a) => a.name\n )\n return agentList.map((agentName) => {\n const active = activeByName[agentName]\n if (!active) {\n throw new Error(\n `generateProjectConfigFromSkills: selected agent '${agentName}' has no ` +\n `non-excluded AgentScopeConfig in agentConfigs.`\n )\n }\n return active\n })\n}\n\nfunction asProjectCopies(skillIds: SkillId[]): SkillConfig[] {\n return skillIds.map((id) => ({\n id,\n scope: \"project\" as const,\n origin: EJECT_SOURCE,\n }))\n}\n\n/** Values are already SkillAssignment[] (normalized by loadStacks()). */\nexport function buildStackProperty(\n stack: Stack\n): Partial<Record<AgentName, StackAgentConfig>> {\n return typedFromEntries(\n typedEntries<AgentName, StackAgentConfig>(stack.agents)\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- typedEntries drops Partial's `| undefined`; this guards an explicitly-undefined slot\n .filter(([, agentConfig]) => agentConfig && hasCategories(agentConfig))\n .map(\n ([agent, agentConfig]) =>\n [agent, withResolvedLoads(agent, agentConfig)] as const\n )\n .filter(([, agentStack]) => hasCategories(agentStack))\n )\n}\n\nfunction withResolvedLoads(\n agent: AgentName,\n agentConfig: StackAgentConfig\n): StackAgentConfig {\n return mapCategoriesDroppingEmpty(agentConfig, (assignments) =>\n assignments.map((assignment) =>\n toStackPropertyAssignment(assignment, agent)\n )\n )\n}\n\n/**\n * An author's flag rides through (`loadStacks` makes even bare strings explicit for third-party\n * stacks).\n */\nfunction toStackPropertyAssignment(\n assignment: SkillAssignment,\n agent: AgentName\n): SkillAssignment {\n if (assignment.preloaded !== undefined) return assignment\n if (mappedLoadState(assignment.id, agent) === \"lazy\") return assignment\n\n return { ...assignment, preloaded: true }\n}\n\nfunction mapCategoriesDroppingEmpty(\n agentStack: StackAgentConfig,\n transform: (assignments: SkillAssignment[]) => SkillAssignment[]\n): StackAgentConfig {\n return typedFromEntries(\n typedEntries<Category, SkillAssignment[]>(agentStack)\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- typedEntries drops Partial's `| undefined`; this guards an explicitly-undefined slot\n .filter(([, assignments]) => assignments !== undefined)\n .map(\n ([category, assignments]) => [category, transform(assignments)] as const\n )\n .filter(([, transformed]) => transformed.length > 0)\n )\n}\n\nexport function splitConfigByScope(config: ProjectConfig): SplitConfigResult {\n // Excluded-global tombstones go to the project partition as overrides.\n const [globalSkills, projectSkills] = partition(config.skills, (s) =>\n isActiveAt(s, \"global\")\n )\n const [globalAgents, projectAgents] = partition(config.agents, (a) =>\n isActiveAt(a, \"global\")\n )\n const stack = splitStackByScope(\n config.stack ?? {},\n globalAgents,\n projectAgents,\n new Set(globalSkills.map((s) => s.id))\n )\n\n // `stack` is written on both partitions unconditionally: the spread carries the undivided\n // stack, and an empty derivation must still say `{}` or the merger keeps the stale one.\n return {\n global: {\n ...omit(config, HAND_WRITTEN_FIELDS),\n name: GLOBAL_CONFIG_NAME,\n agents: globalAgents,\n skills: globalSkills,\n stack: stack.global,\n },\n project: {\n ...config,\n agents: projectAgents,\n skills: projectSkills,\n stack: stack.project,\n },\n }\n}\n\n/** Global agents reference only global skills; project agents keep every reference. */\nfunction splitStackByScope(\n stack: NonNullable<ProjectConfig[\"stack\"]>,\n globalAgents: AgentScopeConfig[],\n projectAgents: AgentScopeConfig[],\n globalSkillIds: ReadonlySet<SkillId>\n): Record<SkillScope, NonNullable<ProjectConfig[\"stack\"]>> {\n const globalAgentSplits = stackEntriesOf(stack, globalAgents).map(\n ([agent, agentStack]) =>\n [agent, splitAgentStack(agentStack, globalSkillIds)] as const\n )\n const nonEmptyHalves = (scope: SkillScope) =>\n globalAgentSplits\n .map(([agent, split]) => [agent, split[scope]] as const)\n .filter(([, half]) => hasCategories(half))\n\n return {\n global: typedFromEntries(nonEmptyHalves(\"global\")),\n project: typedFromEntries([\n ...nonEmptyHalves(\"project\"),\n ...stackEntriesOf(stack, projectAgents),\n ]),\n }\n}\n\nfunction stackEntriesOf(\n stack: NonNullable<ProjectConfig[\"stack\"]>,\n agents: AgentScopeConfig[]\n): (readonly [AgentName, StackAgentConfig])[] {\n return agents.flatMap(({ name }) => {\n const agentStack = stack[name]\n return agentStack ? [[name, agentStack] as const] : []\n })\n}\n\nfunction splitAgentStack(\n agentStack: StackAgentConfig,\n globalSkillIds: ReadonlySet<SkillId>\n): Record<SkillScope, StackAgentConfig> {\n const isGlobalSkill = (assignment: SkillAssignment) =>\n globalSkillIds.has(assignment.id)\n\n return {\n global: mapCategoriesDroppingEmpty(agentStack, (assignments) =>\n assignments.filter(isGlobalSkill)\n ),\n project: mapCategoriesDroppingEmpty(agentStack, (assignments) =>\n assignments.filter((assignment) => !isGlobalSkill(assignment))\n ),\n }\n}\n\n/** What the CLI installs: a shared configuration decoded against the catalog. */\nexport type InstallSelection = {\n skills: SkillConfig[]\n selectedAgents: AgentName[]\n agentConfigs: AgentScopeConfig[]\n assignedStack: Partial<Record<AgentName, StackAgentConfig>>\n selectedStackId: string | null\n /** The sharer's description (`init --from`); undefined takes the applied stack's. */\n description?: string\n selectedDomains: Domain[]\n validation: SelectionValidation\n}\n\n/** A skipped skill and the sub-agents it alone brought in, so they go with it. */\nexport type SkippedSkillAgents = { skillId: string; agentNames: AgentName[] }\n\nexport type SeedMapping = {\n result: InstallSelection\n skippedSkillIds: string[]\n skippedAgentNames: string[]\n /** Only skills naming such a sub-agent; `result` is the same with or without them. */\n agentsOnlySkippedSkillsCarried: SkippedSkillAgents[]\n}\n\ntype SeedAgentMap = {\n known: Map<AgentName, SeedAgent>\n switchedOff: Set<string>\n unknown: string[]\n}\n\ntype InstallableSeedSkill = {\n id: SkillId\n category: Category\n domain: Domain\n seedSkill: SeedSkill\n catalogSkill: CatalogSkill\n}\n\ntype PlacedAssignment = {\n agent: AgentName\n category: Category\n assignment: SkillAssignment\n}\n\ntype UnwritableAssignment = { skillId: SkillId; agent: AgentName }\n\ntype AssignmentRow =\n | ({ kind: \"placed\" } & PlacedAssignment)\n | ({ kind: \"unwritable\" } & UnwritableAssignment)\n | { kind: \"unknownAgent\"; agentName: string }\n\n/**\n * A shared configuration in the shape `init --from` installs. Unknown ids are skipped, never\n * fatal, so a rename cannot break older links. Assignments become `assignedStack`, which replaces\n * the derived stack. An unwritable pair is the one fatal case: nothing downstream filters\n * `assignedStack`.\n */\nexport function seedToInstallSelection(\n payload: SeedPayload,\n catalog: CompileCatalog\n): SeedMapping {\n const agentMap = readAgentMap(payload.agents)\n const { installable, skipped } = resolveSeedSkills(payload.skills, catalog)\n // An agent is not switched on by a skill this catalog cannot install.\n const rows = installable.flatMap((skill) => assignmentRows(skill, agentMap))\n refuseUnwritableAssignments(rows)\n\n const placed = rows.filter((row) => row.kind === \"placed\")\n const selectedAgents = selectedAgentsOf(placed, agentMap)\n const skills = installable.map(toSeedSkillConfig)\n const selected = new Set(selectedAgents)\n\n return {\n result: {\n skills,\n selectedAgents,\n agentConfigs: selectedAgents.map((name) =>\n agentScopeConfig(name, agentMap.known.get(name))\n ),\n assignedStack: assignedStackOf(placed),\n selectedStackId: payload.stackId,\n // Absent and empty are different files on disk.\n ...(payload.description !== undefined && {\n description: payload.description,\n }),\n selectedDomains: orderDomains([\n ...new Set(installable.map((skill) => skill.domain)),\n ]),\n // Revalidated: the payload was consistent against the authoring app's catalog, not this one.\n validation: validateSelection(\n skills.map((skill) => skill.id),\n catalog\n ),\n },\n skippedSkillIds: skipped.map(({ skillId }) => skillId),\n skippedAgentNames: skippedAgentNamesOf(agentMap, rows),\n agentsOnlySkippedSkillsCarried: skipped.flatMap((skill) =>\n agentsOnlyItCarried(skill, agentMap, selected)\n ),\n }\n}\n\nfunction refuseUnwritableAssignments(rows: AssignmentRow[]): void {\n const unwritable = rows.filter((row) => row.kind === \"unwritable\")\n if (unwritable.length > 0) {\n throw new Error(unwritableAssignmentsError(unwritable))\n }\n}\n\nfunction selectedAgentsOf(\n placed: PlacedAssignment[],\n agentMap: SeedAgentMap\n): AgentName[] {\n return [\n ...new Set([\n ...placed.map((row) => row.agent),\n ...agentsSwitchedOn(agentMap),\n ]),\n ]\n}\n\nfunction skippedAgentNamesOf(\n agentMap: SeedAgentMap,\n rows: AssignmentRow[]\n): string[] {\n const unknownAssignees = rows\n .filter((row) => row.kind === \"unknownAgent\")\n .map((row) => row.agentName)\n\n return [...new Set([...agentMap.unknown, ...unknownAssignees])]\n}\n\ntype SkippedSeedSkill = { skillId: string; seedSkill: SeedSkill }\n\n/** A sub-agent this catalog ships, not switched off, that nothing installed selects. */\nfunction agentsOnlyItCarried(\n { skillId, seedSkill }: SkippedSeedSkill,\n agentMap: SeedAgentMap,\n selected: ReadonlySet<AgentName>\n): SkippedSkillAgents[] {\n const agentNames = Object.keys(seedSkill.assignments)\n .filter(isAgentName)\n .filter((name) => !agentMap.switchedOff.has(name) && !selected.has(name))\n\n return agentNames.length === 0 ? [] : [{ skillId, agentNames }]\n}\n\nfunction readAgentMap(agents: SeedPayload[\"agents\"]): SeedAgentMap {\n const known = new Map<AgentName, SeedAgent>()\n const switchedOff = new Set<string>()\n const unknown: string[] = []\n\n for (const [name, entry] of Object.entries(agents)) {\n if (!isAgentName(name)) unknown.push(name)\n else if (entry.on === false) switchedOff.add(name)\n else known.set(name, entry)\n }\n\n return { known, switchedOff, unknown }\n}\n\nfunction agentsSwitchedOn(agentMap: SeedAgentMap): AgentName[] {\n return [...agentMap.known]\n .filter(([, entry]) => entry.on === true)\n .map(([name]) => name)\n}\n\nfunction resolveSeedSkills(\n seedSkills: SeedPayload[\"skills\"],\n catalog: CompileCatalog\n): { installable: InstallableSeedSkill[]; skipped: SkippedSeedSkill[] } {\n const looked = Object.entries(seedSkills).map(([skillId, seedSkill]) => ({\n skillId,\n seedSkill,\n installable: installableSkill(skillId, seedSkill, catalog),\n }))\n\n return {\n installable: looked.map((entry) => entry.installable).filter(isDefined),\n skipped: looked\n .filter((entry) => entry.installable === undefined)\n .map(({ skillId, seedSkill }) => ({ skillId, seedSkill })),\n }\n}\n\nfunction installableSkill(\n skillId: string,\n seedSkill: SeedSkill,\n catalog: CompileCatalog\n): InstallableSeedSkill | undefined {\n const catalogSkill = catalog.skills[skillId]\n if (!catalogSkill?.category) return undefined\n const domain = categoryDomain(catalog, catalogSkill.category)\n if (domain === undefined) return undefined\n\n // Boundary casts: these come from the catalogue's own keys, and the `local` pseudo-category\n // (no domain) has already returned.\n return {\n id: skillId as SkillId,\n category: catalogSkill.category as Category,\n domain: domain as Domain,\n seedSkill,\n catalogSkill,\n }\n}\n\nfunction toSeedSkillConfig({\n id,\n seedSkill,\n catalogSkill,\n}: InstallableSeedSkill): SkillConfig {\n return {\n id,\n scope: seedSkill.scope,\n origin:\n seedSkill.install === \"eject\"\n ? EJECT_SOURCE\n : sourceForSkill(catalogSkill),\n }\n}\n\nfunction sourceForSkill(skill: CatalogSkill): string {\n return (\n skill.availableSources?.find((s) => s.primary)?.name ??\n DEFAULT_PUBLIC_SOURCE_NAME\n )\n}\n\nfunction assignmentRows(\n skill: InstallableSeedSkill,\n agentMap: SeedAgentMap\n): AssignmentRow[] {\n return Object.entries(skill.seedSkill.assignments)\n .map(([agentName, load]) => assignmentRow(skill, agentName, load, agentMap))\n .filter(isDefined)\n}\n\nfunction assignmentRow(\n skill: InstallableSeedSkill,\n agentName: string,\n load: SeedLoadState,\n agentMap: SeedAgentMap\n): AssignmentRow | undefined {\n if (agentMap.switchedOff.has(agentName)) return undefined\n if (!isAgentName(agentName)) return { kind: \"unknownAgent\", agentName }\n\n const agentScope = seedAgentScope(agentMap.known.get(agentName))\n if (!isScopePairCompatible(skill.seedSkill.scope, agentScope)) {\n return { kind: \"unwritable\", skillId: skill.id, agent: agentName }\n }\n\n return {\n kind: \"placed\",\n agent: agentName,\n category: skill.category,\n assignment: toSkillAssignment(skill.id, load),\n }\n}\n\nfunction toSkillAssignment(\n skillId: SkillId,\n load: SeedLoadState\n): SkillAssignment {\n return { id: skillId, preloaded: load === \"preloaded\" }\n}\n\n/** `skills` is keyed by id, so a `(skill, sub-agent)` pair occurs once: nothing to de-duplicate. */\nfunction assignedStackOf(\n placed: PlacedAssignment[]\n): Partial<Record<AgentName, StackAgentConfig>> {\n return mapValues(\n groupBy(placed, (row) => row.agent),\n (agentRows) =>\n mapValues(\n groupBy(agentRows, (row) => row.category),\n (categoryRows) => categoryRows.map((row) => row.assignment)\n )\n )\n}\n\n/** An absent key keeps whatever the agent's metadata says. */\nfunction agentScopeConfig(\n name: AgentName,\n entry: SeedAgent | undefined\n): AgentScopeConfig {\n return {\n name,\n scope: seedAgentScope(entry),\n ...(entry?.model !== undefined && { model: entry.model }),\n ...offeredCodexModel(name, entry?.codexModel),\n ...(entry?.effort !== undefined && { effort: entry.effort }),\n }\n}\n\nconst OFFERED_CODEX_MODELS = new Set<string>(CODEX_MODEL_NAMES)\n\nfunction isOfferedCodexModel(id: string): id is CodexModelName {\n return OFFERED_CODEX_MODELS.has(id)\n}\n\n/** The wire carries any Codex id so a retired one cannot break a link. */\nfunction offeredCodexModel(\n agent: AgentName,\n id: string | undefined\n): Pick<AgentScopeConfig, \"codexModel\"> {\n if (id === undefined) return {}\n if (isOfferedCodexModel(id)) return { codexModel: id }\n\n diagnostics().warn(codexModelNotOfferedWarning(agent, id))\n return {}\n}\n\nfunction codexModelNotOfferedWarning(agent: AgentName, id: string): string {\n return (\n `Sub-agent '${agent}' asks for Codex model '${id}', which this version of the CLI does not ` +\n `offer, so it runs on the session's model. Offered: ${inAnEnglishList(CODEX_MODEL_NAMES)}.`\n )\n}\n\nfunction unwritableAssignmentsError(\n assignments: UnwritableAssignment[]\n): string {\n return [\n \"This configuration cannot be installed: a project-scoped skill never reaches a sub-agent \" +\n \"that rests at global scope, so these assignments have nowhere to be written:\",\n ...assignments.map(({ skillId, agent }) => ` ${skillId} -> ${agent}`),\n \"Re-share it with each sub-agent above pinned to the project, or each skill above at global scope.\",\n ].join(\"\\n\")\n}\n","import { omit } from \"remeda\"\n\nimport {\n byCategoryDeclarationOrder,\n isExclusiveCategory,\n type CompileCatalog,\n} from \"./catalog.js\"\nimport {\n INDENT_STEP,\n commentEntry,\n isKeyedRecord,\n propertyPosition,\n quoteText,\n renderArrayLine,\n renderTypeImportLine,\n renderValueLine,\n sourceEntry,\n valueEntries,\n type ArrayEntry,\n type LinePosition,\n} from \"./installed-format.js\"\nimport { DEFAULT_PLUGIN_NAME, GLOBAL_CONFIG_NAME } from \"./paths.js\"\nimport { bytewise } from \"./string.js\"\nimport type {\n AgentScopeConfig,\n ProjectConfig,\n SkillAssignment,\n SkillConfig,\n SkillScope,\n} from \"./types.js\"\n\n// Renders `config.ts` sources and writes nothing; writing is `config-gate/`'s alone.\n\n/**\n * `isProjectConfig: true` needs `globalConfig` or `globalImportPath` (`globalConfig` wins).\n * {@link generateProjectConfig} enforces it at runtime: a discriminated union on the literal widens\n * to `boolean` at un-annotated call sites.\n */\nexport type ConfigSourceOptions = {\n isProjectConfig?: boolean\n\n /** Inlines global skills/agents for a self-contained snapshot. */\n globalConfig?: ProjectConfig\n\n /** For the spread form. A parameter because this package runs in a browser. */\n globalImportPath?: string\n}\n\n/**\n * Fields an author writes by hand and no install produces. Each stays in the file that declares\n * it: a project's name in the global config would rename every installation without one.\n */\nexport const HAND_WRITTEN_FIELDS = [\n \"branding\",\n \"skillsDir\",\n \"stacksFile\",\n \"categoriesFile\",\n \"rulesFile\",\n] as const satisfies readonly (keyof ProjectConfig)[]\n\n/** Emitted as typed named variables above the export default. */\nconst EXTRACTED_FIELDS = new Set([\n \"skills\",\n \"agents\",\n \"stack\",\n \"selectedDomains\",\n])\n\n/**\n * The loader schema's field order, so the writer is a fixed point: a Zod load and a merge insert\n * keys in different orders.\n */\nconst CANONICAL_FIELD_ORDER = [\n \"name\",\n \"description\",\n \"agents\",\n \"skills\",\n \"author\",\n \"selectedDomains\",\n \"stack\",\n \"marketplace\",\n \"marketplaceName\",\n \"projects\",\n] as const satisfies readonly (keyof ProjectConfig)[]\n\nconst CANONICAL_SKILL_ENTRY_ORDER = [\n \"id\",\n \"scope\",\n \"origin\",\n \"excluded\",\n] as const satisfies readonly (keyof SkillConfig)[]\n\nconst CANONICAL_AGENT_ENTRY_ORDER = [\n \"name\",\n \"scope\",\n \"model\",\n \"codexModel\",\n \"effort\",\n \"excluded\",\n] as const satisfies readonly (keyof AgentScopeConfig)[]\n\nconst CANONICAL_ASSIGNMENT_ORDER = [\n \"id\",\n \"preloaded\",\n \"local\",\n \"path\",\n] as const satisfies readonly (keyof SkillAssignment)[]\n\n/** Unnamed (passthrough) keys keep their arrival order, after every named one. */\nfunction withKeysInSchemaOrder(\n record: Record<string, unknown>,\n schemaOrder: readonly string[]\n): Record<string, unknown> {\n const named = new Set<string>(schemaOrder)\n const inSchemaOrder = schemaOrder\n .filter((key) => key in record)\n .map((key): [string, unknown] => [key, record[key]])\n const passthrough = Object.entries(record).filter(([key]) => !named.has(key))\n\n return Object.fromEntries([...inSchemaOrder, ...passthrough])\n}\n\nfunction canonicalizeFieldOrder(\n cleaned: Record<string, unknown>\n): Record<string, unknown> {\n return withKeysInSchemaOrder(cleaned, CANONICAL_FIELD_ORDER)\n}\n\n/** An absent array stays absent: the emission tells it from an empty one. */\nfunction withEntriesInSchemaOrder(\n cleaned: Record<string, unknown>\n): Record<string, unknown> {\n const reordered = { ...cleaned }\n if (Array.isArray(reordered.skills)) {\n reordered.skills = entriesInSchemaOrder(\n reordered.skills,\n CANONICAL_SKILL_ENTRY_ORDER\n )\n }\n if (Array.isArray(reordered.agents)) {\n reordered.agents = entriesInSchemaOrder(\n reordered.agents,\n CANONICAL_AGENT_ENTRY_ORDER\n )\n }\n return reordered\n}\n\nfunction entriesInSchemaOrder(\n entries: unknown[],\n schemaOrder: readonly string[]\n): unknown[] {\n return entries.map((entry: unknown) =>\n isKeyedRecord(entry) ? withKeysInSchemaOrder(entry, schemaOrder) : entry\n )\n}\n\nfunction withKeysOrderedBy<T>(\n record: Record<string, T>,\n compareKeys: (a: string, b: string) => number\n): Record<string, T> {\n return Object.fromEntries(\n Object.entries(record).sort(([a], [b]) => compareKeys(a, b))\n )\n}\n\n/**\n * Sub-agents by name and categories in catalogue declaration order, whoever assembled the stack: a\n * compiled sub-agent lists its skills in stack order, so producer order would change its file.\n */\nexport function canonicalizeStackOrder<Assignments>(\n stack: Record<string, Record<string, Assignments>>,\n catalog: CompileCatalog\n): Record<string, Record<string, Assignments>> {\n const byDeclaration = byCategoryDeclarationOrder(catalog)\n const withCategoriesInOrder = Object.entries(stack).map(\n ([agent, categories]) =>\n [agent, withKeysOrderedBy(categories, byDeclaration)] as const\n )\n\n return withKeysOrderedBy(Object.fromEntries(withCategoriesInOrder), bytewise)\n}\n\nconst CONFIG_TYPES_SPECIFIER = \"./config-types\"\n\nconst STACK_TYPE = \"Partial<Record<ProjectAgentName, StackAgentConfig>>\"\n\nfunction declarationPosition(name: string, type: string): LinePosition {\n return { indent: 0, prefix: `const ${name}: ${type} = `, suffix: \"\" }\n}\n\n/** Every declaration is preceded by a blank line, which the emitted pair's readers key on. */\nfunction declaration(name: string, type: string, value: unknown): string[] {\n return [\"\", renderValueLine(value, declarationPosition(name, type))]\n}\n\nfunction entryDeclaration(\n name: string,\n type: string,\n entries: readonly ArrayEntry[]\n): string[] {\n return [\"\", renderArrayLine(entries, declarationPosition(name, type))]\n}\n\nfunction renderScalarField(key: string, value: unknown): string {\n return renderValueLine(value, propertyPosition(key, INDENT_STEP))\n}\n\ntype ConfigArrays = {\n skills: SkillConfig[]\n agents: AgentScopeConfig[]\n stack: Record<string, unknown> | undefined\n selectedDomains: unknown[]\n}\n\nfunction extractConfigArrays(cleaned: Record<string, unknown>): ConfigArrays {\n // Boundary cast: the JSON round trip of a `ProjectConfig`. `??` runs first because the round\n // trip drops undefined-valued keys.\n return {\n skills: (cleaned.skills ?? []) as SkillConfig[],\n agents: (cleaned.agents ?? []) as AgentScopeConfig[],\n stack: cleaned.stack as Record<string, unknown> | undefined,\n selectedDomains: (cleaned.selectedDomains ?? []) as unknown[],\n }\n}\n\n/**\n * JSON round trip (drops undefined), `projects` removed for project configs, stack compaction, and\n * canonical key order at every level the bytes expose, so the bytes depend on values alone.\n */\nfunction cleanForEmission(\n config: ProjectConfig,\n catalog: CompileCatalog,\n options: { dropProjects: boolean }\n): Record<string, unknown> {\n // Boundary cast: `JSON.parse` is typed `any`.\n const cleaned = JSON.parse(JSON.stringify(config)) as Record<string, unknown>\n if (options.dropProjects) {\n delete cleaned.projects\n }\n if (cleaned.stack) {\n // Boundary cast: a JSON round trip, so agent -> category -> assignment arrays.\n const compacted = compactStackAssignments(\n cleaned.stack as Record<string, Record<string, unknown[]>>,\n catalog\n )\n cleaned.stack = canonicalizeStackOrder(compacted, catalog)\n }\n return canonicalizeFieldOrder(withEntriesInSchemaOrder(cleaned))\n}\n\n/**\n * Typed named declarations first, then an `export default` referring to each. The catalogue is a\n * parameter: exclusivity and declaration order differ between the CLI's catalogue and the editor's.\n */\nexport function generateConfigSource(\n config: ProjectConfig,\n catalog: CompileCatalog,\n options?: ConfigSourceOptions\n): string {\n if (options?.isProjectConfig) {\n return generateProjectConfig(config, catalog, options)\n }\n\n return generateStandaloneConfig(\n cleanForEmission(config, catalog, { dropProjects: false })\n )\n}\n\n/**\n * Refuses options naming neither emission: the standalone writer would answer a project request\n * with a global-shaped file carrying `projects`.\n */\nfunction generateProjectConfig(\n config: ProjectConfig,\n catalog: CompileCatalog,\n options: ConfigSourceOptions\n): string {\n const cleaned = cleanForEmission(config, catalog, { dropProjects: true })\n\n if (options.globalConfig) {\n return generateProjectConfigWithInlinedGlobal(\n cleaned,\n cleanForEmission(options.globalConfig, catalog, { dropProjects: true })\n )\n }\n if (options.globalImportPath !== undefined) {\n return generateProjectConfigWithGlobalImport(\n cleaned,\n options.globalImportPath\n )\n }\n\n throw new Error(\n \"A project config needs the global config it extends: pass `globalConfig` to inline its \" +\n \"entries, or `globalImportPath` to import and spread them. Neither was given.\"\n )\n}\n\nfunction generateProjectConfigWithGlobalImport(\n cleaned: Record<string, unknown>,\n globalImportPath: string\n): string {\n const { skills, agents, stack, selectedDomains } =\n extractConfigArrays(cleaned)\n const emitted: EmittedSections = {\n hasSkills: true,\n hasAgents: true,\n hasStack: hasStackEntries(stack),\n hasSelectedDomains: selectedDomains.length > 0,\n }\n const scalarFields = Object.entries(cleaned)\n .filter(([key]) => isCopiedScalarField(key))\n .map(([key, value]) => renderScalarField(key, value))\n\n return assembleConfigSource({\n imports: [\n `import globalConfig from ${quoteText(`${globalImportPath}/config`)}`,\n renderTypeImportLine(buildTypeImports(emitted), CONFIG_TYPES_SPECIFIER),\n ],\n declarations: [\n ...entryDeclaration(\"skills\", \"SkillConfig[]\", [\n sourceEntry(\"...globalConfig.skills\"),\n ...valueEntries(skills),\n ]),\n ...entryDeclaration(\"agents\", \"AgentScopeConfig[]\", [\n sourceEntry(\"...globalConfig.agents\"),\n ...valueEntries(agents),\n ]),\n ...(emitted.hasStack ? declaration(\"stack\", STACK_TYPE, stack) : []),\n ...(emitted.hasSelectedDomains\n ? entryDeclaration(\"selectedDomains\", \"Domain[]\", [\n sourceEntry(\"...(globalConfig.selectedDomains ?? [])\"),\n ...valueEntries(selectedDomains),\n ])\n : []),\n ],\n exportFields: [\n ` ...globalConfig,`,\n renderScalarField(\"name\", resolveProjectName(cleaned)),\n ` skills,`,\n ` agents,`,\n ...(emitted.hasStack ? [` stack,`] : []),\n ...(emitted.hasSelectedDomains ? [` selectedDomains,`] : []),\n ...scalarFields,\n ],\n })\n}\n\nfunction generateStandaloneConfig(cleaned: Record<string, unknown>): string {\n const { skills, agents, stack, selectedDomains } =\n extractConfigArrays(cleaned)\n const emitted: EmittedSections = {\n hasSkills: skills.length > 0,\n hasAgents: agents.length > 0,\n hasStack: hasStackEntries(stack),\n hasSelectedDomains: selectedDomains.length > 0,\n }\n\n return assembleConfigSource({\n imports: [\n renderTypeImportLine(buildTypeImports(emitted), CONFIG_TYPES_SPECIFIER),\n ],\n declarations: [\n ...(emitted.hasSkills\n ? declaration(\"skills\", \"SkillConfig[]\", skills)\n : []),\n ...(emitted.hasAgents\n ? declaration(\"agents\", \"AgentScopeConfig[]\", agents)\n : []),\n ...(emitted.hasStack ? declaration(\"stack\", STACK_TYPE, stack) : []),\n ...(emitted.hasSelectedDomains\n ? declaration(\"selectedDomains\", \"Domain[]\", selectedDomains)\n : []),\n ],\n exportFields: Object.entries(cleaned).flatMap(([key, value]) =>\n standaloneExportField(key, value, emitted)\n ),\n })\n}\n\n/** Extracted fields reference their variable, or an empty literal when none was emitted. */\nfunction standaloneExportField(\n key: string,\n value: unknown,\n emitted: EmittedSections\n): string[] {\n if (!EXTRACTED_FIELDS.has(key)) return [renderScalarField(key, value)]\n if (key === \"skills\") return [` skills${emitted.hasSkills ? \"\" : \": []\"},`]\n if (key === \"agents\") return [` agents${emitted.hasAgents ? \"\" : \": []\"},`]\n if (key === \"stack\") return emitted.hasStack ? [` stack,`] : []\n return [` selectedDomains${emitted.hasSelectedDomains ? \"\" : \": []\"},`]\n}\n\ntype ConfigSourceParts = {\n imports: string[]\n /** Each already led by its blank line. */\n declarations: string[]\n exportFields: string[]\n}\n\nfunction assembleConfigSource({\n imports,\n declarations,\n exportFields,\n}: ConfigSourceParts): string {\n return [\n ...imports,\n ...declarations,\n \"\",\n \"export default {\",\n ...exportFields,\n \"} satisfies ProjectConfig\",\n \"\",\n ].join(\"\\n\")\n}\n\ntype EmittedSections = {\n hasSkills: boolean\n hasAgents: boolean\n hasStack: boolean\n hasSelectedDomains: boolean\n}\n\nfunction hasStackEntries(stack: Record<string, unknown> | undefined): boolean {\n return stack != null && Object.keys(stack).length > 0\n}\n\nfunction buildTypeImports(flags: EmittedSections): string[] {\n return [\n flags.hasSelectedDomains && \"Domain\",\n \"ProjectConfig\",\n flags.hasStack && \"ProjectAgentName\",\n flags.hasAgents && \"AgentScopeConfig\",\n flags.hasSkills && \"SkillConfig\",\n flags.hasStack && \"StackAgentConfig\",\n ].filter((t): t is string => Boolean(t))\n}\n\n/** A project copies these as they stand; its `name` is {@link resolveProjectName}'s. */\nfunction isCopiedScalarField(key: string): boolean {\n return !EXTRACTED_FIELDS.has(key) && key !== \"name\"\n}\n\n/** Project configs never inherit \"global\" as their name from the globalConfig spread. */\nfunction resolveProjectName(cleaned: Record<string, unknown>): unknown {\n return cleaned.name && cleaned.name !== GLOBAL_CONFIG_NAME\n ? cleaned.name\n : DEFAULT_PLUGIN_NAME\n}\n\ntype InlinedGlobalPartition = {\n /** Global entries with active entries replaced by their project tombstones. */\n globalSkills: SkillConfig[]\n globalAgents: AgentScopeConfig[]\n projectSkills: SkillConfig[]\n projectAgents: AgentScopeConfig[]\n filteredStack: Record<string, unknown> | undefined\n selectedDomains: unknown[]\n}\n\n/**\n * Excluded globals render under `// global`; an active global entry is replaced by its tombstone,\n * which masks it for this project. Global agents' stacks stay in the global config.\n */\nfunction partitionInlinedConfigEntries(\n cleaned: Record<string, unknown>,\n cleanedGlobal: Record<string, unknown>\n): InlinedGlobalPartition {\n const project = extractConfigArrays(cleaned)\n const global = extractConfigArrays(cleanedGlobal)\n\n const excludedGlobalSkills = project.skills.filter(isExcluded)\n const excludedGlobalAgents = project.agents.filter(isExcluded)\n const projectAgents = project.agents.filter((a) => !isExcluded(a))\n\n return {\n globalSkills: maskedByTombstones(global.skills, excludedGlobalSkills, idOf),\n globalAgents: maskedByTombstones(\n global.agents,\n excludedGlobalAgents,\n nameOf\n ),\n projectSkills: project.skills.filter((s) => !isExcluded(s)),\n projectAgents,\n filteredStack: stackOfAgents(project.stack, projectAgents),\n selectedDomains: [\n ...new Set([...global.selectedDomains, ...project.selectedDomains]),\n ],\n }\n}\n\nconst isExcluded = (entry: SkillConfig | AgentScopeConfig): boolean =>\n entry.excluded === true\nconst idOf = (skill: SkillConfig): string => skill.id\nconst nameOf = (agent: AgentScopeConfig): string => agent.name\n\nfunction maskedByTombstones<Entry>(\n globalEntries: Entry[],\n tombstones: Entry[],\n keyOf: (entry: Entry) => string\n): Entry[] {\n const masked = new Set(tombstones.map(keyOf))\n return [\n ...globalEntries.filter((entry) => !masked.has(keyOf(entry))),\n ...tombstones,\n ]\n}\n\nfunction stackOfAgents(\n stack: Record<string, unknown> | undefined,\n agents: AgentScopeConfig[]\n): Record<string, unknown> | undefined {\n if (!stack) return undefined\n\n const names = new Set(agents.map(nameOf))\n return Object.fromEntries(\n Object.entries(stack).filter(([agent]) => names.has(agent))\n )\n}\n\n/**\n * One canonically ordered sequence, project values winning, so a re-emit moves no line. The\n * global's {@link HAND_WRITTEN_FIELDS} stay in the global's file.\n */\nfunction mergeInlinedScalarFields(\n cleaned: Record<string, unknown>,\n cleanedGlobal: Record<string, unknown>\n): [string, unknown][] {\n return Object.entries(\n canonicalizeFieldOrder({\n ...omit(cleanedGlobal, HAND_WRITTEN_FIELDS),\n ...cleaned,\n })\n ).filter(([key]) => isCopiedScalarField(key))\n}\n\n/** Self-contained: global items under `// global`, then project items under `// project`. */\nfunction generateProjectConfigWithInlinedGlobal(\n cleaned: Record<string, unknown>,\n cleanedGlobal: Record<string, unknown>\n): string {\n const partition = partitionInlinedConfigEntries(cleaned, cleanedGlobal)\n const emitted: EmittedSections = {\n hasSkills:\n partition.globalSkills.length > 0 || partition.projectSkills.length > 0,\n hasAgents:\n partition.globalAgents.length > 0 || partition.projectAgents.length > 0,\n hasStack: hasStackEntries(partition.filteredStack),\n hasSelectedDomains: partition.selectedDomains.length > 0,\n }\n const scalarFields = mergeInlinedScalarFields(cleaned, cleanedGlobal)\n\n return assembleConfigSource({\n imports: [\n renderTypeImportLine(buildTypeImports(emitted), CONFIG_TYPES_SPECIFIER),\n ],\n declarations: [\n ...(emitted.hasSkills\n ? entryDeclaration(\n \"skills\",\n \"SkillConfig[]\",\n scopeSectionEntries(partition.globalSkills, partition.projectSkills)\n )\n : []),\n ...(emitted.hasAgents\n ? entryDeclaration(\n \"agents\",\n \"AgentScopeConfig[]\",\n scopeSectionEntries(partition.globalAgents, partition.projectAgents)\n )\n : []),\n ...(emitted.hasStack\n ? declaration(\"stack\", STACK_TYPE, partition.filteredStack)\n : []),\n ...(emitted.hasSelectedDomains\n ? declaration(\"selectedDomains\", \"Domain[]\", partition.selectedDomains)\n : []),\n ],\n exportFields: [\n renderScalarField(\"name\", resolveProjectName(cleaned)),\n ...scalarFields.map(([key, value]) => renderScalarField(key, value)),\n emitted.hasSkills ? ` skills,` : ` skills: [],`,\n emitted.hasAgents ? ` agents,` : ` agents: [],`,\n ...(emitted.hasStack ? [` stack,`] : []),\n ...(emitted.hasSelectedDomains ? [` selectedDomains,`] : []),\n ],\n })\n}\n\n/** The scope comments are entries: a `//` line keeps the array one entry per line. */\nfunction scopeSectionEntries(\n global: unknown[],\n project: unknown[]\n): ArrayEntry[] {\n return [\n ...scopeSection(\"global\", global),\n ...scopeSection(\"project\", project),\n ]\n}\n\nfunction scopeSection(scope: SkillScope, entries: unknown[]): ArrayEntry[] {\n return entries.length > 0\n ? [commentEntry(scope), ...valueEntries(entries)]\n : []\n}\n\nfunction carriesFlags(assignment: SkillAssignment): boolean {\n return Boolean(assignment.preloaded || assignment.local || assignment.path)\n}\n\n/** Structural only: assignments may name skills outside the generated union. */\nfunction isSkillAssignment(value: unknown): value is SkillAssignment {\n if (typeof value !== \"object\" || value === null) return false\n // Boundary cast: probing an unknown object's field inside the guard\n return typeof (value as { id?: unknown }).id === \"string\"\n}\n\n/**\n * A flag-less (or `preloaded: false`) assignment collapses to its bare id; one carrying a flag\n * keeps the object form.\n */\nfunction compactAssignment(assignment: unknown): unknown {\n if (!isSkillAssignment(assignment)) return assignment\n if (!carriesFlags(assignment)) return assignment.id\n return withKeysInSchemaOrder(assignment, CANONICAL_ASSIGNMENT_ORDER)\n}\n\n/**\n * An exclusive category emits its one assignment bare; a non-exclusive one keeps its array. Two\n * skills in an exclusive category cannot be expressed, so it throws rather than drop one.\n */\nfunction compactCategoryAssignments(\n category: string,\n assignments: unknown[],\n catalog: CompileCatalog\n): unknown {\n const compacted = assignments.map(compactAssignment)\n if (!isExclusiveCategory(catalog, category)) return compacted\n\n if (compacted.length > 1) {\n throw new Error(\n `Category '${category}' is exclusive but holds ${compacted.length} skills: ${JSON.stringify(compacted)}`\n )\n }\n return compacted[0]\n}\n\n/** For `edit --from`, which removes skills before writing: refuses before the first removal. */\nexport function refuseUnwritableStack(\n stack: ProjectConfig[\"stack\"],\n catalog: CompileCatalog\n): void {\n for (const agentStack of Object.values(stack ?? {})) {\n compactCategories(agentStack, catalog)\n }\n}\n\nfunction compactCategories(\n categories: Record<string, unknown[]>,\n catalog: CompileCatalog\n): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(categories)\n .filter(\n ([, assignments]) =>\n Array.isArray(assignments) && assignments.length > 0\n )\n .map(([category, assignments]) => [\n category,\n compactCategoryAssignments(category, assignments, catalog),\n ])\n )\n}\n\nfunction compactStackAssignments(\n stack: Record<string, Record<string, unknown[]>>,\n catalog: CompileCatalog\n): Record<string, Record<string, unknown>> {\n return Object.fromEntries(\n Object.entries(stack)\n .map(\n ([agent, categories]) =>\n [agent, compactCategories(categories, catalog)] as const\n )\n .filter(([, categories]) => Object.keys(categories).length > 0)\n )\n}\n\nexport function generateBlankGlobalConfigSource(): string {\n return `import type { ProjectConfig } from ${quoteText(CONFIG_TYPES_SPECIFIER)}\n\nexport default {\n name: ${quoteText(GLOBAL_CONFIG_NAME)},\n skills: [],\n agents: [],\n selectedDomains: [],\n} satisfies ProjectConfig\\n`\n}\n","/**\n * Emits an install's `config.ts` and `config-types.ts` already prettier-formatted under the user's\n * settings (`semi: false, singleQuote: true, printWidth: 100, trailingComma: \"all\"`). Prettier is\n * not imported: it would bundle the TypeScript parser into the CLI and the editor preview.\n * `contract/emission-scenarios.test.ts` checks prettier leaves the output unchanged.\n */\n\nconst PRINT_WIDTH = 100\n\nexport const INDENT_STEP = 2\n\n/** Prettier's `isObjectPropertyWithShortKey`: a key narrower than this keeps its value beside it. */\nconst SHORT_KEY_WIDTH = INDENT_STEP + 3\n\nconst PREFERRED_QUOTE = \"'\"\nconst FALLBACK_QUOTE = '\"'\n\n/** `quoteProps: \"as-needed\"` leaves a plain identifier unquoted. */\nconst BARE_KEY = /^[A-Za-z_$][A-Za-z0-9_$]*$/\n\nconst EMPTY_ARRAY = \"[]\"\nconst EMPTY_RECORD = \"{}\"\n\nexport function isKeyedRecord(\n value: unknown\n): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n}\n\n/** Prettier's pick: the preferred quote unless swapping saves escapes; a tie keeps it. */\nexport function quoteText(value: string): string {\n const preferred = occurrences(value, PREFERRED_QUOTE)\n const fallback = occurrences(value, FALLBACK_QUOTE)\n const quote = preferred > fallback ? FALLBACK_QUOTE : PREFERRED_QUOTE\n\n return `${quote}${escapedFor(value, quote)}${quote}`\n}\n\nexport function renderKey(key: string): string {\n return BARE_KEY.test(key) ? key : quoteText(key)\n}\n\n/** A comment is an entry because a `//` line is what forces the array to break. */\nexport type ArrayEntry =\n | { kind: \"value\"; value: unknown }\n | { kind: \"source\"; source: string }\n | { kind: \"comment\"; text: string }\n\nexport function valueEntries(values: readonly unknown[]): ArrayEntry[] {\n return values.map((value) => ({ kind: \"value\", value }))\n}\n\nexport function commentEntry(text: string): ArrayEntry {\n return { kind: \"comment\", text }\n}\n\nexport function sourceEntry(source: string): ArrayEntry {\n return { kind: \"source\", source }\n}\n\nexport type LinePosition = {\n /** Columns of indentation the line starts at, and its closing line returns to. */\n indent: number\n /** What precedes the value on its first line, after the indentation. */\n prefix: string\n /** What follows the value on its last line. */\n suffix: string\n /** The printed key, when the value is an object property's. */\n key?: string\n}\n\nexport function renderValueLine(\n value: unknown,\n position: LinePosition\n): string {\n return line(\n renderValue(value, position),\n movesBelowItsPrefix(value),\n position\n )\n}\n\nexport function renderArrayLine(\n entries: readonly ArrayEntry[],\n position: LinePosition\n): string {\n return line(renderArray(entries, position), entries.length === 0, position)\n}\n\nexport type UnionLayout = \"inline\" | \"indented\" | \"stacked\"\n\nexport type BrokenUnionLayout = Exclude<UnionLayout, \"inline\">\n\nexport type UnionPosition = {\n /** Columns before the union on the line it would sit inline on. */\n headWidth: number\n /** Columns after it on that same line. */\n tailWidth: number\n /** Indentation the union's own lines take once it leaves that line. */\n bodyIndent: number\n}\n\n/** Inline if the line fits, else its own indented line if that fits, else one member per line. */\nexport function unionLayout(\n members: readonly string[],\n position: UnionPosition\n): UnionLayout {\n const flat = flatUnion(members)\n const inlineWidth = position.headWidth + flat.length + position.tailWidth\n\n return inlineWidth <= PRINT_WIDTH\n ? \"inline\"\n : brokenUnionLayout(members, position.bodyIndent)\n}\n\n/** For sectioned unions, whose `// Custom` heading already broke the line. */\nexport function brokenUnionLayout(\n members: readonly string[],\n bodyIndent: number\n): BrokenUnionLayout {\n return bodyIndent + flatUnion(members).length <= PRINT_WIDTH\n ? \"indented\"\n : \"stacked\"\n}\n\nexport function renderUnionBody(\n members: readonly string[],\n layout: BrokenUnionLayout,\n bodyIndent: number\n): string {\n const padding = spaces(bodyIndent)\n\n return layout === \"indented\"\n ? `${padding}${flatUnion(members)}`\n : members.map((member) => `${padding}| ${member}`).join(\"\\n\")\n}\n\nexport function flatUnion(members: readonly string[]): string {\n return members.join(\" | \")\n}\n\nexport function renderTypeImportLine(\n specifiers: readonly string[],\n modulePath: string\n): string {\n const from = ` from ${quoteText(modulePath)}`\n const inline = `import type { ${specifiers.join(\", \")} }${from}`\n if (inline.length <= PRINT_WIDTH) return inline\n\n const lines = specifiers.map(\n (specifier) => `${spaces(INDENT_STEP)}${specifier},`\n )\n return [\"import type {\", ...lines, `}${from}`].join(\"\\n\")\n}\n\n/** An array element (empty prefix) has nothing to move under and stays put. */\nfunction line(\n rendered: string,\n mayMoveBelowPrefix: boolean,\n position: LinePosition\n): string {\n const prefix = position.prefix.trimEnd()\n if (\n !mayMoveBelowPrefix ||\n prefix === \"\" ||\n hasShortKey(position) ||\n fits(rendered, position)\n ) {\n return asLine(rendered, position)\n }\n\n const body = `${spaces(position.indent + INDENT_STEP)}${rendered}${position.suffix}`\n return `${spaces(position.indent)}${prefix}\\n${body}`\n}\n\nfunction hasShortKey({ key }: LinePosition): boolean {\n return key !== undefined && key.length < SHORT_KEY_WIDTH\n}\n\n/**\n * Measured against prettier 3.9: strings, `null` and empty arrays/records move below their prefix;\n * numbers and booleans stay on the line however wide.\n */\nfunction movesBelowItsPrefix(value: unknown): boolean {\n if (typeof value === \"string\" || value === null) return true\n if (Array.isArray(value)) return value.length === 0\n return isKeyedRecord(value) && Object.keys(value).length === 0\n}\n\nfunction asLine(rendered: string, position: LinePosition): string {\n return `${spaces(position.indent)}${position.prefix}${rendered}${position.suffix}`\n}\n\nfunction renderValue(value: unknown, position: LinePosition): string {\n if (Array.isArray(value)) return renderArray(valueEntries(value), position)\n if (isKeyedRecord(value)) return renderRecord(value, position)\n return renderScalar(value)\n}\n\nfunction renderArray(\n entries: readonly ArrayEntry[],\n position: LinePosition\n): string {\n // Breaking it would print `[` and `]` on two lines; `line` moves it below its prefix instead.\n if (entries.length === 0) return EMPTY_ARRAY\n\n const flat = flatArray(entries)\n if (flat !== undefined && fits(flat, position)) return flat\n\n const inner = position.indent + INDENT_STEP\n const lines = entries.map((entry) => renderEntryLine(entry, inner))\n return [\"[\", ...lines, `${spaces(position.indent)}]`].join(\"\\n\")\n}\n\nfunction renderEntryLine(entry: ArrayEntry, indent: number): string {\n if (entry.kind === \"comment\") return `${spaces(indent)}// ${entry.text}`\n if (entry.kind === \"source\") return `${spaces(indent)}${entry.source},`\n return renderValueLine(entry.value, { indent, prefix: \"\", suffix: \",\" })\n}\n\nfunction renderRecord(\n record: Record<string, unknown>,\n position: LinePosition\n): string {\n const properties = Object.entries(record)\n if (properties.length === 0) return EMPTY_RECORD\n\n const flat = flatRecord(record)\n if (fits(flat, position)) return flat\n\n const inner = position.indent + INDENT_STEP\n const lines = properties.map(([key, value]) =>\n renderValueLine(value, propertyPosition(key, inner))\n )\n return [\"{\", ...lines, `${spaces(position.indent)}}`].join(\"\\n\")\n}\n\nexport function propertyPosition(key: string, indent: number): LinePosition {\n const printed = renderKey(key)\n return { indent, prefix: `${printed}: `, suffix: \",\", key: printed }\n}\n\nfunction flatArray(entries: readonly ArrayEntry[]): string | undefined {\n const items: string[] = []\n\n for (const entry of entries) {\n // A `//` line cannot fold onto one line.\n if (entry.kind === \"comment\") return undefined\n items.push(entry.kind === \"source\" ? entry.source : flatValue(entry.value))\n }\n\n return flatList(items)\n}\n\nfunction flatValue(value: unknown): string {\n if (Array.isArray(value)) return flatList(value.map(flatValue))\n if (isKeyedRecord(value)) return flatRecord(value)\n return renderScalar(value)\n}\n\nfunction flatList(items: readonly string[]): string {\n return items.length === 0 ? EMPTY_ARRAY : `[${items.join(\", \")}]`\n}\n\nfunction flatRecord(record: Record<string, unknown>): string {\n const properties = Object.entries(record).map(\n ([key, value]) => `${renderKey(key)}: ${flatValue(value)}`\n )\n return properties.length === 0 ? EMPTY_RECORD : `{ ${properties.join(\", \")} }`\n}\n\nfunction renderScalar(value: unknown): string {\n return typeof value === \"string\" ? quoteText(value) : String(value)\n}\n\nfunction fits(flat: string, position: LinePosition): boolean {\n const width =\n position.indent +\n position.prefix.length +\n flat.length +\n position.suffix.length\n\n return width <= PRINT_WIDTH\n}\n\nfunction occurrences(value: string, character: string): number {\n return value.split(character).length - 1\n}\n\n/** JSON escaping, with the escape moved onto whichever quote encloses the string. */\nfunction escapedFor(value: string, quote: string): string {\n const jsonBody = JSON.stringify(value).slice(1, -1)\n if (quote === FALLBACK_QUOTE) return jsonBody\n\n return jsonBody.replaceAll('\\\\\"', '\"').replaceAll(\"'\", \"\\\\'\")\n}\n\nexport function spaces(count: number): string {\n return \" \".repeat(count)\n}\n","// The built-ins widen keys to `string`; each cast restores `K`.\nexport function typedEntries<K extends string, V>(\n obj: Partial<Record<K, V>>\n): [K, V][] {\n return Object.entries(obj) as [K, V][]\n}\n\nexport function typedKeys<K extends string>(\n obj: Partial<Record<K, unknown>>\n): K[] {\n return Object.keys(obj) as K[]\n}\n\nexport function typedFromEntries<K extends string, V>(\n entries: Iterable<readonly [K, V]>\n): Partial<Record<K, V>> {\n return Object.fromEntries(entries) as Partial<Record<K, V>>\n}\n","import { indexBy, omit, pick, uniqueBy } from \"remeda\";\nimport { HAND_WRITTEN_FIELDS } from \"@workspace/compile/config-source\";\n\nimport type { ProjectConfig } from \"../../types\";\nimport type { AgentScopeConfig, SkillConfig } from \"../../types/config\";\nimport { getProjectConfigPath } from \"../installation/install-base-dir\";\nimport { loadProjectConfig, type LoadedProjectConfig } from \"./project-config\";\nimport { isGlobalTombstone, isProjectOwned, type ScopedEntry } from \"./scope-predicates\";\n\n/**\n * How authoritative `newConfig` is over absent entries: `\"all\"` (global edit) drops any; `\"owned\"`\n * (project edit) drops absent project-owned ones only; `undefined` (init) never drops.\n */\nexport type AuthoritativeScope = \"all\" | \"owned\";\n\ntype MergeContext = {\n projectDir: string;\n authoritativeScope?: AuthoritativeScope;\n};\n\nexport type MergeResult = {\n config: ProjectConfig;\n merged: boolean;\n existingConfigPath?: string;\n};\n\n/** How one roster's entries are told apart: the compound key, and the name or id it extends. */\ntype RosterIdentity<Entry> = {\n keyOf: (entry: Entry) => string;\n identityOf: (entry: Entry) => string;\n};\n\n/** The key adds scope and the excluded flag, so scoped entries and tombstones stay distinct. */\nfunction rosterIdentity<Entry extends ScopedEntry>(\n identityOf: (entry: Entry) => string,\n): RosterIdentity<Entry> {\n return {\n keyOf: (entry) => `${identityOf(entry)}:${entry.scope}${entry.excluded ? \":excluded\" : \"\"}`,\n identityOf,\n };\n}\n\nconst AGENT_IDENTITY = rosterIdentity<AgentScopeConfig>((agent) => agent.name);\n\nconst SKILL_IDENTITY = rosterIdentity<SkillConfig>((skill) => skill.id);\n\n/** Project edits own project-scoped entries and their global tombstones, not inherited globals. */\nfunction isWithinSessionAuthority(entry: ScopedEntry, scope: AuthoritativeScope): boolean {\n if (scope === \"all\") return true;\n return isProjectOwned(entry);\n}\n\n/**\n * Replaces entries by compound key; drops an entry whose name the incoming roster manages under\n * another key, a dual-scope entry the incoming roster dropped, or an absent in-authority one.\n */\nfunction mergeRoster<Entry extends ScopedEntry>(\n incoming: Entry[],\n existing: Entry[],\n identity: RosterIdentity<Entry>,\n authoritativeScope: AuthoritativeScope | undefined,\n): Entry[] {\n const incomingByKey = indexBy(incoming, identity.keyOf);\n const existingKeys = new Set(existing.map(identity.keyOf));\n const isDroppedByEdit = editDrops(incoming, existing, identity, authoritativeScope);\n\n const updatedExisting = existing.flatMap((entry) => {\n const matching = incomingByKey[identity.keyOf(entry)];\n if (matching !== undefined) return [matching];\n return isDroppedByEdit(entry) ? [] : [entry];\n });\n const added = incoming.filter((entry) => !existingKeys.has(identity.keyOf(entry)));\n return uniqueBy([...updatedExisting, ...added], identity.keyOf);\n}\n\n/** Whether the edit drops an existing entry that nothing incoming shares a compound key with. */\nfunction editDrops<Entry extends ScopedEntry>(\n incoming: Entry[],\n existing: Entry[],\n identity: RosterIdentity<Entry>,\n authoritativeScope: AuthoritativeScope | undefined,\n): (entry: Entry) => boolean {\n const incomingIdentities = new Set(incoming.map(identity.identityOf));\n // A global tombstone marks a dual-scope entry; with nothing incoming for it, both rows drop.\n const dualScopeIdentities = new Set(existing.filter(isGlobalTombstone).map(identity.identityOf));\n\n return (entry) =>\n // The incoming roster manages this name under another key: the edit dropped this row.\n incomingIdentities.has(identity.identityOf(entry)) ||\n dualScopeIdentities.has(identity.identityOf(entry)) ||\n (authoritativeScope !== undefined && isWithinSessionAuthority(entry, authoritativeScope));\n}\n\ntype MergeOptions = Pick<MergeContext, \"authoritativeScope\">;\n\n/**\n * Existing identity fields win; `newConfig` is authoritative for every name or id it references. A\n * final compound-key dedup collapses on-disk duplicates. A skill the run could not resolve is\n * removed like any other absent entry.\n */\nexport function mergeConfigs(\n newConfig: ProjectConfig,\n existingConfig: ProjectConfig,\n options?: MergeOptions,\n): ProjectConfig {\n const merged = { ...newConfig };\n\n if (existingConfig.name) {\n merged.name = existingConfig.name;\n }\n\n if (existingConfig.description) {\n merged.description = existingConfig.description;\n }\n\n if (existingConfig.marketplace && !newConfig.marketplace) {\n merged.marketplace = existingConfig.marketplace;\n }\n\n merged.agents = mergeRoster(\n merged.agents,\n existingConfig.agents,\n AGENT_IDENTITY,\n options?.authoritativeScope,\n );\n merged.skills = mergeRoster(\n merged.skills,\n existingConfig.skills,\n SKILL_IDENTITY,\n options?.authoritativeScope,\n );\n\n // `{}` is a deliberate mutator output; only an undefined stack keeps the existing one.\n if (newConfig.stack === undefined && existingConfig.stack) {\n merged.stack = existingConfig.stack;\n }\n\n if (existingConfig.author) {\n merged.author = existingConfig.author;\n }\n\n // The stored name labels the marketplace it was recorded beside.\n if (existingConfig.marketplaceName && merged.marketplace === existingConfig.marketplace) {\n merged.marketplaceName = existingConfig.marketplaceName;\n }\n\n // Hand-written fields have no other record, so a rewrite must keep them.\n Object.assign(merged, pick(existingConfig, HAND_WRITTEN_FIELDS));\n\n // The selection never carries registered projects; losing them silently stops propagation.\n if (existingConfig.projects && !newConfig.projects) {\n merged.projects = existingConfig.projects;\n }\n\n return merged;\n}\n\n/** What describes the global installation rather than any project under it. */\nconst GLOBAL_IDENTITY_FIELDS = [...HAND_WRITTEN_FIELDS, \"description\"] as const;\n\n/**\n * A config from the home fallback lends every field except its name, its description and the\n * hand-written fields: the incoming configuration describes the project.\n */\nfunction existingConfigForMerge(\n loaded: LoadedProjectConfig,\n projectDir: string,\n ownName: string,\n): ProjectConfig {\n // Compared against the same provider's path, or a project's own config reads as inherited.\n const isProjectsOwnFile = loaded.configPath === getProjectConfigPath(projectDir, loaded.provider);\n if (isProjectsOwnFile) return loaded.config;\n\n return { ...omit(loaded.config, GLOBAL_IDENTITY_FIELDS), name: ownName };\n}\n\nexport async function mergeWithExistingConfig(\n newConfig: ProjectConfig,\n context: MergeContext,\n): Promise<MergeResult> {\n const existingFullConfig = await loadProjectConfig(context.projectDir);\n if (!existingFullConfig) return { config: { ...newConfig }, merged: false };\n\n const existingConfig = existingConfigForMerge(\n existingFullConfig,\n context.projectDir,\n newConfig.name,\n );\n return {\n config: mergeConfigs(newConfig, existingConfig, context),\n merged: true,\n existingConfigPath: existingFullConfig.configPath,\n };\n}\n","import os from \"os\";\nimport path from \"path\";\nimport type { z } from \"zod\";\nimport { fileExists } from \"../../utils/fs\";\nimport { verbose, warn } from \"../../utils/logger\";\nimport { getErrorMessage } from \"../../utils/errors\";\nimport type { Provider } from \"../../consts\";\nimport type { ProjectConfig, ValidationResult } from \"../../types\";\nimport { normalizeStackRecord } from \"../stacks/stacks-loader\";\nimport { projectConfigLoaderSchema } from \"../schemas\";\nimport { formatZodErrors } from \"../schema-validator\";\nimport { getProjectConfigPath } from \"../installation/install-base-dir\";\nimport { providerInUse } from \"../installation/install-layout\";\nimport { providerToNameAt } from \"../installation/provider-to-name\";\nimport { isHomeDirectory } from \"../installation/is-home-directory\";\nimport type { ScopeKind } from \"../installation/source-scopes\";\nimport { loadConfig, NO_VALID_DEFAULT_EXPORT } from \"./config-loader\";\n\nexport type LoadedProjectConfig = {\n config: ProjectConfig;\n configPath: string;\n /** Carried on the read because only the folder records it. */\n provider: Provider;\n};\n\n/**\n * A config that exists but cannot be loaded; never collapse it into the `null` of a missing file.\n */\nexport class ConfigLoadError extends Error {\n readonly scope: ScopeKind;\n /** Named with `--provider` in a remedy handed out for this installation; beside another only. */\n readonly providerToName: Provider | undefined;\n\n constructor(\n readonly configPath: string,\n readonly reason: string,\n /** The directory whose installation this config is: a project, or the home directory. */\n readonly scopeRoot: string,\n provider: Provider,\n ) {\n super(`Config at '${configPath}' could not be loaded: ${reason}`);\n this.name = \"ConfigLoadError\";\n this.scope = isHomeDirectory(scopeRoot) ? \"global\" : \"project\";\n this.providerToName = providerToNameAt(scopeRoot, provider);\n }\n}\n\n/** `null` only when the file is absent; throws `ConfigLoadError` when it exists but cannot load. */\nexport async function loadProjectConfigFromDir(\n projectDir: string,\n provider: Provider,\n): Promise<LoadedProjectConfig | null> {\n return loadProjectConfigAt(getProjectConfigPath(projectDir, provider), projectDir, provider);\n}\n\n/** As `loadProjectConfigFromDir`, at a path the caller names rather than the resolver's pick. */\nexport async function loadProjectConfigAt(\n configPath: string,\n projectDir: string,\n provider: Provider,\n): Promise<LoadedProjectConfig | null> {\n const scope = isHomeDirectory(projectDir) ? \"global\" : \"project\";\n const scopeLabel = scope === \"project\" ? \"Project\" : \"Global\";\n\n if (!(await fileExists(configPath))) {\n verbose(`${scopeLabel} config not found at ${configPath}`);\n return null;\n }\n\n // The file exists: from here any failure is a ConfigLoadError, never `null`.\n const refuse = (reason: string) => new ConfigLoadError(configPath, reason, projectDir, provider);\n const parsed = await parseConfigFile(configPath, refuse);\n const config = asProjectConfig(parsed, projectDir);\n warnOfDefaultedFields(parsed, configPath);\n\n verbose(`Loaded ${scope} config from ${configPath}`);\n return {\n config,\n configPath,\n provider,\n };\n}\n\ntype ParsedProjectConfig = z.infer<typeof projectConfigLoaderSchema>;\n\n/** The file's default export, held to the lenient loader schema. */\nasync function parseConfigFile(\n configPath: string,\n refuse: (reason: string) => ConfigLoadError,\n): Promise<ParsedProjectConfig> {\n let raw: unknown;\n try {\n raw = await loadConfig<ProjectConfig>(configPath);\n } catch (error) {\n throw refuse(getErrorMessage(error));\n }\n\n if (!raw || typeof raw !== \"object\") throw refuse(NO_VALID_DEFAULT_EXPORT);\n\n const result = projectConfigLoaderSchema.safeParse(raw);\n if (!result.success) throw refuse(formatZodErrors(result.error).join(\"; \"));\n return result.data;\n}\n\n/** Normalizes the stack before claiming ProjectConfig, so the cast below is the only one. */\nfunction asProjectConfig(parsed: ParsedProjectConfig, projectDir: string): ProjectConfig {\n const normalizedStack = parsed.stack ? normalizeStackRecord(parsed.stack) : undefined;\n\n // Boundary cast: the loader schema is lenient about the string unions; validateProjectConfig\n // enforces the strict shape after load.\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- see above\n return {\n ...parsed,\n name: parsed.name ?? path.basename(projectDir),\n skills: parsed.skills ?? [],\n agents: parsed.agents ?? [],\n ...(normalizedStack && { stack: normalizedStack }),\n } as ProjectConfig;\n}\n\nfunction warnOfDefaultedFields(parsed: ParsedProjectConfig, configPath: string): void {\n if (parsed.name === undefined) {\n warn(\n `Project config at '${configPath}' is missing required 'name' field — defaulting to directory name`,\n );\n }\n if (parsed.skills === undefined) {\n warn(`Project config at '${configPath}' is missing 'skills' array — defaulting to empty`);\n }\n}\n\n/** The config of whichever installation `dir` holds, read off the folder. */\nexport async function loadInstalledConfig(dir: string): Promise<LoadedProjectConfig | null> {\n return loadProjectConfigFromDir(dir, providerInUse(dir));\n}\n\n/** The project's own config dir plus the global one it inlines; one dir at the home root. */\nexport function configDirsInPlay(projectDir: string): string[] {\n return isHomeDirectory(projectDir) ? [projectDir] : [projectDir, os.homedir()];\n}\n\n/** Shared by `ensureConfigReadable` and `doctor`, so both agree on which configs are in play. */\nexport async function findConfigLoadFailures(projectDir: string): Promise<ConfigLoadError[]> {\n const outcomes = await Promise.all(configDirsInPlay(projectDir).map(configLoadFailure));\n return outcomes.filter((failure): failure is ConfigLoadError => failure !== undefined);\n}\n\nasync function configLoadFailure(dir: string): Promise<ConfigLoadError | undefined> {\n try {\n await loadInstalledConfig(dir);\n return undefined;\n } catch (error) {\n if (error instanceof ConfigLoadError) return error;\n throw error;\n }\n}\n\n/** The project's config, falling back to the global one of the same provider. */\nexport async function loadProjectConfig(projectDir: string): Promise<LoadedProjectConfig | null> {\n const provider = providerInUse(projectDir);\n const projectResult = await loadProjectConfigFromDir(projectDir, provider);\n if (projectResult) return projectResult;\n\n if (!isHomeDirectory(projectDir)) {\n return loadProjectConfigFromDir(os.homedir(), provider);\n }\n\n return null;\n}\n\n/** On top of the lenient schema, a usable config also needs `name` and `agents`. */\nexport function validateProjectConfig(config: unknown): ValidationResult {\n const result = projectConfigLoaderSchema.safeParse(config);\n if (!result.success) {\n return { valid: false, errors: formatZodErrors(result.error), warnings: [] };\n }\n\n const errors = [\n ...(result.data.name ? [] : [\"name is required and must be a string\"]),\n ...(result.data.agents ? [] : [\"agents is required and must be an array\"]),\n ];\n return { valid: errors.length === 0, errors, warnings: [] };\n}\n","import path from \"path\";\nimport { flatMap, groupBy, mapValues, partition, pipe, unique, uniqueBy } from \"remeda\";\nimport { getErrorMessage } from \"../../utils/errors\";\nimport { verbose, warn } from \"../../utils/logger\";\nimport { matrix } from \"../matrix/matrix-provider\";\nimport type {\n AgentName,\n SkillAssignment,\n SkillId,\n SkillReference,\n Stack,\n StackAgentConfig,\n Category,\n} from \"../../types\";\nimport { stacksConfigSchema } from \"../schemas\";\nimport { typedEntries } from \"../../utils/typed-object\";\nimport { isSkillAssignment } from \"../../utils/type-guards\";\nimport { LOCAL_PSEUDO_CATEGORY, STACKS_FILE_PATH } from \"../../consts\";\nimport { loadConfig } from \"../configuration/config-loader\";\nimport { offersBuiltInStacks } from \"../configuration/config\";\nimport { defaultStacks } from \"../configuration/default-stacks\";\n\nconst stacksCache = new Map<string, Stack[]>();\n\n/**\n * Accepts a bare string, a single `{ id, preloaded }` object, or an array of either; a bare string\n * becomes `preloaded: false`.\n */\nexport function normalizeAgentConfig(agentConfig: Record<string, unknown>): StackAgentConfig {\n // Boundary casts: Zod-parsed config is loose until normalized here.\n return mapValues(agentConfig, (value) => {\n const items = Array.isArray(value) ? value : [value];\n return items.map((item): SkillAssignment => {\n if (typeof item === \"string\") return { id: item as SkillId, preloaded: false };\n if (isSkillAssignment(item)) return item;\n warn(`Malformed skill assignment in stack data: ${JSON.stringify(item)}`);\n return item as SkillAssignment;\n });\n });\n}\n\n/** `undefined` for an id the matrix lacks or a skill in the `local` pseudo-category. */\nfunction liveCategoryOf(skillId: SkillId): Category | undefined {\n const category = matrix.skills[skillId]?.category;\n if (category === undefined || category === LOCAL_PSEUDO_CATEGORY) return undefined;\n // TypeScript narrows CategoryPath to Category after excluding \"local\"\n return category;\n}\n\ntype PlacedAssignment = {\n storedCategory: Category;\n liveCategory: Category;\n assignment: SkillAssignment;\n};\n\nfunction placeAssignments(agentConfig: StackAgentConfig): PlacedAssignment[] {\n return typedEntries<Category, SkillAssignment[]>(agentConfig).flatMap(\n ([storedCategory, assignments]) =>\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- Object.entries drops the `| undefined` a Partial<Record> admits\n (assignments ?? []).map((assignment) => ({\n storedCategory,\n liveCategory: liveCategoryOf(assignment.id) ?? storedCategory,\n assignment,\n })),\n );\n}\n\n/**\n * Re-keys a saved stack under each skill's live category, since only the id is identity. A skill\n * already under its live category wins a collision with a stale duplicate of itself.\n */\nfunction rekeyToLiveCategories(agentConfig: StackAgentConfig): StackAgentConfig {\n const [settled, moved] = partition(\n placeAssignments(agentConfig),\n (placed) => placed.liveCategory === placed.storedCategory,\n );\n\n if (moved.length > 0) {\n verbose(\n `Re-keyed stack entries to their live category: ` +\n moved\n .map((p) => `${p.assignment.id} (${p.storedCategory} -> ${p.liveCategory})`)\n .join(\", \"),\n );\n }\n\n return mapValues(\n groupBy([...settled, ...moved], (placed) => placed.liveCategory),\n (placed) =>\n uniqueBy(\n placed.map((p) => p.assignment),\n (assignment) => assignment.id,\n ),\n );\n}\n\n/** The persisted-config boundary; a source's `stacks.ts` skips it, its keys being its own. */\nexport function normalizeStackRecord(\n rawStack: Record<string, Record<string, unknown>>,\n): Record<string, StackAgentConfig> {\n return mapValues(rawStack, (agentConfig) =>\n rekeyToLiveCategories(normalizeAgentConfig(agentConfig)),\n );\n}\n\nexport async function loadStacks(configDir: string, stacksFile?: string): Promise<Stack[]> {\n const resolvedStacksFile = stacksFile ?? STACKS_FILE_PATH;\n const cacheKey = `${configDir}:${resolvedStacksFile}`;\n const cached = stacksCache.get(cacheKey);\n if (cached) return cached;\n\n const stacksPath = path.join(configDir, resolvedStacksFile);\n\n try {\n const raw = await loadConfig(stacksPath, stacksConfigSchema);\n\n if (raw == null) {\n verbose(`No stacks file found at ${stacksPath}`);\n return [];\n }\n\n // Boundary casts: the schema outputs loose records; normalization makes SkillAssignment[].\n const stacks: Stack[] = raw.stacks.map((stack) => ({\n ...stack,\n agents: mapValues(\n stack.agents as Partial<Record<AgentName, Record<string, unknown>>>,\n (agentConfig) => normalizeAgentConfig(agentConfig),\n ),\n }));\n\n stacksCache.set(cacheKey, stacks);\n verbose(`Loaded ${stacks.length} stacks from ${stacksPath}`);\n\n return stacks;\n } catch (error) {\n const errorMessage = getErrorMessage(error);\n throw new Error(`Failed to load stacks from '${stacksPath}': ${errorMessage}`, {\n cause: error,\n });\n }\n}\n\n/** Built-in stacks stand in for the public catalogue only, as `resolveOfferedStacks` offers. */\nexport async function loadStackById(\n stackId: string,\n configDir: string,\n source: string,\n): Promise<Stack | null> {\n const stacks = await loadStacks(configDir);\n const stack = stacks.find((s) => s.id === stackId);\n\n if (stack) {\n verbose(`Found stack: ${stack.name} (${stackId})`);\n return stack;\n }\n\n if (!(await offersBuiltInStacks(configDir, source))) {\n verbose(\n `Marketplace '${source}' does not ship stack '${stackId}', and gets no built-in stand-in`,\n );\n return null;\n }\n\n const defaultStack = defaultStacks.find((s) => s.id === stackId) ?? null;\n if (defaultStack) {\n verbose(`Found default stack: ${defaultStack.name} (${stackId})`);\n } else {\n verbose(`Stack '${stackId}' not found in the default marketplace or the built-ins`);\n }\n return defaultStack;\n}\n\n/** One wording for both callers that turn a null from `loadStackById` into a failure. */\nexport function stackNotOfferedMessage(stackId: string, source: string): string {\n return (\n `Stack '${stackId}' is not a stack the source '${source}' offers. ` +\n `A marketplace ships its own stacks; the CLI's built-in ones belong to the default ` +\n `public marketplace alone.`\n );\n}\n\n/** Exported so every surface writes the fallback word for word; the editor preview mirrors it. */\nexport function defaultUsageGuidance(category: string): string {\n return `Use when working with ${category}.`;\n}\n\n/** The skill's own `usageGuidance`, or the category fallback when it has none or it is blank. */\nfunction statedUsageFor(skillId: SkillId, category: Category): string {\n const stated = matrix.skills[skillId]?.usageGuidance;\n return stated !== undefined && stated.trim() !== \"\" ? stated : defaultUsageGuidance(category);\n}\n\nexport function resolveAgentConfigToSkills(agentConfig: StackAgentConfig): SkillReference[] {\n return typedEntries<Category, SkillAssignment[]>(agentConfig).flatMap(([category, assignments]) =>\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- Object.entries drops the `| undefined` a Partial<Record> admits\n (assignments ?? []).map((assignment): SkillReference => ({\n id: assignment.id,\n usage: statedUsageFor(assignment.id, category),\n preloaded: assignment.preloaded ?? false,\n })),\n );\n}\n\nexport function getStackSkillIds(stack: Record<string, StackAgentConfig>): SkillId[] {\n return pipe(\n Object.values(stack),\n flatMap(resolveAgentConfigToSkills),\n (refs) => refs.map((r) => r.id),\n unique(),\n );\n}\n","import path from \"path\";\nimport { parse as parseYaml, stringify as stringifyYaml } from \"yaml\";\n\nimport { fileExists, readFile, writeFile } from \"../../utils/fs\";\nimport { getCurrentDate } from \"../versioning\";\nimport { SCHEMA_PATHS, STANDARD_FILES, YAML_FORMATTING } from \"../../consts\";\nimport { yamlSchemaComment, stripYamlSchemaComment } from \"../../utils/yaml-schema\";\nimport type { SkillId } from \"../../types\";\nimport { formatZodIssues, localSkillMetadataSchema } from \"../schemas\";\nimport { warn } from \"../../utils/logger\";\nimport { getErrorMessage } from \"../../utils/errors\";\n\n/** Provenance written under `forkedFrom` when a skill is copied locally. */\nexport type ForkedFromMetadata = {\n skillId: SkillId;\n /** SHA-256 hash of the source SKILL.md content at the time of installation */\n contentHash: string;\n /** ISO date string (YYYY-MM-DD) when the skill was installed or last updated */\n date: string;\n source?: string;\n /**\n * The skill's directory inside `source`; recorded only for a skill no catalogue resolves by id.\n */\n path?: string;\n};\n\n/** The index signature preserves fields written by other tools. */\nexport type LocalSkillMetadata = {\n forkedFrom?: ForkedFromMetadata;\n [key: string]: unknown;\n};\n\n/** `null` when absent, without `forkedFrom`, or invalid (warned). */\nexport async function readForkedFromMetadata(skillDir: string): Promise<ForkedFromMetadata | null> {\n const metadata = await readLocalSkillMetadata(skillDir);\n return metadata?.forkedFrom ?? null;\n}\n\n/** `null` when absent or invalid; uninstall uses it to tell CLI-installed skills apart. */\nexport async function readLocalSkillMetadata(skillDir: string): Promise<LocalSkillMetadata | null> {\n const metadataPath = path.join(skillDir, STANDARD_FILES.METADATA_YAML);\n\n if (!(await fileExists(metadataPath))) {\n return null;\n }\n\n const content = await readFile(metadataPath);\n const read = readYaml(content);\n\n if (!read.parsed) {\n warn(`Invalid metadata.yaml at ${metadataPath}: ${read.reason}`);\n return null;\n }\n\n const result = localSkillMetadataSchema.safeParse(read.value);\n\n if (!result.success) {\n warn(`Invalid metadata.yaml at ${metadataPath}: ${formatZodIssues(result.error.issues)}`);\n return null;\n }\n\n return result.data;\n}\n\n/**\n * Overwrites `{destPath}/metadata.yaml` with `forkedFrom` set, keeping existing fields when the\n * file parses; otherwise writes only `forkedFrom`, with a warning. `origin` is a bag so its two\n * strings cannot be swapped silently.\n */\nexport async function injectForkedFromMetadata(\n destPath: string,\n skillId: SkillId,\n contentHash: string,\n origin: Pick<ForkedFromMetadata, \"source\" | \"path\"> = {},\n): Promise<void> {\n const metadataPath = path.join(destPath, STANDARD_FILES.METADATA_YAML);\n const rawContent = await readFile(metadataPath);\n const { yamlContent } = stripYamlSchemaComment(rawContent);\n\n const metadata: LocalSkillMetadata = {\n ...existingMetadataFields(yamlContent, metadataPath),\n forkedFrom: {\n skillId,\n contentHash,\n date: getCurrentDate(),\n ...(origin.source !== undefined && { source: origin.source }),\n ...(origin.path !== undefined && { path: origin.path }),\n },\n };\n\n await writeMetadataYaml(metadataPath, metadata, `${yamlSchemaComment(SCHEMA_PATHS.metadata)}\\n`);\n}\n\nexport async function writeMetadataYaml(\n filePath: string,\n metadata: unknown,\n schemaComment = \"\",\n): Promise<void> {\n const yamlContent = stringifyYaml(metadata, { lineWidth: YAML_FORMATTING.LINE_WIDTH_NONE });\n await writeFile(filePath, schemaComment + yamlContent);\n}\n\ntype YamlRead =\n | { readonly parsed: true; readonly value: unknown }\n | { readonly parsed: false; readonly reason: string };\n\n/** Catches a syntax error, which throws before any schema `safeParse` runs. */\nfunction readYaml(content: string): YamlRead {\n try {\n return { parsed: true, value: parseYaml(content) };\n } catch (error) {\n return { parsed: false, reason: getErrorMessage(error) };\n }\n}\n\n/** Empty, with one warning, for either failure: the author's fields are about to be replaced. */\nfunction existingMetadataFields(\n yamlContent: string,\n metadataPath: string,\n): Partial<LocalSkillMetadata> {\n const read = readYaml(yamlContent);\n\n if (read.parsed) {\n const result = localSkillMetadataSchema.safeParse(read.value);\n if (result.success) return result.data;\n }\n\n warn(`Malformed metadata.yaml at '${metadataPath}' — existing fields may be lost`);\n return {};\n}\n","import { createHash } from \"crypto\";\nimport { readFile as readFileBytes } from \"fs/promises\";\nimport path from \"path\";\nimport { getErrorMessage } from \"../utils/errors\";\nimport { readFile, readFileSafe, writeFile, glob, fileExists } from \"../utils/fs\";\nimport { warn } from \"../utils/logger\";\nimport {\n DEFAULT_VERSION,\n MAX_PLUGIN_FILE_SIZE,\n STANDARD_FILES,\n HASH_PREFIX_LENGTH,\n} from \"../consts\";\nimport { pluginManifestSchema } from \"./schemas\";\nimport { SKILL_CONTENT_FILES, SKILL_CONTENT_DIRS } from \"./metadata-keys\";\n\nconst ISO_DATE_LENGTH = 10;\n\nexport function getCurrentDate(): string {\n return new Date().toISOString().slice(0, ISO_DATE_LENGTH);\n}\n\nexport function computeStringHash(content: string): string {\n const hash = createHash(\"sha256\");\n hash.update(content);\n return hash.digest(\"hex\").slice(0, HASH_PREFIX_LENGTH);\n}\n\nexport async function computeFileHash(filePath: string): Promise<string> {\n const content = await readFile(filePath);\n return computeStringHash(content);\n}\n\nexport async function computeSkillFolderHash(skillPath: string): Promise<string> {\n const contents: string[] = [];\n\n for (const fileName of SKILL_CONTENT_FILES) {\n const filePath = path.join(skillPath, fileName);\n if (await fileExists(filePath)) {\n const content = await readFile(filePath);\n contents.push(`${fileName}:${content}`);\n }\n }\n\n for (const dirName of SKILL_CONTENT_DIRS) {\n const dirPath = path.join(skillPath, dirName);\n if (await fileExists(dirPath)) {\n const files = await glob(\"**/*\", dirPath);\n for (const file of files.sort()) {\n const filePath = path.join(dirPath, file);\n const content = await readFile(filePath);\n contents.push(`${dirName}/${file}:${content}`);\n }\n }\n }\n\n const combined = contents.join(\"\\n---\\n\");\n return computeStringHash(combined);\n}\n\nconst CONTENT_HASH_FILE = \".content-hash\";\n\nfunction contentHashFileBeside(manifestPath: string): string {\n return manifestPath.replace(STANDARD_FILES.PLUGIN_JSON, CONTENT_HASH_FILE);\n}\n\nfunction parseMajorVersion(version: string): number {\n const [, major] = version.match(/^(\\d+)\\./) ?? [];\n return major === undefined ? 1 : parseInt(major, 10);\n}\n\nfunction bumpMajorVersion(version: string): string {\n const major = parseMajorVersion(version);\n return `${major + 1}.0.0`;\n}\n\nasync function readExistingPluginManifest(\n pluginDir: string,\n getManifestPath: (dir: string) => string,\n): Promise<{ version: string; contentHash: string | undefined } | null> {\n const manifestPath = getManifestPath(pluginDir);\n\n if (!(await fileExists(manifestPath))) {\n return null;\n }\n\n try {\n const version = await readManifestVersion(manifestPath);\n\n const hashFilePath = contentHashFileBeside(manifestPath);\n const contentHash = (await fileExists(hashFilePath))\n ? (await readFile(hashFilePath)).trim()\n : undefined;\n\n return { version, contentHash };\n } catch (error) {\n warn(`Failed to read plugin manifest at '${manifestPath}': ${getErrorMessage(error)}`);\n return null;\n }\n}\n\nasync function readManifestVersion(manifestPath: string): Promise<string> {\n const content = await readFileSafe(manifestPath, MAX_PLUGIN_FILE_SIZE);\n return pluginManifestSchema.parse(JSON.parse(content)).version ?? DEFAULT_VERSION;\n}\n\nasync function computeBytesHash(filePath: string): Promise<string> {\n return createHash(\"sha256\")\n .update(await readFileBytes(filePath))\n .digest(\"hex\");\n}\n\n/** NUL-delimited, since no path can hold a NUL. */\nasync function describeShippedFile(pluginDir: string, file: string): Promise<string> {\n return `${file}\\0${await computeBytesHash(path.join(pluginDir, file))}\\0`;\n}\n\n/** Every file in a plugin's folder, by path and bytes: what a host copies when it installs it. */\nexport async function computeShippedHash(pluginDir: string): Promise<string> {\n const files = await glob(\"**/*\", pluginDir, { dot: true });\n const described = await Promise.all(files.map((file) => describeShippedFile(pluginDir, file)));\n return createHash(\"sha256\").update(described.join(\"\")).digest(\"hex\");\n}\n\ntype EarlierBuild = { version: string; shippedHash: string };\n\n/**\n * Read before a rebuild clears the folder. Null where no build made it, and, warning, where its\n * manifest cannot be read.\n */\nexport async function readEarlierBuild(\n pluginDir: string,\n getManifestPath: (dir: string) => string,\n): Promise<EarlierBuild | null> {\n const manifestPath = getManifestPath(pluginDir);\n if (!(await fileExists(manifestPath))) return null;\n\n const version = await readManifestVersion(manifestPath).catch((error: unknown) => {\n warn(`Failed to read plugin manifest at '${manifestPath}': ${getErrorMessage(error)}`);\n return null;\n });\n if (version === null) return null;\n\n return { version, shippedHash: await computeShippedHash(pluginDir) };\n}\n\n/**\n * `shippedHash` is the rebuild's, made at the earlier build's version, so that the two differ only\n * where what the plugin ships does.\n */\nexport function versionAfterRebuild(earlier: EarlierBuild | null, shippedHash: string): string {\n if (!earlier) return DEFAULT_VERSION;\n return earlier.shippedHash === shippedHash ? earlier.version : bumpMajorVersion(earlier.version);\n}\n\nexport async function determinePluginVersion(\n newHash: string,\n pluginDir: string,\n getManifestPath: (dir: string) => string,\n): Promise<{ version: string; contentHash: string }> {\n const existing = await readExistingPluginManifest(pluginDir, getManifestPath);\n\n if (!existing) {\n return {\n version: DEFAULT_VERSION,\n contentHash: newHash,\n };\n }\n\n if (existing.contentHash !== newHash) {\n return {\n version: bumpMajorVersion(existing.version),\n contentHash: newHash,\n };\n }\n\n return {\n version: existing.version,\n contentHash: newHash,\n };\n}\n\nexport async function writeContentHash(\n pluginDir: string,\n contentHash: string,\n getManifestPath: (dir: string) => string,\n): Promise<void> {\n await writeFile(contentHashFileBeside(getManifestPath(pluginDir)), contentHash);\n}\n","export function yamlSchemaComment(schemaPath: string): string {\n return `# yaml-language-server: $schema=${schemaPath}`;\n}\n\n/** `schemaComment` keeps its trailing newline, or is empty when absent. */\nexport function stripYamlSchemaComment(content: string): {\n schemaComment: string;\n yamlContent: string;\n} {\n const lines = content.split(\"\\n\");\n if (lines[0]?.startsWith(\"# yaml-language-server:\")) {\n return { schemaComment: `${lines[0]}\\n`, yamlContent: lines.slice(1).join(\"\\n\") };\n }\n return { schemaComment: \"\", yamlContent: content };\n}\n","import path from \"path\";\n\nimport { copy, ensureDir, isPathWithin } from \"../../utils/fs\";\nimport { getErrorMessage } from \"../../utils/errors\";\nimport { plural } from \"../../utils/string\";\nimport { computeFileHash } from \"../versioning\";\nimport { EJECT_SOURCE, SOURCE_SRC_DIR, STANDARD_FILES } from \"../../consts\";\nimport type { ResolvedSkill, SkillId } from \"../../types\";\nimport type { SourceLoadResult } from \"../loading\";\nimport { getSkillById } from \"../matrix/matrix-provider\";\nimport { injectForkedFromMetadata } from \"./skill-metadata\";\n\nexport type CopiedSkill = {\n skillId: SkillId;\n contentHash: string;\n sourcePath: string;\n destPath: string;\n local?: boolean;\n};\n\nconst NULL_BYTE_PATTERN = /\\0/;\n\n/** Guards against path traversal such as `../../sensitive` in `skill.path`. */\nexport function validateSkillPath(\n resolvedPath: string,\n expectedParent: string,\n skillPath: string,\n): void {\n if (NULL_BYTE_PATTERN.test(skillPath)) {\n throw new Error(`Invalid skill path: '${skillPath}' contains null bytes`);\n }\n\n if (!isPathWithin(resolvedPath, expectedParent)) {\n throw new Error(\n `Invalid skill path: '${skillPath}' escapes expected directory '${path.resolve(expectedParent)}'`,\n );\n }\n}\n\nfunction resolveSkillPath(basePath: string, skillPath: string): string {\n const resolved = path.join(basePath, skillPath);\n validateSkillPath(resolved, basePath, skillPath);\n return resolved;\n}\n\nfunction getSkillSourcePath(skill: ResolvedSkill, rootDir: string): string {\n const srcDir = path.join(rootDir, SOURCE_SRC_DIR);\n return resolveSkillPath(srcDir, skill.path);\n}\n\nasync function generateSkillHash(skillSourcePath: string): Promise<string> {\n const skillMdPath = path.join(skillSourcePath, STANDARD_FILES.SKILL_MD);\n return computeFileHash(skillMdPath);\n}\n\nasync function copySkillTo(\n skill: ResolvedSkill,\n sourcePath: string,\n destPath: string,\n source?: string,\n): Promise<CopiedSkill> {\n const contentHash = await generateSkillHash(sourcePath);\n\n await ensureDir(path.dirname(destPath));\n await copy(sourcePath, destPath);\n\n // No directory: the marketplace resolves the id. Omitted, since undefined renders as a word.\n await injectForkedFromMetadata(destPath, skill.id, contentHash, {\n ...(source !== undefined && { source }),\n });\n\n return { skillId: skill.id, contentHash, sourcePath, destPath };\n}\n\nasync function resolveLocalCopiedSkill(\n skill: ResolvedSkill,\n localPath: string,\n): Promise<CopiedSkill> {\n const contentHash = await generateSkillHash(localPath);\n return {\n skillId: skill.id,\n sourcePath: localPath,\n destPath: localPath,\n contentHash,\n local: true,\n };\n}\n\n/**\n * Throws naming every failed id: `Promise.all` alone surfaces one ENOENT inside the source cache,\n * which the user cannot act on.\n */\nasync function copyEachSkill(\n selectedSkillIds: SkillId[],\n copyOne: (skillId: SkillId) => Promise<CopiedSkill>,\n): Promise<CopiedSkill[]> {\n const outcomes = await Promise.all(\n selectedSkillIds.map(async (skillId) => attemptCopy(skillId, copyOne)),\n );\n const failures = outcomes.filter(isCopyFailure);\n\n if (failures.length > 0) throw new Error(copyFailureMessage(failures, selectedSkillIds.length));\n\n return outcomes.filter(isCopySuccess).map((outcome) => outcome.copied);\n}\n\ntype CopySuccess = { skillId: SkillId; copied: CopiedSkill };\ntype CopyFailure = { skillId: SkillId; problem: string };\ntype CopyOutcome = CopySuccess | CopyFailure;\n\nasync function attemptCopy(\n skillId: SkillId,\n copyOne: (skillId: SkillId) => Promise<CopiedSkill>,\n): Promise<CopyOutcome> {\n try {\n return { skillId, copied: await copyOne(skillId) };\n } catch (error) {\n return { skillId, problem: getErrorMessage(error) };\n }\n}\n\nfunction isCopyFailure(outcome: CopyOutcome): outcome is CopyFailure {\n return \"problem\" in outcome;\n}\n\nfunction isCopySuccess(outcome: CopyOutcome): outcome is CopySuccess {\n return \"copied\" in outcome;\n}\n\nfunction copyFailureMessage(failures: CopyFailure[], attempted: number): string {\n const lines = failures.map((failure) => ` ${failure.skillId}: ${failure.problem}`);\n\n return `Could not copy ${failures.length} of ${plural(attempted, \"skill\")}:\\n${lines.join(\"\\n\")}`;\n}\n\nfunction getFlattenedSkillDestPath(skill: ResolvedSkill, localSkillsDir: string): string {\n return resolveSkillPath(localSkillsDir, skill.id);\n}\n\nasync function copySkillToLocalFlattened(\n skill: ResolvedSkill,\n localSkillsDir: string,\n sourceResult: SourceLoadResult,\n): Promise<CopiedSkill> {\n return copySkillTo(\n skill,\n getSkillSourcePath(skill, sourceResult.sourcePath),\n getFlattenedSkillDestPath(skill, localSkillsDir),\n sourceResult.sourceConfig.source,\n );\n}\n\nexport async function copySkillsToLocalFlattened(\n selectedSkillIds: SkillId[],\n localSkillsDir: string,\n sourceResult: SourceLoadResult,\n sourceSelections?: Partial<Record<SkillId, string>>,\n): Promise<CopiedSkill[]> {\n return copyEachSkill(selectedSkillIds, (skillId) =>\n copySelectedSkill(skillId, localSkillsDir, sourceResult, sourceSelections?.[skillId]),\n );\n}\n\n/**\n * From the source, unless the skill is a local one the user did not point at a remote source;\n * that one is copied from where it lives, or recorded in place when it already lives there.\n */\nasync function copySelectedSkill(\n skillId: SkillId,\n localSkillsDir: string,\n sourceResult: SourceLoadResult,\n selectedSource: string | undefined,\n): Promise<CopiedSkill> {\n const skill = getSkillById(skillId);\n const localPath = picksRemoteSource(selectedSource) ? undefined : localPathOf(skill);\n if (localPath === undefined) {\n return copySkillToLocalFlattened(skill, localSkillsDir, sourceResult);\n }\n\n const destPath = getFlattenedSkillDestPath(skill, localSkillsDir);\n if (path.resolve(localPath) === path.resolve(destPath)) {\n return resolveLocalCopiedSkill(skill, localPath);\n }\n\n return copyLocalSkillTo(skill, localPath, destPath);\n}\n\nfunction picksRemoteSource(selectedSource: string | undefined): boolean {\n return !!selectedSource && selectedSource !== EJECT_SOURCE;\n}\n\nfunction localPathOf(skill: ResolvedSkill): string | undefined {\n return skill.local && skill.localPath ? skill.localPath : undefined;\n}\n\nasync function copyLocalSkillTo(\n skill: ResolvedSkill,\n localPath: string,\n destPath: string,\n): Promise<CopiedSkill> {\n const contentHash = await generateSkillHash(localPath);\n await ensureDir(path.dirname(destPath));\n await copy(localPath, destPath);\n\n return { skillId: skill.id, sourcePath: localPath, destPath, contentHash };\n}\n","import path from \"path\";\nimport { parse as parseYaml } from \"yaml\";\nimport { getErrorMessage } from \"../../utils/errors\";\nimport {\n readFile,\n writeFile,\n ensureDir,\n glob,\n fileExists,\n copy,\n isPathWithin,\n isDirectoryEmpty,\n remove,\n} from \"../../utils/fs\";\nimport { log, verbose, warn } from \"../../utils/logger\";\nimport {\n generateSkillPluginManifest,\n writePluginManifest,\n getPluginManifestPath,\n} from \"../plugins\";\nimport { parseFrontmatter } from \"../loading\";\nimport {\n computeShippedHash,\n computeSkillFolderHash,\n readEarlierBuild,\n versionAfterRebuild,\n writeContentHash,\n} from \"../versioning\";\nimport type { PluginManifest, SkillFrontmatter } from \"../../types\";\nimport { formatZodIssues, skillMetadataLoaderSchema } from \"../schemas\";\nimport type { z } from \"zod\";\n\ntype SkillMetadata = z.infer<typeof skillMetadataLoaderSchema>;\nimport {\n DEFAULT_BRANDING,\n DEFAULT_VERSION,\n PLUGIN_MANIFEST_DIR,\n PLUGIN_MANIFEST_FILE,\n STANDARD_DIRS,\n STANDARD_FILES,\n} from \"../../consts\";\nimport { stripYamlSchemaComment } from \"../../utils/yaml-schema\";\nimport { plural } from \"../../utils/string\";\nimport { SKILL_CONTENT_FILES, SKILL_CONTENT_DIRS } from \"../metadata-keys\";\n\ntype SkillPluginOptions = {\n skillPath: string;\n outputDir: string;\n skillName?: string;\n};\n\nexport type CompiledSkillPlugin = {\n pluginPath: string;\n manifest: PluginManifest;\n skillName: string;\n};\n\ntype SkillCompilationRun = {\n compiled: CompiledSkillPlugin[];\n /** Directory basenames of skills that failed to compile this run. */\n failed: string[];\n};\n\nfunction sanitizeSkillName(name: string): string {\n return name.replace(/\\+/g, \"-\");\n}\n\nfunction isSingleFolderName(name: string): boolean {\n return name !== \"\" && name !== \".\" && name !== \"..\" && path.basename(name) === name;\n}\n\n/**\n * A plugin's folder is cleared before each build, so it must be one folder directly inside the\n * output directory, must not hold the skill's own source, and must not hold files no build made.\n */\nasync function assertClearable(\n pluginDir: string,\n skillPath: string,\n skillName: string,\n): Promise<void> {\n const skill = `Skill '${path.basename(skillPath)}'`;\n const file = `File: ${path.join(skillPath, STANDARD_FILES.SKILL_MD)}`;\n\n if (!isSingleFolderName(skillName)) {\n throw new Error(\n `${skill} is named '${skillName}', which is not a single folder name, so its plugin cannot be built inside the output directory. ${file}`,\n );\n }\n if (isPathWithin(skillPath, pluginDir)) {\n throw new Error(\n `${skill} would be built into ${pluginDir}, which holds its own source, so building it would overwrite that source. Build into an output directory outside the skills directory. ${file}`,\n );\n }\n if (await holdsContentNoBuildMade(pluginDir)) {\n throw new Error(\n `${skill} would be built into ${pluginDir}, which holds no ${path.join(PLUGIN_MANIFEST_DIR, PLUGIN_MANIFEST_FILE)} and is not empty, so no earlier build made it and a rebuild would delete what it holds. Move its contents out, or build into another output directory. ${file}`,\n );\n }\n}\n\n/** A folder an earlier build made holds its plugin manifest. */\nasync function isEarlierBuild(pluginDir: string): Promise<boolean> {\n return fileExists(getPluginManifestPath(pluginDir));\n}\n\nasync function holdsContentNoBuildMade(pluginDir: string): Promise<boolean> {\n if (await isEarlierBuild(pluginDir)) return false;\n return !(await isDirectoryEmpty(pluginDir));\n}\n\nasync function clearEarlierBuild(pluginDir: string): Promise<void> {\n if (await isEarlierBuild(pluginDir)) await remove(pluginDir);\n}\n\n/**\n * Unlike `readSkillMetadata` in `loading/loader.ts`: takes the skill directory, answers null for an\n * absent or unreadable file, and warns, since the compile runs either way.\n */\nasync function readPluginSkillMetadata(skillPath: string): Promise<SkillMetadata | null> {\n const metadataPath = path.join(skillPath, STANDARD_FILES.METADATA_YAML);\n\n if (!(await fileExists(metadataPath))) {\n return null;\n }\n\n try {\n const content = await readFile(metadataPath);\n const { yamlContent } = stripYamlSchemaComment(content);\n\n const result = skillMetadataLoaderSchema.safeParse(parseYaml(yamlContent));\n if (!result.success) {\n warn(`Invalid metadata.yaml at '${skillPath}': ${formatZodIssues(result.error.issues)}`);\n return null;\n }\n return result.data;\n } catch (error) {\n warn(`Failed to read metadata.yaml at '${skillPath}': ${getErrorMessage(error)}`);\n return null;\n }\n}\n\nfunction generateReadme(skillName: string, frontmatter: SkillFrontmatter): string {\n return `# ${skillName}\n\n${frontmatter.description}\n\n## Installation\n\nAdd this plugin to your Claude Code configuration:\n\n\\`\\`\\`json\n{\n \"plugins\": [\"${skillName}\"]\n}\n\\`\\`\\`\n\n## Usage\n\nThis skill is automatically available when installed.\n\n---\n\n*Generated by ${DEFAULT_BRANDING.NAME} skill-plugin-compiler*\n`;\n}\n\nasync function writeSkillFiles(\n skillPath: string,\n pluginSkillDir: string,\n skillMdContent: string,\n): Promise<void> {\n await ensureDir(pluginSkillDir);\n await writeFile(path.join(pluginSkillDir, STANDARD_FILES.SKILL_MD), skillMdContent);\n verbose(` Copied ${STANDARD_FILES.SKILL_MD}`);\n\n for (const fileName of SKILL_CONTENT_FILES) {\n if (fileName === STANDARD_FILES.SKILL_MD) continue;\n\n const sourcePath = path.join(skillPath, fileName);\n if (await fileExists(sourcePath)) {\n const content = await readFile(sourcePath);\n await writeFile(path.join(pluginSkillDir, fileName), content);\n verbose(` Copied ${fileName}`);\n }\n }\n\n for (const dirName of SKILL_CONTENT_DIRS) {\n const sourceDir = path.join(skillPath, dirName);\n if (await fileExists(sourceDir)) {\n await copy(sourceDir, path.join(pluginSkillDir, dirName));\n verbose(` Copied ${dirName}/`);\n }\n }\n}\n\n/** A plugin is built from the skill's SKILL.md, so one that is absent or unparseable refuses. */\nasync function readSkillMdToBuild(\n skillPath: string,\n): Promise<{ skillMdContent: string; frontmatter: SkillFrontmatter }> {\n const dirBasename = path.basename(skillPath);\n\n const skillMdPath = path.join(skillPath, STANDARD_FILES.SKILL_MD);\n if (!(await fileExists(skillMdPath))) {\n throw new Error(\n `Skill '${dirBasename}' is missing required ${STANDARD_FILES.SKILL_MD} file. Expected at: ${skillMdPath}`,\n );\n }\n\n const skillMdContent = await readFile(skillMdPath);\n const frontmatter = parseFrontmatter(skillMdContent, skillMdPath);\n\n // No cause inlined: `parseFrontmatter` has already warned it for this path.\n if (!frontmatter) {\n throw new Error(\n `Skill '${dirBasename}' has invalid or missing YAML frontmatter in ${STANDARD_FILES.SKILL_MD}. ` +\n `File: ${skillMdPath}`,\n );\n }\n\n return { skillMdContent, frontmatter };\n}\n\nexport async function compileSkillPlugin(\n options: SkillPluginOptions,\n): Promise<CompiledSkillPlugin> {\n const { skillPath, outputDir, skillName: overrideName } = options;\n const { skillMdContent, frontmatter } = await readSkillMdToBuild(skillPath);\n\n const skillName = overrideName ?? sanitizeSkillName(frontmatter.name);\n const pluginDir = path.join(outputDir, skillName);\n await assertClearable(pluginDir, skillPath, skillName);\n\n verbose(`Compiling skill plugin: ${skillName} from ${skillPath}`);\n\n const metadata = await readPluginSkillMetadata(skillPath);\n const manifestAt = (version: string): PluginManifest =>\n generateSkillPluginManifest({\n skillName,\n description: frontmatter.description,\n ...(metadata?.author !== undefined && { author: metadata.author }),\n ...(metadata?.category !== undefined && { category: metadata.category }),\n version,\n });\n\n // Read before the clear: what the earlier build shipped decides whether the version moves.\n const earlierBuild = await readEarlierBuild(pluginDir, getPluginManifestPath);\n await clearEarlierBuild(pluginDir);\n\n // At the earlier build's version, so the version alone cannot set the two builds apart; and\n // first, so a build that stops halfway leaves a folder the next build may clear.\n await writePluginManifest(pluginDir, manifestAt(earlierBuild?.version ?? DEFAULT_VERSION));\n\n // Nothing reads it back. Every plugin built so far ships it, so dropping it would bump them all.\n await writeContentHash(pluginDir, await computeSkillFolderHash(skillPath), getPluginManifestPath);\n\n await writeSkillFiles(\n skillPath,\n path.join(pluginDir, STANDARD_DIRS.SKILLS, skillName),\n skillMdContent,\n );\n\n const readme = generateReadme(skillName, frontmatter);\n await writeFile(path.join(pluginDir, STANDARD_FILES.README_MD), readme);\n verbose(\" Generated README.md\");\n\n const manifest = manifestAt(\n versionAfterRebuild(earlierBuild, await computeShippedHash(pluginDir)),\n );\n await writePluginManifest(pluginDir, manifest);\n verbose(` Wrote plugin.json for ${skillName} (v${manifest.version})`);\n\n return {\n pluginPath: pluginDir,\n manifest,\n skillName,\n };\n}\n\nexport async function compileAllSkillPlugins(\n skillsDir: string,\n outputDir: string,\n): Promise<SkillCompilationRun> {\n const compiled: CompiledSkillPlugin[] = [];\n const failed: string[] = [];\n\n const skillMdFiles = await glob(`**/${STANDARD_FILES.SKILL_MD}`, skillsDir);\n\n for (const skillMdFile of skillMdFiles) {\n const skillPath = path.join(skillsDir, path.dirname(skillMdFile));\n\n try {\n const result = await compileSkillPlugin({\n skillPath,\n outputDir,\n });\n compiled.push(result);\n log(` [OK] ${result.skillName}`);\n } catch (error) {\n const errorMessage = getErrorMessage(error);\n const dirBasename = path.basename(skillPath);\n failed.push(dirBasename);\n warn(`Failed to compile skill from '${dirBasename}': ${errorMessage}`);\n }\n }\n\n return { compiled, failed };\n}\n\nexport function printCompilationSummary(results: CompiledSkillPlugin[]): void {\n log(`\\nCompiled ${plural(results.length, \"skill plugin\")}:`);\n for (const result of results) {\n log(` - ${result.skillName} (v${result.manifest.version})`);\n }\n}\n","import path from \"path\";\n\nimport { ensureDir, writeFile } from \"../../utils/fs\";\nimport { DEFAULT_VERSION } from \"../../consts\";\nimport type { PluginAuthor, PluginManifest } from \"../../types\";\nimport { getPluginManifestPath } from \"./plugin-finder\";\n\nconst AGENT_PLUGIN_PREFIX = \"agent-\";\n\ntype SkillManifestOptions = {\n skillName: string;\n description?: string;\n author?: string;\n authorEmail?: string;\n category?: string;\n version?: string;\n keywords?: string[];\n};\n\ntype AgentManifestOptions = {\n agentName: string;\n description?: string;\n version?: string;\n};\n\nfunction buildAuthor(name?: string, email?: string): PluginAuthor | undefined {\n if (!name) {\n return undefined;\n }\n return { name, ...(email ? { email } : {}) };\n}\n\nexport function generateSkillPluginManifest(options: SkillManifestOptions): PluginManifest {\n const author = buildAuthor(options.author, options.authorEmail);\n return {\n name: options.skillName,\n version: options.version ?? DEFAULT_VERSION,\n skills: \"./skills/\",\n ...(options.description ? { description: options.description } : {}),\n ...(author ? { author } : {}),\n ...(options.category ? { category: options.category } : {}),\n ...(options.keywords?.length ? { keywords: options.keywords } : {}),\n };\n}\n\n/** Both the plugin's manifest name and the folder it is built into. */\nexport function agentPluginName(agentName: string): string {\n return `${AGENT_PLUGIN_PREFIX}${agentName}`;\n}\n\nexport function generateAgentPluginManifest(options: AgentManifestOptions): PluginManifest {\n return {\n name: agentPluginName(options.agentName),\n version: options.version ?? DEFAULT_VERSION,\n agents: \"./agents/\",\n ...(options.description ? { description: options.description } : {}),\n };\n}\n\nexport async function writePluginManifest(\n outputDir: string,\n manifest: PluginManifest,\n): Promise<string> {\n const manifestPath = getPluginManifestPath(outputDir);\n\n await ensureDir(path.dirname(manifestPath));\n\n const content = JSON.stringify(manifest, null, 2);\n await writeFile(manifestPath, content);\n\n return manifestPath;\n}\n","import os from \"os\";\nimport path from \"path\";\n\nimport { getErrorMessage } from \"../../utils/errors\";\nimport { fileExists, readFileSafe } from \"../../utils/fs\";\nimport { verbose } from \"../../utils/logger\";\nimport {\n CLAUDE_DIR,\n MAX_PLUGIN_FILE_SIZE,\n PLUGINS_SUBDIR,\n PLUGIN_MANIFEST_DIR,\n PLUGIN_MANIFEST_FILE,\n STANDARD_DIRS,\n} from \"../../consts\";\nimport type { PluginManifest } from \"../../types\";\nimport { pluginManifestSchema } from \"../schemas\";\n\nexport function getUserPluginsDir(): string {\n return path.join(os.homedir(), CLAUDE_DIR, PLUGINS_SUBDIR);\n}\n\nexport function getProjectPluginsDir(projectDir?: string): string {\n const dir = projectDir ?? process.cwd();\n return path.join(dir, CLAUDE_DIR, PLUGINS_SUBDIR);\n}\n\nexport function getPluginAgentsDir(pluginDir: string): string {\n return path.join(pluginDir, STANDARD_DIRS.AGENTS);\n}\n\nexport function getPluginManifestPath(pluginDir: string): string {\n return path.join(pluginDir, PLUGIN_MANIFEST_DIR, PLUGIN_MANIFEST_FILE);\n}\n\nexport async function readPluginManifest(pluginDir: string): Promise<PluginManifest | null> {\n const manifestPath = getPluginManifestPath(pluginDir);\n\n if (!(await fileExists(manifestPath))) {\n verbose(` No manifest at ${manifestPath}`);\n return null;\n }\n\n try {\n const content = await readFileSafe(manifestPath, MAX_PLUGIN_FILE_SIZE);\n const manifest = pluginManifestSchema.parse(JSON.parse(content));\n\n if (!manifest.name || typeof manifest.name !== \"string\") {\n verbose(` Invalid manifest at ${manifestPath}: missing name`);\n return null;\n }\n\n return manifest;\n } catch (error) {\n verbose(` Failed to parse manifest at ${manifestPath}: ${getErrorMessage(error)}`);\n return null;\n }\n}\n","/** Bare ids do not match registry entries. */\nexport function buildMarketplacePluginRef(id: string, marketplace: string): string {\n return `${id}@${marketplace}`;\n}\n\nexport function parseMarketplacePluginRef(ref: string): string {\n const separator = ref.indexOf(\"@\");\n return separator === -1 ? ref : ref.slice(0, separator);\n}\n","import { readdir } from \"fs/promises\";\nimport type { Dirent } from \"fs\";\n\nimport { DEFAULT_PLUGIN_NAME, type Provider } from \"../../consts\";\nimport { loadProjectConfig } from \"../configuration\";\nimport { loadProjectConfigFromDir } from \"../configuration/project-config\";\nimport {\n declaresNoContent,\n deriveInstallMode,\n detectInstallation,\n detectInstallations,\n installBaseDir,\n isHomeDirectory,\n resolveInstallPaths,\n INSTALL_MODE_LABELS,\n type Installation,\n type InstallMode,\n} from \"../installation\";\nimport type { DetectedInstallation } from \"../installation/detect-installations\";\nimport { agentCodec, agentsDir } from \"../installation/install-layout\";\nimport type { ProjectConfig, SkillScope } from \"../../types/config\";\n\nexport type InstallationInfo = {\n mode: InstallMode;\n name: string;\n skillCount: number;\n agentCount: number;\n configPath: string;\n agentDirs: string[];\n};\n\nexport async function getInstallationInfo(): Promise<InstallationInfo | null> {\n const installation = await detectInstallation();\n if (!installation) return null;\n\n const [loaded, agentDirCounts] = await Promise.all([\n loadProjectConfig(installation.projectDir),\n countCompiledAgentsPerScope(installation, installedScopes(installation)),\n ]);\n\n return {\n mode: installation.mode,\n name: loaded?.config.name || DEFAULT_PLUGIN_NAME,\n skillCount: loaded ? countManagedSkills(loaded.config) : 0,\n agentCount: sumCounts(agentDirCounts),\n configPath: installation.configPath,\n agentDirs: agentDirCounts.filter(hasEntries).map((scopeCount) => scopeCount.dir),\n };\n}\n\n/** One provider's installation, counted in its own folders and its own agent format. */\nexport type ProviderInstallation = {\n provider: Provider;\n mode: InstallMode;\n skillCount: number;\n agentCount: number;\n marketplace?: string;\n};\n\n/**\n * One per provider installed where a bare `init` looks — the project's, else the global ones — in\n * roster order. Each is read under its own provider, never through the run's `providerInUse`.\n */\nexport async function getInstallationsByProvider(cwd: string): Promise<ProviderInstallation[]> {\n const found = await detectInstallations(cwd);\n const loaded = await Promise.all(found.map((installed) => withItsConfig(installed, cwd)));\n const inView = projectsOwnElseGlobal(loaded.filter(declaresContent));\n\n return Promise.all(inView.map((installed) => describeInstallation(installed, cwd)));\n}\n\ntype LoadedInstallation = DetectedInstallation & { config: ProjectConfig };\n\n/** A config declaring nothing is not an installation, as `detectInstallation` holds too. */\nfunction declaresContent(installed: LoadedInstallation | null): installed is LoadedInstallation {\n return installed !== null && !declaresNoContent(installed.config);\n}\n\n/** Global installations stand in only where the project holds none of its own. */\nfunction projectsOwnElseGlobal(installed: LoadedInstallation[]): LoadedInstallation[] {\n const inProject = installed.filter(({ scope }) => scope === \"project\");\n return inProject.length > 0 ? inProject : installed;\n}\n\n/** ABORT: an unloadable config throws, as `detectInstallation` beside it would. */\nasync function withItsConfig(\n installed: DetectedInstallation,\n cwd: string,\n): Promise<LoadedInstallation | null> {\n const loaded = await loadProjectConfigFromDir(\n installBaseDir(cwd, installed.scope),\n installed.provider,\n );\n return loaded === null ? null : { ...installed, config: loaded.config };\n}\n\n/** A global installation's agents are global; a project's sit at both scopes. */\nasync function describeInstallation(\n { provider, scope, config }: LoadedInstallation,\n cwd: string,\n): Promise<ProviderInstallation> {\n const scopes: SkillScope[] = scope === \"global\" ? [\"global\"] : [\"global\", \"project\"];\n const { extension } = agentCodec(provider);\n const counts = await Promise.all(\n scopes.map((agentScope) =>\n countDirEntries(agentsDir(provider, agentScope, cwd), isCompiledAgentFileIn(extension)),\n ),\n );\n\n return {\n provider,\n mode: deriveInstallMode(config.skills),\n skillCount: countManagedSkills(config),\n agentCount: counts.reduce((total, count) => total + count, 0),\n ...(config.marketplace !== undefined && { marketplace: config.marketplace }),\n };\n}\n\n/** Counted from the config, not the plugin registry or skills dir, which each hold only part. */\nfunction countManagedSkills(config: ProjectConfig): number {\n const managed = config.skills.filter((skill) => !skill.excluded);\n return new Set(managed.map((skill) => skill.id)).size;\n}\n\n/** Global first; at the home root both scopes are one directory, counted once. */\nfunction installedScopes(installation: Installation): SkillScope[] {\n return isHomeDirectory(installation.projectDir) ? [\"project\"] : [\"global\", \"project\"];\n}\n\ntype ScopeCount = {\n dir: string;\n count: number;\n};\n\nfunction hasEntries(scopeCount: ScopeCount): boolean {\n return scopeCount.count > 0;\n}\n\nfunction sumCounts(scopeCounts: ScopeCount[]): number {\n return scopeCounts.reduce((total, scopeCount) => total + scopeCount.count, 0);\n}\n\nasync function countCompiledAgentsPerScope(\n installation: Installation,\n scopes: SkillScope[],\n): Promise<ScopeCount[]> {\n return Promise.all(\n scopes.map(async (scope) => {\n const dir = resolveInstallPaths(installation.projectDir, scope).agentsDir;\n return {\n dir,\n count: await countDirEntries(dir, isCompiledAgentFileIn(agentCodec(\"claude\").extension)),\n };\n }),\n );\n}\n\nfunction isCompiledAgentFileIn(extension: string): (entry: Dirent) => boolean {\n return (entry) => entry.isFile() && entry.name.endsWith(extension);\n}\n\nasync function countDirEntries(dir: string, pred: (entry: Dirent) => boolean): Promise<number> {\n try {\n const entries = await readdir(dir, { withFileTypes: true });\n return entries.filter(pred).length;\n } catch {\n return 0;\n }\n}\n\nexport function formatInstallationDisplay(info: InstallationInfo): string {\n const agentDirLines = info.agentDirs.map((dir) => `\\n Agents: ${dir}`).join(\"\");\n\n return `Installation: ${info.name}\n Mode: ${INSTALL_MODE_LABELS[info.mode]}\n Skills: ${info.skillCount}\n Agents: ${info.agentCount}\n Config: ${info.configPath}${agentDirLines}`;\n}\n","import os from \"os\";\nimport path from \"path\";\nimport { fileExists } from \"../../utils/fs\";\nimport { ConfigLoadError, loadProjectConfigFromDir } from \"../configuration/project-config\";\nimport { CLAUDE_DIR, PLUGINS_SUBDIR, EJECT_SOURCE, STANDARD_DIRS } from \"../../consts\";\nimport { getProjectConfigPath } from \"./install-base-dir\";\nimport { agentsDir, providerInUse } from \"./install-layout\";\nimport type { ProjectConfig, SkillConfig, SkillScope } from \"../../types/config\";\nimport type { InstallMode } from \"../../types/matrix\";\n\nexport type { InstallMode };\n\nexport const INSTALL_MODE_LABELS = {\n plugin: \"Plugin\",\n mixed: \"Mixed\",\n eject: \"Eject\",\n} as const satisfies Record<InstallMode, string>;\n\n/**\n * No directory is named: it depends on host and scope, and one selection can span several.\n * `mixed` is absent because nothing is switched to it.\n */\nexport const INSTALL_MODE_DESCRIPTIONS = {\n plugin: `${INSTALL_MODE_LABELS.plugin} (native install)`,\n eject: `${INSTALL_MODE_LABELS.eject} (local copy)`,\n} as const satisfies Record<Exclude<InstallMode, \"mixed\">, string>;\n\nexport type Installation = {\n mode: InstallMode;\n configPath: string;\n agentsDir: string;\n skillsDir: string;\n projectDir: string;\n};\n\n/** Shared with `doctor`, so both agree which configs count as content-less. */\nexport function declaresNoContent(config: ProjectConfig): boolean {\n return config.skills.length === 0 && config.agents.length === 0;\n}\n\nexport function deriveInstallMode(skills: SkillConfig[]): InstallMode {\n if (skills.length === 0) return \"eject\";\n const hasEject = skills.some((s) => s.origin === EJECT_SOURCE);\n const hasPlugin = skills.some((s) => s.origin !== EJECT_SOURCE);\n if (hasEject && hasPlugin) return \"mixed\";\n return hasEject ? \"eject\" : \"plugin\";\n}\n\nasync function detectInstallationInDir(\n dir: string,\n scope: SkillScope,\n): Promise<Installation | null> {\n const provider = providerInUse(dir);\n const configPath = getProjectConfigPath(dir, provider);\n\n if (!(await fileExists(configPath))) {\n return null;\n }\n\n // Aborts: a corrupt config throws ConfigLoadError to the caller rather than reading as absent.\n const loaded = await loadProjectConfigFromDir(dir, provider);\n if (!loaded) {\n // Vanished since the fileExists check.\n return null;\n }\n\n // Content-less is not an installation, so init routes to the editor.\n if (declaresNoContent(loaded.config)) {\n return null;\n }\n\n const mode: InstallMode = deriveInstallMode(loaded.config.skills);\n\n return {\n mode,\n configPath,\n agentsDir: agentsDir(provider, scope, dir),\n // Mixed mode uses the local skills dir, as eject does.\n skillsDir: path.join(\n dir,\n CLAUDE_DIR,\n mode === \"plugin\" ? PLUGINS_SUBDIR : STANDARD_DIRS.SKILLS,\n ),\n projectDir: dir,\n };\n}\n\n/** No global fallback. */\nexport async function detectProjectInstallation(projectDir: string): Promise<Installation | null> {\n return detectInstallationInDir(projectDir, \"project\");\n}\n\n/** Degrades: a config that exists but cannot be loaded still answers yes. */\nexport async function holdsItsOwnInstallation(dir: string): Promise<boolean> {\n try {\n return (await detectProjectInstallation(dir)) !== null;\n } catch (error) {\n if (error instanceof ConfigLoadError) return true;\n throw error;\n }\n}\n\nexport async function detectGlobalInstallation(): Promise<Installation | null> {\n return detectInstallationInDir(os.homedir(), \"global\");\n}\n\n/** Project first, else global; never merged. */\nexport async function detectInstallation(\n projectDir: string = process.cwd(),\n): Promise<Installation | null> {\n const projectInstallation = await detectProjectInstallation(projectDir);\n if (projectInstallation) return projectInstallation;\n\n return detectGlobalInstallation();\n}\n","import os from \"os\";\nimport path from \"path\";\nimport { unique } from \"remeda\";\nimport type {\n AgentDefinition,\n AgentName,\n CompileAgentConfig,\n ProjectConfig,\n SkillId,\n SkillReference,\n Stack,\n StackAgentConfig,\n} from \"../../types\";\nimport { isHomeDirectory } from \"./is-home-directory\";\nimport type { AgentScopeConfig, SkillConfig, SkillScope } from \"../../types/config\";\nimport type { InstallSelection } from \"@workspace/compile/seed-to-config\";\nimport {\n type MergeResult,\n type AuthoritativeScope,\n mergeWithExistingConfig,\n loadProjectConfig,\n loadInstalledConfig,\n} from \"../configuration\";\nimport { type SourceLoadResult } from \"../loading\";\nimport { loadStackById, stackNotOfferedMessage } from \"../stacks\";\nimport { buildSkillRefsFromConfig } from \"../resolver\";\nimport { generateProjectConfigFromSkills, buildStackProperty } from \"../configuration\";\nimport {\n isActiveAt,\n activeAgentScopeMap,\n effectivelyExcludedSkillIds,\n} from \"../configuration/scope-predicates\";\nimport { verbose } from \"../../utils/logger\";\nimport { typedFromEntries } from \"../../utils/typed-object\";\nimport { DEFAULT_PLUGIN_NAME } from \"../../consts\";\n\n/**\n * Assigned `(skill, agent)` pairs replace the ownership-derived stack so the sharer's curation\n * survives. With no agents selected the key is absent and the merger keeps the stack on disk.\n */\nfunction resolveStackProperty(\n generated: ProjectConfig[\"stack\"],\n assigned: InstallSelection[\"assignedStack\"],\n): ProjectConfig[\"stack\"] {\n return generated === undefined ? undefined : assigned;\n}\n\n/** A loaded stack wins over a carried description (`init --from` with `stackId: null`). */\nfunction resolveDescription(\n loadedStack: Stack | null,\n shared: InstallSelection[\"description\"],\n): string | undefined {\n return loadedStack === null ? shared : loadedStack.description;\n}\n\n/** At `$HOME` the basename is the account name, so the global config takes the product name. */\nfunction configNameFor(projectDir: string): string {\n return isHomeDirectory(projectDir) ? DEFAULT_PLUGIN_NAME : path.basename(projectDir);\n}\n\n/**\n * A global sub-agent's curation lives only in the global config, so both are read; the project's\n * row wins per agent.\n */\nasync function loadCuratedStack(\n projectDir: string,\n projectStack: ProjectConfig[\"stack\"],\n): Promise<Partial<Record<AgentName, StackAgentConfig>>> {\n // At `$HOME` the loaded config IS the global one.\n const globalStack = isHomeDirectory(projectDir) ? undefined : await loadGlobalStack();\n\n return { ...globalStack, ...projectStack };\n}\n\nasync function loadGlobalStack(): Promise<ProjectConfig[\"stack\"]> {\n return (await loadInstalledConfig(os.homedir()))?.config.stack;\n}\n\nasync function buildInstallConfig(\n selection: InstallSelection,\n sourceResult: SourceLoadResult,\n projectDir: string,\n): Promise<{ config: ProjectConfig; loadedStack: Stack | null }> {\n const skillIds = unique(selection.skills.map((s) => s.id));\n verbose(selectionForLog(selection, skillIds));\n\n const loadedStack = await loadSelectedStack(selection.selectedStackId, sourceResult);\n const existing = await loadProjectConfig(projectDir);\n const existingStack = await loadCuratedStack(projectDir, existing?.config.stack);\n\n const options = generatorOptionsFor(selection, stackToPreserve(loadedStack, existingStack));\n const generated = generateProjectConfigFromSkills(configNameFor(projectDir), skillIds, options);\n const localConfig = withSelectionCuration(generated, selection, loadedStack);\n\n verbose(installConfigForLog(localConfig));\n\n return { config: localConfig, loadedStack };\n}\n\nfunction withSelectionCuration(\n generated: ProjectConfig,\n selection: InstallSelection,\n loadedStack: Stack | null,\n): ProjectConfig {\n const stack = resolveStackProperty(generated.stack, selection.assignedStack);\n const description = resolveDescription(loadedStack, selection.description);\n\n return {\n ...generated,\n ...(stack && { stack }),\n ...(description !== undefined && { description }),\n };\n}\n\nfunction selectionForLog(selection: InstallSelection, skillIds: SkillId[]): string {\n return (\n `buildInstallConfig: selectedStackId='${selection.selectedStackId}', ` +\n `skills=[${skillIds.join(\", \")}], ` +\n `selectedAgents=[${selection.selectedAgents.join(\", \")}]`\n );\n}\n\nfunction installConfigForLog(config: ProjectConfig): string {\n return (\n `buildInstallConfig result: stack=${stackSizeForLog(config.stack)}, ` +\n `agents=[${config.agents.map((a) => a.name).join(\", \")}], skills=${config.skills.length}`\n );\n}\n\n/**\n * Lets a caller refuse before writing anything (the `--from` producers do); the install's own\n * lookup is only the backstop, landing after plugins are installed.\n */\nexport async function refuseUnofferedStack(\n stackId: InstallSelection[\"selectedStackId\"],\n sourceResult: SourceLoadResult,\n): Promise<void> {\n await loadSelectedStack(stackId, sourceResult);\n}\n\nasync function loadSelectedStack(\n stackId: InstallSelection[\"selectedStackId\"],\n sourceResult: SourceLoadResult,\n): Promise<Stack | null> {\n if (!stackId) return null;\n\n const { source } = sourceResult.sourceConfig;\n const loadedStack = await loadStackById(stackId, sourceResult.sourcePath, source);\n verbose(\n `buildInstallConfig: loadedStack=${loadedStack ? `found (id='${loadedStack.id}')` : \"NOT FOUND\"}`,\n );\n if (!loadedStack) throw new Error(stackNotOfferedMessage(stackId, source));\n\n return loadedStack;\n}\n\n/** The curated stack on disk wins per agent over any stack this install applies. */\nfunction stackToPreserve(\n loadedStack: Stack | null,\n curatedStack: Partial<Record<AgentName, StackAgentConfig>>,\n): Partial<Record<AgentName, StackAgentConfig>> {\n if (loadedStack === null) return curatedStack;\n return { ...buildStackProperty(loadedStack), ...curatedStack };\n}\n\nfunction generatorOptionsFor(\n selection: InstallSelection,\n existingStack: Partial<Record<AgentName, StackAgentConfig>>,\n): {\n selectedAgents?: AgentName[];\n skillConfigs: SkillConfig[];\n agentConfigs: AgentScopeConfig[];\n existingStack: Partial<Record<AgentName, StackAgentConfig>>;\n} {\n return {\n skillConfigs: selection.skills,\n agentConfigs: selection.agentConfigs,\n existingStack,\n ...(selection.selectedAgents.length > 0 && {\n selectedAgents: selection.selectedAgents,\n }),\n };\n}\n\nfunction stackSizeForLog(stack: ProjectConfig[\"stack\"]): string {\n return stack ? `${Object.keys(stack).length} agents` : \"UNDEFINED\";\n}\n\nfunction setConfigMetadata(\n config: ProjectConfig,\n selection: InstallSelection,\n sourceResult: SourceLoadResult,\n sourceFlag?: string,\n): ProjectConfig {\n const result = { ...config };\n\n if (selection.selectedDomains.length > 0) {\n result.selectedDomains = selection.selectedDomains;\n }\n\n if (sourceFlag) {\n result.marketplace = sourceFlag;\n } else if (sourceResult.sourceConfig.source) {\n result.marketplace = sourceResult.sourceConfig.source;\n }\n\n if (sourceResult.marketplace) {\n result.marketplaceName = sourceResult.marketplace;\n }\n\n return result;\n}\n\nexport async function buildAndMergeConfig(\n selection: InstallSelection,\n sourceResult: SourceLoadResult,\n projectDir: string,\n sourceFlag?: string,\n authoritativeScope?: AuthoritativeScope,\n): Promise<MergeResult> {\n const { config } = await buildInstallConfig(selection, sourceResult, projectDir);\n verbose(`buildAndMergeConfig: before merge — stack=${stackSizeForLog(config.stack)}`);\n const configWithMetadata = setConfigMetadata(config, selection, sourceResult, sourceFlag);\n const result = await mergeWithExistingConfig(configWithMetadata, {\n projectDir,\n ...(authoritativeScope !== undefined && { authoritativeScope }),\n });\n verbose(\n `buildAndMergeConfig: after merge — stack=${stackSizeForLog(result.config.stack)}, merged=${result.merged}`,\n );\n return result;\n}\n\nexport function buildCompileAgents(\n config: ProjectConfig,\n agents: Partial<Record<AgentName, AgentDefinition>>,\n): Partial<Record<AgentName, CompileAgentConfig>> {\n const activeAgents = config.agents.filter((a) => !a.excluded);\n const excludedSkillIds = effectivelyExcludedSkillIds(config.skills);\n const globalSkillIds = new Set(\n config.skills.filter((s) => isActiveAt(s, \"global\")).map((s) => s.id),\n );\n const sourceById = new Map<SkillId, string>(\n config.skills.filter((s) => !s.excluded).map((s) => [s.id, s.origin]),\n );\n\n // A global agent takes only the skills active at global scope.\n const compilesInto = (ref: SkillReference, agentConfig: AgentScopeConfig): boolean => {\n if (excludedSkillIds.has(ref.id)) return false;\n if (agentConfig.scope === \"global\") return globalSkillIds.has(ref.id);\n return true;\n };\n\n // `origin` picks plugin (`${id}:${id}`) or eject (bare id); a user-authored local skill has none.\n const withItsOrigin = (ref: SkillReference): SkillReference => {\n const source = sourceById.get(ref.id);\n return { ...ref, ...(source !== undefined && { source }) };\n };\n\n const buildAgentCompileEntry = (agentConfig: AgentScopeConfig): CompileAgentConfig => {\n // Kept even for an agent with no stack entry.\n const tuning: CompileAgentConfig = {\n ...(agentConfig.model !== undefined && { model: agentConfig.model }),\n ...(agentConfig.codexModel !== undefined && { codexModel: agentConfig.codexModel }),\n ...(agentConfig.effort !== undefined && { effort: agentConfig.effort }),\n };\n\n const agentStack = config.stack?.[agentConfig.name];\n if (!agentStack) return tuning;\n\n const filteredRefs = buildSkillRefsFromConfig(agentStack)\n .filter((ref) => compilesInto(ref, agentConfig))\n .map(withItsOrigin);\n return { ...tuning, skills: filteredRefs };\n };\n\n return typedFromEntries<AgentName, CompileAgentConfig>(\n activeAgents\n .filter((agentConfig) => agents[agentConfig.name])\n .map((agentConfig) => [agentConfig.name, buildAgentCompileEntry(agentConfig)]),\n );\n}\n\nexport function buildAgentScopeMap(config: ProjectConfig): Map<AgentName, SkillScope> {\n return activeAgentScopeMap(config.agents);\n}\n","import { parse as parseYaml } from \"yaml\";\nimport path from \"path\";\nimport { getErrorMessage } from \"../../utils/errors\";\nimport { extractFrontmatter } from \"../../utils/frontmatter\";\nimport { glob, readFile, directoryExists, fileExists } from \"../../utils/fs\";\nimport { verbose, warn } from \"../../utils/logger\";\nimport { isRecord } from \"../../utils/type-guards\";\nimport {\n DIRS,\n LOCAL_PSEUDO_CATEGORY,\n STANDARD_DIRS,\n STANDARD_FILES,\n PROJECT_ROOT,\n} from \"../../consts\";\nimport { providerInUse, sourceFolderInUse } from \"../installation/install-layout\";\nimport type {\n AgentDefinition,\n AgentName,\n AgentYamlConfig,\n SkillDefinition,\n SkillDefinitionMap,\n SkillFrontmatter,\n} from \"../../types\";\nimport {\n describeMetadataSchemaFailure,\n formatZodIssues,\n localRawMetadataSchema,\n skillFrontmatterLoaderSchema,\n agentYamlConfigSchema,\n} from \"../schemas\";\nimport type { LocalRawMetadata } from \"../skills/local-skill-loader\";\nimport { METADATA_KEYS } from \"../metadata-keys\";\n\ntype SkillMetadataRead =\n { usable: true; metadata: LocalRawMetadata } | { usable: false; reason: string };\n\n/**\n * The single judgment of whether a metadata.yaml describes its skill, shared by `compile`,\n * local-skill discovery and `doctor`. Refuses an unparseable file and one missing required fields.\n */\nexport async function readSkillMetadata(metadataPath: string): Promise<SkillMetadataRead> {\n let parsed: unknown;\n try {\n parsed = parseYaml(await readFile(metadataPath));\n } catch (error) {\n return { usable: false, reason: getErrorMessage(error) };\n }\n\n if (!isRecord(parsed)) {\n return { usable: false, reason: `expected metadata fields, found ${nameYamlValue(parsed)}` };\n }\n\n const validated = localRawMetadataSchema.safeParse(parsed);\n if (!validated.success) {\n return { usable: false, reason: describeMetadataSchemaFailure(validated.error.issues, parsed) };\n }\n\n return { usable: true, metadata: validated.data };\n}\n\n/**\n * `local` belongs to no domain, so a skill wearing it is unreachable. Separate from\n * `readSkillMetadata`, and not repairable, because nothing in the file is malformed.\n */\nexport function namesPlaceholderCategory(metadata: LocalRawMetadata): boolean {\n return metadata.category === LOCAL_PSEUDO_CATEGORY;\n}\n\n/** Names what a metadata.yaml holds when it holds no fields — for the refusal's reason. */\nfunction nameYamlValue(value: unknown): string {\n if (value === null || value === undefined) return \"an empty file\";\n if (Array.isArray(value)) return \"a list\";\n return `a ${typeof value}`;\n}\n\nexport function parseFrontmatter(content: string, filePath?: string): SkillFrontmatter | null {\n const rawFrontmatter = extractFrontmatter(content);\n if (rawFrontmatter === null) return null;\n\n const parsed = skillFrontmatterLoaderSchema.safeParse(rawFrontmatter);\n\n if (!parsed.success) {\n const location = filePath ?? \"unknown file\";\n warn(`Invalid SKILL.md frontmatter in '${location}': ${formatZodIssues(parsed.error.issues)}`);\n return null;\n }\n return parsed.data;\n}\n\ntype LoadAgentsFromDirOptions = {\n /** Relative base recorded on each definition (project agents live under the source folder's agents/). */\n agentBaseDir?: string;\n /** Propagate the `custom: true` metadata flag (source/CLI agents only). */\n includeCustomFlag?: boolean;\n verboseLabel: string;\n};\n\n/** Names the path: this is the last boundary that knows which file the value came from. */\nfunction refusalOfAgentMetadata(metadataPath: string, reason: string): string {\n return `Skipping invalid ${STANDARD_FILES.AGENT_METADATA_YAML} at '${metadataPath}': ${reason}`;\n}\n\nasync function loadAgentsFromDir(\n agentsDir: string,\n sourceRoot: string,\n options: LoadAgentsFromDirOptions,\n): Promise<Partial<Record<AgentName, AgentDefinition>>> {\n const agents: Record<string, AgentDefinition> = {};\n const files = await glob(`**/${STANDARD_FILES.AGENT_METADATA_YAML}`, agentsDir);\n\n for (const file of files) {\n const read = await readAgentDefinition(agentsDir, file, sourceRoot, options);\n if (read) agents[read.id] = read.definition;\n }\n\n return agents;\n}\n\ntype AgentDefinitionRead = { id: AgentYamlConfig[\"id\"]; definition: AgentDefinition };\n\n/** Undefined, and warned about, when the file cannot be read or is not a valid definition. */\nasync function readAgentDefinition(\n agentsDir: string,\n file: string,\n sourceRoot: string,\n options: LoadAgentsFromDirOptions,\n): Promise<AgentDefinitionRead | undefined> {\n const fullPath = path.join(agentsDir, file);\n try {\n const content = await readFile(fullPath);\n // safeParse: a ZodError's message is a JSON dump, and this warning is the only report.\n const parsed = agentYamlConfigSchema.safeParse(parseYaml(content));\n if (!parsed.success) {\n warn(refusalOfAgentMetadata(fullPath, formatZodIssues(parsed.error.issues)));\n return undefined;\n }\n const config = parsed.data;\n\n const definition = toAgentDefinition(config, file, sourceRoot, options);\n verbose(`Loaded ${options.verboseLabel}: ${config.id} from ${file}`);\n return { id: config.id, definition };\n } catch (error) {\n warn(refusalOfAgentMetadata(fullPath, getErrorMessage(error)));\n return undefined;\n }\n}\n\n/** `file` is the path under the agents directory; its parent becomes the agent's `path`. */\nfunction toAgentDefinition(\n config: AgentYamlConfig,\n file: string,\n sourceRoot: string,\n options: LoadAgentsFromDirOptions,\n): AgentDefinition {\n return {\n title: config.title,\n description: config.description,\n ...(config.model !== undefined && { model: config.model }),\n ...(config.effort !== undefined && { effort: config.effort }),\n tools: config.tools,\n // Spread conditionally: the template branches on presence; `undefined` renders a key.\n ...(config.disallowedTools !== undefined && {\n disallowedTools: config.disallowedTools,\n }),\n ...(config.permissionMode !== undefined && { permissionMode: config.permissionMode }),\n ...(config.isolation !== undefined && { isolation: config.isolation }),\n ...(config.hooks !== undefined && { hooks: config.hooks }),\n ...(config.experimental !== undefined && { experimental: config.experimental }),\n ...(config.outputFormat !== undefined && { outputFormat: config.outputFormat }),\n path: path.dirname(file),\n sourceRoot,\n ...(options.agentBaseDir ? { agentBaseDir: options.agentBaseDir } : {}),\n ...(config.domain ? { domain: config.domain } : {}),\n ...(options.includeCustomFlag && config.custom === true ? { custom: true } : {}),\n };\n}\n\nexport async function loadAllAgents(\n projectRoot: string,\n): Promise<Partial<Record<AgentName, AgentDefinition>>> {\n return loadAgentsFromDir(path.join(projectRoot, DIRS.agents), projectRoot, {\n includeCustomFlag: true,\n verboseLabel: \"agent\",\n });\n}\n\n/** Source definitions win name collisions. */\nexport async function loadMergedAgents(\n sourcePath: string,\n): Promise<Partial<Record<AgentName, AgentDefinition>>> {\n const [cliAgents, sourceAgents] = await Promise.all([\n loadAllAgents(PROJECT_ROOT),\n loadAllAgents(sourcePath),\n ]);\n return { ...cliAgents, ...sourceAgents };\n}\n\nexport async function loadProjectAgents(\n projectRoot: string,\n): Promise<Partial<Record<AgentName, AgentDefinition>>> {\n const sourceFolder = sourceFolderInUse(projectRoot, providerInUse(projectRoot));\n const projectAgentsDir = path.join(sourceFolder.dir, STANDARD_DIRS.AGENTS);\n\n if (!(await directoryExists(projectAgentsDir))) {\n verbose(`No project agents directory at ${projectAgentsDir}`);\n return {};\n }\n\n return loadAgentsFromDir(projectAgentsDir, projectRoot, {\n // The folder this scope is actually on, so `path` names a directory the reader can open.\n agentBaseDir: `${sourceFolder.relName}/${STANDARD_DIRS.AGENTS}`,\n verboseLabel: \"project agent\",\n });\n}\n\ntype LoadSkillsFromDirOptions = {\n /** Path prefix recorded on each skill's `path` (e.g. LOCAL_SKILLS_PATH or \"skills\"). */\n pathPrefix?: string;\n /**\n * Skip a SKILL.md whose metadata.yaml is missing or describes no skill; plugin skills carry none.\n */\n requireMetadata?: boolean;\n};\n\nexport type UnusableSkillMetadata = {\n /** The skill's directory name, as it appears under `.claude/skills/`. */\n skillDirName: string;\n metadataPath: string;\n /** The YAML parser's own message, what the file holds instead of fields, or which fields it lacks. */\n reason: string;\n};\n\nexport type LoadedSkills = {\n skills: SkillDefinitionMap;\n /** Only non-empty under `requireMetadata`. */\n unusableMetadata: UnusableSkillMetadata[];\n};\n\n/** Unreadable files and bad frontmatter are logged and skipped, never thrown. */\nexport async function loadSkillsFromDir(\n skillsDir: string,\n options: LoadSkillsFromDirOptions = {},\n): Promise<LoadedSkills> {\n const { pathPrefix = \"\", requireMetadata = false } = options;\n const skills: SkillDefinitionMap = {};\n const unusableMetadata: UnusableSkillMetadata[] = [];\n\n if (!(await directoryExists(skillsDir))) {\n return { skills, unusableMetadata };\n }\n\n const skillFiles = await glob(`**/${STANDARD_FILES.SKILL_MD}`, skillsDir);\n\n for (const skillFile of skillFiles) {\n const skill = locateSkill(skillsDir, skillFile, pathPrefix);\n\n if (requireMetadata) {\n const verdict = await judgeSkillMetadata(skill);\n if (verdict.kind === \"unusable\") unusableMetadata.push(verdict.refusal);\n if (verdict.kind !== \"admitted\") continue;\n }\n\n const definition = await readSkillDefinition(skill);\n if (definition) skills[definition.id] = definition;\n }\n\n return { skills, unusableMetadata };\n}\n\ntype SkillLocation = {\n skillFile: string;\n skillMdPath: string;\n skillDir: string;\n skillDirName: string;\n /** The `path` recorded on the skill: prefixed, relative, slash-terminated. */\n displayPath: string;\n};\n\nfunction locateSkill(skillsDir: string, skillFile: string, pathPrefix: string): SkillLocation {\n const skillMdPath = path.join(skillsDir, skillFile);\n const skillDir = path.dirname(skillMdPath);\n const relativePath = path.relative(skillsDir, skillDir);\n\n return {\n skillFile,\n skillMdPath,\n skillDir,\n skillDirName: path.basename(skillDir),\n displayPath: pathPrefix ? `${pathPrefix}/${relativePath}/` : `${relativePath}/`,\n };\n}\n\n/** Only an `unusable` file is the caller's to report; a `skipped` skill is logged here. */\ntype SkillMetadataVerdict =\n { kind: \"admitted\" } | { kind: \"skipped\" } | { kind: \"unusable\"; refusal: UnusableSkillMetadata };\n\nasync function judgeSkillMetadata(skill: SkillLocation): Promise<SkillMetadataVerdict> {\n const metadataPath = path.join(skill.skillDir, STANDARD_FILES.METADATA_YAML);\n if (!(await fileExists(metadataPath))) {\n warn(\n `Skill '${skill.skillDirName}' in '${skill.displayPath}' is missing ${STANDARD_FILES.METADATA_YAML} — skipped. Add ${STANDARD_FILES.METADATA_YAML} to register it with the CLI.`,\n );\n return { kind: \"skipped\" };\n }\n\n // Reported rather than loaded around: discovery and compile refuse the same file.\n const read = await readSkillMetadata(metadataPath);\n if (!read.usable) {\n verbose(` Unusable ${STANDARD_FILES.METADATA_YAML} in '${skill.skillDirName}'`);\n return {\n kind: \"unusable\",\n refusal: { skillDirName: skill.skillDirName, metadataPath, reason: read.reason },\n };\n }\n\n // Skipped silently: the file is intact, and `extractLocalSkill` says which field to fix.\n if (namesPlaceholderCategory(read.metadata)) {\n verbose(` Placeholder ${METADATA_KEYS.CATEGORY} in '${skill.skillDirName}'`);\n return { kind: \"skipped\" };\n }\n\n return { kind: \"admitted\" };\n}\n\n/** Undefined, and logged, when the file cannot be read or names no skill. */\nasync function readSkillDefinition(skill: SkillLocation): Promise<SkillDefinition | undefined> {\n try {\n const content = await readFile(skill.skillMdPath);\n const frontmatter = parseFrontmatter(content, skill.skillMdPath);\n\n if (!frontmatter?.name) {\n warn(`Skipping skill in '${skill.skillDirName}': missing or invalid frontmatter name`);\n return undefined;\n }\n\n const canonicalId = frontmatter.name;\n verbose(` Loaded skill: ${canonicalId}`);\n return {\n id: canonicalId,\n path: skill.displayPath,\n description: frontmatter.description || \"\",\n };\n } catch (error) {\n verbose(` Failed to load skill: ${skill.skillFile} - ${getErrorMessage(error)}`);\n return undefined;\n }\n}\n\n/** Plugin skills carry no metadata.yaml, so nothing can be refused and only the map comes back. */\nexport async function loadPluginSkills(pluginDir: string): Promise<SkillDefinitionMap> {\n const { skills } = await loadSkillsFromDir(path.join(pluginDir, \"skills\"), {\n pathPrefix: \"skills\",\n requireMetadata: false,\n });\n return skills;\n}\n","import { parse as parseYaml } from \"yaml\";\nimport { getErrorMessage } from \"./errors\";\n\nconst FRONTMATTER_PATTERN = /^---\\r?\\n([\\s\\S]*?)\\r?\\n---/;\n\ntype FrontmatterRead = { parsed: unknown } | { unreadable: string };\n\nfunction readFrontmatter(content: string): FrontmatterRead {\n const block = content.match(FRONTMATTER_PATTERN)?.[1];\n if (!block) return { unreadable: \"there is no frontmatter between --- fences at its top\" };\n\n try {\n return { parsed: parseYaml(block) };\n } catch (error) {\n return { unreadable: getErrorMessage(error) };\n }\n}\n\nexport function extractFrontmatter(content: string): unknown {\n const read = readFrontmatter(content);\n return \"parsed\" in read ? read.parsed : null;\n}\n\n/** Why frontmatter reads as nothing (absent, empty or unparseable), or `undefined` when it reads. */\nexport function unreadableFrontmatter(content: string): string | undefined {\n const read = readFrontmatter(content);\n if (\"unreadable\" in read) return read.unreadable;\n return read.parsed === null ? \"its frontmatter is empty\" : undefined;\n}\n","import { createHash } from \"crypto\";\nimport { isRecord } from \"../../utils/type-guards.js\";\nimport { downloadTemplate, type DownloadTemplateResult } from \"giget\";\nimport os from \"os\";\nimport path from \"path\";\nimport type { z } from \"zod\";\n\nimport {\n cacheRoot,\n CACHE_HASH_LENGTH,\n CACHE_READABLE_PREFIX_LENGTH,\n MAX_MARKETPLACE_FILE_SIZE,\n MAX_JSON_NESTING_DEPTH,\n MAX_MARKETPLACE_PLUGINS,\n MARKETPLACE_JSON,\n marketplaceManifestPath,\n} from \"../../consts\";\nimport { getErrorMessage } from \"../../utils/errors\";\nimport {\n ensureDir,\n directoryExists,\n fileExists,\n readFileOptional,\n readFileSafe,\n remove,\n writeFile,\n} from \"../../utils/fs\";\nimport { log, verbose, warn } from \"../../utils/logger\";\nimport { sourceUnreachableUsingCache, STATUS_MESSAGES } from \"../../utils/messages\";\nimport {\n DEFAULT_SOURCE,\n isLocalSource,\n NAMED_MARKETPLACE,\n validateSourceFormat,\n} from \"../configuration\";\nimport { validateLoadedMarketplaceName } from \"../marketplace-generator\";\nimport {\n formatZodIssues,\n marketplaceSchema,\n sourceRevalidationSchema,\n validateNestingDepth,\n warnUnknownFields,\n} from \"../schemas\";\nimport type { Marketplace, MarketplaceFetchResult } from \"../../types\";\n\n/** No shell metacharacters. */\nconst SAFE_NAME_PATTERN = /^[a-zA-Z0-9@._/ -]+$/;\nconst MAX_NAME_LENGTH = 200;\nconst QUOTED_NAME_LENGTH = 50;\n\n/** Matches giget's source protocol regex to extract provider name */\nconst SOURCE_PROTO_RE = /^([\\w-.]+):/;\n\n/** giget's git URI regex. Groups: repo (org/name), subdir, ref (#branch). */\nconst GIT_URI_RE = /^(?<repo>[\\w.-]+\\/[\\w.-]+)(?<subdir>[^#]+)?(?<ref>#[\\w./@-]+)?/;\n\ntype FetchOptions = {\n subdir?: string;\n};\n\ntype FetchResult = {\n path: string;\n fromCache: boolean;\n /** The source could not be asked, so a cached copy of unknown age stood in for it. */\n unreachable: boolean;\n source: string;\n};\n\nexport function sanitizeSourceForCache(source: string): string {\n const hash = createHash(\"sha256\").update(source).digest(\"hex\").slice(0, CACHE_HASH_LENGTH);\n\n const readable = source\n .replace(/[^a-zA-Z0-9]/g, \"-\")\n .replace(/--+/g, \"-\")\n .replace(/^-|-$/g, \"\")\n .slice(0, CACHE_READABLE_PREFIX_LENGTH);\n\n return readable ? `${readable}-${hash}` : hash;\n}\n\nfunction getCacheDir(source: string): string {\n const sanitized = sanitizeSourceForCache(source) || \"unknown\";\n return path.join(cacheRoot(), \"sources\", sanitized);\n}\n\n/** Every fetch passes the check `resolveSource` applies, whoever chose the source. */\nexport async function fetchFromSource(\n source: string,\n options: FetchOptions = {},\n): Promise<FetchResult> {\n const { subdir } = options;\n validateSourceFormat(source, NAMED_MARKETPLACE);\n\n if (isLocalSource(source)) {\n return fetchFromLocalSource(source, subdir);\n }\n\n return fetchFromRemoteSource(source, subdir);\n}\n\nasync function fetchFromLocalSource(source: string, subdir?: string): Promise<FetchResult> {\n const fullPath = subdir ? path.join(source, subdir) : source;\n const absolutePath = path.isAbsolute(fullPath) ? fullPath : path.resolve(process.cwd(), fullPath);\n\n if (!(await directoryExists(absolutePath))) {\n throw new Error(\n `Local marketplace not found: '${absolutePath}'\\n\\n` +\n `Nothing is at that path, and a local marketplace must be a directory holding skills.\\n\\n` +\n `Check it for a typo, or name a marketplace that exists:\\n` +\n ` --marketplace ${DEFAULT_SOURCE}`,\n );\n }\n\n verbose(`Using local marketplace: ${absolutePath}`);\n\n return {\n path: absolutePath,\n fromCache: false,\n unreachable: false,\n source,\n };\n}\n\n/** Replicates giget's cache path, `{root}/{provider}/{repo}`; undefined for a non-git source. */\nexport function getGigetCacheDir(source: string): string | undefined {\n const protoMatch = source.match(SOURCE_PROTO_RE);\n\n // http/https providers use the full URL, not parseable as git URI\n if (protoMatch && (protoMatch[1] === \"http\" || protoMatch[1] === \"https\")) {\n return undefined;\n }\n\n const providerName = protoMatch?.[1] ?? \"github\";\n const rawSource = protoMatch ? source.slice(protoMatch[0].length) : source;\n\n const uriMatch = rawSource.match(GIT_URI_RE);\n if (!uriMatch?.groups?.repo) {\n return undefined;\n }\n\n // Replicate giget's template.name sanitization\n const templateName = uriMatch.groups.repo.replace(\"/\", \"-\").replace(/[^\\da-z-]/gi, \"-\");\n\n const gigetCacheRoot = process.env.XDG_CACHE_HOME\n ? path.resolve(process.env.XDG_CACHE_HOME, \"giget\")\n : path.resolve(os.homedir(), \".cache\", \"giget\");\n\n return path.join(gigetCacheRoot, providerName, templateName);\n}\n\n/** Clears giget's tarball/ETag cache so downloadTemplate() fetches fresh. */\nasync function clearGigetCache(source: string): Promise<void> {\n const gigetDir = getGigetCacheDir(source);\n if (!gigetDir) return;\n\n if (await directoryExists(gigetDir)) {\n verbose(`Clearing giget cache: ${gigetDir}`);\n await remove(gigetDir);\n }\n}\n\nasync function fetchFromRemoteSource(source: string, subdir?: string): Promise<FetchResult> {\n const cacheDir = getCacheDir(source);\n const fullSource = subdir ? `${source}/${subdir}` : source;\n\n verbose(`Fetching from remote: ${fullSource}`);\n verbose(`Cache directory: ${cacheDir}`);\n\n if (await directoryExists(cacheDir)) {\n const verdict = await revalidateCachedCopy(cacheDir, source);\n if (verdict === \"current\" || verdict === \"unreachable\") {\n verbose(`Using cached marketplace: ${cacheDir}`);\n return {\n path: cacheDir,\n fromCache: true,\n unreachable: verdict === \"unreachable\",\n source: fullSource,\n };\n }\n\n announceRefetch(verdict);\n await discardCachedCopy(cacheDir, source);\n }\n\n return downloadFreshCopy(cacheDir, source, fullSource);\n}\n\nasync function discardCachedCopy(cacheDir: string, source: string): Promise<void> {\n await clearGigetCache(source);\n await remove(cacheDir);\n}\n\nasync function downloadFreshCopy(\n cacheDir: string,\n source: string,\n fullSource: string,\n): Promise<FetchResult> {\n await ensureDir(path.dirname(cacheDir));\n\n try {\n const result = await downloadTemplate(fullSource, {\n dir: cacheDir,\n force: true, // Always force when downloading to avoid \"already exists\" error\n offline: false,\n });\n\n verbose(`Downloaded to: ${result.dir}`);\n await recordFetchedCopy(cacheDir, result);\n markCopyCurrentForThisRun(cacheDir);\n\n return {\n path: result.dir,\n fromCache: false,\n unreachable: false,\n source: fullSource,\n };\n } catch (error) {\n throw createDetailedFetchError(error, source);\n }\n}\n\n/** `unrecorded`: no fetch record beside the cache, so it is re-fetched once, quietly. */\ntype CacheVerdict = \"current\" | \"superseded\" | \"unrecorded\" | \"unreachable\";\n\ntype SourceRevalidation = z.infer<typeof sourceRevalidationSchema>;\n\n/** About twenty times a healthy answer, and half the platform's ~10s connect timeout. */\nconst REVALIDATION_TIMEOUT_MS = 5000;\n\n/** Where a cache directory's fetch record sits: beside it, never inside it. */\nconst FETCH_RECORD_SUFFIX = \".etag.json\";\n\n/** One question per source per process: a command loads the same source more than once. */\nconst askedThisRun = new Map<string, Promise<CacheVerdict>>();\n\n/** Silent for `unrecorded`, which is housekeeping rather than news. */\nfunction announceRefetch(verdict: Extract<CacheVerdict, \"superseded\" | \"unrecorded\">): void {\n if (verdict === \"superseded\") {\n log(STATUS_MESSAGES.MARKETPLACE_HAS_NEWER_CONTENT);\n }\n}\n\nfunction revalidateCachedCopy(cacheDir: string, source: string): Promise<CacheVerdict> {\n const asked = askedThisRun.get(cacheDir);\n if (asked) return asked;\n\n const verdict = classifyCachedCopy(cacheDir, source);\n askedThisRun.set(cacheDir, verdict);\n return verdict;\n}\n\n/**\n * A copy this run just downloaded is current by construction, so later loads do not re-fetch it.\n */\nfunction markCopyCurrentForThisRun(cacheDir: string): void {\n askedThisRun.set(cacheDir, Promise.resolve(\"current\"));\n}\n\n/** Warns about an unreachable source here, where the verdict is memoised: once per run. */\nasync function classifyCachedCopy(cacheDir: string, source: string): Promise<CacheVerdict> {\n const record = await readFetchRecord(cacheDir);\n if (!record) return \"unrecorded\";\n\n if (record.etag === undefined) {\n verbose(`No ETag was recorded for ${record.tar} — keeping the cached copy`);\n return \"current\";\n }\n\n try {\n const live = await fetchEtag(record.tar);\n if (live === undefined) {\n verbose(`${record.tar} answered without an ETag — keeping the cached copy`);\n return \"current\";\n }\n return live === record.etag ? \"current\" : \"superseded\";\n } catch (error) {\n verbose(`Could not revalidate ${record.tar}: ${getErrorMessage(error)}`);\n warn(sourceUnreachableUsingCache(source));\n return \"unreachable\";\n }\n}\n\n/** A HEAD from the same runtime as giget, so the two agree; the token is never stored. */\nasync function fetchEtag(tar: string): Promise<string | undefined> {\n const auth = process.env.GIGET_AUTH;\n const response = await fetch(tar, {\n method: \"HEAD\",\n ...(auth && { headers: { Authorization: `Bearer ${auth}` } }),\n signal: AbortSignal.timeout(REVALIDATION_TIMEOUT_MS),\n });\n return response.headers.get(\"etag\") ?? undefined;\n}\n\n/** Exported: `e2e/fixtures/default-source-cache.ts` seeds a cache and writes its record here. */\nexport function fetchRecordPath(cacheDir: string): string {\n return `${cacheDir}${FETCH_RECORD_SUFFIX}`;\n}\n\nasync function readFetchRecord(cacheDir: string): Promise<SourceRevalidation | undefined> {\n const raw = await readFileOptional(fetchRecordPath(cacheDir));\n if (!raw) return undefined;\n\n const parsed = sourceRevalidationSchema.safeParse(parseJsonOrUndefined(raw));\n if (!parsed.success) {\n verbose(`Unusable fetch record at ${fetchRecordPath(cacheDir)} — re-fetching the marketplace`);\n return undefined;\n }\n\n return parsed.data;\n}\n\n/** The tarball URL is narrowed from giget's untyped result; without one, nothing is recorded. */\nasync function recordFetchedCopy(cacheDir: string, result: DownloadTemplateResult): Promise<void> {\n const tar: unknown = result.tar;\n if (typeof tar !== \"string\") {\n verbose(\"No tarball URL came back from the download — the copy cannot be revalidated\");\n return;\n }\n\n const etag = await fetchEtag(tar).catch(() => undefined);\n const record: SourceRevalidation = { tar, ...(etag !== undefined && { etag }) };\n await writeFile(fetchRecordPath(cacheDir), JSON.stringify(record));\n}\n\nfunction parseJsonOrUndefined(raw: string): unknown {\n try {\n return JSON.parse(raw);\n } catch {\n return undefined;\n }\n}\n\nfunction createDetailedFetchError(error: unknown, source: string): Error {\n const message = getErrorMessage(error);\n\n if (message.includes(\"404\") || message.includes(\"Not Found\")) {\n return new Error(\n `Repository not found: ${source}\\n\\n` +\n `This could mean:\\n` +\n ` - The repository doesn't exist\\n` +\n ` - The repository is private and you need to set authentication\\n` +\n ` - There's a typo in the URL\\n\\n` +\n `For private repositories, set the GIGET_AUTH environment variable:\\n` +\n ` export GIGET_AUTH=ghp_your_github_token`,\n );\n }\n\n if (message.includes(\"401\") || message.includes(\"Unauthorized\")) {\n return new Error(\n `Authentication required for: ${source}\\n\\n` +\n `Set the GIGET_AUTH environment variable with a GitHub token:\\n` +\n ` export GIGET_AUTH=ghp_your_github_token\\n\\n` +\n `Create a token at: https://github.com/settings/tokens\\n` +\n `Required scope: repo (for private repos) or public_repo (for public)`,\n );\n }\n\n if (message.includes(\"403\") || message.includes(\"Forbidden\")) {\n return new Error(\n `Access denied to: ${source}\\n\\n` +\n `Your token may not have sufficient permissions.\\n` +\n `Ensure your GIGET_AUTH token has the 'repo' scope for private repositories.`,\n );\n }\n\n if (\n message.includes(\"ENOTFOUND\") ||\n message.includes(\"ETIMEDOUT\") ||\n message.includes(\"network\")\n ) {\n return new Error(\n `Network error fetching: ${source}\\n\\n` +\n `Please check your internet connection.\\n` +\n `If you're behind a corporate proxy, you may need to set:\\n` +\n ` export HTTPS_PROXY=http://your-proxy:port\\n` +\n ` export FORCE_NODE_FETCH=true # Required for Node 20+`,\n );\n }\n\n return new Error(`Failed to fetch ${source}: ${message}`);\n}\n\n/** Absent and unreadable have different remedies, so absence gets its own type. */\nexport class MarketplaceManifestAbsentError extends Error {}\n\n/** A name Claude Code will not register plugins under: it loads but installs nothing. */\nexport class MarketplaceNameRefusedError extends Error {}\n\n/** Typed against `Marketplace`, so a rename fails here rather than silencing the refusal. */\nconst MANIFEST_NAME_FIELD: keyof Marketplace = \"name\";\n\n/** Worded as the schema's own name refusal: the manifest is the file the reader can change. */\nconst LOADED_NAME_WAY_OUT = \"rename the marketplace in this manifest\";\n\n/** Read off the issue path, not its text, which gets rewritten. */\nfunction refusesTheName(issues: readonly z.ZodIssue[]): boolean {\n return issues.some((issue) => issue.path.length === 1 && issue.path[0] === MANIFEST_NAME_FIELD);\n}\n\n/** The same sentence either way; the error type carries the remedy. */\nfunction manifestRefusal(marketplacePath: string, issues: readonly z.ZodIssue[]): Error {\n const message =\n `Invalid ${MARKETPLACE_JSON} at: ${marketplacePath}\\n\\n` +\n `Validation errors: ${formatZodIssues([...issues])}`;\n\n return refusesTheName(issues) ? new MarketplaceNameRefusedError(message) : new Error(message);\n}\n\nexport async function fetchMarketplace(source: string): Promise<MarketplaceFetchResult> {\n const { path: sourcePath, fromCache } = await fetchFromSource(source, { subdir: \"\" });\n const marketplacePath = marketplaceManifestPath(sourcePath);\n\n await refuseAbsentManifest(marketplacePath, source);\n const parsed = await readManifestJson(marketplacePath);\n const marketplace = validateManifest(parsed, marketplacePath);\n warnAboutUnknownManifestFields(parsed);\n refuseTooManyPlugins(marketplace, marketplacePath);\n warnAboutPluginNames(marketplace);\n\n verbose(`Loaded marketplace: ${marketplace.name} v${marketplace.version}`);\n return { marketplace, sourcePath, fromCache };\n}\n\n/** The file, not its directory: a plugin repo ships `.claude-plugin/` with no marketplace in it. */\nasync function refuseAbsentManifest(marketplacePath: string, source: string): Promise<void> {\n if (await fileExists(marketplacePath)) return;\n\n throw new MarketplaceManifestAbsentError(\n `Marketplace not found at: ${source}\\n\\n` +\n `The .claude-plugin/marketplace.json file is missing from this repository.\\n\\n` +\n `Possible causes:\\n` +\n \" - The marketplace URL may be incorrect\\n\" +\n \" - The repository may not have a marketplace configured\\n\\n\" +\n \"To create a marketplace, add a .claude-plugin/marketplace.json file to your marketplace repository.\",\n );\n}\n\nasync function readManifestJson(marketplacePath: string): Promise<unknown> {\n const content = await readFileSafe(marketplacePath, MAX_MARKETPLACE_FILE_SIZE);\n const parsed: unknown = JSON.parse(content);\n\n if (!validateNestingDepth(parsed, MAX_JSON_NESTING_DEPTH)) {\n throw new Error(\n `Invalid marketplace.json at: ${marketplacePath}\\n\\n` +\n `JSON structure exceeds maximum nesting depth of ${MAX_JSON_NESTING_DEPTH}.`,\n );\n }\n return parsed;\n}\n\n/** The schema first, then the reserved names the schema cannot know. */\nfunction validateManifest(parsed: unknown, marketplacePath: string): Marketplace {\n const validation = marketplaceSchema.safeParse(parsed);\n if (!validation.success) {\n throw manifestRefusal(marketplacePath, validation.error.issues);\n }\n\n const marketplace = validation.data;\n const reservedName = validateLoadedMarketplaceName(marketplace.name, LOADED_NAME_WAY_OUT);\n if (reservedName) {\n throw new MarketplaceNameRefusedError(\n `Invalid ${MARKETPLACE_JSON} at: ${marketplacePath}\\n\\n${reservedName}`,\n );\n }\n return marketplace;\n}\n\nconst EXPECTED_MARKETPLACE_KEYS = [\n \"$schema\",\n \"name\",\n \"version\",\n \"description\",\n \"owner\",\n \"metadata\",\n \"plugins\",\n] as const;\n\nfunction warnAboutUnknownManifestFields(parsed: unknown): void {\n if (isRecord(parsed)) {\n warnUnknownFields(parsed, EXPECTED_MARKETPLACE_KEYS, MARKETPLACE_JSON);\n }\n}\n\nfunction refuseTooManyPlugins(marketplace: Marketplace, marketplacePath: string): void {\n if (marketplace.plugins.length <= MAX_MARKETPLACE_PLUGINS) return;\n\n throw new Error(\n `Invalid marketplace.json at: ${marketplacePath}\\n\\n` +\n `Too many plugins: ${marketplace.plugins.length} (limit: ${MAX_MARKETPLACE_PLUGINS}).`,\n );\n}\n\nfunction warnAboutPluginNames(marketplace: Marketplace): void {\n for (const plugin of marketplace.plugins) {\n if (plugin.name.length > MAX_NAME_LENGTH) {\n warn(\n `Marketplace plugin name too long (${plugin.name.length} chars): '${plugin.name.slice(0, QUOTED_NAME_LENGTH)}...'`,\n );\n }\n if (!SAFE_NAME_PATTERN.test(plugin.name)) {\n warn(\n `Marketplace plugin name contains unsafe characters: '${plugin.name.slice(0, QUOTED_NAME_LENGTH)}'`,\n );\n }\n }\n}\n","import path from \"path\";\nimport { countBy, sortBy } from \"remeda\";\n\nimport {\n DEFAULT_PUBLIC_SOURCE_NAME,\n DEFAULT_VERSION,\n EJECT_SOURCE,\n PLUGIN_MANIFEST_DIR,\n PLUGIN_MANIFEST_FILE,\n PUBLIC_CATALOGUE_PACKAGE,\n} from \"../consts\";\nimport { writeFile, glob, ensureDir } from \"../utils/fs\";\nimport { verbose, warn } from \"../utils/logger\";\nimport type { Marketplace, MarketplacePlugin, PluginManifest } from \"../types\";\n// Not the `./plugins` barrel, which reaches the loader back through plugin discovery.\nimport { readPluginManifest } from \"./plugins/plugin-finder\";\n\nconst PLUGIN_MANIFEST_PATH = `${PLUGIN_MANIFEST_DIR}/${PLUGIN_MANIFEST_FILE}`;\nconst MARKETPLACE_SCHEMA_URL = \"https://anthropic.com/claude-code/marketplace.schema.json\";\n\nconst EXTERNAL_SKILL_NAMESPACE = \"external\";\n\nconst LOCAL_SKILL_NAMESPACE = \"local\";\n\n/** Ids an author does not own: the catalogue's, `external`, `local`, and `eject`. */\nconst RESERVED_MARKETPLACE_NAMES: readonly string[] = [\n DEFAULT_PUBLIC_SOURCE_NAME,\n EXTERNAL_SKILL_NAMESPACE,\n LOCAL_SKILL_NAMESPACE,\n EJECT_SOURCE,\n];\n\nconst MAX_REPORTED_NAMESPACE_VIOLATIONS = 10;\n\ntype MarketplaceOptions = {\n name: string;\n version?: string;\n description?: string;\n ownerName: string;\n ownerEmail?: string;\n pluginRoot: string;\n};\n\nfunction convertManifestToMarketplacePlugin(\n manifest: PluginManifest,\n pluginRoot: string,\n pluginDirName: string,\n): MarketplacePlugin {\n return {\n name: manifest.name,\n source: `./${pluginRoot}/${pluginDirName}`,\n ...(manifest.description !== undefined && { description: manifest.description }),\n ...(manifest.version !== undefined && { version: manifest.version }),\n ...(manifest.author !== undefined && { author: manifest.author }),\n ...(manifest.category !== undefined && { category: manifest.category }),\n ...(manifest.keywords !== undefined && { keywords: manifest.keywords }),\n };\n}\n\nexport async function generateMarketplace(\n pluginsDir: string,\n options: MarketplaceOptions,\n): Promise<Marketplace> {\n verbose(`Scanning plugins directory: ${pluginsDir}`);\n\n const manifestFiles = await glob(`**/${PLUGIN_MANIFEST_PATH}`, pluginsDir);\n verbose(`Found ${manifestFiles.length} plugin manifests`);\n\n const plugins: MarketplacePlugin[] = [];\n const rootWithoutDotSlash = options.pluginRoot.replace(/^\\.\\//, \"\");\n\n for (const manifestFile of manifestFiles) {\n const pluginDirName = pluginDirNameOf(manifestFile);\n const pluginDir = path.join(pluginsDir, pluginDirName);\n\n const manifest = await readPluginManifest(pluginDir);\n if (!manifest) {\n warn(`Could not read plugin manifest: '${manifestFile}'`);\n continue;\n }\n\n const plugin = convertManifestToMarketplacePlugin(manifest, rootWithoutDotSlash, pluginDirName);\n plugins.push(plugin);\n verbose(` [OK] ${plugin.name}`);\n }\n\n const sortedPlugins = sortBy(plugins, (p) => p.name);\n\n // Field order matters: the object is serialized verbatim into marketplace.json.\n return {\n $schema: MARKETPLACE_SCHEMA_URL,\n name: options.name,\n version: options.version ?? DEFAULT_VERSION,\n owner: {\n name: options.ownerName,\n ...(options.ownerEmail ? { email: options.ownerEmail } : {}),\n },\n metadata: {\n pluginRoot: options.pluginRoot,\n },\n plugins: sortedPlugins,\n ...(options.description ? { description: options.description } : {}),\n };\n}\n\n/** The first segment of a manifest's path under the plugins directory. */\nfunction pluginDirNameOf(manifestFile: string): string {\n const separator = manifestFile.indexOf(\"/\");\n return separator === -1 ? manifestFile : manifestFile.slice(0, separator);\n}\n\n/** `packageName` tells the catalogue's own package from a claimant; `wayOut` is the remedy. */\nexport function validateMarketplaceName(\n marketplaceName: string,\n packageName: string,\n wayOut: string,\n): string | null {\n if (!RESERVED_MARKETPLACE_NAMES.includes(marketplaceName)) return null;\n if (isCatalogueOwnReservedName(marketplaceName, packageName)) return null;\n\n return reservedNameError(marketplaceName, wayOut);\n}\n\n/** The reserved list less the catalogue's own name: a load has no package.json to check. */\nexport function validateLoadedMarketplaceName(\n marketplaceName: string,\n wayOut: string,\n): string | null {\n if (marketplaceName === DEFAULT_PUBLIC_SOURCE_NAME) return null;\n return RESERVED_MARKETPLACE_NAMES.includes(marketplaceName)\n ? reservedNameError(marketplaceName, wayOut)\n : null;\n}\n\n/**\n * The public catalogue is exempt, which is safe only because `validateMarketplaceName` runs first.\n */\nexport function validateSkillIdNamespace(marketplace: Marketplace): string | null {\n if (marketplace.name === DEFAULT_PUBLIC_SOURCE_NAME) return null;\n\n const foreignIds = marketplace.plugins\n .filter((plugin) => !carriesNamespace(plugin.name, marketplace.name))\n .map((plugin) => plugin.name);\n\n if (foreignIds.length === 0) return null;\n\n return namespaceViolationError(foreignIds, marketplace.name);\n}\n\n/** Both halves: the name claimed is the catalogue's and so is the package claiming it. */\nfunction isCatalogueOwnReservedName(marketplaceName: string, packageName: string): boolean {\n return marketplaceName === DEFAULT_PUBLIC_SOURCE_NAME && packageName === PUBLIC_CATALOGUE_PACKAGE;\n}\n\nfunction carriesNamespace(skillId: string, marketplaceName: string): boolean {\n return skillId.startsWith(`${marketplaceName}-`);\n}\n\nfunction reservedNameError(marketplaceName: string, wayOut: string): string {\n return (\n `Marketplace name '${marketplaceName}' is reserved. ` +\n `'${DEFAULT_PUBLIC_SOURCE_NAME}' is the public catalogue's own namespace, ` +\n `'${EXTERNAL_SKILL_NAMESPACE}' and '${LOCAL_SKILL_NAMESPACE}' hold the skills that belong to ` +\n `no marketplace, and '${EJECT_SOURCE}' is what an installation records for a skill copied ` +\n `into it rather than installed as a plugin — a marketplace under any of them is read back ` +\n `as something it is not. Choose a name of your own: ${wayOut}.`\n );\n}\n\nfunction namespaceViolationError(foreignIds: string[], marketplaceName: string): string {\n const listed = foreignIds\n .slice(0, MAX_REPORTED_NAMESPACE_VIOLATIONS)\n .map((id) => ` ${id} -> ${marketplaceName}-${id}`);\n const unlisted = foreignIds.length - listed.length;\n\n return [\n `Marketplace '${marketplaceName}' ships ${foreignIds.length} skill id(s) outside its own ` +\n `namespace. Every skill id must begin with the marketplace's name:`,\n ...listed,\n ...(unlisted > 0 ? [` ... and ${unlisted} more`] : []),\n `Rename each skill directory and the 'name' in its SKILL.md, re-run 'build plugins', then ` +\n `build the marketplace again.`,\n ].join(\"\\n\");\n}\n\nexport async function writeMarketplace(\n outputPath: string,\n marketplace: Marketplace,\n): Promise<void> {\n await ensureDir(path.dirname(outputPath));\n const content = `${JSON.stringify(marketplace, null, 2)}\\n`;\n await writeFile(outputPath, content);\n}\n\nexport function getMarketplaceStats(marketplace: Marketplace): {\n total: number;\n byCategory: Record<string, number>;\n} {\n return {\n total: marketplace.plugins.length,\n byCategory: countBy(marketplace.plugins, (p) => p.category ?? \"uncategorized\"),\n };\n}\n","import os from \"os\";\nimport { unique } from \"remeda\";\n\nimport { isHomeDirectory } from \"../installation/is-home-directory\";\nimport { DEFAULT_PUBLIC_SOURCE_NAME, EJECT_SOURCE } from \"../../consts\";\nimport type {\n MergedSkillsMatrix,\n ResolvedSkill,\n SkillId,\n SkillSource,\n SkillSourceType,\n} from \"../../types\";\nimport { verbose } from \"../../utils/logger\";\nimport { typedEntries, typedKeys } from \"../../utils/typed-object\";\nimport { isDefaultSource, type ResolvedConfig } from \"../configuration\";\nimport { discoverAllPluginSkills } from \"../plugins\";\n\n/** Asked of the tagged sources, not `custom`; a skill the pass never reached answers `false`. */\nexport function isLocalOnlySkill(skill: ResolvedSkill | undefined): boolean {\n return (\n skill?.availableSources !== undefined &&\n !skill.availableSources.some((source) => source.type !== \"local\")\n );\n}\n\nfunction addAvailableSource(\n skill: { availableSources?: SkillSource[] },\n source: SkillSource,\n): void {\n skill.availableSources = skill.availableSources ?? [];\n skill.availableSources.push(source);\n}\n\n/**\n * Tags every skill with `availableSources` (the local copy and at most one marketplace) and\n * `activeSource`, mutating `primaryMatrix` in place. `unbackedSkillIds` are ids the marketplace\n * does not carry, left out of the marketplace tag.\n */\nexport async function loadSkillsFromAllSources(\n primaryMatrix: MergedSkillsMatrix,\n sourceConfig: ResolvedConfig,\n projectDir: string,\n marketplace?: string,\n unbackedSkillIds: ReadonlySet<SkillId> = new Set(),\n): Promise<void> {\n const { name: primarySourceName, type: primarySourceType } = marketplaceSource(\n sourceConfig,\n marketplace,\n );\n\n tagPrimarySourceSkills(primaryMatrix, sourceConfig, marketplace, unbackedSkillIds);\n tagLocalSkills(primaryMatrix);\n await tagPluginSkills(primaryMatrix, projectDir, primarySourceName, primarySourceType);\n setActiveSources(primaryMatrix);\n}\n\n/** A fresh object per call: the tagging pass mutates the entry it is handed. */\nexport function marketplaceSource(sourceConfig: ResolvedConfig, marketplace?: string): SkillSource {\n return {\n name: marketplace ?? sourceConfig.marketplace ?? DEFAULT_PUBLIC_SOURCE_NAME,\n type: isDefaultSource(sourceConfig.source) ? \"public\" : \"private\",\n installed: false,\n primary: true,\n };\n}\n\nfunction tagPrimarySourceSkills(\n matrix: MergedSkillsMatrix,\n sourceConfig: ResolvedConfig,\n marketplace: string | undefined,\n unbackedSkillIds: ReadonlySet<SkillId>,\n): void {\n for (const [id, skill] of typedEntries(matrix.skills)) {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- Object.entries drops the `| undefined` a Partial<Record> admits\n if (!skill) continue;\n if (unbackedSkillIds.has(id)) continue;\n\n addAvailableSource(skill, marketplaceSource(sourceConfig, marketplace));\n }\n}\n\nfunction tagLocalSkills(matrix: MergedSkillsMatrix): void {\n let count = 0;\n for (const [, skill] of typedEntries(matrix.skills)) {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- Object.entries drops the `| undefined` a Partial<Record> admits\n if (!skill) continue;\n if (!skill.local) continue;\n\n const source: SkillSource = {\n name: EJECT_SOURCE,\n type: \"local\",\n installed: true,\n installMode: \"eject\",\n };\n\n addAvailableSource(skill, source);\n count++;\n }\n\n verbose(`Tagged ${count} local skills with local source`);\n}\n\nasync function tagPluginSkills(\n matrix: MergedSkillsMatrix,\n projectDir: string,\n primarySourceName: string,\n primarySourceType: SkillSourceType,\n): Promise<void> {\n const allPluginSkillIds = await collectPluginSkillIds(projectDir);\n\n if (allPluginSkillIds.length === 0) {\n return;\n }\n\n for (const skillId of allPluginSkillIds) {\n const skill = matrix.skills[skillId];\n if (!skill) continue;\n\n markInstalledAsPlugin(skill, primarySourceName, primarySourceType);\n }\n\n verbose(`Tagged ${allPluginSkillIds.length} plugin-installed skills`);\n}\n\n/** Uses the skill's own marketplace entry, so a seated global skill keeps its own label. */\nfunction markInstalledAsPlugin(\n skill: ResolvedSkill,\n primarySourceName: string,\n primarySourceType: SkillSourceType,\n): void {\n skill.availableSources = skill.availableSources ?? [];\n\n const existingSource = skill.availableSources.find((s) => s.primary === true);\n if (existingSource && !existingSource.installMode) {\n existingSource.installed = true;\n existingSource.installMode = \"plugin\";\n return;\n }\n if (skill.availableSources.some((s) => s.installMode === \"plugin\")) return;\n\n addAvailableSource(skill, {\n name: primarySourceName,\n type: primarySourceType,\n installed: true,\n installMode: \"plugin\",\n primary: true,\n });\n}\n\nasync function collectPluginSkillIds(projectDir: string): Promise<SkillId[]> {\n const projectSkillIds = await pluginSkillIdsIn(projectDir);\n const globalSkillIds = isHomeDirectory(projectDir) ? [] : await pluginSkillIdsIn(os.homedir());\n\n if (globalSkillIds.length > 0) {\n verbose(`Found ${globalSkillIds.length} global plugin skill(s)`);\n return unique([...projectSkillIds, ...globalSkillIds]);\n }\n\n if (projectSkillIds.length === 0) {\n verbose(\"No plugin skills discovered from settings.json\");\n }\n\n return projectSkillIds;\n}\n\nasync function pluginSkillIdsIn(dir: string): Promise<SkillId[]> {\n return typedKeys<SkillId>(await discoverAllPluginSkills(dir));\n}\n\nfunction setActiveSources(matrix: MergedSkillsMatrix): void {\n for (const [, skill] of typedEntries(matrix.skills)) {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- Object.entries drops the `| undefined` a Partial<Record> admits\n if (!skill) continue;\n\n const sources = skill.availableSources ?? [];\n const [firstSource] = sources;\n if (!firstSource) continue;\n skill.activeSource = sources.find((s) => s.installed) ?? firstSource;\n }\n}\n","import type {\n AgentConfig,\n AgentDefinition,\n AgentName,\n CompileAgentConfig,\n CompileConfig,\n Skill,\n SkillDefinitionMap,\n SkillReference,\n StackAgentConfig,\n} from \"../types\";\nimport { verbose } from \"../utils/logger\";\nimport { typedEntries, typedFromEntries, typedKeys } from \"../utils/typed-object\";\nimport { resolveAgentConfigToSkills } from \"./stacks/stacks-loader\";\n\nfunction resolveSkillReference(ref: SkillReference, skills: SkillDefinitionMap): Skill | null {\n const definition = skills[ref.id];\n if (!definition) {\n verbose(`Skill '${ref.id}' not found in available skills, skipping`);\n return null;\n }\n return {\n ...definition,\n usage: ref.usage,\n preloaded: ref.preloaded ?? false,\n ...(ref.source !== undefined && { source: ref.source }),\n };\n}\n\nfunction resolveSkillReferences(skillRefs: SkillReference[], skills: SkillDefinitionMap): Skill[] {\n return skillRefs\n .map((ref) => resolveSkillReference(ref, skills))\n .filter((skill): skill is Skill => skill !== null);\n}\n\nexport function buildSkillRefsFromConfig(agentStack: StackAgentConfig): SkillReference[] {\n return resolveAgentConfigToSkills(agentStack);\n}\n\n/** Throws when the compile config names an agent no scanned directory defines. */\n// eslint-disable-next-line @typescript-eslint/require-await -- callers await it\nexport async function resolveAgents(\n agents: Partial<Record<AgentName, AgentDefinition>>,\n skills: SkillDefinitionMap,\n compileConfig: CompileConfig,\n): Promise<Partial<Record<AgentName, AgentConfig>>> {\n const entries = typedEntries<AgentName, CompileAgentConfig>(compileConfig.agents).map(\n ([agentName, agentConfig]) =>\n [agentName, resolveAgent(agentName, agentConfig, agents, skills)] as const,\n );\n\n return typedFromEntries(entries);\n}\n\nfunction resolveAgent(\n agentName: AgentName,\n agentConfig: CompileAgentConfig,\n agents: Partial<Record<AgentName, AgentDefinition>>,\n skills: SkillDefinitionMap,\n): AgentConfig {\n const definition = agents[agentName];\n if (!definition) throw new Error(agentNotFoundError(agentName, agents));\n\n // `buildCompileAgents` has already expanded the stack into `skills`.\n const resolvedSkills = resolveSkillReferences(agentConfig.skills ?? [], skills);\n return assembleAgentConfig(agentName, definition, agentConfig, resolvedSkills);\n}\n\nconst MAX_LISTED_AVAILABLE_AGENTS = 5;\n\nfunction agentNotFoundError(\n agentName: AgentName,\n agents: Partial<Record<AgentName, AgentDefinition>>,\n): string {\n const availableAgents = describeAvailableAgents(typedKeys<AgentName>(agents));\n return `Agent '${agentName}' referenced in compile config but not found in scanned agents. ${availableAgents}. Check that src/agents/${agentName}/metadata.yaml exists.`;\n}\n\nfunction describeAvailableAgents(availableAgents: AgentName[]): string {\n if (availableAgents.length === 0) return \"No agents found in scanned directories\";\n\n const listed = availableAgents.slice(0, MAX_LISTED_AVAILABLE_AGENTS).join(\", \");\n const unlisted = availableAgents.length - MAX_LISTED_AVAILABLE_AGENTS;\n return unlisted > 0\n ? `Available agents: ${listed} (and ${unlisted} more)`\n : `Available agents: ${listed}`;\n}\n\nfunction assembleAgentConfig(\n agentName: AgentName,\n definition: AgentDefinition,\n agentConfig: CompileAgentConfig,\n resolvedSkills: Skill[],\n): AgentConfig {\n const model = agentConfig.model ?? definition.model;\n const effort = agentConfig.effort ?? definition.effort;\n\n return {\n name: agentName,\n title: definition.title,\n description: definition.description,\n ...(model !== undefined && { model }),\n ...(agentConfig.codexModel !== undefined && { codexModel: agentConfig.codexModel }),\n ...(effort !== undefined && { effort }),\n tools: definition.tools,\n // Spread conditionally: the template branches on presence, and `undefined` renders a key.\n ...(definition.disallowedTools !== undefined && {\n disallowedTools: definition.disallowedTools,\n }),\n ...(definition.permissionMode !== undefined && {\n permissionMode: definition.permissionMode,\n }),\n ...(definition.isolation !== undefined && { isolation: definition.isolation }),\n ...(definition.hooks !== undefined && { hooks: definition.hooks }),\n ...(definition.experimental !== undefined && {\n experimental: definition.experimental,\n }),\n skills: resolvedSkills,\n ...(definition.path !== undefined && { path: definition.path }),\n ...(definition.sourceRoot !== undefined && { sourceRoot: definition.sourceRoot }),\n ...(definition.agentBaseDir !== undefined && { agentBaseDir: definition.agentBaseDir }),\n };\n}\n","import os from \"os\";\n\nimport type { Provider } from \"../../consts.js\";\nimport { isHomeDirectory } from \"./is-home-directory.js\";\nimport { providerInUse, sourceFolderInUse } from \"./install-layout.js\";\nimport { directoryExists } from \"../../utils/fs.js\";\n\nexport type ScopeKind = \"project\" | \"global\";\n\nexport type ScopeRoot = { kind: ScopeKind; root: string };\n\nexport type SourceScope = {\n kind: ScopeKind;\n root: string;\n provider: Provider;\n /** As a user writes it: `.agents-inc/claude`. */\n relName: string;\n};\n\n/**\n * Scopes with a source folder on disk, global first. Each is read with the provider `providerOf`\n * names, off its folder by default; `doctor` names one installation's for both.\n */\nexport async function sourceScopesInPlay(\n cwd: string,\n providerOf: (scope: ScopeRoot) => Provider = ({ root }) => providerInUse(root),\n): Promise<SourceScope[]> {\n const scopes = await Promise.all(\n scopeRootsInPlay(cwd).map(async (scope) =>\n describeScope(scope.kind, scope.root, providerOf(scope)),\n ),\n );\n return scopes.filter((scope): scope is SourceScope => scope !== null);\n}\n\n/** Global first; run from home, the two scopes collapse into the global one. */\nexport function scopeRootsInPlay(cwd: string): ScopeRoot[] {\n const global: ScopeRoot = { kind: \"global\", root: os.homedir() };\n if (isHomeDirectory(cwd)) return [global];\n return [global, { kind: \"project\", root: cwd }];\n}\n\nasync function describeScope(\n kind: ScopeKind,\n root: string,\n provider: Provider,\n): Promise<SourceScope | null> {\n const folder = sourceFolderInUse(root, provider);\n if (!(await directoryExists(folder.dir))) return null;\n\n return { kind, root, provider, relName: folder.relName };\n}\n","import type { Provider } from \"../../consts.js\";\nimport { PROVIDERS } from \"../../consts.js\";\nimport { fileExists } from \"../../utils/fs.js\";\nimport { getProjectConfigPath } from \"./install-base-dir.js\";\nimport { scopeRootsInPlay, type ScopeKind, type ScopeRoot } from \"./source-scopes.js\";\n\nexport type DetectedInstallation = {\n provider: Provider;\n scope: ScopeKind;\n configPath: string;\n};\n\n/**\n * Global before project, roster order within a scope. Only a folder holding `config.ts` counts,\n * and a scope holding both providers yields two entries.\n */\nexport async function detectInstallations(cwd: string): Promise<DetectedInstallation[]> {\n const everywhereOneCouldBe = scopeRootsInPlay(cwd).flatMap(everyProviderUnder);\n const found = await Promise.all(everywhereOneCouldBe.map(installationIfPresent));\n\n return found.filter(\n (installation): installation is DetectedInstallation => installation !== null,\n );\n}\n\nfunction everyProviderUnder({ kind, root }: ScopeRoot): DetectedInstallation[] {\n return PROVIDERS.map((provider) => ({\n provider,\n scope: kind,\n configPath: getProjectConfigPath(root, provider),\n }));\n}\n\nasync function installationIfPresent(\n candidate: DetectedInstallation,\n): Promise<DetectedInstallation | null> {\n return (await fileExists(candidate.configPath)) ? candidate : null;\n}\n","/** Claude Code's plugin machinery, behind {@link PluginHost}. */\n\nimport os from \"os\";\nimport path from \"path\";\nimport { z } from \"zod\";\n\nimport { PLUGINS_SUBDIR } from \"../../consts.js\";\nimport type { ClaudePluginScope, SkillScope } from \"../../types/config.js\";\nimport { getErrorMessage } from \"../../utils/errors.js\";\nimport {\n execCommand,\n validateMarketplaceSource,\n validatePluginName,\n validatePluginPath,\n type ExecResult,\n} from \"../../utils/exec.js\";\nimport { fileExists } from \"../../utils/fs.js\";\nimport { warn } from \"../../utils/logger.js\";\nimport { pluginsDir } from \"../installation/install-layout.js\";\nimport {\n getEnabledPluginKeys,\n getInstalledPluginsRegistryPath,\n listPluginInstallsForProject,\n} from \"../plugins/plugin-settings.js\";\nimport type {\n HostCallOptions,\n HostPlugin,\n InstallPlacement,\n PluginHost,\n PluginRemovalOutcome,\n} from \"./plugin-host.js\";\n\nconst CLAUDE: PluginHost[\"provider\"] = \"claude\";\n\n/**\n * Claude's two spellings of \"no such plugin or marketplace\". It exits 1 for these and for real\n * failures alike, so the message is what's read; dropping either makes a second removal throw.\n */\nconst NOT_INSTALLED_MESSAGES = [\"not installed\", \"not found\"];\n\nfunction claudeOfferedPlacements(): InstallPlacement[] {\n return [\n { mode: \"plugin\", scope: \"global\" },\n { mode: \"plugin\", scope: \"project\" },\n { mode: \"eject\", scope: \"global\" },\n { mode: \"eject\", scope: \"project\" },\n ];\n}\n\nfunction toClaudePluginScope(scope: SkillScope | undefined): ClaudePluginScope {\n return scope === \"global\" ? \"user\" : \"project\";\n}\n\n/** User-scoped plugins run from home dir so Claude CLI only writes to ~/.claude/settings.json */\nfunction resolvePluginCwd(scope: ClaudePluginScope, projectDir: string): string {\n return scope === \"user\" ? os.homedir() : projectDir;\n}\n\nexport type ClaudeConfigOptions = HostCallOptions;\n\n/** `CLAUDE_CONFIG_DIR` beats `HOME` and overrides an exported one. */\nfunction configDirEnv(options: ClaudeConfigOptions | undefined): { env?: NodeJS.ProcessEnv } {\n if (options?.configDir === undefined) return {};\n return { env: { CLAUDE_CONFIG_DIR: options.configDir } };\n}\n\nexport async function claudePluginInstall(\n pluginPath: string,\n scope: ClaudePluginScope,\n projectDir: string,\n options?: ClaudeConfigOptions,\n): Promise<void> {\n validatePluginPath(pluginPath);\n\n const cwd = resolvePluginCwd(scope, projectDir);\n const args = [\"plugin\", \"install\", pluginPath, \"--scope\", scope];\n const result = await execCommand(\"claude\", args, { cwd, ...configDirEnv(options) });\n\n if (result.exitCode !== 0) {\n throw new Error(`Plugin installation failed: ${whyClaudeFailed(result)}`);\n }\n}\n\nexport async function isClaudeCLIAvailable(options?: ClaudeConfigOptions): Promise<boolean> {\n try {\n const result = await execCommand(\"claude\", [\"--version\"], configDirEnv(options));\n return result.exitCode === 0;\n } catch {\n return false;\n }\n}\n\nexport type MarketplaceInfo = {\n name: string;\n source: string;\n repo?: string;\n path?: string;\n};\n\nconst marketplaceInfoListSchema: z.ZodType<MarketplaceInfo[]> = z.array(\n z.object({\n name: z.string(),\n source: z.string(),\n repo: z.string().exactOptional(),\n path: z.string().exactOptional(),\n }),\n);\n\nexport async function claudePluginMarketplaceList(\n options?: ClaudeConfigOptions,\n): Promise<MarketplaceInfo[]> {\n try {\n const result = await execCommand(\n \"claude\",\n [\"plugin\", \"marketplace\", \"list\", \"--json\"],\n configDirEnv(options),\n );\n\n if (result.exitCode !== 0) return [];\n return marketplacesListedIn(result.stdout);\n } catch {\n return [];\n }\n}\n\nfunction marketplacesListedIn(stdout: string): MarketplaceInfo[] {\n let parsed: unknown;\n try {\n parsed = JSON.parse(stdout);\n } catch {\n warn(\"Failed to parse marketplace list output as JSON\");\n return [];\n }\n\n const listResult = marketplaceInfoListSchema.safeParse(parsed);\n if (!listResult.success) {\n warn(\"Unexpected marketplace list format — expected an array of marketplace entries\");\n return [];\n }\n\n return listResult.data;\n}\n\nexport async function claudePluginMarketplaceExists(\n name: string,\n options?: ClaudeConfigOptions,\n): Promise<boolean> {\n const marketplaces = await claudePluginMarketplaceList(options);\n return marketplaces.some((m) => m.name === name);\n}\n\nexport async function claudePluginMarketplaceAdd(\n source: string,\n options?: ClaudeConfigOptions,\n): Promise<void> {\n validateMarketplaceSource(source);\n\n const args = [\"plugin\", \"marketplace\", \"add\", source];\n const result = await runClaude(args, options, \"add marketplace\");\n if (result.exitCode === 0) return;\n\n const said = whyClaudeFailed(result);\n if (said.includes(\"already installed\")) return;\n throw new Error(`Failed to add marketplace: ${said}`);\n}\n\nexport async function claudePluginMarketplaceRemove(\n name: string,\n options?: ClaudeConfigOptions,\n): Promise<void> {\n validatePluginName(name);\n\n const args = [\"plugin\", \"marketplace\", \"remove\", name];\n const result = await runClaude(args, options, \"remove marketplace\");\n if (result.exitCode === 0) return;\n\n const said = whyClaudeFailed(result);\n if (namesNothingThere(said)) return;\n throw new Error(`Failed to remove marketplace: ${said}`);\n}\n\nexport async function claudePluginMarketplaceUpdate(\n name: string,\n options?: ClaudeConfigOptions,\n): Promise<void> {\n validatePluginName(name);\n\n const args = [\"plugin\", \"marketplace\", \"update\", name];\n const result = await runClaude(args, options, \"update marketplace\");\n if (result.exitCode === 0) return;\n\n throw new Error(`Failed to update marketplace: ${whyClaudeFailed(result)}`);\n}\n\n/** Throws only when `claude` cannot spawn; a non-zero exit is returned for the caller to read. */\nasync function runClaude(\n args: string[],\n options: ClaudeConfigOptions | undefined,\n attempt: string,\n): Promise<ExecResult> {\n try {\n return await execCommand(\"claude\", args, configDirEnv(options));\n } catch (err) {\n throw new Error(`Failed to ${attempt}: ${getErrorMessage(err)}`, { cause: err });\n }\n}\n\nfunction whyClaudeFailed(result: ExecResult): string {\n return (result.stderr || result.stdout || \"Unknown error\").trim();\n}\n\nexport async function claudePluginUninstall(\n pluginName: string,\n scope: ClaudePluginScope,\n projectDir: string,\n options?: ClaudeConfigOptions,\n): Promise<PluginRemovalOutcome> {\n validatePluginName(pluginName);\n\n const cwd = resolvePluginCwd(scope, projectDir);\n const args = [\"plugin\", \"uninstall\", pluginName, \"--scope\", scope];\n const result = await execCommand(\"claude\", args, { cwd, ...configDirEnv(options) });\n\n if (result.exitCode === 0) return \"removed\";\n\n const said = whyClaudeFailed(result);\n if (namesNothingThere(said)) return \"absent\";\n throw new Error(`Plugin uninstall failed: ${said}`);\n}\n\nfunction namesNothingThere(message: string): boolean {\n return NOT_INSTALLED_MESSAGES.some((phrase) => message.includes(phrase));\n}\n\nfunction claudePluginsRoot(\n projectDir: string,\n options: ClaudeConfigOptions | undefined,\n): string | null {\n if (options?.configDir !== undefined) return path.join(options.configDir, PLUGINS_SUBDIR);\n return pluginsDir(CLAUDE, \"global\", projectDir);\n}\n\n/**\n * Read from files, since Claude has no `plugin list --json`. A key recorded more than once\n * answers with this project's own record, else the user-scoped one.\n */\nasync function claudeListPlugins(\n projectDir: string,\n options?: ClaudeConfigOptions,\n): Promise<HostPlugin[]> {\n const pluginsRoot = claudePluginsRoot(projectDir, options);\n if (pluginsRoot === null) return [];\n if (!(await fileExists(getInstalledPluginsRegistryPath(pluginsRoot)))) return [];\n\n const [installs, enabled] = await Promise.all([\n listPluginInstallsForProject(pluginsRoot, projectDir),\n getEnabledPluginKeys(projectDir),\n ]);\n const enabledKeys = new Set(enabled);\n\n return installs.map(({ pluginKey, installPath }) => ({\n pluginKey,\n installPath,\n enabled: enabledKeys.has(pluginKey),\n }));\n}\n\n/** A factory so no caller shares another's `offeredPlacements` array by identity. */\nexport function claudeHost(): PluginHost {\n return {\n provider: CLAUDE,\n offeredPlacements: claudeOfferedPlacements(),\n installsProjectScopedPlugins: true,\n isAvailable: isClaudeCLIAvailable,\n marketplaceExists: claudePluginMarketplaceExists,\n addMarketplace: claudePluginMarketplaceAdd,\n refreshMarketplace: claudePluginMarketplaceUpdate,\n installPlugin: (pluginRef, scope, projectDir, options) =>\n claudePluginInstall(pluginRef, toClaudePluginScope(scope), projectDir, options),\n uninstallPlugin: (pluginRef, scope, projectDir, options) =>\n claudePluginUninstall(pluginRef, toClaudePluginScope(scope), projectDir, options),\n listPlugins: claudeListPlugins,\n };\n}\n","import { spawn } from \"child_process\";\nimport path from \"path\";\n\nconst MAX_PLUGIN_PATH_LENGTH = 1024;\nconst MAX_PLUGIN_NAME_LENGTH = 256;\nconst MAX_MARKETPLACE_SOURCE_LENGTH = 1024;\n\nconst SAFE_NAME_PATTERN = /^[a-zA-Z0-9._@/-]+$/;\n\nconst SAFE_PLUGIN_PATH_PATTERN = /^[a-zA-Z0-9._@/:~-]+$/;\n\nconst OPENS_A_RELATIVE_PATH = /^\\.\\.?[/\\\\]/;\n\n// Mirrors `isLocalSource` in lib/configuration/config.ts without its traversal throw.\nfunction namesADirectoryOnThisMachine(source: string): boolean {\n return path.isAbsolute(source) || OPENS_A_RELATIVE_PATH.test(source);\n}\n\n// eslint-disable-next-line no-control-regex -- matching control characters is this pattern's job\nconst CONTROL_CHAR_PATTERN = /[\\x00-\\x08\\x0E-\\x1F\\x7F]/u;\n\nexport function validatePluginPath(pluginPath: string): void {\n if (!pluginPath || pluginPath.trim().length === 0) {\n throw new Error(\"Plugin path must not be empty.\");\n }\n\n if (pluginPath.length > MAX_PLUGIN_PATH_LENGTH) {\n throw new Error(\n `Plugin path is too long (${pluginPath.length} characters, max ${MAX_PLUGIN_PATH_LENGTH}).`,\n );\n }\n\n if (CONTROL_CHAR_PATTERN.test(pluginPath)) {\n throw new Error(\"Plugin path contains invalid control characters.\");\n }\n\n if (!SAFE_PLUGIN_PATH_PATTERN.test(pluginPath)) {\n throw new Error(\n `Plugin path contains invalid characters: \"${pluginPath}\"\\n` +\n \"Plugin paths may only contain alphanumeric characters, dashes, underscores, dots, slashes, @, and colons.\",\n );\n }\n}\n\n/**\n * A directory source skips the name pattern: the filesystem may name it with spaces, and the\n * argv-array spawn has no shell to re-read it.\n */\nexport function validateMarketplaceSource(source: string): void {\n if (!source || source.trim().length === 0) {\n throw new Error(\"Marketplace must not be empty.\");\n }\n\n if (source.length > MAX_MARKETPLACE_SOURCE_LENGTH) {\n throw new Error(\n `Marketplace is too long (${source.length} characters, max ${MAX_MARKETPLACE_SOURCE_LENGTH}).`,\n );\n }\n\n if (CONTROL_CHAR_PATTERN.test(source)) {\n throw new Error(\"Marketplace contains invalid control characters.\");\n }\n\n if (namesADirectoryOnThisMachine(source)) return;\n\n if (!SAFE_PLUGIN_PATH_PATTERN.test(source)) {\n throw new Error(\n `Marketplace contains invalid characters: \"${source}\"\\n` +\n \"Marketplaces may only contain alphanumeric characters, dashes, underscores, dots, slashes, @, and colons.\",\n );\n }\n}\n\nexport function validatePluginName(pluginName: string): void {\n if (!pluginName || pluginName.trim().length === 0) {\n throw new Error(\"Plugin name must not be empty.\");\n }\n\n if (pluginName.length > MAX_PLUGIN_NAME_LENGTH) {\n throw new Error(\n `Plugin name is too long (${pluginName.length} characters, max ${MAX_PLUGIN_NAME_LENGTH}).`,\n );\n }\n\n if (CONTROL_CHAR_PATTERN.test(pluginName)) {\n throw new Error(\"Plugin name contains invalid control characters.\");\n }\n\n if (!SAFE_NAME_PATTERN.test(pluginName)) {\n throw new Error(\n `Plugin name contains invalid characters: \"${pluginName}\"\\n` +\n \"Names may only contain alphanumeric characters, dashes, underscores, dots, @, and slashes.\",\n );\n }\n}\n\nexport type ExecResult = {\n stdout: string;\n stderr: string;\n exitCode: number;\n};\n\n/** The only place in the package that forwards the whole environment to a child. */\nexport async function execCommand(\n command: string,\n args: string[],\n options?: { cwd?: string; env?: NodeJS.ProcessEnv },\n): Promise<ExecResult> {\n return new Promise((resolve, reject) => {\n const proc = spawn(command, args, {\n cwd: options?.cwd,\n env: { ...process.env, ...options?.env },\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n\n let stdout = \"\";\n let stderr = \"\";\n\n proc.stdout.on(\"data\", (data: Buffer) => {\n stdout += data.toString();\n });\n\n proc.stderr.on(\"data\", (data: Buffer) => {\n stderr += data.toString();\n });\n\n proc.on(\"close\", (code) => {\n resolve({\n stdout,\n stderr,\n exitCode: code ?? 1,\n });\n });\n\n proc.on(\"error\", (err) => {\n reject(err);\n });\n });\n}\n","import path from \"path\";\nimport { z } from \"zod\";\nimport { fileExists, readFileSafe } from \"../../utils/fs\";\nimport { verbose } from \"../../utils/logger\";\nimport { getErrorMessage } from \"../../utils/errors\";\nimport { typedEntries } from \"../../utils/typed-object\";\nimport { CLAUDE_DIR, MAX_CONFIG_FILE_SIZE, STANDARD_FILES } from \"../../consts\";\nimport { formatZodErrors } from \"../schema-validator\";\nimport { INSTALLED_PLUGINS_FILE } from \"../installation/install-layout\";\n\n/** `plugin-name@marketplace`. */\ntype PluginKey = string;\n\nexport type ResolvedPlugin = {\n pluginKey: PluginKey;\n installPath: string;\n};\n\nconst pluginSettingsSchema = z\n .object({\n // Absent when no plugin is enabled.\n enabledPlugins: z.record(z.string(), z.unknown()).exactOptional(),\n })\n .passthrough();\n\nconst installationFields = {\n installPath: z.string(),\n version: z.string(),\n installedAt: z.string(),\n};\n\n/** Discriminated so a project-scoped record without `projectPath` is rejected, not skipped. */\nconst pluginInstallationSchema = z.discriminatedUnion(\"scope\", [\n z.object({ scope: z.literal(\"project\"), projectPath: z.string(), ...installationFields }),\n z.object({ scope: z.literal(\"user\"), ...installationFields }),\n z.object({ scope: z.literal(\"local\"), ...installationFields }),\n]);\n\nconst installedPluginsSchema = z\n .object({\n version: z.number(),\n plugins: z.record(z.string(), z.array(pluginInstallationSchema)),\n })\n .passthrough();\n\nexport function getInstalledPluginsRegistryPath(pluginsDir: string): string {\n return path.join(pluginsDir, INSTALLED_PLUGINS_FILE);\n}\n\n/** Throws on an unreadable or invalid registry rather than answering empty. */\nasync function readRegisteredInstallations(\n pluginsDir: string,\n): Promise<Record<PluginKey, RegisteredInstallation[]>> {\n const registryPath = getInstalledPluginsRegistryPath(pluginsDir);\n const content = await readFileSafe(registryPath, MAX_CONFIG_FILE_SIZE);\n const raw: unknown = JSON.parse(content);\n const result = installedPluginsSchema.safeParse(raw);\n\n if (!result.success) {\n throw new Error(\n `Invalid ${INSTALLED_PLUGINS_FILE}: ${formatZodErrors(result.error).join(\"; \")}`,\n );\n }\n\n return result.data.plugins;\n}\n\n/** Every recorded install across all scopes, unlike {@link listPluginInstallsForProject}. */\nexport async function listRegisteredPluginInstalls(pluginsDir: string): Promise<ResolvedPlugin[]> {\n const installations = await readRegisteredInstallations(pluginsDir);\n\n return typedEntries(installations).flatMap(([pluginKey, forKey]) => {\n const uniquePaths = [...new Set(forKey.map((i) => i.installPath))];\n return uniquePaths.map((installPath) => ({ pluginKey, installPath }));\n });\n}\n\n/** One install per plugin as seen from `projectDir`; another project's record is never returned. */\nexport async function listPluginInstallsForProject(\n pluginsDir: string,\n projectDir: string,\n): Promise<ResolvedPlugin[]> {\n const installations = await readRegisteredInstallations(pluginsDir);\n\n return typedEntries(installations).flatMap(([pluginKey, forKey]) => {\n const picked = pickInstallation(forKey, projectDir);\n if (!picked) {\n verbose(`No installation of '${pluginKey}' belongs to '${projectDir}'`);\n return [];\n }\n return [{ pluginKey, installPath: picked.installPath }];\n });\n}\n\nexport async function getEnabledPluginKeys(projectDir: string): Promise<PluginKey[]> {\n const settingsPath = path.join(projectDir, CLAUDE_DIR, STANDARD_FILES.SETTINGS_JSON);\n\n if (!(await fileExists(settingsPath))) {\n verbose(`No settings.json found at '${settingsPath}'`);\n return [];\n }\n\n try {\n const content = await readFileSafe(settingsPath, MAX_CONFIG_FILE_SIZE);\n const raw: unknown = JSON.parse(content);\n const result = pluginSettingsSchema.safeParse(raw);\n\n if (!result.success) {\n verbose(`Invalid settings.json structure: ${getErrorMessage(result.error)}`);\n return [];\n }\n\n const settings = result.data;\n\n if (!settings.enabledPlugins) {\n verbose(`No enabledPlugins found in '${settingsPath}'`);\n return [];\n }\n\n const enabledKeys = typedEntries(settings.enabledPlugins)\n .filter(([, enabled]) => enabled === true)\n .map(([key]) => key);\n\n verbose(`Found ${enabledKeys.length} enabled plugins in settings.json`);\n return enabledKeys;\n } catch (error) {\n verbose(`Failed to read settings.json: ${getErrorMessage(error)}`);\n return [];\n }\n}\n\ntype RegisteredInstallation = z.infer<typeof pluginInstallationSchema>;\n\n/** This project's own project-scoped installation wins; otherwise the user-scoped one. */\nfunction pickInstallation(\n installations: RegisteredInstallation[],\n projectDir: string,\n): RegisteredInstallation | undefined {\n return (\n installations.find((i) => i.scope === \"project\" && i.projectPath === projectDir) ??\n installations.find((i) => i.scope === \"user\")\n );\n}\n","/**\n * Codex's plugin machinery, behind {@link PluginHost}. `codex plugin` has no scope flag and every\n * write lands in the global `config.toml`, so project-scoped plugins are not offered.\n */\n\nimport os from \"os\";\nimport path from \"path\";\nimport { z } from \"zod\";\n\nimport { PLUGINS_SUBDIR } from \"../../consts.js\";\nimport type { SkillScope } from \"../../types/config.js\";\nimport { getErrorMessage } from \"../../utils/errors.js\";\nimport {\n execCommand,\n validateMarketplaceSource,\n validatePluginName,\n validatePluginPath,\n type ExecResult,\n} from \"../../utils/exec.js\";\nimport { verbose, warnOnce } from \"../../utils/logger.js\";\nimport { ensureDir } from \"../../utils/fs.js\";\nimport { pluginsDir, userConfigRoot } from \"../installation/install-layout.js\";\nimport type {\n HostCallOptions,\n HostPlugin,\n InstallPlacement,\n PluginHost,\n PluginRemovalOutcome,\n} from \"./plugin-host.js\";\n\nconst CODEX: PluginHost[\"provider\"] = \"codex\";\n\n/**\n * `plugin list --json` prints no install path, so it is composed as\n * `<CODEX_HOME>/plugins/cache/<marketplace>/<name>/<version>`.\n */\nconst PLUGIN_CACHE_SUBDIR = \"cache\";\n\n/** Printed on stderr by every run whose `CODEX_HOME` is under the temp dir, even on exit 0. */\nconst STANDING_WARNING = /could not create PATH aliases/;\n\n/**\n * Writes run from home: `plugin add` inside a project still writes the global config. A function\n * so HOME is read per call, not frozen at import.\n */\nfunction codexPluginCwd(): string {\n return os.homedir();\n}\n\nfunction codexOfferedPlacements(): InstallPlacement[] {\n return [\n { mode: \"plugin\", scope: \"global\" },\n { mode: \"eject\", scope: \"global\" },\n { mode: \"eject\", scope: \"project\" },\n ];\n}\n\nexport type CodexConfigOptions = HostCallOptions;\n\nfunction codexHomeEnv(options: CodexConfigOptions | undefined): { env?: NodeJS.ProcessEnv } {\n if (options?.configDir === undefined) return {};\n return { env: { CODEX_HOME: options.configDir } };\n}\n\nfunction codexStateRoot(options: CodexConfigOptions | undefined, askedFrom: string): string {\n return options?.configDir ?? userConfigRoot(CODEX, \"global\", askedFrom);\n}\n\n/**\n * Creates `CODEX_HOME` first: when it is missing, `--version` succeeds but every plugin verb\n * exits 1, so a never-run Codex would look available and fail every install.\n */\nasync function runCodex(\n args: string[],\n options: CodexConfigOptions | undefined,\n askedFrom: string,\n): Promise<ExecResult> {\n await makeTheStateRoot(codexStateRoot(options, askedFrom));\n return execCommand(\"codex\", args, { cwd: askedFrom, ...codexHomeEnv(options) });\n}\n\n/** Degrades on failure: Codex's own refusal names an unusable `CODEX_HOME` better than ours. */\nasync function makeTheStateRoot(root: string): Promise<void> {\n try {\n await ensureDir(root);\n } catch (error) {\n verbose(`Could not create the codex state directory at ${root}: ${getErrorMessage(error)}`);\n }\n}\n\nasync function runCodexOrThrow(\n args: string[],\n options: CodexConfigOptions | undefined,\n attempt: string,\n askedFrom: string,\n): Promise<ExecResult> {\n let result;\n try {\n result = await runCodex(args, options, askedFrom);\n } catch (error) {\n throw new Error(`Failed to ${attempt}: ${getErrorMessage(error)}`, { cause: error });\n }\n\n if (result.exitCode !== 0) throw new Error(`Failed to ${attempt}: ${whyItFailed(result)}`);\n return result;\n}\n\nfunction withoutTheStandingWarning(stream: string): string {\n return stream\n .split(\"\\n\")\n .filter((line) => !STANDING_WARNING.test(line))\n .join(\"\\n\")\n .trim();\n}\n\nfunction whyItFailed(result: ExecResult): string {\n const said = withoutTheStandingWarning(result.stderr) || withoutTheStandingWarning(result.stdout);\n return said || \"Unknown error\";\n}\n\n/**\n * Throws on unparseable output: a listing read as empty would make `marketplaceExists` false\n * forever and re-add the marketplace on every run.\n */\nasync function readJsonFromCodex<T>(\n schema: z.ZodType<T>,\n args: string[],\n options: CodexConfigOptions | undefined,\n attempt: string,\n askedFrom: string,\n): Promise<T> {\n const result = await runCodexOrThrow(args, options, attempt, askedFrom);\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(result.stdout);\n } catch (error) {\n throw new Error(`Failed to ${attempt}: codex answered no JSON at all`, { cause: error });\n }\n\n const validated = schema.safeParse(parsed);\n if (!validated.success) {\n throw new Error(`Failed to ${attempt}: codex answered a document this release cannot read`);\n }\n return validated.data;\n}\n\n/** An object wrapping the array, unlike Claude's bare array; there is no top-level `source`. */\nconst marketplaceRegistrySchema = z.object({\n marketplaces: z.array(\n z.object({\n name: z.string(),\n marketplaceSource: z.object({ sourceType: z.string(), source: z.string() }),\n }),\n ),\n});\n\ntype CodexMarketplace = z.infer<typeof marketplaceRegistrySchema>[\"marketplaces\"][number];\n\n/** `available` (what could be installed) comes back too and is deliberately not read. */\nconst pluginListingSchema = z.object({\n installed: z.array(\n z.object({\n pluginId: z.string(),\n name: z.string(),\n marketplaceName: z.string(),\n version: z.string(),\n enabled: z.boolean(),\n }),\n ),\n});\n\ntype CodexInstalledPlugin = z.infer<typeof pluginListingSchema>[\"installed\"][number];\n\nfunction codexPluginsRoot(\n projectDir: string,\n options: CodexConfigOptions | undefined,\n): string | null {\n if (options?.configDir !== undefined) return path.join(options.configDir, PLUGINS_SUBDIR);\n return pluginsDir(CODEX, \"global\", projectDir);\n}\n\n/** The state tree is pinned because even `codex --version` writes under `$CODEX_HOME/tmp/arg0/`. */\nasync function isCodexCLIAvailable(options?: CodexConfigOptions): Promise<boolean> {\n try {\n const result = await runCodex([\"--version\"], options, codexPluginCwd());\n return result.exitCode === 0;\n } catch {\n return false;\n }\n}\n\n/**\n * Both listing verbs exit 1 with this when any recorded marketplace is unreadable, while writes\n * keep working. Only the members that ask a question degrade on it.\n */\nconst UNREADABLE_MARKETPLACE = /failed to load (?:configured )?marketplace/i;\n\nfunction namesAnUnreadableMarketplace(error: unknown): boolean {\n return UNREADABLE_MARKETPLACE.test(getErrorMessage(error));\n}\n\nasync function codexMarketplaces(\n options: CodexConfigOptions | undefined,\n): Promise<CodexMarketplace[]> {\n const registry = await readJsonFromCodex(\n marketplaceRegistrySchema,\n [\"plugin\", \"marketplace\", \"list\", \"--json\"],\n options,\n \"read the marketplaces codex knows\",\n codexPluginCwd(),\n );\n return registry.marketplaces;\n}\n\n/** By name, never by count: a Codex home may hold the user's own marketplaces beside ours. */\nasync function codexMarketplaceExists(\n name: string,\n options?: CodexConfigOptions,\n): Promise<boolean> {\n return (await codexRegisteredMarketplace(name, options)) !== null;\n}\n\n/** `null` also for an unreadable registry; the caller then adds, which still works there. */\nasync function codexRegisteredMarketplace(\n name: string,\n options?: CodexConfigOptions,\n): Promise<CodexMarketplace | null> {\n let registered;\n try {\n registered = await codexMarketplaces(options);\n } catch (error) {\n if (!namesAnUnreadableMarketplace(error)) throw error;\n warnOnce(sayWhatCodexRefused(\"list the marketplaces it knows\", getErrorMessage(error)));\n return null;\n }\n\n return registered.find((marketplace) => marketplace.name === name) ?? null;\n}\n\nfunction sayWhatCodexRefused(attempt: string, said: string): string {\n return `Codex could not ${attempt}, so this run is treating it as having none. It said: ${said}`;\n}\n\nexport async function codexMarketplaceAdd(\n source: string,\n options?: CodexConfigOptions,\n): Promise<void> {\n validateMarketplaceSource(source);\n await runCodexOrThrow(\n [\"plugin\", \"marketplace\", \"add\", source, \"--json\"],\n options,\n \"add marketplace\",\n codexPluginCwd(),\n );\n}\n\n/**\n * `marketplace upgrade` is git-only (exits 1 on a local source), so a local marketplace is\n * refreshed by re-adding each of its installed plugins.\n */\nasync function refreshCodexMarketplace(name: string, options?: CodexConfigOptions): Promise<void> {\n validatePluginName(name);\n\n const registered = (await codexMarketplaces(options)).find(\n (marketplace) => marketplace.name === name,\n );\n if (registered === undefined) {\n throw new Error(`Failed to refresh marketplace: codex has no marketplace named '${name}'`);\n }\n\n if (isGitSourced(registered)) return upgradeGitMarketplace(name, options);\n return reinstallEachPluginOf(name, options);\n}\n\nfunction isGitSourced(marketplace: CodexMarketplace): boolean {\n return marketplace.marketplaceSource.sourceType === \"git\";\n}\n\nasync function upgradeGitMarketplace(\n name: string,\n options: CodexConfigOptions | undefined,\n): Promise<void> {\n await runCodexOrThrow(\n [\"plugin\", \"marketplace\", \"upgrade\", name, \"--json\"],\n options,\n \"refresh marketplace\",\n codexPluginCwd(),\n );\n}\n\nasync function reinstallEachPluginOf(\n name: string,\n options: CodexConfigOptions | undefined,\n): Promise<void> {\n const installed = await codexPluginListing(options, codexPluginCwd());\n\n // Sequential: every add writes the same `config.toml` and cache.\n for (const plugin of installed.filter((entry) => entry.marketplaceName === name)) {\n await installCodexPlugin(plugin.pluginId, options);\n }\n}\n\n/** Scope and project are unused: Codex takes no scope, and `hostFor` refuses plugin + project. */\nasync function codexInstallPlugin(\n pluginRef: string,\n _scope: SkillScope,\n _projectDir: string,\n options?: CodexConfigOptions,\n): Promise<void> {\n await installCodexPlugin(pluginRef, options);\n}\n\nasync function installCodexPlugin(\n pluginRef: string,\n options: CodexConfigOptions | undefined,\n): Promise<void> {\n validatePluginPath(pluginRef);\n await runCodexOrThrow(\n [\"plugin\", \"add\", pluginRef, \"--json\"],\n options,\n `install ${pluginRef}`,\n codexPluginCwd(),\n );\n}\n\n/**\n * `plugin remove` exits 0 whatever happened, so the outcome comes from listings taken before and\n * after. Removal is machine-wide whichever scope asks.\n */\nasync function codexUninstallPlugin(\n pluginRef: string,\n _scope: SkillScope,\n _projectDir: string,\n options?: CodexConfigOptions,\n): Promise<PluginRemovalOutcome> {\n validatePluginName(pluginRef);\n\n const wasInstalled = await isListed(pluginRef, options);\n await runCodexOrThrow(\n [\"plugin\", \"remove\", pluginRef, \"--json\"],\n options,\n `remove ${pluginRef}`,\n codexPluginCwd(),\n );\n\n if (await isListed(pluginRef, options)) {\n throw new Error(\n `Failed to remove ${pluginRef}: codex still lists it after removing it. ` +\n `Nothing else has been changed.`,\n );\n }\n\n return wasInstalled ? \"removed\" : \"absent\";\n}\n\nasync function isListed(\n pluginRef: string,\n options: CodexConfigOptions | undefined,\n): Promise<boolean> {\n const installed = await codexPluginListing(options, codexPluginCwd());\n return installed.some((plugin) => plugin.pluginId === pluginRef);\n}\n\nasync function codexPluginListing(\n options: CodexConfigOptions | undefined,\n askedFrom: string,\n): Promise<CodexInstalledPlugin[]> {\n const listing = await readJsonFromCodex(\n pluginListingSchema,\n [\"plugin\", \"list\", \"--json\"],\n options,\n \"read the plugins codex has installed\",\n askedFrom,\n );\n return listing.installed;\n}\n\n/**\n * Asked from the project root: in a project the global config trusts, the project's own\n * `config.toml` decides `enabled`. An unreadable marketplace degrades to an empty listing.\n */\nasync function codexListPlugins(\n projectDir: string,\n options?: CodexConfigOptions,\n): Promise<HostPlugin[]> {\n const listing = await codexPluginsOrUnreadable(projectDir, options);\n if (listing.kind === \"listed\") return [...listing.plugins];\n\n warnOnce(sayWhatCodexRefused(\"list the plugins it has installed\", listing.reason));\n return [];\n}\n\ntype CodexPluginListing =\n | { readonly kind: \"listed\"; readonly plugins: readonly HostPlugin[] }\n | { readonly kind: \"unreadable\"; readonly reason: string };\n\nasync function codexPluginsOrUnreadable(\n projectDir: string,\n options?: CodexConfigOptions,\n): Promise<CodexPluginListing> {\n const pluginsRoot = codexPluginsRoot(projectDir, options);\n if (pluginsRoot === null) return { kind: \"listed\", plugins: [] };\n const cacheRoot = path.join(pluginsRoot, PLUGIN_CACHE_SUBDIR);\n\n let installed;\n try {\n installed = await codexPluginListing(options, projectDir);\n } catch (error) {\n if (!namesAnUnreadableMarketplace(error)) throw error;\n return { kind: \"unreadable\", reason: getErrorMessage(error) };\n }\n\n return {\n kind: \"listed\",\n plugins: installed.map((plugin) => ({\n pluginKey: plugin.pluginId,\n installPath: path.join(cacheRoot, plugin.marketplaceName, plugin.name, plugin.version),\n enabled: plugin.enabled,\n })),\n };\n}\n\n/** A factory so no caller shares another's `offeredPlacements` array by identity. */\nexport function codexHost(): PluginHost {\n return {\n provider: CODEX,\n offeredPlacements: codexOfferedPlacements(),\n installsProjectScopedPlugins: false,\n isAvailable: isCodexCLIAvailable,\n marketplaceExists: codexMarketplaceExists,\n addMarketplace: codexMarketplaceAdd,\n refreshMarketplace: refreshCodexMarketplace,\n installPlugin: codexInstallPlugin,\n uninstallPlugin: codexUninstallPlugin,\n listPlugins: codexListPlugins,\n };\n}\n","/**\n * Makes {@link PluginHost.offeredPlacements} binding. Enforced once at `hostFor`'s door rather than\n * in each host, so a new host is bound without remembering to be.\n */\n\nimport { EJECT_SOURCE } from \"../../consts.js\";\nimport type { SkillConfig } from \"../../types/config.js\";\nimport type { InstallPlacement, PluginHost } from \"./plugin-host.js\";\n\nfunction placementName(placement: InstallPlacement): string {\n return `${placement.mode}+${placement.scope}`;\n}\n\nfunction offersPlacement(host: PluginHost, placement: InstallPlacement): boolean {\n return host.offeredPlacements.some(\n (offered) => offered.mode === placement.mode && offered.scope === placement.scope,\n );\n}\n\n/** Exported for the install pre-flight, which must refuse before anything is written. */\nexport function refuseUnofferedPlacement(\n host: PluginHost,\n placement: InstallPlacement,\n subject: string,\n): void {\n if (offersPlacement(host, placement)) return;\n\n throw new Error(\n `Refusing to install ${subject} as ${placementName(placement)}: the ${host.provider} host ` +\n `offers ${host.offeredPlacements.map(placementName).join(\", \")}. Nothing has been changed.`,\n );\n}\n\nfunction placementAskedFor(skill: SkillConfig): InstallPlacement {\n return { mode: skill.origin === EJECT_SOURCE ? \"eject\" : \"plugin\", scope: skill.scope };\n}\n\n/**\n * For the read path too: a config copied into another provider's folder never met that host's\n * pre-flight. Excluded rows place nothing, so they are skipped.\n */\nexport function refuseUnofferedPlacements(skills: readonly SkillConfig[], host: PluginHost): void {\n for (const skill of skills) {\n if (skill.excluded === true) continue;\n refuseUnofferedPlacement(host, placementAskedFor(skill), skill.id);\n }\n}\n\n/** `installPlugin` only: uninstalling at an unoffered scope is an ordinary no-op sweep. */\nexport function bindsItsOfferedPlacements(host: PluginHost): PluginHost {\n return {\n ...host,\n // `async` so a refusal is a rejection, which `installPluginSkills` collects per skill; a\n // synchronous throw would abort the whole install.\n installPlugin: async (pluginRef, scope, projectDir, options) => {\n refuseUnofferedPlacement(host, { mode: \"plugin\", scope }, pluginRef);\n return host.installPlugin(pluginRef, scope, projectDir, options);\n },\n };\n}\n","/** The door to a host's plugin machinery; every host leaves with its placements binding. */\n\nimport type { Provider } from \"../../consts.js\";\nimport { providerInUse } from \"../installation/install-layout.js\";\nimport { claudeHost } from \"./claude-host.js\";\nimport { codexHost } from \"./codex-host.js\";\nimport { bindsItsOfferedPlacements } from \"./offered-placements.js\";\nimport type { PluginHost } from \"./plugin-host.js\";\n\n/** For a run TOLD its provider, e.g. `init --from --provider` before the folder exists. */\nexport function hostFor(provider: Provider): PluginHost {\n switch (provider) {\n case \"claude\":\n return bindsItsOfferedPlacements(claudeHost());\n case \"codex\":\n return bindsItsOfferedPlacements(codexHost());\n default: {\n const _exhaustive: never = provider;\n return _exhaustive;\n }\n }\n}\n\n/** For a caller holding only a directory: the folder is the only record of a provider. */\nexport function hostAt(root: string): PluginHost {\n return hostFor(providerInUse(root));\n}\n","import type { SkillId } from \"../../types\";\nimport type { SkillConfig, SkillScope } from \"../../types/config\";\nimport type { SourceLoadResult } from \"../loading\";\n// Type-only: the operations layer imports back into this module.\nimport type { PluginInstallResult } from \"../operations/skills/install-plugin-skills\";\nimport { deleteLocalSkill, copySkillsToLocalFlattened } from \"../skills\";\nimport { hostAt } from \"../hosts/host-for\";\nimport type { PluginHost } from \"../hosts/plugin-host\";\nimport { buildMarketplacePluginRef } from \"../plugins/plugin-ref\";\nimport { resolveInstallPaths } from \"./install-base-dir\";\nimport { verbose } from \"../../utils/logger\";\nimport { getErrorMessage } from \"../../utils/errors\";\nimport { plural } from \"../../utils/string\";\nimport { CLI_INVOKE_COMMAND, EJECT_SOURCE } from \"../../consts\";\n\nexport type SkillMigration = {\n id: SkillId;\n oldSource: string;\n newSource: string;\n oldScope: SkillScope;\n newScope: SkillScope;\n};\n\nexport type MigrationPlan = {\n toEject: SkillMigration[];\n toPlugin: SkillMigration[];\n scopeChanges: SkillMigration[];\n};\n\n/** A non-empty `failed` means the caller must hard-error before writing any config. */\nexport type EjectCopyResult = {\n copied: SkillId[];\n failed: Array<{ id: SkillId; error: string }>;\n};\n\nexport type MigrationResult = {\n ejectCopies: EjectCopyResult;\n /** A non-empty `failed` means the caller must hard-error before writing any config. */\n pluginInstalls: PluginInstallResult;\n warnings: string[];\n};\n\nexport function ejectCopyFailureError(failedCount: number): string {\n return `Failed to copy ${failedCount} skill(s) for eject. Eject intent could not be honored. Check that the destination skills directory is writable, then apply the same id again with '${CLI_INVOKE_COMMAND} edit --from <id>' — or switch the affected skills back to plugin mode.`;\n}\n\n/** The global plugin keeps serving every other project, so nothing switches: a copy is added. */\nexport function copyingBesideGlobalPlugins(count: number): string {\n const kept = count === 1 ? \"the global plugin stays\" : \"the global plugins stay\";\n return `Copying ${plural(count, \"skill\")} into this project (${kept})`;\n}\n\n/** The global copy keeps serving every other project, so nothing switches: a plugin is added. */\nexport function installingBesideGlobalCopies(count: number): string {\n const installedAs = count === 1 ? \"a plugin\" : \"plugins\";\n const kept = count === 1 ? \"the global copy stays\" : \"the global copies stay\";\n return `Installing ${plural(count, \"skill\")} as ${installedAs} in this project (${kept})`;\n}\n\nexport function detectMigrations(\n oldSkills: SkillConfig[],\n newSkills: SkillConfig[],\n): MigrationPlan {\n const oldById = new Map(oldSkills.map((s) => [s.id, s]));\n const migrations = newSkills.flatMap((newSkill) => {\n const oldSkill = oldById.get(newSkill.id);\n return oldSkill ? [migrationBetween(oldSkill, newSkill)] : [];\n });\n\n return {\n toEject: migrations.filter(switchesToEject),\n toPlugin: migrations.filter(switchesToPlugin),\n scopeChanges: migrations.filter(movesScopeWithoutSwitchingMode),\n };\n}\n\nfunction migrationBetween(oldSkill: SkillConfig, newSkill: SkillConfig): SkillMigration {\n return {\n id: newSkill.id,\n oldSource: oldSkill.origin,\n newSource: newSkill.origin,\n oldScope: oldSkill.scope,\n newScope: newSkill.scope,\n };\n}\n\nfunction wasEjected(migration: SkillMigration): boolean {\n return migration.oldSource === EJECT_SOURCE;\n}\n\nfunction isEjected(migration: SkillMigration): boolean {\n return migration.newSource === EJECT_SOURCE;\n}\n\nfunction switchesToEject(migration: SkillMigration): boolean {\n return !wasEjected(migration) && isEjected(migration);\n}\n\nfunction switchesToPlugin(migration: SkillMigration): boolean {\n return wasEjected(migration) && !isEjected(migration);\n}\n\n/** A skill that switches mode is planned as `toEject`/`toPlugin`, never also as a scope change. */\nfunction movesScopeWithoutSwitchingMode(migration: SkillMigration): boolean {\n return (\n migration.oldScope !== migration.newScope && wasEjected(migration) === isEjected(migration)\n );\n}\n\nexport async function executeMigration(\n plan: MigrationPlan,\n projectDir: string,\n sourceResult: SourceLoadResult,\n): Promise<MigrationResult> {\n const host = hostAt(projectDir);\n\n const ejectCopies = await copyMigratedSkillsToLocal(plan.toEject, projectDir, sourceResult);\n // Only skills whose copy landed lose their plugin, so a failed copy leaves the skill installed.\n const warnings = await uninstallMigratedPlugins(\n migrationsWhoseCopyLanded(plan.toEject, ejectCopies),\n projectDir,\n sourceResult,\n host,\n );\n const pluginInstalls = await installMigratedPlugins(\n plan.toPlugin,\n projectDir,\n sourceResult,\n host,\n );\n\n return { ejectCopies, pluginInstalls, warnings };\n}\n\n/** Installs first and deletes a skill's ejected copy only once its plugin is registered. */\nasync function installMigratedPlugins(\n migrations: SkillMigration[],\n projectDir: string,\n sourceResult: SourceLoadResult,\n host: PluginHost,\n): Promise<PluginInstallResult> {\n const installs: PluginInstallResult = { installed: [], failed: [] };\n if (migrations.length === 0) return installs;\n\n if (!sourceResult.marketplace) {\n throw new Error(\n `Cannot install skills as plugins: marketplace could not be resolved from ` +\n `'${sourceResult.sourceConfig.source}'. Plugin install mode requires a marketplace — ` +\n `fix the marketplace or switch the affected skills to eject mode.`,\n );\n }\n\n for (const migration of migrations) {\n const pluginRef = buildMarketplacePluginRef(migration.id, sourceResult.marketplace);\n try {\n await host.installPlugin(pluginRef, migration.newScope, projectDir);\n } catch (error) {\n installs.failed.push({ id: migration.id, error: getErrorMessage(error) });\n continue;\n }\n installs.installed.push({ id: migration.id, ref: pluginRef });\n verbose(`Installed plugin for ${migration.id}`);\n await deleteEjectedWorkingCopy(migration, projectDir);\n }\n\n return installs;\n}\n\n/** Per skill and per scope; failures are collected so the user sees every one at once. */\nasync function copyMigratedSkillsToLocal(\n migrations: SkillMigration[],\n projectDir: string,\n sourceResult: SourceLoadResult,\n): Promise<EjectCopyResult> {\n const copies: EjectCopyResult = { copied: [], failed: [] };\n\n for (const migration of migrations) {\n const { skillsDir } = resolveInstallPaths(projectDir, migration.newScope);\n try {\n const copied = await copySkillsToLocalFlattened([migration.id], skillsDir, sourceResult);\n copies.copied.push(...copied.map((skill) => skill.skillId));\n } catch (error) {\n copies.failed.push({ id: migration.id, error: getErrorMessage(error) });\n }\n }\n\n return copies;\n}\n\nfunction migrationsWhoseCopyLanded(\n migrations: SkillMigration[],\n copies: EjectCopyResult,\n): SkillMigration[] {\n const landed = new Set(copies.copied);\n return migrations.filter((migration) => landed.has(migration.id));\n}\n\n/**\n * Global→project leaves the global install, plugin or copy, serving every other project. The one\n * test both directions read, so what a run keeps and what it says it keeps cannot disagree.\n */\nexport function keepsGlobalInstall(migration: SkillMigration): boolean {\n return migration.oldScope === \"global\" && migration.newScope === \"project\";\n}\n\n/** Diagnostic-only: the local copy is the install now, so failures become warnings. */\nasync function uninstallMigratedPlugins(\n migrations: SkillMigration[],\n projectDir: string,\n sourceResult: SourceLoadResult,\n host: PluginHost,\n): Promise<string[]> {\n const warnings: string[] = [];\n\n for (const migration of migrations) {\n if (keepsGlobalInstall(migration)) {\n verbose(`Keeping global plugin for ${migration.id} (migrated to project-eject)`);\n continue;\n }\n if (!sourceResult.marketplace) {\n warnings.push(`Could not uninstall plugin for ${migration.id}: no marketplace configured`);\n continue;\n }\n\n // Only the old scope, so a same-id plugin at the other scope survives.\n const pluginRef = buildMarketplacePluginRef(migration.id, sourceResult.marketplace);\n try {\n await host.uninstallPlugin(pluginRef, migration.oldScope, projectDir);\n } catch (error) {\n warnings.push(`Could not uninstall plugin for ${migration.id}: ${getErrorMessage(error)}`);\n continue;\n }\n verbose(`Uninstalled plugin for ${migration.id}`);\n }\n\n return warnings;\n}\n\nasync function deleteEjectedWorkingCopy(\n migration: SkillMigration,\n projectDir: string,\n): Promise<void> {\n if (keepsGlobalInstall(migration)) {\n verbose(`Keeping global local skill for ${migration.id} (migrated to project-plugin)`);\n return;\n }\n await deleteLocalSkill(projectDir, migration.id, migration.oldScope);\n}\n","import { isRecord } from \"../../utils/type-guards.js\";\nimport path from \"path\";\nimport { getErrorMessage } from \"../../utils/errors\";\nimport {\n fileExists,\n glob,\n readFile,\n readFileSafe,\n directoryExists,\n listDirectories,\n} from \"../../utils/fs\";\nimport type { ValidationResult } from \"../../types\";\nimport { validResult, invalidResult, mergeValidationResults } from \"../validation-result\";\nimport { extractFrontmatter } from \"../../utils/frontmatter\";\nimport { formatZodErrors } from \"../schema-validator\";\nimport {\n pluginManifestValidationSchema,\n skillFrontmatterValidationSchema,\n agentFrontmatterValidationSchema,\n} from \"../schemas\";\nimport {\n KEBAB_CASE_PATTERN,\n MAX_PLUGIN_FILE_SIZE,\n PLUGIN_MANIFEST_DIR,\n STANDARD_FILES,\n} from \"../../consts\";\nimport { getPluginManifestPath } from \"./plugin-finder\";\nimport { agentCodec } from \"../installation/install-layout\";\n\nconst SEMVER_REGEX =\n /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$/;\n\nfunction isKebabCase(str: string): boolean {\n return KEBAB_CASE_PATTERN.test(str);\n}\n\nfunction isValidSemver(str: string): boolean {\n return SEMVER_REGEX.test(str);\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value !== \"\";\n}\n\nasync function validatePluginStructure(pluginPath: string): Promise<ValidationResult> {\n const errors: string[] = [];\n const warnings: string[] = [];\n\n if (!(await directoryExists(pluginPath))) {\n return invalidResult(`Plugin directory does not exist: ${pluginPath}`);\n }\n\n const pluginDir = path.join(pluginPath, PLUGIN_MANIFEST_DIR);\n if (!(await directoryExists(pluginDir))) {\n errors.push(`Missing ${PLUGIN_MANIFEST_DIR}/ directory`);\n }\n\n const manifestPath = path.join(pluginDir, STANDARD_FILES.PLUGIN_JSON);\n if (!(await fileExists(manifestPath))) {\n errors.push(`Missing ${PLUGIN_MANIFEST_DIR}/${STANDARD_FILES.PLUGIN_JSON}`);\n }\n\n const readmePath = path.join(pluginPath, STANDARD_FILES.README_MD);\n if (!(await fileExists(readmePath))) {\n warnings.push(\"Missing README.md (recommended for documentation)\");\n }\n\n return {\n valid: errors.length === 0,\n errors,\n warnings,\n };\n}\n\nexport async function validatePluginManifest(manifestPath: string): Promise<ValidationResult> {\n const errors: string[] = [];\n const warnings: string[] = [];\n\n let manifest: Record<string, unknown>;\n try {\n const content = await readFileSafe(manifestPath, MAX_PLUGIN_FILE_SIZE);\n const parsed: unknown = JSON.parse(content);\n if (!isRecord(parsed)) {\n return invalidResult(`${STANDARD_FILES.PLUGIN_JSON} must contain a JSON object`);\n }\n manifest = parsed;\n } catch (err) {\n return invalidResult(`Invalid JSON in ${STANDARD_FILES.PLUGIN_JSON}: ${getErrorMessage(err)}`);\n }\n\n const result = pluginManifestValidationSchema.safeParse(manifest);\n\n if (!result.success) {\n errors.push(...formatZodErrors(result.error));\n }\n\n if (isNonEmptyString(manifest.name)) {\n if (!isKebabCase(manifest.name)) {\n errors.push(`name must be kebab-case: \"${manifest.name}\"`);\n }\n }\n\n if (isNonEmptyString(manifest.version)) {\n if (!isValidSemver(manifest.version)) {\n errors.push(\n `version \"${manifest.version}\" is not valid semver (expected: major.minor.patch)`,\n );\n }\n }\n\n if (!manifest.description) {\n warnings.push(\"Missing description field (recommended for discoverability)\");\n }\n\n const pluginDir = path.dirname(path.dirname(manifestPath));\n\n if (isNonEmptyString(manifest.skills)) {\n const skillsPath = path.join(pluginDir, manifest.skills);\n if (!(await directoryExists(skillsPath))) {\n errors.push(`Skills path does not exist: ${manifest.skills}`);\n }\n }\n\n if (isNonEmptyString(manifest.agents)) {\n const agentsPath = path.join(pluginDir, manifest.agents);\n if (!(await directoryExists(agentsPath))) {\n errors.push(`Agents path does not exist: ${manifest.agents}`);\n }\n }\n\n return {\n valid: errors.length === 0,\n errors,\n warnings,\n };\n}\n\nexport async function validateSkillFrontmatter(skillPath: string): Promise<ValidationResult> {\n const errors: string[] = [];\n const warnings: string[] = [];\n\n if (!(await fileExists(skillPath))) {\n return invalidResult(`Skill file not found: ${skillPath}`);\n }\n\n const content = await readFile(skillPath);\n const frontmatter = extractFrontmatter(content);\n\n if (frontmatter === null) {\n return invalidResult(\"Missing or invalid YAML frontmatter\");\n }\n\n const result = skillFrontmatterValidationSchema.safeParse(frontmatter);\n\n if (!result.success) {\n errors.push(...formatZodErrors(result.error));\n }\n\n return {\n valid: errors.length === 0,\n errors,\n warnings,\n };\n}\n\nexport async function validateAgentFrontmatter(agentPath: string): Promise<ValidationResult> {\n const errors: string[] = [];\n const warnings: string[] = [];\n\n if (!(await fileExists(agentPath))) {\n return invalidResult(`Agent file not found: ${agentPath}`);\n }\n\n const content = await readFile(agentPath);\n const frontmatter = extractFrontmatter(content);\n\n if (frontmatter === null) {\n return invalidResult(\"Missing or invalid YAML frontmatter\");\n }\n\n const result = agentFrontmatterValidationSchema.safeParse(frontmatter);\n\n if (!result.success) {\n errors.push(...formatZodErrors(result.error));\n }\n\n // Boundary cast: parsed YAML frontmatter, narrowed for field access.\n const fm = frontmatter as Record<string, unknown>;\n\n if (isNonEmptyString(fm.name)) {\n if (!isKebabCase(fm.name)) {\n errors.push(`name must be kebab-case: \"${fm.name}\"`);\n }\n }\n\n return {\n valid: errors.length === 0,\n errors,\n warnings,\n };\n}\n\nfunction prefixResult(result: ValidationResult, prefix: string): ValidationResult {\n return {\n valid: result.valid,\n errors: result.valid ? [] : result.errors.map((e) => `${prefix}: ${e}`),\n warnings: result.warnings.map((w) => `${prefix}: ${w}`),\n };\n}\n\n/** Each file's result is named by its path in the plugin. */\nasync function validateEachFile(\n pluginPath: string,\n scannedDir: string,\n files: string[],\n validate: (filePath: string) => Promise<ValidationResult>,\n): Promise<ValidationResult> {\n const results = await Promise.all(\n files.map(async (file) => {\n const filePath = path.join(scannedDir, file);\n return prefixResult(await validate(filePath), path.relative(pluginPath, filePath));\n }),\n );\n return mergeValidationResults(results);\n}\n\nasync function validatePluginSkillFiles(\n pluginPath: string,\n skillsRelPath: string,\n): Promise<ValidationResult> {\n const skillsDir = path.join(pluginPath, skillsRelPath);\n if (!(await directoryExists(skillsDir))) return validResult();\n\n const files = await glob(`**/${STANDARD_FILES.SKILL_MD}`, skillsDir);\n if (files.length === 0) {\n return {\n valid: true,\n errors: [],\n warnings: [`Skills directory exists but contains no SKILL.md files: ${skillsRelPath}`],\n };\n }\n\n return validateEachFile(pluginPath, skillsDir, files, validateSkillFrontmatter);\n}\n\nasync function validatePluginAgentFiles(\n pluginPath: string,\n agentsRelPath: string,\n): Promise<ValidationResult> {\n const agentsDir = path.join(pluginPath, agentsRelPath);\n if (!(await directoryExists(agentsDir))) return validResult();\n\n const files = await glob(agentCodec(\"claude\").listGlob, agentsDir);\n if (files.length === 0) {\n return {\n valid: true,\n errors: [],\n warnings: [`Agents directory exists but contains no .md files: ${agentsRelPath}`],\n };\n }\n\n return validateEachFile(pluginPath, agentsDir, files, validateAgentFrontmatter);\n}\n\nasync function loadManifestForValidation(\n manifestPath: string,\n): Promise<Record<string, unknown> | null> {\n try {\n const content = await readFileSafe(manifestPath, MAX_PLUGIN_FILE_SIZE);\n const parsed: unknown = JSON.parse(content);\n return isRecord(parsed) ? parsed : null;\n } catch {\n return null;\n }\n}\n\nexport async function validatePlugin(pluginPath: string): Promise<ValidationResult> {\n const structureResult = await validatePluginStructure(pluginPath);\n if (!structureResult.valid) return structureResult;\n\n const manifestPath = getPluginManifestPath(pluginPath);\n const [manifestResult, manifest] = await Promise.all([\n validatePluginManifest(manifestPath),\n loadManifestForValidation(manifestPath),\n ]);\n const skillsResult = await validateDeclaredDir(\n pluginPath,\n manifest?.skills,\n validatePluginSkillFiles,\n );\n const agentsResult = await validateDeclaredDir(\n pluginPath,\n manifest?.agents,\n validatePluginAgentFiles,\n );\n\n return mergeValidationResults([structureResult, manifestResult, skillsResult, agentsResult]);\n}\n\n/** A manifest field naming no directory leaves nothing to validate. */\nasync function validateDeclaredDir(\n pluginPath: string,\n declaredRelPath: unknown,\n validate: (pluginPath: string, relPath: string) => Promise<ValidationResult>,\n): Promise<ValidationResult> {\n if (!isNonEmptyString(declaredRelPath)) return validResult();\n return validate(pluginPath, declaredRelPath);\n}\n\ntype NamedPluginValidation = { name: string; result: ValidationResult };\n\ntype PluginsDirValidation = {\n valid: boolean;\n results: NamedPluginValidation[];\n summary: {\n total: number;\n valid: number;\n invalid: number;\n withWarnings: number;\n };\n};\n\nexport async function validateAllPlugins(pluginsDir: string): Promise<PluginsDirValidation> {\n if (!(await directoryExists(pluginsDir))) {\n return refusedPluginsDir(pluginsDir, `Directory does not exist: ${pluginsDir}`);\n }\n\n const pluginDirs = await listPluginDirNames(pluginsDir);\n if (pluginDirs.length === 0) {\n return refusedPluginsDir(\n pluginsDir,\n `No plugins found in directory: ${pluginsDir}. Plugins must contain a ${PLUGIN_MANIFEST_DIR}/ directory.`,\n );\n }\n\n const results = await validateEachPlugin(pluginsDir, pluginDirs);\n return summarizePluginValidations(results);\n}\n\n/** The directory itself stands as the one invalid result: nothing inside it was validated. */\nfunction refusedPluginsDir(pluginsDir: string, message: string): PluginsDirValidation {\n return {\n valid: false,\n results: [{ name: pluginsDir, result: invalidResult(message) }],\n summary: { total: 0, valid: 0, invalid: 1, withWarnings: 0 },\n };\n}\n\n/** Direct children carrying a plugin manifest directory, in listing order. */\nexport async function listPluginDirNames(pluginsDir: string): Promise<string[]> {\n const allDirs = await listDirectories(pluginsDir);\n const dirChecks = await Promise.all(\n allDirs.map(async (dirName) => ({\n dirName,\n isPlugin: await directoryExists(path.join(pluginsDir, dirName, PLUGIN_MANIFEST_DIR)),\n })),\n );\n return dirChecks.filter((c) => c.isPlugin).map((c) => c.dirName);\n}\n\nasync function validateEachPlugin(\n pluginsDir: string,\n pluginDirs: string[],\n): Promise<NamedPluginValidation[]> {\n const results: NamedPluginValidation[] = [];\n for (const pluginName of pluginDirs) {\n const result = await validatePlugin(path.join(pluginsDir, pluginName));\n results.push({ name: pluginName, result });\n }\n return results;\n}\n\nfunction summarizePluginValidations(results: NamedPluginValidation[]): PluginsDirValidation {\n const validCount = results.filter((r) => r.result.valid).length;\n const summary = {\n total: results.length,\n valid: validCount,\n invalid: results.length - validCount,\n withWarnings: results.filter((r) => r.result.warnings.length > 0).length,\n };\n\n return {\n valid: summary.invalid === 0,\n results,\n summary,\n };\n}\n","import type { ValidationResult } from \"../types\";\n\n/** A factory rather than a constant: callers mutate the arrays, so each needs its own. */\nexport function validResult(): ValidationResult {\n return { valid: true, errors: [], warnings: [] };\n}\n\nexport function invalidResult(message: string): ValidationResult {\n return { valid: false, errors: [message], warnings: [] };\n}\n\nexport function mergeValidationResults<E, W>(\n results: ReadonlyArray<{ errors: E[]; warnings: W[] }>,\n): { valid: boolean; errors: E[]; warnings: W[] } {\n const errors = results.flatMap((r) => r.errors);\n const warnings = results.flatMap((r) => r.warnings);\n return { valid: errors.length === 0, errors, warnings };\n}\n","import type { SkillDefinitionMap } from \"../../types\";\nimport { getErrorMessage } from \"../../utils/errors\";\nimport { fileExists } from \"../../utils/fs\";\nimport { verbose } from \"../../utils/logger\";\nimport { typedEntries } from \"../../utils/typed-object\";\nimport { hostAt } from \"../hosts/host-for.js\";\nimport { loadPluginSkills } from \"../loading\";\nimport { getPluginManifestPath } from \"./plugin-finder\";\nimport type { ResolvedPlugin } from \"./plugin-settings\";\n\n/**\n * Enabled plugins whose manifest is still on disk. Degrades to `[]` on an unreadable registry, so\n * `doctor` reports it as a finding rather than an aborted check.\n */\nexport async function getVerifiedPluginInstallPaths(projectDir: string): Promise<ResolvedPlugin[]> {\n let enabled: ResolvedPlugin[];\n try {\n const installed = await hostAt(projectDir).listPlugins(projectDir);\n enabled = installed\n .filter((plugin) => plugin.enabled)\n .map(({ pluginKey, installPath }) => ({ pluginKey, installPath }));\n } catch (error) {\n verbose(`Failed to list installed plugins: ${getErrorMessage(error)}`);\n return [];\n }\n\n const onDisk = await Promise.all(enabled.map(hasManifestOnDisk));\n const verified = enabled.filter((_, index) => onDisk[index] === true);\n\n verbose(`Verified ${verified.length} plugin install paths`);\n return verified;\n}\n\nasync function hasManifestOnDisk({ pluginKey, installPath }: ResolvedPlugin): Promise<boolean> {\n const pluginJsonPath = getPluginManifestPath(installPath);\n const manifestExists = await fileExists(pluginJsonPath);\n if (!manifestExists) {\n verbose(`Plugin '${pluginKey}' manifest does not exist at: '${pluginJsonPath}'`);\n }\n return manifestExists;\n}\n\nexport async function discoverAllPluginSkills(projectDir: string): Promise<SkillDefinitionMap> {\n const pluginPaths = await getVerifiedPluginInstallPaths(projectDir);\n\n if (pluginPaths.length === 0) {\n verbose(`No enabled plugins found for '${projectDir}'`);\n return {};\n }\n\n const perPluginSkills = await Promise.all(pluginPaths.map(loadSkillsOfPlugin));\n return mergeInPluginOrder(perPluginSkills);\n}\n\nasync function loadSkillsOfPlugin({\n pluginKey,\n installPath,\n}: ResolvedPlugin): Promise<SkillDefinitionMap> {\n verbose(`Discovering skills from plugin: '${pluginKey}'`);\n try {\n return await loadPluginSkills(installPath);\n } catch (error) {\n verbose(`Failed to load skills from '${pluginKey}': ${getErrorMessage(error)}`);\n return {};\n }\n}\n\n/** A later plugin overrides an earlier one on the same id. */\nfunction mergeInPluginOrder(perPluginSkills: readonly SkillDefinitionMap[]): SkillDefinitionMap {\n const allSkills: SkillDefinitionMap = {};\n for (const pluginSkills of perPluginSkills) {\n for (const [id, skill] of typedEntries(pluginSkills)) {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- typedEntries drops the `| undefined` a Partial<Record> slot can hold\n if (skill) allSkills[id] = skill;\n }\n }\n return allSkills;\n}\n\nexport async function listPluginNames(projectDir: string): Promise<string[]> {\n const pluginPaths = await getVerifiedPluginInstallPaths(projectDir);\n return pluginPaths.map(({ pluginKey }) => pluginKey);\n}\n","import path from \"path\";\nimport { directoryExists, listDirectories, fileExists, readFile } from \"../../utils/fs\";\nimport { verbose, warn } from \"../../utils/logger\";\nimport { plural } from \"../../utils/string\";\nimport { LOCAL_PSEUDO_CATEGORY, LOCAL_SKILLS_PATH, STANDARD_FILES } from \"../../consts\";\nimport { namesPlaceholderCategory, parseFrontmatter, readSkillMetadata } from \"../loading\";\nimport type { CategoryPath, Domain, ExtractedSkillMetadata, SkillSlug } from \"../../types\";\nimport { LOCAL_DEFAULTS, METADATA_KEYS } from \"../metadata-keys\";\n\nexport type LocalRawMetadata = {\n displayName: string;\n slug: SkillSlug;\n cliDescription?: string;\n category: CategoryPath;\n usageGuidance?: string;\n tags?: string[];\n domain: Domain;\n custom?: boolean;\n};\n\nexport type LocalSkillDiscoveryResult = {\n skills: ExtractedSkillMetadata[];\n localSkillsPath: string;\n};\n\nexport async function discoverLocalSkills(\n projectDir: string,\n): Promise<LocalSkillDiscoveryResult | null> {\n const localSkillsPath = path.join(projectDir, LOCAL_SKILLS_PATH);\n\n if (!(await directoryExists(localSkillsPath))) {\n verbose(`Local skills directory not found: ${localSkillsPath}`);\n return null;\n }\n\n const skillDirs = await listDirectories(localSkillsPath);\n const extracted = await Promise.all(\n skillDirs.map((skillDirName) => extractLocalSkill(localSkillsPath, skillDirName)),\n );\n const skills = extracted.filter((skill) => skill !== null);\n\n verbose(`Discovered ${plural(skills.length, \"local skill\")} from ${localSkillsPath}`);\n\n return {\n skills,\n localSkillsPath,\n };\n}\n\nasync function extractLocalSkill(\n localSkillsPath: string,\n skillDirName: string,\n): Promise<ExtractedSkillMetadata | null> {\n const skillDir = path.join(localSkillsPath, skillDirName);\n const metadataPath = path.join(skillDir, STANDARD_FILES.METADATA_YAML);\n const skillMdPath = path.join(skillDir, STANDARD_FILES.SKILL_MD);\n\n if (!(await fileExists(metadataPath))) {\n verbose(`Skipping local skill '${skillDirName}': No metadata.yaml found`);\n return null;\n }\n\n if (!(await fileExists(skillMdPath))) {\n verbose(`Skipping local skill '${skillDirName}': No SKILL.md found`);\n return null;\n }\n\n // One file that describes no skill skips its own skill, not the whole discovery.\n const read = await readSkillMetadata(metadataPath);\n if (!read.usable) {\n warn(\n `Skipping local skill '${skillDirName}': ${STANDARD_FILES.METADATA_YAML} at ${metadataPath} does not describe it — ${read.reason}`,\n );\n return null;\n }\n\n const metadata = read.metadata;\n\n // Warned here only: this pass reaches every command, so it is said once per run.\n if (namesPlaceholderCategory(metadata)) {\n warn(\n `Skipping local skill '${skillDirName}': ${METADATA_KEYS.CATEGORY} '${LOCAL_PSEUDO_CATEGORY}' is a placeholder, not a real category, so no sub-agent can be given this skill. Set ${METADATA_KEYS.CATEGORY} in ${metadataPath} to a real one.`,\n );\n return null;\n }\n\n const skillMdContent = await readFile(skillMdPath);\n const frontmatter = parseFrontmatter(skillMdContent, skillMdPath);\n\n if (!frontmatter) {\n verbose(`Skipping local skill '${skillDirName}': invalid SKILL.md frontmatter`);\n return null;\n }\n\n const relativePath = `${LOCAL_SKILLS_PATH}/${skillDirName}/`;\n const absolutePath = path.join(localSkillsPath, skillDirName) + path.sep;\n const skillId = frontmatter.name;\n\n const extracted: ExtractedSkillMetadata = {\n id: skillId,\n directoryPath: skillDirName,\n description: metadata.cliDescription || frontmatter.description,\n ...(frontmatter.description && { activationDescription: frontmatter.description }),\n ...(metadata.usageGuidance !== undefined && { usageGuidance: metadata.usageGuidance }),\n category: metadata.category,\n author: LOCAL_DEFAULTS.AUTHOR,\n path: relativePath,\n local: true,\n localPath: absolutePath,\n domain: metadata.domain,\n ...(metadata.custom !== undefined && { custom: metadata.custom }),\n slug: metadata.slug,\n displayName: metadata.displayName,\n };\n\n verbose(`Extracted local skill: ${skillId}`);\n return extracted;\n}\n","import path from \"path\";\n\nimport { EJECT_SOURCE, STANDARD_FILES } from \"../../consts\";\nimport type { SkillConfig } from \"../../types\";\nimport { fileExists } from \"../../utils/fs\";\nimport { resolveInstallPaths } from \"../installation/install-base-dir\";\nimport { readSkillMetadata, type UnusableSkillMetadata } from \"../loading\";\n\n/** Saved entries whose local skill is installed but whose metadata.yaml describes no skill. */\nexport async function findUnusableSavedSkillMetadata(\n savedSkills: readonly SkillConfig[],\n projectDir: string,\n): Promise<UnusableSkillMetadata[]> {\n const verdicts = await Promise.all(\n savedSkills.map((saved) => unusableMetadataOf(saved, projectDir)),\n );\n return verdicts.filter((verdict) => verdict !== null);\n}\n\n/** A directory with no metadata.yaml is unregistered, so `compile` skips rather than refuses it. */\nasync function unusableMetadataOf(\n saved: SkillConfig,\n projectDir: string,\n): Promise<UnusableSkillMetadata | null> {\n if (!claimsLocalCopy(saved)) return null;\n\n const metadataPath = installedMetadataPath(saved, projectDir);\n if (!(await fileExists(metadataPath))) return null;\n\n const read = await readSkillMetadata(metadataPath);\n return read.usable ? null : { skillDirName: saved.id, metadataPath, reason: read.reason };\n}\n\n/** Only an installed, ejected entry claims a local copy: a tombstone names nothing on disk. */\nfunction claimsLocalCopy(saved: SkillConfig): boolean {\n return !saved.excluded && saved.origin === EJECT_SOURCE;\n}\n\nfunction installedMetadataPath(saved: SkillConfig, projectDir: string): string {\n const { skillsDir } = resolveInstallPaths(projectDir, saved.scope);\n return path.join(skillsDir, saved.id, STANDARD_FILES.METADATA_YAML);\n}\n","import path from \"path\";\n\nimport {\n copy,\n directoryExists,\n ensureDir,\n isPathWithin,\n remove,\n removeDirIfEmpty,\n} from \"../../utils/fs\";\nimport { verbose, warn } from \"../../utils/logger\";\nimport { resolveInstallPaths } from \"../installation/install-base-dir\";\nimport type { SkillId, SkillScope } from \"../../types\";\n\n/** An id of `.` resolves to the skills directory itself, so a delete would take every skill. */\nconst THE_DIRECTORY_ITSELF = \".\";\n\n/** Runtime check: template literal types do not stop malformed ids arriving from YAML/JSON. */\nfunction validateSkillId(skillId: string): boolean {\n return !(\n skillId.length === 0 ||\n skillId === THE_DIRECTORY_ITSELF ||\n skillId.includes(\"\\0\") ||\n skillId.includes(\"..\") ||\n skillId.includes(\"/\") ||\n skillId.includes(\"\\\\\")\n );\n}\n\n/** Deletes `<skillsDir>/<skill-id>/`, with `skillsDir` resolved per host as the copy side does. */\nexport async function deleteLocalSkill(\n projectDir: string,\n skillId: SkillId,\n scope: SkillScope = \"project\",\n): Promise<void> {\n if (!validateSkillId(skillId)) {\n warn(`Invalid skill ID for deletion: '${skillId}'`);\n return;\n }\n\n const skillsDir = path.resolve(resolveInstallPaths(projectDir, scope).skillsDir);\n const skillPath = path.resolve(skillsDir, skillId);\n\n if (!isPathWithin(skillPath, skillsDir)) {\n warn(`Skill ID '${skillId}' resolves outside the skills directory.`);\n return;\n }\n\n try {\n await remove(skillPath);\n } catch {\n // Skill may not exist — silently ignore\n }\n\n // The host's directory above stays: removing it is uninstall's decision.\n await removeDirIfEmpty(skillsDir);\n\n verbose(`Deleted local skill '${skillId}'`);\n}\n\n/** P→G removes the project copy; G→P overrides, keeping the global one. No-op when absent. */\nexport async function migrateLocalSkillScope(\n skillId: SkillId,\n fromScope: SkillScope,\n projectDir: string,\n): Promise<void> {\n if (!validateSkillId(skillId)) {\n warn(`Invalid skill ID for scope migration: '${skillId}'`);\n return;\n }\n\n const toScope: SkillScope = fromScope === \"global\" ? \"project\" : \"global\";\n // Resolves `os.homedir()` at call time, so test home-dir mocks apply.\n const fromSkillsDir = path.resolve(resolveInstallPaths(projectDir, fromScope).skillsDir);\n const toSkillsDir = path.resolve(resolveInstallPaths(projectDir, toScope).skillsDir);\n\n const fromPath = path.resolve(fromSkillsDir, skillId);\n const toPath = path.resolve(toSkillsDir, skillId);\n\n if (!isPathWithin(fromPath, fromSkillsDir)) {\n warn(`Skill ID '${skillId}' resolves outside the source skills directory.`);\n return;\n }\n if (!isPathWithin(toPath, toSkillsDir)) {\n warn(`Skill ID '${skillId}' resolves outside the destination skills directory.`);\n return;\n }\n\n if (!(await directoryExists(fromPath))) {\n if (await directoryExists(toPath)) {\n verbose(`Skill '${skillId}' already at ${toScope} scope — no migration needed`);\n return;\n }\n warn(`Could not migrate skill '${skillId}' — not found at either scope`);\n return;\n }\n\n await ensureDir(toSkillsDir);\n await copy(fromPath, toPath);\n\n if (fromScope === \"project\") {\n await remove(fromPath);\n }\n\n verbose(`Migrated skill '${skillId}' from ${fromScope} to ${toScope}`);\n}\n","import { parse as parseYaml } from \"yaml\";\nimport path from \"path\";\nimport { getErrorMessage } from \"../../utils/errors\";\nimport { unreadableFrontmatter } from \"../../utils/frontmatter\";\nimport { glob, readFile, fileExists } from \"../../utils/fs\";\nimport { verbose, warn } from \"../../utils/logger\";\nimport { STANDARD_DIRS, STANDARD_FILES } from \"../../consts\";\nimport { loadConfig } from \"../configuration/config-loader\";\nimport { METADATA_KEYS } from \"../metadata-keys\";\nimport { parseFrontmatter } from \"../loading\";\nimport {\n skillCategoriesFileSchema,\n skillRulesFileSchema,\n formatZodIssues,\n matrixRawMetadataSchema,\n} from \"../schemas\";\nimport type {\n CategoryMap,\n ExtractedSkillMetadata,\n SkillFrontmatter,\n SkillRulesConfig,\n} from \"../../types\";\nimport type { z } from \"zod\";\n\ntype MatrixRawMetadata = z.infer<typeof matrixRawMetadataSchema>;\n\nexport async function loadSkillCategories(configPath: string): Promise<CategoryMap> {\n const data = await loadConfig(configPath, skillCategoriesFileSchema);\n\n if (!data) {\n throw new Error(`Invalid skill categories at '${configPath}': failed to load or validate`);\n }\n\n verbose(`Loaded skill categories: ${configPath}`);\n return data.categories;\n}\n\nexport async function loadSkillRules(configPath: string): Promise<SkillRulesConfig> {\n const data = await loadConfig(configPath, skillRulesFileSchema);\n\n if (!data) {\n throw new Error(`Invalid skill rules at '${configPath}': failed to load or validate`);\n }\n\n const config: SkillRulesConfig = {\n version: data.version,\n relationships: data.relationships ?? {\n conflicts: [],\n discourages: [],\n requires: [],\n alternatives: [],\n },\n };\n\n verbose(`Loaded skill rules: ${configPath}`);\n return config;\n}\n\n/** Files describing no skill are warned and skipped; a missing `displayName` throws. */\nexport async function extractAllSkills(skillsDir: string): Promise<ExtractedSkillMetadata[]> {\n const metadataFiles = await glob(`**/${STANDARD_FILES.METADATA_YAML}`, skillsDir);\n const skills: ExtractedSkillMetadata[] = [];\n\n for (const metadataFile of metadataFiles) {\n const skill = await extractSkill(skillsDir, metadataFile);\n if (skill) skills.push(skill);\n }\n\n return skills;\n}\n\n/** `null` skips this skill, not the scan. */\nasync function extractSkill(\n skillsDir: string,\n metadataFile: string,\n): Promise<ExtractedSkillMetadata | null> {\n const skillDir = path.dirname(metadataFile);\n const skillMdPath = path.join(skillsDir, skillDir, STANDARD_FILES.SKILL_MD);\n\n if (!(await fileExists(skillMdPath))) {\n verbose(`Skipping ${metadataFile}: No ${STANDARD_FILES.SKILL_MD} found`);\n return null;\n }\n\n const metadata = await readMatrixMetadataOrWarn(metadataFile, path.join(skillsDir, metadataFile));\n if (!metadata) return null;\n\n const frontmatter = parseFrontmatterOrWarn(skillDir, skillMdPath, await readFile(skillMdPath));\n if (!frontmatter) return null;\n\n if (!metadata.displayName) {\n throw new Error(\n `Skill at ${metadataFile} is missing required '${METADATA_KEYS.DISPLAY_NAME}' field in metadata.yaml`,\n );\n }\n\n const skillId = frontmatter.name;\n\n const extracted: ExtractedSkillMetadata = {\n id: skillId,\n directoryPath: skillDir,\n description: metadata.cliDescription || frontmatter.description,\n ...(frontmatter.description && { activationDescription: frontmatter.description }),\n ...(metadata.usageGuidance !== undefined && { usageGuidance: metadata.usageGuidance }),\n category: metadata.category,\n author: metadata.author,\n path: `${STANDARD_DIRS.SKILLS}/${skillDir}/`,\n domain: metadata.domain,\n displayName: metadata.displayName,\n slug: metadata.slug,\n ...(metadata.custom === true ? { custom: true } : {}),\n };\n\n verbose(`Extracted skill: ${skillId}`);\n return extracted;\n}\n\nasync function readMatrixMetadataOrWarn(\n metadataFile: string,\n metadataPath: string,\n): Promise<MatrixRawMetadata | null> {\n const metadataContent = await readFile(metadataPath);\n\n // safeParse cannot catch a file nothing parses; both skip this skill, not the scan.\n let rawMetadata: unknown;\n try {\n rawMetadata = parseYaml(metadataContent);\n } catch (error) {\n warn(\n `Skipping '${metadataFile}': unparseable ${STANDARD_FILES.METADATA_YAML} at ${metadataPath} — ${getErrorMessage(error)}`,\n );\n return null;\n }\n\n const metadataResult = matrixRawMetadataSchema.safeParse(rawMetadata);\n\n if (!metadataResult.success) {\n warn(\n `Skipping '${metadataFile}': invalid metadata.yaml — ${formatZodIssues(metadataResult.error.issues)}`,\n );\n return null;\n }\n\n return metadataResult.data;\n}\n\n/** A frontmatter that read but failed its schema was already named by `parseFrontmatter`. */\nfunction parseFrontmatterOrWarn(\n skillDir: string,\n skillMdPath: string,\n skillMdContent: string,\n): SkillFrontmatter | null {\n const frontmatter = parseFrontmatter(skillMdContent, skillMdPath);\n if (frontmatter) return frontmatter;\n\n const unreadable = unreadableFrontmatter(skillMdContent);\n if (unreadable !== undefined) {\n warn(\n `Skipping '${path.join(skillDir, STANDARD_FILES.SKILL_MD)}': unparseable ${STANDARD_FILES.SKILL_MD} frontmatter at ${skillMdPath} — ${unreadable}`,\n );\n }\n return null;\n}\n","import { verbose, warn } from \"../../utils/logger\";\nimport { unique, uniqueBy } from \"remeda\";\nimport { toTitleCase } from \"../../utils/string\";\nimport { DEFAULT_VERSION, LOCAL_PSEUDO_CATEGORY } from \"../../consts\";\nimport { defaultRules } from \"../configuration/default-rules\";\nimport type {\n CategoryDefinition,\n CategoryMap,\n Domain,\n ExtractedSkillMetadata,\n MergedSkillsMatrix,\n RelationshipDefinitions,\n RequireRule,\n ResolvedSkill,\n SkillAlternative,\n SkillId,\n SkillRelation,\n SkillRequirement,\n SkillRulesConfig,\n SkillSlug,\n SkillSlugMap,\n Category,\n} from \"../../types\";\n\ntype ResolveId = (slug: SkillSlug, context?: string) => SkillId | null;\n\nconst AUTO_SYNTH_ORDER = 999;\n\n/** Warns when skills file an undeclared category under different domains; the first wins. */\nfunction warnOnDomainDisagreement(\n skill: ExtractedSkillMetadata,\n decidedBy: ExtractedSkillMetadata,\n): void {\n if (skill.domain === decidedBy.domain) return;\n\n warn(\n `Category '${skill.category}' has no definition, so its domain was taken from the first skill ` +\n `naming it — '${decidedBy.id}' (${decidedBy.domain}). '${skill.id}' declares ` +\n `'${skill.domain}' and will be filed under '${decidedBy.domain}'. Declare the category in ` +\n `the marketplace's own config, or make the two skills agree.`,\n );\n}\n\nexport function synthesizeCategory(category: Category, domain: Domain): CategoryDefinition {\n verbose(\n `Category '${category}' has no definition in skill-categories.ts — using auto-generated placeholder`,\n );\n const displayName = toTitleCase(category);\n\n return {\n id: category,\n displayName,\n description: `Auto-generated category for ${category}`,\n domain,\n exclusive: false,\n order: AUTO_SYNTH_ORDER,\n };\n}\n\n/** A held slug keeps its holder silently: another marketplace's skill may share it. */\nexport function claimSlug(slugMap: SkillSlugMap, slug: SkillSlug, id: SkillId): void {\n slugMap.slugToId[slug] ??= id;\n}\n\n/** First claim wins, later ones named: in one marketplace a shared slug is the author's bug. */\nfunction buildSlugMap(skills: ExtractedSkillMetadata[]): SkillSlugMap {\n const slugMap: SkillSlugMap = { slugToId: {} };\n\n for (const { slug, id } of skills) {\n const incumbent = slugMap.slugToId[slug];\n if (incumbent !== undefined && incumbent !== id) {\n warn(`Duplicate slug '${slug}': already mapped to '${incumbent}', ignoring '${id}'`);\n }\n claimSlug(slugMap, slug, id);\n }\n\n return slugMap;\n}\n\n/** Warns on duplicate ids (first wins), which would otherwise resolve in glob order. */\nfunction buildResolvedSkillMap(\n skills: ExtractedSkillMetadata[],\n relationships: RelationshipDefinitions,\n slugMap: SkillSlugMap,\n): Partial<Record<SkillId, ResolvedSkill>> {\n const resolvedSkills: Partial<Record<SkillId, ResolvedSkill>> = {};\n\n for (const skill of skills) {\n const existing = resolvedSkills[skill.id];\n if (existing) {\n warn(\n `Duplicate skill id '${skill.id}': already resolved from '${existing.path}', ignoring '${skill.path}'`,\n );\n continue;\n }\n\n resolvedSkills[skill.id] = buildResolvedSkill(skill, relationships, slugMap);\n }\n\n return resolvedSkills;\n}\n\nfunction resolveToCanonicalId(\n slug: SkillSlug,\n slugToId: SkillSlugMap[\"slugToId\"],\n context?: string,\n): SkillId | null {\n const slugResult = slugToId[slug];\n if (slugResult) {\n return slugResult;\n }\n const location = context ? ` in ${context}` : \"\";\n warn(`Unresolved slug '${slug}'${location} — skipping`);\n return null;\n}\n\n/** Every slug the rules name, in the order the four rule kinds declare them. */\nfunction slugsNamedByRules(relationships: RelationshipDefinitions): SkillSlug[] {\n return [\n ...relationships.conflicts.flatMap((rule) => rule.skills),\n ...relationships.discourages.flatMap((rule) => rule.skills),\n ...relationships.requires.flatMap((rule) => [rule.skill, ...rule.needs]),\n ...relationships.alternatives.flatMap((rule) => rule.skills),\n ];\n}\n\n/** Asked of the rules, not per skill, so a typo is reported once. */\nfunction collectUnresolvedSlugs(\n relationships: RelationshipDefinitions,\n slugToId: SkillSlugMap[\"slugToId\"],\n): SkillSlug[] {\n return unique(slugsNamedByRules(relationships).filter((slug) => slugToId[slug] === undefined));\n}\n\n/** Merges relationship rule sets: source rules first, so they win first-match lookups. */\nfunction mergeRelationships(\n source: RelationshipDefinitions,\n defaults: RelationshipDefinitions,\n): RelationshipDefinitions {\n return {\n conflicts: [...source.conflicts, ...defaults.conflicts],\n discourages: [...source.discourages, ...defaults.discourages],\n requires: [...source.requires, ...defaults.requires],\n alternatives: [...source.alternatives, ...defaults.alternatives],\n };\n}\n\n/** Below two present members a group rule relates nothing, so it is dropped whole. */\nconst MIN_RELATABLE_GROUP_MEMBERS = 2;\n\n/** Group rules — conflicts, discourages, alternatives — keeping only present slugs. */\nfunction narrowGroupsToSlugs<Rule extends { skills: SkillSlug[] }>(\n rules: Rule[],\n shipped: ReadonlySet<SkillSlug>,\n): Rule[] {\n return rules\n .map((rule) => ({ ...rule, skills: rule.skills.filter((slug) => shipped.has(slug)) }))\n .filter((rule) => rule.skills.length >= MIN_RELATABLE_GROUP_MEMBERS);\n}\n\n/**\n * Keeps requirements a present skill declares over present skills; one left needing nothing goes.\n */\nfunction narrowRequirementsToSlugs(\n rules: RequireRule[],\n shipped: ReadonlySet<SkillSlug>,\n): RequireRule[] {\n return rules\n .filter((rule) => shipped.has(rule.skill))\n .map((rule) => ({ ...rule, needs: rule.needs.filter((slug) => shipped.has(slug)) }))\n .filter((rule) => rule.needs.length > 0);\n}\n\nfunction narrowToShippedSlugs(\n rules: RelationshipDefinitions,\n shipped: ReadonlySet<SkillSlug>,\n): RelationshipDefinitions {\n return {\n conflicts: narrowGroupsToSlugs(rules.conflicts, shipped),\n discourages: narrowGroupsToSlugs(rules.discourages, shipped),\n requires: narrowRequirementsToSlugs(rules.requires, shipped),\n alternatives: narrowGroupsToSlugs(rules.alternatives, shipped),\n };\n}\n\n/** The source's own rules verbatim, plus the built-ins narrowed to the slugs this source ships. */\nexport function relationshipsForSource(\n skills: ExtractedSkillMetadata[],\n sourceRules?: SkillRulesConfig,\n): RelationshipDefinitions {\n const shipped = new Set(skills.map((skill) => skill.slug));\n const builtIn = narrowToShippedSlugs(defaultRules.relationships, shipped);\n return sourceRules ? mergeRelationships(sourceRules.relationships, builtIn) : builtIn;\n}\n\nexport function mergeMatrixWithSkills(\n categories: CategoryMap,\n relationships: RelationshipDefinitions,\n skills: ExtractedSkillMetadata[],\n): MergedSkillsMatrix {\n const slugMap = buildSlugMap(skills);\n const resolvedSkills = buildResolvedSkillMap(skills, relationships, slugMap);\n const synthesizedCategories = withUndeclaredCategoriesSynthesized(categories, skills);\n const unresolvedSlugs = collectUnresolvedSlugs(relationships, slugMap.slugToId);\n\n const merged: MergedSkillsMatrix = {\n version: DEFAULT_VERSION,\n categories: synthesizedCategories,\n skills: resolvedSkills,\n suggestedStacks: [],\n slugMap,\n ...(unresolvedSlugs.length > 0 && { unresolvedSlugs }),\n generatedAt: new Date().toISOString(),\n };\n\n return merged;\n}\n\n/** A placeholder for each category a skill names that no definition declares. */\nfunction withUndeclaredCategoriesSynthesized(\n categories: CategoryMap,\n skills: ExtractedSkillMetadata[],\n): CategoryMap {\n const synthesizedCategories = { ...categories };\n const synthesizedFrom = new Map<string, ExtractedSkillMetadata>();\n for (const skill of skills) {\n // Skip \"local\" pseudo-category — it's not a real Category union member\n if (skill.category === LOCAL_PSEUDO_CATEGORY) continue;\n\n // A declared category is neither synthesized nor judged here; `checkCategoryDomains` owns it.\n if (categories[skill.category]) continue;\n\n const already = synthesizedFrom.get(skill.category);\n if (already === undefined) {\n synthesizedCategories[skill.category] = synthesizeCategory(skill.category, skill.domain);\n synthesizedFrom.set(skill.category, skill);\n verbose(`Auto-synthesized category '${skill.category}' for skill '${skill.id}'`);\n continue;\n }\n\n warnOnDomainDisagreement(skill, already);\n }\n\n return synthesizedCategories;\n}\n\ntype ResolvedRelationships = {\n conflictsWith: SkillRelation[];\n discourages: SkillRelation[];\n requires: SkillRequirement[];\n alternatives: SkillAlternative[];\n};\n\n/** Resolves a rule's slugs to canonical ids, warning and skipping any that don't resolve. */\nfunction resolveSlugsOrSkip(slugs: SkillSlug[], resolve: ResolveId, context: string): SkillId[] {\n return slugs.map((slug) => resolve(slug, context)).filter((id): id is SkillId => id !== null);\n}\n\n/** Null when any need names no skill: keeping the rest would apply a rule nobody wrote. */\nfunction resolveEveryNeed(needs: SkillSlug[], resolve: ResolveId): SkillId[] | null {\n // A rule needing nothing states no requirement.\n if (needs.length === 0) return null;\n\n const resolved = resolveSlugsOrSkip(needs, resolve, \"requires.needs\");\n return resolved.length === needs.length ? resolved : null;\n}\n\n/** Members of the groups containing `skillId`, deduped, each paired with its group's rule. */\nfunction collectSymmetricGroupMembers<Rule extends { skills: SkillSlug[] }>(\n rules: readonly Rule[],\n skillId: SkillId,\n resolve: ResolveId,\n context: string,\n): Array<{ memberId: SkillId; rule: Rule }> {\n const members = rules.flatMap((rule) => {\n const resolved = resolveSlugsOrSkip(rule.skills, resolve, context);\n if (!resolved.includes(skillId)) return [];\n return resolved.filter((id) => id !== skillId).map((memberId) => ({ memberId, rule }));\n });\n return uniqueBy(members, (m) => m.memberId);\n}\n\nfunction resolveRelationships(\n skillId: SkillId,\n relationships: RelationshipDefinitions,\n resolve: ResolveId,\n): ResolvedRelationships {\n const conflictsWith = relationsWithin(relationships.conflicts, skillId, resolve, \"conflicts\");\n const discourages = relationsWithin(relationships.discourages, skillId, resolve, \"discourages\");\n const alternatives = alternativesWithin(relationships.alternatives, skillId, resolve);\n const requires = requirementsOf(skillId, relationships.requires, resolve);\n\n return {\n conflictsWith,\n discourages,\n requires,\n alternatives,\n };\n}\n\nfunction relationsWithin(\n rules: RelationshipDefinitions[\"conflicts\" | \"discourages\"],\n skillId: SkillId,\n resolve: ResolveId,\n context: string,\n): SkillRelation[] {\n return collectSymmetricGroupMembers(rules, skillId, resolve, context).map(\n ({ memberId, rule }) => ({ skillId: memberId, reason: rule.reason }),\n );\n}\n\nfunction alternativesWithin(\n rules: RelationshipDefinitions[\"alternatives\"],\n skillId: SkillId,\n resolve: ResolveId,\n): SkillAlternative[] {\n return collectSymmetricGroupMembers(rules, skillId, resolve, \"alternatives\").map(\n ({ memberId, rule }) => ({ skillId: memberId, purpose: rule.purpose }),\n );\n}\n\n/** Directional: a rule's `skill` field names the dependent. */\nfunction requirementsOf(\n skillId: SkillId,\n rules: RequireRule[],\n resolve: ResolveId,\n): SkillRequirement[] {\n return rules.flatMap((rule) => {\n if (resolve(rule.skill, \"requires.skill\") !== skillId) return [];\n\n const resolvedNeeds = resolveEveryNeed(rule.needs, resolve);\n if (!resolvedNeeds) return [];\n\n return [{ skillIds: resolvedNeeds, needsAny: rule.needsAny ?? false, reason: rule.reason }];\n });\n}\n\nfunction buildResolvedSkill(\n skill: ExtractedSkillMetadata,\n relationships: RelationshipDefinitions,\n slugMap: SkillSlugMap,\n): ResolvedSkill {\n const resolve: ResolveId = (slug, context) =>\n resolveToCanonicalId(slug, slugMap.slugToId, context ? `${skill.id} ${context}` : undefined);\n\n const resolved = resolveRelationships(skill.id, relationships, resolve);\n\n return {\n id: skill.id,\n slug: skill.slug,\n displayName: skill.displayName,\n description: skill.description,\n ...(skill.activationDescription !== undefined && {\n activationDescription: skill.activationDescription,\n }),\n ...(skill.usageGuidance !== undefined && { usageGuidance: skill.usageGuidance }),\n category: skill.category,\n author: skill.author,\n ...resolved,\n path: skill.path,\n ...(skill.custom === true ? { custom: true } : {}),\n };\n}\n","import type { SkillId, SkillSlug } from \"../../types\";\n\n/** A skill is fenced by category exclusivity, by a `requires` rule, or not at all. */\ntype AuditVerdict = \"constrained-via-exclusivity-or-requires\" | \"universal\";\n\ntype SkillClass = \"A\" | \"B\" | \"C\";\n\ntype BatchId =\n | \"web-core\"\n | \"web-state\"\n | \"web-ui\"\n | \"web-platform\"\n | \"api-core\"\n | \"api-data\"\n | \"api-services\"\n | \"ai\"\n | \"mobile\"\n | \"desktop\"\n | \"infra-cli\"\n | \"shared-meta\";\n\nexport type SkillAuditEntry = {\n /** ISO date the verdict was established or last re-confirmed. */\n audited: `${number}-${number}-${number}`;\n verdict: AuditVerdict;\n batch: BatchId;\n /** Omitted for framework skills. Class A: no frameworks; B: exactly one; C: the adapter set. */\n classification?: { class: SkillClass; frameworks: SkillSlug[] };\n sources?: string[];\n /** Anything the current vocabulary cannot express, deferred rather than invented here. */\n deferredToD306?: string;\n};\n\n/** Total over SkillId, so every built-in needs a verdict; source skills are checked at runtime. */\nexport const skillAudit: Record<SkillId, SkillAuditEntry> = {\n \"web-framework-react\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-core\",\n },\n \"web-framework-vue-composition-api\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-core\",\n },\n \"web-framework-angular-standalone\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-core\",\n },\n \"web-framework-solidjs\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-core\",\n },\n \"web-framework-svelte\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-core\",\n },\n \"web-meta-framework-nextjs\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-core\",\n },\n \"web-meta-framework-remix\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-core\",\n },\n \"web-meta-framework-nuxt\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-core\",\n },\n \"web-meta-framework-sveltekit\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-core\",\n },\n \"web-meta-framework-astro\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-core\",\n },\n \"web-meta-framework-qwik\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-core\",\n },\n \"web-meta-framework-docusaurus\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-core\",\n classification: { class: \"A\", frameworks: [] },\n sources: [\"https://docusaurus.io\"],\n },\n \"web-meta-framework-vitepress\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-core\",\n classification: { class: \"A\", frameworks: [] },\n sources: [\"https://github.com/honojs/website\", \"https://vitepress.dev\"],\n },\n \"web-routing-react-router\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-core\",\n classification: { class: \"B\", frameworks: [\"react\"] },\n sources: [\"https://reactrouter.com\"],\n },\n \"web-routing-tanstack-router\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-core\",\n classification: { class: \"B\", frameworks: [\"react\"] },\n deferredToD306:\n \"Solid trigger: widen to needsAny [react, solidjs] if Solid content lands in the body (the official @tanstack/solid-router adapter already shipped upstream).\",\n },\n \"web-server-state-react-query\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-core\",\n classification: { class: \"B\", frameworks: [\"react\"] },\n deferredToD306:\n \"The hey-api MUST beside tRPC: the MUST reads literally (generated query options from hey-api — never write custom React Query hooks) and sits in tension beside tRPC-generated options in a hybrid stack; if that MUST is ever re-cut to claim ALL server data, the coexistence rationale reopens.\",\n },\n \"web-data-fetching-swr\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-core\",\n classification: { class: \"B\", frameworks: [\"react\"] },\n },\n \"web-data-fetching-trpc\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-core\",\n classification: { class: \"B\", frameworks: [\"react\"] },\n },\n \"web-data-fetching-graphql-apollo\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-core\",\n classification: { class: \"B\", frameworks: [\"react\"] },\n },\n \"web-data-fetching-graphql-urql\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-core\",\n classification: {\n class: \"C\",\n frameworks: [\"react\", \"vue-composition-api\", \"solidjs\", \"svelte\"],\n },\n },\n\n \"web-state-jotai\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-state\",\n classification: { class: \"B\", frameworks: [\"react\"] },\n deferredToD306:\n \"Jotai beside a store library is a real pattern (atomic UI atoms beside a domain store) with an official bridge extension (jotai-zustand / atomWithStore) but no vendor-documented two-peers steady state; unrepresentable while the zustand skill's MUST is territorial. Reopen trigger: the zustand MUST being re-cut to store-shaped state.\",\n },\n \"web-state-mobx\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-state\",\n classification: { class: \"B\", frameworks: [\"react\"] },\n },\n \"web-state-redux-toolkit\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-state\",\n classification: { class: \"B\", frameworks: [\"react\"] },\n },\n \"web-state-zustand\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-state\",\n classification: { class: \"B\", frameworks: [\"react\"] },\n },\n \"web-state-pinia\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-state\",\n classification: { class: \"B\", frameworks: [\"vue-composition-api\"] },\n },\n \"web-state-ngrx-signalstore\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-state\",\n classification: { class: \"B\", frameworks: [\"angular-standalone\"] },\n },\n \"web-forms-react-hook-form\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-state\",\n classification: { class: \"B\", frameworks: [\"react\"] },\n },\n \"web-forms-tanstack-form\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-state\",\n classification: {\n class: \"C\",\n frameworks: [\"react\", \"vue-composition-api\", \"angular-standalone\", \"solidjs\"],\n },\n deferredToD306:\n \"Svelte-widening trigger: widen the needsAny to svelte/sveltekit when Svelte content lands in the body (@tanstack/svelte-form is stable upstream; the skill claims React/Vue/Solid/Angular/Lit only).\",\n },\n \"web-forms-vee-validate\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-state\",\n classification: { class: \"B\", frameworks: [\"vue-composition-api\"] },\n },\n \"web-forms-zod-validation\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"web-state\",\n classification: { class: \"A\", frameworks: [] },\n sources: [\"https://zod.dev\"],\n },\n \"web-error-handling-error-boundaries\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-state\",\n classification: { class: \"B\", frameworks: [\"react\"] },\n },\n \"web-error-handling-result-types\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"web-state\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"web-i18n-next-intl\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-state\",\n classification: { class: \"B\", frameworks: [\"nextjs\"] },\n },\n \"web-i18n-react-intl\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-state\",\n classification: { class: \"B\", frameworks: [\"react\"] },\n },\n \"web-i18n-vue-i18n\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-state\",\n classification: { class: \"B\", frameworks: [\"vue-composition-api\"] },\n },\n \"web-utilities-rxjs\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"web-state\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"web-utilities-date-fns\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"web-state\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"web-utilities-vueuse\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-state\",\n classification: { class: \"B\", frameworks: [\"vue-composition-api\"] },\n },\n \"web-utilities-native-js\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"web-state\",\n classification: { class: \"A\", frameworks: [] },\n },\n\n \"web-ui-shadcn-ui\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-ui\",\n classification: { class: \"B\", frameworks: [\"react\"] },\n },\n \"web-ui-mui\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-ui\",\n classification: { class: \"C\", frameworks: [\"react\", \"nextjs\"] },\n },\n \"web-ui-chakra-ui\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-ui\",\n classification: { class: \"B\", frameworks: [\"react\"] },\n },\n \"web-ui-mantine\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-ui\",\n classification: { class: \"B\", frameworks: [\"react\"] },\n },\n \"web-ui-ant-design\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-ui\",\n classification: { class: \"C\", frameworks: [\"react\", \"nextjs\"] },\n },\n \"web-ui-vuetify\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-ui\",\n classification: { class: \"B\", frameworks: [\"vue-composition-api\"] },\n },\n \"web-ui-radix-ui\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-ui\",\n classification: { class: \"B\", frameworks: [\"react\"] },\n },\n \"web-ui-headless-ui\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-ui\",\n classification: { class: \"B\", frameworks: [\"react\"] },\n },\n \"web-ui-base-ui\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-ui\",\n classification: { class: \"B\", frameworks: [\"react\"] },\n sources: [\"https://base-ui.com\"],\n },\n \"web-ui-tanstack-table\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-ui\",\n classification: { class: \"B\", frameworks: [\"react\"] },\n },\n \"web-styling-tailwind\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"web-ui\",\n classification: { class: \"C\", frameworks: [] },\n },\n \"web-styling-scss-modules\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"web-ui\",\n classification: { class: \"A\", frameworks: [] },\n deferredToD306:\n \"tailwind <-> scss-modules coexistence is documented (Tailwind's own compatibility page allows but discourages it) — a discourages-shaped pair, no fence today.\",\n },\n \"web-styling-cva\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"web-ui\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"web-styling-theming\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"web-ui\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"web-styling-design-tokens\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"web-ui\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"web-animation-framer-motion\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-ui\",\n classification: { class: \"B\", frameworks: [\"react\"] },\n },\n \"web-animation-css-animations\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"web-ui\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"web-animation-view-transitions\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"web-ui\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"web-editor-lexical\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-ui\",\n classification: { class: \"B\", frameworks: [\"react\"] },\n sources: [\"https://lexical.dev\"],\n },\n \"web-editor-tiptap\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-ui\",\n classification: { class: \"C\", frameworks: [\"react\", \"vue-composition-api\"] },\n },\n \"web-3d-react-three-fiber\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-ui\",\n classification: { class: \"B\", frameworks: [\"react\"] },\n sources: [\"https://r3f.docs.pmnd.rs\"],\n },\n \"web-dnd-dnd-kit\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-ui\",\n classification: { class: \"B\", frameworks: [\"react\"] },\n sources: [\n \"skill body (DndContext/useDraggable/useDroppable/useSortable; every import a @dnd-kit/* React package)\",\n 'npm @dnd-kit/core (\"a lightweight React library\")',\n ],\n },\n\n \"web-testing-playwright-e2e\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-platform\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"web-testing-cypress-e2e\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-platform\",\n classification: { class: \"A\", frameworks: [] },\n deferredToD306:\n \"Cypress component testing beside Playwright E2E is unrepresentable — carried by the cy.mount slice; 2026 guidance keys the CT tool to the incumbent E2E runner, so the radio holds.\",\n },\n \"web-testing-react-testing-library\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-platform\",\n classification: { class: \"B\", frameworks: [\"react\"] },\n },\n \"web-testing-vue-test-utils\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-platform\",\n classification: { class: \"B\", frameworks: [\"vue-composition-api\"] },\n },\n \"web-testing-vitest\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"web-platform\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"web-testing-visual-regression\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"web-platform\",\n classification: { class: \"A\", frameworks: [] },\n deferredToD306:\n \"Pairs with a capture harness (playwright / cypress / storybook) — advice only; enumerating the harnesses would misstate BackstopJS/Percy-class setups.\",\n },\n \"web-tooling-storybook\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-platform\",\n classification: {\n class: \"C\",\n frameworks: [\n \"react\",\n \"vue-composition-api\",\n \"angular-standalone\",\n \"solidjs\",\n \"svelte\",\n \"qwik\",\n ],\n },\n sources: [\"https://storybook.js.org/docs/configure/integration/frameworks\"],\n deferredToD306:\n \"A community Astro framework exists (storybook-astro.org) but is not official — astro stays fenced out today. Package-health watch: storybook-framework-qwik 0.6.1, personal repo, trails Storybook 10.x.\",\n },\n \"web-tooling-vite\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"web-platform\",\n classification: { class: \"A\", frameworks: [] },\n deferredToD306:\n \"vite <-> nextjs and vite <-> docusaurus are dubious combos (discourages-shaped, advice not fence) — with the 6-of-15 vite-carrying default-stack rosters that also pin nextjs named as curation debt for the stack owner.\",\n },\n \"web-tooling-component-library\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-platform\",\n classification: { class: \"B\", frameworks: [\"react\"] },\n sources: [\n 'skill body (self-scope on all three surfaces; 3 of 5 MUSTs React/RSC-keyed; the \"use client\" contract)',\n ],\n },\n \"web-realtime-websockets\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-platform\",\n classification: { class: \"C\", frameworks: [\"react\"] },\n },\n \"web-realtime-socket-io\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-platform\",\n classification: { class: \"C\", frameworks: [\"react\"] },\n deferredToD306:\n \"A native-WebSocket third-party feed beside Socket.IO-to-own-server (the external service dictates the protocol) is a scope split the radio cannot express.\",\n },\n \"web-realtime-sse\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"web-platform\",\n classification: { class: \"C\", frameworks: [\"react\"] },\n },\n \"web-pwa-service-workers\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"web-platform\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"web-pwa-offline-first\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"web-platform\",\n classification: { class: \"C\", frameworks: [\"react\"] },\n },\n \"web-dataviz-d3\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"web-platform\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"web-dataviz-recharts\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-platform\",\n classification: { class: \"B\", frameworks: [\"react\"] },\n sources: [\"https://recharts.org\"],\n },\n \"web-maps-leaflet\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-platform\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"web-maps-mapbox\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-platform\",\n classification: { class: \"A\", frameworks: [] },\n deferredToD306:\n \"mapbox-gl-leaflet embedding (the Leaflet API drives a non-interactive GL layer, so half the mapbox skill applies and half must not be followed); Mapbox-as-tile-service needs no skill pairing at all.\",\n },\n \"web-mocks-msw\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"web-platform\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"web-files-file-upload-patterns\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-platform\",\n classification: { class: \"B\", frameworks: [\"react\"] },\n },\n \"web-files-image-handling\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"web-platform\",\n classification: { class: \"B\", frameworks: [\"react\"] },\n },\n \"web-performance-web-performance\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"web-platform\",\n classification: { class: \"C\", frameworks: [\"react\"] },\n },\n \"web-accessibility-web-accessibility\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"web-platform\",\n classification: { class: \"A\", frameworks: [] },\n },\n\n \"api-framework-hono\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-core\",\n },\n \"api-framework-express\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-core\",\n },\n \"api-framework-fastify\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-core\",\n },\n \"api-framework-nestjs\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-core\",\n },\n \"api-framework-elysia\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-core\",\n },\n \"api-graphql-apollo-server\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-core\",\n classification: { class: \"C\", frameworks: [\"express\", \"fastify\"] },\n },\n \"api-graphql-yoga\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-core\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"api-graphql-mercurius\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-core\",\n classification: { class: \"B\", frameworks: [\"fastify\"] },\n sources: [\n 'skill body (\"When NOT to use: Not using Fastify (Mercurius is Fastify-only)\")',\n \"mercurius README (npm i fastify mercurius graphql; app.register(mercurius))\",\n ],\n },\n \"api-auth-better-auth-drizzle-hono\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-core\",\n classification: { class: \"B\", frameworks: [\"hono\"] },\n sources: [\n 'skill body (app.on([\"POST\",\"GET\"], \"/auth/*\", …); createMiddleware<{ Variables: AuthVariables }>; c.req.raw)',\n \"https://better-auth.com\",\n ],\n },\n \"api-auth-nextauth\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-core\",\n classification: { class: \"B\", frameworks: [\"nextjs\"] },\n sources: [\"https://authjs.dev\"],\n },\n \"api-auth-clerk\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-core\",\n classification: { class: \"B\", frameworks: [\"nextjs\"] },\n },\n \"api-specs-openapi\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"api-core\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"api-messaging-webhooks\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"api-core\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"api-caching-strategies\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"api-core\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"api-queue-bullmq\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-core\",\n classification: { class: \"A\", frameworks: [] },\n sources: [\n \"https://docs.bullmq.io/guide/redis-tm-compatibility\",\n \"https://upstash.com/docs/redis/integrations/bullmq\",\n ],\n deferredToD306:\n \"BullMQ polls Redis even when idle, so Upstash's per-request Pay-As-You-Go pricing balloons (Upstash recommends a Fixed plan) — curation advice, not a fence.\",\n },\n \"api-performance-api-performance\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"api-core\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"api-commerce-stripe\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"api-core\",\n classification: { class: \"A\", frameworks: [] },\n },\n\n \"api-database-postgresql\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-data\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"api-database-mysql\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-data\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"api-database-cockroachdb\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-data\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"api-database-drizzle\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-data\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"api-database-prisma\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-data\",\n classification: { class: \"A\", frameworks: [] },\n deferredToD306:\n \"Prisma-on-Mongo overlaps mongoose as a full Mongo data layer; the pair is deliberately unfenced across the sql-engine/document radios (accepted over-permissiveness).\",\n },\n \"api-database-sequelize\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-data\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"api-database-typeorm\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-data\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"api-database-knex\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-data\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"api-database-mongodb\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-data\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"api-database-mongoose\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-data\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"api-database-edgedb\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-data\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"api-database-surrealdb\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-data\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"api-database-redis\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-data\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"api-database-upstash\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-data\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"api-database-vercel-kv\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-data\",\n classification: { class: \"A\", frameworks: [] },\n deferredToD306:\n \"vercel-kv -> requires [vercel] deferred, not adopted: product-true (only provisionable on Vercel) but the product is discontinued (Dec 2024) and retirement is the better disposition.\",\n },\n \"api-database-vercel-postgres\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-data\",\n classification: { class: \"A\", frameworks: [] },\n deferredToD306:\n \"vercel-postgres -> requires [vercel] deferred, not adopted: product-true but the product is discontinued (auto-migrated to Neon) and retirement is the better disposition.\",\n },\n \"api-baas-supabase\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-data\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"api-baas-firebase\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-data\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"api-baas-appwrite\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-data\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"api-baas-neon\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-data\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"api-baas-planetscale\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-data\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"api-baas-turso\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-data\",\n classification: { class: \"A\", frameworks: [] },\n deferredToD306:\n \"turso as an edge-replica secondary beside a primary Postgres host is a real minority pattern the api-db-host radio over-restricts — accepted.\",\n },\n\n \"api-vector-db-pinecone\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-services\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"api-vector-db-qdrant\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-services\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"api-vector-db-chroma\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-services\",\n classification: { class: \"A\", frameworks: [] },\n deferredToD306:\n \"chroma <-> pinecone dev/prod graduation split is the one real minority pattern the vector-db radio blocks.\",\n },\n \"api-vector-db-weaviate\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-services\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"api-search-elasticsearch\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-services\",\n classification: { class: \"A\", frameworks: [] },\n deferredToD306:\n \"Elasticsearch-for-logs beside Meilisearch-for-product-search is a real dual-role coexistence the api-search radio blocks.\",\n },\n \"api-search-meilisearch\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-services\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"api-search-xquik\": {\n audited: \"2026-08-09\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-services\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"api-cms-payload\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-services\",\n classification: { class: \"C\", frameworks: [\"nextjs\"] },\n deferredToD306:\n \"payload's full surface (admin panel, mounted REST/GraphQL) is Next-hosted today; the taught surface (config, collections, access control, hooks, Local API) is the documented headless mode and host-neutral — the nextjs pairing is recommends-shaped. Re-derive if the body grows Next mounting content, or when the 4.0 framework adapters land.\",\n },\n \"api-cms-sanity\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-services\",\n classification: { class: \"C\", frameworks: [\"react\"] },\n },\n \"api-cms-strapi\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-services\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"api-analytics-setup-posthog\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"api-services\",\n classification: { class: \"C\", frameworks: [\"react\"] },\n },\n \"api-flags-posthog-flags\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"api-services\",\n classification: { class: \"C\", frameworks: [\"react\"] },\n },\n \"api-analytics-posthog-analytics\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"api-services\",\n classification: { class: \"C\", frameworks: [\"react\"] },\n },\n \"api-observability-setup-axiom-pino-sentry\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-services\",\n classification: { class: \"C\", frameworks: [\"nextjs\"] },\n sources: [\n \"skill body (next-axiom, @sentry/nextjs, next.config.ts wrapped withAxiom(withSentryConfig(...)), instrumentation.ts, sentry.{client,server,edge}.config.ts)\",\n 'todo/skills.md — \"Next-only in all but name\"',\n ],\n },\n \"api-observability-axiom-pino-sentry\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"api-services\",\n classification: { class: \"C\", frameworks: [\"react\"] },\n },\n \"api-email-setup-resend\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-services\",\n classification: { class: \"B\", frameworks: [\"react\"] },\n sources: [\"https://react.email/docs\"],\n },\n \"api-email-resend-react-email\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"api-services\",\n classification: { class: \"B\", frameworks: [\"react\"] },\n deferredToD306:\n \"React-as-template-renderer is not React-as-app-framework: React Email runs in any Node backend, but because react sits in the exclusive web-framework radio the rule fences every Vue/Svelte/Angular project out of the catalog's only email-usage skill.\",\n },\n\n \"ai-provider-anthropic-sdk\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"ai\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"ai-provider-openai-sdk\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"ai\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"ai-provider-google-gemini-sdk\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"ai\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"ai-provider-mistral-sdk\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"ai\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"ai-provider-cohere-sdk\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"ai\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"ai-provider-elevenlabs\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"ai\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"ai-provider-claude-vision\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"ai\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"ai-provider-openai-whisper\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"ai\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"ai-infrastructure-huggingface-inference\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"ai\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"ai-infrastructure-together-ai\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"ai\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"ai-infrastructure-litellm\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"ai\",\n classification: { class: \"A\", frameworks: [] },\n deferredToD306:\n \"Wire-protocol reuse is not a skill dependency: litellm's TypeScript client literally is new OpenAI({ baseURL }), but the body carries its own complete client pointed away from OpenAI, so it derives no requires [openai-sdk].\",\n },\n \"ai-infrastructure-replicate\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"ai\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"ai-infrastructure-modal\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"ai\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"ai-infrastructure-ollama\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"ai\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"ai-orchestration-langchain\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"ai\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"ai-orchestration-llamaindex\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"ai\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"ai-orchestration-vercel-ai-sdk\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"ai\",\n classification: { class: \"C\", frameworks: [\"react\"] },\n },\n \"ai-observability-langfuse\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"ai\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"ai-observability-promptfoo\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"ai\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"ai-patterns-tool-use-patterns\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"ai\",\n classification: { class: \"A\", frameworks: [] },\n },\n\n \"mobile-framework-react-native\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"mobile\",\n },\n \"mobile-framework-expo\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"mobile\",\n },\n \"mobile-navigation-react-navigation\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"mobile\",\n classification: { class: \"B\", frameworks: [\"react-native\"] },\n sources: [\"https://reactnavigation.org\"],\n },\n \"mobile-navigation-expo-router\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"mobile\",\n classification: { class: \"B\", frameworks: [\"expo\"] },\n sources: [\"https://docs.expo.dev/router/installation/\"],\n },\n \"mobile-styling-nativewind\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"mobile\",\n classification: { class: \"B\", frameworks: [\"react-native\"] },\n sources: [\"https://www.nativewind.dev\"],\n },\n \"mobile-styling-unistyles\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"mobile\",\n classification: { class: \"B\", frameworks: [\"react-native\"] },\n sources: [\"https://www.unistyl.es\"],\n },\n \"mobile-testing-detox\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"mobile\",\n classification: { class: \"B\", frameworks: [\"react-native\"] },\n sources: [\"https://github.com/wix/Detox\"],\n },\n \"mobile-testing-maestro\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"mobile\",\n classification: { class: \"A\", frameworks: [] },\n sources: [\"https://docs.maestro.dev/get-started/supported-platform\"],\n deferredToD306:\n \"Needs an app Maestro can drive; the needsAny enumerates the catalog's current mobile-app producers (react-native, expo, tauri-mobile) — re-derive when that set changes.\",\n },\n \"mobile-ui-components-tamagui\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"mobile\",\n classification: { class: \"C\", frameworks: [\"react-native\", \"react\"] },\n sources: [\"https://tamagui.dev/docs/intro/installation\", \"https://github.com/tamagui/tamagui\"],\n deferredToD306:\n \"Surfaces a mobile-domain UI kit in web-only stacks — a curation question for the web-ui-kit split (group #14), advice-level only.\",\n },\n \"mobile-ui-components-react-native-paper\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"mobile\",\n classification: { class: \"B\", frameworks: [\"react-native\"] },\n sources: [\"https://callstack.github.io/react-native-paper/\"],\n },\n \"mobile-animation-reanimated\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"mobile\",\n classification: { class: \"B\", frameworks: [\"react-native\"] },\n sources: [\"https://docs.swmansion.com/react-native-reanimated/\"],\n },\n \"mobile-animation-gesture-handler\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"mobile\",\n classification: { class: \"B\", frameworks: [\"react-native\"] },\n sources: [\"https://docs.swmansion.com/react-native-gesture-handler/\"],\n },\n \"mobile-animation-skia\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"mobile\",\n classification: { class: \"B\", frameworks: [\"react-native\"] },\n sources: [\"https://shopify.github.io/react-native-skia/\"],\n },\n \"mobile-storage-mmkv\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"mobile\",\n classification: { class: \"B\", frameworks: [\"react-native\"] },\n sources: [\"https://github.com/mrousavy/react-native-mmkv\"],\n },\n \"mobile-storage-sqlite-powersync\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"mobile\",\n classification: { class: \"B\", frameworks: [\"react-native\"] },\n sources: [\"https://docs.powersync.com/resources/supported-platforms\"],\n },\n \"mobile-storage-watermelondb\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"mobile\",\n classification: { class: \"B\", frameworks: [\"react-native\"] },\n sources: [\"https://watermelondb.dev/docs/Implementation/DatabaseAdapters\"],\n deferredToD306:\n \"Upstream runs on React web via the LokiJS adapter; widen the binding if and only if the skill body ever covers it.\",\n },\n \"mobile-deployment-eas\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"mobile\",\n classification: { class: \"B\", frameworks: [\"expo\"] },\n sources: [\"https://docs.expo.dev/build/introduction/\"],\n },\n \"mobile-camera-vision-camera\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"mobile\",\n classification: { class: \"B\", frameworks: [\"react-native\"] },\n sources: [\"https://react-native-vision-camera.com\"],\n },\n \"mobile-hardware-ble-nfc\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"mobile\",\n classification: { class: \"B\", frameworks: [\"react-native\"] },\n sources: [\n \"https://github.com/dotintent/react-native-ble-plx\",\n \"https://github.com/revtel/react-native-nfc-manager\",\n ],\n },\n \"mobile-notifications-push\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"mobile\",\n classification: { class: \"B\", frameworks: [\"react-native\"] },\n sources: [\n \"https://docs.expo.dev/push-notifications/overview/\",\n \"https://rnfirebase.io/messaging/usage\",\n ],\n },\n \"mobile-background-tasks\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"mobile\",\n classification: { class: \"B\", frameworks: [\"react-native\"] },\n sources: [\n \"https://docs.expo.dev/versions/latest/sdk/background-task/\",\n \"https://github.com/transistorsoft/react-native-background-fetch\",\n ],\n },\n \"mobile-deep-linking-app-links\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"mobile\",\n classification: { class: \"B\", frameworks: [\"react-native\"] },\n sources: [\n \"https://docs.expo.dev/linking/overview/\",\n \"https://reactnavigation.org/docs/deep-linking/\",\n ],\n },\n \"mobile-performance-react-native\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"mobile\",\n classification: { class: \"B\", frameworks: [\"react-native\"] },\n sources: [\"https://reactnative.dev/docs/performance\"],\n },\n \"mobile-security-react-native\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"mobile\",\n classification: { class: \"B\", frameworks: [\"react-native\"] },\n sources: [\n \"https://docs.expo.dev/versions/latest/sdk/securestore/\",\n \"https://github.com/oblador/react-native-keychain\",\n ],\n },\n\n \"desktop-framework-electron\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"desktop\",\n },\n \"desktop-framework-tauri\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"desktop\",\n },\n \"desktop-ipc-electron\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"desktop\",\n classification: { class: \"B\", frameworks: [\"electron\"] },\n sources: [\"https://www.electronjs.org/docs/latest/tutorial/ipc\"],\n },\n \"desktop-storage-electron\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"desktop\",\n classification: { class: \"B\", frameworks: [\"electron\"] },\n sources: [\n \"https://www.electronjs.org/docs/latest/api/safe-storage\",\n \"https://github.com/sindresorhus/electron-store\",\n ],\n },\n \"desktop-ui-electron\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"desktop\",\n classification: { class: \"B\", frameworks: [\"electron\"] },\n sources: [\"https://www.electronjs.org/docs/latest/api/tray\"],\n },\n \"desktop-testing-electron\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"desktop\",\n classification: { class: \"B\", frameworks: [\"electron\"] },\n sources: [\"https://playwright.dev/docs/api/class-electron\"],\n },\n \"desktop-updates-electron-updater\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"desktop\",\n classification: { class: \"B\", frameworks: [\"electron\"] },\n sources: [\n \"https://github.com/electron-userland/electron-builder\",\n \"https://www.electron.build/auto-update\",\n ],\n deferredToD306:\n \"Defaults to the electron-builder pipeline (reads app-update.yml, written only by electron-builder's PublishManager); Forge apps using the Squirrel maker use Electron's built-in autoUpdater instead; Forge without Squirrel, and custom distributions, can still run electron-updater with custom config / generic provider.\",\n },\n \"desktop-multiwindow-electron\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"desktop\",\n classification: { class: \"B\", frameworks: [\"electron\"] },\n sources: [\"https://www.electronjs.org/docs/latest/api/base-window\"],\n },\n \"desktop-security-electron\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"desktop\",\n classification: { class: \"B\", frameworks: [\"electron\"] },\n sources: [\"https://www.electronjs.org/docs/latest/tutorial/fuses\"],\n },\n \"desktop-packaging-electron-forge\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"desktop\",\n classification: { class: \"B\", frameworks: [\"electron\"] },\n sources: [\"https://www.electronforge.io\"],\n },\n \"desktop-backend-tauri\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"desktop\",\n classification: { class: \"B\", frameworks: [\"tauri\"] },\n sources: [\"https://v2.tauri.app/develop/calling-rust/\"],\n },\n \"desktop-packaging-tauri\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"desktop\",\n classification: { class: \"B\", frameworks: [\"tauri\"] },\n sources: [\"https://v2.tauri.app/distribute/\"],\n },\n \"desktop-plugins-tauri\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"desktop\",\n classification: { class: \"B\", frameworks: [\"tauri\"] },\n sources: [\"https://v2.tauri.app/plugin/\"],\n },\n \"desktop-multiwindow-tauri\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"desktop\",\n classification: { class: \"B\", frameworks: [\"tauri\"] },\n sources: [\"https://v2.tauri.app/develop/calling-frontend/\"],\n },\n \"desktop-security-tauri\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"desktop\",\n classification: { class: \"B\", frameworks: [\"tauri\"] },\n sources: [\"https://v2.tauri.app/security/capabilities/\"],\n },\n \"desktop-mobile-tauri\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"desktop\",\n classification: { class: \"B\", frameworks: [\"tauri\"] },\n sources: [\n \"https://v2.tauri.app/reference/cli\",\n \"https://v2.tauri.app/blog/roadmap-to-tauri-2-0\",\n ],\n },\n\n \"infra-ci-cd-github-actions\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"infra-cli\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"infra-ci-cd-docker\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"infra-cli\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"infra-ci-cd-turborepo-ci\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"infra-cli\",\n classification: { class: \"B\", frameworks: [\"turborepo\"] },\n sources: [\"https://turborepo.dev/docs\"],\n },\n \"infra-config-setup-env\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"infra-cli\",\n classification: { class: \"C\", frameworks: [\"nextjs\", \"vite\"] },\n },\n \"infra-containers-kubernetes\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"infra-cli\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"infra-iac-terraform\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"infra-cli\",\n classification: { class: \"A\", frameworks: [] },\n deferredToD306:\n \"Layered terraform + pulumi coexistence via Pulumi's RemoteStateReference (a Pulumi program consuming the outputs of a Terraform-managed layer) is real at org scope; the radio models one engine per project.\",\n },\n \"infra-iac-pulumi\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"infra-cli\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"infra-iac-sst\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"infra-cli\",\n classification: { class: \"A\", frameworks: [] },\n deferredToD306:\n \"sst's typical data plane is @aws-sdk/client-* — the sst skill's own handlers import it; the pairing is recommended, not required, and platform-boundness (SST needs AWS-the-platform, which has no catalog anchor) is unrepresentable in the current vocabulary.\",\n },\n \"infra-platform-vercel\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"infra-cli\",\n classification: { class: \"A\", frameworks: [] },\n deferredToD306:\n \"vercel <-> netlify is a same-slot tension (one primary Git-centric host per app; monorepo split-hosting and migrations are the minority) and vercel <-> cloudflare-workers-as-host is the same shape — dubious combos, declined as fences.\",\n },\n \"infra-platform-netlify\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"infra-cli\",\n classification: { class: \"A\", frameworks: [] },\n deferredToD306:\n \"Carries the same dubious-combo record as vercel: vercel <-> netlify is a same-slot tension declined as a fence.\",\n },\n \"infra-platform-cloudflare-workers\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"infra-cli\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"infra-platform-aws-sdk\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"infra-cli\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"cli-framework-cli-commander\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"infra-cli\",\n },\n \"cli-framework-oclif-ink\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"infra-cli\",\n },\n \"cli-prompts-clack\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"infra-cli\",\n classification: { class: \"A\", frameworks: [] },\n },\n\n \"shared-monorepo-turborepo\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"shared-meta\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"shared-monorepo-nx\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"shared-meta\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"shared-monorepo-pnpm-workspaces\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"shared-meta\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"shared-tooling-biome\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"shared-meta\",\n classification: { class: \"A\", frameworks: [] },\n deferredToD306:\n \"The steady-state Biome-as-formatter plus bare-ESLint-for-plugin-gaps hybrid is real; it is unrepresentable while the catalog's ESLint skill bundles Prettier. A future bare eslint skill reopens this radio's rationale.\",\n },\n \"shared-tooling-eslint-prettier\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"shared-meta\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"shared-tooling-typescript-config\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"shared-meta\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"shared-tooling-git-hooks\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"shared-meta\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"shared-tooling-changesets\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"shared-meta\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"meta-config-stack-detect\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"shared-meta\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"shared-security-auth-security\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"shared-meta\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"meta-design-expressive-typescript\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"shared-meta\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"meta-design-composable-components\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"shared-meta\",\n classification: { class: \"B\", frameworks: [\"react\"] },\n sources: [\n 'skill body and all four example files (imports from \"react\"; @base-ui/react/use-render; @base-ui/react/merge-props; forwardRef; JSX-part composition)',\n ],\n },\n \"meta-methodology-research-methodology\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"shared-meta\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"meta-planning-web-planning\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"shared-meta\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"meta-planning-api-planning\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"shared-meta\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"meta-planning-cli-planning\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"shared-meta\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"meta-planning-ai-planning\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"shared-meta\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"meta-reviewing-reviewing\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"shared-meta\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"meta-reviewing-web-reviewing\": {\n audited: \"2026-08-07\",\n verdict: \"constrained-via-exclusivity-or-requires\",\n batch: \"shared-meta\",\n classification: { class: \"B\", frameworks: [\"react\"] },\n sources: [\n 'skill body self-scope (description \"Load when reviewing a diff that adds or changes React components or hooks\"; Applies-to \"Diffs that add or change React components or custom hooks\"; \"React PR review\" auto-detection) plus a React-keyed majority (4 of 5 critical requirements, 6 of 7 patterns)',\n ],\n },\n \"meta-reviewing-api-reviewing\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"shared-meta\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"meta-reviewing-cli-reviewing\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"shared-meta\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"meta-reviewing-ai-reviewing\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"shared-meta\",\n classification: { class: \"A\", frameworks: [] },\n },\n \"meta-reviewing-infra-reviewing\": {\n audited: \"2026-08-07\",\n verdict: \"universal\",\n batch: \"shared-meta\",\n classification: { class: \"A\", frameworks: [] },\n },\n};\n\n/** Rows whose verdict is ahead of its category disposition. */\nexport const auditVerdictsPendingApply: Partial<Record<SkillId, string>> = {};\n","import { warn } from \"../../utils/logger\";\nimport { LOCAL_PSEUDO_CATEGORY } from \"../../consts\";\nimport type {\n CategoryDefinition,\n CategoryPath,\n MergedSkillsMatrix,\n ResolvedSkill,\n SkillId,\n Category,\n} from \"../../types\";\nimport { isSkillId } from \"../../utils/type-guards\";\nimport { typedEntries } from \"../../utils/typed-object\";\nimport { skillAudit, auditVerdictsPendingApply } from \"../configuration/skill-audit\";\nimport type { SkillAuditEntry } from \"../configuration/skill-audit\";\n\n/** A closed union: callers branch on a kind, so a misspelling must be a compile error. */\ntype MatrixHealthFinding =\n | \"category-missing-domain\"\n | \"skill-unknown-category\"\n | \"skill-unresolved-relation-ref\"\n | \"rule-unresolved-slug\"\n | \"audit-verdict-contradiction\"\n | \"skill-unaudited\";\n\nexport type MatrixHealthIssue = {\n severity: \"warning\" | \"error\";\n finding: MatrixHealthFinding;\n details: string;\n};\n\n/** What the health check finds in `matrix`, said to nobody. */\nexport function matrixHealthIssues(matrix: MergedSkillsMatrix): MatrixHealthIssue[] {\n return [\n ...checkCategoryDomains(matrix),\n ...checkSkillCategories(matrix),\n ...checkSkillRelationRefs(matrix),\n ...checkUnresolvedRuleSlugs(matrix),\n ...checkAuditVerdictContradictions(matrix),\n ...checkUnauditedSkills(matrix),\n ];\n}\n\n/** Warns each issue; callers that only file them use `matrixHealthIssues`. */\nexport function checkMatrixHealth(matrix: MergedSkillsMatrix): MatrixHealthIssue[] {\n const issues = matrixHealthIssues(matrix);\n\n for (const issue of issues) {\n warn(`[matrix] ${issue.details}`);\n }\n\n return issues;\n}\n\nfunction checkCategoryDomains(matrix: MergedSkillsMatrix): MatrixHealthIssue[] {\n return (\n typedEntries<Category, CategoryDefinition>(matrix.categories)\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- Object.entries drops the `| undefined` a Partial<Record> admits\n .filter(([, cat]) => cat !== undefined && !cat.domain)\n .map(([catId]) => ({\n severity: \"warning\" as const,\n finding: \"category-missing-domain\",\n details: `Category '${catId}' has no domain — it won't appear under any domain`,\n }))\n );\n}\n\nfunction checkSkillCategories(matrix: MergedSkillsMatrix): MatrixHealthIssue[] {\n return typedEntries<SkillId, ResolvedSkill>(matrix.skills)\n .filter(\n ([, skill]) =>\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- Object.entries drops the `| undefined` a Partial<Record> admits\n skill !== undefined &&\n // \"local\" is a pseudo-category that won't exist in matrix.categories — skip it\n skill.category !== LOCAL_PSEUDO_CATEGORY &&\n !matrix.categories[skill.category],\n )\n .map(([skillId, skill]) => ({\n severity: \"warning\" as const,\n finding: \"skill-unknown-category\",\n details: `Skill '${skillId}' references category '${skill.category}' which does not exist in the matrix`,\n }));\n}\n\nfunction relationRefs(skill: ResolvedSkill): Array<{ field: string; ref: SkillId }> {\n return [\n ...skill.conflictsWith.map((relation) => ({ field: \"conflictsWith\", ref: relation.skillId })),\n ...skill.requires.flatMap((requirement) =>\n requirement.skillIds.map((ref) => ({ field: \"requires\", ref })),\n ),\n ];\n}\n\nfunction checkSkillRelationRefs(matrix: MergedSkillsMatrix): MatrixHealthIssue[] {\n return typedEntries<SkillId, ResolvedSkill>(matrix.skills).flatMap(([skillId, skill]) =>\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- Object.entries drops the `| undefined` a Partial<Record> admits\n skill === undefined\n ? []\n : relationRefs(skill)\n .filter(({ ref }) => !matrix.skills[ref])\n .map(({ field, ref }) => ({\n severity: \"warning\" as const,\n finding: \"skill-unresolved-relation-ref\",\n details: `Skill '${skillId}' has unresolved reference '${ref}' in '${field}'`,\n })),\n );\n}\n\n/** An `error`: the source's defect. `source-validator` downgrades it for consumers. */\nfunction checkUnresolvedRuleSlugs(matrix: MergedSkillsMatrix): MatrixHealthIssue[] {\n return (matrix.unresolvedSlugs ?? []).map((slug) => ({\n severity: \"error\" as const,\n finding: \"rule-unresolved-slug\",\n details: `Unresolved slug '${slug}' in the relationship rules — no skill carries it, so every rule naming it states nothing`,\n }));\n}\n\nfunction isExclusiveCategory(matrix: MergedSkillsMatrix, category: CategoryPath): boolean {\n // \"local\" is a pseudo-category with no definition in matrix.categories — never a fence\n if (category === LOCAL_PSEUDO_CATEGORY) return false;\n\n const definition = matrix.categories[category];\n return definition !== undefined && definition.exclusive;\n}\n\n/** The one definition of fenced that the runtime check and the manifest test share. */\nexport function isFencedByMatrix(matrix: MergedSkillsMatrix, skillId: SkillId): boolean {\n const skill = matrix.skills[skillId];\n if (skill === undefined) return false;\n\n return skill.requires.length > 0 || isExclusiveCategory(matrix, skill.category);\n}\n\n/** Runtime lookup: the manifest is total over built-ins, but a matrix may carry source skills. */\nfunction auditEntryFor(skillId: SkillId): SkillAuditEntry | undefined {\n return Object.hasOwn(skillAudit, skillId) ? skillAudit[skillId] : undefined;\n}\n\nfunction fenceDescription(skill: ResolvedSkill): string {\n if (skill.requires.length > 0) return \"it carries a 'requires' rule\";\n return `its category '${skill.category}' is exclusive`;\n}\n\n/** A `universal` verdict contradicts a `requires` rule or exclusive category; pending exempt. */\nfunction checkAuditVerdictContradictions(matrix: MergedSkillsMatrix): MatrixHealthIssue[] {\n return typedEntries<SkillId, ResolvedSkill>(matrix.skills)\n .filter(([skillId, skill]) => {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- Object.entries drops the `| undefined` a Partial<Record> admits\n if (skill === undefined || auditVerdictsPendingApply[skillId]) return false;\n const audit = auditEntryFor(skillId);\n\n return audit?.verdict === \"universal\" && isFencedByMatrix(matrix, skillId);\n })\n .map(([skillId, skill]) => ({\n severity: \"error\" as const,\n finding: \"audit-verdict-contradiction\",\n details: `Skill '${skillId}' is audited 'universal' but ${fenceDescription(skill)}`,\n }));\n}\n\n/** Built-in ids only: marketplace and local skills are outside the manifest by construction. */\nfunction checkUnauditedSkills(matrix: MergedSkillsMatrix): MatrixHealthIssue[] {\n return typedEntries<SkillId, ResolvedSkill>(matrix.skills)\n .filter(\n ([skillId, skill]) =>\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- Object.entries drops the `| undefined` a Partial<Record> admits\n skill !== undefined &&\n !skill.local &&\n isSkillId(skillId) &&\n auditEntryFor(skillId) === undefined,\n )\n .map(([skillId]) => ({\n severity: \"warning\" as const,\n finding: \"skill-unaudited\",\n details: `Skill '${skillId}' has no audit verdict — the built-in audit manifest is missing an entry it is meant to carry`,\n }));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAOA,UAAQ;AACf,SAAS,aAAAC,YAAW,UAAAC,eAAc;AAClC,OAAOC,YAAU;;;ACFjB,OAAO,QAAQ;AACf,OAAO,QAAQ;AAGR,SAAS,gBAAgB,KAAsB;AACpD,MAAI;AACF,WAAO,GAAG,aAAa,GAAG,MAAM,GAAG,aAAa,GAAG,QAAQ,CAAC;AAAA,EAC9D,QAAQ;AACN,WAAO,QAAQ,GAAG,QAAQ;AAAA,EAC5B;AACF;;;ACRO,IAAM,gBAAgB;AAAA,EAC3B,cAAc;AAAA,EACd,iBAAiB;AAAA,EACjB,UAAU;AAAA,EACV,aAAa;AAAA,EACb,cAAc;AAAA,EACd,gBAAgB;AAAA,EAChB,QAAQ;AACV;AAGO,IAAM,iBAAiB;AAAA,EAC5B,QAAQ;AACV;AAEO,IAAM,sBAAsB,CAAC,eAAe,UAAU,eAAe,YAAY;AAEjF,IAAM,qBAAqB,CAAC,cAAc,UAAU,cAAc,OAAO;;;ACbzE,SAAS,gBAAgB,OAAwB;AACtD,SAAO,sBAAsB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AACrF;;;ACRA,OAAOC,SAAQ;AACf,OAAO,QAAQ;AACf,OAAOC,SAAQ;AACf,OAAOC,WAAU;;;ACHjB,OAAOC,SAAQ;AACf,OAAOC,SAAQ;AACf,OAAO,UAAU;;;ACsBjB,IAAM,aAAa;AAGZ,SAAS,oBAAoB,OAAoB,MAAsB;AAC5E,0BAAwB,MAAM,MAAM,IAAI;AAExC,SAAO;AAAA,IACL,GAAG,YAAY,OAAO,IAAI;AAAA;AAA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ACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,IAAME,aAAY;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAIO,IAAM,aAAa;AAAA,EACxB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAsBO,IAAMC,eAAc;AAAA,EACzB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;;;AC12BO,SAAS,SAAS,OAAkD;AACzE,SAAO,OAAO,UAAU,YAAY,UAAU,QA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,eAAe;AAAA,IAEvB,eAAe,eAAe,iBAAiB,CAAC;AAAA,IAChD,UAAU,eAAe,YAAY,CAAC;AAAA,IACtC,cAAc,eAAe,gBAAgB,CAAC;AAAA,IAC9C,aAAa,eAAe,eAAe,CAAC;AAAA,IAE5C,MAAM,SAAS;AAAA,IAEf,OAAO;AAAA,IACP,GAAI,SAAS,cAAc,UAAa,EAAE,WAAW,SAAS,UAAU;AAAA,IACxE,GAAI,SAAS,WAAW,UAAa,EAAE,QAAQ,SAAS,OAAO;AAAA,EACjE;AACF;AAKA,SAAS,sBACPA,SACA,UACA,QACM;AACN,MAAI,aAAa,sBAAuB;AACxC,MAAIA,QAAO,WAAW,QAAQ,EAAG;AAEjC,EAAAA,QAAO,WAAW,QAAQ,IAAI;AAAA,IAC5B,IAAI;AAAA,IACJ,aAAa;AAAA,IACb,aAAa;AAAA,IACb;AAAA,IACA,WAAW;AAAA,IACX,OAAO;AAAA,EACT;AACA,UAAQ,yBAAyB,QAAQ,aAAa,MAAM,GAAG;AACjE;","names":["os","partition","unique","path","fs","os","path","fs","os","line","os","fs","path","fs","directoryExists","os","AsyncLocalStorage","configLoadFailure","agentsDir","skillsDir","SKILL_IDS","AGENT_NAMES","AGENT_NAMES","SKILL_IDS","os","path","z","z","path","CODEX_MODEL_NAMES","z","CODEX_MODEL_NAMES","path","unknownKeys","path","path","path","path","fs","fs","scopeLabel","path","os","CONTROL_CHAR_PATTERN","z","omit","partition","partition","isSkillAssignment","typedEntries","typedKeys","typedFromEntries","typedKeys","partition","typedEntries","typedFromEntries","isSkillId","isAgentName","omit","indexBy","omit","uniqueBy","os","path","path","groupBy","mapValues","partition","unique","mapValues","partition","groupBy","path","unique","scopeLabel","path","os","indexBy","uniqueBy","omit","path","path","path","path","path","NULL_BYTE_PATTERN","path","path","parseYaml","path","os","path","path","os","path","os","path","path","os","os","path","unique","parseYaml","path","parseYaml","parseYaml","parseYaml","agentsDir","path","directoryExists","skillsDir","createHash","os","path","path","pluginsDir","path","createHash","path","directoryExists","os","os","unique","matrix","os","unique","path","os","unique","os","os","directoryExists","os","path","z","path","SAFE_NAME_PATTERN","path","z","z","pluginsDir","path","os","z","path","os","path","z","os","line","z","path","cacheRoot","skillsDir","path","directoryExists","path","skillsDir","agentsDir","pluginsDir","path","parseYaml","sourceDir","skillsDir","path","path","directoryExists","path","skillsDir","path","path","skillsDir","path","directoryExists","parseYaml","path","skillsDir","path","parseYaml","unique","uniqueBy","unique","uniqueBy","matrix","isExclusiveCategory","matrix","os","skillsDir","path","partition","unique"]}
|