diff --git a/CHANGELOG.md b/CHANGELOG.md index afb5407c..df4bc739 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- Removed unreachable migration barrels, obsolete prompt/example artifacts, and unused internal helpers; builds now reject unused locals and parameters. - Bounded semantic, file-analysis, MCP-session, and host-session retention with TTL/LRU limits, proactive cleanup, raw directory-entry scan budgets, and safe runtime configuration clamps. - Moved checkpoint payload history from `session.json` into individually bounded, paginated checkpoint records with summary-only session reads, incremental counts, legacy dual-read, and lazy migration. - Made host-session binding mutations atomic across concurrent hooks, with owner-identified inter-process locks that safely recover after a crashed hook, preserve live legacy locks during rolling upgrades, and prevent terminal MCP activity sessions from being reused. diff --git a/CONVENTIONS.md b/CONVENTIONS.md index af9ff186..f72ce1db 100644 --- a/CONVENTIONS.md +++ b/CONVENTIONS.md @@ -36,11 +36,9 @@ CONTRIBUTING.md LICENSE README.md docs/ -- Published documentation produced by this tool -example-documentation.ts jest.config.js package.json package-lock.json -prompts/ -- Prompt templates (update_plan_prompt.md, update_scaffold_prompt.md) scripts/ -- Build and test helper scripts src/ -- TypeScript source (~240 files): CLI entrypoint, services, generators, utilities tsconfig.json @@ -70,4 +68,3 @@ Generated: 2026-03-18T21:32:55.004Z ## Testing See [testing-strategy.md](../testing-strategy.md) in the parent docs directory for full test framework documentation. - diff --git a/docs/src/content/docs/en/about/architecture.md b/docs/src/content/docs/en/about/architecture.md index 2e9b024a..7b18eff4 100644 --- a/docs/src/content/docs/en/about/architecture.md +++ b/docs/src/content/docs/en/about/architecture.md @@ -123,7 +123,7 @@ The operator's package. It ships the full CLI stack and exports a handful of ser - `SyncService` — export/import rules, agents, and skills - `ReportService` — generate workflow progress reports -It includes the `prompts/` directory used by the interactive CLI, and its bin is `dotcontext`. +Its executable is exposed as the `dotcontext` bin. ### `@dotcontext/harness` diff --git a/docs/src/content/docs/en/about/contributing.md b/docs/src/content/docs/en/about/contributing.md index 58f111b8..9743b541 100644 --- a/docs/src/content/docs/en/about/contributing.md +++ b/docs/src/content/docs/en/about/contributing.md @@ -64,7 +64,6 @@ Builds the five isolated package bundles into `.release/packages/{cli,harness,mc - Writes a package-specific `package.json` manifest for each surface — filtered dependencies, `exports`, and `bin` entries. - Copies shared files (`LICENSE`, `README.md`). - Generates bin shims for the executables (`dotcontext`, `dotcontext-mcp`). -- Copies the `prompts/` directory (CLI only). ### `npm run smoke:packages` @@ -75,7 +74,7 @@ Runs `scripts/smoke-package-bundles.js` to validate the bundles you just built. - The expected exports are present in each compiled index. - Bin entries and local shims exist for CLI and MCP. - **No legacy `dist/services/` folder** ships — this enforces the architecture (domain behavior must not leak into the transport surfaces). -- `README.md` and `LICENSE` are included; the `prompts/` directory is present for CLI. +- `README.md` and `LICENSE` are included. :::caution The "no `dist/services/`" check is intentional. If a package smoke test fails on it, you have probably moved domain behavior into `cli` or `mcp` instead of `harness`. See [Architecture](/about/architecture/) for the boundary rules. diff --git a/docs/src/content/docs/pt-br/about/architecture.md b/docs/src/content/docs/pt-br/about/architecture.md index eb9adfb5..d8041c8e 100644 --- a/docs/src/content/docs/pt-br/about/architecture.md +++ b/docs/src/content/docs/pt-br/about/architecture.md @@ -116,7 +116,7 @@ O pacote do operador. Ele entrega a stack completa da CLI e exporta um punhado d - `SyncService` — exportar/importar rules, agents e skills - `ReportService` — gerar relatórios de progresso do workflow -Ele inclui o diretório `prompts/` usado pela CLI interativa, e seu bin é `dotcontext`. +Seu executável é exposto pelo bin `dotcontext`. ### `@dotcontext/harness` diff --git a/docs/src/content/docs/pt-br/about/contributing.md b/docs/src/content/docs/pt-br/about/contributing.md index ec4aad18..6ae83453 100644 --- a/docs/src/content/docs/pt-br/about/contributing.md +++ b/docs/src/content/docs/pt-br/about/contributing.md @@ -64,7 +64,6 @@ Faz o build dos cinco bundles de pacote isolados em `.release/packages/{cli,harn - Escreve um manifesto `package.json` específico para cada surface — dependências filtradas, `exports` e entradas `bin`. - Copia arquivos compartilhados (`LICENSE`, `README.md`). - Gera os shims de bin para os executáveis (`dotcontext`, `dotcontext-mcp`). -- Copia o diretório `prompts/` (somente CLI). ### `npm run smoke:packages` @@ -75,7 +74,7 @@ Roda `scripts/smoke-package-bundles.js` para validar os bundles que você acabou - Que os `exports` esperados estão presentes em cada index compilado. - Que as entradas `bin` e os shims locais existem para CLI e MCP. - Que **nenhuma pasta legada `dist/services/`** é publicada — isso reforça a arquitetura (comportamento de domínio não pode vazar para as surfaces de transporte). -- Que `README.md` e `LICENSE` estão incluídos; e que o diretório `prompts/` está presente para a CLI. +- Que `README.md` e `LICENSE` estão incluídos. :::caution A verificação de "nenhum `dist/services/`" é intencional. Se um smoke test de pacote falhar nela, provavelmente você moveu comportamento de domínio para `cli` ou `mcp` em vez de para o `harness`. Veja a [Arquitetura](/pt-br/about/architecture/) para as regras de fronteira. diff --git a/example-documentation.ts b/example-documentation.ts deleted file mode 100644 index dc1ee489..00000000 --- a/example-documentation.ts +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Example script demonstrating how to scaffold documentation and agent playbooks - * programmatically without going through the CLI binary. - */ - -import path from 'node:path'; -import { DocumentationGenerator } from './src/generators/documentation'; -import { AgentGenerator } from './src/generators/agents'; -import { FileMapper } from './src/utils/fileMapper'; - -async function scaffoldRepo(repoRoot: string, outputDir: string = path.join(repoRoot, '.context')) { - const fileMapper = new FileMapper(); - const documentationGenerator = new DocumentationGenerator(); - const agentGenerator = new AgentGenerator(); - - const repoStructure = await fileMapper.mapRepository(repoRoot); - - await documentationGenerator.generateDocumentation(repoStructure, outputDir, {}, true); - await agentGenerator.generateAgentPrompts(repoStructure, outputDir, true); - - console.log(`Scaffold written to ${outputDir}`); -} - -if (require.main === module) { - const repoRoot = process.argv[2] ? path.resolve(process.argv[2]) : process.cwd(); - scaffoldRepo(repoRoot).catch(error => { - console.error('Failed to scaffold repository:', error); - process.exit(1); - }); -} - -export { scaffoldRepo }; diff --git a/package.json b/package.json index ca4c2838..06030770 100644 --- a/package.json +++ b/package.json @@ -20,8 +20,7 @@ "files": [ "dist/**/*", "README.md", - "LICENSE", - "prompts/**/*" + "LICENSE" ], "engines": { "node": ">=20.12.0" diff --git a/prompts/github_issue_prevc_prompt.md b/prompts/github_issue_prevc_prompt.md deleted file mode 100644 index 59cbfb54..00000000 --- a/prompts/github_issue_prevc_prompt.md +++ /dev/null @@ -1,94 +0,0 @@ -# Prompt: Start PREVC from a GitHub Issue - -## Purpose -You are an AI coding assistant starting structured dotcontext PREVC work from a GitHub issue. Your goal is to turn the live issue into a reviewable plan, initialize or prepare the dotcontext workflow, define validation evidence, and stop before implementation unless the user explicitly approves execution. - -## Inputs -- GitHub issue reference, such as `#108`, `owner/repo#108`, or a GitHub issue URL. -- Repository path or current working directory. -- Optional workflow name, branch name, milestone, or target PR. - -## Preparation Checklist -1. Confirm the repository path, current branch, working tree state, and target base branch. -2. Read repository instructions first, including `AGENTS.md`, `CLAUDE.md`, `CONTRIBUTING.md`, `README.md`, and relevant project docs. -3. Fetch the live GitHub issue body, labels, comments, linked PRs, acceptance criteria, and blockers. -4. Inspect nearby code, tests, scripts, CI, and docs only enough to scope the work and identify validation sensors. -5. Check whether `.context/` exists and whether an active PREVC workflow is already running. - -## Workflow Procedure -1. **Issue Snapshot** - - Summarize the issue goal, user impact, acceptance criteria, and explicit non-goals. - - Note the live issue URL and any linked PRs or blockers. - -2. **Context Readiness** - - If `.context/` is missing, prepare the context initialization steps. - - If `.context/` exists, run or request a context readiness check. - - Identify canonical docs, architecture notes, and repo-specific workflow rules. - -3. **PREVC Setup** - - Choose a concise workflow name derived from the issue. - - Select an appropriate scale: `QUICK`, `SMALL`, `MEDIUM`, or `LARGE`. - - Start or prepare a PREVC workflow for non-trivial work. - - Do not advance beyond planning until the plan is reviewable. - -4. **Plan Scaffold** - - Create or update a plan under `.context/plans/`. - - Link the plan to the issue, workflow, branch, target base, and acceptance criteria. - - Break the work into PREVC-aligned phases with clear deliverables. - - Keep scope limited to the issue unless dependencies force a follow-up. - -5. **Sensors and Evidence** - - Identify concrete validation commands from the repository, such as tests, typecheck, lint, build, smoke checks, screenshots, or deployment checks. - - Record required artifacts: PR link, test output, screenshots, logs, docs updates, migration notes, or release notes. - - Mark any unavailable sensor as blocked with the reason and a substitute evidence path. - -6. **Handoff** - - Produce a concise handoff that a human or another agent can review before execution. - - Include unresolved questions only when they block a correct implementation. - - Ask for approval before coding if the repository policy requires it. - -## Output Format -Return Markdown with these sections: - -```markdown -## Issue -- Reference: -- Goal: -- Acceptance: -- Non-goals: - -## Workflow -- Name: -- Scale: -- Current phase: -- Plan file: -- Base branch: -- Work branch: - -## Scope -- In: -- Out: -- Risks: -- Dependencies: - -## Sensors -- Command: -- Command: - -## Evidence -- Artifact: -- Artifact: - -## Unresolved Questions -- Question or `None`. - -## Next Prompt -Paste-ready prompt for the next agent turn. -``` - -## Acceptance Criteria -- The issue is based on live GitHub state, not stale local memory. -- Repository instructions and relevant docs are reflected in the plan. -- The PREVC workflow is initialized or the exact initialization step is documented. -- The plan has clear scope, sensors, evidence, risks, and review gates. -- No implementation changes are made unless the user explicitly approves execution. diff --git a/prompts/update_plan_prompt.md b/prompts/update_plan_prompt.md deleted file mode 100644 index a492f95a..00000000 --- a/prompts/update_plan_prompt.md +++ /dev/null @@ -1,41 +0,0 @@ -# Prompt: Update Collaboration Plans - -## Purpose -You are an AI assistant responsible for refining collaboration plans that live in the `.context/plans/` directory. Each plan orchestrates work across documentation guides (`docs/`) and agent playbooks (`agents/`). Your goal is to replace placeholders with actionable guidance that keeps the plan aligned with the referenced docs, agents, and repository context. - -## Preparation Checklist -1. Review the plan’s YAML front matter to understand the stated `ai_update_goal`, `required_inputs`, and `success_criteria`. -2. Inspect the provided documentation excerpts (from `docs/`) and agent playbooks to ensure the plan reflects their current guidance. -3. Confirm that the “Agent Lineup” and “Documentation Touchpoints” tables link to real files and reference the correct `agent-update` markers. -4. Note any TODOs, `agent-fill` placeholders, or missing evidence sections that must be resolved. - -## Update Procedure -1. **Task Snapshot** - - Summarize the primary goal and success signal in concrete terms. - - List authoritative references (docs, issues, specs) that contributors should consult. - -2. **Agent Alignment** - - For each agent in the lineup, describe why they are involved and call out the first responsibility they should focus on. - - Ensure playbook links and responsibility summaries match the referenced agent files. - -3. **Documentation Touchpoints** - - Map each plan stage to the docs excerpts provided, highlighting which sections need to be updated during execution. - - Keep the table sorted and ensure the listed `agent-update` markers exist. - -4. **Working Stages** - - Break the work into clear stages with owners, deliverables, and evidence checkpoints. - - Reference documentation and agent resources that the team should consult while executing each stage. - -5. **Evidence & Follow-up** - - Specify the artefacts that must be captured (PR links, test runs, change logs) before the plan is considered complete. - - Record any follow-up actions or decisions that require human confirmation. - -## Acceptance Criteria -- Every TODO or placeholder inside the plan’s `agent-update` block is resolved or accompanied by a clear escalation note. -- Tables reference existing files and stay in sync with the docs/agent indices. -- Stages provide actionable guidance, owners, and success signals. -- The plan remains fully self-contained and ready for contributors to execute. - -## Deliverables -- Updated plan Markdown returned verbatim. -- No additional commentary outside the Markdown output. diff --git a/prompts/update_scaffold_prompt.md b/prompts/update_scaffold_prompt.md deleted file mode 100644 index c219f36c..00000000 --- a/prompts/update_scaffold_prompt.md +++ /dev/null @@ -1,27 +0,0 @@ -# Prompt: Update Repository Documentation and Agent Playbooks - -## Purpose -You are an AI assistant responsible for refreshing the documentation (`docs/`) and agent playbooks (`agents/`). Your goal is to bring every guide up to date with the latest repository state and maintain cross-references between docs and agent instructions. - -## Context Gathering -1. Review the repository structure and recent changes. -2. Inspect `package.json`, CI configuration, and any release or roadmap notes. -3. Check `docs/README.md` for the current document map. - -## Update Procedure -1. **Update Documentation** - - Replace TODO placeholders with accurate, current information. - - Verify that links between docs remain valid. - - If you add new guides or sections, update `docs/README.md`. - -2. **Agent Playbook Alignment** - - For each change in `docs/`, adjust the related `agents/*.md` playbooks. - - Update responsibilities, best practices, and documentation touchpoints. - -## Acceptance Criteria -- No unresolved TODO placeholders remain unless they require explicit human input. -- Agent playbooks list accurate responsibilities and best practices. -- Changes are self-contained, well-formatted Markdown. - -## Deliverables -- Updated Markdown files. diff --git a/scripts/build-package-bundles.js b/scripts/build-package-bundles.js index 371f8452..07c4744e 100644 --- a/scripts/build-package-bundles.js +++ b/scripts/build-package-bundles.js @@ -130,11 +130,10 @@ function buildBundles() { exports: { '.': './dist/cli/index.js' }, bin: { dotcontext: 'dist/index.js' }, dependencies: rootPkg.dependencies, - files: ['dist/**/*', 'prompts/**/*', 'README.md', 'LICENSE'], + files: ['dist/**/*', 'README.md', 'LICENSE'], } ), readme: loadTemplate('cli.README.md'), - copyPrompts: true, }, { slug: 'harness', @@ -235,9 +234,6 @@ function buildBundles() { copyDir(distDir, path.join(pkgRoot, 'dist')); } - if (pkg.copyPrompts && fs.existsSync(path.join(repoRoot, 'prompts'))) { - copyDir(path.join(repoRoot, 'prompts'), path.join(pkgRoot, 'prompts')); - } for (const file of commonFiles) { copyFile(path.join(repoRoot, file), path.join(pkgRoot, file)); } diff --git a/scripts/smoke-package-bundles.js b/scripts/smoke-package-bundles.js index a7dac22a..8645ecf5 100644 --- a/scripts/smoke-package-bundles.js +++ b/scripts/smoke-package-bundles.js @@ -21,7 +21,6 @@ const bundles = [ 'ReportService', ], bin: 'dotcontext', - requiresPrompts: true, }, { slug: 'harness', @@ -144,10 +143,6 @@ function smokeBundle(bundle) { ); } - if (bundle.requiresPrompts) { - assert(fs.existsSync(path.join(bundleRoot, 'prompts')), `${bundle.slug}: prompts missing`); - } - const mod = requireFresh(mainPath); for (const exportName of bundle.expectedExports) { assert(mod[exportName], `${bundle.slug}: missing export ${exportName}`); diff --git a/scripts/test-mcp.js b/scripts/test-mcp.js deleted file mode 100644 index 36351d50..00000000 --- a/scripts/test-mcp.js +++ /dev/null @@ -1,102 +0,0 @@ -#!/usr/bin/env node -/** - * Simple MCP test client for local development - * - * Usage: node scripts/test-mcp.js - */ - -const { spawn } = require('child_process'); -const readline = require('readline'); - -const server = spawn('node', ['dist/index.js', 'mcp', '-v'], { - stdio: ['pipe', 'pipe', 'inherit'] -}); - -const rl = readline.createInterface({ - input: server.stdout, - crlfDelay: Infinity -}); - -let messageId = 1; - -function send(method, params = {}) { - const message = { - jsonrpc: '2.0', - id: messageId++, - method, - params - }; - console.log('\n→ Sending:', JSON.stringify(message, null, 2)); - server.stdin.write(JSON.stringify(message) + '\n'); -} - -rl.on('line', (line) => { - try { - const response = JSON.parse(line); - console.log('\n← Received:', JSON.stringify(response, null, 2)); - } catch { - console.log('← Raw:', line); - } -}); - -// Test sequence -async function runTests() { - console.log('=== MCP Server Test ===\n'); - - // 1. Initialize - send('initialize', { - protocolVersion: '2024-11-05', - capabilities: {}, - clientInfo: { name: 'test-client', version: '1.0.0' } - }); - - await sleep(500); - - // 2. Send initialized notification - server.stdin.write(JSON.stringify({ - jsonrpc: '2.0', - method: 'notifications/initialized' - }) + '\n'); - - await sleep(500); - - // 3. List tools - send('tools/list', {}); - - await sleep(500); - - // 4. Call a tool - send('tools/call', { - name: 'listFiles', - arguments: { - pattern: '*.ts', - cwd: process.cwd() + '/src' - } - }); - - await sleep(1000); - - // 5. List resources - send('resources/list', {}); - - await sleep(500); - - console.log('\n=== Tests complete ==='); - console.log('Press Ctrl+C to exit\n'); -} - -function sleep(ms) { - return new Promise(resolve => setTimeout(resolve, ms)); -} - -server.on('close', (code) => { - console.log(`Server exited with code ${code}`); - process.exit(code); -}); - -process.on('SIGINT', () => { - server.kill(); - process.exit(0); -}); - -runTests().catch(console.error); diff --git a/src/bin/dotcontext.ts b/src/bin/dotcontext.ts index 57b73cf0..7ef972be 100644 --- a/src/bin/dotcontext.ts +++ b/src/bin/dotcontext.ts @@ -13,7 +13,6 @@ import { isPromptCancelled, themedCheckbox, themedConfirm, - themedInput, themedSelect, } from '../utils/themedPrompt'; import { CLIInterface } from '../utils/cliUI'; @@ -60,21 +59,10 @@ import { } from '../harness'; import { detectSmartDefaults, - displayConfigSummary, - type ConfigSummary } from '../utils/prompts'; import { VERSION, PACKAGE_NAME } from '../version'; const rawArgs = process.argv.slice(2); -const isMcpCommand = rawArgs.includes('mcp'); - -// Determine if we're in interactive mode (no command args, only flags like --lang) -const isInteractiveMode = rawArgs.every(arg => - arg.startsWith('-') || - rawArgs[rawArgs.indexOf(arg) - 1]?.startsWith('--lang') || - rawArgs[rawArgs.indexOf(arg) - 1]?.startsWith('--language') || - rawArgs[rawArgs.indexOf(arg) - 1]?.startsWith('-l') -); const initialLocale = detectLocale(rawArgs, process.env.DOTCONTEXT_LANG, [ process.env.LC_ALL, @@ -1430,72 +1418,6 @@ async function runIntegrationsMenu(): Promise { } } -async function runInteractiveSync(): Promise { - const defaults = await detectSmartDefaults(); - const defaultSource = path.resolve(defaults.repoPath, '.context/agents'); - - // Simplified: single prompt for target selection with common presets - const quickTarget = await themedSelect({ - message: t('prompts.sync.quickTarget'), - choices: [ - { name: t('prompts.sync.quickTarget.common'), value: 'common' }, - { name: t('prompts.sync.quickTarget.claude'), value: 'claude' }, - { name: t('prompts.sync.quickTarget.all'), value: 'all' }, - { name: t('prompts.sync.quickTarget.custom'), value: 'custom' } - ], - default: 'common' - }); - - let preset: string | undefined; - let target: string[] | undefined; - let sourcePath = defaultSource; - - if (quickTarget === 'custom') { - // Custom path: ask for source and target - sourcePath = await themedInput({ - message: t('prompts.sync.source'), - default: defaultSource - }); - target = [await themedInput({ - message: t('prompts.sync.customPath') - })]; - } else if (quickTarget === 'common') { - // Common: Claude + GitHub - use explicit target paths instead of preset - target = [ - path.resolve(defaults.repoPath, '.claude/agents'), - path.resolve(defaults.repoPath, '.github/agents') - ]; - } else { - preset = quickTarget; - } - - // Show summary - const summary: ConfigSummary = { - operation: 'sync', - repoPath: sourcePath, - options: { - Target: quickTarget === 'custom' ? (target?.[0] || 'custom') : quickTarget, - Mode: 'symlink' - } - }; - - displayConfigSummary(summary, t); - - try { - await syncService.run({ - source: sourcePath, - mode: 'symlink', - preset: preset as any, - target, - force: false, - dryRun: false - }); - } catch (error) { - ui.displayError(t('errors.sync.failed'), error as Error); - } -} - - // ============================================================================ // Synchronize my context - unified sync for agents, skills, and docs // ============================================================================ diff --git a/src/cli/adapters/in/index.ts b/src/cli/adapters/in/index.ts deleted file mode 100644 index a593a488..00000000 --- a/src/cli/adapters/in/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { runDotcontextCli, runDotcontextCliFromProcess } from '../../../bin/dotcontext'; diff --git a/src/cli/commands/index.ts b/src/cli/commands/index.ts deleted file mode 100644 index f472e793..00000000 --- a/src/cli/commands/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { runDotcontextCli, runDotcontextCliFromProcess } from '../../bin/dotcontext'; diff --git a/src/cli/services/index.ts b/src/cli/services/index.ts index 97c8c1a5..0b6987ca 100644 --- a/src/cli/services/index.ts +++ b/src/cli/services/index.ts @@ -88,7 +88,6 @@ export { export { StateDetector, - default as DefaultStateDetector, type ProjectState, type StateDetectionResult, type StateDetectorOptions, diff --git a/src/cli/services/mcpInstallService.ts b/src/cli/services/mcpInstallService.ts index d59b0efd..f9d8ad8d 100644 --- a/src/cli/services/mcpInstallService.ts +++ b/src/cli/services/mcpInstallService.ts @@ -15,7 +15,7 @@ import { createEmptyResult, addError, } from '../../shared/system/types'; -import { TOOL_REGISTRY, getToolById, ToolDefinition } from '../../shared/registry/toolRegistry'; +import { getToolById, ToolDefinition } from '../../shared/registry/toolRegistry'; import type { TranslateFn } from '../../utils/i18n'; // ============================================================================ diff --git a/src/cli/ui/index.ts b/src/cli/ui/index.ts deleted file mode 100644 index 3264d1a9..00000000 --- a/src/cli/ui/index.ts +++ /dev/null @@ -1,6 +0,0 @@ -export { CLIInterface } from '../../utils/cliUI'; -export * from '../../utils/theme'; -export * from '../../utils/themedPrompt'; -export * from '../../utils/splashScreen'; -export * from '../../utils/i18n'; -export * from '../../utils/versionChecker'; diff --git a/src/harness/adapters/index.ts b/src/harness/adapters/index.ts deleted file mode 100644 index 87027aff..00000000 --- a/src/harness/adapters/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * as out from './out'; diff --git a/src/harness/adapters/out/contextStore/index.ts b/src/harness/adapters/out/contextStore/index.ts deleted file mode 100644 index 7a362174..00000000 --- a/src/harness/adapters/out/contextStore/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from '../../../../shared/context/contextRootResolver'; -export * from '../../../../shared/context/contextLayout'; diff --git a/src/harness/adapters/out/fs/index.ts b/src/harness/adapters/out/fs/index.ts deleted file mode 100644 index 1572a628..00000000 --- a/src/harness/adapters/out/fs/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * from '../../../../utils/fileMapper'; -export * from '../../../../utils/gitignoreManager'; -export * from '../../../../utils/pathSecurity'; diff --git a/src/harness/adapters/out/git/index.ts b/src/harness/adapters/out/git/index.ts deleted file mode 100644 index c4357685..00000000 --- a/src/harness/adapters/out/git/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '../../../../utils/gitService'; diff --git a/src/harness/adapters/out/index.ts b/src/harness/adapters/out/index.ts deleted file mode 100644 index 759b0612..00000000 --- a/src/harness/adapters/out/index.ts +++ /dev/null @@ -1,8 +0,0 @@ -export * as fs from './fs'; -export * as git from './git'; -export * as semantic from './semantic'; -export * as workflowState from './workflowState'; -export * as runtimeState from './runtimeState'; -export * as contextStore from './contextStore'; -export * as toolConfig from './toolConfig'; -export * as sensors from './sensors'; diff --git a/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts b/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts index dcf4e3ae..90647a11 100644 --- a/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts +++ b/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts @@ -177,7 +177,7 @@ describe('HarnessRuntimeStateService', () => { it('lists sessions sorted by recency', async () => { const first = await service.createSession({ name: 'first' }); await service.completeSession(first.id); - const second = await service.createSession({ name: 'second' }); + await service.createSession({ name: 'second' }); const sessions = await service.listSessions(); expect(sessions.map((item) => item.name)).toEqual(['second', 'first']); diff --git a/src/harness/adapters/out/runtimeState/runtimeStateService.ts b/src/harness/adapters/out/runtimeState/runtimeStateService.ts index 8e8da574..f639930d 100644 --- a/src/harness/adapters/out/runtimeState/runtimeStateService.ts +++ b/src/harness/adapters/out/runtimeState/runtimeStateService.ts @@ -1035,7 +1035,7 @@ export class HarnessRuntimeStateService { const summary: HarnessSensorSummary = { version: 1, updatedAt: nowIso(), latestBySensor, runCount }; await this.ensureSessionDir(sessionId); await fs.ensureDir(this.sensorSummaryDir(sessionId)); - for (const [sensorId, run] of Object.entries(latestBySensor)) { + for (const run of Object.values(latestBySensor)) { await this.updateSensorSummary(sessionId, { id: randomUUID(), sessionId, level: 'info', event: 'sensor.run', message: 'sensor summary migration', createdAt: (run as Record).createdAt as string ?? summary.updatedAt, data: { run: run as Record }, diff --git a/src/harness/adapters/out/semantic/__tests__/codebaseAnalyzer.test.ts b/src/harness/adapters/out/semantic/__tests__/codebaseAnalyzer.test.ts index 96b9733f..f690f61f 100644 --- a/src/harness/adapters/out/semantic/__tests__/codebaseAnalyzer.test.ts +++ b/src/harness/adapters/out/semantic/__tests__/codebaseAnalyzer.test.ts @@ -3,7 +3,7 @@ import * as path from 'path'; import * as fs from 'fs-extra'; import { CodebaseAnalyzer, MAX_FILE_ANALYSIS_CONCURRENCY } from '../codebaseAnalyzer'; -import type { SemanticContext, FileAnalysis, ExtractedSymbol } from '../types'; +import type { FileAnalysis, ExtractedSymbol } from '../types'; jest.mock('glob', () => ({ glob: jest.fn() })); @@ -368,7 +368,7 @@ describe('CodebaseAnalyzer', () => { it('should add type info to exported symbols when LSP is enabled', async () => { const analyzer = new CodebaseAnalyzer({ useLSP: true }); - const context = await analyzer.analyze(tempDir); + await analyzer.analyze(tempDir); // LSP enhancement should have been called for exported symbols expect(mockGetTypeInfo).toHaveBeenCalled(); @@ -460,7 +460,7 @@ describe('CodebaseAnalyzer', () => { const analyzer = new CodebaseAnalyzer({ useLSP: false }); const context = await analyzer.analyze(tempDir); - const summary = analyzer.getSummary(context, tempDir); + const summary = analyzer.getSummary(context); expect(summary).toContain('## Codebase Analysis Summary'); expect(summary).toContain('**Total Files**:'); @@ -472,7 +472,7 @@ describe('CodebaseAnalyzer', () => { const analyzer = new CodebaseAnalyzer({ useLSP: false }); const context = await analyzer.analyze(tempDir); - const summary = analyzer.getSummary(context, tempDir); + const summary = analyzer.getSummary(context); expect(summary).toContain('### Architecture Layers'); }); @@ -501,7 +501,7 @@ describe('CodebaseAnalyzer', () => { const analyzer = new CodebaseAnalyzer({ useLSP: false }); const context = await analyzer.analyze(tempDir); - const summary = analyzer.getSummary(context, tempDir); + const summary = analyzer.getSummary(context); expect(summary).toContain('### Detected Patterns'); }); diff --git a/src/harness/adapters/out/semantic/codebaseAnalyzer.ts b/src/harness/adapters/out/semantic/codebaseAnalyzer.ts index 46d45e4f..c39bfa98 100644 --- a/src/harness/adapters/out/semantic/codebaseAnalyzer.ts +++ b/src/harness/adapters/out/semantic/codebaseAnalyzer.ts @@ -22,11 +22,9 @@ import { ArchitectureLayer, DetectedPattern, AnalyzerOptions, - DependencyInfo, DEFAULT_EXCLUDE_PATTERNS, LANGUAGE_EXTENSIONS, FunctionalPattern, - FunctionalPatternType, DetectedFunctionalPatterns, PatternIndicator, FlowNode, @@ -253,7 +251,7 @@ export class CodebaseAnalyzer { metrics.durationsMs.parsing = Date.now() - parsingStartedAt; // 3. Build base context - const context = this.buildBaseContext(fileAnalyses, projectPath); + const context = this.buildBaseContext(fileAnalyses); // 4. Enhance with LSP if enabled (adds type info, references) if (this.lspLayer) { @@ -470,10 +468,7 @@ export class CodebaseAnalyzer { return analyses; } - private buildBaseContext( - analyses: Map, - projectPath: string - ): SemanticContext { + private buildBaseContext(analyses: Map): SemanticContext { const symbols = { classes: [] as ExtractedSymbol[], interfaces: [] as ExtractedSymbol[], @@ -514,7 +509,7 @@ export class CodebaseAnalyzer { // Build dependency graph const importedFiles = analysis.imports - .map((imp) => this.resolveImportPath(file, imp.source, projectPath)) + .map((imp) => this.resolveImportPath(file, imp.source)) .filter((f): f is string => f !== null); dependencyGraph.set(file, importedFiles); @@ -550,8 +545,7 @@ export class CodebaseAnalyzer { private resolveImportPath( fromFile: string, - importSource: string, - projectPath: string + importSource: string ): string | null { // Skip external packages if (!importSource.startsWith('.') && !importSource.startsWith('/')) { @@ -865,7 +859,7 @@ export class CodebaseAnalyzer { if (!analysis) continue; for (const imp of analysis.imports) { - const resolved = this.resolveImportPath(file, imp.source, projectPath); + const resolved = this.resolveImportPath(file, imp.source); if (resolved) { const depLayer = fileToLayer.get(resolved); if (depLayer && depLayer !== layer.name) { @@ -882,8 +876,8 @@ export class CodebaseAnalyzer { /** * Get a summary suitable for documentation generation */ - getSummary(context: SemanticContext, projectPath: string): string { - const { symbols, architecture, stats } = context; + getSummary(context: SemanticContext): string { + const { architecture, stats } = context; const lines: string[] = [ `## Codebase Analysis Summary\n`, @@ -1069,11 +1063,11 @@ export class CodebaseAnalyzer { if (validationPattern) patterns.push(validationPattern); // Error handling pattern detection - const errorPattern = this.detectErrorHandlingPattern(allSymbols, allImports, files); + const errorPattern = this.detectErrorHandlingPattern(allSymbols, files); if (errorPattern) patterns.push(errorPattern); // Testing pattern detection - const testingPattern = this.detectTestingPattern(allSymbols, allImports, files); + const testingPattern = this.detectTestingPattern(allImports, files); if (testingPattern) patterns.push(testingPattern); return { @@ -1462,7 +1456,6 @@ export class CodebaseAnalyzer { private detectErrorHandlingPattern( symbols: ExtractedSymbol[], - imports: Array<{ source: string; specifiers: string[]; file: string }>, files: string[] ): FunctionalPattern | null { const indicators: PatternIndicator[] = []; @@ -1502,7 +1495,6 @@ export class CodebaseAnalyzer { } private detectTestingPattern( - symbols: ExtractedSymbol[], imports: Array<{ source: string; specifiers: string[]; file: string }>, files: string[] ): FunctionalPattern | null { @@ -1679,7 +1671,7 @@ export class CodebaseAnalyzer { // Check if it's an imported symbol for (const imp of analysis.imports) { if (imp.specifiers.includes(call)) { - const resolvedPath = this.resolveImportPath(filePath, imp.source, projectPath); + const resolvedPath = this.resolveImportPath(filePath, imp.source); if (resolvedPath) { const importedAnalysis = await this.treeSitter.analyzeFile(resolvedPath); const importedSymbol = importedAnalysis.symbols.find((s) => s.name === call); diff --git a/src/harness/adapters/out/semantic/contextCache.ts b/src/harness/adapters/out/semantic/contextCache.ts index f80eceb7..a35f3953 100644 --- a/src/harness/adapters/out/semantic/contextCache.ts +++ b/src/harness/adapters/out/semantic/contextCache.ts @@ -110,7 +110,7 @@ export class ContextCache { */ async get(repoPath: string, contextType: string, keyOptions?: unknown): Promise { const cache = await this.cacheForRepo(repoPath); - const key = this.buildKey(repoPath, contextType, keyOptions); + const key = this.buildKey(contextType, keyOptions); const entry = cache.get(key); if (!entry) { @@ -136,7 +136,7 @@ export class ContextCache { */ async set(repoPath: string, contextType: string, content: string, keyOptions?: unknown): Promise { const cache = await this.cacheForRepo(repoPath); - const key = this.buildKey(repoPath, contextType, keyOptions); + const key = this.buildKey(contextType, keyOptions); const freshness = await this.captureFreshness(repoPath); // Without an injected strong fingerprint, partial discovery cannot @@ -218,7 +218,7 @@ export class ContextCache { /** * Build a unique cache key from repo path and context type. */ - private buildKey(repoPath: string, contextType: string, keyOptions?: unknown): string { + private buildKey(contextType: string, keyOptions?: unknown): string { const optionsKey = keyOptions === undefined ? '' : `:${JSON.stringify(keyOptions)}`; return `${contextType}${optionsKey}`; } diff --git a/src/harness/adapters/out/toolConfig/index.ts b/src/harness/adapters/out/toolConfig/index.ts deleted file mode 100644 index a403a30a..00000000 --- a/src/harness/adapters/out/toolConfig/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -// The MCP install service is an operator-facing concern and lives on the CLI -// surface (`src/cli/services/mcpInstallService`). The harness intentionally -// does not re-export it — harness must not depend on cli. Only the shared -// tool registry, which both surfaces build on, is exposed here. -export * from '../../../../shared/registry/toolRegistry'; diff --git a/src/harness/application/context/index.ts b/src/harness/application/context/index.ts index 0b490c7d..8683115b 100644 --- a/src/harness/application/context/index.ts +++ b/src/harness/application/context/index.ts @@ -2,5 +2,3 @@ export * from './contextService'; export * from './contextTools'; export * from './analysisBundle'; export * from './boundedExplore'; -export * as intelligence from './intelligence'; -export * as scaffolding from './scaffolding'; diff --git a/src/harness/application/context/intelligence/autoFill/autoFillService.ts b/src/harness/application/context/intelligence/autoFill/autoFillService.ts index 5466b1a1..2d2c8452 100644 --- a/src/harness/application/context/intelligence/autoFill/autoFillService.ts +++ b/src/harness/application/context/intelligence/autoFill/autoFillService.ts @@ -18,11 +18,6 @@ export interface AutoFillContext { topLevelDirectories?: string[]; } -interface DirectoryStat { - name: string; - fileCount: number; -} - const SEMANTIC_SNAPSHOT_REFERENCE = 'Use `context({ action: "getMap", section: "all" })` to inspect the generated semantic snapshot for stack, architecture, key files, and dependency hotspots.'; @@ -119,7 +114,7 @@ export class AutoFillService { agentType: string, ctx: AutoFillContext ): string { - const { semantics, stackInfo } = ctx; + const { stackInfo } = ctx; // Fill "Key Files" section if (section.heading.toLowerCase().includes('key files') || section.heading.toLowerCase().includes('relevant files')) { @@ -145,7 +140,7 @@ export class AutoFillService { // ===== Project Overview Sections ===== private fillProjectOverviewSection(section: ScaffoldSection, ctx: AutoFillContext): string { - const { semantics, stackInfo, repoPath, topLevelDirectories } = ctx; + const { semantics, stackInfo, topLevelDirectories } = ctx; switch (section.heading) { case 'Project Overview': diff --git a/src/harness/application/context/intelligence/index.ts b/src/harness/application/context/intelligence/index.ts deleted file mode 100644 index db2db63c..00000000 --- a/src/harness/application/context/intelligence/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -export * as semantic from '../../../adapters/out/semantic'; -export * as stack from './stack'; -export * as qa from './qa'; -export * as autoFill from './autoFill'; diff --git a/src/harness/application/context/intelligence/qa/qaService.ts b/src/harness/application/context/intelligence/qa/qaService.ts index c895abf2..08f583f0 100644 --- a/src/harness/application/context/intelligence/qa/qaService.ts +++ b/src/harness/application/context/intelligence/qa/qaService.ts @@ -97,8 +97,7 @@ export class QAService { absolutePath, topic, stack, - patterns, - topicDetection + patterns ); if (entry) { generated.push(entry); @@ -220,8 +219,7 @@ export class QAService { repoPath: string, topic: QATopic, stack: StackInfo, - patterns: DetectedFunctionalPatterns, - topicResult: TopicDetectionResult + patterns: DetectedFunctionalPatterns ): Promise { const relevantFiles: string[] = []; let answer = ''; @@ -251,7 +249,7 @@ export class QAService { break; case 'middleware': - answer = await this.generateMiddlewareAnswer(repoPath, patterns); + answer = this.generateMiddlewareAnswer(patterns); relevantFiles.push(...(await this.findRelevantFiles(repoPath, ['middleware/', 'middlewares/']))); break; @@ -271,7 +269,7 @@ export class QAService { break; case 'testing': - answer = this.generateTestingAnswer(stack, patterns); + answer = this.generateTestingAnswer(stack); relevantFiles.push(...(await this.findRelevantFiles(repoPath, ['test/', 'tests/', '__tests__/', '*.test.', '*.spec.']))); break; @@ -535,10 +533,7 @@ export class QAService { return lines.join('\n'); } - private async generateMiddlewareAnswer( - repoPath: string, - patterns: DetectedFunctionalPatterns - ): Promise { + private generateMiddlewareAnswer(patterns: DetectedFunctionalPatterns): string { const lines: string[] = []; lines.push('## Middleware\n'); lines.push('Middleware functions process requests before they reach route handlers.\n'); @@ -620,7 +615,7 @@ export class QAService { return lines.join('\n'); } - private generateTestingAnswer(stack: StackInfo, patterns: DetectedFunctionalPatterns): string { + private generateTestingAnswer(stack: StackInfo): string { const lines: string[] = []; lines.push('## Testing\n'); diff --git a/src/harness/application/context/scaffolding/generators/agents/agentConfig.ts b/src/harness/application/context/scaffolding/generators/agents/agentConfig.ts index 55d372f3..b2115892 100644 --- a/src/harness/application/context/scaffolding/generators/agents/agentConfig.ts +++ b/src/harness/application/context/scaffolding/generators/agents/agentConfig.ts @@ -92,88 +92,3 @@ export const AGENT_RESPONSIBILITIES: Record = { 'Integrate push notifications and offline capabilities' ] }; - -export const AGENT_BEST_PRACTICES: Record = { - 'code-reviewer': [ - 'Focus on maintainability and readability', - 'Consider the broader impact of changes', - 'Be constructive and specific in feedback' - ], - 'bug-fixer': [ - 'Reproduce the bug before fixing', - 'Write tests to prevent regression', - 'Document the fix for future reference' - ], - 'feature-developer': [ - 'Follow existing patterns and conventions', - 'Consider edge cases and error handling', - 'Write tests alongside implementation' - ], - 'refactoring-specialist': [ - 'Make small, incremental changes', - 'Ensure tests pass after each refactor', - 'Preserve existing functionality exactly' - ], - 'test-writer': [ - 'Write tests that are clear and maintainable', - 'Test both happy path and edge cases', - 'Use descriptive test names' - ], - 'documentation-writer': [ - 'Keep documentation up-to-date with code', - 'Write from the user\'s perspective', - 'Include practical examples' - ], - 'performance-optimizer': [ - 'Measure before optimizing', - 'Focus on actual bottlenecks', - 'Don\'t sacrifice readability unnecessarily' - ], - 'security-auditor': [ - 'Follow security best practices', - 'Stay updated on common vulnerabilities', - 'Consider the principle of least privilege' - ], - 'backend-specialist': [ - 'Design APIs according the specification of the project', - 'Implement proper error handling and logging', - 'Use appropriate design patterns and clean architecture', - 'Consider scalability and performance from the start', - 'Implement comprehensive testing for business logic' - ], - 'frontend-specialist': [ - 'Follow modern frontend development patterns', - 'Optimize for accessibility and user experience', - 'Implement responsive design principles', - 'Use component-based architecture effectively', - 'Optimize performance and loading times' - ], - 'architect-specialist': [ - 'Consider long-term maintainability and scalability', - 'Balance technical debt with business requirements', - 'Document architectural decisions and rationale', - 'Promote code reusability and modularity', - 'Stay updated on industry trends and technologies' - ], - 'devops-specialist': [ - 'Automate everything that can be automated', - 'Implement infrastructure as code for reproducibility', - 'Monitor system health proactively', - 'Design for failure and implement proper fallbacks', - 'Keep security and compliance in every deployment' - ], - 'database-specialist': [ - 'Always benchmark queries before and after optimization', - 'Plan migrations with rollback strategies', - 'Use appropriate indexing strategies for workloads', - 'Maintain data consistency across transactions', - 'Document schema changes and their business impact' - ], - 'mobile-specialist': [ - 'Test on real devices, not just simulators', - 'Optimize for battery life and data usage', - 'Follow platform-specific design guidelines', - 'Implement proper offline-first strategies', - 'Plan for app store review requirements early' - ] -}; \ No newline at end of file diff --git a/src/harness/application/context/scaffolding/generators/agents/agentGenerator.ts b/src/harness/application/context/scaffolding/generators/agents/agentGenerator.ts index 6650557d..dddfbcd3 100644 --- a/src/harness/application/context/scaffolding/generators/agents/agentGenerator.ts +++ b/src/harness/application/context/scaffolding/generators/agents/agentGenerator.ts @@ -3,9 +3,7 @@ import { RepoStructure } from '../../../../../../types'; import { GeneratorUtils } from '../shared'; import { AGENT_TYPES, AgentType } from './agentTypes'; import { renderAgentIndex } from './templates'; -import { DOCUMENT_GUIDES } from '../documentation/guideRegistry'; -import { CodebaseAnalyzer, SemanticContext, ExtractedSymbol } from '../../../../../adapters/out/semantic'; -import { KeySymbolInfo } from './templates/types'; +import { CodebaseAnalyzer, SemanticContext } from '../../../../../adapters/out/semantic'; import { AGENT_RESPONSIBILITIES } from './agentConfig'; import { createAgentFrontmatter, @@ -93,17 +91,6 @@ function formatAgentTitle(agentType: AgentType): string { } export class AgentGenerator { - private readonly docTouchpoints = [ - { - title: 'Documentation Index', - path: '../docs/README.md' - }, - ...DOCUMENT_GUIDES.map(guide => ({ - title: guide.title, - path: `../docs/${guide.file}` - })) - ]; - private analyzer?: CodebaseAnalyzer; constructor(..._legacyArgs: unknown[]) {} @@ -241,97 +228,6 @@ export class AgentGenerator { return `\n## Available Skills\n\nThe following skills provide detailed procedures for specific tasks. Activate them when needed:\n\n| Skill | Description |\n|-------|-------------|\n${rows.join('\n')}\n`; } - private getRelevantSymbolsForAgent(agentType: AgentType, semantics?: SemanticContext): KeySymbolInfo[] { - if (!semantics) return []; - - const { symbols } = semantics; - let relevantSymbols: ExtractedSymbol[] = []; - - // Filter symbols based on agent type - switch (agentType) { - case 'test-writer': - // Test writer needs test-related symbols - relevantSymbols = [ - ...symbols.functions.filter(s => /test|spec|mock|stub/i.test(s.name)), - ...symbols.classes.filter(s => /test|spec/i.test(s.name)), - ]; - break; - - case 'code-reviewer': - case 'refactoring-specialist': - // These need main classes and interfaces - relevantSymbols = [ - ...symbols.classes.filter(s => s.exported), - ...symbols.interfaces.filter(s => s.exported), - ]; - break; - - case 'documentation-writer': - // Documentation writer needs exported symbols - relevantSymbols = [ - ...symbols.classes.filter(s => s.exported), - ...symbols.interfaces.filter(s => s.exported), - ...symbols.functions.filter(s => s.exported), - ...symbols.types.filter(s => s.exported), - ]; - break; - - case 'security-auditor': - // Security auditor needs auth-related symbols - relevantSymbols = [ - ...symbols.functions.filter(s => /auth|security|crypt|token|password|secret/i.test(s.name)), - ...symbols.classes.filter(s => /auth|security|guard|policy/i.test(s.name)), - ]; - break; - - case 'performance-optimizer': - // Performance needs cache, async, and data processing symbols - relevantSymbols = [ - ...symbols.functions.filter(s => /cache|async|batch|queue|pool/i.test(s.name)), - ...symbols.classes.filter(s => /cache|pool|buffer|queue/i.test(s.name)), - ]; - break; - - case 'database-specialist': - // Database specialist needs repository and model symbols - relevantSymbols = [ - ...symbols.classes.filter(s => /repository|model|entity|schema|migration/i.test(s.name)), - ...symbols.interfaces.filter(s => /repository|model|entity/i.test(s.name)), - ]; - break; - - case 'backend-specialist': - // Backend needs services, controllers, handlers - relevantSymbols = [ - ...symbols.classes.filter(s => /service|controller|handler|middleware/i.test(s.name)), - ]; - break; - - case 'frontend-specialist': - // Frontend needs components and hooks - relevantSymbols = [ - ...symbols.functions.filter(s => /^use[A-Z]/i.test(s.name)), // hooks - ...symbols.classes.filter(s => /component|view|page|screen/i.test(s.name)), - ]; - break; - - default: - // Default: top exported symbols - relevantSymbols = [ - ...symbols.classes.filter(s => s.exported).slice(0, 5), - ...symbols.interfaces.filter(s => s.exported).slice(0, 5), - ]; - } - - // Convert to KeySymbolInfo and limit - return relevantSymbols.slice(0, 15).map(s => ({ - name: s.name, - kind: s.kind, - file: s.location.file, - line: s.location.line, - })); - } - private resolveAgentSelection( selected?: string[], filteredByProjectType?: AgentType[] diff --git a/src/harness/application/context/scaffolding/generators/agents/agentTypes.ts b/src/harness/application/context/scaffolding/generators/agents/agentTypes.ts index 647d895f..eed668ff 100644 --- a/src/harness/application/context/scaffolding/generators/agents/agentTypes.ts +++ b/src/harness/application/context/scaffolding/generators/agents/agentTypes.ts @@ -16,9 +16,3 @@ export const AGENT_TYPES = [ ] as const; export type AgentType = typeof AGENT_TYPES[number]; - -export const IMPORTANT_FILES = [ - 'package.json', 'tsconfig.json', 'webpack.config.js', - 'next.config.js', 'tailwind.config.js', 'README.md', - '.gitignore', 'Dockerfile', 'docker-compose.yml' -]; \ No newline at end of file diff --git a/src/harness/application/context/scaffolding/generators/agents/index.ts b/src/harness/application/context/scaffolding/generators/agents/index.ts deleted file mode 100644 index 973cf1fc..00000000 --- a/src/harness/application/context/scaffolding/generators/agents/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -export { AgentGenerator } from './agentGenerator'; -export { AGENT_TYPES, AgentType, IMPORTANT_FILES } from './agentTypes'; -export { AGENT_RESPONSIBILITIES, AGENT_BEST_PRACTICES } from './agentConfig'; diff --git a/src/harness/application/context/scaffolding/generators/agents/templates/index.ts b/src/harness/application/context/scaffolding/generators/agents/templates/index.ts index d384a343..7d9e372b 100644 --- a/src/harness/application/context/scaffolding/generators/agents/templates/index.ts +++ b/src/harness/application/context/scaffolding/generators/agents/templates/index.ts @@ -1,2 +1 @@ export { renderAgentIndex } from './indexTemplate'; -export type { AgentTemplateContext, DocTouchpoint } from './types'; diff --git a/src/harness/application/context/scaffolding/generators/agents/templates/types.ts b/src/harness/application/context/scaffolding/generators/agents/templates/types.ts deleted file mode 100644 index 508db351..00000000 --- a/src/harness/application/context/scaffolding/generators/agents/templates/types.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { AgentType } from '../agentTypes'; -import { SemanticContext } from '../../../../../../adapters/out/semantic'; - -export interface DocTouchpoint { - title: string; - path: string; -} - -export interface KeySymbolInfo { - name: string; - kind: string; - file: string; - line: number; -} - -export interface AgentTemplateContext { - agentType: AgentType; - topLevelDirectories: string[]; - docTouchpoints: DocTouchpoint[]; - responsibilities: string[]; - bestPractices: string[]; - semantics?: SemanticContext; - relevantSymbols?: KeySymbolInfo[]; -} diff --git a/src/harness/application/context/scaffolding/generators/documentation/documentationGenerator.ts b/src/harness/application/context/scaffolding/generators/documentation/documentationGenerator.ts index ca202cf0..b0d4df95 100644 --- a/src/harness/application/context/scaffolding/generators/documentation/documentationGenerator.ts +++ b/src/harness/application/context/scaffolding/generators/documentation/documentationGenerator.ts @@ -7,7 +7,7 @@ import { GuideMeta, renderIndex, } from './templates'; -import { getGuidesByKeys, DOCUMENT_GUIDES } from './guideRegistry'; +import { getGuidesByKeys } from './guideRegistry'; import { CodebaseAnalyzer, SemanticContext, @@ -20,7 +20,7 @@ import { serializeFrontmatter, DocScaffoldFrontmatter, } from '../../../../../../types/scaffoldFrontmatter'; -import { getScaffoldStructure, ScaffoldStructure, serializeStructureAsMarkdown } from '../shared/structures'; +import { getScaffoldStructure, serializeStructureAsMarkdown } from '../shared/structures'; import { AutoFillService, AutoFillContext } from '../../../intelligence/autoFill'; import type { AnalysisBundle } from '../../../analysisBundle'; diff --git a/src/harness/application/context/scaffolding/generators/documentation/guideRegistry.ts b/src/harness/application/context/scaffolding/generators/documentation/guideRegistry.ts index a5c7dece..06b55a6b 100644 --- a/src/harness/application/context/scaffolding/generators/documentation/guideRegistry.ts +++ b/src/harness/application/context/scaffolding/generators/documentation/guideRegistry.ts @@ -62,13 +62,3 @@ export function getGuidesByKeys(keys?: string[]): GuideMeta[] { const filtered = DOCUMENT_GUIDES.filter(guide => set.has(guide.key)); return filtered.length > 0 ? filtered : DOCUMENT_GUIDES; } - -export function getDocFilesByKeys(keys?: string[]): Set | undefined { - if (!keys || keys.length === 0) { - return undefined; - } - const files = DOCUMENT_GUIDES - .filter(guide => keys.includes(guide.key)) - .map(guide => guide.file); - return files.length ? new Set(files) : undefined; -} diff --git a/src/harness/application/context/scaffolding/generators/documentation/index.ts b/src/harness/application/context/scaffolding/generators/documentation/index.ts deleted file mode 100644 index 85b44a14..00000000 --- a/src/harness/application/context/scaffolding/generators/documentation/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -export { DocumentationGenerator } from './documentationGenerator'; -export { CodebaseMapGenerator } from './codebaseMapGenerator'; -export type { CodebaseMap, CodebaseMapOptions, KeyFile, NavigationHints, SemanticSnapshotMetadata } from './codebaseMapGenerator'; diff --git a/src/harness/application/context/scaffolding/generators/documentation/templates/common.ts b/src/harness/application/context/scaffolding/generators/documentation/templates/common.ts index 1f7a83dd..7b767655 100644 --- a/src/harness/application/context/scaffolding/generators/documentation/templates/common.ts +++ b/src/harness/application/context/scaffolding/generators/documentation/templates/common.ts @@ -1,25 +1,4 @@ -import * as path from 'path'; -import { DirectoryStat, DocumentationTemplateContext } from './types'; -import type { ExtractedSymbol } from '../../../../../../adapters/out/semantic/types'; - -/** - * Wrap template content with YAML front matter for status detection. - * This allows instant detection of unfilled files by reading only the first line. - */ -export function wrapWithFrontMatter( - content: string, - options?: { name?: string; description?: string } -): string { - const date = new Date().toISOString().split('T')[0]; - const nameLine = options?.name ? `name: ${options.name}\n` : ''; - const descLine = options?.description ? `description: ${options.description}\n` : ''; - return `--- -${nameLine}${descLine}status: unfilled -generated: ${date} ---- - -${content}`; -} +import { DocumentationTemplateContext } from './types'; const KNOWN_DESCRIPTIONS: Record = { src: 'TypeScript source files and CLI entrypoints.', @@ -58,146 +37,3 @@ export function buildDocumentMapTable(guides: DocumentationTemplateContext['guid const rows = guides.map(meta => `| ${meta.title} | \`${meta.file}\` | ${meta.primaryInputs} |`); return ['| Guide | File | Primary Inputs |', '| --- | --- | --- |', ...rows].join('\n'); } - -export function formatDirectoryStats(stats: DirectoryStat[]): string { - if (!stats.length) { - return '*No directories detected.*'; - } - - return stats - .map(stat => `- \`${stat.name}/\` — approximately ${stat.fileCount} files`) - .join('\n'); -} - -export function formatInlineDirectoryList(directories: string[]): string { - if (!directories.length) { - return '`n/a`'; - } - - return directories.map(dir => `\`${dir}\``).join(', '); -} - -// Code Reference Helpers - -/** - * Format a symbol as a markdown link with line number - * Output: [`SymbolName`](src/path/file.ts#L42) - */ -export function formatSymbolRef( - symbol: ExtractedSymbol, - repoRoot: string -): string { - const relPath = path.relative(repoRoot, symbol.location.file); - return `[\`${symbol.name}\`](${relPath}#L${symbol.location.line})`; -} - -/** - * Format a file:line reference (non-link format) - * Output: src/path/file.ts:42 - */ -export function formatCodeLocation( - filePath: string, - line: number, - repoRoot: string -): string { - const relPath = path.relative(repoRoot, filePath); - return `${relPath}:${line}`; -} - -/** - * Format a file path as a markdown link with line number - * Output: [`file.ts`](src/path/file.ts#L42) - */ -export function formatFileRef( - filePath: string, - line: number, - repoRoot: string, - displayName?: string -): string { - const relPath = path.relative(repoRoot, filePath); - const name = displayName || path.basename(filePath); - return `[\`${name}\`](${relPath}#L${line})`; -} - -/** - * Build a markdown table of symbols with links - */ -export function buildSymbolTable( - symbols: ExtractedSymbol[], - repoRoot: string, - columns: ('name' | 'kind' | 'location' | 'description')[] = ['name', 'kind', 'location'] -): string { - if (symbols.length === 0) { - return '*No symbols found.*'; - } - - const headers: Record = { - name: 'Symbol', - kind: 'Type', - location: 'Location', - description: 'Description' - }; - - const headerRow = '| ' + columns.map(c => headers[c]).join(' | ') + ' |'; - const separatorRow = '| ' + columns.map(() => '---').join(' | ') + ' |'; - - const dataRows = symbols.map(sym => { - const cells = columns.map(col => { - switch (col) { - case 'name': - return formatSymbolRef(sym, repoRoot); - case 'kind': - return sym.kind; - case 'location': - return formatCodeLocation(sym.location.file, sym.location.line, repoRoot); - case 'description': - return sym.documentation || '-'; - default: - return '-'; - } - }); - return '| ' + cells.join(' | ') + ' |'; - }); - - return [headerRow, separatorRow, ...dataRows].join('\n'); -} - -/** - * Build a bullet list of symbols with links - */ -export function buildSymbolList( - symbols: ExtractedSymbol[], - repoRoot: string, - includeKind: boolean = true -): string { - if (symbols.length === 0) { - return '*No symbols found.*'; - } - - return symbols.map(sym => { - const ref = formatSymbolRef(sym, repoRoot); - const kindSuffix = includeKind ? ` (${sym.kind})` : ''; - const docSuffix = sym.documentation ? ` — ${sym.documentation}` : ''; - return `- ${ref}${kindSuffix}${docSuffix}`; - }).join('\n'); -} - -/** - * Group symbols by their containing directory - */ -export function groupSymbolsByDirectory( - symbols: ExtractedSymbol[], - repoRoot: string -): Map { - const groups = new Map(); - - for (const sym of symbols) { - const relPath = path.relative(repoRoot, sym.location.file); - const dir = path.dirname(relPath); - const existing = groups.get(dir) || []; - existing.push(sym); - groups.set(dir, existing); - } - - return groups; -} diff --git a/src/harness/application/context/scaffolding/generators/documentation/templates/index.ts b/src/harness/application/context/scaffolding/generators/documentation/templates/index.ts index b82c05bc..ad01d45a 100644 --- a/src/harness/application/context/scaffolding/generators/documentation/templates/index.ts +++ b/src/harness/application/context/scaffolding/generators/documentation/templates/index.ts @@ -1,2 +1,2 @@ export { renderIndex } from './indexTemplate'; -export type { DocumentationTemplateContext, GuideMeta, DirectoryStat } from './types'; +export type { DocumentationTemplateContext, GuideMeta } from './types'; diff --git a/src/harness/application/context/scaffolding/generators/plans/index.ts b/src/harness/application/context/scaffolding/generators/plans/index.ts deleted file mode 100644 index f6608106..00000000 --- a/src/harness/application/context/scaffolding/generators/plans/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { PlanGenerator } from './planGenerator'; diff --git a/src/harness/application/context/scaffolding/generators/skills/index.ts b/src/harness/application/context/scaffolding/generators/skills/index.ts index c2ec3205..24b0a106 100644 --- a/src/harness/application/context/scaffolding/generators/skills/index.ts +++ b/src/harness/application/context/scaffolding/generators/skills/index.ts @@ -9,6 +9,6 @@ export { createSkillGenerator, } from './skillGenerator'; -export { generateSkillContent, getDefaultPhases } from './templates/skillTemplate'; +export { getDefaultPhases } from './templates/skillTemplate'; export { generateSkillsIndex } from './templates/indexTemplate'; diff --git a/src/harness/application/context/scaffolding/generators/skills/templates/skillTemplate.ts b/src/harness/application/context/scaffolding/generators/skills/templates/skillTemplate.ts index 5da03aab..8a4f1abd 100644 --- a/src/harness/application/context/scaffolding/generators/skills/templates/skillTemplate.ts +++ b/src/harness/application/context/scaffolding/generators/skills/templates/skillTemplate.ts @@ -1,108 +1,6 @@ -/** - * SKILL.md Template - * - * REFERENCE ONLY - This file is not used by generators anymore. - * - * Scaffold structures are now defined in the harness context scaffolding - * layer. - * - * This file serves as historical reference for the structure/content - * that should be generated for this skill type. - * - * @deprecated Since v2.0.0 scaffold system - */ - -import { SkillMetadata, SKILL_TO_PHASES, BuiltInSkillType, isBuiltInSkill } from '../../../../../../domain/workflow/skills'; +import { SKILL_TO_PHASES, BuiltInSkillType, isBuiltInSkill } from '../../../../../../domain/workflow/skills'; import { PrevcPhase } from '../../../../../../domain/workflow/types'; -export interface SkillTemplateOptions { - name: string; - description: string; - phases?: PrevcPhase[]; - mode?: boolean; - disableModelInvocation?: boolean; -} - -/** - * Generate SKILL.md content - */ -export function generateSkillContent(options: SkillTemplateOptions): string { - const { name, description, phases, mode, disableModelInvocation } = options; - - const frontmatter = buildFrontmatter({ - name, - description, - phases, - mode, - disableModelInvocation, - }); - - const body = buildBody(name, description); - - return `${frontmatter}\n\n${body}`; -} - -function buildFrontmatter(options: SkillTemplateOptions): string { - const lines: string[] = ['---']; - - lines.push(`name: ${options.name}`); - lines.push(`description: ${options.description}`); - - if (options.phases && options.phases.length > 0) { - lines.push(`phases: [${options.phases.join(', ')}]`); - } - - if (options.mode !== undefined) { - lines.push(`mode: ${options.mode}`); - } - - if (options.disableModelInvocation !== undefined) { - lines.push(`disable-model-invocation: ${options.disableModelInvocation}`); - } - - lines.push('---'); - - return lines.join('\n'); -} - -function buildBody(name: string, description: string): string { - const title = name - .split('-') - .map((word) => word.charAt(0).toUpperCase() + word.slice(1)) - .join(' '); - - return `# ${title} - -## When to Use - -${description} - -## Instructions - - - -1. First step -2. Second step -3. Third step - -## Examples - - - -\`\`\` -Example usage here -\`\`\` - -## Guidelines - - - -- Guideline 1 -- Guideline 2 -- Guideline 3 -`; -} - /** * Get default phases for a skill name */ diff --git a/src/harness/application/context/scaffolding/index.ts b/src/harness/application/context/scaffolding/index.ts deleted file mode 100644 index d1e8cbc2..00000000 --- a/src/harness/application/context/scaffolding/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -export * as generators from './generators/shared'; -export * as documentation from './generators/documentation'; -export * as agents from './generators/agents'; -export * as plans from './generators/plans'; -export * as skills from './generators/skills'; diff --git a/src/harness/application/context/stateDetector.ts b/src/harness/application/context/stateDetector.ts index c1292511..6c0cd96b 100644 --- a/src/harness/application/context/stateDetector.ts +++ b/src/harness/application/context/stateDetector.ts @@ -16,7 +16,7 @@ import * as path from 'path'; import * as fs from 'fs-extra'; import { glob } from 'glob'; -import { needsFill, getFilledStats } from '../../../utils/frontMatter'; +import { getFilledStats } from '../../../utils/frontMatter'; export type ProjectState = 'new' | 'unfilled' | 'ready' | 'outdated'; @@ -200,5 +200,3 @@ export class StateDetector { } } } - -export { StateDetector as default }; diff --git a/src/harness/application/contracts/taskContractsService.ts b/src/harness/application/contracts/taskContractsService.ts index e682cce3..eef7527b 100644 --- a/src/harness/application/contracts/taskContractsService.ts +++ b/src/harness/application/contracts/taskContractsService.ts @@ -232,10 +232,6 @@ export class HarnessTaskContractsService { return resolveRuntimeLayoutFromRepo(this.options.repoPath); } - private get contractsPath(): string { - return this.layout.contractsDir; - } - private get tasksPath(): string { return this.layout.contractTasksDir; } diff --git a/src/harness/application/exchange/import/importAgentsService.ts b/src/harness/application/exchange/import/importAgentsService.ts index fc6ad003..8d0b9faa 100644 --- a/src/harness/application/exchange/import/importAgentsService.ts +++ b/src/harness/application/exchange/import/importAgentsService.ts @@ -16,13 +16,11 @@ import { AgentsDetector } from './agentsDetector'; export class ImportAgentsService { private readonly ui: CLIInterface; private readonly t: TranslateFn; - private readonly version: string; private readonly detector: AgentsDetector; constructor(dependencies: ImportServiceDependencies) { this.ui = dependencies.ui; this.t = dependencies.t; - this.version = dependencies.version; this.detector = new AgentsDetector(); } diff --git a/src/harness/application/exchange/import/importRulesService.ts b/src/harness/application/exchange/import/importRulesService.ts index 898f4bc2..6cdd0f2b 100644 --- a/src/harness/application/exchange/import/importRulesService.ts +++ b/src/harness/application/exchange/import/importRulesService.ts @@ -17,13 +17,11 @@ import { RulesDetector } from './rulesDetector'; export class ImportRulesService { private readonly ui: CLIInterface; private readonly t: TranslateFn; - private readonly version: string; private readonly detector: RulesDetector; constructor(dependencies: ImportServiceDependencies) { this.ui = dependencies.ui; this.t = dependencies.t; - this.version = dependencies.version; this.detector = new RulesDetector(); } diff --git a/src/harness/application/exchange/index.ts b/src/harness/application/exchange/index.ts deleted file mode 100644 index 6d7fbeb7..00000000 --- a/src/harness/application/exchange/index.ts +++ /dev/null @@ -1,11 +0,0 @@ -export * from './syncActionService'; -export * from './sync'; -export * from './import'; -export * from './export'; -export * from './reverseSync'; -export * from './quickSync'; -export * as sync from './sync'; -export * as importServices from './import'; -export * as exportServices from './export'; -export * as reverseSync from './reverseSync'; -export * as quickSync from './quickSync'; diff --git a/src/harness/application/exchange/reverseSync/importSkillsService.ts b/src/harness/application/exchange/reverseSync/importSkillsService.ts index 1b6bc513..027fb9da 100644 --- a/src/harness/application/exchange/reverseSync/importSkillsService.ts +++ b/src/harness/application/exchange/reverseSync/importSkillsService.ts @@ -10,12 +10,10 @@ import * as fs from 'fs-extra'; import { colors, symbols, typography } from '../../../../utils/theme'; import type { CLIInterface } from '../../../../utils/cliUI'; -import type { TranslateFn } from '../../../../utils/i18n'; import type { ImportSkillsCommandFlags, ImportSkillsOptions, SkillFileInfo, - MergeStrategy, ImportMetadata, ReverseSyncServiceDependencies, ImportAction, @@ -40,14 +38,10 @@ export interface ImportSkillsResult { export class ImportSkillsService { private readonly ui: CLIInterface; - private readonly t: TranslateFn; - private readonly version: string; private readonly detector: SkillsDetector; constructor(dependencies: ReverseSyncServiceDependencies) { this.ui = dependencies.ui; - this.t = dependencies.t; - this.version = dependencies.version; this.detector = new SkillsDetector(); } @@ -185,7 +179,7 @@ export class ImportSkillsService { } if (options.verbose) { - this.logImportAction(file, importResult); + this.logImportAction(importResult); } } catch (error) { result.filesFailed++; @@ -379,7 +373,6 @@ export class ImportSkillsService { } private logImportAction( - skill: SkillFileInfo, result: { action: ImportAction; targetPath: string } ): void { const actionSymbols: Record = { diff --git a/src/harness/application/exchange/reverseSync/reverseQuickSyncService.ts b/src/harness/application/exchange/reverseSync/reverseQuickSyncService.ts index e77ed581..16d2929c 100644 --- a/src/harness/application/exchange/reverseSync/reverseQuickSyncService.ts +++ b/src/harness/application/exchange/reverseSync/reverseQuickSyncService.ts @@ -6,45 +6,30 @@ */ import * as path from 'path'; -import * as fs from 'fs-extra'; - import { colors, symbols, typography } from '../../../../utils/theme'; import type { CLIInterface } from '../../../../utils/cliUI'; -import type { TranslateFn } from '../../../../utils/i18n'; import type { ReverseSyncServiceDependencies, ReverseSyncOptions, ReverseSyncResult, ReverseSyncCommandFlags, ToolDetectionResult, - MergeStrategy, - ImportAction, } from './types'; -import type { ImportFormat } from '../import/types'; import { ToolDetector, formatDetectionSummary } from './toolDetector'; -import { SkillsDetector } from './skillsDetector'; import { ImportSkillsService } from './importSkillsService'; import { ImportRulesService } from '../import/importRulesService'; import { ImportAgentsService } from '../import/importAgentsService'; -import { getToolIdFromPath } from './presets'; -import { VERSION } from '../../../../version'; export class ReverseQuickSyncService { private readonly ui: CLIInterface; - private readonly t: TranslateFn; - private readonly version: string; private readonly toolDetector: ToolDetector; - private readonly skillsDetector: SkillsDetector; private readonly importSkillsService: ImportSkillsService; private readonly importRulesService: ImportRulesService; private readonly importAgentsService: ImportAgentsService; constructor(deps: ReverseSyncServiceDependencies) { this.ui = deps.ui; - this.t = deps.t; - this.version = deps.version; this.toolDetector = new ToolDetector(); - this.skillsDetector = new SkillsDetector(); this.importSkillsService = new ImportSkillsService(deps); this.importRulesService = new ImportRulesService(deps); this.importAgentsService = new ImportAgentsService(deps); diff --git a/src/harness/application/exchange/reverseSync/toolDetector.ts b/src/harness/application/exchange/reverseSync/toolDetector.ts index 8f6452bf..d41eb5c8 100644 --- a/src/harness/application/exchange/reverseSync/toolDetector.ts +++ b/src/harness/application/exchange/reverseSync/toolDetector.ts @@ -12,8 +12,6 @@ import { AgentsDetector } from '../import/agentsDetector'; import { SkillsDetector } from './skillsDetector'; import { ALL_TOOL_IDS, - TOOL_DISPLAY_NAMES, - TOOL_CAPABILITIES, getToolIdFromPath, getToolDisplayName, } from './presets'; @@ -81,12 +79,6 @@ export class ToolDetector { const toolMap = new Map(); for (const toolId of ALL_TOOL_IDS) { - const capabilities = TOOL_CAPABILITIES[toolId] || { - rules: false, - agents: false, - skills: false, - }; - toolMap.set(toolId, { id: toolId, displayName: getToolDisplayName(toolId), diff --git a/src/harness/application/exchange/sync/symlinkHandler.ts b/src/harness/application/exchange/sync/symlinkHandler.ts index 2865acee..84971f66 100644 --- a/src/harness/application/exchange/sync/symlinkHandler.ts +++ b/src/harness/application/exchange/sync/symlinkHandler.ts @@ -10,7 +10,6 @@ function getTargetFilename(agent: AgentFileInfo, options: HandlerOptions): strin export async function createSymlinks( agentFiles: AgentFileInfo[], targetPath: string, - sourcePath: string, options: HandlerOptions ): Promise { const result: HandlerResult = { diff --git a/src/harness/application/exchange/sync/syncService.ts b/src/harness/application/exchange/sync/syncService.ts index 91eb4fc7..ec0272b5 100644 --- a/src/harness/application/exchange/sync/syncService.ts +++ b/src/harness/application/exchange/sync/syncService.ts @@ -20,12 +20,10 @@ import { createMarkdownReferences } from './markdownReferenceHandler'; export class SyncService { private readonly ui: CLIInterface; private readonly t: TranslateFn; - private readonly version: string; constructor(dependencies: SyncServiceDependencies) { this.ui = dependencies.ui; this.t = dependencies.t; - this.version = dependencies.version; } async run(rawOptions: SyncCommandFlags): Promise { @@ -193,7 +191,7 @@ export class SyncService { const preset = getPresetByPath(targetPath); const handlerResult = options.mode === 'symlink' - ? await createSymlinks(agentFiles, targetPath, options.sourcePath, { + ? await createSymlinks(agentFiles, targetPath, { force: options.force, dryRun: options.dryRun, verbose: options.verbose, diff --git a/src/harness/application/execution/executionService.ts b/src/harness/application/execution/executionService.ts index e899d033..2116985d 100644 --- a/src/harness/application/execution/executionService.ts +++ b/src/harness/application/execution/executionService.ts @@ -61,7 +61,7 @@ export class HarnessExecutionService { readonly replay: HarnessReplayService; readonly datasets: HarnessDatasetService; - constructor(private readonly options: HarnessExecutionServiceOptions) { + constructor(options: HarnessExecutionServiceOptions) { this.state = new HarnessRuntimeStateService({ repoPath: options.repoPath }); this.sensors = new HarnessSensorsService({ stateService: this.state }); this.contracts = new HarnessTaskContractsService({ diff --git a/src/harness/application/index.ts b/src/harness/application/index.ts index 2ac80d94..5d7d6cf0 100644 --- a/src/harness/application/index.ts +++ b/src/harness/application/index.ts @@ -15,11 +15,3 @@ export * from './history'; export * from '../adapters/out/runtimeState'; export * from '../adapters/out/workflowState'; export * from '../adapters/out/sensors'; - -export * as actions from './actions'; -export * as hooks from './hooks'; -export * as workflow from './workflow'; -export * as context from './context'; -export * as exchange from './exchange'; -export * as agents from './agents'; -export * as skills from './skills'; diff --git a/src/harness/application/sensors/sensorsService.ts b/src/harness/application/sensors/sensorsService.ts index 89305069..26c43307 100644 --- a/src/harness/application/sensors/sensorsService.ts +++ b/src/harness/application/sensors/sensorsService.ts @@ -9,7 +9,6 @@ import { randomUUID } from 'crypto'; import type { AppendTraceInput, HarnessRuntimeStatePort, - HarnessTraceRecord, } from '../../adapters/out/runtimeState/runtimeStateService'; import type { RuntimeHistoryPage, RuntimeHistoryQuery } from '../history/runtimeHistory'; diff --git a/src/harness/application/workflow/autoAdvance.ts b/src/harness/application/workflow/autoAdvance.ts deleted file mode 100644 index fe5b70fa..00000000 --- a/src/harness/application/workflow/autoAdvance.ts +++ /dev/null @@ -1,231 +0,0 @@ -/** - * Auto-Advance Service - * - * Automatically detects when phase outputs are complete and advances the workflow. - */ - -import * as path from 'path'; -import * as fs from 'fs-extra'; -import { glob } from 'glob'; -import { - PrevcPhase, - PrevcStatus, - getOutputsForPhase, -} from '../../domain/workflow'; - -export interface AutoAdvanceResult { - shouldAdvance: boolean; - reason?: string; - detectedOutputs: string[]; - missingOutputs: string[]; -} - -/** - * Expected outputs for each phase (file patterns) - */ -const PHASE_OUTPUT_PATTERNS: Record = { - P: [ - '**/PRD.md', - '**/requirements*.md', - '**/specs*.md', - '**/user-stories*.md', - '**/*planning*.md', - ], - R: [ - '**/architecture*.md', - '**/design*.md', - '**/ADR*.md', - '**/tech-spec*.md', - '**/*review*.md', - ], - E: [ - '**/*.ts', - '**/*.tsx', - '**/*.js', - '**/*.jsx', - '**/*.py', - '**/*.go', - '**/*.rs', - '**/*.java', - ], - V: [ - '**/*.test.*', - '**/*.spec.*', - '**/test_*.py', - '**/*_test.go', - '**/tests/**', - '**/__tests__/**', - ], - C: [ - '**/CHANGELOG*.md', - '**/RELEASE*.md', - '**/deployment*.md', - '**/*confirmation*.md', - ], -}; - -/** - * Minimum number of new files to consider phase complete - */ -const PHASE_MIN_FILES: Record = { - P: 1, - R: 1, - E: 1, - V: 1, - C: 1, -}; - -export class AutoAdvanceDetector { - private contextPath: string; - private repoPath: string; - - constructor(repoPath: string) { - this.repoPath = path.resolve(repoPath); - this.contextPath = path.join(this.repoPath, '.context'); - } - - /** - * Check if the current phase should auto-advance - */ - async checkAutoAdvance( - currentPhase: PrevcPhase, - status: PrevcStatus - ): Promise { - const result: AutoAdvanceResult = { - shouldAdvance: false, - detectedOutputs: [], - missingOutputs: [], - }; - - const patterns = PHASE_OUTPUT_PATTERNS[currentPhase]; - const minFiles = PHASE_MIN_FILES[currentPhase]; - - // Get phase start time - const phaseStatus = status.phases[currentPhase]; - const phaseStartTime = phaseStatus?.started_at - ? new Date(phaseStatus.started_at) - : new Date(0); - - // Search for new files matching the patterns - for (const pattern of patterns) { - try { - const matches = await glob(pattern, { - cwd: this.repoPath, - ignore: ['node_modules/**', '.git/**', 'dist/**', 'build/**'], - absolute: true, - }); - - for (const match of matches) { - try { - const stats = await fs.stat(match); - // File was modified after phase started - if (stats.mtime > phaseStartTime) { - const relativePath = path.relative(this.repoPath, match); - if (!result.detectedOutputs.includes(relativePath)) { - result.detectedOutputs.push(relativePath); - } - } - } catch { - // File stat failed, skip - } - } - } catch { - // Glob failed, skip pattern - } - } - - // Check if we have enough outputs - if (result.detectedOutputs.length >= minFiles) { - result.shouldAdvance = true; - result.reason = `Detected ${result.detectedOutputs.length} output(s) for phase ${currentPhase}`; - } else { - result.missingOutputs = this.getExpectedOutputTypes(currentPhase); - result.reason = `Waiting for outputs: ${result.missingOutputs.join(', ')}`; - } - - return result; - } - - /** - * Get human-readable expected output types for a phase - */ - private getExpectedOutputTypes(phase: PrevcPhase): string[] { - const outputMap: Record = { - P: ['PRD document', 'Requirements specification', 'User stories'], - R: ['Architecture document', 'Design decisions', 'Technical spec'], - E: ['Implementation code', 'Source files'], - V: ['Test files', 'Test results'], - C: ['Changelog', 'Release notes', 'Documentation updates'], - }; - - return outputMap[phase] || []; - } - - /** - * Watch for file changes and trigger callback when outputs detected - */ - async watchForOutputs( - currentPhase: PrevcPhase, - status: PrevcStatus, - onOutputsDetected: (outputs: string[]) => void, - intervalMs: number = 5000 - ): Promise<() => void> { - let running = true; - let previousOutputs = new Set(); - - const check = async () => { - if (!running) return; - - const result = await this.checkAutoAdvance(currentPhase, status); - - // Find new outputs - const newOutputs = result.detectedOutputs.filter( - (o) => !previousOutputs.has(o) - ); - - if (newOutputs.length > 0) { - newOutputs.forEach((o) => previousOutputs.add(o)); - onOutputsDetected(newOutputs); - } - - if (running) { - setTimeout(check, intervalMs); - } - }; - - // Start checking - check(); - - // Return stop function - return () => { - running = false; - }; - } - - /** - * Validate outputs for a phase - */ - async validatePhaseOutputs( - phase: PrevcPhase, - outputs: string[] - ): Promise<{ valid: boolean; errors: string[] }> { - const errors: string[] = []; - - for (const output of outputs) { - const fullPath = path.isAbsolute(output) - ? output - : path.join(this.repoPath, output); - - if (!(await fs.pathExists(fullPath))) { - errors.push(`Output file not found: ${output}`); - } - } - - return { - valid: errors.length === 0, - errors, - }; - } -} - -export { AutoAdvanceDetector as default }; diff --git a/src/harness/application/workflow/fileCollaborationStore.ts b/src/harness/application/workflow/fileCollaborationStore.ts index b1b97e99..1fec5840 100644 --- a/src/harness/application/workflow/fileCollaborationStore.ts +++ b/src/harness/application/workflow/fileCollaborationStore.ts @@ -81,14 +81,12 @@ export function migrateDocument( } export class FileCollaborationStore implements CollaborationSessionStore { - private readonly contextPath: string; private readonly filePath: string; private readonly tmpPath: string; private readonly maxConcludedAgeMs: number; private readonly logger: NonNullable; constructor(contextPath: string, options: FileCollaborationStoreOptions = {}) { - this.contextPath = contextPath; this.filePath = resolveRuntimeLayout(contextPath).collaborationFile; this.tmpPath = `${this.filePath}.tmp`; const envMax = process.env.DOTCONTEXT_COLLAB_MAX_CONCLUDED_AGE_MS; diff --git a/src/harness/application/workflow/index.ts b/src/harness/application/workflow/index.ts index 0f1aa163..a7d5352d 100644 --- a/src/harness/application/workflow/index.ts +++ b/src/harness/application/workflow/index.ts @@ -5,7 +5,6 @@ export { type WorkflowHarnessStatus, HarnessWorkflowBlockedError, } from './workflowService'; -export { AutoAdvanceDetector, AutoAdvanceResult } from './autoAdvance'; export * from './derivedPlanTaskContractBuilder'; export * from './fileCollaborationStore'; export * from './harnessSessionFacade'; diff --git a/src/harness/application/workflow/workflowService.ts b/src/harness/application/workflow/workflowService.ts index bc9b2477..8a1cce27 100644 --- a/src/harness/application/workflow/workflowService.ts +++ b/src/harness/application/workflow/workflowService.ts @@ -124,7 +124,6 @@ export class WorkflowService { // Narrow accessors used by advance/handoff/plan-sync logic below. // Fresh `get` each call keeps the facade as the single owner. private get runtimeStateService() { return this.harness.runtimeStateService; } - private get sensorsService() { return this.harness.sensorsService; } private get taskContractsService() { return this.harness.taskContractsService; } private get policyService() { return this.harness.policyService; } diff --git a/src/harness/domain/collaboration/index.ts b/src/harness/domain/collaboration/index.ts deleted file mode 100644 index 9393990c..00000000 --- a/src/harness/domain/collaboration/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '../workflow/collaboration'; diff --git a/src/harness/domain/context/index.ts b/src/harness/domain/context/index.ts deleted file mode 100644 index 918881c0..00000000 --- a/src/harness/domain/context/index.ts +++ /dev/null @@ -1,7 +0,0 @@ -export { - type ContextLayoutClassification, - type ContextLayoutEntry, -} from '../../../shared/context/contextLayout'; -export { - type ContentType, -} from '../../../shared/context/contentTypeRegistry'; diff --git a/src/harness/domain/index.ts b/src/harness/domain/index.ts deleted file mode 100644 index fad53334..00000000 --- a/src/harness/domain/index.ts +++ /dev/null @@ -1,8 +0,0 @@ -export * as workflow from './workflow'; -export * as plans from './plans'; -export * as policies from './policies'; -export * as sensors from './sensors'; -export * as collaboration from './collaboration'; -export * as context from './context'; -export * as retention from './retention'; -export * as execution from './execution'; diff --git a/src/harness/domain/plans/index.ts b/src/harness/domain/plans/index.ts deleted file mode 100644 index 52e6c7e5..00000000 --- a/src/harness/domain/plans/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '../workflow/plans'; diff --git a/src/harness/domain/policies/index.ts b/src/harness/domain/policies/index.ts deleted file mode 100644 index 57ba62a4..00000000 --- a/src/harness/domain/policies/index.ts +++ /dev/null @@ -1,11 +0,0 @@ -export { - HarnessPolicyBlockedError, - type HarnessPolicyTarget, - type HarnessPolicyScope, - type HarnessPolicyEffect, - type HarnessPolicyRisk, - type HarnessPolicyRule, - type CreateHarnessPolicyRuleInput, - type HarnessPolicyEvaluationInput, - type HarnessPolicyEvaluationResult, -} from '../../application/policies/policyService'; diff --git a/src/harness/domain/retention/index.ts b/src/harness/domain/retention/index.ts deleted file mode 100644 index 514af691..00000000 --- a/src/harness/domain/retention/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './boundedLruCache'; diff --git a/src/harness/domain/sensors/index.ts b/src/harness/domain/sensors/index.ts deleted file mode 100644 index 5c238e53..00000000 --- a/src/harness/domain/sensors/index.ts +++ /dev/null @@ -1,11 +0,0 @@ -export { - type HarnessSensorSeverity, - type HarnessSensorStatus, - type HarnessSensorDefinition, - type HarnessSensorRun, - type HarnessBackpressurePolicy, - type HarnessBackpressureResult, - type HarnessShellSensorConfig, - type HarnessSensorCatalogDocument, - type HarnessSensorCatalogSeverity, -} from '../../application'; diff --git a/src/harness/domain/workflow/gates/__tests__/gateChecker.test.ts b/src/harness/domain/workflow/gates/__tests__/gateChecker.test.ts index e5201abf..45c74e73 100644 --- a/src/harness/domain/workflow/gates/__tests__/gateChecker.test.ts +++ b/src/harness/domain/workflow/gates/__tests__/gateChecker.test.ts @@ -1,9 +1,8 @@ import { WorkflowGateChecker, getDefaultSettings, - GateCheckResult, } from '../gateChecker'; -import { PrevcStatus, ProjectScale, WorkflowSettings } from '../../types'; +import { PrevcStatus, ProjectScale } from '../../types'; // Helper to create a minimal valid PrevcStatus function createMockStatus(overrides: Partial = {}): PrevcStatus { diff --git a/src/harness/domain/workflow/orchestrator.ts b/src/harness/domain/workflow/orchestrator.ts index 6c519c24..b052c31b 100644 --- a/src/harness/domain/workflow/orchestrator.ts +++ b/src/harness/domain/workflow/orchestrator.ts @@ -18,7 +18,7 @@ import { import { PrevcStatusManager } from './status/statusManager'; import { detectProjectScale, getScaleRoute } from './scaling'; import { PREVC_PHASE_ORDER, getPhaseDefinition } from './phases'; -import { WorkflowGateChecker, GateCheckResult, getDefaultSettings, ExecutionEvidence } from './gates'; +import { WorkflowGateChecker, GateCheckResult, ExecutionEvidence } from './gates'; import { PlanLinker } from './plans/planLinker'; import { assertPhaseStatusConverges } from './plans/invariants'; import { WorkflowGuidanceService } from './orchestration/workflowGuidanceService'; @@ -53,7 +53,6 @@ export interface InitWorkflowOptions { */ export class PrevcOrchestrator { private repoPath: string; - private contextPath: string; private statusManager: PrevcStatusManager; private gateChecker: WorkflowGateChecker; private planLinker: PlanLinker; @@ -61,7 +60,6 @@ export class PrevcOrchestrator { constructor(contextPath: string, workflowState: HarnessWorkflowStateService) { this.repoPath = path.dirname(contextPath); - this.contextPath = contextPath; this.statusManager = new PrevcStatusManager(workflowState); this.gateChecker = new WorkflowGateChecker(); // Pass statusManager to PlanLinker for breadcrumb trail logging diff --git a/src/harness/domain/workflow/phases.ts b/src/harness/domain/workflow/phases.ts index 0c0ed7e3..f6ba7ccc 100644 --- a/src/harness/domain/workflow/phases.ts +++ b/src/harness/domain/workflow/phases.ts @@ -1,4 +1,4 @@ -import { PrevcPhase, PhaseDefinition, PhaseStatus } from './types'; +import { PrevcPhase, PhaseDefinition } from './types'; import { PREVC_PHASE_MODEL, PREVC_PHASE_SEQUENCE, diff --git a/src/harness/domain/workflow/plans/planLinker.ts b/src/harness/domain/workflow/plans/planLinker.ts index cf6036d8..74cde051 100644 --- a/src/harness/domain/workflow/plans/planLinker.ts +++ b/src/harness/domain/workflow/plans/planLinker.ts @@ -44,9 +44,9 @@ export class PlanLinker { private readonly orchestrator: PlanUpdateOrchestrator; constructor( - private readonly repoPath: string, - private readonly statusManager?: PrevcStatusManager, - private readonly autoCommitOnPhaseComplete: boolean = true + repoPath: string, + statusManager?: PrevcStatusManager, + autoCommitOnPhaseComplete: boolean = true ) { this.contextPath = path.join(repoPath, '.context'); this.plansPath = path.join(this.contextPath, 'plans'); diff --git a/src/harness/domain/workflow/prevcConfig.ts b/src/harness/domain/workflow/prevcConfig.ts index 5b91ea0b..8e6f17c5 100644 --- a/src/harness/domain/workflow/prevcConfig.ts +++ b/src/harness/domain/workflow/prevcConfig.ts @@ -3,7 +3,7 @@ * * `ROLE_CONFIG` is intentionally **not exported**. It is a narrow * projection of `PREVC_ROLE_MODEL` used only by the helpers in this file - * (`getRoleConfig`, `getOutputsForRole`, `getResponsibilitiesForRole`). + * (`getRoleConfig`). * External callers should depend on those helpers or on `PREVC_ROLE_MODEL` * directly from `./registries/prevcModel`, so there is a single source of * truth for role metadata. @@ -13,7 +13,6 @@ import { PrevcRole, RoleDefinition } from './types'; import { - PREVC_PHASE_SEQUENCE, PREVC_ROLE_MODEL, PREVC_ROLE_SEQUENCE, } from './registries/prevcModel'; @@ -40,26 +39,3 @@ const ROLE_CONFIG: Record = Object.fromEntries( export function getRoleConfig(role: PrevcRole): RoleDefinition { return ROLE_CONFIG[role]; } - -/** - * Get all roles that participate in a specific phase - */ -export function getRolesForPhase(phase: string): PrevcRole[] { - return PREVC_ROLE_SEQUENCE.filter((role) => - PREVC_ROLE_MODEL[role].phases.includes(phase as (typeof PREVC_PHASE_SEQUENCE)[number]) - ); -} - -/** - * Get all outputs for a specific role - */ -export function getOutputsForRole(role: PrevcRole): string[] { - return ROLE_CONFIG[role]?.outputs || []; -} - -/** - * Get all responsibilities for a specific role - */ -export function getResponsibilitiesForRole(role: PrevcRole): string[] { - return ROLE_CONFIG[role]?.responsibilities || []; -} diff --git a/src/harness/domain/workflow/registries/prevcModel.ts b/src/harness/domain/workflow/registries/prevcModel.ts index 10b075b0..5c6d9db5 100644 --- a/src/harness/domain/workflow/registries/prevcModel.ts +++ b/src/harness/domain/workflow/registries/prevcModel.ts @@ -348,5 +348,3 @@ export const PREVC_DOC_GUIDES: Record = { description: 'Index of the repository knowledge base and supporting guides.', }, }; - -export { PREVC_SKILL_PHASES } from '../skills/builtInSkillCatalog'; diff --git a/src/harness/domain/workflow/skills/skillRegistry.ts b/src/harness/domain/workflow/skills/skillRegistry.ts index f8160821..bff037f3 100644 --- a/src/harness/domain/workflow/skills/skillRegistry.ts +++ b/src/harness/domain/workflow/skills/skillRegistry.ts @@ -9,7 +9,6 @@ import * as fs from 'fs'; import * as path from 'path'; import { Skill, - SkillMetadata, DiscoveredSkills, BUILT_IN_SKILLS, BuiltInSkillType, diff --git a/src/harness/domain/workflow/skills/types.ts b/src/harness/domain/workflow/skills/types.ts index f22e2e87..d9bfded6 100644 --- a/src/harness/domain/workflow/skills/types.ts +++ b/src/harness/domain/workflow/skills/types.ts @@ -66,6 +66,5 @@ export { BUILT_IN_SKILLS, BuiltInSkillType, isBuiltInSkill, - PREVC_SKILL_PHASES, SKILL_TO_PHASES, } from './builtInSkillCatalog'; diff --git a/src/harness/domain/workflow/status/templates.ts b/src/harness/domain/workflow/status/templates.ts index 10c207b5..20a3f0d2 100644 --- a/src/harness/domain/workflow/status/templates.ts +++ b/src/harness/domain/workflow/status/templates.ts @@ -159,51 +159,3 @@ export function createInitialStatus(options: CreateStatusOptions): PrevcStatus { roles, }; } - -/** - * Create a minimal status for quick flow - */ -export function createQuickFlowStatus(name: string): PrevcStatus { - return createInitialStatus({ - name, - scale: ProjectScale.QUICK, - phases: ['E', 'V'], - roles: ['solo-dev'], - }); -} - -/** - * Create a status for small projects - */ -export function createSmallProjectStatus(name: string): PrevcStatus { - return createInitialStatus({ - name, - scale: ProjectScale.SMALL, - phases: ['P', 'E', 'V'], - roles: ['planner', 'developer', 'qa'], - }); -} - -/** - * Create a status for medium projects - */ -export function createMediumProjectStatus(name: string): PrevcStatus { - return createInitialStatus({ - name, - scale: ProjectScale.MEDIUM, - phases: ['P', 'R', 'E', 'V'], - roles: ['planner', 'architect', 'developer', 'qa', 'reviewer'], - }); -} - -/** - * Create a status for large projects - */ -export function createLargeProjectStatus(name: string): PrevcStatus { - return createInitialStatus({ - name, - scale: ProjectScale.LARGE, - phases: ['P', 'R', 'E', 'V', 'C'], - roles: 'all', - }); -} diff --git a/src/harness/ports/in/index.ts b/src/harness/ports/in/index.ts deleted file mode 100644 index 0380c3f8..00000000 --- a/src/harness/ports/in/index.ts +++ /dev/null @@ -1,11 +0,0 @@ -export { - type HarnessAdapterToolName, - type HarnessAdapterInput, - type HarnessAdapterRequest, - type HarnessAdapterRuntimeResult, -} from '../../application/actions/adapterRuntime'; -export { - type HarnessHookEvent, - type HarnessHookResponse, - type HarnessHookSource, -} from '../../application/hooks/hookAdapter'; diff --git a/src/harness/ports/index.ts b/src/harness/ports/index.ts deleted file mode 100644 index daaaed69..00000000 --- a/src/harness/ports/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * as inPorts from './in'; -export * as outPorts from './out'; diff --git a/src/harness/ports/out/index.ts b/src/harness/ports/out/index.ts deleted file mode 100644 index ab5a934f..00000000 --- a/src/harness/ports/out/index.ts +++ /dev/null @@ -1,17 +0,0 @@ -export { - type HarnessRuntimeStatePort, - type CreateSessionInput, - type AppendTraceInput, - type AddArtifactInput, - type CheckpointInput, - type HarnessCheckpointPage, - type ListCheckpointsOptions, -} from '../../adapters/out/runtimeState/runtimeStateService'; -export { - type HarnessWorkflowRecord, - type WorkflowHarnessBinding, -} from '../../adapters/out/workflowState/workflowStateService'; -export { - type ContextBuilderOptions, - type ContextFormat, -} from '../../adapters/out/semantic/contextBuilder'; diff --git a/src/integrations/claude-code/hooks/index.ts b/src/integrations/claude-code/hooks/index.ts deleted file mode 100644 index 5681fee9..00000000 --- a/src/integrations/claude-code/hooks/index.ts +++ /dev/null @@ -1,23 +0,0 @@ -export { - ClaudeCodeHarnessHookAdapter, - createClaudeCodeHookAdapter, - type ClaudeCodeHookEvent, - type ClaudeCodeHookResponse, - type ClaudeCodeHookAdapterOptions, -} from './createClaudeCodeHookAdapter'; - -export { - mapClaudeCodeEvent, - type ClaudeCodeHookInput, -} from './mapClaudeCodeEvent'; - -export { - mapClaudeCodeResponse, - type ClaudeCodeHookOutput, -} from './mapClaudeCodeResponse'; - -export { - CLAUDE_CODE_HOOK_TEMPLATES, - CLAUDE_CODE_HOOK_DISPATCH_COMMAND, - buildClaudeCodeHooksFragment, -} from './claudeCodeHookTemplates'; diff --git a/src/integrations/codex/hooks/index.ts b/src/integrations/codex/hooks/index.ts deleted file mode 100644 index 038ec197..00000000 --- a/src/integrations/codex/hooks/index.ts +++ /dev/null @@ -1,25 +0,0 @@ -export { - CodexHarnessHookAdapter, - createCodexHookAdapter, - type CodexHookEvent, - type CodexHookResponse, - type CodexHookAdapterOptions, -} from './createCodexHookAdapter'; - -export { - mapCodexEvent, - type CodexHookInput, -} from './mapCodexEvent'; - -export { - mapCodexResponse, - type CodexHookOutput, -} from './mapCodexResponse'; - -export { - CODEX_HOOK_TEMPLATES, - CODEX_HOOK_DISPATCH_COMMAND, - CODEX_HOOK_TRUST_REMINDER, - buildCodexHooksDocument, - buildCodexTomlHookBlocks, -} from './codexHookTemplates'; diff --git a/src/integrations/pi-dev/hooks/index.ts b/src/integrations/pi-dev/hooks/index.ts deleted file mode 100644 index 5d521e99..00000000 --- a/src/integrations/pi-dev/hooks/index.ts +++ /dev/null @@ -1,23 +0,0 @@ -export { - PiDevHarnessHookAdapter, - createPiDevHookAdapter, - type PiDevHookEvent, - type PiDevHookResponse, - type PiDevHookAdapterOptions, -} from './createPiDevHookAdapter'; - -export { - mapPiEvent, - isTracedPiTool, - type PiSessionStartEvent, - type PiSessionStartNavigationEvent, - type PiHarnessCreateSessionEvent, - type PiToolExecutionEndEvent, - type PiAgentEndEvent, -} from './mapPiEvent'; - -export { - mapPiResponse, - extractHarnessSessionId, - type PiHookOutput, -} from './mapPiResponse'; diff --git a/src/integrations/shared/hookSessionStore.ts b/src/integrations/shared/hookSessionStore.ts index 9cb5a320..6710dcc9 100644 --- a/src/integrations/shared/hookSessionStore.ts +++ b/src/integrations/shared/hookSessionStore.ts @@ -72,10 +72,6 @@ export interface HookSessionAdapter { }): Promise; } -function storeKey(source: ShellHookSource, hostSessionId: string): string { - return `${source}:${hostSessionId}`; -} - async function getStorePath(repoPath: string): Promise { const contextRoot = await getContextRootPath(repoPath); return path.join(contextRoot, 'runtime', 'hooks', 'host-sessions.json'); @@ -421,7 +417,3 @@ export async function ensureHookHarnessSession( return harnessSessionId; } - -export function hookSessionStoreKey(source: ShellHookSource, hostSessionId: string): string { - return storeKey(source, hostSessionId); -} diff --git a/src/mcp/adapters/in/index.ts b/src/mcp/adapters/in/index.ts deleted file mode 100644 index 629f8a0f..00000000 --- a/src/mcp/adapters/in/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from '../../server'; -export * from '../../gateway'; diff --git a/src/mcp/gateway/metrics.ts b/src/mcp/gateway/metrics.ts index cf22b26a..9fb1327d 100644 --- a/src/mcp/gateway/metrics.ts +++ b/src/mcp/gateway/metrics.ts @@ -84,7 +84,7 @@ class MetricsStore { } getSummary(): MetricsSummary { - const { contextQueries, fileReads, tokensEstimate } = this.metrics; + const { contextQueries, fileReads } = this.metrics; // Calculate ratio (higher is better - more context queries, fewer file reads) const ratio = fileReads > 0 ? contextQueries / fileReads : contextQueries > 0 ? Infinity : 0; diff --git a/src/mcp/logging/actionLogger.ts b/src/mcp/logging/actionLogger.ts index 13915ac9..e25447d4 100644 --- a/src/mcp/logging/actionLogger.ts +++ b/src/mcp/logging/actionLogger.ts @@ -45,7 +45,6 @@ const MCP_ACTIVITY_NAME = 'mcp-activity'; const sessionCaches = new Map; signature: string; - diagnostics: string[]; }>(); function normalizeRepoPath(repoPath: string): string { @@ -77,7 +76,7 @@ async function sessionCacheForRepo(repoPath: string): Promise Buffer.byteLength(sessionId) + Buffer.byteLength(key), }); - sessionCaches.set(normalized, { cache, signature, diagnostics: loaded.diagnostics }); + sessionCaches.set(normalized, { cache, signature }); while (sessionCaches.size > limits.maxEntries) { const oldest = sessionCaches.keys().next().value as string | undefined; if (!oldest) break; @@ -96,10 +95,6 @@ export function getMcpActionSessionCacheSize(): number { return [...sessionCaches.values()].reduce((total, owner) => total + owner.cache.size, 0); } -export function getMcpActionSessionCacheDiagnostics(repoPath: string): string[] { - return [...(sessionCaches.get(normalizeRepoPath(repoPath))?.diagnostics ?? [])]; -} - export function getMcpActionSessionCacheMetrics(repoPath: string): BoundedLruCacheMetrics | undefined { return sessionCaches.get(normalizeRepoPath(repoPath))?.cache.metrics(); } diff --git a/src/mcp/logging/index.ts b/src/mcp/logging/index.ts deleted file mode 100644 index c1627178..00000000 --- a/src/mcp/logging/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { logMcpAction } from './actionLogger'; diff --git a/src/mcp/resources/index.ts b/src/mcp/resources/index.ts deleted file mode 100644 index cb0ff5c3..00000000 --- a/src/mcp/resources/index.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/src/prompts/defaults.ts b/src/prompts/defaults.ts deleted file mode 100644 index 819d40e0..00000000 --- a/src/prompts/defaults.ts +++ /dev/null @@ -1,106 +0,0 @@ -export const UPDATE_SCAFFOLD_PROMPT_FALLBACK = `# Prompt: Update Repository Documentation and Agent Playbooks - -## Purpose -You are an AI assistant responsible for refreshing the documentation (\`docs/\`) and agent playbooks (\`agents/\`). Your goal is to bring every guide up to date with the latest repository state and maintain cross-references between docs and agent instructions. - -## Context Gathering -1. Review the repository structure and recent changes. -2. Inspect \`package.json\`, CI configuration, and any release or roadmap notes. -3. Check \`docs/README.md\` for the current document map. - -## Update Procedure -1. **Update Documentation** - - Replace TODO placeholders with accurate, current information. - - Verify that links between docs remain valid. - - If you add new guides or sections, update \`docs/README.md\`. - -2. **Agent Playbook Alignment** - - For each change in \`docs/\`, adjust the related \`agents/*.md\` playbooks. - - Update responsibilities, best practices, and documentation touchpoints. - -## Acceptance Criteria -- No unresolved TODO placeholders remain unless they require explicit human input. -- Agent playbooks list accurate responsibilities and best practices. -- Changes are self-contained, well-formatted Markdown. - -## Deliverables -- Updated Markdown files. -`; - -/** - * Prompt for AI agents to enhance scaffolding via MCP tools. - * This prompt MUST be included in ALL scaffolding generation responses. - */ -export const MCP_SCAFFOLD_ENHANCEMENT_PROMPT = `# AI Enhancement Required - -Your scaffolding has been generated but contains placeholder content that MUST be enhanced. - -## Required Actions - -1. **For each generated file**, call \`fillSingleFile\` to get: - - Semantic context from the codebase - - Scaffold structure with section guidance - - Current file content to enhance - -2. **Generate rich content** based on the context provided: - - Replace ALL placeholders with accurate, codebase-specific information - - Follow the tone and audience guidelines in the scaffold structure - - Include cross-references to related docs/agents - - Use concrete examples from the actual codebase - -3. **Write the enhanced content** using the Write tool - -## Quality Checklist - -- [ ] No TODO placeholders remain -- [ ] All sections have concrete, actionable content -- [ ] Cross-references point to existing files -- [ ] Examples are drawn from actual codebase code -- [ ] Terminology matches project conventions - -## Example Workflow - -\`\`\` -1. context({ action: "listToFill" }) → Get list of files needing content -2. context({ action: "fillSingle", filePath }) → Get context for each file -3. Generate content based on semantic context -4. Write enhanced content to file -5. Repeat for all files -\`\`\` - -DO NOT consider scaffolding complete until ALL files have been enhanced with codebase-specific content. -`; - -export const UPDATE_PLAN_PROMPT_FALLBACK = `# Prompt: Update Collaboration Plans - -## Purpose -You are an AI assistant responsible for refining collaboration plans. Each plan orchestrates work across documentation guides (\`docs/\`) and agent playbooks (\`agents/\`). Your goal is to replace TODOs with actionable guidance. - -## Update Procedure -1. **Task Snapshot** - - Summarize the primary goal and success signal in concrete terms. - - List authoritative references (docs, issues, specs). - -2. **Agent Alignment** - - For each agent in the lineup, describe why they are involved. - - Ensure playbook links match the referenced agent files. - -3. **Documentation Touchpoints** - - Map each plan stage to the docs excerpts provided. - -4. **Working Phases** - - Break the work into sequential phases with numbered steps and deliverables. - - Reference documentation and agent resources for each phase. - -5. **Evidence & Follow-up** - - Specify artefacts to capture (PR links, test runs, change logs). - - Record any follow-up actions. - -## Acceptance Criteria -- TODOs are resolved with concrete information. -- Tables reference existing files. -- Phases provide actionable guidance. - -## Deliverables -- Updated plan Markdown returned verbatim. -`; diff --git a/src/shared/fs/index.ts b/src/shared/fs/index.ts deleted file mode 100644 index c3344717..00000000 --- a/src/shared/fs/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * from '../../utils/fileMapper'; -export * from '../../utils/gitignoreManager'; -export * from '../../utils/pathSecurity'; diff --git a/src/shared/system/index.ts b/src/shared/system/index.ts deleted file mode 100644 index 8d178d13..00000000 --- a/src/shared/system/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from '../../utils/processShutdown'; -export * from '../../utils/gitService'; diff --git a/src/shared/system/uiHelpers.ts b/src/shared/system/uiHelpers.ts index 7189e2be..3523516d 100644 --- a/src/shared/system/uiHelpers.ts +++ b/src/shared/system/uiHelpers.ts @@ -6,7 +6,6 @@ */ import type { CLIInterface } from '../../utils/cliUI'; -import type { TranslateFn } from '../../utils/i18n'; import type { OperationResult } from './types'; import { typography } from '../../utils/theme'; diff --git a/src/types.ts b/src/types.ts index bae254b2..5900773d 100644 --- a/src/types.ts +++ b/src/types.ts @@ -54,48 +54,3 @@ export interface RepoStructure { skipped?: RepoDiscoverySkip[]; discoveryMetrics?: RepoDiscoveryMetrics; } - -export type AIProvider = 'openrouter' | 'openai' | 'anthropic' | 'google'; - -export interface LLMConfig { - apiKey: string; - model: string; - baseUrl?: string; - provider: AIProvider; -} - -export interface CLIOptions { - repoPath: string; - outputDir?: string; - model?: string; - apiKey?: string; - provider?: LLMConfig['provider']; - exclude?: string[]; - include?: string[]; - verbose?: boolean; - since?: string; - staged?: boolean; - force?: boolean; -} - -export interface AgentPrompt { - name: string; - description: string; - systemPrompt: string; - context: string; - examples?: string[]; -} - -export interface TokenUsage { - promptTokens: number; - completionTokens: number; - totalTokens: number; -} - -export interface UsageStats { - totalCalls: number; - totalPromptTokens: number; - totalCompletionTokens: number; - totalTokens: number; - model: string; -} diff --git a/src/types/scaffoldFrontmatter.ts b/src/types/scaffoldFrontmatter.ts index 79a3e0a7..740f0d52 100644 --- a/src/types/scaffoldFrontmatter.ts +++ b/src/types/scaffoldFrontmatter.ts @@ -6,7 +6,6 @@ * generates complete content based on scaffold structure definitions. */ -import { z } from 'zod'; import { PrevcPhase } from '../harness/domain/workflow/types'; /** @@ -386,76 +385,3 @@ export function serializeFrontmatter(fm: ScaffoldFrontmatter): string { return lines.join('\n'); } -/** - * Zod schemas for validating scaffold/plan frontmatter at I/O boundaries. - */ -const prevcPhaseSchema = z.enum(['P', 'R', 'E', 'V', 'C']); - -const planStepSchema = z.object({ - order: z.number(), - description: z.string(), - assignee: z.string().optional(), - deliverables: z.array(z.string()).optional(), -}); - -const requiredArtifactSpecSchema = z.discriminatedUnion('kind', [ - z.object({ kind: z.literal('name'), name: z.string().min(1) }), - z.object({ kind: z.literal('path'), path: z.string().min(1) }), - z.object({ - kind: z.literal('glob'), - glob: z.string().min(1), - minMatches: z.number().int().positive().optional(), - }), - z.object({ - kind: z.literal('file-count'), - glob: z.string().min(1), - min: z.number().int().positive(), - }), -]); - -const requiredArtifactInputSchema = z.union([ - z.string().min(1), - requiredArtifactSpecSchema, -]); - -const planPhaseSchema = z.object({ - id: z.string().min(1), - name: z.string().min(1), - prevc: prevcPhaseSchema, - summary: z.string().optional(), - deliverables: z.array(z.string()).optional(), - steps: z.array(planStepSchema).optional(), - required_sensors: z.array(z.string().min(1)).optional(), - required_artifacts: z.array(requiredArtifactInputSchema).optional(), -}); - -const agentEntrySchema = z.object({ - type: z.string().min(1), - role: z.string(), -}); - -export const planScaffoldFrontmatterSchema = z.object({ - type: z.literal('plan'), - name: z.string().min(1), - description: z.string().min(1), - generated: z.string().min(1), - status: z.enum(['unfilled', 'filled']), - scaffoldVersion: z.literal('2.0.0'), - planSlug: z.string().min(1), - summary: z.string().optional(), - agents: z.array(agentEntrySchema).optional(), - docs: z.array(z.string()).optional(), - phases: z.array(planPhaseSchema).optional(), -}); - -export type PlanScaffoldFrontmatterValidated = z.infer; - -/** - * Validate plan frontmatter parsed from YAML. Returns parsed value or null if - * invalid. Keep at the boundary; do not pepper throughout the codebase. - */ -export function validatePlanFrontmatter(raw: unknown): PlanScaffoldFrontmatterValidated | null { - const result = planScaffoldFrontmatterSchema.safeParse(raw); - return result.success ? result.data : null; -} - diff --git a/src/utils/__tests__/themedPrompt.test.ts b/src/utils/__tests__/themedPrompt.test.ts index 00ce14cc..56b57db4 100644 --- a/src/utils/__tests__/themedPrompt.test.ts +++ b/src/utils/__tests__/themedPrompt.test.ts @@ -4,8 +4,6 @@ import { isPromptCancelled, themedCheckbox, themedConfirm, - themedInput, - themedPassword, themedPromptTestHooks, themedSelect, } from '../themedPrompt'; @@ -17,8 +15,6 @@ describe('themedPrompt', () => { return { select: jest.fn(), confirm: jest.fn(), - text: jest.fn(), - password: jest.fn(), multiselect: jest.fn(), isCancel: jest.fn((value: unknown) => value === cancelSymbol), cancel: jest.fn(), @@ -111,43 +107,6 @@ describe('themedPrompt', () => { }); }); - it('maps input and password validation for Clack', async () => { - const clack = createClackModule(); - clack.text.mockImplementation(async (options) => { - expect(options.validate?.('')).toBe('Required'); - expect(options.validate?.('ok')).toBeUndefined(); - return 'typed'; - }); - clack.password.mockImplementation(async (options) => { - expect(options.validate?.('short')).toBe('Too short'); - expect(options.validate?.('long-enough')).toBeUndefined(); - return 'secret'; - }); - installClackModule(clack); - - await expect(themedInput({ - message: 'Name', - default: 'dotcontext', - validate: (value) => value.length > 0 || 'Required', - })).resolves.toBe('typed'); - await expect(themedPassword({ - message: 'Token', - mask: '*', - validate: (value) => value.length >= 8 || 'Too short', - })).resolves.toBe('secret'); - - expect(clack.text).toHaveBeenCalledWith({ - message: 'Name', - defaultValue: 'dotcontext', - validate: expect.any(Function), - }); - expect(clack.password).toHaveBeenCalledWith({ - message: 'Token', - mask: '*', - validate: expect.any(Function), - }); - }); - it('converts Clack cancellation to PromptCancelledError', async () => { const clack = createClackModule(); clack.confirm.mockResolvedValue(cancelSymbol); diff --git a/src/utils/frontMatter.ts b/src/utils/frontMatter.ts index 2603c084..6bfb44c7 100644 --- a/src/utils/frontMatter.ts +++ b/src/utils/frontMatter.ts @@ -7,7 +7,7 @@ import { load as loadYaml } from 'js-yaml'; import { PrevcPhase } from '../harness/domain/workflow/types'; -import type { ScaffoldFrontmatter, ScaffoldFileType, ScaffoldStatus } from '../types/scaffoldFrontmatter'; +import type { ScaffoldFileType, ScaffoldStatus } from '../types/scaffoldFrontmatter'; import type { RequiredArtifactInput, RequiredArtifactSpec } from '../harness/application/contracts/taskContractsService'; /** diff --git a/src/utils/gitService.ts b/src/utils/gitService.ts index b3d23413..71f29ea5 100644 --- a/src/utils/gitService.ts +++ b/src/utils/gitService.ts @@ -2,7 +2,7 @@ import { execSync } from 'child_process'; import * as path from 'path'; import * as fs from 'fs-extra'; -import { colors, symbols, typography } from './theme'; +import { colors, typography } from './theme'; export interface GitChanges { added: string[]; @@ -595,4 +595,4 @@ export class GitService { return hasStateFile || (hasContextFolder && hasDocumentation); } -} \ No newline at end of file +} diff --git a/src/utils/i18n.ts b/src/utils/i18n.ts index 18e13270..8bc292b9 100644 --- a/src/utils/i18n.ts +++ b/src/utils/i18n.ts @@ -6,7 +6,6 @@ export const DEFAULT_LOCALE: Locale = 'en'; const englishMessages = { 'cli.description': 'Sync .context assets, reverse-sync tool state, and install MCP integrations for your repository', 'global.options.lang': 'Language for CLI output (en or pt-BR)', - 'ui.version': 'Version {version}', 'ui.projectConfiguration.title': 'Project Configuration', 'ui.projectConfiguration.repository': 'Repository', 'ui.projectConfiguration.output': 'Output', @@ -25,180 +24,16 @@ const englishMessages = { 'ui.generationSummary.nextStep': 'Next step: customize the generated templates to match your project.', 'ui.error.title': 'Error', 'ui.splash.directoryLabel': 'directory', - 'info.prompt.title': 'System Prompt', - 'info.prompt.usingCustom': 'Using prompt from {path}.', - 'info.prompt.usingPackage': 'Using packaged prompt at {path}.', - 'info.prompt.usingBundled': 'Using built-in prompt bundled with dotcontext.', 'info.update.available.title': 'Update available', 'info.update.available.detail': 'A newer version {latest} is available (current {current}). Update with {command}.', - 'commands.init.description': 'Generate docs and agent scaffolding for a repository', - 'commands.init.arguments.repoPath': 'Path to the repository to analyze', - 'commands.init.arguments.type': 'Scaffold type: "docs", "agents", or "both" (default)', - 'commands.init.options.output': 'Output directory for generated assets', - 'commands.init.options.exclude': 'Glob patterns to exclude from analysis', - 'commands.init.options.include': 'Glob patterns to include during analysis', - 'commands.init.options.verbose': 'Enable verbose logging', - 'commands.init.options.noSemantic': 'Disable semantic code analysis (enabled by default)', - 'commands.init.options.noContentStubs': 'Disable content stubs (section headings and guidance) in scaffolds', - 'commands.fill.description': 'Use an LLM to fill generated docs and agent playbooks with the latest repo context', - 'commands.fill.arguments.repoPath': 'Path to the repository root used to build context', - 'commands.fill.options.output': 'Scaffold directory containing docs/ and agents/', - 'commands.fill.options.apiKey': 'API key for the LLM provider', - 'commands.fill.options.model': 'LLM model to use', - 'commands.fill.options.provider': 'LLM provider (openrouter, openai, anthropic, google)', - 'commands.fill.options.baseUrl': 'Custom base URL for provider APIs', - 'commands.fill.options.prompt': 'Path to an instruction prompt', - 'commands.fill.options.limit': 'Maximum number of files to process', - 'commands.fill.options.exclude': 'Glob patterns to exclude from repository analysis', - 'commands.fill.options.include': 'Glob patterns to include during analysis', 'commands.fill.options.verbose': 'Enable verbose logging', - 'commands.fill.options.noSemantic': 'Disable semantic context mode and use tool-based exploration instead', - 'commands.fill.options.languages': 'Programming languages to analyze (e.g., typescript,python)', - 'commands.fill.options.useLsp': 'Enable LSP for deeper semantic analysis (type info, references)', - 'prompts.fill.semantic': 'Use semantic context mode? (faster, fewer tokens - recommended)', - 'prompts.fill.languages': 'Select programming languages for analysis', - 'prompts.fill.useLsp': 'Use LSP for deeper type analysis? (slower but more accurate)', - 'commands.plan.description': 'Create a development plan that links documentation and agent playbooks', - 'commands.plan.arguments.planName': 'Name of the plan (used to create the file slug)', - 'commands.plan.options.output': 'Output directory for generated plan files', - 'commands.plan.options.title': 'Custom title for the plan document', - 'commands.plan.options.summary': 'Seed summary for the plan header', - 'commands.plan.options.force': 'Overwrite the plan if it already exists (scaffold mode)', - 'commands.plan.options.fill': 'Use an LLM to fill or update the plan instead of scaffolding', - 'commands.plan.options.repo': 'Repository root for semantic context', - 'commands.plan.options.apiKey': 'API key for the LLM provider', - 'commands.plan.options.model': 'LLM model to use', - 'commands.plan.options.provider': 'LLM provider (openrouter, openai, anthropic, google)', - 'commands.plan.options.baseUrl': 'Custom base URL for provider APIs', - 'commands.plan.options.prompt': 'Path to a plan update instruction prompt', - 'commands.plan.options.dryRun': 'Preview updates without writing files', - 'commands.plan.options.include': 'Glob patterns to include during repository analysis', - 'commands.plan.options.exclude': 'Glob patterns to exclude from repository analysis', - 'commands.plan.options.verbose': 'Enable verbose logging', - 'commands.plan.options.noSemantic': 'Disable semantic code analysis (enabled by default)', - 'commands.plan.options.noLsp': 'Disable LSP semantic analysis (enabled by default for plans)', - 'errors.init.scaffoldFailed': 'Failed to scaffold repository assets', - 'errors.fill.failed': 'Failed to fill documentation with LLM assistance', - 'errors.plan.creationFailed': 'Failed to create plan template', - 'errors.init.invalidType': 'Invalid scaffold type "{value}". Expected one of: {allowed}', - 'errors.common.repoMissing': 'Repository path does not exist: {path}', - 'warnings.scaffold.noneSelected': 'No documentation or agent playbooks selected. Nothing to scaffold.', - 'warnings.agents.missingDirectory': 'No agents directory found. Initialize or import context through MCP first.', - 'steps.init.analyze': 'Analyzing repository structure', - 'steps.init.docs': 'Scaffolding documentation', - 'steps.init.agents': 'Scaffolding agent playbooks', - 'spinner.repo.scanning': 'Scanning repository...', - 'spinner.repo.scanComplete': 'Found {fileCount} files across {directoryCount} directories', - 'spinner.docs.creating': 'Creating docs directory and templates...', - 'spinner.docs.creatingWithSemantic': 'Analyzing codebase and creating docs templates...', - 'spinner.docs.created': 'Documentation scaffold created ({count} files)', - 'spinner.agents.creating': 'Creating agent directory and templates...', - 'spinner.agents.creatingWithSemantic': 'Analyzing codebase and creating agent playbooks...', - 'spinner.agents.created': 'Agent scaffold created ({count} files)', - 'spinner.plan.creating': 'Creating plan template...', - 'spinner.plan.created': 'Plan template created', - 'spinner.plan.creationFailed': 'Failed to create plan template', - 'success.scaffold.ready': 'Scaffold ready in {path}', - 'success.plan.createdAt': 'Plan created at {path}', - 'errors.fill.missingDocsScaffold': 'Documentation scaffold not found. Run `dotcontext init` first.', - 'errors.fill.missingAgentsScaffold': 'Agent scaffold not found. Run `dotcontext init` first.', - 'errors.fill.missingScaffold': 'No scaffold found. Run `dotcontext init` first to create docs and/or agents.', - 'steps.fill.analyze': 'Analyzing repository structure', - 'warnings.fill.noTargets': 'No Markdown files found in .context/docs or .context/agents. Run "dotcontext init" before filling.', - 'steps.fill.processFiles': 'Updating {count} files with {model}', - 'spinner.fill.processing': 'Processing {path}...', - 'spinner.fill.noContent': 'No content received for {path}', - 'messages.fill.emptyResponse': 'Empty response from LLM', - 'messages.fill.previewStart': '--- Preview Start ---', - 'messages.fill.previewEnd': '--- Preview End ---', - 'spinner.fill.updated': 'Updated {path}', - 'spinner.fill.failed': 'Failed {path}', - 'steps.fill.summary': 'Summarizing LLM usage', - 'success.fill.completed': 'LLM-assisted update complete. Review the changes and commit when ready.', - 'errors.plan.invalidName': 'Plan name must contain at least one alphanumeric character.', - 'messages.plan.regenerated': 'Regenerated {path} before LLM fill.', - 'messages.plan.created': 'Created {path} before LLM fill.', - 'info.plan.scaffolded.title': 'Plan scaffolded', - 'errors.plan.missingPlansDir': 'Plans directory not found. Run `dotcontext plan ` to create one.', - 'errors.plan.notFound': 'Plan not found. Expected {expected}.', - 'steps.plan.summary': 'Summarizing repository state', - 'spinner.planFill.analyzingRepo': 'Analyzing repository...', - 'spinner.planFill.summaryReady': 'Repository summary ready', - 'steps.plan.update': 'Updating {path} with {model}', - 'spinner.planFill.updating': 'Filling {path}...', - 'spinner.planFill.noContent': 'No content received from LLM', - 'spinner.planFill.dryRun': 'Dry run - preview follows', - 'spinner.planFill.updated': 'Updated {path}', - 'spinner.planFill.failed': 'Failed to fill plan', - 'steps.plan.summaryResults': 'Summarizing LLM usage', - 'success.plan.filled': 'Plan fill complete. Review the updates and commit when ready.', - 'errors.commands.analyzeRemoved': 'The analyze command has been removed in the scaffolding-only version of dotcontext.', - 'errors.commands.fillRemoved': 'The fill command is now available only through MCP-enabled AI tools.', - 'errors.commands.updateRemoved': 'The update command is no longer supported. Re-run `dotcontext init` to refresh scaffolds.', - 'errors.commands.previewRemoved': 'Preview mode has been retired. Use the generated docs and agent templates directly.', - 'errors.commands.guidelinesRemoved': 'Guidelines generation relied on LLMs and is no longer available.', 'errors.cli.executionFailed': 'CLI execution failed', - 'errors.init.overwriteDeclined': 'Scaffold aborted to avoid overwriting existing content.', 'prompts.main.action': 'What would you like to do?', - 'prompts.main.choice.scaffold': 'Generate documentation/agent scaffolding', - 'prompts.main.choice.fill': 'Fill docs and agents with an LLM', - 'prompts.main.choice.plan': 'Create a development plan', - 'prompts.main.choice.changeLanguage': 'Change language', 'prompts.main.choice.exit': 'Exit interactive mode', - 'prompts.scaffold.repoPath': 'Repository path to analyze', - 'prompts.scaffold.type': 'What should we scaffold?', - 'prompts.scaffold.typeBoth': 'Docs and agents', - 'prompts.scaffold.typeDocs': 'Docs only', - 'prompts.scaffold.typeAgents': 'Agents only', - 'prompts.scaffold.selectComponents': 'What should we scaffold? (Select all that apply)', - 'prompts.scaffold.componentDocs': 'Documentation', - 'prompts.scaffold.componentAgents': 'Agent playbooks', - 'prompts.scaffold.componentSkills': 'Skills', - 'spinner.skills.creating': 'Creating skills directory and templates...', - 'spinner.skills.created': 'Skills scaffold created ({count} files)', - 'steps.init.skills': 'Scaffolding skills', - 'prompts.init.confirmOverwriteDocs': 'Documentation already exists at {path}. Overwrite existing files?', - 'prompts.init.confirmOverwriteAgents': 'Agent playbooks already exist at {path}. Overwrite existing files?', - 'prompts.init.confirmOverwriteSkills': 'Skills already exist at {path}. Overwrite existing files?', - 'prompts.common.verbose': 'Enable verbose logging?', - 'prompts.fill.repoPath': 'Repository path containing the scaffold', - 'prompts.fill.promptPath': 'Custom prompt path (leave blank to use the bundled default)', - 'prompts.fill.limit': 'Maximum number of files to update (leave blank for all)', - 'prompts.fill.overrideModel': 'Override provider/model configuration?', - 'prompts.fill.provider': 'Select LLM provider', - 'prompts.fill.provider.openrouter': 'OpenRouter (access to multiple models)', - 'prompts.fill.provider.openai': 'OpenAI (GPT-4, etc.)', - 'prompts.fill.provider.anthropic': 'Anthropic (Claude)', - 'prompts.fill.provider.google': 'Google (Gemini)', - 'prompts.fill.model': 'Model identifier', - 'prompts.fill.provideApiKey': 'Provide an API key for this run?', - 'prompts.fill.apiKey': 'API key', - 'prompts.plan.name': 'Plan name (used for the file slug)', - 'prompts.plan.goal': 'What should be planned?', - 'prompts.plan.mode': 'How would you like to work with this plan?', - 'prompts.plan.modeScaffold': 'Scaffold a plan template', - 'prompts.plan.modeFill': 'Create a plan with AI (outline or AI-filled)', - 'prompts.plan.summary': 'Optional summary to seed the plan (leave blank to add later)', - 'prompts.plan.repoPath': 'Repository root for context', - 'prompts.plan.dryRun': 'Preview updates without writing files?', - 'prompts.plan.useLsp': 'Use LSP for deeper type analysis? (recommended for plans)', 'prompts.language.select': 'Choose the CLI language / Escolha o idioma do CLI', 'prompts.language.option.en': 'English / Inglês', 'prompts.language.option.pt-BR': 'Portuguese (Brazil) / Português (Brasil)', - 'errors.plan.fillFailed': 'Failed to fill plan with LLM assistance', - 'errors.fill.promptMissing': 'Prompt file not found at {path}.', - 'errors.fill.apiKeyMissing': '{provider} API key is required. Set one of {envVars} or use --api-key.', - 'info.interactive.returning.title': 'Main menu', - 'info.interactive.returning.detail': 'Returning to the interactive menu. Pick another action or choose Exit.', 'success.interactive.goodbye': 'Goodbye! Thanks for using dotcontext.', - 'agent.starting': 'Starting', - 'agent.complete': 'Complete', - 'agent.steps': 'steps', - 'agent.type.documentation': 'Documentation Agent', - 'agent.type.playbook': 'Playbook Agent', - 'agent.type.plan': 'Plan Agent', - 'agent.type.fill': 'Fill Agent', - 'agent.type.skill': 'Skill Agent', 'commands.sync.description': 'Sync agent playbooks to AI tool directories (.claude, .github, etc.)', 'commands.sync.options.source': 'Source agents directory', 'commands.sync.options.target': 'Target directories to sync to', @@ -207,39 +42,9 @@ const englishMessages = { 'commands.sync.options.force': 'Overwrite existing files/symlinks', 'commands.sync.options.dryRun': 'Preview changes without writing', 'commands.sync.options.verbose': 'Enable verbose logging', - 'prompts.main.choice.syncAgents': 'Sync agents to AI tools', - 'prompts.main.choice.create': 'Create documentation for this project', - 'prompts.main.choice.moreOptions': 'More options...', 'prompts.main.choice.viewPending': 'View pending files', - 'prompts.main.choice.updateDocs': 'Update documentation', - 'prompts.main.choice.updateDocsBehind': 'Update documentation ({daysBehind} days behind)', - 'prompts.main.choice.rescaffold': 'Re-scaffold (overwrite)', 'prompts.main.unfilledPrompt': '{count} files still need content. What would you like to do?', 'prompts.main.pendingFilesHeader': 'Files pending content:', - 'prompts.setup.confirmContinue': 'This will create and fill documentation. Continue?', - 'spinner.setup.creatingStructure': 'Creating documentation structure...', - 'spinner.setup.fillingDocs': 'Filling documentation with AI...', - 'info.setup.incomplete.title': 'Setup incomplete', - 'info.setup.incomplete.detail': 'Use MCP in your AI tool to fill or refresh documentation later.', - 'info.setup.enhanceWithAI': 'Use MCP in your AI tool to fill or refresh context files.', - 'success.setup.docsCreated': 'Documentation created!', - 'success.setup.scaffoldCreated': 'Scaffolds created with codebase context!', - 'info.setup.reviewFiles': 'Review the files in .context/ and commit them.', - 'prompts.sync.source': 'Source agents directory', - 'prompts.sync.mode': 'How should references be created?', - 'prompts.sync.modeSymlink': 'Symlinks (recommended)', - 'prompts.sync.modeMarkdown': 'Markdown reference files', - 'prompts.sync.targetType': 'Where to sync agents?', - 'prompts.sync.targetPreset': 'Use a preset (Claude, GitHub, etc.)', - 'prompts.sync.targetCustom': 'Custom path', - 'prompts.sync.selectPreset': 'Select target preset', - 'prompts.sync.preset.claude': 'Claude Code (.claude/agents)', - 'prompts.sync.preset.github': 'GitHub Copilot (.github/agents)', - 'prompts.sync.preset.cursor': 'Cursor (.cursor/agents)', - 'prompts.sync.preset.all': 'All presets', - 'prompts.sync.customPath': 'Enter custom target path', - 'prompts.sync.dryRun': 'Preview changes first (dry-run)?', - 'prompts.sync.force': 'Overwrite existing files?', 'errors.sync.failed': 'Failed to sync agents', 'errors.sync.noTargetsSpecified': 'No targets specified. Use --target or --preset.', 'errors.sync.sourceMissing': 'Source directory does not exist: {path}', @@ -261,14 +66,12 @@ const englishMessages = { 'commands.importRules.options.force': 'Overwrite existing files', 'commands.importRules.options.dryRun': 'Preview changes without writing', 'commands.importRules.options.verbose': 'Enable verbose logging', - 'commands.importRules.options.autoDetect': 'Auto-detect rules in common locations', 'commands.importAgents.description': 'Import agents from AI tool directories to .context/agents', 'commands.importAgents.options.source': 'Source paths to scan for agents', 'commands.importAgents.options.target': 'Target directory for imported agents', 'commands.importAgents.options.force': 'Overwrite existing files', 'commands.importAgents.options.dryRun': 'Preview changes without writing', 'commands.importAgents.options.verbose': 'Enable verbose logging', - 'commands.importAgents.options.autoDetect': 'Auto-detect agents in common locations', 'warnings.import.noRulesFound': 'No rules files found.', 'warnings.import.noAgentsFound': 'No agent files found.', 'spinner.import.detectingRules': 'Detecting rules files...', @@ -282,65 +85,11 @@ const englishMessages = { 'info.import.foundAgentsDetail': 'Found {count} agent files to import', 'success.import.completed': 'Import completed successfully.', 'errors.import.failed': 'Failed to import files', - 'prompts.mode.select': 'How would you like to configure this operation?', - 'prompts.mode.quick': 'Quick Start (use smart defaults)', - 'prompts.mode.advanced': 'Advanced (customize all options)', - 'prompts.summary.title': 'Configuration Summary', - 'prompts.summary.proceed': 'Proceed with this configuration?', - 'prompts.llm.autoDetected': 'Auto-detected from environment', - 'prompts.quick.confirmRepo': 'Use this repository?', - 'prompts.sync.quickTarget': 'Where should agents be synced?', - 'prompts.sync.quickTarget.common': 'Claude Code + GitHub Copilot (recommended)', - 'prompts.sync.quickTarget.claude': 'Claude Code only', - 'prompts.sync.quickTarget.all': 'All AI tools', - 'prompts.sync.quickTarget.custom': 'Custom path...', // PREVC Workflow translations - 'prompts.main.choice.workflow': 'PREVC Workflow', - 'prompts.workflow.noWorkflowFound': 'No PREVC workflow found. Create a new one?', - 'prompts.workflow.projectName': 'Project/feature name:', - 'prompts.workflow.projectNameRequired': 'Name is required', - 'prompts.workflow.description': 'Brief description (for scale detection):', - 'prompts.workflow.scale': 'Project scale:', - 'prompts.workflow.scale.auto': 'Auto-detect (based on description)', - 'prompts.workflow.scale.quick': 'Quick - Bug fixes, tweaks (~5 min)', - 'prompts.workflow.scale.small': 'Small - Simple features (~15 min)', - 'prompts.workflow.scale.medium': 'Medium - Regular features (~30 min)', - 'prompts.workflow.scale.large': 'Large - Complex systems, compliance (~1+ hours)', - 'prompts.workflow.action': 'Workflow action:', - 'prompts.workflow.action.advance': 'Advance to next phase', - 'prompts.workflow.action.refresh': 'Refresh status', - 'prompts.workflow.action.back': 'Back to main menu', - 'success.workflow.initialized': 'Workflow PREVC initialized: {name}', - 'success.workflow.advanced': 'Advanced to phase: {phase} - {phaseName}', - 'success.workflow.completed': 'Workflow completed.', - 'errors.workflow.initFailed': 'Failed to initialize workflow', - 'errors.workflow.advanceFailed': 'Failed to advance workflow', - 'errors.workflow.notFound': 'No workflow found. Run "workflow init " first.', - 'info.workflow.scale': 'Scale', - 'info.workflow.currentPhase': 'Current Phase', - 'prompts.workflow.workflowComplete': 'Current workflow is complete. What would you like to do?', - 'prompts.workflow.action.newWorkflow': 'Start a new workflow', - 'prompts.workflow.action.viewStatus': 'View completed workflow status', - 'prompts.workflow.confirmNewWorkflow': 'This will replace the current workflow. Continue?', // Start command translations - 'commands.start.description': 'Smart start: initialize context and start workflow in one command', - 'commands.start.arguments.featureName': 'Optional feature name to start a workflow', - 'commands.start.options.template': 'Workflow template: hotfix, feature, mvp, or auto', - 'commands.start.options.skipFill': 'Skip AI-assisted documentation filling', - 'commands.start.options.skipWorkflow': 'Skip workflow initialization', 'commands.previewSplash.description': 'Render the interactive splash screen preview', 'commands.previewSplash.options.title': 'Override the splash title', 'commands.previewSplash.options.directory': 'Directory to display in the splash', - 'spinner.start.detectingStack': 'Detecting technology stack...', - 'spinner.start.stackDetected': 'Stack detected: {stack}', - 'spinner.start.initializing': 'Initializing project context...', - 'spinner.start.initialized': 'Project context initialized', - 'spinner.start.initFailed': 'Failed to initialize context', - 'spinner.start.filling': 'Filling documentation with AI...', - 'spinner.start.filled': 'Documentation filled', - 'spinner.start.fillFailed': 'Documentation refresh is now handled through MCP-enabled AI tools', - 'errors.start.workflowFailed': 'Failed to start workflow', - 'success.start.complete': 'Project ready! {details}', // MCP Install command translations 'commands.mcpInstall.description': 'Install MCP server configuration for AI tools (Claude Code, Cursor, etc.)', 'commands.mcpInstall.options.global': 'Install globally in home directory (default)', @@ -413,14 +162,6 @@ const englishMessages = { 'errors.hook.unsupportedHost': 'Unsupported host: {host}. Supported: {supported}', 'errors.hook.dispatchFailed': 'Hook dispatch failed', // MCP tool display names - 'commands.mcpInstall.selectTool.claudeDesktop': 'Claude Desktop', - 'commands.mcpInstall.selectTool.vscode': 'VS Code (GitHub Copilot)', - 'commands.mcpInstall.selectTool.roo': 'Roo Code', - 'commands.mcpInstall.selectTool.amazonq': 'Amazon Q Developer CLI', - 'commands.mcpInstall.selectTool.geminiCli': 'Gemini CLI', - 'commands.mcpInstall.selectTool.kiro': 'Kiro', - 'commands.mcpInstall.selectTool.zed': 'Zed Editor', - 'commands.mcpInstall.selectTool.jetbrains': 'JetBrains IDEs', // Export command translations 'commands.export.description': 'Export rules from .context to AI tool directories', 'commands.export.options.source': 'Source directory for rules', @@ -444,68 +185,12 @@ const englishMessages = { 'errors.report.noWorkflow': 'No workflow found. Run "workflow init" first.', 'success.report.saved': 'Report saved to {path}', // Visual dashboard translations - 'dashboard.title': 'Workflow Dashboard', - 'dashboard.phase.completed': 'Completed', - 'dashboard.phase.inProgress': 'In Progress', - 'dashboard.phase.pending': 'Pending', - 'dashboard.phase.skipped': 'Skipped', // Auto-advance translations - 'autoAdvance.detected': 'Detected {count} output(s) for phase {phase}', - 'autoAdvance.suggest': 'Ready to advance to next phase?', // Workflow template translations - 'prompts.workflow.template': 'Select workflow template:', - 'prompts.workflow.template.hotfix': 'Hotfix - Quick bug fix (E → V)', - 'prompts.workflow.template.feature': 'Feature - Regular development (P → R → E → V)', - 'prompts.workflow.template.mvp': 'MVP - Full product workflow (P → R → E → V → C)', - 'prompts.workflow.template.auto': 'Auto-detect based on description', // Skill command translations 'commands.skill.description': 'Manage skills (on-demand expertise for AI agents)', - 'commands.skill.init.description': 'Initialize skills directory with built-in skills', - 'commands.skill.fill.description': 'Fill skills with AI-generated project-specific content', 'commands.skill.list.description': 'List available skills', 'commands.skill.export.description': 'Export skills to AI tool directories (Claude, Gemini, Codex)', - 'commands.skill.create.description': 'Create a new custom skill', - 'prompts.main.choice.skills': 'Manage skills', - 'prompts.skill.action': 'What would you like to do with skills?', - 'prompts.skill.action.init': 'Initialize built-in skills', - 'prompts.skill.action.fill': 'Fill skills with AI', - 'prompts.skill.action.list': 'List available skills', - 'prompts.skill.action.export': 'Export skills to AI tools', - 'prompts.skill.action.create': 'Create a custom skill', - 'prompts.skill.action.back': 'Back to main menu', - 'prompts.skill.name': 'Skill name:', - 'prompts.skill.description': 'Skill description:', - 'prompts.skill.phases': 'PREVC phases (comma-separated: P,R,E,V,C):', - 'prompts.skill.exportPreset': 'Export to which AI tools?', - 'prompts.skill.exportPreset.all': 'All tools (Claude, Gemini, Codex)', - 'prompts.skill.exportPreset.claude': 'Claude Code only', - 'prompts.skill.exportPreset.gemini': 'Gemini CLI only', - 'prompts.skill.exportPreset.codex': 'Codex CLI only', - 'success.skill.initialized': 'Skills initialized in {path}', - 'success.skill.created': 'Created skill: {name}', - 'success.skill.exported': 'Exported {count} skills to {targets} targets', - 'success.skill.filled': 'Filled {count} skills with project-specific content', - 'errors.skill.initFailed': 'Failed to initialize skills', - 'errors.skill.listFailed': 'Failed to list skills', - 'errors.skill.exportFailed': 'Failed to export skills', - 'errors.skill.createFailed': 'Failed to create skill', - 'errors.skill.fillFailed': 'Failed to fill skills', - 'errors.skill.missingScaffold': 'Skills directory not found. Run "skill init" first.', - 'steps.skill.discover': 'Discovering skills', - 'steps.skill.loadContext': 'Loading docs and agents context', - 'steps.skill.fillSkills': 'Filling {count} skills with {model}', - 'steps.skill.summary': 'Summary', - 'spinner.skill.discovering': 'Discovering scaffolded skills...', - 'spinner.skill.discovered': 'Found {count} skills to fill', - 'spinner.skill.loadingContext': 'Loading docs and agents context...', - 'spinner.skill.contextLoaded': 'Loaded docs ({docsSize} chars) and agents ({agentsSize} chars)', - 'spinner.skill.noContent': 'No content generated for {skill}', - 'spinner.skill.filled': 'Filled {skill}', - 'spinner.skill.failed': 'Failed to fill {skill}', - 'warnings.skill.noTargets': 'No skills found to fill. Run "skill init" first.', - 'info.skill.generated': 'Generated', - 'info.skill.skipped': 'Skipped (already exist)', - 'info.skill.path': 'Path', // Synchronize my context translations 'prompts.main.choice.quickSync': 'Synchronize my context', 'prompts.quickSync.selectComponents': 'Select components to sync:', @@ -521,7 +206,6 @@ const englishMessages = { 'prompts.quickSync.syncing.rules': 'Exporting rules...', 'prompts.quickSync.syncing.docs': 'Checking docs...', 'prompts.quickSync.docsOutdated': '{days} days old', - 'prompts.quickSync.updateDocs': 'Update docs too?', 'success.quickSync.complete': 'Sync complete', // Import my context translations 'prompts.main.choice.reverseSync': 'Import my context', @@ -538,15 +222,8 @@ const englishMessages = { 'success.reverseSync.complete': 'Imported {count} files', 'errors.reverseSync.failed': 'Reverse sync failed', // Manage submenus - 'prompts.main.choice.manageSkills': 'Manage Skills', - 'prompts.main.choice.manageAgents': 'Manage Agents', 'prompts.main.choice.settings': 'Settings (language)', - 'prompts.main.choice.mcpInstall': 'Install MCP', 'prompts.main.choice.integrations': 'Integrations', - 'prompts.main.choice.startWorkflow': 'Start Workflow', - 'prompts.main.choice.createPlan': 'Create Plan', - 'prompts.main.choice.quickSetup': 'Quick Setup (creates context from codebase)', - 'prompts.main.choice.enhanceWithAI': 'Enhance context with AI', // Integrations submenu 'prompts.integrations.action': 'Integrations:', 'prompts.integrations.choice.installMcp': 'Install MCP', @@ -559,30 +236,10 @@ const englishMessages = { 'prompts.integrations.codexHookFormat': 'Codex hook config format:', 'prompts.integrations.removePiMcp': 'Remove Pi MCP config too?', // Agents submenu - 'prompts.agents.action': 'Agents:', - 'prompts.agents.choice.sync': 'Sync to targets', - 'prompts.agents.choice.create': 'Create custom agent', - 'prompts.agents.choice.list': 'List agents', - 'prompts.agents.choice.back': 'Back', // Create custom agent - 'prompts.agent.name': 'Agent name:', - 'prompts.agent.description': 'Agent description:', - 'prompts.agent.role': 'Agent role/specialty:', - 'success.agent.created': 'Created agent: {name}', - 'spinner.agent.creating': 'Creating agent with AI...', - 'spinner.agent.created': 'Agent created', // Settings submenu - 'prompts.settings.action': 'Settings:', - 'prompts.settings.choice.language': 'Change language', - 'prompts.settings.choice.back': 'Back', // Mode selection (interactive entry) - 'prompts.modeSelect.select': 'How would you like to use @dotcontext/cli?', - 'prompts.modeSelect.choice.mcp': 'Set up MCP for my AI tool (recommended — no API key needed)', - 'prompts.modeSelect.choice.cli': 'Use the interactive CLI for workflow, sync, imports, and MCP setup', - 'prompts.modeSelect.choice.exit': 'Exit', // More options submenu - 'prompts.more.action': 'More options:', - 'prompts.more.choice.back': 'Back', // Synchronize my context mode 'prompts.quickSync.mode': 'Sync all (agents, skills, docs) to common targets?', 'prompts.quickSync.mode.syncAll': 'Yes, sync all', @@ -595,22 +252,10 @@ const englishMessages = { 'status.unfilled': 'Context found, {count} files still need content', 'status.detected.project': 'Detected: {languages} project', // Hit Enter / Press Enter - 'prompts.pressEnter': 'Press Enter to continue...', // Environment variable loading - 'prompts.env.loadEnv': 'Load environment variables from .env file?', // Config summary labels - 'configSummary.config': 'Config:', - 'configSummary.options': 'Options:', - 'configSummary.repo': 'repo', - 'configSummary.provider': 'provider', - 'configSummary.yes': 'Yes', - 'configSummary.no': 'No', // API key validation - 'warnings.apiKey.empty': 'API key is empty. LLM calls will likely fail.', - 'warnings.apiKey.formatMismatch': 'API key does not start with expected prefix "{prefix}" for {provider}. It may still work if correct.', // Back/cancel options - 'prompts.analysis.back': 'Back (cancel analysis options)', - 'prompts.llm.back': 'Back (cancel LLM configuration)' } as const; export type TranslationKey = keyof typeof englishMessages; @@ -620,7 +265,6 @@ type TranslationDictionary = Record; const portugueseMessages: TranslationDictionary = { 'cli.description': 'Sincronize assets de .context, faça reverse-sync do estado das ferramentas e instale integrações MCP para o seu repositório', 'global.options.lang': 'Idioma para a saída do CLI (en ou pt-BR)', - 'ui.version': 'Versão {version}', 'ui.projectConfiguration.title': 'Configuração do Projeto', 'ui.projectConfiguration.repository': 'Repositório', 'ui.projectConfiguration.output': 'Saída', @@ -639,180 +283,16 @@ const portugueseMessages: TranslationDictionary = { 'ui.generationSummary.nextStep': 'Próximo passo: personalize os templates gerados para o seu projeto.', 'ui.error.title': 'Erro', 'ui.splash.directoryLabel': 'diretorio', - 'info.prompt.title': 'Prompt do sistema', - 'info.prompt.usingCustom': 'Usando prompt em {path}.', - 'info.prompt.usingPackage': 'Usando prompt empacotado em {path}.', - 'info.prompt.usingBundled': 'Usando prompt padrão incluído no dotcontext.', 'info.update.available.title': 'Atualização disponível', 'info.update.available.detail': 'Uma nova versão {latest} está disponível (atual {current}). Atualize com {command}.', - 'commands.init.description': 'Gerar bases de documentação e agentes para um repositório', - 'commands.init.arguments.repoPath': 'Caminho do repositório a ser analisado', - 'commands.init.arguments.type': 'Tipo de base: "docs", "agents" ou "both" (padrão)', - 'commands.init.options.output': 'Diretório de saída para os artefatos gerados', - 'commands.init.options.exclude': 'Padrões glob para excluir da análise', - 'commands.init.options.include': 'Padrões glob para incluir durante a análise', - 'commands.init.options.verbose': 'Ativa logs detalhados', - 'commands.init.options.noSemantic': 'Desativa análise semântica de código (ativada por padrão)', - 'commands.init.options.noContentStubs': 'Desativa stubs de conteúdo (cabeçalhos e orientações) nos scaffolds', - 'commands.fill.description': 'Usar um assistente de IA para preencher docs e agents com o contexto mais recente do repositório', - 'commands.fill.arguments.repoPath': 'Caminho da raiz do repositório usado para montar o contexto', - 'commands.fill.options.output': 'Diretório com docs/ e agents/ gerados pela base', - 'commands.fill.options.apiKey': 'Chave de API para o provedor de LLM', - 'commands.fill.options.model': 'Modelo de LLM a ser utilizado', - 'commands.fill.options.provider': 'Provedor de LLM (openrouter, openai, anthropic, google)', - 'commands.fill.options.baseUrl': 'URL base personalizada para as APIs do provedor', - 'commands.fill.options.prompt': 'Caminho para o prompt de instrução', - 'commands.fill.options.limit': 'Número máximo de arquivos a processar', - 'commands.fill.options.exclude': 'Padrões glob para excluir da análise do repositório', - 'commands.fill.options.include': 'Padrões glob para incluir durante a análise', 'commands.fill.options.verbose': 'Ativa logs detalhados', - 'commands.fill.options.noSemantic': 'Desativa modo de contexto semântico e usa exploração baseada em ferramentas', - 'commands.fill.options.languages': 'Linguagens de programação a analisar (ex: typescript,python)', - 'commands.fill.options.useLsp': 'Habilita LSP para análise semântica mais profunda (tipos, referências)', - 'prompts.fill.semantic': 'Usar modo de contexto semântico? (mais rápido, menos tokens - recomendado)', - 'prompts.fill.languages': 'Selecione as linguagens de programação para análise', - 'prompts.fill.useLsp': 'Usar LSP para análise de tipos mais profunda? (mais lento mas mais preciso)', - 'commands.plan.description': 'Criar um plano de desenvolvimento que conecta docs e playbooks de agentes', - 'commands.plan.arguments.planName': 'Nome do plano (usado como slug do arquivo)', - 'commands.plan.options.output': 'Diretório de saída para os arquivos de plano gerados', - 'commands.plan.options.title': 'Título personalizado para o plano', - 'commands.plan.options.summary': 'Resumo inicial para o cabeçalho do plano', - 'commands.plan.options.force': 'Sobrescreve o plano se ele já existir (modo base)', - 'commands.plan.options.fill': 'Usa um assistente de IA para preencher ou atualizar o plano em vez de apenas gerar', - 'commands.plan.options.repo': 'Raiz do repositório para contexto semântico', - 'commands.plan.options.apiKey': 'Chave de API para o provedor de LLM', - 'commands.plan.options.model': 'Modelo de LLM a ser utilizado', - 'commands.plan.options.provider': 'Provedor de LLM (openrouter, openai, anthropic, google)', - 'commands.plan.options.baseUrl': 'URL base personalizada para as APIs do provedor', - 'commands.plan.options.prompt': 'Caminho para o prompt de atualização do plano', - 'commands.plan.options.dryRun': 'Pré-visualiza as atualizações sem escrever arquivos', - 'commands.plan.options.include': 'Padrões glob para incluir na análise do repositório', - 'commands.plan.options.exclude': 'Padrões glob para excluir da análise do repositório', - 'commands.plan.options.verbose': 'Ativa logs detalhados', - 'commands.plan.options.noSemantic': 'Desativa análise semântica de código (ativada por padrão)', - 'commands.plan.options.noLsp': 'Desativa análise semântica LSP (ativada por padrão para planos)', - 'errors.init.scaffoldFailed': 'Falha ao gerar os artefatos base', - 'errors.fill.failed': 'Falha ao preencher documentação e agentes com ajuda de um assistente de IA', - 'errors.plan.creationFailed': 'Falha ao criar o template do plano', - 'errors.init.invalidType': 'Tipo de base "{value}" inválido. Use um dos seguintes: {allowed}', - 'errors.common.repoMissing': 'O caminho do repositório não existe: {path}', - 'warnings.scaffold.noneSelected': 'Nenhuma documentação ou playbook selecionado. Nada a gerar.', - 'warnings.agents.missingDirectory': 'Nenhum diretório de agents encontrado. Inicialize ou importe o contexto via MCP primeiro.', - 'steps.init.analyze': 'Analisando a estrutura do repositório', - 'steps.init.docs': 'Gerando bases de documentação', - 'steps.init.agents': 'Gerando playbooks de agentes', - 'spinner.repo.scanning': 'Escaneando o repositório...', - 'spinner.repo.scanComplete': 'Encontrados {fileCount} arquivos em {directoryCount} diretórios', - 'spinner.docs.creating': 'Criando diretório e templates de docs...', - 'spinner.docs.creatingWithSemantic': 'Analisando codebase e criando templates de docs...', - 'spinner.docs.created': 'Scaffold de documentação criado ({count} arquivos)', - 'spinner.agents.creating': 'Criando diretório e templates de agentes...', - 'spinner.agents.creatingWithSemantic': 'Analisando codebase e criando playbooks de agentes...', - 'spinner.agents.created': 'Scaffold de agentes criado ({count} arquivos)', - 'spinner.plan.creating': 'Criando template de plano...', - 'spinner.plan.created': 'Template de plano criado', - 'spinner.plan.creationFailed': 'Falha ao criar o template do plano', - 'success.scaffold.ready': 'Base disponível em {path}', - 'success.plan.createdAt': 'Plano criado em {path}', - 'errors.fill.missingDocsScaffold': 'Scaffold de documentação não encontrado. Execute `dotcontext init` primeiro.', - 'errors.fill.missingAgentsScaffold': 'Scaffold de agentes não encontrado. Execute `dotcontext init` primeiro.', - 'errors.fill.missingScaffold': 'Nenhum scaffold encontrado. Execute `dotcontext init` primeiro para criar docs e/ou agents.', - 'steps.fill.analyze': 'Analisando a estrutura do repositório', - 'warnings.fill.noTargets': 'Nenhum arquivo Markdown foi encontrado em .context/docs ou .context/agents. Execute "dotcontext init" antes de preencher.', - 'steps.fill.processFiles': 'Atualizando {count} arquivos com {model}', - 'spinner.fill.processing': 'Processando {path}...', - 'spinner.fill.noContent': 'Nenhum conteúdo recebido para {path}', - 'messages.fill.emptyResponse': 'Resposta vazia do assistente de IA', - 'messages.fill.previewStart': '--- Início da prévia ---', - 'messages.fill.previewEnd': '--- Fim da prévia ---', - 'spinner.fill.updated': 'Atualizado {path}', - 'spinner.fill.failed': 'Falha em {path}', - 'steps.fill.summary': 'Resumindo o uso do assistente de IA', - 'success.fill.completed': 'Preenchimento com assistente de IA concluído. Revise as mudanças e faça o commit quando estiver pronto.', - 'errors.plan.invalidName': 'O nome do plano deve conter ao menos um caractere alfanumérico.', - 'messages.plan.regenerated': 'Regerado {path} antes do preenchimento com assistente de IA.', - 'messages.plan.created': 'Criado {path} antes do preenchimento com assistente de IA.', - 'info.plan.scaffolded.title': 'Plano criado', - 'errors.plan.missingPlansDir': 'Diretório de planos não encontrado. Execute `dotcontext plan ` para criar um.', - 'errors.plan.notFound': 'Plano não encontrado. Esperado {expected}.', - 'steps.plan.summary': 'Resumindo estado do repositório', - 'spinner.planFill.analyzingRepo': 'Analisando repositório...', - 'spinner.planFill.summaryReady': 'Resumo do repositório pronto', - 'steps.plan.update': 'Atualizando {path} com {model}', - 'spinner.planFill.updating': 'Preenchendo {path}...', - 'spinner.planFill.noContent': 'Nenhum conteúdo recebido do assistente de IA', - 'spinner.planFill.dryRun': 'Execução simulada - prévia a seguir', - 'spinner.planFill.updated': 'Atualizado {path}', - 'spinner.planFill.failed': 'Falha ao preencher o plano', - 'steps.plan.summaryResults': 'Resumindo o uso do assistente de IA', - 'success.plan.filled': 'Preenchimento do plano concluído. Revise as atualizações e faça o commit quando estiver pronto.', - 'errors.commands.analyzeRemoved': 'O comando analyze foi removido na versão focada em bases do dotcontext.', - 'errors.commands.fillRemoved': 'O comando fill agora está disponível apenas por ferramentas de IA com MCP.', - 'errors.commands.updateRemoved': 'O comando update não é mais suportado. Execute `dotcontext init` novamente para atualizar as bases.', - 'errors.commands.previewRemoved': 'O modo de pré-visualização foi descontinuado. Use diretamente os docs e playbooks gerados.', - 'errors.commands.guidelinesRemoved': 'A geração de guidelines dependia de LLMs e não está mais disponível.', 'errors.cli.executionFailed': 'Falha na execução do CLI', - 'errors.init.overwriteDeclined': 'Scaffold cancelado para evitar sobrescrever conteúdo existente.', 'prompts.main.action': 'O que você gostaria de fazer?', - 'prompts.main.choice.scaffold': 'Gerar bases de documentação/agentes', - 'prompts.main.choice.fill': 'Preencher docs e agentes com um LLM', - 'prompts.main.choice.plan': 'Criar um plano de desenvolvimento', - 'prompts.main.choice.changeLanguage': 'Mudar idioma', 'prompts.main.choice.exit': 'Sair do modo interativo', - 'prompts.scaffold.repoPath': 'Caminho do repositório para analisar', - 'prompts.scaffold.type': 'O que devemos gerar?', - 'prompts.scaffold.typeBoth': 'Docs e playbooks', - 'prompts.scaffold.typeDocs': 'Somente docs', - 'prompts.scaffold.typeAgents': 'Somente playbooks', - 'prompts.scaffold.selectComponents': 'O que devemos gerar? (Selecione todos que desejar)', - 'prompts.scaffold.componentDocs': 'Documentacao', - 'prompts.scaffold.componentAgents': 'Playbooks de agentes', - 'prompts.scaffold.componentSkills': 'Skills', - 'spinner.skills.creating': 'Criando diretorio e templates de skills...', - 'spinner.skills.created': 'Scaffold de skills criado ({count} arquivos)', - 'steps.init.skills': 'Gerando skills', - 'prompts.init.confirmOverwriteDocs': 'A documentação já existe em {path}. Deseja sobrescrever os arquivos atuais?', - 'prompts.init.confirmOverwriteAgents': 'Os playbooks de agentes já existem em {path}. Deseja sobrescrever os arquivos atuais?', - 'prompts.init.confirmOverwriteSkills': 'Os skills já existem em {path}. Deseja sobrescrever os arquivos atuais?', - 'prompts.common.verbose': 'Ativar logs detalhados?', - 'prompts.fill.repoPath': 'Caminho do repositório que contém a base', - 'prompts.fill.promptPath': 'Caminho do prompt personalizado (deixe em branco para usar o padrão incluso)', - 'prompts.fill.limit': 'Número máximo de arquivos a atualizar (deixe em branco para todos)', - 'prompts.fill.overrideModel': 'Sobrescrever configuração de provedor/modelo?', - 'prompts.fill.provider': 'Selecione o provedor de LLM', - 'prompts.fill.provider.openrouter': 'OpenRouter (acesso a múltiplos modelos)', - 'prompts.fill.provider.openai': 'OpenAI (GPT-4, etc.)', - 'prompts.fill.provider.anthropic': 'Anthropic (Claude)', - 'prompts.fill.provider.google': 'Google (Gemini)', - 'prompts.fill.model': 'Identificador do modelo', - 'prompts.fill.provideApiKey': 'Informar uma chave de API para esta execução?', - 'prompts.fill.apiKey': 'Chave de API', - 'prompts.plan.name': 'Nome do plano (usado no slug do arquivo)', - 'prompts.plan.goal': 'O que deve ser planejado?', - 'prompts.plan.mode': 'Como você quer trabalhar com este plano?', - 'prompts.plan.modeScaffold': 'Gerar um template de plano', - 'prompts.plan.modeFill': 'Criar um plano com I.A. (cria um plano com o contexto atual)', - 'prompts.plan.summary': 'Resumo opcional para iniciar o plano (deixe em branco para adicionar depois)', - 'prompts.plan.repoPath': 'Raiz do repositório para contexto', - 'prompts.plan.dryRun': 'Pré-visualizar atualizações sem escrever arquivos?', - 'prompts.plan.useLsp': 'Usar LSP para análise de tipos mais profunda? (recomendado para planos)', 'prompts.language.select': 'Escolha o idioma do CLI / Choose the CLI language', 'prompts.language.option.en': 'Inglês / English', 'prompts.language.option.pt-BR': 'Português (Brasil) / Portuguese (Brazil)', - 'errors.plan.fillFailed': 'Falha ao preencher o plano com ajuda de um assistente de IA', - 'errors.fill.promptMissing': 'Arquivo de prompt não encontrado em {path}.', - 'errors.fill.apiKeyMissing': 'É necessária uma chave de API {provider}. Defina uma das variáveis {envVars} ou use --api-key.', - 'info.interactive.returning.title': 'Menu principal', - 'info.interactive.returning.detail': 'Voltando ao menu interativo. Escolha outra ação ou selecione Sair.', 'success.interactive.goodbye': 'Até logo! Obrigado por usar o dotcontext.', - 'agent.starting': 'Iniciando', - 'agent.complete': 'Concluído', - 'agent.steps': 'passos', - 'agent.type.documentation': 'Agente de Documentação', - 'agent.type.playbook': 'Agente de Playbook', - 'agent.type.plan': 'Agente de Plano', - 'agent.type.fill': 'Agente de Preenchimento', - 'agent.type.skill': 'Agente de Skill', 'commands.sync.description': 'Sincronizar playbooks de agentes com diretórios de ferramentas IA (.claude, .github, etc.)', 'commands.sync.options.source': 'Diretório de origem dos agentes', 'commands.sync.options.target': 'Diretórios de destino para sincronizar', @@ -821,39 +301,9 @@ const portugueseMessages: TranslationDictionary = { 'commands.sync.options.force': 'Sobrescrever arquivos/symlinks existentes', 'commands.sync.options.dryRun': 'Pré-visualizar mudanças sem escrever', 'commands.sync.options.verbose': 'Ativa logs detalhados', - 'prompts.main.choice.syncAgents': 'Sincronizar agentes com ferramentas IA', - 'prompts.main.choice.create': 'Criar documentação para este projeto', - 'prompts.main.choice.moreOptions': 'Mais opções...', 'prompts.main.choice.viewPending': 'Ver arquivos pendentes', - 'prompts.main.choice.updateDocs': 'Atualizar documentação', - 'prompts.main.choice.updateDocsBehind': 'Atualizar documentação ({daysBehind} dias atrás)', - 'prompts.main.choice.rescaffold': 'Refazer scaffold (sobrescrever)', 'prompts.main.unfilledPrompt': '{count} arquivos ainda precisam de conteudo. O que você gostaria de fazer?', 'prompts.main.pendingFilesHeader': 'Arquivos pendentes de conteúdo:', - 'prompts.setup.confirmContinue': 'Isso criará e preencherá a documentação. Continuar?', - 'spinner.setup.creatingStructure': 'Criando estrutura de documentação...', - 'spinner.setup.fillingDocs': 'Preenchendo documentação com IA...', - 'info.setup.incomplete.title': 'Configuração incompleta', - 'info.setup.incomplete.detail': 'Use MCP na sua ferramenta de IA para preencher ou atualizar a documentação depois.', - 'info.setup.enhanceWithAI': 'Use MCP na sua ferramenta de IA para preencher ou atualizar os arquivos de contexto.', - 'success.setup.docsCreated': 'Documentação criada!', - 'success.setup.scaffoldCreated': 'Scaffolds criados com contexto do codebase!', - 'info.setup.reviewFiles': 'Revise os arquivos em .context/ e faça commit.', - 'prompts.sync.source': 'Diretório de origem dos agentes', - 'prompts.sync.mode': 'Como as referências devem ser criadas?', - 'prompts.sync.modeSymlink': 'Symlinks (recomendado)', - 'prompts.sync.modeMarkdown': 'Arquivos de referência Markdown', - 'prompts.sync.targetType': 'Para onde sincronizar os agentes?', - 'prompts.sync.targetPreset': 'Usar um preset (Claude, GitHub, etc.)', - 'prompts.sync.targetCustom': 'Caminho personalizado', - 'prompts.sync.selectPreset': 'Selecione o preset de destino', - 'prompts.sync.preset.claude': 'Claude Code (.claude/agents)', - 'prompts.sync.preset.github': 'GitHub Copilot (.github/agents)', - 'prompts.sync.preset.cursor': 'Cursor (.cursor/agents)', - 'prompts.sync.preset.all': 'Todos os presets', - 'prompts.sync.customPath': 'Digite o caminho personalizado de destino', - 'prompts.sync.dryRun': 'Pré-visualizar mudanças primeiro (dry-run)?', - 'prompts.sync.force': 'Sobrescrever arquivos existentes?', 'errors.sync.failed': 'Falha ao sincronizar agentes', 'errors.sync.noTargetsSpecified': 'Nenhum destino especificado. Use --target ou --preset.', 'errors.sync.sourceMissing': 'Diretório de origem não existe: {path}', @@ -875,14 +325,12 @@ const portugueseMessages: TranslationDictionary = { 'commands.importRules.options.force': 'Sobrescrever arquivos existentes', 'commands.importRules.options.dryRun': 'Pré-visualizar mudanças sem escrever', 'commands.importRules.options.verbose': 'Ativar logs detalhados', - 'commands.importRules.options.autoDetect': 'Auto-detectar regras em locais comuns', 'commands.importAgents.description': 'Importar agentes de diretórios de ferramentas IA para .context/agents', 'commands.importAgents.options.source': 'Caminhos de origem para procurar agentes', 'commands.importAgents.options.target': 'Diretório de destino para agentes importados', 'commands.importAgents.options.force': 'Sobrescrever arquivos existentes', 'commands.importAgents.options.dryRun': 'Pré-visualizar mudanças sem escrever', 'commands.importAgents.options.verbose': 'Ativar logs detalhados', - 'commands.importAgents.options.autoDetect': 'Auto-detectar agentes em locais comuns', 'warnings.import.noRulesFound': 'Nenhum arquivo de regras encontrado.', 'warnings.import.noAgentsFound': 'Nenhum arquivo de agente encontrado.', 'spinner.import.detectingRules': 'Detectando arquivos de regras...', @@ -896,65 +344,11 @@ const portugueseMessages: TranslationDictionary = { 'info.import.foundAgentsDetail': 'Encontrados {count} arquivos de agentes para importar', 'success.import.completed': 'Importação concluída com sucesso.', 'errors.import.failed': 'Falha ao importar arquivos', - 'prompts.mode.select': 'Como você quer configurar esta operação?', - 'prompts.mode.quick': 'Início Rápido (usar configurações automáticas)', - 'prompts.mode.advanced': 'Avançado (personalizar todas as opções)', - 'prompts.summary.title': 'Resumo da Configuração', - 'prompts.summary.proceed': 'Prosseguir com esta configuração?', - 'prompts.llm.autoDetected': 'Detectado automaticamente do ambiente', - 'prompts.quick.confirmRepo': 'Usar este repositório?', - 'prompts.sync.quickTarget': 'Para onde sincronizar os agentes?', - 'prompts.sync.quickTarget.common': 'Claude Code + GitHub Copilot (recomendado)', - 'prompts.sync.quickTarget.claude': 'Somente Claude Code', - 'prompts.sync.quickTarget.all': 'Todas as ferramentas IA', - 'prompts.sync.quickTarget.custom': 'Caminho personalizado...', // PREVC Workflow translations - 'prompts.main.choice.workflow': 'Workflow PREVC', - 'prompts.workflow.noWorkflowFound': 'Nenhum workflow PREVC encontrado. Criar um novo?', - 'prompts.workflow.projectName': 'Nome do projeto/feature:', - 'prompts.workflow.projectNameRequired': 'Nome é obrigatório', - 'prompts.workflow.description': 'Descrição breve (para detecção de escala):', - 'prompts.workflow.scale': 'Escala do projeto:', - 'prompts.workflow.scale.auto': 'Auto-detectar (baseado na descrição)', - 'prompts.workflow.scale.quick': 'Rápido - Bug fixes, ajustes (~5 min)', - 'prompts.workflow.scale.small': 'Pequeno - Features simples (~15 min)', - 'prompts.workflow.scale.medium': 'Médio - Features regulares (~30 min)', - 'prompts.workflow.scale.large': 'Grande - Sistemas complexos, compliance (~1+ hora)', - 'prompts.workflow.action': 'Ação do workflow:', - 'prompts.workflow.action.advance': 'Avançar para próxima fase', - 'prompts.workflow.action.refresh': 'Atualizar status', - 'prompts.workflow.action.back': 'Voltar ao menu principal', - 'success.workflow.initialized': 'Workflow PREVC inicializado: {name}', - 'success.workflow.advanced': 'Avançou para fase: {phase} - {phaseName}', - 'success.workflow.completed': 'Workflow concluído.', - 'errors.workflow.initFailed': 'Falha ao inicializar workflow', - 'errors.workflow.advanceFailed': 'Falha ao avançar workflow', - 'errors.workflow.notFound': 'Nenhum workflow encontrado. Execute "workflow init " primeiro.', - 'info.workflow.scale': 'Escala', - 'info.workflow.currentPhase': 'Fase Atual', - 'prompts.workflow.workflowComplete': 'O workflow atual está concluído. O que você gostaria de fazer?', - 'prompts.workflow.action.newWorkflow': 'Iniciar um novo workflow', - 'prompts.workflow.action.viewStatus': 'Ver status do workflow concluído', - 'prompts.workflow.confirmNewWorkflow': 'Isso substituirá o workflow atual. Continuar?', // Traduções do comando start - 'commands.start.description': 'Inicio inteligente: inicializa o contexto e inicia o workflow em um comando', - 'commands.start.arguments.featureName': 'Nome opcional da feature para iniciar um workflow', - 'commands.start.options.template': 'Template de workflow: hotfix, feature, mvp ou auto', - 'commands.start.options.skipFill': 'Pular preenchimento de documentação com IA', - 'commands.start.options.skipWorkflow': 'Pular inicialização do workflow', 'commands.previewSplash.description': 'Renderizar uma previa da splash screen interativa', 'commands.previewSplash.options.title': 'Sobrescrever o titulo da splash', 'commands.previewSplash.options.directory': 'Diretorio exibido na splash', - 'spinner.start.detectingStack': 'Detectando stack de tecnologia...', - 'spinner.start.stackDetected': 'Stack detectada: {stack}', - 'spinner.start.initializing': 'Inicializando contexto do projeto...', - 'spinner.start.initialized': 'Contexto do projeto inicializado', - 'spinner.start.initFailed': 'Falha ao inicializar contexto', - 'spinner.start.filling': 'Preenchendo documentação com IA...', - 'spinner.start.filled': 'Documentação preenchida', - 'spinner.start.fillFailed': 'A atualização da documentação agora é feita por ferramentas de IA com MCP', - 'errors.start.workflowFailed': 'Falha ao iniciar workflow', - 'success.start.complete': 'Projeto pronto! {details}', // Traduções do comando mcp:install 'commands.mcpInstall.description': 'Instalar configuração do servidor MCP para ferramentas de IA (Claude Code, Cursor, etc.)', 'commands.mcpInstall.options.global': 'Instalar globalmente no diretório home (padrão)', @@ -1027,14 +421,6 @@ const portugueseMessages: TranslationDictionary = { 'errors.hook.unsupportedHost': 'Host não suportado: {host}. Suportados: {supported}', 'errors.hook.dispatchFailed': 'Falha no dispatch de hook', // Nomes de exibição das ferramentas MCP - 'commands.mcpInstall.selectTool.claudeDesktop': 'Claude Desktop', - 'commands.mcpInstall.selectTool.vscode': 'VS Code (GitHub Copilot)', - 'commands.mcpInstall.selectTool.roo': 'Roo Code', - 'commands.mcpInstall.selectTool.amazonq': 'Amazon Q Developer CLI', - 'commands.mcpInstall.selectTool.geminiCli': 'Gemini CLI', - 'commands.mcpInstall.selectTool.kiro': 'Kiro', - 'commands.mcpInstall.selectTool.zed': 'Zed Editor', - 'commands.mcpInstall.selectTool.jetbrains': 'JetBrains IDEs', // Traduções do comando export 'commands.export.description': 'Exportar regras de .context para diretórios de ferramentas IA', 'commands.export.options.source': 'Diretório fonte das regras', @@ -1058,68 +444,12 @@ const portugueseMessages: TranslationDictionary = { 'errors.report.noWorkflow': 'Nenhum workflow encontrado. Execute "workflow init" primeiro.', 'success.report.saved': 'Relatório salvo em {path}', // Traduções do dashboard visual - 'dashboard.title': 'Dashboard do Workflow', - 'dashboard.phase.completed': 'Concluído', - 'dashboard.phase.inProgress': 'Em Andamento', - 'dashboard.phase.pending': 'Pendente', - 'dashboard.phase.skipped': 'Pulado', // Traduções do auto-advance - 'autoAdvance.detected': 'Detectados {count} output(s) para fase {phase}', - 'autoAdvance.suggest': 'Pronto para avançar para próxima fase?', // Traduções de templates de workflow - 'prompts.workflow.template': 'Selecione o template de workflow:', - 'prompts.workflow.template.hotfix': 'Hotfix - Correção rápida de bug (E → V)', - 'prompts.workflow.template.feature': 'Feature - Desenvolvimento regular (P → R → E → V)', - 'prompts.workflow.template.mvp': 'MVP - Workflow completo de produto (P → R → E → V → C)', - 'prompts.workflow.template.auto': 'Auto-detectar baseado na descrição', // Traduções do comando skill 'commands.skill.description': 'Gerenciar skills (expertise sob demanda para agentes IA)', - 'commands.skill.init.description': 'Inicializar diretório de skills com skills built-in', - 'commands.skill.fill.description': 'Preencher skills com conteúdo específico do projeto gerado por IA', 'commands.skill.list.description': 'Listar skills disponíveis', 'commands.skill.export.description': 'Exportar skills para diretórios de ferramentas IA (Claude, Gemini, Codex)', - 'commands.skill.create.description': 'Criar uma nova skill personalizada', - 'prompts.main.choice.skills': 'Gerenciar skills', - 'prompts.skill.action': 'O que você gostaria de fazer com skills?', - 'prompts.skill.action.init': 'Inicializar skills built-in', - 'prompts.skill.action.fill': 'Preencher skills com IA', - 'prompts.skill.action.list': 'Listar skills disponíveis', - 'prompts.skill.action.export': 'Exportar skills para ferramentas IA', - 'prompts.skill.action.create': 'Criar uma skill personalizada', - 'prompts.skill.action.back': 'Voltar ao menu principal', - 'prompts.skill.name': 'Nome da skill:', - 'prompts.skill.description': 'Descrição da skill:', - 'prompts.skill.phases': 'Fases PREVC (separadas por vírgula: P,R,E,V,C):', - 'prompts.skill.exportPreset': 'Exportar para quais ferramentas IA?', - 'prompts.skill.exportPreset.all': 'Todas as ferramentas (Claude, Gemini, Codex)', - 'prompts.skill.exportPreset.claude': 'Somente Claude Code', - 'prompts.skill.exportPreset.gemini': 'Somente Gemini CLI', - 'prompts.skill.exportPreset.codex': 'Somente Codex CLI', - 'success.skill.initialized': 'Skills inicializadas em {path}', - 'success.skill.created': 'Skill criada: {name}', - 'success.skill.exported': 'Exportadas {count} skills para {targets} destinos', - 'success.skill.filled': '{count} skills preenchidas com conteúdo específico do projeto', - 'errors.skill.initFailed': 'Falha ao inicializar skills', - 'errors.skill.listFailed': 'Falha ao listar skills', - 'errors.skill.exportFailed': 'Falha ao exportar skills', - 'errors.skill.createFailed': 'Falha ao criar skill', - 'errors.skill.fillFailed': 'Falha ao preencher skills', - 'errors.skill.missingScaffold': 'Diretório de skills não encontrado. Execute "skill init" primeiro.', - 'steps.skill.discover': 'Descobrindo skills', - 'steps.skill.loadContext': 'Carregando contexto de docs e agents', - 'steps.skill.fillSkills': 'Preenchendo {count} skills com {model}', - 'steps.skill.summary': 'Resumo', - 'spinner.skill.discovering': 'Descobrindo skills scaffolded...', - 'spinner.skill.discovered': 'Encontradas {count} skills para preencher', - 'spinner.skill.loadingContext': 'Carregando contexto de docs e agents...', - 'spinner.skill.contextLoaded': 'Carregado docs ({docsSize} chars) e agents ({agentsSize} chars)', - 'spinner.skill.noContent': 'Nenhum conteúdo gerado para {skill}', - 'spinner.skill.filled': '{skill} preenchida', - 'spinner.skill.failed': 'Falha ao preencher {skill}', - 'warnings.skill.noTargets': 'Nenhuma skill encontrada para preencher. Execute "skill init" primeiro.', - 'info.skill.generated': 'Geradas', - 'info.skill.skipped': 'Puladas (já existem)', - 'info.skill.path': 'Caminho', // Synchronize my context translations 'prompts.main.choice.quickSync': 'Synchronize my context', 'prompts.quickSync.selectComponents': 'Selecione os componentes para sincronizar:', @@ -1135,7 +465,6 @@ const portugueseMessages: TranslationDictionary = { 'prompts.quickSync.syncing.rules': 'Exportando regras...', 'prompts.quickSync.syncing.docs': 'Verificando docs...', 'prompts.quickSync.docsOutdated': '{days} dias atrás', - 'prompts.quickSync.updateDocs': 'Atualizar docs também?', 'success.quickSync.complete': 'Sincronização completa', // Import my context translations 'prompts.main.choice.reverseSync': 'Import my context', @@ -1152,15 +481,8 @@ const portugueseMessages: TranslationDictionary = { 'success.reverseSync.complete': '{count} arquivos importados', 'errors.reverseSync.failed': 'Reverse sync falhou', // Manage submenus - 'prompts.main.choice.manageSkills': 'Gerenciar Skills', - 'prompts.main.choice.manageAgents': 'Gerenciar Agents', 'prompts.main.choice.settings': 'Configurações (idioma)', - 'prompts.main.choice.mcpInstall': 'Instalar MCP', 'prompts.main.choice.integrations': 'Integrações', - 'prompts.main.choice.startWorkflow': 'Iniciar Workflow', - 'prompts.main.choice.createPlan': 'Criar Plano', - 'prompts.main.choice.quickSetup': 'Setup Rápido (cria contexto do codebase)', - 'prompts.main.choice.enhanceWithAI': 'Aprimorar contexto com IA', // Submenu de integrações 'prompts.integrations.action': 'Integrações:', 'prompts.integrations.choice.installMcp': 'Instalar MCP', @@ -1173,30 +495,10 @@ const portugueseMessages: TranslationDictionary = { 'prompts.integrations.codexHookFormat': 'Formato da configuração de hooks do Codex:', 'prompts.integrations.removePiMcp': 'Remover também a configuração MCP do Pi?', // Agents submenu - 'prompts.agents.action': 'Agents:', - 'prompts.agents.choice.sync': 'Sincronizar para targets', - 'prompts.agents.choice.create': 'Criar agent personalizado', - 'prompts.agents.choice.list': 'Listar agents', - 'prompts.agents.choice.back': 'Voltar', // Create custom agent - 'prompts.agent.name': 'Nome do agent:', - 'prompts.agent.description': 'Descrição do agent:', - 'prompts.agent.role': 'Role/especialidade do agent:', - 'success.agent.created': 'Agent criado: {name}', - 'spinner.agent.creating': 'Criando agent com IA...', - 'spinner.agent.created': 'Agent criado', // Settings submenu - 'prompts.settings.action': 'Configurações:', - 'prompts.settings.choice.language': 'Mudar idioma', - 'prompts.settings.choice.back': 'Voltar', // Mode selection (interactive entry) - 'prompts.modeSelect.select': 'Como você gostaria de usar o @dotcontext/cli?', - 'prompts.modeSelect.choice.mcp': 'Configurar MCP para minha ferramenta de IA (recomendado — sem API key)', - 'prompts.modeSelect.choice.cli': 'Usar a CLI interativa para workflow, sincronização, importações e configuração MCP', - 'prompts.modeSelect.choice.exit': 'Sair', // More options submenu - 'prompts.more.action': 'Mais opções:', - 'prompts.more.choice.back': 'Voltar', // Synchronize my context mode 'prompts.quickSync.mode': 'Sincronizar tudo (agents, skills, docs) para destinos comuns?', 'prompts.quickSync.mode.syncAll': 'Sim, sincronizar tudo', @@ -1209,22 +511,10 @@ const portugueseMessages: TranslationDictionary = { 'status.unfilled': 'Contexto encontrado, {count} arquivos ainda precisam de conteúdo', 'status.detected.project': 'Detectado: projeto {languages}', // Hit Enter / Press Enter - 'prompts.pressEnter': 'Pressione Enter para continuar...', // Environment variable loading - 'prompts.env.loadEnv': 'Carregar variáveis de ambiente do arquivo .env?', // Config summary labels - 'configSummary.config': 'Configuração:', - 'configSummary.options': 'Opções:', - 'configSummary.repo': 'repo', - 'configSummary.provider': 'provedor', - 'configSummary.yes': 'Sim', - 'configSummary.no': 'Não', // API key validation - 'warnings.apiKey.empty': 'A chave de API está vazia. Chamadas ao LLM provavelmente falharão.', - 'warnings.apiKey.formatMismatch': 'A chave de API não começa com o prefixo esperado "{prefix}" para {provider}. Pode funcionar se estiver correta.', // Back/cancel options - 'prompts.analysis.back': 'Voltar (cancelar opções de análise)', - 'prompts.llm.back': 'Voltar (cancelar configuração do LLM)' }; const dictionaries: Record = { @@ -1297,10 +587,6 @@ function fillTemplate(template: string, params?: TranslateParams): string { }); } -export function isSupportedLocale(locale: string): boolean { - return SUPPORTED_LOCALES.some(candidate => candidate.toLowerCase() === locale.toLowerCase()); -} - function resolveLocaleCandidate(locale?: string | null): Locale | undefined { if (!locale) { return undefined; diff --git a/src/utils/pathSecurity.ts b/src/utils/pathSecurity.ts index dfa317b5..1e77b944 100644 --- a/src/utils/pathSecurity.ts +++ b/src/utils/pathSecurity.ts @@ -39,7 +39,7 @@ export class SecurityError extends Error { export class PathValidator { private readonly normalizedRoot: string; - constructor(private readonly workspaceRoot: string) { + constructor(workspaceRoot: string) { this.normalizedRoot = path.resolve(workspaceRoot); } diff --git a/src/utils/processShutdown.ts b/src/utils/processShutdown.ts index 04512ebe..485c4a6d 100644 --- a/src/utils/processShutdown.ts +++ b/src/utils/processShutdown.ts @@ -34,7 +34,7 @@ export function registerProcessShutdown( signalListeners.clear(); }; - const shutdown = async (signal?: NodeJS.Signals): Promise => { + const shutdown = async (): Promise => { if (shuttingDown) { return; } @@ -55,7 +55,7 @@ export function registerProcessShutdown( for (const signal of signals) { const listener = () => { - void shutdown(signal); + void shutdown(); }; signalListeners.set(signal, listener); process.once(signal, listener); diff --git a/src/utils/prompts/configSummary.ts b/src/utils/prompts/configSummary.ts deleted file mode 100644 index 6afc02af..00000000 --- a/src/utils/prompts/configSummary.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { colors } from '../theme'; -import type { TranslateFn } from '../i18n'; -import type { ConfigSummary } from './types'; - -/** - * Displays a compact configuration summary before execution - */ -export function displayConfigSummary(summary: ConfigSummary, _t: TranslateFn): void { - // Line 1: operation | repo | provider (model) - const parts: string[] = []; - parts.push(summary.operation); - if (summary.repoPath) parts.push(`${_t('configSummary.repo')}: ${summary.repoPath}`); - if (summary.provider) { - const providerInfo = summary.model - ? `${summary.provider} (${summary.model})` - : summary.provider; - parts.push(`${_t('configSummary.provider')}: ${providerInfo}`); - } - console.log(` ${colors.secondary(_t('configSummary.config'))} ${parts.join(' | ')}`); - - // Line 2: options (if any) - if (summary.options && Object.keys(summary.options).length > 0) { - const optParts: string[] = []; - for (const [key, value] of Object.entries(summary.options)) { - const displayValue = - typeof value === 'boolean' - ? value ? _t('configSummary.yes') : _t('configSummary.no') - : Array.isArray(value) - ? value.join(', ') - : String(value); - optParts.push(`${key}=${displayValue}`); - } - console.log(` ${colors.secondary(_t('configSummary.options'))} ${optParts.join(', ')}`); - } -} diff --git a/src/utils/prompts/index.ts b/src/utils/prompts/index.ts index 1bb6b49c..68c39928 100644 --- a/src/utils/prompts/index.ts +++ b/src/utils/prompts/index.ts @@ -1,105 +1,2 @@ -import type { TranslateFn } from '../i18n'; -import type { InteractiveMode, AnalysisOptions } from './types'; -import { themedSelect, themedConfirm, themedCheckbox, Separator } from '../themedPrompt'; -import { colors } from '../theme'; - -// Re-export types -export * from './types'; - -// Re-export modules +export type { SmartDefaults } from './types'; export { detectSmartDefaults } from './smartDefaults'; -export { displayConfigSummary } from './configSummary'; - -/** - * Prompts user to choose between quick and advanced mode - */ -export async function promptInteractiveMode(t: TranslateFn): Promise { - return themedSelect({ - message: t('prompts.mode.select'), - choices: [ - { name: t('prompts.mode.quick'), value: 'quick' }, - { name: t('prompts.mode.advanced'), value: 'advanced' } - ], - default: 'quick' - }); -} - -/** - * Prompts for analysis options (semantic, languages, LSP) - * - * Returns null if the user chooses to go back/cancel. - */ -export async function promptAnalysisOptions( - t: TranslateFn, - defaults: { languages?: string[]; useLsp?: boolean } = {} -): Promise { - // Use a select instead of confirm so we can offer a back option - const semanticChoice = await themedSelect<'yes' | 'no' | '__back__'>({ - message: t('prompts.fill.semantic'), - choices: [ - { name: 'Yes', value: 'yes' }, - { name: 'No', value: 'no' }, - new Separator(), - { name: colors.secondary(t('prompts.analysis.back')), value: '__back__' } - ], - default: 'yes' - }); - - if (semanticChoice === '__back__') { - return null; - } - - const useSemantic = semanticChoice === 'yes'; - let languages: string[] | undefined; - let useLsp = false; - - if (useSemantic) { - const defaultLanguages = defaults.languages || ['typescript', 'javascript', 'python']; - const selectedLanguages = await themedCheckbox({ - message: t('prompts.fill.languages'), - choices: [ - { name: 'TypeScript', value: 'typescript', checked: defaultLanguages.includes('typescript') }, - { name: 'JavaScript', value: 'javascript', checked: defaultLanguages.includes('javascript') }, - { name: 'Python', value: 'python', checked: defaultLanguages.includes('python') } - ] - }); - languages = selectedLanguages.length > 0 ? selectedLanguages : undefined; - - useLsp = await themedConfirm({ - message: t('prompts.fill.useLsp'), - default: defaults.useLsp ?? false - }); - } - - const verbose = await themedConfirm({ - message: t('prompts.common.verbose'), - default: false - }); - - return { - semantic: useSemantic, - languages, - useLsp, - verbose - }; -} - -/** - * Prompts for confirmation before proceeding - */ -export async function promptConfirmProceed(t: TranslateFn): Promise { - return themedConfirm({ - message: t('prompts.summary.proceed'), - default: true - }); -} - -/** - * Prompts user to load environment variables from .env file - */ -export async function promptLoadEnv(t: TranslateFn): Promise { - return themedConfirm({ - message: t('prompts.env.loadEnv'), - default: false - }); -} diff --git a/src/utils/prompts/types.ts b/src/utils/prompts/types.ts index 34bcaa2c..a237beef 100644 --- a/src/utils/prompts/types.ts +++ b/src/utils/prompts/types.ts @@ -1,30 +1,6 @@ -export type InteractiveMode = 'quick' | 'advanced'; - -export interface PathsPromptResult { - repoPath: string; - outputDir: string; -} - export interface SmartDefaults { repoPath: string; outputDir: string; scaffoldExists: boolean; detectedLanguages: string[]; } - -export interface ConfigSummary { - operation: 'fill' | 'plan' | 'sync'; - repoPath?: string; - outputDir?: string; - provider?: string; - model?: string; - apiKeySource?: 'env' | 'provided' | 'none'; - options?: Record; -} - -export interface AnalysisOptions { - semantic: boolean; - languages?: string[]; - useLsp: boolean; - verbose: boolean; -} diff --git a/src/utils/themedPrompt.ts b/src/utils/themedPrompt.ts index e6fe1e22..4d2ba629 100644 --- a/src/utils/themedPrompt.ts +++ b/src/utils/themedPrompt.ts @@ -7,7 +7,7 @@ type ClackPrompts = typeof import('@clack/prompts'); type ClackPromptModule = Pick< ClackPrompts, - 'select' | 'confirm' | 'text' | 'password' | 'multiselect' | 'isCancel' | 'cancel' + 'select' | 'confirm' | 'multiselect' | 'isCancel' | 'cancel' >; const importEsm = new Function( @@ -51,9 +51,6 @@ type ClackPromptOption = Value extends PrimitiveChoiceValue disabled?: boolean; }; -type LegacyValidateResult = boolean | string; -type LegacyValidate = (value: string) => LegacyValidateResult | Promise; -type ClackValidate = (value: string | undefined) => string | Error | undefined; type SelectOptions = Parameters>[0]['options']; type MultiselectOptions = Parameters>[0]['options']; @@ -131,42 +128,6 @@ function mapCheckedValues( }); } -function mapValidateResult(result: LegacyValidateResult): string | undefined { - if (result === true) { - return undefined; - } - - if (result === false) { - return 'Invalid value'; - } - - return result; -} - -function isPromiseLike(value: unknown): value is PromiseLike { - return ( - typeof value === 'object' && - value !== null && - typeof (value as { then?: unknown }).then === 'function' - ); -} - -function mapValidate(validate?: LegacyValidate): ClackValidate | undefined { - if (!validate) { - return undefined; - } - - return (value) => { - const result = validate(value ?? ''); - - if (isPromiseLike(result)) { - throw new Error('Async prompt validation is not supported by @clack/prompts'); - } - - return mapValidateResult(result); - }; -} - function unwrapPromptResult( clack: Pick, result: Value | symbol @@ -210,36 +171,6 @@ export async function themedConfirm(config: { return unwrapPromptResult(clack, result); } -export async function themedInput(config: { - message: string; - default?: string; - validate?: LegacyValidate; -}): Promise { - const clack = await loadClack(); - const result = await clack.text({ - message: config.message, - defaultValue: config.default, - validate: mapValidate(config.validate), - }); - - return unwrapPromptResult(clack, result); -} - -export async function themedPassword(config: { - message: string; - mask?: string; - validate?: LegacyValidate; -}): Promise { - const clack = await loadClack(); - const result = await clack.password({ - message: config.message, - mask: config.mask, - validate: mapValidate(config.validate), - }); - - return unwrapPromptResult(clack, result); -} - export async function themedCheckbox(config: { message: string; choices: ReadonlyArray | Separator>; @@ -268,6 +199,5 @@ export const themedPromptTestHooks = { }, mapChoicesToOptions, mapCheckedValues, - mapValidateResult, unwrapPromptResult, }; diff --git a/tsconfig.json b/tsconfig.json index 49c898eb..dfa936f0 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -5,6 +5,8 @@ "outDir": "./dist", "rootDir": "./src", "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true,