π The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
ci: remove untracked-copilot files from darwin sweep; regenerate pnpm-lock.yaml
ruvc81cd6ab0f34
diff --git a/v3/@claude-flow/copilot/AGENTS.md b/v3/@claude-flow/copilot/AGENTS.mddeleted file mode 100644index 13c2283bd2..0000000000--- a/v3/@claude-flow/copilot/AGENTS.md+++ /dev/null@@ -1,54 +0,0 @@-# @claude-flow/copilot--> GitHub Copilot SDK platform adapter for RuFlo--This package is part of the v3 monorepo. Inherits all rules from-`v3/CLAUDE.md` and the repo root `CLAUDE.md`.--## Behavior--- Files under 500 lines-- No hardcoded secrets β token resolution lives in `src/client/auth.ts` and- must keep the absolute "never read the raw token" rule from MEMORY.md-- Typed APIs at every export boundary-- TDD London School (mock-first); E2E tests gated behind `COPILOT_E2E=1`--## Package layout--```-src/- index.ts # root re-exports- types.ts # shared types- initializer.ts # CopilotInitializer- cli.ts # claude-flow-copilot bin- client/ # @github/copilot-sdk wrapper + auth + tools + models- mcp/ # bidirectional MCP bridge- dual-mode/ # MultiModeOrchestrator (extends DualModeOrchestrator)- loop/ # runCopilotLoop()- generators/ # AGENTS.md, config, skill emitters- migrations/ # CLAUDE.md β AGENTS.md; codex β copilot- validators/ # AGENTS.md, SKILL.md, config validators- templates/ # built-in skills list-tests/ # vitest; mock-first-```--## Build--```bash-npm install-npm run build # tsc; <500ms cold-npm test # vitest run-```--## When changing the package--1. Run `npm run build` β TypeScript must pass clean.-2. Run `wc -l src/**/*.ts` β every file must be < 500 lines.-3. Run `grep -rE 'ghp_|gho_|github_pat_|sk-' src/` β must be empty.-4. Add/update vitest tests for any new exported symbol.--## Related docs--- ADR-147: `v3/docs/adr/ADR-147-copilot-sdk-adapter.md`-- Research dossier: `docs/research/copilot-sdk-ruflo-integration.md`-- Codex adapter (mirror reference): `v3/@claude-flow/codex/`diff --git a/v3/@claude-flow/copilot/NEXT.md b/v3/@claude-flow/copilot/NEXT.mddeleted file mode 100644index 03720455d2..0000000000--- a/v3/@claude-flow/copilot/NEXT.md+++ /dev/null@@ -1,94 +0,0 @@-# Next-iteration pickup list β @claude-flow/copilot--**Last touched**: 2026-06-03 by Claude Code (Opus 4.7) via /loop.-**State at handoff**: ADR-147 written, package skeleton complete, tsc clean, vitest 56/56 green.--## Completed in this iteration--- `v3/docs/adr/ADR-147-copilot-sdk-adapter.md` (Implemented status)-- `v3/@claude-flow/copilot/` β full module tree: 24 source files in `src/`, 6 test files in `tests/`-- `npm install --no-package-lock --no-workspaces` succeeds-- `npm run build` clean-- `npm test` β 56 tests, all pass--## Next iteration should pick up these items in priority order--### 1. Wire `--copilot` flag into `@claude-flow/cli init` (ADR-147 P5)--In `v3/@claude-flow/cli/src/commands/init.ts` (or wherever init lives β grep-for `--codex`), add a `--copilot` flag that delegates to:--```ts-import { CopilotInitializer } from '@claude-flow/copilot';-const initializer = new CopilotInitializer();-await initializer.initialize({ projectPath, template, force });-```--The codex equivalent is the reference. The CLI's `init` already accepts-`--codex` per `v3/@claude-flow/codex/src/initializer.ts` integration; mirror-that wiring.--### 2. Install workspaces issue--The package installs cleanly only with `--no-package-lock --no-workspaces`.-The root npm workspaces config tries to resolve `@claude-flow/codex` and-`@claude-flow/guidance` peer deps via `workspace:*` protocol, which trips-the install. Two options:-- (a) Make codex/guidance proper workspace packages in root `package.json`- workspaces array β needs cross-package check.-- (b) Move both peers from peerDependencies to optionalDependencies so npm- doesn't try to resolve them during install of the standalone package.--Option (b) is the safer, less-disruptive path. Implement it before publish.--### 3. SDK version pinning--`@github/copilot-sdk` is listed in research Β§3.2 as `1.0.0-beta.12` despite-the GA announcement. Once an authenticated developer can run-`npm view @github/copilot-sdk` from a clean shell, pin the exact major in-`package.json`. Currently `@github/copilot-sdk` is NOT a direct dependency-(intentional β the optional dynamic-import pattern in `src/client/chat.ts`-makes it a soft peer). Decide whether to:-- promote it to a direct dependency once 1.0.0 is published; or-- keep the soft-import pattern and document it as a runtime opt-in.--### 4. SDK-backed E2E test--`tests/__mocks__/@github/copilot-sdk.ts` does not yet exist. The CLI fallback-is covered by `tests/dual-mode/orchestrator.test.ts` (via dry-run); a real-SDK round-trip test gated behind `COPILOT_E2E=1` would close the contract.-Pattern: stub a `CopilotClient` that exposes a `createSession()` returning-a fake `sendAndWait()`; assert `runGoverned()` calls it once and returns-the content unchanged.--### 5. Telemetry sink for ADR-146 P5 alignment--`CopilotMcpBridge` collects events but currently nothing consumes them. Wire-the bridge into the shared `GuardrailEvent` sink described in ADR-146 P5-so MCP tool calls from Copilot sessions show up on the security dashboard-alongside ADR-131 / 144 / 145 events.--### 6. Publishing checklist (do NOT do without user confirmation)--When the user asks to publish:-- `cd v3/@claude-flow/copilot && npm version 3.8.0 --no-git-tag-version`-- `npm publish`-- `npm dist-tag add @claude-flow/[email protected] alpha`-- `npm dist-tag add @claude-flow/[email protected] v3alpha`-- Then bump `claude-flow` (umbrella) and `ruflo` (wrapper) to 3.8.0 per the- three-package protocol in root `CLAUDE.md`.--## Open questions carried over--See ADR-147 "Open questions" section. None block ADR acceptance.--## Quick re-verify--```bash-cd v3/@claude-flow/copilot-npm install --no-package-lock --no-workspaces-npm run build # must be clean-npm test # must be 56/56 green-```--If those three pass, the package is in the same state I left it.diff --git a/v3/@claude-flow/copilot/README.md b/v3/@claude-flow/copilot/README.mddeleted file mode 100644index e5557c7144..0000000000--- a/v3/@claude-flow/copilot/README.md+++ /dev/null@@ -1,59 +0,0 @@-# @claude-flow/copilot--GitHub Copilot SDK platform adapter for [RuFlo](https://github.com/ruvnet/ruflo) β the third platform in the tri-mode collaboration system (Claude Code + Codex + Copilot).--Mirrors the [`@claude-flow/codex`](../codex) package structure module-for-module, with two net-new subfolders:--- `src/client/` β wraps `@github/copilot-sdk` (or drives the bundled `copilot` CLI in `-p/--prompt` non-interactive mode when the SDK is absent)-- `src/mcp/` β bidirectional MCP bridge that wires the RuFlo MCP server into every Copilot session--See [ADR-147](../../docs/adr/ADR-147-copilot-sdk-adapter.md) for the design.--## Quick start--```bash-# 1. Install once globally (or per-project)-npm install -g @claude-flow/copilot--# 2. Initialize a project-npx claude-flow-copilot init --template default--# 3. Run the doctor-npx claude-flow-copilot doctor--# 4. Try tri-mode collaboration-npx claude-flow-copilot dual run feature --task "Add OAuth login"-```--## Subcommands--| Command | Purpose |-|---------|---------|-| `init` | Scaffold AGENTS.md + .copilot/config.json + skills |-| `auth status` | Verify a credential source exists (never echoes the token) |-| `auth clear` | Clear the local handle file |-| `mcp register` | Print the `mcpServers` JSON used to wire RuFlo into Copilot |-| `chat` | One-shot governed prompt (`pre-task` β `route` β call β `post-task`) |-| `dual run` | Tri-mode collaborative swarm |-| `loop run` | Bounded autonomous /loop iteration |-| `doctor` | Health check (Node version, credential, AGENTS.md) |--## Model routing--| Tier | Model | Multiplier | Use case |-|------|-------|------------|----------|-| 2 (fast) | `gpt-5.4-mini` | 0.33Γ | Simple tasks (complexity < 30) |-| 3 (default) | `gpt-5.3-codex` (LTS) | 1.0Γ | Architecture, code generation |-| 3 (frontier, opt-in) | `gpt-5.5` | 7.5Γ | Complex reasoning |--`getOptimalModel(complexity, allowFrontier)` returns the right ID.--## Security--The package NEVER prints, persists, or logs the raw GitHub token. The cache-file at `~/.config/ruflo/copilot/token.json` holds only a credential SOURCE-identifier (e.g. `"env:GH_TOKEN"`). See ADR-147 Part G.--## License--MITdiff --git a/v3/@claude-flow/copilot/package.json b/v3/@claude-flow/copilot/package.jsondeleted file mode 100644index b1b3266b0f..0000000000--- a/v3/@claude-flow/copilot/package.json+++ /dev/null@@ -1,116 +0,0 @@-{- "name": "@claude-flow/copilot",- "version": "3.8.0",- "description": "GitHub Copilot SDK integration for RuFlo (claude-flow) β Copilot platform adapter and tri-mode collaboration",- "type": "module",- "main": "./dist/index.js",- "types": "./dist/index.d.ts",- "bin": {- "claude-flow-copilot": "./dist/cli.js"- },- "exports": {- ".": {- "types": "./dist/index.d.ts",- "import": "./dist/index.js",- "require": "./dist/index.js",- "default": "./dist/index.js"- },- "./client": {- "types": "./dist/client/index.d.ts",- "import": "./dist/client/index.js",- "require": "./dist/client/index.js"- },- "./mcp": {- "types": "./dist/mcp/index.d.ts",- "import": "./dist/mcp/index.js",- "require": "./dist/mcp/index.js"- },- "./generators": {- "types": "./dist/generators/index.d.ts",- "import": "./dist/generators/index.js",- "require": "./dist/generators/index.js"- },- "./templates": {- "types": "./dist/templates/index.d.ts",- "import": "./dist/templates/index.js",- "require": "./dist/templates/index.js"- },- "./migrations": {- "types": "./dist/migrations/index.d.ts",- "import": "./dist/migrations/index.js",- "require": "./dist/migrations/index.js"- },- "./dual-mode": {- "types": "./dist/dual-mode/index.d.ts",- "import": "./dist/dual-mode/index.js",- "require": "./dist/dual-mode/index.js"- },- "./loop": {- "types": "./dist/loop/index.d.ts",- "import": "./dist/loop/index.js",- "require": "./dist/loop/index.js"- }- },- "files": [- "dist"- ],- "scripts": {- "build": "tsc",- "dev": "tsc --watch",- "lint": "eslint src --ext .ts",- "test": "vitest run",- "test:watch": "vitest",- "prepublishOnly": "npm run build"- },- "keywords": [- "copilot",- "github",- "claude-flow",- "ruflo",- "agents",- "skills",- "AGENTS.md",- "agentic-ai",- "tri-mode"- ],- "author": "rUv",- "license": "MIT",- "repository": {- "type": "git",- "url": "https://github.com/ruvnet/ruflo.git",- "directory": "v3/@claude-flow/copilot"- },- "homepage": "https://github.com/ruvnet/ruflo#readme",- "bugs": {- "url": "https://github.com/ruvnet/ruflo/issues"- },- "engines": {- "node": ">=20"- },- "peerDependencies": {- "@claude-flow/cli": "^3.0.0",- "@claude-flow/codex": "^3.0.0",- "@claude-flow/guidance": "^3.0.0"- },- "peerDependenciesMeta": {- "@claude-flow/cli": { "optional": true },- "@claude-flow/codex": { "optional": true },- "@claude-flow/guidance": { "optional": true }- },- "dependencies": {- "commander": "^12.0.0",- "fs-extra": "^11.2.0",- "chalk": "^5.3.0",- "inquirer": "^9.2.0",- "yaml": "^2.4.0",- "toml": "^3.0.0",- "@iarna/toml": "^2.2.5"- },- "devDependencies": {- "@types/fs-extra": "^11.0.4",- "@types/node": "^20.0.0",- "typescript": "^5.4.0",- "vitest": "^4.0.16",- "eslint": "^8.57.0"- }-}diff --git a/v3/@claude-flow/copilot/src/cli.ts b/v3/@claude-flow/copilot/src/cli.tsdeleted file mode 100644index 0ebdf0bf31..0000000000--- a/v3/@claude-flow/copilot/src/cli.ts+++ /dev/null@@ -1,187 +0,0 @@-#!/usr/bin/env node-/**- * @claude-flow/copilot - CLI entry point- *- * Subcommands: init, auth, chat, mcp, dual, loop, doctor.- */--import { Command } from 'commander';-import chalk from 'chalk';-import fs from 'fs-extra';-import path from 'node:path';-import { CopilotInitializer } from './initializer.js';-import {- clearCachedToken,- CopilotAuthRequiredError,- CopilotClient,- getCachedToken,- resolveCredential,-} from './client/index.js';-import { registerRufloMcpWithCopilot } from './mcp/index.js';-import { createMultiModeCommand } from './dual-mode/index.js';-import { createLoopCommand } from './loop/cli.js';-import { VERSION, PACKAGE_INFO } from './index.js';--const program = new Command();--function banner(): void {- console.log(chalk.cyan.bold('\n Claude Flow Copilot'));- console.log(chalk.gray(' GitHub Copilot SDK adapter β RuFlo\n'));-}--function handleError(err: unknown, prefix?: string): never {- const msg = err instanceof Error ? err.message : String(err);- const label = prefix ? `${prefix}: ${msg}` : msg;- console.error(chalk.red.bold('\nError:'), chalk.red(label));- process.exit(1);-}--program- .name('claude-flow-copilot')- .description('GitHub Copilot SDK integration for Claude Flow / RuFlo')- .version(VERSION, '-v, --version', 'Display version number');--program- .command('init')- .description('Initialize a new Copilot project (AGENTS.md + .copilot/config.json + skills)')- .option('-t, --template <template>', 'Template (minimal|default|full|enterprise)', 'default')- .option('-s, --skills <skills>', 'Comma-separated skills list')- .option('-f, --force', 'Overwrite existing files', false)- .option('--dual', 'Generate both Copilot and Claude Code configs', false)- .option('-p, --path <path>', 'Project path', process.cwd())- .action(async (options) => {- try {- banner();- const init = new CopilotInitializer();- const skills = options.skills?.split(',').map((s: string) => s.trim()).filter(Boolean);- const result = await init.initialize({- projectPath: path.resolve(options.path),- template: options.template,- skills,- force: options.force,- dual: options.dual,- });- if (result.success) {- console.log(chalk.green.bold(' Project initialized!'));- for (const f of result.filesCreated) console.log(chalk.gray(` + ${f}`));- if (result.warnings) for (const w of result.warnings) console.log(chalk.yellow(` ! ${w}`));- } else {- console.log(chalk.red.bold(' Initialization failed'));- if (result.errors) for (const e of result.errors) console.log(chalk.red(` - ${e}`));- process.exit(1);- }- } catch (err) {- handleError(err, 'init failed');- }- });--const authCmd = program.command('auth').description('Verify Copilot credential source');-authCmd- .command('status')- .description('Check whether a credential source is available (never prints the token)')- .action(async () => {- const source = await resolveCredential();- if (source === null) {- console.log(chalk.yellow('No Copilot credential found.'));- console.log(chalk.gray('Run `gh auth login` or export GITHUB_TOKEN.'));- process.exit(1);- }- console.log(chalk.green(`Credential source: ${source}`));- const cached = await getCachedToken();- if (cached) console.log(chalk.gray(`Cached at: ~/.config/ruflo/copilot/token.json (verified ${cached.verifiedAt})`));- });-authCmd- .command('clear')- .description('Clear the cached credential handle (does NOT log out the underlying credential)')- .action(async () => {- await clearCachedToken();- console.log(chalk.green('Cleared cached credential handle.'));- });--const mcpCmd = program.command('mcp').description('MCP wiring for Copilot sessions');-mcpCmd- .command('register')- .description('Print the mcpServers JSON for a session')- .option('-p, --path <path>', 'Project path', process.cwd())- .option('--tools <list>', 'Comma-separated tool allowlist (or "*" for all)', '*')- .action(async (options) => {- const filter = options.tools === '*' ? '*' : options.tools.split(',').map((s: string) => s.trim());- const out = await registerRufloMcpWithCopilot(path.resolve(options.path), filter);- console.log(JSON.stringify(out, null, 2));- });--program- .command('chat')- .description('Send a single prompt through the governed runGoverned() pipeline')- .requiredOption('--prompt <text>', 'Prompt to send')- .option('--model <model>', 'Override the default model')- .option('--task-id <id>', 'Task ID', () => `chat-${Date.now()}`)- .action(async (options) => {- try {- const client = new CopilotClient();- const result = await client.runGoverned({- prompt: options.prompt,- taskId: options.taskId,- ...(options.model ? { sessionConfig: { model: options.model } } : {}),- onWarn: (m) => console.log(chalk.yellow(`hook: ${m}`)),- });- console.log(result.content);- } catch (err) {- if (err instanceof CopilotAuthRequiredError) {- console.error(chalk.red(err.message));- process.exit(2);- }- handleError(err, 'chat failed');- }- });--program- .command('doctor')- .description('System health check')- .action(async () => {- banner();- const checks: Array<{ name: string; ok: boolean; msg: string }> = [];-- const nodeMajor = parseInt(process.version.slice(1).split('.')[0] ?? '0', 10);- checks.push({ name: 'Node.js', ok: nodeMajor >= 20, msg: `${process.version} (>=20 required)` });-- const source = await resolveCredential();- checks.push({ name: 'Credential', ok: source !== null, msg: source ?? 'missing β run `gh auth login`' });-- const agentsMd = await fs.pathExists(path.join(process.cwd(), 'AGENTS.md'));- checks.push({ name: 'AGENTS.md', ok: agentsMd, msg: agentsMd ? 'present' : 'missing (run init)' });-- let failed = 0;- for (const c of checks) {- const icon = c.ok ? chalk.green('PASS') : chalk.red('FAIL');- console.log(` ${icon} ${chalk.white(c.name)}`);- console.log(chalk.gray(` ${c.msg}`));- if (!c.ok) failed++;- }- if (failed > 0) process.exit(1);- });--program- .command('info')- .description('Show package info')- .action(() => {- console.log(chalk.cyan.bold('\n @claude-flow/copilot'));- console.log(chalk.white(` Version: ${PACKAGE_INFO.version}`));- console.log(chalk.white(` Description: ${PACKAGE_INFO.description}`));- console.log(chalk.white(` Platform: ${PACKAGE_INFO.platform}`));- console.log(chalk.white(` Repository: ${PACKAGE_INFO.repository}\n`));- });--program.addCommand(createMultiModeCommand());-program.addCommand(createLoopCommand());--program.on('command:*', () => {- console.error(chalk.red(`Unknown command: ${program.args.join(' ')}`));- process.exit(1);-});--program.parse();-if (!process.argv.slice(2).length) {- banner();- program.outputHelp();-}diff --git a/v3/@claude-flow/copilot/src/client/auth.ts b/v3/@claude-flow/copilot/src/client/auth.tsdeleted file mode 100644index 0cb0849817..0000000000--- a/v3/@claude-flow/copilot/src/client/auth.ts+++ /dev/null@@ -1,158 +0,0 @@-/**- * @claude-flow/copilot - Authentication resolver- *- * Verifies that a Copilot CLI credential exists, WITHOUT ever- * reading, logging, persisting, or returning the raw token value.- *- * Compliance with ADR-147 Part G and the MEMORY rule- * "Never expose the user's API keys":- *- * - We only check env-var PRESENCE (not value) and `gh auth status` exit code.- * - The cache file at ~/.config/ruflo/copilot/token.json holds the SOURCE- * identifier only (e.g. `"env:GH_TOKEN"`), never the credential string.- * - The Copilot SDK / CLI reads the actual credential itself.- */--import fs from 'fs-extra';-import os from 'node:os';-import path from 'node:path';-import { spawn } from 'node:child_process';-import type { CredentialHandle, CredentialSource } from '../types.js';--const CACHE_DIR = path.join(os.homedir(), '.config', 'ruflo', 'copilot');-const CACHE_FILE = path.join(CACHE_DIR, 'token.json');-const CACHE_MODE = 0o600;--/**- * Ordered list of env vars the Copilot CLI itself checks (research Β§3.1).- * We only check `process.env[name] !== undefined && length > 0`.- */-const ENV_CANDIDATES: ReadonlyArray<{ name: string; source: CredentialSource }> = [- { name: 'COPILOT_GITHUB_TOKEN', source: 'env:COPILOT_GITHUB_TOKEN' },- { name: 'GH_TOKEN', source: 'env:GH_TOKEN' },- { name: 'GITHUB_TOKEN', source: 'env:GITHUB_TOKEN' },-];--/**- * Resolve a credential SOURCE (never the token itself).- *- * Returns one of:- * - "env:COPILOT_GITHUB_TOKEN" / "env:GH_TOKEN" / "env:GITHUB_TOKEN"- * - "gh-cli" (when `gh auth status` exits 0)- * - null (no credential available β caller surfaces COPILOT_AUTH_REQUIRED)- */-export async function resolveCredential(): Promise<CredentialSource> {- // 1. Env var presence (cheap, no subprocess).- for (const candidate of ENV_CANDIDATES) {- const raw = process.env[candidate.name];- if (raw !== undefined && raw.length > 0) {- await writeCachedHandle({ source: candidate.source, verifiedAt: nowIso() });- return candidate.source;- }- }-- // 2. gh CLI authenticated? Check exit code only β never read stdout.- const ghOk = await checkGhAuthStatus();- if (ghOk) {- await writeCachedHandle({ source: 'gh-cli', verifiedAt: nowIso() });- return 'gh-cli';- }-- return null;-}--/**- * Read the cached credential handle from disk.- *- * Returns null if the file is missing, unreadable, or malformed.- * Does NOT validate that the underlying credential is still valid;- * callers should call `resolveCredential()` for that.- */-export async function getCachedToken(): Promise<CredentialHandle | null> {- try {- if (!(await fs.pathExists(CACHE_FILE))) return null;- const raw = await fs.readJson(CACHE_FILE) as unknown;- if (!isCredentialHandle(raw)) return null;- return raw;- } catch {- return null;- }-}--/**- * Remove the cached credential handle. The actual GitHub credential- * (env var or `gh auth login` token store) is not touched β that's- * the user's GitHub CLI domain.- */-export async function clearCachedToken(): Promise<void> {- try {- await fs.remove(CACHE_FILE);- } catch {- /* file may already be gone β non-fatal */- }-}--/**- * Typed error surfaced to upstream callers when no credential resolves.- * The message NEVER contains a token; only the next action the user- * should take.- */-export class CopilotAuthRequiredError extends Error {- override readonly name = 'CopilotAuthRequiredError';- readonly code = 'COPILOT_AUTH_REQUIRED' as const;- constructor(- message = 'No GitHub Copilot credential found. Run `gh auth login` or set GITHUB_TOKEN.',- ) {- super(message);- }-}--/* ------------------------------------------------------------------ */-/* Internal helpers */-/* ------------------------------------------------------------------ */--async function writeCachedHandle(handle: CredentialHandle): Promise<void> {- try {- await fs.ensureDir(CACHE_DIR);- await fs.writeJson(CACHE_FILE, handle, { spaces: 2 });- await fs.chmod(CACHE_FILE, CACHE_MODE);- } catch {- /* cache is best-effort β failure to persist is non-fatal */- }-}--function nowIso(): string {- return new Date().toISOString();-}--function isCredentialHandle(value: unknown): value is CredentialHandle {- if (typeof value !== 'object' || value === null) return false;- const v = value as Record<string, unknown>;- const sourceOk =- v['source'] === null ||- v['source'] === 'env:COPILOT_GITHUB_TOKEN' ||- v['source'] === 'env:GH_TOKEN' ||- v['source'] === 'env:GITHUB_TOKEN' ||- v['source'] === 'gh-cli';- return sourceOk && typeof v['verifiedAt'] === 'string';-}--/**- * Run `gh auth status` and resolve to `true` iff exit code is 0.- * Stdout/stderr are deliberately discarded so we never see token fragments.- */-function checkGhAuthStatus(): Promise<boolean> {- return new Promise((resolve) => {- let proc;- try {- proc = spawn('gh', ['auth', 'status'], {- stdio: ['ignore', 'ignore', 'ignore'],- });- } catch {- resolve(false);- return;- }- proc.on('error', () => resolve(false));- proc.on('close', (code) => resolve(code === 0));- });-}diff --git a/v3/@claude-flow/copilot/src/client/chat.ts b/v3/@claude-flow/copilot/src/client/chat.tsdeleted file mode 100644index e39f2c455e..0000000000--- a/v3/@claude-flow/copilot/src/client/chat.ts+++ /dev/null@@ -1,296 +0,0 @@-/**- * @claude-flow/copilot - Chat / governed call entry point- *- * Wraps the GitHub Copilot SDK's client-session model. Two layers:- *- * - `CopilotClient`: thin SDK shim. Calls into `@github/copilot-sdk`- * when available; falls back to driving the bundled `copilot` CLI- * in `-p/--prompt` non-interactive mode when the SDK is absent.- * - `runGoverned()`: the canonical governed entry. Wires the four- * hook calls (`pre-task` β `route` β call β `post-task`) per- * ADR-147 Part F, exactly mirroring the codex adapter pattern.- */--import { spawn } from 'node:child_process';-import {- CopilotAuthRequiredError,- resolveCredential,-} from './auth.js';-import { TIER_DEFAULTS } from './models.js';-import type { CopilotMcpServerConfig, CopilotPermissionHandler } from '../types.js';--/**- * Per-message structure (OpenAI-style role/content pair).- */-export interface CopilotMessage {- role: 'system' | 'user' | 'assistant' | 'tool';- content: string;- name?: string;-}--/**- * Delta event emitted during streaming.- */-export interface StreamEvent {- type: 'assistant.message_delta' | 'assistant.message_complete' | 'tool.call' | 'session.idle';- text?: string;- toolName?: string;- toolInput?: unknown;-}--/**- * Client construction config.- */-export interface CopilotClientConfig {- /** Override the `copilot` CLI binary location. Default: PATH lookup. */- cliCommand?: string;- /** Per-call default timeout in ms. */- timeoutMs?: number;- /** Disable real subprocess calls β used by tests. */- dryRun?: boolean;-}--/**- * Per-session config (mirrors the SDK's `createSession` shape).- */-export interface CopilotSessionConfig {- model?: string;- streaming?: boolean;- permissionHandler?: CopilotPermissionHandler;- mcpServers?: Record<string, CopilotMcpServerConfig>;- systemPrompt?: string;-}--/**- * Handle returned by `createSession()`.- */-export interface CopilotSession {- config: CopilotSessionConfig;- sendAndWait(input: { prompt: string }): Promise<{ content: string; model: string }>;- disconnect(): Promise<void>;-}--/**- * Thin Copilot SDK wrapper.- *- * The SDK is imported dynamically so the rest of the package- * still type-checks and tests when `@github/copilot-sdk` is not- * installed in the local node_modules.- */-export class CopilotClient {- private readonly cliCommand: string;- private readonly timeoutMs: number;- private readonly dryRun: boolean;-- constructor(config: CopilotClientConfig = {}) {- this.cliCommand = config.cliCommand ?? 'copilot';- this.timeoutMs = config.timeoutMs ?? 5 * 60_000;- this.dryRun = config.dryRun ?? false;- }-- /**- * Create a session. Resolves auth first; throws CopilotAuthRequiredError- * if no credential source is available.- */- async createSession(config: CopilotSessionConfig = {}): Promise<CopilotSession> {- if (!this.dryRun) {- const cred = await resolveCredential();- if (cred === null) throw new CopilotAuthRequiredError();- }- const resolved: CopilotSessionConfig = {- model: config.model ?? TIER_DEFAULTS.Tier3,- streaming: config.streaming ?? false,- permissionHandler: config.permissionHandler ?? 'approve-all',- ...(config.mcpServers !== undefined ? { mcpServers: config.mcpServers } : {}),- ...(config.systemPrompt !== undefined ? { systemPrompt: config.systemPrompt } : {}),- };- return this.makeSession(resolved);- }-- /**- * Stop any background SDK resources. Currently a no-op for the- * CLI fallback; SDK-backed sessions release their JSON-RPC channel.- */- async stop(): Promise<void> {- /* no-op β process cleanup happens per-session */- }-- /**- * Run a prompt through the full governance lifecycle:- *- * pre-task β route β Copilot call β post-task- *- * Mirrors `CodexInitializer`'s lifecycle hook wiring. Hook failures- * are non-fatal (logged via `onWarn` if supplied) β only the actual- * Copilot call failure rejects the promise.- */- async runGoverned(opts: {- prompt: string;- taskId: string;- sessionConfig?: CopilotSessionConfig;- onWarn?: (message: string) => void;- }): Promise<{ content: string; model: string; taskId: string }> {- const { prompt, taskId, sessionConfig = {}, onWarn = () => undefined } = opts;-- await runHook(['pre-task', '--description', prompt], onWarn);- const recommendedModel = await runHookCapture(- ['route', '--task', prompt, '--context', 'copilot'],- onWarn,- );-- const session = await this.createSession({- ...sessionConfig,- model: extractModelFromRoute(recommendedModel) ?? sessionConfig.model ?? TIER_DEFAULTS.Tier3,- });-- try {- const result = await session.sendAndWait({ prompt });- await runHook(- ['post-task', '--task-id', taskId, '--success', 'true', '--store-results', 'true'],- onWarn,- );- return { content: result.content, model: result.model, taskId };- } catch (err) {- await runHook(- ['post-task', '--task-id', taskId, '--success', 'false'],- onWarn,- );- throw err;- } finally {- await session.disconnect();- }- }-- /* ----------------------------------------------------------- */- /* Internal session factory */- /* ----------------------------------------------------------- */-- private async makeSession(config: CopilotSessionConfig): Promise<CopilotSession> {- // Try SDK first.- const sdkSession = await this.trySdkSession(config);- if (sdkSession !== null) return sdkSession;-- // Fallback: drive the copilot CLI in -p mode.- return this.makeCliSession(config);- }-- private async trySdkSession(- config: CopilotSessionConfig,- ): Promise<CopilotSession | null> {- try {- // Dynamic import via a string variable so TypeScript does not try to- // resolve `@github/copilot-sdk` at compile time. The package is an- // optional runtime dependency β when present, we use it; when absent,- // the CLI fallback in makeCliSession() drives the bundled `copilot` CLI.- const sdkModuleName = '@github/copilot-sdk';- const sdk = (await import(sdkModuleName).catch(() => null)) as {- CopilotClient?: new () => { createSession(c: CopilotSessionConfig): Promise<CopilotSession> };- } | null;- if (!sdk?.CopilotClient) return null;- const inner = new sdk.CopilotClient();- const session = await inner.createSession(config);- return session;- } catch {- return null;- }- }-- private makeCliSession(config: CopilotSessionConfig): CopilotSession {- const cliCommand = this.cliCommand;- const timeoutMs = this.timeoutMs;- const dryRun = this.dryRun;-- return {- config,- async sendAndWait({ prompt }): Promise<{ content: string; model: string }> {- if (dryRun) {- return {- content: `[dry-run] copilot would receive: ${prompt.slice(0, 80)}`,- model: config.model ?? TIER_DEFAULTS.Tier3,- };- }- const args = ['-p', prompt, '--allow-all-tools'];- if (config.model) args.push('--model', config.model);- const stdout = await runCli(cliCommand, args, timeoutMs);- return { content: stdout, model: config.model ?? TIER_DEFAULTS.Tier3 };- },- async disconnect(): Promise<void> {- /* CLI mode is per-call; nothing to release */- },- };- }-}--/**- * Convenience constructor for callers that don't need a config.- */-export function createCopilotClient(config?: CopilotClientConfig): CopilotClient {- return new CopilotClient(config ?? {});-}--/* ------------------------------------------------------------------ */-/* Helpers */-/* ------------------------------------------------------------------ */--/**- * Run a `@claude-flow/cli` hook subcommand. Failures are non-fatal β they- * propagate to `onWarn` only. The hook ecosystem is best-effort.- */-async function runHook(args: string[], onWarn: (m: string) => void): Promise<void> {- await spawnAndCapture('npx', ['@claude-flow/cli@latest', 'hooks', ...args])- .catch((err: Error) => onWarn(`hook ${args[0] ?? '?'} failed: ${err.message}`));-}--/**- * Run a hook and return its stdout (for `route`). Returns empty string- * on failure.- */-async function runHookCapture(args: string[], onWarn: (m: string) => void): Promise<string> {- return spawnAndCapture('npx', ['@claude-flow/cli@latest', 'hooks', ...args])- .catch((err: Error) => {- onWarn(`hook ${args[0] ?? '?'} failed: ${err.message}`);- return '';- });-}--/**- * Parse `[TASK_MODEL_RECOMMENDATION] Use model="gpt-5.4-mini"` out of- * a hook's stdout. Returns null if not present.- */-export function extractModelFromRoute(stdout: string): string | null {- const m = stdout.match(/Use model="([^"]+)"/);- return m && m[1] ? m[1] : null;-}--function runCli(command: string, args: string[], timeoutMs: number): Promise<string> {- return spawnAndCapture(command, args, timeoutMs);-}--function spawnAndCapture(command: string, args: string[], timeoutMs = 60_000): Promise<string> {- return new Promise((resolve, reject) => {- let proc;- try {- proc = spawn(command, args, {- env: { ...process.env, FORCE_COLOR: '0' },- stdio: ['ignore', 'pipe', 'pipe'],- });- } catch (err) {- reject(err as Error);- return;- }- let stdout = '';- let stderr = '';- const timer = setTimeout(() => {- proc.kill('SIGTERM');- reject(new Error(`Process timed out after ${timeoutMs}ms`));- }, timeoutMs);- proc.stdout?.on('data', (d) => { stdout += d.toString(); });- proc.stderr?.on('data', (d) => { stderr += d.toString(); });- proc.on('error', (e) => { clearTimeout(timer); reject(e); });- proc.on('close', (code) => {- clearTimeout(timer);- if (code === 0) resolve(stdout);- else reject(new Error(`Exited ${code}: ${stderr || stdout}`));- });- });-}diff --git a/v3/@claude-flow/copilot/src/client/index.ts b/v3/@claude-flow/copilot/src/client/index.tsdeleted file mode 100644index de3f0d82a6..0000000000--- a/v3/@claude-flow/copilot/src/client/index.ts+++ /dev/null@@ -1,44 +0,0 @@-/**- * @claude-flow/copilot - client module barrel- */--export {- CopilotClient,- createCopilotClient,- extractModelFromRoute,-} from './chat.js';-export type {- CopilotClientConfig,- CopilotMessage,- CopilotSession,- CopilotSessionConfig,- StreamEvent,-} from './chat.js';--export {- resolveCredential,- getCachedToken,- clearCachedToken,- CopilotAuthRequiredError,-} from './auth.js';--export {- defineCopilotTool,- CopilotToolRegistry,-} from './tools.js';-export type {- CopilotTool,- CopilotToolHandler,- CopilotToolParameters,-} from './tools.js';--export {- COPILOT_MODEL_CATALOG,- TIER_DEFAULTS,- RETIRING_MODELS,- getOptimalModel,- isCatalogModel,- isRetiringModel,- getModelEntry,-} from './models.js';-export type { CopilotModelId } from './models.js';diff --git a/v3/@claude-flow/copilot/src/client/models.ts b/v3/@claude-flow/copilot/src/client/models.tsdeleted file mode 100644index c1dd48e9ed..0000000000--- a/v3/@claude-flow/copilot/src/client/models.ts+++ /dev/null@@ -1,130 +0,0 @@-/**- * @claude-flow/copilot - Model catalog and tier selection- *- * Source of truth for the Copilot SDK model IDs used by RuFlo's- * 3-tier router (ADR-026, refined in ADR-147 Part B).- *- * Only GA OpenAI GPT-family models from the Copilot catalog appear- * here. Retiring models live in RETIRING_MODELS for migration warnings.- *- * Runtime authoritative source: `client.listModels()` once the SDK- * is installed (research Β§4).- */--import type { CopilotModelEntry, CopilotTierName } from '../types.js';--/**- * Confirmed GA OpenAI models in the Copilot SDK as of 2026-06-03.- *- * Source: github.blog changelogs cited in ADR-147 references.- * Model IDs follow the lowercase-hyphen convention confirmed by- * `copilot --model gpt-5.3-codex` invocations.- */-export const COPILOT_MODEL_CATALOG = {- 'gpt-5.3-codex': {- tier: 3 as const,- multiplier: 1.0,- category: 'coding-lts' as const,- ltsUntil: '2027-02-04',- },- 'gpt-5.4-mini': {- tier: 2 as const,- multiplier: 0.33,- category: 'fast' as const,- ltsUntil: null,- },- 'gpt-5.5': {- tier: 3 as const,- multiplier: 7.5,- category: 'frontier' as const,- ltsUntil: null,- },-} as const satisfies Record<string, CopilotModelEntry>;--/**- * Default model per routing tier.- *- * Tier 1 is deterministic codemod ($0, no LLM β handled outside this map).- * Tier 2 default: gpt-5.4-mini (cheapest GA).- * Tier 3 default: gpt-5.3-codex (LTS).- * Tier 3 reasoning: gpt-5.5 (frontier, opt-in due to 7.5x multiplier).- */-export const TIER_DEFAULTS = {- Tier2: 'gpt-5.4-mini',- Tier3: 'gpt-5.3-codex',- Tier3Reasoning: 'gpt-5.5',-} as const;--/**- * Models the Copilot catalog has marked retiring on or before 2026-06-01.- *- * The router MUST NOT select from this list. Migration logic surfaces them- * to the user as warnings when an old AGENTS.md/config still references them.- */-export const RETIRING_MODELS = [- 'gpt-4.1',- 'gpt-5.2',- 'gpt-5.2-codex',- 'gpt-5.4-nano', // GA but no agent/ask/edit mode β exclude from routing-] as const;--/**- * Catalog model ID type alias- */-export type CopilotModelId = keyof typeof COPILOT_MODEL_CATALOG;--/**- * Resolve the optimal model for a routing request.- *- * - `complexity: number (0-100)` β chooses tier by complexity threshold:- * <30 β Tier 2; 30-79 β Tier 3 LTS; β₯80 β Tier 3 LTS unless- * `allowFrontier=true`, then Tier 3 Reasoning (gpt-5.5).- * - Named tier β returns the tier default directly.- *- * @param complexityOrTier Either a 0-100 score or one of the tier names.- * @param allowFrontier When true and complexity β₯ 80, returns gpt-5.5.- */-export function getOptimalModel(- complexityOrTier: number | CopilotTierName,- allowFrontier = false,-): string {- if (typeof complexityOrTier === 'string') {- if (complexityOrTier === 'Tier2') return TIER_DEFAULTS.Tier2;- if (complexityOrTier === 'Tier3Reasoning') {- return allowFrontier ? TIER_DEFAULTS.Tier3Reasoning : TIER_DEFAULTS.Tier3;- }- return TIER_DEFAULTS.Tier3;- }-- const c = clampComplexity(complexityOrTier);- if (c < 30) return TIER_DEFAULTS.Tier2;- if (c >= 80 && allowFrontier) return TIER_DEFAULTS.Tier3Reasoning;- return TIER_DEFAULTS.Tier3;-}--/**- * Returns `true` if the model id appears in the GA catalog.- */-export function isCatalogModel(modelId: string): modelId is CopilotModelId {- return Object.prototype.hasOwnProperty.call(COPILOT_MODEL_CATALOG, modelId);-}--/**- * Returns `true` if the model id is in the retiring list.- */-export function isRetiringModel(modelId: string): boolean {- return (RETIRING_MODELS as readonly string[]).includes(modelId);-}--/**- * Lookup helper returning a typed entry or `null`.- */-export function getModelEntry(modelId: string): CopilotModelEntry | null {- if (!isCatalogModel(modelId)) return null;- return COPILOT_MODEL_CATALOG[modelId];-}--function clampComplexity(value: number): number {- if (!Number.isFinite(value)) return 50;- return Math.min(100, Math.max(0, value));-}diff --git a/v3/@claude-flow/copilot/src/client/tools.ts b/v3/@claude-flow/copilot/src/client/tools.tsdeleted file mode 100644index 275e10263d..0000000000--- a/v3/@claude-flow/copilot/src/client/tools.ts+++ /dev/null@@ -1,92 +0,0 @@-/**- * @claude-flow/copilot - Tool / function-calling adapter- *- * Thin adapter over the SDK's tool-calling protocol. v1 keeps a- * platform-neutral registry so other adapters (or tests) can compose- * tools without taking a hard dependency on `@github/copilot-sdk`.- */--/**- * JSON-Schema parameter spec passed to the SDK as a tool's- * input contract. We accept any object shape β the SDK validates.- */-export type CopilotToolParameters = Record<string, unknown>;--/**- * Function called when the Copilot session invokes the tool.- */-export type CopilotToolHandler = (input: unknown) => Promise<unknown>;--/**- * Single registered tool entry.- */-export interface CopilotTool {- name: string;- description: string;- parameters: CopilotToolParameters;- handler: CopilotToolHandler;-}--/**- * Define a tool. The returned object is the shape passed to- * `createSession({ tools: [...] })`.- */-export function defineCopilotTool(- name: string,- description: string,- parameters: CopilotToolParameters,- handler: CopilotToolHandler,-): CopilotTool {- if (!/^[a-z][a-z0-9_-]*$/.test(name)) {- throw new Error(- `Invalid Copilot tool name "${name}". Use lowercase letters, digits, underscores, hyphens.`,- );- }- if (!description.trim()) {- throw new Error(`Tool "${name}" requires a non-empty description.`);- }- return { name, description, parameters, handler };-}--/**- * Per-session tool registry. Used by `CopilotClient.createSession`.- */-export class CopilotToolRegistry {- private readonly tools = new Map<string, CopilotTool>();-- register(tool: CopilotTool): void {- if (this.tools.has(tool.name)) {- throw new Error(`Tool "${tool.name}" already registered.`);- }- this.tools.set(tool.name, tool);- }-- unregister(name: string): boolean {- return this.tools.delete(name);- }-- list(): CopilotTool[] {- return Array.from(this.tools.values());- }-- get(name: string): CopilotTool | undefined {- return this.tools.get(name);- }-- size(): number {- return this.tools.size;- }-- /**- * Invoke a registered tool. Throws if unknown. Errors from the- * handler propagate β the caller (SDK shim) is responsible for- * translating them into the tool-call error shape.- */- async invoke(name: string, input: unknown): Promise<unknown> {- const tool = this.tools.get(name);- if (!tool) {- throw new Error(`Unknown Copilot tool "${name}".`);- }- return tool.handler(input);- }-}diff --git a/v3/@claude-flow/copilot/src/dual-mode/cli.ts b/v3/@claude-flow/copilot/src/dual-mode/cli.tsdeleted file mode 100644index 68278d2543..0000000000--- a/v3/@claude-flow/copilot/src/dual-mode/cli.ts+++ /dev/null@@ -1,152 +0,0 @@-/**- * @claude-flow/copilot - tri-mode CLI- *- * Provides the `claude-flow-copilot dual` subcommand. Accepts the same- * spec syntax as codex's `dual run` but admits a third `copilot:` worker- * prefix.- */--import { Command } from 'commander';-import chalk from 'chalk';-import {- MultiModeOrchestrator,- TriModeCollaborationTemplates,- type MultiModeWorkerConfig,-} from './orchestrator.js';--export function createMultiModeCommand(): Command {- const cmd = new Command('dual')- .description('Run tri-mode collaborative swarms (Claude + Codex + Copilot)')- .addCommand(createRunCommand())- .addCommand(createTemplateCommand());- return cmd;-}--function createRunCommand(): Command {- return new Command('run')- .description('Run a tri-mode collaborative swarm')- .argument('[template]', 'Pre-built template (feature, security, refactor)')- .option('-t, --template <name>', 'Pre-built template name')- .option(- '-w, --worker <spec>',- 'Worker spec "<platform>:<role>:<prompt>" (platform = claude|codex|copilot). Repeatable.',- (val: string, acc: string[]) => { acc.push(val); return acc; },- [] as string[],- )- .option('--parallel-workers', 'Run --worker specs in parallel', false)- .option('--task <description>', 'Task description for the swarm')- .option('--max-concurrent <n>', 'Maximum concurrent workers', '4')- .option('--timeout <ms>', 'Worker timeout', '300000')- .option('--namespace <name>', 'Shared memory namespace', 'collaboration')- .action(async (templateArg: string | undefined, options) => {- const orchestrator = new MultiModeOrchestrator({- projectPath: process.cwd(),- maxConcurrent: parseInt(options.maxConcurrent, 10),- timeout: parseInt(options.timeout, 10),- sharedNamespace: options.namespace,- });-- orchestrator.on('worker:started', ({ id, role, platform }) => {- const icon = platform === 'claude' ? '[claude]' : platform === 'codex' ? '[codex]' : '[copilot]';- console.log(chalk.blue(`${icon} ${role} (${id}) started`));- });- orchestrator.on('worker:completed', ({ id }) => console.log(chalk.green(`OK ${id}`)));- orchestrator.on('worker:failed', ({ id, error }) => console.log(chalk.red(`FAIL ${id}: ${error}`)));-- const specs: string[] = (options.worker as string[] | undefined) ?? [];- const templateName: string | undefined = options.template ?? templateArg;- const task = options.task ?? 'Complete the assigned task';-- let workers: MultiModeWorkerConfig[];- if (specs.length > 0) {- workers = parseWorkerSpecs(specs, options.parallelWorkers === true);- } else if (templateName) {- workers = getTemplateWorkers(templateName, task);- } else {- console.log(chalk.yellow('Provide --template <name>, [template], or --worker <spec>'));- console.log('Templates: feature, security, refactor');- console.log('Worker spec: "claude:architect:Design X" or "copilot:reviewer:Review Y"');- return;- }-- console.log(chalk.bold(`\nRunning ${workers.length} worker(s)...\n`));- const result = await orchestrator.runCollaboration(workers, task);-- console.log();- console.log(chalk.bold('Results:'));- console.log(` Status: ${result.success ? chalk.green('SUCCESS') : chalk.red('FAILED')}`);- console.log(` Duration: ${(result.totalDuration / 1000).toFixed(2)}s`);- console.log();- for (const w of result.workers) {- const status = w.status === 'completed' ? chalk.green('OK') : chalk.red('FAIL');- const icon = w.platform === 'claude' ? '[claude]' : w.platform === 'codex' ? '[codex]' : '[copilot]';- console.log(` ${status} ${icon} ${w.id} (${w.role})`);- }- if (result.errors.length > 0) {- console.log(chalk.red('\nErrors:'));- for (const e of result.errors) console.log(chalk.red(` - ${e}`));- process.exitCode = 1;- }- });-}--function createTemplateCommand(): Command {- return new Command('templates')- .description('List available collaboration templates')- .action(() => {- console.log(chalk.bold('\nTri-Mode Collaboration Templates:\n'));- console.log(chalk.cyan('feature') + ' β architect (claude) β coder (codex) β reviewer (copilot) β tester (claude)');- console.log(chalk.cyan('security') + ' β scanner (copilot/gpt-5.5) β fixer (codex)');- console.log(chalk.cyan('refactor') + ' β analyzer (claude) β refactorer (copilot) β validator (codex)');- });-}--/**- * Parse `--worker "<platform>:<role>:<prompt>"` specs.- * Accepts three platforms: claude, codex, copilot.- */-export function parseWorkerSpecs(specs: string[], parallel: boolean): MultiModeWorkerConfig[] {- const usedIds = new Set<string>();- const workers: MultiModeWorkerConfig[] = [];-- specs.forEach((spec, index) => {- const first = spec.indexOf(':');- const second = first >= 0 ? spec.indexOf(':', first + 1) : -1;- if (first < 0 || second < 0) {- throw new Error(`Invalid --worker spec "${spec}". Expected "<platform>:<role>:<prompt>".`);- }- const platformRaw = spec.slice(0, first).trim().toLowerCase();- const role = spec.slice(first + 1, second).trim() || `worker-${index + 1}`;- const prompt = spec.slice(second + 1).trim();- if (!prompt) throw new Error(`Invalid --worker spec "${spec}". Missing prompt.`);- if (platformRaw !== 'claude' && platformRaw !== 'codex' && platformRaw !== 'copilot') {- throw new Error(`Invalid platform "${platformRaw}". Use claude, codex, or copilot.`);- }- const platform = platformRaw as 'claude' | 'codex' | 'copilot';-- let id = role.replace(/\s+/g, '-');- let suffix = 2;- while (usedIds.has(id)) { id = `${role.replace(/\s+/g, '-')}-${suffix++}`; }- usedIds.add(id);-- const worker: MultiModeWorkerConfig = { id, platform, role, prompt };- const prev = workers[workers.length - 1];- if (!parallel && prev) worker.dependsOn = [prev.id];- workers.push(worker);- });-- return workers;-}--function getTemplateWorkers(template: string, task: string): MultiModeWorkerConfig[] {- switch (template) {- case 'feature':- return TriModeCollaborationTemplates.featureDevelopment(task);- case 'security':- return TriModeCollaborationTemplates.securityAudit(task);- case 'refactor':- return TriModeCollaborationTemplates.refactoring(task);- default:- throw new Error(`Unknown template: ${template}`);- }-}diff --git a/v3/@claude-flow/copilot/src/dual-mode/index.ts b/v3/@claude-flow/copilot/src/dual-mode/index.tsdeleted file mode 100644index 08ff8d5eef..0000000000--- a/v3/@claude-flow/copilot/src/dual-mode/index.ts+++ /dev/null@@ -1,16 +0,0 @@-/**- * @claude-flow/copilot - dual-mode barrel- */--export {- MultiModeOrchestrator,- TriModeCollaborationTemplates,-} from './orchestrator.js';-export type {- MultiModeConfig,- MultiModeWorkerConfig,- MultiModeWorkerResult,- CollaborationResult,-} from './orchestrator.js';--export { createMultiModeCommand, parseWorkerSpecs } from './cli.js';diff --git a/v3/@claude-flow/copilot/src/dual-mode/orchestrator.ts b/v3/@claude-flow/copilot/src/dual-mode/orchestrator.tsdeleted file mode 100644index 8e2ea814a9..0000000000--- a/v3/@claude-flow/copilot/src/dual-mode/orchestrator.ts+++ /dev/null@@ -1,363 +0,0 @@-/**- * @claude-flow/copilot - MultiModeOrchestrator- *- * Extends `DualModeOrchestrator` from @claude-flow/codex with a third- * `copilot:` platform. Does NOT rename the parent class β that would- * be a breaking change for every codex importer.- *- * The implementation falls back to a self-contained mini-orchestrator- * when the codex package is not installed, so this package's tests- * stay independent of codex.- */--import { spawn, type ChildProcess } from 'node:child_process';-import { EventEmitter } from 'node:events';-import { CopilotClient } from '../client/chat.js';-import { TIER_DEFAULTS, getOptimalModel } from '../client/models.js';-import { registerRufloMcpWithCopilot } from '../mcp/register.js';-import type { CopilotPermissionHandler } from '../types.js';--/**- * Worker config, widened to admit `copilot` as a third platform.- */-export interface MultiModeWorkerConfig {- id: string;- platform: 'claude' | 'codex' | 'copilot';- role: string;- prompt: string;- model?: string;- maxTurns?: number;- timeout?: number;- dependsOn?: string[];- /** Tier hint for Copilot routing. Ignored for other platforms. */- copilotTier?: 'Tier2' | 'Tier3' | 'Tier3Reasoning';- copilotModel?: string;- copilotOptions?: {- permissionHandler?: CopilotPermissionHandler;- streaming?: boolean;- };-}--export interface MultiModeWorkerResult {- id: string;- platform: 'claude' | 'codex' | 'copilot';- role: string;- status: 'pending' | 'running' | 'completed' | 'failed';- output?: string;- error?: string;- startedAt?: Date;- completedAt?: Date;-}--export interface MultiModeConfig {- projectPath: string;- maxConcurrent?: number;- sharedNamespace?: string;- timeout?: number;- claudeCommand?: string;- codexCommand?: string;-}--export interface CollaborationResult {- success: boolean;- workers: MultiModeWorkerResult[];- totalDuration: number;- errors: string[];-}--/**- * Multi-mode (tri-platform) orchestrator.- */-export class MultiModeOrchestrator extends EventEmitter {- protected readonly config: Required<MultiModeConfig>;- private readonly results = new Map<string, MultiModeWorkerResult>();- private readonly processes = new Map<string, ChildProcess>();- private readonly copilotClient: CopilotClient;-- constructor(config: MultiModeConfig) {- super();- this.config = {- projectPath: config.projectPath,- maxConcurrent: config.maxConcurrent ?? 4,- sharedNamespace: config.sharedNamespace ?? 'collaboration',- timeout: config.timeout ?? 5 * 60_000,- claudeCommand: config.claudeCommand ?? 'claude',- codexCommand: config.codexCommand ?? 'codex',- };- this.copilotClient = new CopilotClient({ timeoutMs: this.config.timeout });- }-- /**- * Run a swarm of workers grouped by dependency level.- */- async runCollaboration(- workers: MultiModeWorkerConfig[],- taskContext: string,- ): Promise<CollaborationResult> {- const startedAt = Date.now();- const errors: string[] = [];-- const levels = this.buildDependencyLevels(workers);- this.emit('collaboration:start', { workers: workers.length, levels: levels.length, taskContext });-- for (const level of levels) {- const promises = level.map((w) =>- this.runWorker(w).catch((err: Error) => {- errors.push(`${w.id}: ${err.message}`);- }),- );- await Promise.all(promises);- }-- return {- success: errors.length === 0,- workers: Array.from(this.results.values()),- totalDuration: Date.now() - startedAt,- errors,- };- }-- /**- * Run a single worker and record its result.- */- async runWorker(config: MultiModeWorkerConfig): Promise<void> {- const result: MultiModeWorkerResult = {- id: config.id,- platform: config.platform,- role: config.role,- status: 'running',- startedAt: new Date(),- };- this.results.set(config.id, result);- this.emit('worker:started', { id: config.id, role: config.role, platform: config.platform });-- try {- const output = await this.executeHeadless(config);- result.status = 'completed';- result.output = output;- result.completedAt = new Date();- this.emit('worker:completed', { id: config.id });- } catch (err) {- result.status = 'failed';- result.error = err instanceof Error ? err.message : String(err);- result.completedAt = new Date();- this.emit('worker:failed', { id: config.id, error: result.error });- throw err;- }- }-- /**- * Dispatch a worker to the right platform.- */- protected async executeHeadless(config: MultiModeWorkerConfig): Promise<string> {- if (config.platform === 'copilot') return this.executeCopilotHeadless(config);- return this.executeSubprocessHeadless(config);- }-- protected async executeCopilotHeadless(config: MultiModeWorkerConfig): Promise<string> {- const model =- config.copilotModel ??- (config.copilotTier ? getOptimalModel(config.copilotTier) : TIER_DEFAULTS.Tier3);- const mcpServers = await registerRufloMcpWithCopilot(this.config.projectPath);- const session = await this.copilotClient.createSession({- model,- mcpServers,- ...(config.copilotOptions?.permissionHandler- ? { permissionHandler: config.copilotOptions.permissionHandler }- : { permissionHandler: 'approve-all' }),- ...(config.copilotOptions?.streaming !== undefined- ? { streaming: config.copilotOptions.streaming }- : { streaming: false }),- });- try {- const result = await session.sendAndWait({ prompt: this.buildPrompt(config) });- return result.content;- } finally {- await session.disconnect();- }- }-- protected async executeSubprocessHeadless(config: MultiModeWorkerConfig): Promise<string> {- const cmd = config.platform === 'claude' ? this.config.claudeCommand : this.config.codexCommand;- const args =- config.platform === 'claude'- ? this.buildClaudeArgs(config)- : this.buildCodexArgs(config);-- return new Promise<string>((resolve, reject) => {- let proc;- try {- proc = spawn(cmd, args, {- cwd: this.config.projectPath,- env: { ...process.env, FORCE_COLOR: '0' },- stdio: ['ignore', 'pipe', 'pipe'],- });- } catch (err) {- reject(err as Error);- return;- }- this.processes.set(config.id, proc);- let stdout = '';- let stderr = '';- const timer = setTimeout(() => {- proc.kill('SIGTERM');- reject(new Error(`Worker ${config.id} timed out`));- }, config.timeout ?? this.config.timeout);- proc.stdout?.on('data', (d) => { stdout += d.toString(); });- proc.stderr?.on('data', (d) => { stderr += d.toString(); });- proc.on('error', (e) => { clearTimeout(timer); reject(e); });- proc.on('close', (code) => {- clearTimeout(timer);- this.processes.delete(config.id);- if (code === 0 || stdout.length > 0) resolve(stdout || stderr);- else reject(new Error(`Worker ${config.id} exited ${code}: ${stderr}`));- });- });- }-- protected buildClaudeArgs(config: MultiModeWorkerConfig): string[] {- const args = ['-p', this.buildPrompt(config), '--output-format', 'text'];- if (config.maxTurns) args.push('--max-turns', String(config.maxTurns));- if (config.model) args.push('--model', config.model);- return args;- }-- protected buildCodexArgs(config: MultiModeWorkerConfig): string[] {- const args = ['exec', '--sandbox', 'workspace-write', '--skip-git-repo-check'];- if (config.model) args.push('-m', config.model);- args.push(this.buildPrompt(config));- return args;- }-- protected buildPrompt(config: MultiModeWorkerConfig): string {- return [- `You are a ${config.role.toUpperCase()} agent in a tri-mode swarm (Claude + Codex + Copilot).`,- `Platform: ${config.platform}`,- `Working Directory: ${this.config.projectPath}`,- `Shared Memory Namespace: ${this.config.sharedNamespace}`,- '',- 'COLLABORATION PROTOCOL:',- `1. Search shared memory: npx ruflo@alpha memory search --query "..." --namespace ${this.config.sharedNamespace}`,- '2. Complete your assigned task',- `3. Store results: npx ruflo@alpha memory store --key "${config.id}-result" --value "..." --namespace ${this.config.sharedNamespace}`,- '',- 'YOUR TASK:',- config.prompt,- ].join('\n');- }-- protected buildDependencyLevels(workers: MultiModeWorkerConfig[]): MultiModeWorkerConfig[][] {- const levels: MultiModeWorkerConfig[][] = [];- const placed = new Set<string>();- while (placed.size < workers.length) {- const level: MultiModeWorkerConfig[] = [];- for (const w of workers) {- if (placed.has(w.id)) continue;- const ready = !w.dependsOn || w.dependsOn.every((d) => placed.has(d));- if (ready) level.push(w);- }- if (level.length === 0) {- for (const w of workers) if (!placed.has(w.id)) level.push(w); // break circular- }- for (const w of level) placed.add(w.id);- levels.push(level);- }- return levels;- }-- /**- * Send SIGTERM to all active subprocesses. Copilot SDK sessions- * are released by their own `disconnect()` call.- */- stopAll(): void {- for (const [id, proc] of this.processes) {- proc.kill('SIGTERM');- this.emit('worker:stopped', { id });- }- this.processes.clear();- }-}--/**- * Pre-built tri-mode collaboration templates.- */-export const TriModeCollaborationTemplates = {- featureDevelopment: (feature: string): MultiModeWorkerConfig[] => [- {- id: 'architect',- platform: 'claude',- role: 'architect',- prompt: `Design the architecture for: ${feature}. Define components, interfaces, and data flow.`,- maxTurns: 10,- },- {- id: 'coder',- platform: 'codex',- role: 'coder',- prompt: 'Implement the feature based on the architecture. Write clean, typed code.',- dependsOn: ['architect'],- maxTurns: 15,- },- {- id: 'reviewer',- platform: 'copilot',- role: 'reviewer',- prompt: 'Review the code for quality, security, and best practices.',- dependsOn: ['coder'],- copilotModel: 'gpt-5.3-codex',- },- {- id: 'tester',- platform: 'claude',- role: 'tester',- prompt: 'Write comprehensive tests. Target 80% coverage.',- dependsOn: ['reviewer'],- maxTurns: 10,- },- ],-- securityAudit: (target: string): MultiModeWorkerConfig[] => [- {- id: 'scanner',- platform: 'copilot',- role: 'security-scanner',- prompt: `Scan ${target} for security vulnerabilities. Check OWASP Top 10.`,- copilotTier: 'Tier3Reasoning',- copilotModel: 'gpt-5.5',- },- {- id: 'fixer',- platform: 'codex',- role: 'security-fixer',- prompt: 'Generate fixes for identified vulnerabilities.',- dependsOn: ['scanner'],- maxTurns: 12,- },- ],-- refactoring: (target: string): MultiModeWorkerConfig[] => [- {- id: 'analyzer',- platform: 'claude',- role: 'code-analyzer',- prompt: `Analyze ${target} for refactoring opportunities.`,- maxTurns: 8,- },- {- id: 'refactorer',- platform: 'copilot',- role: 'refactorer',- prompt: 'Execute the refactoring plan. Maintain all existing functionality.',- dependsOn: ['analyzer'],- copilotModel: 'gpt-5.3-codex',- },- {- id: 'validator',- platform: 'codex',- role: 'validator',- prompt: 'Run tests and validate the refactoring did not break anything.',- dependsOn: ['refactorer'],- maxTurns: 5,- },- ],-};diff --git a/v3/@claude-flow/copilot/src/generators/agents-md.ts b/v3/@claude-flow/copilot/src/generators/agents-md.tsdeleted file mode 100644index 67633c6f8e..0000000000--- a/v3/@claude-flow/copilot/src/generators/agents-md.ts+++ /dev/null@@ -1,247 +0,0 @@-/**- * @claude-flow/copilot - AGENTS.md generator- *- * Copilot-flavored AGENTS.md. Content is portable with the codex- * adapter (same standard); the surface emphasizes Copilot SDK- * specifics (model defaults, MCP wiring, permission handler).- */--import type { AgentsMdOptions, AgentsMdTemplate } from '../types.js';-import { BUILT_IN_SKILLS } from '../templates/index.js';--export async function generateAgentsMd(options: AgentsMdOptions): Promise<string> {- const template = options.template ?? 'default';- switch (template) {- case 'minimal':- return generateMinimal(options);- case 'full':- return generateFull(options);- case 'enterprise':- return generateEnterprise(options);- case 'default':- default:- return generateDefault(options);- }-}--function generateMinimal(options: AgentsMdOptions): string {- const {- projectName,- description = 'A Claude Flow powered project (Copilot adapter)',- buildCommand = 'npm run build',- testCommand = 'npm test',- } = options;-- return `# ${projectName}--> ${description}--## Quick Start--### Setup-\`\`\`bash-npm install && ${buildCommand}-\`\`\`--### Test-\`\`\`bash-${testCommand}-\`\`\`--## Copilot Session Defaults--| Setting | Value |-|---------|-------|-| Model | gpt-5.3-codex (LTS through 2027-02-04) |-| Permission handler | approve-all (local), custom (CI) |-| Streaming | false |-| MCP servers | ruflo |--## Agent Behavior--- Keep files under 500 lines-- No hardcoded secrets or credentials β credentials come from env or \`gh auth login\`-- Validate input at system boundaries-- Use typed interfaces for public APIs--## Security Rules--- NEVER commit .env files or secrets-- NEVER write a raw GitHub token into AGENTS.md or any committed file-- Always validate user inputs--## Links--- RuFlo: https://github.com/ruvnet/ruflo-- Copilot SDK: https://docs.github.com/en/copilot/how-tos/copilot-sdk-`;-}--function generateDefault(options: AgentsMdOptions): string {- const {- projectName,- description = 'A Claude Flow powered project with GitHub Copilot integration',- techStack = 'TypeScript, Node.js 20+',- buildCommand = 'npm run build',- testCommand = 'npm test',- devCommand = 'npm run dev',- skills = ['swarm-orchestration', 'memory-management', 'sparc-methodology', 'security-audit'],- } = options;-- const skillsTable = skills- .map((skill) => {- const info = BUILT_IN_SKILLS[skill as keyof typeof BUILT_IN_SKILLS];- return info- ? `| \`${skill}\` (MCP tool) | ${info.description} |`- : `| \`${skill}\` (MCP tool) | Custom skill |`;- })- .join('\n');-- return `# ${projectName}--> Multi-agent orchestration framework β Copilot SDK adapter--## Project Overview--${description}--**Tech Stack**: ${techStack}-**Architecture**: Domain-Driven Design with bounded contexts--## Quick Start--\`\`\`bash-npm install-${buildCommand}-${testCommand}-${devCommand}-\`\`\`--## Copilot SDK Integration--| Setting | Default | Source |-|---------|---------|--------|-| Model | \`gpt-5.3-codex\` | ADR-147 Part B (LTS) |-| Tier 2 fast | \`gpt-5.4-mini\` (0.33x) | ADR-026 |-| Tier 3 frontier | \`gpt-5.5\` (7.5x, opt-in) | ADR-147 |-| Permission handler | \`approve-all\` | Local dev only |-| Streaming | \`false\` | v1 β streaming tool calls unverified |--## MCP Wiring--Every Copilot session is created with the RuFlo MCP server registered:--\`\`\`ts-import { registerRufloMcpWithCopilot } from '@claude-flow/copilot/mcp';--const mcpServers = await registerRufloMcpWithCopilot(process.cwd());-const session = await client.createSession({ model: 'gpt-5.3-codex', mcpServers });-\`\`\`--This exposes \`memory_store\`, \`memory_search\`, \`swarm_init\`, \`hooks_route\`,-and all other ruflo MCP tools to the Copilot agent.--## Available Skills--| Skill | Use Case |-|-------|----------|-${skillsTable}--## Agent Types--| Type | Role | Use Case |-|------|------|----------|-| \`researcher\` | Requirements analysis | Understanding scope |-| \`architect\` | System design | Planning structure |-| \`coder\` | Implementation | Writing code |-| \`tester\` | Test creation | Quality assurance |-| \`reviewer\` | Code review | Security and quality |--## Execution Model--- **claude-flow** = LEDGER (coordinates: memory, routing, swarm state)-- **Copilot SDK** = EXECUTOR (writes code, runs tests, creates files)--Coordination commands return instantly β continue immediately with the next-implementation step.--## Code Standards--- Files under 500 lines-- No hardcoded secrets-- Input validation at boundaries-- Typed interfaces for public APIs-- TDD London School (mock-first) preferred--## Security--- NEVER commit secrets, credentials, or .env files-- NEVER hardcode API keys-- Credentials resolve via env var or \`gh auth login\` β see ADR-147 Part G-- The cache file at \`~/.config/ruflo/copilot/token.json\` holds only the- credential source identifier, never the token itself--## Memory System--\`\`\`bash-npx @claude-flow/cli memory store --key "pattern-name" --value "description" --namespace patterns-npx @claude-flow/cli memory search --query "search terms" --namespace patterns-\`\`\`--## Quick Commands--\`\`\`bash-npx @claude-flow/cli memory search --query "relevant patterns"-npx @claude-flow/cli hooks route --task "current task description"-npx @claude-flow/cli swarm init --topology hierarchical-\`\`\`--## Links--- RuFlo: https://github.com/ruvnet/ruflo-- Copilot SDK docs: https://docs.github.com/en/copilot/how-tos/copilot-sdk-- ADR-147: \`v3/docs/adr/ADR-147-copilot-sdk-adapter.md\`-`;-}--function generateFull(options: AgentsMdOptions): string {- const base = generateDefault(options);- return base + `\n## Tri-Mode Collaboration--This project supports running Claude Code, Codex, and Copilot workers in-parallel via the \`MultiModeOrchestrator\` (extends \`DualModeOrchestrator\`):--\`\`\`bash-npx claude-flow-copilot dual run feature --task "Add OAuth login"-\`\`\`--Pipeline: claude (architect) β codex (coder) β copilot (reviewer) β claude (tester).--## Performance Targets--| Metric | Target |-|--------|--------|-| CLI startup | <500ms |-| MCP response | <100ms |-| Route hook overhead | <50ms |-`;-}--function generateEnterprise(options: AgentsMdOptions): string {- const full = generateFull(options);- return full + `\n## Governance--Every Copilot call passes through the four governance verbs:-**compile** β **enforce** β **prove** β **evolve**. See-\`v3/@claude-flow/guidance/src/index.ts\` for the API surface.--### Compliance--- Audit log: every governed call is recorded with task ID, model, tokens, outcome.-- Cost tracking: per-session token estimates feed the \`cost-tracking\` namespace.-- Telemetry shape: GuardrailEvent (ADR-146 P5) β shared with ADR-144 and ADR-145.-`;-}--// Used by AdjacentAgentsMdTemplate routing.-export type _AgentsMdTemplateRef = AgentsMdTemplate;diff --git a/v3/@claude-flow/copilot/src/generators/config-toml.ts b/v3/@claude-flow/copilot/src/generators/config-toml.tsdeleted file mode 100644index ec6a5a3c26..0000000000--- a/v3/@claude-flow/copilot/src/generators/config-toml.ts+++ /dev/null@@ -1,177 +0,0 @@-/**- * @claude-flow/copilot - Config generator- *- * Copilot's session config is naturally JSON (per the SDK), but for- * symmetry with the codex adapter we also emit a TOML-flavored- * `.copilot/config.toml` so projects can keep one config surface.- *- * Two emitters:- * - generateCopilotConfigJson β `.copilot/config.json` (canonical)- * - generateConfigToml β `.copilot/config.toml` (compat)- */--import type { CopilotMcpServerConfig, SkillConfig } from '../types.js';--export interface CopilotConfigOptions {- model?: string;- tier2Model?: string;- tier3FrontierModel?: string;- permissionHandler?: 'approve-all' | 'deny-all' | 'custom';- streaming?: boolean;- mcpServers?: Record<string, CopilotMcpServerConfig>;- skills?: SkillConfig[];- /** Per-call timeout in ms */- timeoutMs?: number;-}--const DEFAULT_OPTIONS: Required<Omit<CopilotConfigOptions, 'mcpServers' | 'skills'>> = {- model: 'gpt-5.3-codex',- tier2Model: 'gpt-5.4-mini',- tier3FrontierModel: 'gpt-5.5',- permissionHandler: 'approve-all',- streaming: false,- timeoutMs: 300_000,-};--/**- * JSON config (canonical). This is the file `CopilotInitializer`- * writes to `.copilot/config.json`.- */-export async function generateCopilotConfigJson(- options: CopilotConfigOptions = {},-): Promise<string> {- const merged = { ...DEFAULT_OPTIONS, ...options };- const body: Record<string, unknown> = {- $schema: 'https://github.com/ruvnet/ruflo/schemas/copilot-config-v1.json',- model: merged.model,- tiers: {- tier2: merged.tier2Model,- tier3: merged.model,- tier3Reasoning: merged.tier3FrontierModel,- },- permissionHandler: merged.permissionHandler,- streaming: merged.streaming,- timeoutMs: merged.timeoutMs,- mcpServers: options.mcpServers ?? {- ruflo: {- type: 'local',- command: 'npx',- args: ['-y', 'ruflo@latest', 'mcp', 'start'],- tools: ['*'],- },- },- skills: options.skills ?? [],- };- return JSON.stringify(body, null, 2) + '\n';-}--/**- * TOML config (compat). Mirrors the codex generator's shape.- */-export async function generateConfigToml(- options: CopilotConfigOptions = {},-): Promise<string> {- const merged = { ...DEFAULT_OPTIONS, ...options };- const lines: string[] = [];- lines.push('# =============================================================================');- lines.push('# Claude Flow V3 - Copilot Configuration');- lines.push('# Generated by: @claude-flow/copilot');- lines.push('# Documentation: https://github.com/ruvnet/ruflo');- lines.push('# =============================================================================');- lines.push('');- lines.push('# Model defaults');- lines.push(`model = "${merged.model}"`);- lines.push(`tier2_model = "${merged.tier2Model}"`);- lines.push(`tier3_frontier_model = "${merged.tier3FrontierModel}"`);- lines.push('');- lines.push('# Session behavior');- lines.push(`permission_handler = "${merged.permissionHandler}"`);- lines.push(`streaming = ${merged.streaming}`);- lines.push(`timeout_ms = ${merged.timeoutMs}`);- lines.push('');-- // MCP servers- lines.push('# =============================================================================');- lines.push('# MCP Servers');- lines.push('# =============================================================================');- lines.push('');- const servers = options.mcpServers ?? {- ruflo: {- type: 'local' as const,- command: 'npx',- args: ['-y', 'ruflo@latest', 'mcp', 'start'],- tools: ['*'],- },- };- for (const [name, server] of Object.entries(servers)) {- lines.push(`[mcp_servers.${name}]`);- lines.push(`type = "${server.type}"`);- if (server.command) lines.push(`command = "${server.command}"`);- if (server.args) lines.push(`args = [${server.args.map((a) => `"${a}"`).join(', ')}]`);- if (server.url) lines.push(`url = "${server.url}"`);- if (server.tools) {- const toolsArr = Array.isArray(server.tools) ? server.tools : [server.tools];- lines.push(`tools = [${toolsArr.map((t) => `"${t}"`).join(', ')}]`);- }- if (server.timeout !== undefined) lines.push(`timeout = ${server.timeout}`);- lines.push('');- }-- // Skills- const skills = options.skills ?? [];- if (skills.length > 0) {- lines.push('# =============================================================================');- lines.push('# Skills');- lines.push('# =============================================================================');- lines.push('');- for (const skill of skills) {- lines.push('[[skills.config]]');- lines.push(`path = "${skill.path}"`);- lines.push(`enabled = ${skill.enabled ?? true}`);- lines.push('');- }- }-- return lines.join('\n');-}--/**- * Minimal config helper.- */-export async function generateMinimalConfig(options: CopilotConfigOptions = {}): Promise<string> {- const merged = { ...DEFAULT_OPTIONS, ...options };- return [- '# Claude Flow V3 - Minimal Copilot Configuration',- '',- `model = "${merged.model}"`,- `permission_handler = "${merged.permissionHandler}"`,- '',- '[mcp_servers.ruflo]',- 'type = "local"',- 'command = "npx"',- 'args = ["-y", "ruflo@latest", "mcp", "start"]',- 'tools = ["*"]',- '',- ].join('\n');-}--/**- * CI-flavored config helper.- */-export async function generateCIConfig(): Promise<string> {- return [- '# Claude Flow V3 - Copilot CI Configuration',- '',- 'model = "gpt-5.4-mini"',- 'permission_handler = "deny-all"',- 'streaming = false',- 'timeout_ms = 120000',- '',- '[mcp_servers.ruflo]',- 'type = "local"',- 'command = "npx"',- 'args = ["-y", "ruflo@latest", "mcp", "start"]',- 'tools = ["memory_search", "memory_store"]',- '',- ].join('\n');-}diff --git a/v3/@claude-flow/copilot/src/generators/index.ts b/v3/@claude-flow/copilot/src/generators/index.tsdeleted file mode 100644index f00efc9ef6..0000000000--- a/v3/@claude-flow/copilot/src/generators/index.ts+++ /dev/null@@ -1,13 +0,0 @@-/**- * @claude-flow/copilot - generators module barrel- */--export { generateAgentsMd } from './agents-md.js';-export {- generateConfigToml,- generateCopilotConfigJson,- generateMinimalConfig,- generateCIConfig,-} from './config-toml.js';-export type { CopilotConfigOptions } from './config-toml.js';-export { generateSkillMd, generateBuiltInSkill } from './skill-md.js';diff --git a/v3/@claude-flow/copilot/src/generators/skill-md.ts b/v3/@claude-flow/copilot/src/generators/skill-md.tsdeleted file mode 100644index 265b1d2ace..0000000000--- a/v3/@claude-flow/copilot/src/generators/skill-md.ts+++ /dev/null@@ -1,73 +0,0 @@-/**- * @claude-flow/copilot - SKILL.md generator- *- * Same format as the codex package's skill-md generator. Copilot- * does not invoke skills via `$name` or `/name` syntax; the skill- * is loaded as documentation and may be invoked through an MCP tool.- */--import type { SkillMdOptions } from '../types.js';--export async function generateSkillMd(options: SkillMdOptions): Promise<string> {- const {- name,- description,- version = '1.0.0',- author = 'rUv',- tags = deriveTags(name),- triggers = ['Define when to trigger this skill'],- skipWhen = ['Define when to skip this skill'],- } = options;-- const frontmatter = [- '---',- `name: ${name}`,- `description: ${description}`,- `version: ${version}`,- `author: ${author}`,- `tags: [${tags.map((t) => `"${t}"`).join(', ')}]`,- '---',- '',- ].join('\n');-- const body = [- `# ${name}`,- '',- '## Purpose',- '',- description,- '',- '## When to Trigger',- '',- ...triggers.map((t) => `- ${t}`),- '',- '## When to Skip',- '',- ...skipWhen.map((s) => `- ${s}`),- '',- '## Usage',- '',- `Invoke through the Copilot MCP bridge β \`${name}\` is registered as a tool ` +- 'when the ruflo MCP server is connected to the session.',- '',- ].join('\n');-- return frontmatter + body;-}--/**- * Generate one of the built-in skill stubs.- */-export async function generateBuiltInSkill(- name: string,-): Promise<{ skillMd: string; scripts: Record<string, string>; references: Record<string, string> }> {- const skillMd = await generateSkillMd({- name,- description: `Built-in RuFlo skill: ${name}`,- });- return { skillMd, scripts: {}, references: {} };-}--function deriveTags(name: string): string[] {- return name.split('-').filter(Boolean);-}diff --git a/v3/@claude-flow/copilot/src/index.ts b/v3/@claude-flow/copilot/src/index.tsdeleted file mode 100644index 109e696090..0000000000--- a/v3/@claude-flow/copilot/src/index.ts+++ /dev/null@@ -1,155 +0,0 @@-/**- * @claude-flow/copilot- *- * GitHub Copilot SDK platform adapter for Claude Flow / RuFlo.- * Third platform in the tri-mode collaboration system- * (Claude Code + OpenAI Codex + GitHub Copilot).- *- * See ADR-147 for the design.- *- * @packageDocumentation- */--// Types-export * from './types.js';--// Generators-export {- generateAgentsMd,- generateSkillMd,- generateConfigToml,- generateCopilotConfigJson,- generateMinimalConfig,- generateCIConfig,- generateBuiltInSkill,-} from './generators/index.js';-export type { CopilotConfigOptions } from './generators/index.js';--// Migrations-export {- migrateFromClaudeCode,- migrateFromCodex,- analyzeClaudeMd,- generateMigrationReport,- convertSkillSyntax,- convertSettingsToConfig,- FEATURE_MAPPINGS,- CODEX_TO_COPILOT_MAPPINGS,-} from './migrations/index.js';--// Validators-export {- validateAgentsMd,- validateSkillMd,- validateConfig,-} from './validators/index.js';--// Initializer-export { CopilotInitializer, initializeCopilotProject } from './initializer.js';--// Client (SDK wrapper)-export {- CopilotClient,- createCopilotClient,- extractModelFromRoute,- resolveCredential,- getCachedToken,- clearCachedToken,- CopilotAuthRequiredError,- defineCopilotTool,- CopilotToolRegistry,- COPILOT_MODEL_CATALOG,- TIER_DEFAULTS,- RETIRING_MODELS,- getOptimalModel,- isCatalogModel,- isRetiringModel,- getModelEntry,-} from './client/index.js';-export type {- CopilotClientConfig,- CopilotMessage,- CopilotSession,- CopilotSessionConfig,- StreamEvent,- CopilotTool,- CopilotToolHandler,- CopilotToolParameters,- CopilotModelId,-} from './client/index.js';--// MCP bridge-export {- registerRufloMcpWithCopilot,- buildMcpServers,- CopilotMcpBridge,-} from './mcp/index.js';-export type {- RufloMcpServerConfig,- RufloMcpToolFilter,- CopilotMcpCallEvent,-} from './mcp/index.js';--// Tri-mode collaboration-export {- MultiModeOrchestrator,- TriModeCollaborationTemplates,- createMultiModeCommand,- parseWorkerSpecs,-} from './dual-mode/index.js';-export type {- MultiModeConfig,- MultiModeWorkerConfig,- MultiModeWorkerResult,- CollaborationResult,-} from './dual-mode/index.js';--// /loop runner-export {- buildCopilotLoopPrompt,- loadLoopState,- normalizeLoopName,- requestLoopStop,- resolveLoopPaths,- runCopilotLoop,-} from './loop/index.js';-export { createLoopCommand } from './loop/cli.js';-export type {- LoopCommandResult,- LoopEvent,- LoopPaths,- LoopRunOptions,- LoopState,-} from './loop/index.js';--// Templates-export {- getTemplate,- listTemplates,- BUILT_IN_SKILLS,- TEMPLATES,- DEFAULT_SKILLS_BY_TEMPLATE,- ALL_AVAILABLE_SKILLS,- DIRECTORY_STRUCTURE,- PLATFORM_MAPPING,- GITIGNORE_ENTRIES,- AGENTS_OVERRIDE_TEMPLATE,-} from './templates/index.js';--/**- * Package version- */-export const VERSION = '3.8.0';--/**- * Package metadata- */-export const PACKAGE_INFO = {- name: '@claude-flow/copilot',- version: VERSION,- description: 'GitHub Copilot SDK integration for Claude Flow / RuFlo',- platform: 'copilot',- repository: 'https://github.com/ruvnet/ruflo',-} as const;--export default { VERSION, PACKAGE_INFO };diff --git a/v3/@claude-flow/copilot/src/initializer.ts b/v3/@claude-flow/copilot/src/initializer.tsdeleted file mode 100644index 621ab475cc..0000000000--- a/v3/@claude-flow/copilot/src/initializer.ts+++ /dev/null@@ -1,256 +0,0 @@-/**- * @claude-flow/copilot - CopilotInitializer- *- * Mirrors the CodexInitializer flow: writes AGENTS.md, .copilot/config.json,- * skill stubs, and an AGENTS.override.md to a target project.- *- * MCP wiring is done via the SDK's `mcpServers` map on every session,- * not via a one-shot `mcp add` command (see register.ts) β so this- * initializer does NOT exec a Copilot subcommand to register a server.- */--import fs from 'fs-extra';-import path from 'node:path';-import type { AgentsMdTemplate, BuiltInSkill, CopilotInitOptions, CopilotInitResult } from './types.js';-import { generateAgentsMd } from './generators/agents-md.js';-import { generateCopilotConfigJson } from './generators/config-toml.js';-import { generateBuiltInSkill, generateSkillMd } from './generators/skill-md.js';-import { AGENTS_OVERRIDE_TEMPLATE, DEFAULT_SKILLS_BY_TEMPLATE, GITIGNORE_ENTRIES } from './templates/index.js';--const BUILT_IN_SKILLS: BuiltInSkill[] = [- 'swarm-orchestration',- 'memory-management',- 'sparc-methodology',- 'security-audit',- 'performance-analysis',- 'github-automation',-];--/**- * Initialize a Copilot-flavored project. Same shape as CodexInitializer.- */-export class CopilotInitializer {- private projectPath = '';- private template: AgentsMdTemplate = 'default';- private skills: string[] = [];- private force = false;- private dual = false;-- async initialize(options: CopilotInitOptions): Promise<CopilotInitResult> {- this.projectPath = path.resolve(options.projectPath);- this.template = options.template ?? 'default';- this.skills = options.skills ?? DEFAULT_SKILLS_BY_TEMPLATE[this.template];- this.force = options.force ?? false;- this.dual = options.dual ?? false;-- const filesCreated: string[] = [];- const skillsGenerated: string[] = [];- const warnings: string[] = [];- const errors: string[] = [];-- try {- await this.validateProjectPath();- if (await this.isAlreadyInitialized()) {- if (!this.force) {- return {- success: false,- filesCreated,- skillsGenerated,- warnings: ['Project already initialized. Use --force to overwrite.'],- errors: ['Project already initialized'],- };- }- warnings.push('Overwriting existing configuration files');- }-- await this.createDirectoryStructure();-- // AGENTS.md- const agentsMd = await generateAgentsMd({- projectName: path.basename(this.projectPath),- template: this.template,- skills: this.skills,- });- const agentsMdPath = path.join(this.projectPath, 'AGENTS.md');- if (await this.shouldWrite(agentsMdPath)) {- await fs.writeFile(agentsMdPath, agentsMd, 'utf-8');- filesCreated.push('AGENTS.md');- } else {- warnings.push('AGENTS.md already exists β skipped');- }-- // .copilot/config.json- const configJson = await generateCopilotConfigJson();- const configPath = path.join(this.projectPath, '.copilot', 'config.json');- if (await this.shouldWrite(configPath)) {- await fs.writeFile(configPath, configJson, 'utf-8');- filesCreated.push('.copilot/config.json');- } else {- warnings.push('.copilot/config.json already exists β skipped');- }-- // Skills- for (const skill of this.skills) {- try {- const result = await this.generateSkill(skill);- if (result.created) {- skillsGenerated.push(skill);- filesCreated.push(result.path);- } else if (result.skipped) {- warnings.push(`Skill ${skill} already exists β skipped`);- }- } catch (err) {- const msg = err instanceof Error ? err.message : String(err);- warnings.push(`Failed to generate skill ${skill}: ${msg}`);- }- }-- // AGENTS.override.md- const overridePath = path.join(this.projectPath, '.copilot', 'AGENTS.override.md');- if (await this.shouldWrite(overridePath)) {- await fs.writeFile(overridePath, AGENTS_OVERRIDE_TEMPLATE, 'utf-8');- filesCreated.push('.copilot/AGENTS.override.md');- }-- // .gitignore- const gitignoreUpdated = await this.updateGitignore();- if (gitignoreUpdated) filesCreated.push('.gitignore (updated)');-- // Dual mode (also emit CLAUDE.md stub)- if (this.dual) {- const claudeMdPath = path.join(this.projectPath, 'CLAUDE.md');- if (await this.shouldWrite(claudeMdPath)) {- await fs.writeFile(claudeMdPath, this.generateDualClaudeMd(), 'utf-8');- filesCreated.push('CLAUDE.md');- }- }-- const result: CopilotInitResult = {- success: true,- filesCreated,- skillsGenerated,- };- if (warnings.length > 0) result.warnings = warnings;- return result;- } catch (err) {- errors.push(err instanceof Error ? err.message : 'Unknown error');- const result: CopilotInitResult = { success: false, filesCreated, skillsGenerated, errors };- if (warnings.length > 0) result.warnings = warnings;- return result;- }- }-- async dryRun(options: CopilotInitOptions): Promise<string[]> {- const skills = options.skills ?? DEFAULT_SKILLS_BY_TEMPLATE[options.template ?? 'default'];- const files = [- 'AGENTS.md',- '.copilot/config.json',- '.copilot/AGENTS.override.md',- '.gitignore (updated)',- ];- for (const s of skills) files.push(`.agents/skills/${s}/SKILL.md`);- if (options.dual) files.push('CLAUDE.md');- return files;- }-- /* ----------------------------------------------------------- */- /* helpers */- /* ----------------------------------------------------------- */-- private async validateProjectPath(): Promise<void> {- try {- await fs.ensureDir(this.projectPath);- const probe = path.join(this.projectPath, '.copilot-init-test');- await fs.writeFile(probe, 'test', 'utf-8');- await fs.remove(probe);- } catch {- throw new Error(`Cannot write to project path: ${this.projectPath}`);- }- }-- private async isAlreadyInitialized(): Promise<boolean> {- const a = await fs.pathExists(path.join(this.projectPath, 'AGENTS.md'));- const b = await fs.pathExists(path.join(this.projectPath, '.copilot', 'config.json'));- return a || b;- }-- private async shouldWrite(filePath: string): Promise<boolean> {- if (this.force) return true;- return !(await fs.pathExists(filePath));- }-- private async createDirectoryStructure(): Promise<void> {- const dirs = ['.copilot', '.copilot/loop', '.agents', '.agents/skills', '.claude-flow', '.claude-flow/data'];- for (const d of dirs) await fs.ensureDir(path.join(this.projectPath, d));- }-- private async generateSkill(name: string): Promise<{ created: boolean; skipped: boolean; path: string }> {- const skillDir = path.join(this.projectPath, '.agents', 'skills', name);- const skillPath = path.join(skillDir, 'SKILL.md');- if (!this.force && (await fs.pathExists(skillPath))) {- return { created: false, skipped: true, path: `.agents/skills/${name}/SKILL.md` };- }- await fs.ensureDir(skillDir);- let body: string;- if (BUILT_IN_SKILLS.includes(name as BuiltInSkill)) {- const res = await generateBuiltInSkill(name);- body = res.skillMd;- } else {- body = await generateSkillMd({ name, description: `Custom skill: ${name}` });- }- await fs.writeFile(skillPath, body, 'utf-8');- return { created: true, skipped: false, path: `.agents/skills/${name}/SKILL.md` };- }-- private async updateGitignore(): Promise<boolean> {- const gi = path.join(this.projectPath, '.gitignore');- let content = '';- if (await fs.pathExists(gi)) content = await fs.readFile(gi, 'utf-8');- if (content.includes('.copilot/')) return false;- const sep = content.length > 0 && !content.endsWith('\n') ? '\n\n' : '\n';- await fs.writeFile(gi, content + sep + GITIGNORE_ENTRIES.join('\n') + '\n');- return true;- }-- private generateDualClaudeMd(): string {- const name = path.basename(this.projectPath);- return `# ${name}--> This project supports both Claude Code and GitHub Copilot.--## Platform Compatibility--| Platform | Config | Skill syntax |-|---|---|---|-| Claude Code | CLAUDE.md | /skill-name |-| Copilot (this adapter) | AGENTS.md | MCP tool call |--Primary instructions are in \`AGENTS.md\`.--## Security--- NEVER commit secrets or .env files-- Credentials for Copilot come from \`gh auth login\` or env vars (see ADR-147 Part G)--Generated by @claude-flow/copilot (dual mode).-`;- }-}--/**- * Programmatic helper.- */-export async function initializeCopilotProject(- projectPath: string,- options?: Partial<CopilotInitOptions>,-): Promise<CopilotInitResult> {- const init = new CopilotInitializer();- const opts: CopilotInitOptions = {- projectPath,- template: options?.template ?? 'default',- force: options?.force ?? false,- dual: options?.dual ?? false,- };- if (options?.skills) opts.skills = options.skills;- return init.initialize(opts);-}diff --git a/v3/@claude-flow/copilot/src/loop/cli.ts b/v3/@claude-flow/copilot/src/loop/cli.tsdeleted file mode 100644index c773151c36..0000000000--- a/v3/@claude-flow/copilot/src/loop/cli.ts+++ /dev/null@@ -1,99 +0,0 @@-/**- * @claude-flow/copilot - loop CLI- */--import { Command } from 'commander';-import chalk from 'chalk';-import path from 'node:path';-import { loadLoopState, requestLoopStop, resolveLoopPaths, runCopilotLoop, type LoopState } from './index.js';--export function createLoopCommand(): Command {- const loop = new Command('loop').description('Run Copilot in a bounded /loop iteration cycle');-- loop- .command('run')- .description('Start a Copilot loop')- .argument('[prompt...]', 'Prompt for Copilot')- .option('-n, --name <name>', 'Loop name', 'default')- .option('-p, --path <path>', 'Project path', process.cwd())- .option('-i, --interval <seconds>', 'Seconds between iterations', '270')- .option('-m, --max-iterations <count>', 'Maximum iterations; 0 = unbounded', '10')- .option('--timeout <ms>', 'Per-iteration timeout', '1800000')- .option('--until-file <path>', 'Stop when this file exists')- .option('--model <model>', 'Copilot model id')- .option('--dry-run', 'Plan only β do not call Copilot')- .action(async (promptParts: string[], options) => {- try {- const prompt = promptParts.join(' ').trim();- if (!prompt) throw new Error('Prompt required (positional argument)');- const state = await runCopilotLoop({- name: options.name,- projectPath: options.path,- prompt,- model: options.model,- intervalSeconds: parseInt(options.interval, 10),- maxIterations: parseInt(options.maxIterations, 10),- timeoutMs: parseInt(options.timeout, 10),- untilFile: options.untilFile,- dryRun: options.dryRun,- onEvent: (event) => {- if (event.type === 'iteration-start') {- console.log(chalk.cyan(`iteration ${event.state.iteration} starting`));- } else if (event.type === 'iteration-complete') {- console.log(chalk.gray(event.message ?? ''));- } else if (event.type === 'sleep') {- console.log(chalk.gray(event.message));- } else if (event.type === 'error') {- console.log(chalk.red(event.message));- }- },- });- printState(state);- if (state.status === 'failed') process.exitCode = 1;- } catch (err) {- console.error(chalk.red(err instanceof Error ? err.message : String(err)));- process.exitCode = 1;- }- });-- loop- .command('status')- .description('Show loop state')- .option('-n, --name <name>', 'Loop name', 'default')- .option('-p, --path <path>', 'Project path', process.cwd())- .option('--json', 'Print raw JSON')- .action(async (options) => {- const state = await loadLoopState(path.resolve(options.path), options.name);- if (!state) {- const paths = resolveLoopPaths(path.resolve(options.path), options.name);- console.log(chalk.yellow(`No loop state found at ${paths.statePath}`));- return;- }- if (options.json) {- console.log(JSON.stringify(state, null, 2));- } else {- printState(state);- }- });-- loop- .command('stop')- .description('Request a running loop to stop')- .option('-n, --name <name>', 'Loop name', 'default')- .option('-p, --path <path>', 'Project path', process.cwd())- .action(async (options) => {- const paths = await requestLoopStop(path.resolve(options.path), options.name);- console.log(chalk.green(`Stop requested: ${paths.stopPath}`));- });-- return loop;-}--function printState(state: LoopState): void {- const color = state.status === 'failed' ? chalk.red : state.status === 'running' ? chalk.cyan : chalk.green;- console.log(color(`Loop ${state.name}: ${state.status}`));- console.log(chalk.gray(` iteration: ${state.iteration}/${state.maxIterations === 0 ? 'unbounded' : state.maxIterations}`));- console.log(chalk.gray(` interval: ${state.intervalSeconds}s`));- console.log(chalk.gray(` until: ${state.untilFile}`));- if (state.lastError) console.log(chalk.red(` last error: ${state.lastError.split('\n')[0]}`));-}diff --git a/v3/@claude-flow/copilot/src/loop/index.ts b/v3/@claude-flow/copilot/src/loop/index.tsdeleted file mode 100644index f692f961f8..0000000000--- a/v3/@claude-flow/copilot/src/loop/index.ts+++ /dev/null@@ -1,256 +0,0 @@-/**- * @claude-flow/copilot - /loop runner- *- * Mirrors the codex /loop shape exactly, swapping `codex exec`- * for `CopilotClient.runGoverned()`.- */--import { existsSync } from 'node:fs';-import fs from 'fs-extra';-import path from 'node:path';-import { CopilotClient } from '../client/chat.js';--export interface LoopRunOptions {- name?: string;- projectPath?: string;- prompt?: string;- model?: string;- intervalSeconds?: number;- maxIterations?: number;- timeoutMs?: number;- untilFile?: string;- stateDir?: string;- dryRun?: boolean;- onEvent?: (event: LoopEvent) => void;-}--export interface LoopState {- name: string;- projectPath: string;- mode: 'copilot' | 'command';- prompt?: string;- status: 'idle' | 'running' | 'stopping' | 'completed' | 'failed' | 'stopped';- iteration: number;- maxIterations: number;- intervalSeconds: number;- startedAt: string;- updatedAt: string;- lastOutput?: string;- lastError?: string;- untilFile: string;-}--export interface LoopEvent {- type: 'start' | 'iteration-start' | 'iteration-complete' | 'sleep' | 'stop' | 'complete' | 'error' | 'dry-run';- state: LoopState;- message?: string;-}--export interface LoopPaths {- stateDir: string;- statePath: string;- stopPath: string;- completePath: string;-}--export interface LoopCommandResult {- ok: boolean;- output: string;- error?: string;-}--export function normalizeLoopName(name = 'default'): string {- const normalized = name.trim().toLowerCase().replace(/[^a-z0-9_.-]+/g, '-').replace(/^-+|-+$/g, '');- return normalized || 'default';-}--export function resolveLoopPaths(projectPath: string, name = 'default', stateDir?: string): LoopPaths {- const safe = normalizeLoopName(name);- const dir = path.resolve(projectPath, stateDir ?? path.join('.copilot', 'loop'));- return {- stateDir: dir,- statePath: path.join(dir, `${safe}.json`),- stopPath: path.join(dir, `${safe}.stop`),- completePath: path.join(dir, `${safe}.complete`),- };-}--export async function loadLoopState(projectPath: string, name = 'default', stateDir?: string): Promise<LoopState | null> {- const paths = resolveLoopPaths(projectPath, name, stateDir);- if (!(await fs.pathExists(paths.statePath))) return null;- return (await fs.readJson(paths.statePath)) as LoopState;-}--export async function requestLoopStop(projectPath: string, name = 'default', stateDir?: string): Promise<LoopPaths> {- const paths = resolveLoopPaths(projectPath, name, stateDir);- await fs.ensureDir(paths.stateDir);- await fs.writeFile(paths.stopPath, new Date().toISOString());- const state = await loadLoopState(projectPath, name, stateDir);- if (state && state.status === 'running') {- state.status = 'stopping';- state.updatedAt = new Date().toISOString();- await saveState(paths.statePath, state);- }- return paths;-}--export function buildCopilotLoopPrompt(state: LoopState): string {- const max = state.maxIterations > 0 ? state.maxIterations : 'unbounded';- return [- 'You are running inside a Copilot /loop iteration.',- `Loop: ${state.name}`,- `Iteration: ${state.iteration}/${max}`,- `Project: ${state.projectPath}`,- '',- 'Task:',- state.prompt ?? '',- '',- 'Work autonomously for this iteration. Make concrete progress.',- `If the task is fully complete, create this marker file: ${state.untilFile}`,- 'If more work remains, leave the marker absent so the next iteration can continue.',- ].join('\n');-}--export async function runCopilotLoop(options: LoopRunOptions = {}): Promise<LoopState> {- const projectPath = path.resolve(options.projectPath ?? process.cwd());- const name = normalizeLoopName(options.name);- const paths = resolveLoopPaths(projectPath, name, options.stateDir);- const intervalSeconds = clampInt(options.intervalSeconds ?? 270, 0, 86_400);- const maxIterations = clampInt(options.maxIterations ?? 10, 0, 100_000);- const timeoutMs = clampInt(options.timeoutMs ?? 30 * 60_000, 1_000, 24 * 60 * 60_000);- const untilFile = path.resolve(projectPath, options.untilFile ?? paths.completePath);-- if (!options.prompt?.trim()) throw new Error('loop run requires a prompt');-- await fs.ensureDir(paths.stateDir);- await fs.remove(paths.stopPath);-- const startedAt = new Date().toISOString();- const state: LoopState = {- name,- projectPath,- mode: 'copilot',- status: 'running',- iteration: 0,- maxIterations,- intervalSeconds,- startedAt,- updatedAt: startedAt,- untilFile,- };- if (options.prompt !== undefined) state.prompt = options.prompt;-- await saveState(paths.statePath, state);- emit(options, 'start', state, `Loop ${name} started`);-- if (options.dryRun) {- state.status = 'idle';- state.updatedAt = new Date().toISOString();- await saveState(paths.statePath, state);- emit(options, 'dry-run', state, 'Dry run complete');- return state;- }-- const client = new CopilotClient({ timeoutMs });-- try {- while (shouldContinue(state, paths)) {- state.iteration += 1;- state.updatedAt = new Date().toISOString();- await saveState(paths.statePath, state);- emit(options, 'iteration-start', state, `Iteration ${state.iteration} starting`);-- const result = await runOnce(client, state, options.model);-- state.lastOutput = truncate(result.output, 8_000);- if (result.ok) {- delete state.lastError;- } else {- state.lastError = truncate(result.error ?? 'unknown error', 8_000);- }- state.updatedAt = new Date().toISOString();- await saveState(paths.statePath, state);- emit(options, 'iteration-complete', state, `Iteration ${state.iteration} ${result.ok ? 'ok' : 'failed'}`);-- if (existsSync(untilFile)) {- state.status = 'completed';- await finalize(paths, state);- emit(options, 'complete', state, `Completion marker found`);- return state;- }-- if (!result.ok) {- state.status = 'failed';- await finalize(paths, state);- emit(options, 'error', state, state.lastError);- return state;- }-- if (!shouldContinue(state, paths)) break;- emit(options, 'sleep', state, `Sleeping ${intervalSeconds}s`);- await sleep(intervalSeconds * 1000);- }-- state.status = existsSync(paths.stopPath) ? 'stopped' : 'completed';- await finalize(paths, state);- emit(options, state.status === 'stopped' ? 'stop' : 'complete', state);- return state;- } catch (err) {- state.status = 'failed';- state.lastError = err instanceof Error ? err.message : String(err);- await finalize(paths, state);- emit(options, 'error', state, state.lastError);- return state;- } finally {- await client.stop();- }-}--async function runOnce(client: CopilotClient, state: LoopState, model?: string): Promise<LoopCommandResult> {- try {- const result = await client.runGoverned({- prompt: buildCopilotLoopPrompt(state),- taskId: `${state.name}-${state.iteration}`,- ...(model ? { sessionConfig: { model } } : {}),- });- return { ok: true, output: result.content };- } catch (err) {- return { ok: false, output: '', error: err instanceof Error ? err.message : String(err) };- }-}--async function finalize(paths: LoopPaths, state: LoopState): Promise<void> {- state.updatedAt = new Date().toISOString();- await saveState(paths.statePath, state);-}--async function saveState(p: string, state: LoopState): Promise<void> {- await fs.ensureDir(path.dirname(p));- await fs.writeJson(p, state, { spaces: 2 });-}--function shouldContinue(state: LoopState, paths: LoopPaths): boolean {- if (state.status !== 'running') return false;- if (existsSync(paths.stopPath)) return false;- if (existsSync(state.untilFile)) return false;- return state.maxIterations === 0 || state.iteration < state.maxIterations;-}--function emit(options: LoopRunOptions, type: LoopEvent['type'], state: LoopState, message?: string): void {- const event: LoopEvent = { type, state: { ...state } };- if (message !== undefined) event.message = message;- options.onEvent?.(event);-}--function clampInt(value: number, min: number, max: number): number {- if (!Number.isFinite(value)) return min;- return Math.min(max, Math.max(min, Math.floor(value)));-}--function truncate(s: string, max: number): string {- return s.length <= max ? s : `${s.slice(0, max)}\n...[truncated]`;-}--function sleep(ms: number): Promise<void> {- return new Promise((r) => setTimeout(r, ms));-}diff --git a/v3/@claude-flow/copilot/src/mcp/bridge.ts b/v3/@claude-flow/copilot/src/mcp/bridge.tsdeleted file mode 100644index e9a332c3e6..0000000000--- a/v3/@claude-flow/copilot/src/mcp/bridge.ts+++ /dev/null@@ -1,65 +0,0 @@-/**- * @claude-flow/copilot - MCP bridge / call audit- *- * Per-session bookkeeping for MCP tool invocations made by a Copilot- * session. The orchestrator reads `events()` after a run to feed the- * shared telemetry sink described in ADR-146 P5.- */--export interface CopilotMcpCallEvent {- /** Stable session ID assigned at bridge creation */- sessionId: string;- /** MCP server name from the session's `mcpServers` map */- serverId: string;- /** Fully-qualified tool name */- toolName: string;- /** Anonymized input payload β caller decides what to log */- inputSummary?: string;- /** Whether the tool returned ok or threw */- outcome: 'allowed' | 'denied' | 'errored';- /** Optional error message (sanitized β never raw token-bearing payloads) */- error?: string;- /** Unix-ms timestamp */- ts: number;-}--/**- * Per-session collector. Cheap; one instance per `createSession()` call.- */-export class CopilotMcpBridge {- private readonly events_: CopilotMcpCallEvent[] = [];-- constructor(public readonly sessionId: string) {}-- /**- * Record a tool call event.- */- record(event: Omit<CopilotMcpCallEvent, 'sessionId' | 'ts'>): void {- this.events_.push({- sessionId: this.sessionId,- ts: Date.now(),- ...event,- });- }-- /**- * Return a snapshot of all events recorded so far.- */- events(): readonly CopilotMcpCallEvent[] {- return [...this.events_];- }-- /**- * Total event count.- */- count(): number {- return this.events_.length;- }-- /**- * Drop all recorded events. Used between iterations of `/loop`.- */- clear(): void {- this.events_.length = 0;- }-}diff --git a/v3/@claude-flow/copilot/src/mcp/index.ts b/v3/@claude-flow/copilot/src/mcp/index.tsdeleted file mode 100644index a54aa363e5..0000000000--- a/v3/@claude-flow/copilot/src/mcp/index.ts+++ /dev/null@@ -1,15 +0,0 @@-/**- * @claude-flow/copilot - mcp module barrel- */--export {- registerRufloMcpWithCopilot,- buildMcpServers,-} from './register.js';-export type {- RufloMcpServerConfig,- RufloMcpToolFilter,-} from './register.js';--export { CopilotMcpBridge } from './bridge.js';-export type { CopilotMcpCallEvent } from './bridge.js';diff --git a/v3/@claude-flow/copilot/src/mcp/register.ts b/v3/@claude-flow/copilot/src/mcp/register.tsdeleted file mode 100644index 548db8824a..0000000000--- a/v3/@claude-flow/copilot/src/mcp/register.ts+++ /dev/null@@ -1,69 +0,0 @@-/**- * @claude-flow/copilot - MCP registration helpers- *- * Builds the `mcpServers` map shape required by the Copilot SDK's- * `createSession({ mcpServers })` (research Β§6.8).- *- * The Copilot backend never executes MCP tools β MCP servers run- * **client-side** as subprocesses on the user's machine. This means- * the RuFlo MCP server (`npx ruflo@latest mcp start`) keeps direct- * access to local AgentDB, hooks, and the filesystem.- */--import type { CopilotMcpServerConfig } from '../types.js';--/**- * Default tool filter β `['*']` means "expose every tool the ruflo- * MCP server registers". Passing an explicit array tightens the surface.- */-export type RufloMcpToolFilter = string[] | '*';--/**- * `mcpServers` value Copilot understands for the ruflo entry.- */-export interface RufloMcpServerConfig extends CopilotMcpServerConfig {- type: 'local';- command: 'npx';- args: string[];-}--/**- * Build the `mcpServers` object you pass to `createSession()`.- *- * @param projectPath The project root β surfaced via `CLAUDE_FLOW_CONFIG` env.- * @param toolFilter `'*'` or an array of allowed tool names.- */-export async function registerRufloMcpWithCopilot(- projectPath: string,- toolFilter: RufloMcpToolFilter = '*',-): Promise<Record<string, RufloMcpServerConfig>> {- const tools = toolFilter === '*' ? ['*'] : [...toolFilter];- return {- ruflo: {- type: 'local',- command: 'npx',- args: ['-y', 'ruflo@latest', 'mcp', 'start'],- tools,- env: {- CLAUDE_FLOW_CONFIG: `${projectPath}/claude-flow.config.json`,- },- cwd: projectPath,- timeout: 120_000,- },- };-}--/**- * Convenience: merge ruflo's MCP entry with caller-supplied additional servers.- *- * Caller's entries take precedence on name collision (so projects can- * override ruflo's defaults without surprising fallthrough).- */-export async function buildMcpServers(- projectPath: string,- extra: Record<string, CopilotMcpServerConfig> = {},- toolFilter: RufloMcpToolFilter = '*',-): Promise<Record<string, CopilotMcpServerConfig>> {- const ruflo = await registerRufloMcpWithCopilot(projectPath, toolFilter);- return { ...ruflo, ...extra };-}diff --git a/v3/@claude-flow/copilot/src/migrations/index.ts b/v3/@claude-flow/copilot/src/migrations/index.tsdeleted file mode 100644index d189414168..0000000000--- a/v3/@claude-flow/copilot/src/migrations/index.ts+++ /dev/null@@ -1,234 +0,0 @@-/**- * @claude-flow/copilot - Migrations- *- * Convert CLAUDE.md (Claude Code) and codex AGENTS.md/.agents/config.toml- * artifacts into Copilot-flavored AGENTS.md + .copilot/config.json.- *- * Per research Β§8.- */--import fs from 'fs-extra';-import path from 'node:path';-import type { FeatureMapping, MigrationOptions, MigrationResult } from '../types.js';-import { generateAgentsMd } from '../generators/agents-md.js';-import { generateCopilotConfigJson } from '../generators/config-toml.js';--/**- * Feature mappings: Claude Code β Copilot.- */-export const FEATURE_MAPPINGS: FeatureMapping[] = [- { source: 'CLAUDE.md', copilot: 'AGENTS.md', status: 'mapped', notes: 'Content portable' },- { source: 'CLAUDE.local.md', copilot: '.copilot/AGENTS.override.md', status: 'mapped' },- { source: 'settings.json', copilot: '.copilot/config.json', status: 'mapped', notes: 'JSON β JSON, model field changes' },- { source: '/skill-name', copilot: 'MCP tool call', status: 'mapped', notes: 'Skills become registered MCP tools' },- { source: 'hooks system', copilot: 'pre/post-task hook calls', status: 'mapped' },- { source: 'MCP servers', copilot: 'mcpServers in session config', status: 'mapped' },- { source: 'TodoWrite', copilot: 'Custom task-tracking MCP tool', status: 'partial' },-];--/**- * Feature mappings: Codex β Copilot.- */-export const CODEX_TO_COPILOT_MAPPINGS: FeatureMapping[] = [- { source: 'AGENTS.md (codex)', copilot: 'AGENTS.md (copilot)', status: 'mapped', notes: 'Direct copy; content portable' },- { source: '.agents/config.toml', copilot: '.copilot/config.json', status: 'mapped', notes: 'TOML β JSON' },- { source: '$skill-name', copilot: 'MCP tool call', status: 'mapped' },- { source: '[mcp_servers.ruflo]', copilot: 'mcpServers.ruflo', status: 'mapped' },- { source: '.codex/loop/', copilot: '.copilot/loop/', status: 'mapped', notes: 'Same state schema; mode field changes' },- { source: 'codex exec subprocess', copilot: 'SDK session.sendAndWait()', status: 'mapped' },- { source: 'approval_policy = "never"', copilot: 'permissionHandler: "approve-all"', status: 'mapped' },- { source: 'sandbox_mode', copilot: 'CLI-level only β no SDK equivalent', status: 'unsupported' },-];--/**- * Lightweight analysis of a CLAUDE.md β used by the `analyze-only` path.- */-export interface ClaudeMdAnalysis {- title: string;- sections: string[];- skills: string[];- hooks: string[];- customInstructions: string[];- warnings: string[];-}--export async function analyzeClaudeMd(content: string): Promise<ClaudeMdAnalysis> {- const lines = content.split('\n');- const titleMatch = content.match(/^#\s+(.+)$/m);- const sections: string[] = [];- const skills = new Set<string>();- const hooks = new Set<string>();- const customInstructions: string[] = [];- const warnings: string[] = [];-- for (const line of lines) {- const sec = line.match(/^##\s+(.+)$/);- if (sec && sec[1]) sections.push(sec[1].trim());- const skill = line.match(/\/([a-z][a-z0-9-]+)\b/);- if (skill && skill[1]) skills.add(skill[1]);- const hook = line.match(/hooks\s+([a-z][a-z0-9-]+)/i);- if (hook && hook[1]) hooks.add(hook[1]);- if (line.trim().startsWith('- ') && line.length < 200) customInstructions.push(line.trim().slice(2));- }-- if (sections.length === 0) warnings.push('No sections found β AGENTS.md needs at least one ## heading');- if (skills.size > 0) warnings.push(`${skills.size} slash-skill references will become MCP tool calls`);-- return {- title: titleMatch && titleMatch[1] ? titleMatch[1] : 'Untitled Project',- sections,- skills: Array.from(skills),- hooks: Array.from(hooks),- customInstructions,- warnings,- };-}--/**- * Migrate a Claude Code project to Copilot.- */-export async function migrateFromClaudeCode(options: MigrationOptions): Promise<MigrationResult> {- const { sourcePath, targetPath, generateSkills = false } = options;- const warnings: string[] = [];-- let claudeMd: string;- try {- claudeMd = await fs.readFile(sourcePath, 'utf-8');- } catch (err) {- return { success: false, warnings: [`Cannot read source: ${(err as Error).message}`] };- }-- const analysis = await analyzeClaudeMd(claudeMd);- const targetDir = path.resolve(targetPath);- await fs.ensureDir(targetDir);- await fs.ensureDir(path.join(targetDir, '.copilot'));-- // AGENTS.md- const agentsMd = await generateAgentsMd({- projectName: analysis.title,- description: 'Migrated from CLAUDE.md',- template: 'default',- skills: analysis.skills,- });- const agentsMdPath = path.join(targetDir, 'AGENTS.md');- await fs.writeFile(agentsMdPath, agentsMd, 'utf-8');-- // .copilot/config.json- const configJson = await generateCopilotConfigJson();- const configPath = path.join(targetDir, '.copilot', 'config.json');- await fs.writeFile(configPath, configJson, 'utf-8');-- if (generateSkills && analysis.skills.length > 0) {- warnings.push(- `${analysis.skills.length} skill(s) detected β register them as MCP tools via @claude-flow/copilot's defineCopilotTool`,- );- }-- return {- success: true,- agentsMdPath,- configPath,- mappings: FEATURE_MAPPINGS,- warnings,- };-}--/**- * Migrate a Codex project to Copilot.- */-export async function migrateFromCodex(options: MigrationOptions): Promise<MigrationResult> {- const { sourcePath, targetPath } = options;- const warnings: string[] = [];-- const sourceDir = path.resolve(path.dirname(sourcePath));- const targetDir = path.resolve(targetPath);- await fs.ensureDir(targetDir);- await fs.ensureDir(path.join(targetDir, '.copilot'));-- // AGENTS.md (direct copy if present)- const sourceAgentsMd = path.join(sourceDir, 'AGENTS.md');- const targetAgentsMd = path.join(targetDir, 'AGENTS.md');- if (await fs.pathExists(sourceAgentsMd)) {- await fs.copy(sourceAgentsMd, targetAgentsMd, { overwrite: true });- } else {- warnings.push('Source AGENTS.md not found β generating default');- await fs.writeFile(- targetAgentsMd,- await generateAgentsMd({ projectName: path.basename(targetDir), template: 'default' }),- 'utf-8',- );- }-- // .copilot/config.json from defaults (TOMLβJSON parse is out of v1 scope)- const codexConfig = path.join(sourceDir, '.agents', 'config.toml');- if (await fs.pathExists(codexConfig)) {- warnings.push('Codex .agents/config.toml found β converted to defaults; manual review recommended');- }- const configJson = await generateCopilotConfigJson();- const configPath = path.join(targetDir, '.copilot', 'config.json');- await fs.writeFile(configPath, configJson, 'utf-8');-- // .codex/loop β .copilot/loop (state schema-compatible; mode flag flipped)- const codexLoop = path.join(sourceDir, '.codex', 'loop');- const copilotLoop = path.join(targetDir, '.copilot', 'loop');- if (await fs.pathExists(codexLoop)) {- await fs.copy(codexLoop, copilotLoop, { overwrite: true });- warnings.push('Loop state copied β manually flip mode field from "codex" to "copilot" in JSON files');- }-- return {- success: true,- agentsMdPath: targetAgentsMd,- configPath,- mappings: CODEX_TO_COPILOT_MAPPINGS,- warnings,- };-}--/**- * Render a migration report. Same shape codex uses.- */-export function generateMigrationReport(result: MigrationResult): string {- const lines: string[] = ['# Migration Report', ''];- lines.push(`**Status**: ${result.success ? 'SUCCESS' : 'FAILED'}`);- if (result.agentsMdPath) lines.push(`**AGENTS.md**: ${result.agentsMdPath}`);- if (result.configPath) lines.push(`**Config**: ${result.configPath}`);- if (result.skillsCreated && result.skillsCreated.length > 0) {- lines.push('', '## Skills');- for (const s of result.skillsCreated) lines.push(`- ${s}`);- }- if (result.warnings && result.warnings.length > 0) {- lines.push('', '## Warnings');- for (const w of result.warnings) lines.push(`- ${w}`);- }- if (result.mappings && result.mappings.length > 0) {- lines.push('', '## Feature Mappings');- for (const m of result.mappings) {- lines.push(`- ${m.source} β ${m.copilot} (${m.status})${m.notes ? ': ' + m.notes : ''}`);- }- }- return lines.join('\n');-}--/**- * Convert `/skill-name` references to `$skill-name` (codex convention) β- * not strictly needed for Copilot but the utility is exported for- * downstream callers that mix codex + copilot artifacts.- */-export function convertSkillSyntax(content: string): string {- return content.replace(/(^|[^a-zA-Z0-9])\/([a-z][a-z0-9-]+)\b/g, '$1$$$2');-}--/**- * Convert a Claude Code settings.json into a Copilot config object.- * Returns the JSON object (not stringified).- */-export function convertSettingsToConfig(settings: Record<string, unknown>): Record<string, unknown> {- const out: Record<string, unknown> = {- model: (settings['model'] as string | undefined) ?? 'gpt-5.3-codex',- permissionHandler: 'approve-all',- streaming: false,- };- if (settings['mcpServers']) out['mcpServers'] = settings['mcpServers'];- return out;-}diff --git a/v3/@claude-flow/copilot/src/templates/index.ts b/v3/@claude-flow/copilot/src/templates/index.tsdeleted file mode 100644index 2f1332f0ef..0000000000--- a/v3/@claude-flow/copilot/src/templates/index.ts+++ /dev/null@@ -1,120 +0,0 @@-/**- * @claude-flow/copilot - Built-in templates and skills- */--import type { AgentsMdTemplate, BuiltInSkill } from '../types.js';--export const BUILT_IN_SKILLS: Record<BuiltInSkill, { name: string; description: string; category: string }> = {- 'swarm-orchestration': {- name: 'Swarm Orchestration',- description: 'Multi-agent task coordination',- category: 'coordination',- },- 'memory-management': {- name: 'Memory Management',- description: 'Pattern storage and retrieval',- category: 'memory',- },- 'sparc-methodology': {- name: 'SPARC Methodology',- description: 'Structured development workflow',- category: 'workflow',- },- 'security-audit': {- name: 'Security Audit',- description: 'Security scanning and CVE detection',- category: 'security',- },- 'performance-analysis': {- name: 'Performance Analysis',- description: 'Profiling and optimization',- category: 'performance',- },- 'github-automation': {- name: 'GitHub Automation',- description: 'CI/CD and PR management',- category: 'automation',- },-};--export const TEMPLATES: Record<AgentsMdTemplate, { name: string; description: string; skillCount: number }> = {- minimal: { name: 'Minimal', description: 'Basic setup with essential skills only', skillCount: 2 },- default: { name: 'Default', description: 'Standard setup with common skills', skillCount: 4 },- full: { name: 'Full', description: 'Complete setup with all available skills', skillCount: 6 },- enterprise: { name: 'Enterprise', description: 'Full setup with governance', skillCount: 6 },-};--export function getTemplate(name: AgentsMdTemplate): typeof TEMPLATES[AgentsMdTemplate] {- return TEMPLATES[name];-}--export function listTemplates(): Array<{ name: AgentsMdTemplate; description: string; skillCount: number }> {- return Object.entries(TEMPLATES).map(([name, info]) => ({- name: name as AgentsMdTemplate,- description: info.description,- skillCount: info.skillCount,- }));-}--export const ALL_AVAILABLE_SKILLS: string[] = [- 'swarm-orchestration',- 'memory-management',- 'sparc-methodology',- 'security-audit',- 'performance-analysis',- 'github-automation',-];--export const DEFAULT_SKILLS_BY_TEMPLATE: Record<AgentsMdTemplate, string[]> = {- minimal: ['swarm-orchestration', 'memory-management'],- default: ['swarm-orchestration', 'memory-management', 'sparc-methodology', 'security-audit'],- full: ALL_AVAILABLE_SKILLS,- enterprise: ALL_AVAILABLE_SKILLS,-};--export const DIRECTORY_STRUCTURE = {- root: { 'AGENTS.md': 'Main project instructions for Copilot' },- '.copilot': {- 'config.json': 'Copilot SDK session defaults',- 'AGENTS.override.md': 'Local instruction overrides (gitignored)',- 'loop/': '/loop runner state',- },- '.agents': {- 'skills/': 'Shared skill library (compatible with Codex)',- },-};--export const PLATFORM_MAPPING = {- claudeCode: { configFile: 'CLAUDE.md', skillInvocation: '/skill-name' },- codex: { configFile: 'AGENTS.md', skillInvocation: '$skill-name' },- copilot: { configFile: 'AGENTS.md', skillInvocation: 'MCP tool call' },-};--export const GITIGNORE_ENTRIES = [- '# Copilot local configuration',- '.copilot/',- '',- '# Claude Flow runtime data',- '.claude-flow/data/',- '.claude-flow/logs/',- '',- '# Environment variables',- '.env',- '.env.local',- '.env.*.local',-];--export const AGENTS_OVERRIDE_TEMPLATE = `# Local Copilot Development Overrides--## Session defaults-- Model: gpt-5.3-codex-- Permission handler: approve-all (local dev only)-- Streaming: false--## Personal preferences-[Add your specific preferences here]--## Notes-This file is gitignored and contains local-only settings.-Tokens MUST come from environment or \`gh auth login\` β never write a raw token here.-`;diff --git a/v3/@claude-flow/copilot/src/types.ts b/v3/@claude-flow/copilot/src/types.tsdeleted file mode 100644index 173142dff5..0000000000--- a/v3/@claude-flow/copilot/src/types.ts+++ /dev/null@@ -1,202 +0,0 @@-/**- * @claude-flow/copilot - Type Definitions- *- * GitHub Copilot SDK platform adapter types for RuFlo / Claude Flow.- * Mirrors @claude-flow/codex types where shapes are platform-agnostic.- */--/**- * AGENTS.md template types- */-export type AgentsMdTemplate = 'default' | 'minimal' | 'full' | 'enterprise';--/**- * Copilot session permission handler behavior- */-export type CopilotPermissionHandler = 'approve-all' | 'deny-all' | 'custom';--/**- * Routing tier classification for Copilot models- */-export type CopilotModelTier = 2 | 3;--/**- * Tier names exposed to callers- */-export type CopilotTierName = 'Tier2' | 'Tier3' | 'Tier3Reasoning';--/**- * Single entry in the Copilot model catalog- */-export interface CopilotModelEntry {- /** Tier in ADR-026's 3-tier routing table */- tier: CopilotModelTier;- /** AI credits multiplier per call (1.0 = base, 0.33 = mini, 7.5 = frontier) */- multiplier: number;- /** Coarse category for human-readable selection */- category: 'fast' | 'coding-lts' | 'frontier' | 'retiring';- /** ISO date string LTS guarantee expires; null if not LTS */- ltsUntil: string | null;-}--/**- * AGENTS.md generator options (mirror of codex equivalent)- */-export interface AgentsMdOptions {- projectName: string;- description?: string;- techStack?: string;- buildCommand?: string;- testCommand?: string;- devCommand?: string;- template?: AgentsMdTemplate;- skills?: string[];- customSections?: Record<string, string>;-}--/**- * SKILL.md generator options (identical shape to codex)- */-export interface SkillMdOptions {- name: string;- description: string;- version?: string;- author?: string;- tags?: string[];- triggers?: string[];- skipWhen?: string[];-}--/**- * Skill path config used by initializer and config generator- */-export interface SkillConfig {- path: string;- enabled?: boolean;-}--/**- * MCP server descriptor used by Copilot session config- *- * Copilot's `mcpServers` map (see research Β§6.8) supports both- * `type: 'local'` (stdio child process) and `type: 'remote'` (HTTP).- */-export interface CopilotMcpServerConfig {- type: 'local' | 'remote';- command?: string;- args?: string[];- url?: string;- headers?: Record<string, string>;- tools?: string[] | '*';- env?: Record<string, string>;- cwd?: string;- timeout?: number;-}--/**- * Initializer options- */-export interface CopilotInitOptions {- projectPath: string;- template?: AgentsMdTemplate;- skills?: string[];- force?: boolean;- /** Generate both Copilot and Claude Code surfaces */- dual?: boolean;-}--/**- * Initializer result- */-export interface CopilotInitResult {- success: boolean;- filesCreated: string[];- skillsGenerated: string[];- warnings?: string[];- errors?: string[];-}--/**- * Migration options (mirror of codex)- */-export interface MigrationOptions {- sourcePath: string;- targetPath: string;- preserveComments?: boolean;- generateSkills?: boolean;-}--/**- * Migration result- */-export interface MigrationResult {- success: boolean;- agentsMdPath?: string;- skillsCreated?: string[];- configPath?: string;- mappings?: FeatureMapping[];- warnings?: string[];-}--/**- * Feature mapping for cross-platform migration tracking- */-export interface FeatureMapping {- source: string;- copilot: string;- status: 'mapped' | 'partial' | 'unsupported';- notes?: string;-}--/**- * Validation result envelope- */-export interface ValidationResult {- valid: boolean;- errors: ValidationError[];- warnings: ValidationWarning[];-}--export interface ValidationError {- path: string;- message: string;- line?: number;- column?: number;-}--export interface ValidationWarning {- path: string;- message: string;- suggestion?: string;-}--/**- * Built-in skill names (mirror of codex set)- */-export type BuiltInSkill =- | 'swarm-orchestration'- | 'memory-management'- | 'sparc-methodology'- | 'security-audit'- | 'performance-analysis'- | 'github-automation';--/**- * Credential source identifier β NEVER the raw token.- * Cached at ~/.config/ruflo/copilot/token.json (chmod 600).- * See ADR-147 Part G.- */-export type CredentialSource =- | 'env:COPILOT_GITHUB_TOKEN'- | 'env:GH_TOKEN'- | 'env:GITHUB_TOKEN'- | 'gh-cli'- | null;--/**- * Cached credential handle (no token value, only source identifier)- */-export interface CredentialHandle {- source: CredentialSource;- verifiedAt: string;-}diff --git a/v3/@claude-flow/copilot/src/validators/index.ts b/v3/@claude-flow/copilot/src/validators/index.tsdeleted file mode 100644index c4f8b450e8..0000000000--- a/v3/@claude-flow/copilot/src/validators/index.ts+++ /dev/null@@ -1,164 +0,0 @@-/**- * @claude-flow/copilot - Validators- *- * Stripped-down validators tuned for the Copilot surface. Reuses the- * same shape as the codex validators (ValidationResult / errors /- * warnings) so downstream tooling can treat them interchangeably.- */--import type { ValidationError, ValidationResult, ValidationWarning } from '../types.js';-import { isCatalogModel, isRetiringModel } from '../client/models.js';--const SECRET_PATTERNS: Array<{ pattern: RegExp; name: string }> = [- { pattern: /ghp_[a-zA-Z0-9]{36}/, name: 'GitHub personal access token' },- { pattern: /gho_[a-zA-Z0-9]{36}/, name: 'GitHub OAuth token' },- { pattern: /github_pat_[a-zA-Z0-9_]{22,}/, name: 'GitHub fine-grained token' },- { pattern: /sk-[a-zA-Z0-9]{32,}/, name: 'OpenAI-style API key' },- { pattern: /sk-ant-[a-zA-Z0-9-]{32,}/, name: 'Anthropic API key' },- { pattern: /-----BEGIN (?:RSA |EC |DSA )?PRIVATE KEY-----/, name: 'Private key' },-];--const REQUIRED_AGENTS_SECTIONS = ['Setup', 'Security'];--/**- * Validate an AGENTS.md file authored for the Copilot adapter.- */-export async function validateAgentsMd(content: string): Promise<ValidationResult> {- const errors: ValidationError[] = [];- const warnings: ValidationWarning[] = [];- const lines = content.split('\n');-- if (!content.startsWith('# ')) {- errors.push({- path: 'AGENTS.md',- message: 'AGENTS.md should start with a level-1 heading (# Title)',- line: 1,- });- }-- if (content.trim().length < 50) {- errors.push({- path: 'AGENTS.md',- message: 'AGENTS.md content is too short β add meaningful instructions',- line: 1,- });- }-- const lowerContent = content.toLowerCase();- for (const section of REQUIRED_AGENTS_SECTIONS) {- if (!lowerContent.includes(section.toLowerCase())) {- warnings.push({- path: 'AGENTS.md',- message: `Missing recommended section: ## ${section}`,- suggestion: `Add a "## ${section}" section`,- });- }- }-- scanForSecrets(lines, 'AGENTS.md', errors);-- return { valid: errors.length === 0, errors, warnings };-}--/**- * Validate a SKILL.md file. Same constraints the codex validator uses.- */-export async function validateSkillMd(content: string): Promise<ValidationResult> {- const errors: ValidationError[] = [];- const warnings: ValidationWarning[] = [];- const lines = content.split('\n');-- if (!content.startsWith('---')) {- errors.push({ path: 'SKILL.md', message: 'SKILL.md must start with YAML frontmatter', line: 1 });- return { valid: false, errors, warnings };- }-- const closeIndex = lines.findIndex((l, i) => i > 0 && l.trim() === '---');- if (closeIndex === -1) {- errors.push({ path: 'SKILL.md', message: 'YAML frontmatter not properly closed', line: 1 });- return { valid: false, errors, warnings };- }-- // Cheap key checks against the frontmatter.- const frontmatter = lines.slice(1, closeIndex).join('\n');- if (!/^name:\s+\S+/m.test(frontmatter)) {- errors.push({ path: 'SKILL.md', message: 'Missing required field: name', line: 2 });- }- if (!/^description:\s+\S+/m.test(frontmatter)) {- errors.push({ path: 'SKILL.md', message: 'Missing required field: description', line: 2 });- }-- scanForSecrets(lines, 'SKILL.md', errors);- return { valid: errors.length === 0, errors, warnings };-}--/**- * Validate either a `config.toml` or `config.json` Copilot config.- *- * Adds a check: `model` MUST be in the GA catalog, with a warning- * for retiring models.- */-export async function validateConfig(content: string, format: 'toml' | 'json' = 'toml'): Promise<ValidationResult> {- const errors: ValidationError[] = [];- const warnings: ValidationWarning[] = [];- const lines = content.split('\n');-- let model: string | null = null;- if (format === 'json') {- try {- const obj = JSON.parse(content) as Record<string, unknown>;- const m = obj['model'];- if (typeof m === 'string') model = m;- } catch (err) {- errors.push({- path: 'config.json',- message: `Invalid JSON: ${(err as Error).message}`,- line: 1,- });- return { valid: false, errors, warnings };- }- } else {- const match = content.match(/^model\s*=\s*"([^"]+)"/m);- if (match) model = match[1] ?? null;- }-- if (!model) {- errors.push({- path: format === 'json' ? 'config.json' : 'config.toml',- message: 'Missing required field: model',- line: 1,- });- } else if (isRetiringModel(model)) {- warnings.push({- path: format === 'json' ? 'config.json' : 'config.toml',- message: `Model "${model}" is retiring or excluded from routing`,- suggestion: 'Switch to gpt-5.3-codex (LTS) or gpt-5.4-mini (fast)',- });- } else if (!isCatalogModel(model)) {- warnings.push({- path: format === 'json' ? 'config.json' : 'config.toml',- message: `Model "${model}" is not in the @claude-flow/copilot GA catalog`,- suggestion: 'Confirm the SDK exposes this model via client.listModels()',- });- }-- scanForSecrets(lines, format === 'json' ? 'config.json' : 'config.toml', errors);-- return { valid: errors.length === 0, errors, warnings };-}--function scanForSecrets(lines: string[], filename: string, errors: ValidationError[]): void {- for (let i = 0; i < lines.length; i++) {- const line = lines[i];- if (!line) continue;- for (const { pattern, name } of SECRET_PATTERNS) {- if (pattern.test(line)) {- errors.push({- path: filename,- message: `Potential ${name} detected β never commit secrets`,- line: i + 1,- });- }- }- }-}diff --git a/v3/@claude-flow/copilot/tests/client/auth.test.ts b/v3/@claude-flow/copilot/tests/client/auth.test.tsdeleted file mode 100644index d162e8372b..0000000000--- a/v3/@claude-flow/copilot/tests/client/auth.test.ts+++ /dev/null@@ -1,100 +0,0 @@-import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';-import fs from 'fs-extra';-import os from 'node:os';-import path from 'node:path';-import {- CopilotAuthRequiredError,- clearCachedToken,- getCachedToken,- resolveCredential,-} from '../../src/client/auth.js';--const ENV_KEYS = ['COPILOT_GITHUB_TOKEN', 'GH_TOKEN', 'GITHUB_TOKEN'] as const;-const CACHE_FILE = path.join(os.homedir(), '.config', 'ruflo', 'copilot', 'token.json');--describe('auth.resolveCredential', () => {- const saved: Record<string, string | undefined> = {};-- beforeEach(async () => {- for (const k of ENV_KEYS) {- saved[k] = process.env[k];- delete process.env[k];- }- await fs.remove(CACHE_FILE);- });-- afterEach(async () => {- for (const k of ENV_KEYS) {- if (saved[k] !== undefined) process.env[k] = saved[k];- else delete process.env[k];- }- await fs.remove(CACHE_FILE);- });-- it('returns "env:COPILOT_GITHUB_TOKEN" when that env var is set (and never the value)', async () => {- process.env['COPILOT_GITHUB_TOKEN'] = 'ghp_fake_test_value_should_never_leak_1234567890';- const result = await resolveCredential();- expect(result).toBe('env:COPILOT_GITHUB_TOKEN');- // The persisted cache must NEVER contain the token value- const cached = await getCachedToken();- expect(cached).not.toBeNull();- expect(JSON.stringify(cached)).not.toContain('ghp_fake_test_value_should_never_leak');- expect(JSON.stringify(cached)).not.toContain('1234567890');- });-- it('returns "env:GH_TOKEN" when only GH_TOKEN is set', async () => {- process.env['GH_TOKEN'] = 'ghp_another_fake';- expect(await resolveCredential()).toBe('env:GH_TOKEN');- });-- it('returns "env:GITHUB_TOKEN" when only GITHUB_TOKEN is set', async () => {- process.env['GITHUB_TOKEN'] = 'ghp_yet_another_fake';- expect(await resolveCredential()).toBe('env:GITHUB_TOKEN');- });-- it('prefers COPILOT_GITHUB_TOKEN over GH_TOKEN over GITHUB_TOKEN', async () => {- process.env['COPILOT_GITHUB_TOKEN'] = 'a';- process.env['GH_TOKEN'] = 'b';- process.env['GITHUB_TOKEN'] = 'c';- expect(await resolveCredential()).toBe('env:COPILOT_GITHUB_TOKEN');- });-- it('returns null when no env vars are set and gh is not authenticated', async () => {- // gh isn't typically authenticated in the test sandbox; if it is, the test below covers it.- const result = await resolveCredential();- expect(result === null || result === 'gh-cli').toBe(true);- });-});--describe('auth cache lifecycle', () => {- beforeEach(async () => {- for (const k of ENV_KEYS) delete process.env[k];- await fs.remove(CACHE_FILE);- });-- it('getCachedToken returns null when no file exists', async () => {- expect(await getCachedToken()).toBeNull();- });-- it('clearCachedToken removes the cache file', async () => {- process.env['GH_TOKEN'] = 'fake';- await resolveCredential();- expect(await getCachedToken()).not.toBeNull();- await clearCachedToken();- expect(await getCachedToken()).toBeNull();- });-});--describe('CopilotAuthRequiredError', () => {- it('has the correct code and a message that does NOT include any token', () => {- const err = new CopilotAuthRequiredError();- expect(err.code).toBe('COPILOT_AUTH_REQUIRED');- expect(err.name).toBe('CopilotAuthRequiredError');- expect(err.message).not.toMatch(/ghp_|gho_|sk-/);- });-- it('respects custom messages without leaking secrets', () => {- const err = new CopilotAuthRequiredError('Authenticate with `gh auth login`.');- expect(err.message).toBe('Authenticate with `gh auth login`.');- });-});diff --git a/v3/@claude-flow/copilot/tests/client/models.test.ts b/v3/@claude-flow/copilot/tests/client/models.test.tsdeleted file mode 100644index 662160d8dc..0000000000--- a/v3/@claude-flow/copilot/tests/client/models.test.ts+++ /dev/null@@ -1,97 +0,0 @@-import { describe, it, expect } from 'vitest';-import {- COPILOT_MODEL_CATALOG,- RETIRING_MODELS,- TIER_DEFAULTS,- getModelEntry,- getOptimalModel,- isCatalogModel,- isRetiringModel,-} from '../../src/client/models.js';--describe('COPILOT_MODEL_CATALOG', () => {- it('contains the three GA OpenAI models from ADR-147 Part B', () => {- expect(COPILOT_MODEL_CATALOG['gpt-5.3-codex'].tier).toBe(3);- expect(COPILOT_MODEL_CATALOG['gpt-5.3-codex'].multiplier).toBe(1.0);- expect(COPILOT_MODEL_CATALOG['gpt-5.3-codex'].ltsUntil).toBe('2027-02-04');-- expect(COPILOT_MODEL_CATALOG['gpt-5.4-mini'].tier).toBe(2);- expect(COPILOT_MODEL_CATALOG['gpt-5.4-mini'].multiplier).toBe(0.33);-- expect(COPILOT_MODEL_CATALOG['gpt-5.5'].tier).toBe(3);- expect(COPILOT_MODEL_CATALOG['gpt-5.5'].multiplier).toBe(7.5);- });-- it('RETIRING_MODELS excludes catalog entries', () => {- for (const id of RETIRING_MODELS) {- expect(id in COPILOT_MODEL_CATALOG).toBe(false);- }- });-- it('TIER_DEFAULTS pin to the LTS / fast / frontier IDs', () => {- expect(TIER_DEFAULTS.Tier2).toBe('gpt-5.4-mini');- expect(TIER_DEFAULTS.Tier3).toBe('gpt-5.3-codex');- expect(TIER_DEFAULTS.Tier3Reasoning).toBe('gpt-5.5');- });-});--describe('getOptimalModel', () => {- it('returns Tier 2 for low complexity (<30)', () => {- expect(getOptimalModel(0)).toBe('gpt-5.4-mini');- expect(getOptimalModel(15)).toBe('gpt-5.4-mini');- expect(getOptimalModel(29)).toBe('gpt-5.4-mini');- });-- it('returns Tier 3 LTS for mid complexity (30-79)', () => {- expect(getOptimalModel(30)).toBe('gpt-5.3-codex');- expect(getOptimalModel(50)).toBe('gpt-5.3-codex');- expect(getOptimalModel(79)).toBe('gpt-5.3-codex');- });-- it('returns Tier 3 LTS for high complexity without allowFrontier', () => {- expect(getOptimalModel(80)).toBe('gpt-5.3-codex');- expect(getOptimalModel(100)).toBe('gpt-5.3-codex');- });-- it('returns Tier 3 frontier (gpt-5.5) for complexity β₯80 when allowFrontier=true', () => {- expect(getOptimalModel(80, true)).toBe('gpt-5.5');- expect(getOptimalModel(95, true)).toBe('gpt-5.5');- });-- it('accepts named tiers', () => {- expect(getOptimalModel('Tier2')).toBe('gpt-5.4-mini');- expect(getOptimalModel('Tier3')).toBe('gpt-5.3-codex');- expect(getOptimalModel('Tier3Reasoning', true)).toBe('gpt-5.5');- expect(getOptimalModel('Tier3Reasoning', false)).toBe('gpt-5.3-codex');- });-- it('clamps non-finite complexity', () => {- expect(getOptimalModel(NaN)).toBe('gpt-5.3-codex');- expect(getOptimalModel(Infinity)).toBe('gpt-5.3-codex');- expect(getOptimalModel(-50)).toBe('gpt-5.4-mini');- expect(getOptimalModel(9999)).toBe('gpt-5.3-codex');- });-});--describe('isCatalogModel / isRetiringModel / getModelEntry', () => {- it('identifies catalog members', () => {- expect(isCatalogModel('gpt-5.3-codex')).toBe(true);- expect(isCatalogModel('gpt-5.4-mini')).toBe(true);- expect(isCatalogModel('gpt-5.5')).toBe(true);- expect(isCatalogModel('gpt-4.1')).toBe(false);- expect(isCatalogModel('claude-sonnet')).toBe(false);- });-- it('identifies retiring models', () => {- expect(isRetiringModel('gpt-4.1')).toBe(true);- expect(isRetiringModel('gpt-5.2-codex')).toBe(true);- expect(isRetiringModel('gpt-5.3-codex')).toBe(false);- });-- it('getModelEntry returns the typed entry or null', () => {- const entry = getModelEntry('gpt-5.3-codex');- expect(entry).not.toBeNull();- expect(entry?.tier).toBe(3);- expect(getModelEntry('nope')).toBeNull();- });-});diff --git a/v3/@claude-flow/copilot/tests/dual-mode/orchestrator.test.ts b/v3/@claude-flow/copilot/tests/dual-mode/orchestrator.test.tsdeleted file mode 100644index 8563ff18bf..0000000000--- a/v3/@claude-flow/copilot/tests/dual-mode/orchestrator.test.ts+++ /dev/null@@ -1,105 +0,0 @@-import { describe, it, expect } from 'vitest';-import {- MultiModeOrchestrator,- TriModeCollaborationTemplates,- type MultiModeWorkerConfig,-} from '../../src/dual-mode/orchestrator.js';-import { parseWorkerSpecs } from '../../src/dual-mode/cli.js';--describe('parseWorkerSpecs', () => {- it('parses a single claude worker', () => {- const workers = parseWorkerSpecs(['claude:architect:Design the API'], false);- expect(workers).toHaveLength(1);- expect(workers[0]?.platform).toBe('claude');- expect(workers[0]?.role).toBe('architect');- expect(workers[0]?.prompt).toBe('Design the API');- });-- it('accepts the new copilot platform prefix', () => {- const workers = parseWorkerSpecs(['copilot:reviewer:Review for OWASP'], false);- expect(workers[0]?.platform).toBe('copilot');- });-- it('chains workers sequentially by default', () => {- const workers = parseWorkerSpecs(- ['claude:architect:A', 'codex:coder:B', 'copilot:reviewer:C'],- false,- );- expect(workers[1]?.dependsOn).toEqual(['architect']);- expect(workers[2]?.dependsOn).toEqual(['coder']);- });-- it('runs in parallel when requested', () => {- const workers = parseWorkerSpecs(- ['claude:architect:A', 'codex:coder:B'],- true,- );- expect(workers[0]?.dependsOn).toBeUndefined();- expect(workers[1]?.dependsOn).toBeUndefined();- });-- it('rejects unknown platforms', () => {- expect(() => parseWorkerSpecs(['gemini:foo:bar'], false)).toThrow(/Invalid platform/);- });-- it('rejects malformed specs', () => {- expect(() => parseWorkerSpecs(['justone'], false)).toThrow(/Invalid --worker spec/);- expect(() => parseWorkerSpecs(['claude:role:'], false)).toThrow(/Missing prompt/);- });-- it('deduplicates worker ids', () => {- const workers = parseWorkerSpecs(- ['claude:reviewer:A', 'copilot:reviewer:B'],- true,- );- expect(workers[0]?.id).toBe('reviewer');- expect(workers[1]?.id).toBe('reviewer-2');- });-});--describe('TriModeCollaborationTemplates', () => {- it('featureDevelopment includes all three platforms', () => {- const workers = TriModeCollaborationTemplates.featureDevelopment('Add OAuth');- const platforms = new Set(workers.map((w) => w.platform));- expect(platforms.has('claude')).toBe(true);- expect(platforms.has('codex')).toBe(true);- expect(platforms.has('copilot')).toBe(true);- });-- it('securityAudit puts gpt-5.5 frontier on the scanner', () => {- const workers = TriModeCollaborationTemplates.securityAudit('src/auth');- const scanner = workers.find((w) => w.id === 'scanner');- expect(scanner?.platform).toBe('copilot');- expect(scanner?.copilotModel).toBe('gpt-5.5');- });-});--describe('MultiModeOrchestrator', () => {- it('builds dependency levels respecting dependsOn', () => {- const orchestrator = new MultiModeOrchestrator({ projectPath: '/tmp' }) as unknown as {- buildDependencyLevels(w: MultiModeWorkerConfig[]): MultiModeWorkerConfig[][];- };- const workers: MultiModeWorkerConfig[] = [- { id: 'a', platform: 'claude', role: 'r1', prompt: 'p' },- { id: 'b', platform: 'codex', role: 'r2', prompt: 'p', dependsOn: ['a'] },- { id: 'c', platform: 'copilot', role: 'r3', prompt: 'p', dependsOn: ['b'] },- ];- const levels = orchestrator.buildDependencyLevels(workers);- expect(levels).toHaveLength(3);- expect(levels[0]?.[0]?.id).toBe('a');- expect(levels[1]?.[0]?.id).toBe('b');- expect(levels[2]?.[0]?.id).toBe('c');- });-- it('records a failed worker via runWorker and re-throws', async () => {- class FakeOrchestrator extends MultiModeOrchestrator {- protected override async executeHeadless(): Promise<string> {- throw new Error('synthetic failure');- }- }- const orchestrator = new FakeOrchestrator({ projectPath: '/tmp' });- await expect(- orchestrator.runWorker({ id: 'w', platform: 'claude', role: 'r', prompt: 'p' }),- ).rejects.toThrow(/synthetic failure/);- });-});diff --git a/v3/@claude-flow/copilot/tests/initializer.test.ts b/v3/@claude-flow/copilot/tests/initializer.test.tsdeleted file mode 100644index 6c229f43da..0000000000--- a/v3/@claude-flow/copilot/tests/initializer.test.ts+++ /dev/null@@ -1,76 +0,0 @@-import { describe, it, expect, beforeEach, afterEach } from 'vitest';-import fs from 'fs-extra';-import os from 'node:os';-import path from 'node:path';-import { CopilotInitializer, initializeCopilotProject } from '../src/initializer.js';--describe('CopilotInitializer', () => {- let tmp: string;-- beforeEach(async () => {- tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'copilot-init-'));- });-- afterEach(async () => {- await fs.remove(tmp);- });-- it('scaffolds AGENTS.md + .copilot/config.json + skill files', async () => {- const init = new CopilotInitializer();- const result = await init.initialize({- projectPath: tmp,- template: 'default',- });- expect(result.success).toBe(true);- expect(result.filesCreated).toContain('AGENTS.md');- expect(result.filesCreated).toContain('.copilot/config.json');- expect(await fs.pathExists(path.join(tmp, 'AGENTS.md'))).toBe(true);- expect(await fs.pathExists(path.join(tmp, '.copilot', 'config.json'))).toBe(true);- expect(await fs.pathExists(path.join(tmp, '.copilot', 'AGENTS.override.md'))).toBe(true);- });-- it('refuses to overwrite without --force', async () => {- const init = new CopilotInitializer();- await init.initialize({ projectPath: tmp });- const second = await init.initialize({ projectPath: tmp });- expect(second.success).toBe(false);- });-- it('overwrites with --force', async () => {- const init = new CopilotInitializer();- await init.initialize({ projectPath: tmp });- const second = await init.initialize({ projectPath: tmp, force: true });- expect(second.success).toBe(true);- });-- it('generates valid JSON config', async () => {- await initializeCopilotProject(tmp);- const config = await fs.readJson(path.join(tmp, '.copilot', 'config.json')) as Record<string, unknown>;- expect(config['model']).toBe('gpt-5.3-codex');- expect(config['mcpServers']).toBeDefined();- });-- it('dryRun lists files without writing', async () => {- const init = new CopilotInitializer();- const files = await init.dryRun({ projectPath: tmp, template: 'minimal' });- expect(files).toContain('AGENTS.md');- expect(files).toContain('.copilot/config.json');- expect(await fs.pathExists(path.join(tmp, 'AGENTS.md'))).toBe(false);- });-- it('emits a CLAUDE.md in dual mode', async () => {- const init = new CopilotInitializer();- const result = await init.initialize({ projectPath: tmp, dual: true });- expect(result.success).toBe(true);- expect(result.filesCreated).toContain('CLAUDE.md');- expect(await fs.pathExists(path.join(tmp, 'CLAUDE.md'))).toBe(true);- });-- it('updates .gitignore with .copilot/ entries', async () => {- await fs.writeFile(path.join(tmp, '.gitignore'), '# preexisting\nnode_modules\n');- await initializeCopilotProject(tmp);- const gi = await fs.readFile(path.join(tmp, '.gitignore'), 'utf-8');- expect(gi).toContain('.copilot/');- expect(gi).toContain('node_modules'); // preserved- });-});diff --git a/v3/@claude-flow/copilot/tests/mcp/register.test.ts b/v3/@claude-flow/copilot/tests/mcp/register.test.tsdeleted file mode 100644index 8b2798aa6c..0000000000--- a/v3/@claude-flow/copilot/tests/mcp/register.test.ts+++ /dev/null@@ -1,65 +0,0 @@-import { describe, it, expect } from 'vitest';-import { buildMcpServers, registerRufloMcpWithCopilot } from '../../src/mcp/register.js';-import { CopilotMcpBridge } from '../../src/mcp/bridge.js';--describe('registerRufloMcpWithCopilot', () => {- it('produces the local-stdio server shape Copilot expects', async () => {- const out = await registerRufloMcpWithCopilot('/tmp/project');- expect(out.ruflo).toBeDefined();- expect(out.ruflo.type).toBe('local');- expect(out.ruflo.command).toBe('npx');- expect(out.ruflo.args).toEqual(['-y', 'ruflo@latest', 'mcp', 'start']);- expect(out.ruflo.tools).toEqual(['*']);- expect(out.ruflo.env?.['CLAUDE_FLOW_CONFIG']).toBe('/tmp/project/claude-flow.config.json');- expect(out.ruflo.cwd).toBe('/tmp/project');- });-- it('honors an explicit tool allowlist', async () => {- const out = await registerRufloMcpWithCopilot('/x', ['memory_store', 'memory_search']);- expect(out.ruflo.tools).toEqual(['memory_store', 'memory_search']);- });-- it('returns ["*"] when the filter is the literal "*"', async () => {- const out = await registerRufloMcpWithCopilot('/x', '*');- expect(out.ruflo.tools).toEqual(['*']);- });-});--describe('buildMcpServers', () => {- it('merges extra servers AFTER ruflo so caller wins on collisions', async () => {- const out = await buildMcpServers('/x', {- custom: { type: 'remote', url: 'https://example.com/mcp' },- });- expect(Object.keys(out)).toContain('ruflo');- expect(Object.keys(out)).toContain('custom');- expect((out['custom'] as { url?: string }).url).toBe('https://example.com/mcp');- });-- it('caller-supplied "ruflo" overrides default', async () => {- const out = await buildMcpServers('/x', {- ruflo: { type: 'remote', url: 'https://ruflo.cloud/mcp' },- });- expect((out['ruflo'] as { url?: string; type: string }).url).toBe('https://ruflo.cloud/mcp');- expect((out['ruflo'] as { type: string }).type).toBe('remote');- });-});--describe('CopilotMcpBridge', () => {- it('records, snapshots, and clears events', () => {- const bridge = new CopilotMcpBridge('sess-1');- expect(bridge.count()).toBe(0);-- bridge.record({ serverId: 'ruflo', toolName: 'memory_store', outcome: 'allowed' });- bridge.record({ serverId: 'ruflo', toolName: 'memory_search', outcome: 'errored', error: 'connection refused' });-- expect(bridge.count()).toBe(2);- const events = bridge.events();- expect(events[0]?.sessionId).toBe('sess-1');- expect(events[0]?.outcome).toBe('allowed');- expect(events[1]?.outcome).toBe('errored');- expect(events[1]?.error).toBe('connection refused');-- bridge.clear();- expect(bridge.count()).toBe(0);- });-});diff --git a/v3/@claude-flow/copilot/tests/validators.test.ts b/v3/@claude-flow/copilot/tests/validators.test.tsdeleted file mode 100644index 22d8940c9e..0000000000--- a/v3/@claude-flow/copilot/tests/validators.test.ts+++ /dev/null@@ -1,75 +0,0 @@-import { describe, it, expect } from 'vitest';-import { validateAgentsMd, validateConfig, validateSkillMd } from '../src/validators/index.js';--describe('validateAgentsMd', () => {- it('accepts a well-formed AGENTS.md', async () => {- const md = '# My Project\n\n## Setup\nnpm install\n\n## Security\nNo secrets!\n';- const result = await validateAgentsMd(md);- expect(result.valid).toBe(true);- });-- it('rejects missing title', async () => {- const result = await validateAgentsMd('No heading here, just text.');- expect(result.valid).toBe(false);- });-- it('flags potential GitHub tokens', async () => {- const md = '# X\n\n## Setup\nGIT TOKEN: ghp_abcdef0123456789012345678901234567890\n## Security\nok\n';- const result = await validateAgentsMd(md);- expect(result.valid).toBe(false);- expect(result.errors.some((e) => e.message.includes('GitHub'))).toBe(true);- });-});--describe('validateSkillMd', () => {- it('accepts a valid frontmatter block', async () => {- const md = '---\nname: my-skill\ndescription: Test skill\nversion: 1.0.0\n---\n\n# My skill\n';- const result = await validateSkillMd(md);- expect(result.valid).toBe(true);- });-- it('rejects missing required fields', async () => {- const md = '---\nversion: 1.0.0\n---\n\nbody\n';- const result = await validateSkillMd(md);- expect(result.valid).toBe(false);- });-- it('rejects missing frontmatter', async () => {- const result = await validateSkillMd('# No frontmatter');- expect(result.valid).toBe(false);- });-});--describe('validateConfig (TOML)', () => {- it('accepts gpt-5.3-codex', async () => {- const toml = 'model = "gpt-5.3-codex"\n';- const result = await validateConfig(toml, 'toml');- expect(result.valid).toBe(true);- });-- it('warns on retiring models', async () => {- const toml = 'model = "gpt-4.1"\n';- const result = await validateConfig(toml, 'toml');- expect(result.valid).toBe(true);- expect(result.warnings.some((w) => w.message.includes('retiring'))).toBe(true);- });-- it('warns on unknown models', async () => {- const toml = 'model = "mystery-model"\n';- const result = await validateConfig(toml, 'toml');- expect(result.warnings.some((w) => w.message.includes('not in'))).toBe(true);- });-});--describe('validateConfig (JSON)', () => {- it('accepts a JSON config with the LTS model', async () => {- const json = JSON.stringify({ model: 'gpt-5.3-codex', mcpServers: {} });- const result = await validateConfig(json, 'json');- expect(result.valid).toBe(true);- });-- it('rejects unparseable JSON', async () => {- const result = await validateConfig('not json', 'json');- expect(result.valid).toBe(false);- });-});diff --git a/v3/@claude-flow/copilot/tsconfig.json b/v3/@claude-flow/copilot/tsconfig.jsondeleted file mode 100644index 951c349e12..0000000000--- a/v3/@claude-flow/copilot/tsconfig.json+++ /dev/null@@ -1,26 +0,0 @@-{- "compilerOptions": {- "target": "ES2022",- "module": "NodeNext",- "moduleResolution": "NodeNext",- "lib": ["ES2022"],- "outDir": "./dist",- "rootDir": "./src",- "strict": true,- "esModuleInterop": true,- "skipLibCheck": true,- "forceConsistentCasingInFileNames": true,- "declaration": true,- "declarationMap": true,- "sourceMap": true,- "resolveJsonModule": true,- "isolatedModules": true,- "noImplicitAny": true,- "noImplicitReturns": true,- "noFallthroughCasesInSwitch": true,- "noUncheckedIndexedAccess": true,- "exactOptionalPropertyTypes": true- },- "include": ["src/**/*"],- "exclude": ["node_modules", "dist", "**/*.test.ts"]-}diff --git a/v3/@claude-flow/copilot/vitest.config.ts b/v3/@claude-flow/copilot/vitest.config.tsdeleted file mode 100644index 52fb411ad3..0000000000--- a/v3/@claude-flow/copilot/vitest.config.ts+++ /dev/null@@ -1,14 +0,0 @@-import { defineConfig } from 'vitest/config';--export default defineConfig({- test: {- include: ['tests/**/*.test.ts', 'tests/**/*.spec.ts'],- exclude: ['node_modules', 'dist', '.git'],- coverage: {- provider: 'v8',- reporter: ['text', 'json', 'html'],- exclude: ['node_modules', 'dist', 'tests'],- },- globals: true,- },-});