The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.
feat: integrate native Copilot skill and agent distribution
haelyra131c6186c362
diff --cc README.mdindex 95673de4b,d6c39efc4..185416ae7--- a/README.md+++ b/README.md@@@ -404,11 -337,12 +404,12 @@@ cd EC| Qwen CLI | `./install.sh --profile minimal --target qwen` | See the [Qwen guide](docs/QWEN-GUIDE.md) || Hermes | `./install.sh --profile minimal --target hermes` | See the [Hermes setup guide](docs/HERMES-SETUP.md) || OpenClaw | `./install.sh --profile minimal --target openclaw` | Managed home-directory install |-| Kimi Code CLI | `./install.sh --profile minimal --target kimi` | Project-local `.kimi-code/` install |+| Kimi Code CLI | `./install.sh --profile minimal --target kimi` | Project-local `.kimi-code/` install · [Get Kimi Code](https://www.kimi.ai/code?aff=ecc) || CodeBuddy | `./install.sh --profile minimal --target codebuddy` | Project-local `.codebuddy/` install || JoyCode | `./install.sh --profile minimal --target joycode` | Project-local `.joycode/` install |+ | GitHub Copilot | `./install.sh --profile full --target copilot` | Installs skills to `.github/skills/` and agents to `.github/agents/` for Copilot CLI |- GitHub Copilot support is already included in this repository. `.github/copilot-instructions.md` provides the instruction layer, `.github/prompts/` contains the reusable `/plan`, `/tdd`, `/security-review`, `/build-fix`, and `/refactor` prompts, and `.vscode/settings.json` enables `chat.promptFiles`.+ GitHub Copilot support is already included in this repository. `.github/copilot-instructions.md` provides the instruction layer, `.github/prompts/` contains the reusable `/plan`, `/tdd`, `/security-review`, `/build-fix`, and `/refactor` prompts, and `.vscode/settings.json` enables `chat.promptFiles`. GitHub Copilot CLI additionally discovers the `.agents/skills/` subset from a plain clone with no setup; see [Platform Support](#platform-support) for the full catalog and agents.For a harness without a native ECC target, use the [manual adaptation guide](docs/MANUAL-ADAPTATION-GUIDE.md). It explains how to carry a small set of ECC skills and workflow instructions into chat-style tools without pretending hooks or native skill discovery are available.@@@ -1284,15 -1483,6 +1285,16 @@@ ECC's core Node.js CLI and managed instTreat `stable`, `beta`, `experimental`, and `instruction-only` below as capability statements, not marketing tiers.+| Harness | Status | Recommended distribution | Important limitation |+|---|---|---|---|+| Claude Code | Stable primary | Plugin or selective installer | The plugin advertises the installed catalog to the model; use a selective/manual profile when context footprint matters. Optional shell-backed skills are not portable to every OS. |+| Codex | Supported native plugin | Codex marketplace plugin or repo config | Native hooks require an explicit trust decision and do not use Claude's hook profiles. The legacy sync is compatibility-only. |+| Cursor | Beta project adapter | Selective installer into `.cursor/` | Agent discovery varies by Cursor build, and ECC's installer paths do not yet expose identical hook sets ([#2419](https://github.com/affaan-m/ECC/issues/2419)). |+| OpenCode | Beta built plugin | Build plugin, then selective installer | ECC ships a subset of the catalog; connect a provider and select a model in OpenCode ([#2617](https://github.com/affaan-m/ECC/issues/2617)). |- | GitHub Copilot | Instruction-only | Checked-in instructions and prompt files | No ECC hooks, runtime agents, delegation, or native skill discovery. |++| GitHub Copilot Chat | Instruction-only | Checked-in instructions and prompt files | ECC hooks are not adapted. |++| GitHub Copilot CLI | Beta project adapter | `--target copilot` places skills and adapted agents in `.github/` | ECC hooks, rules, and command shims are not installed by this target. |+| Gemini, Zed, Antigravity, Qwen, Hermes, OpenClaw, Kimi, CodeBuddy, JoyCode | Experimental/minimal adapters | Harness-specific selective target | File placement and instruction portability are tested; full Claude feature parity is not claimed. |+<details><summary><strong>Package manager detection</strong></summary>@@@ -1652,7 -1846,7 +1654,7 @@@ For the full ECC OpenCode setup, either<details><summary><strong>GitHub Copilot support in depth</strong></summary>- ECC provides **GitHub Copilot support** for VS Code via Copilot Chat's native instruction and prompt file system. No extra tooling required.-ECC supports **GitHub Copilot** on two surfaces: Copilot Chat in VS Code, via its native instruction and prompt file system, and **GitHub Copilot CLI**, which discovers ECC's skills and agents from paths this repository already ships. No extra tooling is required for either.++ECC supports **GitHub Copilot** on two surfaces: Copilot Chat in VS Code, via its native instruction and prompt file system, and **GitHub Copilot CLI**, which discovers the shared skills already present in this repository. The optional `copilot` install target places canonical skills and adapted agents in the CLI's native project directories.#### What's included for GitHub Copilot@@@ -1673,6 -1867,99 +1675,99 @@@ To use the workflow prompts in Copilot2. Click the **paperclip / attach** icon and select **Prompt...**, or type `/` and choose a prompt.3. Select the prompt (e.g. `plan`, `tdd`, `security-review`).+ #### Copilot CLI: skills and agents++ GitHub Copilot CLI discovers `SKILL.md` skills from `.github/skills/`,+ `.agents/skills/`, `.claude/skills/`, `~/.copilot/skills/`, and+ `~/.agents/skills/`, and custom agents from `.github/agents/`. ECC's skill and-agent frontmatter (`name`, `description`) is already compatible, so no-conversion step is needed.++skill frontmatter is compatible. The managed `copilot` target adapts agent++frontmatter to `name` and `description`, removing Claude-specific model and++tool keys. Raw manual agent copies can retain unsupported metadata.++ Because ECC ships a skill subset in `.agents/skills/`, a plain clone of this+ repository is picked up by Copilot CLI with no configuration at all:++ ```bash+ git clone https://github.com/affaan-m/ECC.git && cd ECC+ copilot skill list-# 42 project skills: 39 from .agents/skills/, 3 from .claude/commands/++# The inventory depends on the checkout and CLI version.+ ```+-Copilot CLI 1.0.83 reports all 42 under `Project skills` with `source:++In the contributor's September 2026 checkout, Copilot CLI 1.0.83 reported all 42 under `Project skills` with `source:+ "project"` and `enabled: true`. The three from `.claude/commands/` are Claude+ command files that Copilot surfaces as skills; they are reported with `path`+ set to the `.claude/commands` directory rather than to a per-skill subdirectory.+-To check this without installing anything, run the npm-distributed build++To check this with a temporary npm-distributed CLI, run the pinned build+ against a throwaway clone:++ ```bash+ git clone --depth 1 https://github.com/affaan-m/ECC.git && cd ECC+ npx -y @github/[email protected] skill list --json | jq '[.[] | select(.source=="project")] | length'-# 42++# Count the current inventory rather than assuming a fixed total.+ ```+-The same 39 + 3 split is reported by 1.0.82 from npm and by 1.0.83 installed++That checkout's 39 + 3 split was reported by 1.0.82 from npm and by 1.0.83 installed+ locally, so the behaviour is not specific to one build or install method.++ To expose the full catalog, place `skills/` where Copilot CLI looks:++ ```bash-cp -r skills .github/skills # or: copilot skill add ./skills-copilot skill list --json | jq '[.[] | select(.path | contains(".github/skills"))] | length'-# 286++mkdir -p .github/skills++cp -r skills/. .github/skills/++copilot skill list --json > copilot-skills.json++jq '[.[] | select(.path | contains(".github/skills"))] | length' copilot-skills.json++# Compare with the current canonical skill catalog.+ ```+-Filter on the path rather than on `source`, because `source == "project"`-returns 290 here: the 286 from `.github/skills/` plus the 3 `.claude/commands/`-entries and the one `.agents/skills/` skill whose name does not collide with a-full-catalog entry. The other 38 `.agents/skills/` entries resolve to the same-skill names as their `.github/skills/` counterparts and are de-duplicated in-favor of `.github/skills/`.++Filter on the path rather than on `source`: the CLI can also discover skills++from other project locations and de-duplicates entries with the same skill++name. Counts depend on the checkout and CLI version. The file redirection also++avoids truncated large JSON output observed with Copilot CLI 1.0.82 on macOS.++ Copilot registers a skill under the `name` in its `SKILL.md` frontmatter, not+ its directory name, so catalog folders whose names differ from their frontmatter+ (for example `scientific-db-pubmed-database`, which declares+ `name: pubmed-database`) still load — they are just listed under the frontmatter+ name.++ Agents work the same way:++ ```bash-cp -r agents .github/agents++./install.sh --profile full --target copilot+ copilot --agent architect -p "Review this module's boundaries"+ ```+-Verified against Copilot CLI 1.0.83. All 286 skills load and report-`enabled: true`. Agents load and run; agent files that declare a Claude model++The contributor verified native discovery with Copilot CLI 1.0.83. Manually++copied agent files that declare a Claude model+ name (`model: opus`, `model: sonnet`) emit a warning and fall back to the+ session's default model, so remove or remap `model:` if you want to pin one.++ #### Installing with the `copilot` target++ The steps above copy files by hand. The `copilot` install target does the same+ placement and additionally rewrites agent frontmatter so no warning is emitted:++ ```bash+ ./install.sh --profile full --target copilot+ # Windows: ./install.ps1 --profile full --target copilot+ ```++ That writes skills to `.github/skills/`, agents to `.github/agents/`, and an+ install-state file to `.github/ecc-install-state.json`. Nothing is written+ outside `.github/`.+-The `full` profile places 285 skills and 68 agents. That is one skill fewer-than the 286 a manual `cp -r skills .github/skills` produces: `dmux-workflows`-belongs to the `orchestration` module, which ships tmux and shell worker-scripts and does not target Copilot. Copy `skills/dmux-workflows` by hand if-you want it.++The `full` profile selects the modules declared for Copilot. It can place fewer++skills than a manual copy of the entire canonical catalog because modules++that require another host's runtime are excluded. List the resulting native++inventory to see what this checkout installs; a count is not a capability grant.++ Claude-only agent frontmatter (`model`, `tools`, `color`) is dropped during the+ copy: Copilot resolves the model from your own configuration, and it governs+ tool access per session through `--allow-tool`/`--deny-tool` rather than through+ agent frontmatter. ECC's rules, commands, and hooks are not installed by this+ target.+#### Feature coverage| ECC Feature | Copilot equivalent |diff --cc manifests/context-packs/[email protected]index b478a347e,000000000..59d218c29mode 100644,000000..100644--- a/manifests/context-packs/[email protected]+++ b/manifests/context-packs/[email protected]@@@ -1,1 -1,0 +1,1 @@@- {"coverage":{"skills":293,"withTriggers":32},"generatedAt":"2026-09-24T23:51:22.784Z","id":"skill-triggers@1","model":{"effort":null,"id":"hand-seeded","source":"manual-curation-pending-regeneration"},"registryDigest":"a4abb961bbb5032e40d14e9aeef7e8c652d3517458b7ab72086b768c2e8b5a8b","schemaVersion":1,"triggers":{"skill:api-connector-builder":["add api integration","new provider connector","match existing integration pattern"],"skill:api-design":["rest endpoint design","pagination api","status codes","api versioning","rate limiting api","resource naming","filtering api","api error responses","offset pagination","limit query parameter","pagination defaults"],"skill:backend-patterns":["express api","node backend architecture","nextjs api routes","server side patterns","data access layer","static file server","url path handling","file server"],"skill:browser-qa":["deployed feature test","visual regression screenshots","core web vitals check","axe accessibility audit","ship do not ship","staging verification"],"skill:canary-watch":["post deploy monitoring","smoke test url","production url check","console errors production","sse stream check","after deploy verification"],"skill:code-tour":["onboarding walkthrough","explain subsystem","architecture tour","pr walkthrough","rca tour"],"skill:coding-standards":["code review standards","naming conventions","readability review","immutability conventions","fix naming typo","export naming","consistent exports"],"skill:content-hash-cache-pattern":["cache file processing","content addressed cache","sha256 hash cache"],"skill:database-migrations":["zero downtime migration","schema change production","add column large table","backfill data","expand contract","concurrent index","migration rollback","prisma migration","django migration"],"skill:deployment-patterns":["ci cd setup","dockerize app","health checks","rollback strategy","production readiness","deploy pipeline","containerize application"],"skill:design-system":["design tokens","visual consistency audit","css custom properties","ui audit","design system bootstrap"],"skill:django-patterns":["django orm","drf api","django rest framework","django caching","django signals","django middleware"],"skill:django-security":["django authentication","csrf protection","sql injection prevention","xss prevention","django deployment security","role based access control","authorization middleware","permissions checks"],"skill:docker-patterns":["dockerfile review","docker compose setup","container security","multi service orchestration"],"skill:error-handling":["error types","retry logic","circuit breaker","user facing errors","exception handling patterns","typed errors","error boundaries","go error handling","custom error class","error codes","config validation"],"skill:evm-token-decimals":["token decimals","wei conversion","erc20 balance off","bridge token precision"],"skill:frontend-a11y":["aria attributes","screen reader support","focus management","semantic html","form labeling","keyboard navigation react","a11y lint errors"],"skill:git-workflow":["merge vs rebase","commit conventions","resolve merge conflict","branching strategy","clean up commits","pull request cleanup","git history tidy"],"skill:hexagonal-architecture":["ports and adapters","dependency injection boundaries","decouple domain from io"],"skill:kubernetes-patterns":["kubernetes manifests","kubectl debugging","pod probes","k8s rbac","autoscaling config","configmap secrets"],"skill:orch-fix-defect":["fix a bug","broken behavior","regression fix","reproduce bug","defect repair"],"skill:postgres-patterns":["slow postgres query","query optimization","index design","rls policies","supabase schema","postgres indexing","database performance","schema design postgres","postgres driver","node postgres","query planner"],"skill:python-patterns":["pythonic code","pep 8","type hints python","python code review","idiomatic python"],"skill:python-testing":["pytest fixtures","mocking python","parametrized tests","coverage python","tdd python"],"skill:redis-patterns":["cache aside pattern","distributed lock","redis rate limiting","cache invalidation"],"skill:regex-vs-llm-structured-text":["parse invoice","extract receipt data","text extraction pipeline","parse form fields","cheap document parser","extract table data","parse log lines","parse access logs","common log format","log line parsing"],"skill:rust-patterns":["rust ownership","borrow checker","rust error handling","traits rust","rust concurrency","idiomatic rust"],"skill:search-first":["find existing library","npm package research","before writing custom code","evaluate existing tools","add dependency research"],"skill:security-review":["security audit","authentication review","sanitize user input","secrets handling","payment security checklist","prevent injection attacks","secure api endpoints","authn authz review","vulnerability checklist","input validation security","parameterized queries","sql injection"],"skill:security-scan":["audit claude config","claudemd security","mcp server audit","agentshield scan","hook configuration audit","settings json security"],"skill:tdd-workflow":["write test first","failing test","red green refactor","test driven development","regression test first","write a regression test"],"skill:verification-loop":["pre pr checks","verification report","quality gates","build lint test coverage","before creating a pr"]},"triggersDigest":"25b97a9e06fc336c7cf95ab854ed1a41033a54bcd6e1fb1cf69dc906332462aa"}++{"coverage":{"skills":293,"withTriggers":32},"generatedAt":"2026-09-24T23:51:22.784Z","id":"skill-triggers@1","model":{"effort":null,"id":"hand-seeded","source":"manual-curation-pending-regeneration"},"registryDigest":"2fcefa0d92c5a761a142ab22c6e98e67cc229cecd9210bf47b7443761c9ca1a5","schemaVersion":1,"triggers":{"skill:api-connector-builder":["add api integration","new provider connector","match existing integration pattern"],"skill:api-design":["rest endpoint design","pagination api","status codes","api versioning","rate limiting api","resource naming","filtering api","api error responses","offset pagination","limit query parameter","pagination defaults"],"skill:backend-patterns":["express api","node backend architecture","nextjs api routes","server side patterns","data access layer","static file server","url path handling","file server"],"skill:browser-qa":["deployed feature test","visual regression screenshots","core web vitals check","axe accessibility audit","ship do not ship","staging verification"],"skill:canary-watch":["post deploy monitoring","smoke test url","production url check","console errors production","sse stream check","after deploy verification"],"skill:code-tour":["onboarding walkthrough","explain subsystem","architecture tour","pr walkthrough","rca tour"],"skill:coding-standards":["code review standards","naming conventions","readability review","immutability conventions","fix naming typo","export naming","consistent exports"],"skill:content-hash-cache-pattern":["cache file processing","content addressed cache","sha256 hash cache"],"skill:database-migrations":["zero downtime migration","schema change production","add column large table","backfill data","expand contract","concurrent index","migration rollback","prisma migration","django migration"],"skill:deployment-patterns":["ci cd setup","dockerize app","health checks","rollback strategy","production readiness","deploy pipeline","containerize application"],"skill:design-system":["design tokens","visual consistency audit","css custom properties","ui audit","design system bootstrap"],"skill:django-patterns":["django orm","drf api","django rest framework","django caching","django signals","django middleware"],"skill:django-security":["django authentication","csrf protection","sql injection prevention","xss prevention","django deployment security","role based access control","authorization middleware","permissions checks"],"skill:docker-patterns":["dockerfile review","docker compose setup","container security","multi service orchestration"],"skill:error-handling":["error types","retry logic","circuit breaker","user facing errors","exception handling patterns","typed errors","error boundaries","go error handling","custom error class","error codes","config validation"],"skill:evm-token-decimals":["token decimals","wei conversion","erc20 balance off","bridge token precision"],"skill:frontend-a11y":["aria attributes","screen reader support","focus management","semantic html","form labeling","keyboard navigation react","a11y lint errors"],"skill:git-workflow":["merge vs rebase","commit conventions","resolve merge conflict","branching strategy","clean up commits","pull request cleanup","git history tidy"],"skill:hexagonal-architecture":["ports and adapters","dependency injection boundaries","decouple domain from io"],"skill:kubernetes-patterns":["kubernetes manifests","kubectl debugging","pod probes","k8s rbac","autoscaling config","configmap secrets"],"skill:orch-fix-defect":["fix a bug","broken behavior","regression fix","reproduce bug","defect repair"],"skill:postgres-patterns":["slow postgres query","query optimization","index design","rls policies","supabase schema","postgres indexing","database performance","schema design postgres","postgres driver","node postgres","query planner"],"skill:python-patterns":["pythonic code","pep 8","type hints python","python code review","idiomatic python"],"skill:python-testing":["pytest fixtures","mocking python","parametrized tests","coverage python","tdd python"],"skill:redis-patterns":["cache aside pattern","distributed lock","redis rate limiting","cache invalidation"],"skill:regex-vs-llm-structured-text":["parse invoice","extract receipt data","text extraction pipeline","parse form fields","cheap document parser","extract table data","parse log lines","parse access logs","common log format","log line parsing"],"skill:rust-patterns":["rust ownership","borrow checker","rust error handling","traits rust","rust concurrency","idiomatic rust"],"skill:search-first":["find existing library","npm package research","before writing custom code","evaluate existing tools","add dependency research"],"skill:security-review":["security audit","authentication review","sanitize user input","secrets handling","payment security checklist","prevent injection attacks","secure api endpoints","authn authz review","vulnerability checklist","input validation security","parameterized queries","sql injection"],"skill:security-scan":["audit claude config","claudemd security","mcp server audit","agentshield scan","hook configuration audit","settings json security"],"skill:tdd-workflow":["write test first","failing test","red green refactor","test driven development","regression test first","write a regression test"],"skill:verification-loop":["pre pr checks","verification report","quality gates","build lint test coverage","before creating a pr"]},"triggersDigest":"25b97a9e06fc336c7cf95ab854ed1a41033a54bcd6e1fb1cf69dc906332462aa"}diff --cc scripts/lib/install-lifecycle.jsindex 98abf8e20,3b6d86c58..d0750cf86--- a/scripts/lib/install-lifecycle.js+++ b/scripts/lib/install-lifecycle.js@@@ -30,18 -20,8 +30,19 @@@ constgetLegacyOpencodeLocation,inspectLegacyOpencodeState,} = require('./install/opencode-legacy-migration');+const {+ acquireSettingsLock,+ assertClaudeSettingsPath,+ getClaudeSettingsPath,+ inspectManagedHooks,+ materializeManagedHooks,+ repairManagedHooks,+ uninstallManagedHooks,+ updateSettingsAtomic,+ validateManagedHooks,+} = require('./install/claude-settings');const { adaptAntigravityAgent } = require('./install/antigravity-agent');+ const { adaptCopilotAgent } = require('./install/copilot-agent');const { buildInstallIndex, rewriteRelativeLinks } = require('./install/link-rewrite');const { getInstallTargetAdapter, listInstallTargetAdapters } = require('./install-targets/registry');const { resolveInvocationEnvironment } = require('./invocation-environment');@@@ -239,12 -218,9 +240,15 @@@ function transformCopyFileContent(operaif (operation.contentTransform === 'antigravity-agent-frontmatter') {return adaptAntigravityAgent(content, operation.sourceRelativePath);}+ if (operation.contentTransform === 'opencode-disable-ecc-hooks') {+ return disableOpenCodeHookPluginRegistration(content, operation.sourceRelativePath);+ }+ if (operation.contentTransform === 'opencode-disable-plugin-entrypoint') {+ return getDisabledOpenCodePluginContent();+ }+ if (operation.contentTransform === 'copilot-agent-frontmatter') {+ return adaptCopilotAgent(content, operation.sourceRelativePath);+ }throw new Error(`Unknown install content transform: ${operation.contentTransform}`);}@@@ -1918,13 -1710,7 +1922,15 @@@ function prepareRepairMigration(plan, rinstallStatePath: record.installStatePath,statePreview: buildAdapterDerivedStatePreview(plan.statePreview, record),};- const migration = prepareClaudeSkillMigration(trustedPlan);+ const initialMigration = prepareClaudeSkillMigration(trustedPlan);- const guardedMigration = record.adapter.id === 'codex-home'- ? prepareUserOwnedFileGuard(trustedPlan, initialMigration)- : initialMigration;++ // Repair normalizes recorded target metadata to the adapter-derived roots.++ // Preserve its recorded operations as the ownership evidence.++ const guardedMigration = prepareUserOwnedFileGuard(++ trustedPlan, initialMigration, buildAdapterDerivedStatePreview(record.state, record)++ );+ const migration = trustedPlan.target === 'opencode'+ ? require('./install/apply').prepareHookConsentMigration(trustedPlan, guardedMigration)+ : guardedMigration;return {migration,plan: {@@@ -2179,161 -1867,129 +2185,159 @@@ function repairInstalledStates(optionsinstallStatePath: record.installStatePath,repairedPaths: [],plannedRepairs: [],- error: formatBuildErrorMessage(error)+ warnings: desiredPlan.warnings,+ error: `Missing source file(s): ${operationHealth.missingSource.map(entry => entry.sourcePath).join(', ')}`};}- }- const rawPlan = createRepairPlanFromRecord(record, context);- const {- migration,- plan: desiredPlan,- } = prepareRepairMigration(rawPlan, record);- const operationHealth = summarizeManagedOperationHealth(- context.repoRoot,- record.targetRoot,- desiredPlan.operations- );+ const repairOperations = [+ ...operationHealth.missing.map(entry => ({ ...entry.operation })),+ ...operationHealth.drifted.map(entry => ({ ...entry.operation })),+ ...desiredPlan.operations+ .filter(operation => (+ operation.kind === 'update-claude-settings'+ && operation.previousManagedHooks+ && !isDeepStrictEqual(operation.previousManagedHooks, operation.managedHooks)+ ))+ .map(operation => ({ ...operation })),+ ].filter((operation, index, items) => items.findIndex(candidate => (+ candidate.kind === operation.kind+ && candidate.destinationPath === operation.destinationPath+ )) === index);+ const repairLinkIndex = buildLinkIndexForOperations(desiredPlan.operations, record.targetRoot);+ const legacyMigrationPaths = migration.legacyOperationsToRemove.map(+ operation => operation.destinationPath+ );+ const plannedRepairs = [...new Set([+ ...(needsOpencodeBuild ? [opencodeBuildRepairPath] : []),+ ...repairOperations.map(operation => operation.destinationPath),+ ...legacyMigrationPaths,+ ])];- const unsafeOperationResult = getUnsafeOperationResult(- record,- operationHealth- );- if (unsafeOperationResult) {- return unsafeOperationResult;- }+ if (options.dryRun) {+ return {+ adapter: record.adapter,+ status: plannedRepairs.length > 0 ? 'planned' : 'ok',+ installStatePath: record.installStatePath,+ repairedPaths: [],+ plannedRepairs,+ stateRefreshed: plannedRepairs.length === 0,+ warnings: desiredPlan.warnings,+ error: null+ };+ }++ const hasLegacyMigration = migration.legacyOperationsToRemove.length > 0;+ const repairedPaths = needsOpencodeBuild ? [opencodeBuildRepairPath] : [];+ if (desiredPlan.target === 'opencode') {+ const { assertOpenCodeActivationUnchanged } = require('./install/apply');+ // Health inspection must not let a changed activation become owned by+ // a bridge checkpoint before the per-write check can reject it.+ for (const destinationPath of activationSnapshot.keys()) {+ assertOpenCodeActivationUnchanged(desiredPlan, { destinationPath }, activationSnapshot);+ }+ }+ if (migration.requiresBridgeState && (repairOperations.length > 0 || hasLegacyMigration)) {+ writeRefreshedInstallState(record, migration.bridgeState);+ }++ for (const operation of repairOperations) {+ if (desiredPlan.target === 'opencode') {+ const { assertOpenCodeActivationUnchanged } = require('./install/apply');+ assertOpenCodeActivationUnchanged(desiredPlan, operation, activationSnapshot);+ }- if (record.adapter.id === 'codex-home') {- assertNoNewUserOwnedFile(migration, operation, desiredPlan);- }++ assertNoNewUserOwnedFile(migration, operation, desiredPlan);+ const repairedPath = executeRepairOperation(+ context.repoRoot,+ operation,+ record.targetRoot,+ repairLinkIndex,+ record.adapter.target,+ Boolean(releaseSettingsLock),+ require('./install/apply').getOpenCodeActivationWriteOptions(operation, activationSnapshot)+ );+ if (repairedPath) {+ repairedPaths.push(repairedPath);+ }+ }+ if (hasLegacyMigration) {+ for (const operation of migration.legacyOperationsToRemove) {+ const removedPath = removeContainedPath(+ operation.destinationPath,+ record.targetRoot,+ 'migrate managed Claude skill',+ { force: true }+ );+ if (removedPath) {+ repairedPaths.push(removedPath);+ }+ }+ }+ const changedInstalledBytes = repairOperations.length > 0+ || needsOpencodeBuild+ || hasLegacyMigration;+ const statePreviewToWrite = changedInstalledBytes+ ? desiredPlan.statePreview+ : {+ ...desiredPlan.statePreview,+ installedAt: record.state.installedAt,+ source: { ...record.state.source },+ };+ assertOpenCodeRepairHookDeactivation(desiredPlan, { requireInactive: true });+ writeRefreshedInstallState(record, statePreviewToWrite, repairedPaths);- if (operationHealth.missingSource.length > 0) {return {adapter: record.adapter,- status: 'error',+ status: (repairOperations.length > 0 || needsOpencodeBuild || hasLegacyMigration)+ ? 'repaired'+ : 'ok',installStatePath: record.installStatePath,- repairedPaths: [],+ repairedPaths,plannedRepairs: [],+ stateRefreshed: true,warnings: desiredPlan.warnings,- error: `Missing source file(s): ${operationHealth.missingSource.map(entry => entry.sourcePath).join(', ')}`+ error: null};- }-- const repairOperations = [...operationHealth.missing.map(entry => ({ ...entry.operation })), ...operationHealth.drifted.map(entry => ({ ...entry.operation }))];- const repairLinkIndex = buildLinkIndexForOperations(desiredPlan.operations, record.targetRoot);- const legacyMigrationPaths = migration.legacyOperationsToRemove.map(- operation => operation.destinationPath- );- const plannedRepairs = [...new Set([- ...(needsOpencodeBuild ? [opencodeBuildRepairPath] : []),- ...repairOperations.map(operation => operation.destinationPath),- ...legacyMigrationPaths,- ])];-- if (options.dryRun) {+ } catch (error) {return {adapter: record.adapter,- status: plannedRepairs.length > 0 ? 'planned' : 'ok',+ status: 'error',installStatePath: record.installStatePath,repairedPaths: [],- plannedRepairs,- stateRefreshed: plannedRepairs.length === 0,- warnings: desiredPlan.warnings,- error: null+ plannedRepairs: [],+ error: error.message};+ } finally {+ if (releaseSettingsLock) releaseSettingsLock();}-- const hasLegacyMigration = migration.legacyOperationsToRemove.length > 0;- const repairedPaths = needsOpencodeBuild ? [opencodeBuildRepairPath] : [];- if (migration.requiresBridgeState && (repairOperations.length > 0 || hasLegacyMigration)) {- writeRefreshedInstallState(record, migration.bridgeState);- }-- for (const operation of repairOperations) {- const repairedPath = executeRepairOperation(- context.repoRoot,- operation,- record.targetRoot,- repairLinkIndex- );- if (repairedPath) {- repairedPaths.push(repairedPath);- }- }- if (hasLegacyMigration) {- for (const operation of migration.legacyOperationsToRemove) {- const removedPath = removeContainedPath(- operation.destinationPath,- record.targetRoot,- 'migrate managed Claude skill',- { force: true }- );- if (removedPath) {- repairedPaths.push(removedPath);- }+ };+ if (record.adapter.target !== 'opencode' || options.dryRun) return performRepair();+ let repairResult;+ try {+ const adapter = getInstallTargetAdapter('opencode');+ const targetRoot = adapter.resolveRoot({+ homeDir: context.homeDir, projectRoot: context.projectRoot,+ repoRoot: context.projectRoot, env: context.env,+ });+ const { getOpenCodeInstallRoots, assertOpenCodeLeaseCoverage } = require('./install/apply');+ const roots = getOpenCodeInstallRoots({ adapter, targetRoot, homeDir: context.homeDir });+ return withOpenCodeInstallLocks(roots, lease => {+ assertOpenCodeLeaseCoverage({ adapter, targetRoot, homeDir: context.homeDir }, lease);+ // Discovery precedes acquisition. Never repair from that stale state.+ record = buildDiscoveryRecord(adapter, context, record.legacyLayout === 'opencode'+ ? getLegacyOpencodeLocation(context.homeDir) : null);+ if (!record.exists || record.error) {+ throw new Error(record.error || 'OpenCode install-state disappeared before repair.');}- }- const changedInstalledBytes = repairOperations.length > 0- || needsOpencodeBuild- || hasLegacyMigration;- const statePreviewToWrite = changedInstalledBytes- ? desiredPlan.statePreview- : {- ...desiredPlan.statePreview,- installedAt: record.state.installedAt,- source: { ...record.state.source },- };- writeRefreshedInstallState(record, statePreviewToWrite);-- return {- adapter: record.adapter,- status: (repairOperations.length > 0 || needsOpencodeBuild || hasLegacyMigration)- ? 'repaired'- : 'ok',- installStatePath: record.installStatePath,- repairedPaths,- plannedRepairs: [],- stateRefreshed: true,- warnings: desiredPlan.warnings,- error: null- };+ repairResult = performRepair(lease);+ return repairResult;+ });} catch (error) {- return {- adapter: record.adapter,- status: 'error',- installStatePath: record.installStatePath,- repairedPaths: [],- plannedRepairs: [],- error: error.message- };+ if (repairResult?.status === 'error') {+ return { ...repairResult, releaseError: error.message };+ }+ return { adapter: record.adapter, status: 'error', installStatePath: record.installStatePath,+ repairedPaths: repairResult?.repairedPaths || [], plannedRepairs: [], error: error.message };}});diff --cc scripts/lib/install-targets/copilot-project.jsindex 000000000,ce8d39440..72bccf4e3mode 000000,100644..100644--- a/scripts/lib/install-targets/copilot-project.js+++ b/scripts/lib/install-targets/copilot-project.js@@@ -1,0 -1,96 +1,97 @@@+ const path = require('path');++ const {+ createInstallTargetAdapter,+ createManagedOperation,+ createManagedScaffoldOperation,+ normalizeRelativePath,+ } = require('./helpers');++ // GitHub Copilot CLI discovers skills from `.github/skills/` and custom agents+ // from `.github/agents/`. Those two directories are the entire supported+ // surface for this target: ECC's hooks target Claude Code's event model, and+ // commands rely on slash-command argument substitution Copilot does not+ // provide, so neither is installed here.+ const SUPPORTED_SOURCE_PREFIXES = ['agents', 'skills'];++ function hasPrefix(normalizedPath, prefix) {+ return normalizedPath === prefix || normalizedPath.startsWith(`${prefix}/`);+ }++ function supportsCopilotSourcePath(sourceRelativePath) {+ const normalizedPath = normalizeRelativePath(sourceRelativePath);++ if (normalizedPath.split('/').includes('..')) return false;+ return SUPPORTED_SOURCE_PREFIXES.some(prefix => hasPrefix(normalizedPath, prefix));+ }++ function stripPrefix(normalizedPath, prefix) {+ return normalizedPath === prefix ? '' : normalizedPath.slice(`${prefix}/`.length);+ }++ function planSourcePathOperations(module, sourceRelativePath, targetRoot) {+ const normalizedSourcePath = normalizeRelativePath(sourceRelativePath);++ if (hasPrefix(normalizedSourcePath, 'agents')) {+ return [+ createManagedOperation({+ moduleId: module.id,+ sourceRelativePath: normalizedSourcePath,+ destinationPath: path.join(+ targetRoot,+ 'agents',+ stripPrefix(normalizedSourcePath, 'agents')+ ),+ strategy: 'preserve-relative-path',+ contentTransform: 'copilot-agent-frontmatter',+ }),+ ];+ }++ if (hasPrefix(normalizedSourcePath, 'skills')) {+ return [+ createManagedScaffoldOperation(+ module.id,+ normalizedSourcePath,+ path.join(targetRoot, 'skills', stripPrefix(normalizedSourcePath, 'skills')),+ 'preserve-relative-path'+ ),+ ];+ }++ return [];+ }++ module.exports = createInstallTargetAdapter({+ id: 'copilot-project',+ target: 'copilot',+ kind: 'project',+ rootSegments: ['.github'],+ installStatePathSegments: ['ecc-install-state.json'],+ supportsModule(module) {+ // Selection gating stays permissive so modules that only act as dependency+ // anchors (rules-core, commands-core, platform-configs) still resolve.+ // planOperations() is what narrows the install to agents and skills, so an+ // unsupported path contributes zero operations rather than skipping the+ // module and every module that depends on it.+ const paths = Array.isArray(module && module.paths) ? module.paths : [];+ return paths.length > 0;+ },+ planOperations(input, adapter) {+ const modules = Array.isArray(input.modules)+ ? input.modules+ : (input.module ? [input.module] : []);+ const { repoRoot, projectRoot, homeDir } = input;+ const targetRoot = adapter.resolveRoot({ repoRoot, projectRoot, homeDir });++ return modules.flatMap(module => {+ const paths = Array.isArray(module.paths) ? module.paths : [];+ return paths+ .filter(supportsCopilotSourcePath)+ .flatMap(sourceRelativePath => planSourcePathOperations(+ module,+ sourceRelativePath,+ targetRoot+ ));+ });+ },+ });diff --cc scripts/lib/install/apply.jsindex 209e53784,b08bc3554..d2e597d13--- a/scripts/lib/install/apply.js+++ b/scripts/lib/install/apply.js@@@ -37,21 -18,10 +37,22 @@@ constremoveLegacyClaudeSkillFiles,} = require('./claude-skill-migration');const { cleanupLegacyAntigravityInstall } = require('./antigravity-legacy-migration');-const { cleanupLegacyOpencodeInstall } = require('./opencode-legacy-migration');+const {+ assertNoNewUserOwnedFile,+ prepareUserOwnedFileGuard,+ preserveUnwrittenFiles,+} = require('./ownership-guard');+const { cleanupLegacyOpencodeInstall, getLegacyLocationForPlan, inspectLegacyOpencodeState,+ verifyManagedLegacyFile } = require('./opencode-legacy-migration');+const { writeFileNoFollow } = require('./guarded-write');+const { withOpenCodeInstallLocks } = require('./opencode-install-lock');+const {+ completeExcludedPathsReconciliation,+ prepareExcludedPathsReconciliation,+} = require('./excluded-paths-reconciliation');const { buildInstallIndex, rewriteRelativeLinks } = require('./link-rewrite');const { adaptAntigravityAgent } = require('./antigravity-agent');+ const { adaptCopilotAgent } = require('./copilot-agent');function isMarkdownPath(filePath) {return /\.(md|mdx|markdown)$/i.test(String(filePath || ''));@@@ -64,12 -34,9 +65,15 @@@ function transformInstallContent(operatif (operation.contentTransform === 'antigravity-agent-frontmatter') {return adaptAntigravityAgent(content, operation.sourceRelativePath);}+ if (operation.contentTransform === 'opencode-disable-ecc-hooks') {+ return disableOpenCodeHookPluginRegistration(content, operation.sourceRelativePath);+ }+ if (operation.contentTransform === 'opencode-disable-plugin-entrypoint') {+ return getDisabledOpenCodePluginContent();+ }+ if (operation.contentTransform === 'copilot-agent-frontmatter') {+ return adaptCopilotAgent(content, operation.sourceRelativePath);+ }throw new Error(`Unknown install content transform: ${operation.contentTransform}`);}diff --cc scripts/lib/install/ownership-guard.jsindex 965761cdc,000000000..e159dc447mode 100644,000000..100644--- a/scripts/lib/install/ownership-guard.js+++ b/scripts/lib/install/ownership-guard.js@@@ -1,175 -1,0 +1,175 @@@+'use strict';++const fs = require('fs');+const path = require('path');++const { readInstallState } = require('../install-state');+const { hasEditedCodexUserConfig } = require('./codex-user-config');++function pathExists(filePath) {+ try {+ fs.lstatSync(filePath);+ return true;+ } catch (error) {+ if (error && error.code === 'ENOENT') {+ return false;+ }+ throw error;+ }+}++function comparablePath(filePath) {+ const resolvedPath = path.resolve(filePath);+ return process.platform === 'win32' ? resolvedPath.toLowerCase() : resolvedPath;+}++/**+ * #2964: the shared copy path used to write every copy-file operation+ * unconditionally and record the destination as `ownership: 'managed'` even+ * when the file already existed and was authored by the user. The visible+ * symptom is a lost edit; the dangerous one is the install-state record,+ * which makes a later uninstall delete the user's file.+ *+ * This guard generalises the Claude flat-skill migration conflict pattern to+ * every adapter copy operation: when a destination exists and is NOT recorded+ * as an ECC-managed operation in the previous install-state, the operation is+ * skipped with a warning instead of overwriting and claiming ownership.+ *+ * All managed targets share this ownership boundary (#2964).+ */- function prepareUserOwnedFileGuard(plan, migration) {- const previousState = pathExists(plan.installStatePath)- ? readInstallState(plan.installStatePath)- : null;++function prepareUserOwnedFileGuard(plan, migration, recordedState) {++ const previousState = recordedState === undefined++ ? (pathExists(plan.installStatePath) ? readInstallState(plan.installStatePath) : null)++ : recordedState;+ if (previousState && (+ previousState.target.id !== plan.adapter.id+ || comparablePath(previousState.target.root) !== comparablePath(plan.targetRoot)+ || comparablePath(previousState.target.installStatePath) !== comparablePath(plan.installStatePath)+ )) {+ throw new Error(`Refusing install: install-state target does not match the current plan at ${plan.installStatePath}.`);+ }+ // Recorded files remain updateable by reinstall/repair. Preserve their prior+ // digests if an attempt fails before writing them so uninstall detects drift.+ const previousManagedOperations = new Map(+ ((previousState && previousState.operations) || [])+ .filter(operation => (+ operation+ && operation.ownership === 'managed'+ && operation.destinationPath+ ))+ .map(operation => [comparablePath(operation.destinationPath), operation])+ );+ const managedDestinations = new Set(previousManagedOperations.keys());++ const plannedOperations = (migration && migration.appliedOperations) || [];+ const plannedDestinations = new Set(plannedOperations.map(operation => comparablePath(operation.destinationPath)));+ // Selective reinstalls retain earlier modules in the ledger. Inspect those+ // entries too, without turning them into additional writes in this install.+ const retainedOperations = ((migration.finalState && migration.finalState.operations) || [])+ .filter(operation => !plannedDestinations.has(comparablePath(operation.destinationPath))+ && previousManagedOperations.has(comparablePath(operation.destinationPath)));+ const skippedOperations = [];+ const warnings = [];+ for (const operation of [...plannedOperations, ...retainedOperations]) {+ const previousOperation = previousManagedOperations.get(comparablePath(operation.destinationPath));+ const editedConfig = previousOperation+ && hasEditedCodexUserConfig(plan, operation, previousOperation);+ if (+ operation+ && operation.kind === 'copy-file'+ && operation.destinationPath+ && pathExists(operation.destinationPath)+ && (!managedDestinations.has(comparablePath(operation.destinationPath)) || editedConfig)+ ) {+ skippedOperations.push(operation);+ warnings.push(editedConfig+ ? `Preserved user configuration ${operation.destinationPath}: changed or unverifiable since installation. ECC no longer manages this file; apply future configuration updates manually.`+ : `Skipped user-owned file ${operation.destinationPath}: the existing file is not recorded in ECC install-state.`);+ continue;+ }+ }++ if (skippedOperations.length === 0) {+ return { ...migration, managedDestinations, previousManagedOperations };+ }++ const skippedDestinations = new Set(+ skippedOperations.map(operation => comparablePath(operation.destinationPath))+ );+ const appliedOperations = plannedOperations.filter(operation => (+ !skippedDestinations.has(comparablePath(operation.destinationPath))+ ));+ const filterStateOperations = operations => (operations || [])+ .filter(operation => !skippedDestinations.has(comparablePath(operation.destinationPath)));++ // Never leave a skipped destination inside the install-state: recording it+ // would claim ownership of a file ECC did not create and make uninstall+ // delete it (#2964).+ const bridgeState = migration.bridgeState+ ? {+ ...migration.bridgeState,+ operations: filterStateOperations(migration.bridgeState.operations),+ }+ : migration.bridgeState;+ const finalState = migration.finalState+ ? {+ ...migration.finalState,+ operations: filterStateOperations(migration.finalState.operations),+ }+ : migration.finalState;++ return {+ ...migration,+ managedDestinations,+ previousManagedOperations,+ appliedOperations,+ skippedOperations: [+ ...((migration && migration.skippedOperations) || []),+ ...skippedOperations,+ ],+ warnings: [...((migration && migration.warnings) || []), ...warnings],+ bridgeState,+ finalState,+ // Only keep bridge persistence when operations actually remain; a fully+ // skipped plan installs nothing and must not claim anything.+ requiresBridgeState: Boolean(migration.requiresBridgeState)+ && appliedOperations.length > 0,+ };+}++function assertNoNewUserOwnedFile(migration, operation, plan) {+ const previousOperation = migration.previousManagedOperations.get(comparablePath(operation.destinationPath));+ if (plan && hasEditedCodexUserConfig(plan, operation, previousOperation)) {+ throw new Error(`Refusing to overwrite user configuration changed after planning: ${operation.destinationPath}. Rerun to preserve it.`);+ }+ if (operation.kind !== 'copy-file'+ || migration.managedDestinations.has(comparablePath(operation.destinationPath))+ || !pathExists(operation.destinationPath)) {+ return;+ }+ throw new Error(`Refusing install: a user-owned file appeared at ${operation.destinationPath} after planning. Rerun the installer to preserve it.`);+}++function preserveUnwrittenFiles(state, migration, writtenDestinations) {+ const writtenPaths = new Set([...writtenDestinations].map(comparablePath));+ return {+ ...state,+ operations: state.operations.filter(operation => (+ operation.kind !== 'copy-file'+ || migration.managedDestinations.has(comparablePath(operation.destinationPath))+ || writtenPaths.has(comparablePath(operation.destinationPath))+ || !pathExists(operation.destinationPath)+ )).map(operation => {+ const destination = comparablePath(operation.destinationPath);+ return operation.kind === 'copy-file' && !writtenPaths.has(destination)+ ? migration.previousManagedOperations.get(destination) || operation+ : operation;+ }),+ };+}++module.exports = {+ assertNoNewUserOwnedFile,+ prepareUserOwnedFileGuard,+ preserveUnwrittenFiles,+};diff --cc tests/lib/copilot-install-target.test.jsindex 000000000,ce1aa4775..153d54639mode 000000,100644..100644--- a/tests/lib/copilot-install-target.test.js+++ b/tests/lib/copilot-install-target.test.js@@@ -1,0 -1,171 +1,206 @@@+ /**+ * Contract tests for the GitHub Copilot install target.+ *+ * Covers the frontmatter transform in isolation and the adapter's operation+ * planning, including the containment guarantee that nothing is written+ * outside the project's .github/ directory.+ */++ 'use strict';++ const assert = require('assert');+ const path = require('path');++ const REPO_ROOT = path.resolve(__dirname, '..', '..');+ const { adaptCopilotAgent } = require(path.join(REPO_ROOT, 'scripts', 'lib', 'install', 'copilot-agent'));+ const copilotAdapter = require(path.join(REPO_ROOT, 'scripts', 'lib', 'install-targets', 'copilot-project'));+ const { getInstallTargetAdapter } = require(path.join(REPO_ROOT, 'scripts', 'lib', 'install-targets', 'registry'));+ const { SUPPORTED_INSTALL_TARGETS } = require(path.join(REPO_ROOT, 'scripts', 'lib', 'install-manifests'));++ let passed = 0;+ let failed = 0;++ function test(name, fn) {+ try {+ fn();+ console.log(` \u2713 ${name}`);+ passed += 1;+ } catch (error) {+ console.log(` \u2717 ${name}`);+ console.log(` Error: ${error.message}`);+ failed += 1;+ }+ }++ const CLAUDE_AGENT = [+ '---',+ 'name: architect',+ 'description: Software architecture specialist.',+ 'tools: Read, Grep, Glob',+ 'model: opus',+ 'color: teal',+ '---',+ '',+ '## Role',+ '',+ 'You are an architect.',+ '',+ ].join('\n');++ function planFor(modules) {+ return copilotAdapter.planOperations({+ repoRoot: '/repo',+ projectRoot: '/project',+ homeDir: '/home/user',+ modules,+ });+ }++ console.log('=== Testing Copilot install target ===\n');++ test('registry resolves the copilot target and adapter id', () => {+ assert.strictEqual(getInstallTargetAdapter('copilot').id, 'copilot-project');+ assert.strictEqual(getInstallTargetAdapter('copilot-project').id, 'copilot-project');+ assert.strictEqual(copilotAdapter.target, 'copilot');+ assert.strictEqual(copilotAdapter.kind, 'project');+ });++ test('copilot is a supported install target', () => {+ assert.ok(SUPPORTED_INSTALL_TARGETS.includes('copilot'));+ });++ test('transform keeps only name and description', () => {+ const adapted = adaptCopilotAgent(CLAUDE_AGENT, 'agents/architect.md');+ assert.match(adapted, /^---\n/);+ assert.match(adapted, /name: architect/);+ assert.match(adapted, /description: Software architecture specialist\./);+ assert.doesNotMatch(adapted, /^model:/m);+ assert.doesNotMatch(adapted, /^tools:/m);+ assert.doesNotMatch(adapted, /^color:/m);+ });++ test('transform preserves the agent body verbatim', () => {+ const adapted = adaptCopilotAgent(CLAUDE_AGENT, 'agents/architect.md');+ assert.ok(adapted.includes('## Role'));+ assert.ok(adapted.includes('You are an architect.'));+ });++ test('transform rejects a file without frontmatter', () => {+ assert.throws(+ () => adaptCopilotAgent('# no frontmatter\n', 'agents/broken.md'),+ /missing YAML frontmatter/+ );+ });++ test('transform rejects frontmatter that is not an object', () => {+ assert.throws(+ () => adaptCopilotAgent('---\n- a\n- b\n---\nbody\n', 'agents/broken.md'),+ /frontmatter must be an object/+ );+ });++ test('transform requires name and description', () => {+ assert.throws(+ () => adaptCopilotAgent('---\nname: only-name\n---\nbody\n', 'agents/broken.md'),+ /missing required frontmatter "description"/+ );+ assert.throws(+ () => adaptCopilotAgent('---\ndescription: only description\n---\nbody\n', 'agents/broken.md'),+ /missing required frontmatter "name"/+ );+ });++ test('agents are planned into .github/agents with the frontmatter transform', () => {+ const operations = planFor([{ id: 'agents-core', paths: ['agents'] }]);+ assert.strictEqual(operations.length, 1);+ assert.strictEqual(operations[0].contentTransform, 'copilot-agent-frontmatter');+ assert.strictEqual(operations[0].destinationPath, path.join('/project', '.github', 'agents'));+ });++ test('skills are planned into .github/skills without a transform', () => {+ const operations = planFor([{ id: 'workflow-quality', paths: ['skills/tdd-workflow'] }]);+ assert.strictEqual(operations.length, 1);+ assert.strictEqual(operations[0].contentTransform, undefined);+ assert.strictEqual(+ operations[0].destinationPath,+ path.join('/project', '.github', 'skills', 'tdd-workflow')+ );+ });++ test('unsupported source paths produce no operations', () => {+ const operations = planFor([+ { id: 'rules-core', paths: ['rules'] },+ { id: 'commands-core', paths: ['commands', 'scripts/harness-audit.js'] },+ { id: 'hooks-runtime', paths: ['hooks', 'scripts/hooks'] },+ { id: 'platform-configs', paths: ['.claude-plugin', '.codex', 'mcp-configs'] },+ ]);+ assert.strictEqual(operations.length, 0);+ });++ test('supportsModule stays permissive so dependency anchors still resolve', () => {+ // rules-core, commands-core and platform-configs ship no agents or skills but+ // are dependencies of the skill modules. Gating them out here would cascade+ // and skip every module that depends on them.+ assert.strictEqual(copilotAdapter.supportsModule({ id: 'rules-core', paths: ['rules'] }), true);+ assert.strictEqual(copilotAdapter.supportsModule({ id: 'empty', paths: [] }), false);+ });++ test('every planned operation is contained within .github', () => {+ const operations = planFor([+ { id: 'agents-core', paths: ['agents', '.agents', 'AGENTS.md'] },+ { id: 'framework-language', paths: ['skills/api-design', 'skills/react-patterns'] },+ { id: 'rules-core', paths: ['rules'] },+ ]);+ const root = path.join('/project', '.github');+ assert.ok(operations.length > 0);+ for (const operation of operations) {+ const relative = path.relative(root, operation.destinationPath);+ assert.ok(+ relative && !relative.startsWith('..') && !path.isAbsolute(relative),+ `operation escapes .github: ${operation.destinationPath}`+ );+ }+ });++ test('AGENTS.md and .agents are not installed by this target', () => {+ const operations = planFor([{ id: 'agents-core', paths: ['.agents', 'AGENTS.md'] }]);+ assert.strictEqual(operations.length, 0);+ });+++test('traversal segments produce no planned operations', () => {++ for (const value of ['agents/../../escape.md', 'skills/../escape.md', 'agents\\..\\..\\escape.md']) {++ assert.deepStrictEqual(planFor([{ id: 'agents-core', paths: [value] }]), []);++ }++});++++test('repair and uninstall preserve user-owned agents across project adapters', () => {++ const fs = require('fs');++ const os = require('os');++ const { createManifestInstallPlan, applyInstallPlan } = require('../../scripts/lib/install-executor');++ const { repairInstalledStates, uninstallInstalledStates } = require('../../scripts/lib/install-lifecycle');++ for (const [target, segments] of [['copilot', ['.github', 'agents']], ['antigravity', ['.agents', 'agents']]]) {++ const project = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-agent-ownership-'));++ try {++ const agent = path.join(project, ...segments, 'architect.md');++ fs.mkdirSync(path.dirname(agent), { recursive: true });++ fs.writeFileSync(agent, 'USER OWNED SENTINEL\n');++ const homeDir = path.join(project, 'home');++ const plan = createManifestInstallPlan({ target, moduleIds: ['agents-core'], projectRoot: project, homeDir, env: {} });++ applyInstallPlan(plan);++ assert.strictEqual(fs.readFileSync(agent, 'utf8'), 'USER OWNED SENTINEL\n', 'install must preserve user file');++ const options = { repoRoot: REPO_ROOT, projectRoot: project, homeDir, targets: [target], env: {} };++ const repair = repairInstalledStates(options);++ assert.strictEqual(repair.summary.errorCount, 0, JSON.stringify(repair));++ assert.strictEqual(fs.readFileSync(agent, 'utf8'), 'USER OWNED SENTINEL\n', 'repair must preserve user file');++ const state = JSON.parse(fs.readFileSync(plan.installStatePath, 'utf8'));++ assert.ok(!state.operations.some(operation => operation.destinationPath === agent), 'repair must not claim ownership');++ uninstallInstalledStates(options);++ assert.strictEqual(fs.readFileSync(agent, 'utf8'), 'USER OWNED SENTINEL\n', 'uninstall must preserve user file');++ } finally {++ fs.rmSync(project, { recursive: true, force: true });++ }++ }++});+++ console.log(`\nResults: Passed: ${passed}, Failed: ${failed}`);+ process.exit(failed === 0 ? 0 : 1);