/**
 * Generalized Ruflo Phase Executor
 *
 * A single, shared executor that runs Ruflo agent swarms for ANY pipeline phase.
 * Each phase passes its own task definitions, artifact context, and agentics
 * agent results — the executor handles swarm init, task creation, and execution.
 *
 * CRITICAL: When Ruflo swarm produces 0 files (no LLM backend in this env),
 * the executor falls back to extracting actual code files from agentics agent
 * responses (forge/sdk, forge/cli return real TypeScript files in their responses)
 * and writing them to disk. This is the cooperation path — agentics agents
 * produce real code, not templates.
 *
 * Supports all 17 target languages — Ruflo is language-agnostic.
 */
import type { AgenticsServiceResult } from './swarm-orchestrator.js';
/** A task to dispatch to the Ruflo swarm. */
export interface RufloTask {
    /** Human-readable label for the task. */
    readonly label: string;
    /** Full task description including what to build and quality expectations. */
    readonly description: string;
    /** Target directory for this task's output (relative to project root). */
    readonly targetDir: string;
    /** Implementation wave (1=foundation, 2=core, 3=dependent, 4=cross-cutting). */
    readonly wave?: number;
    /** Labels of tasks this depends on (must complete before this task starts). */
    readonly dependsOn?: string[];
    /**
     * Extra CLI arguments appended when the task is dispatched to the Ruflo
     * binary. ADR-PIPELINE-091 requires every engineering task to carry
     * `--local-only` so the local swarm does not re-call the same remote
     * backends it is supposed to be independent of. Task builders populate
     * this field; the executor forwards it as argv to `ruflo task create`.
     */
    readonly argv?: readonly string[];
}
/**
 * Minimal Phase 1 dossier shape accepted by `runPrimaryPhaseExecution`.
 *
 * This is an anti-corruption layer around the real Phase 1 output — the
 * canonical `ResearchDossier` in `phase2/types.ts` is richer but
 * consumer-unfriendly for the new primary-executor entry point. The primary
 * executor only needs the user's scenario query + pointers to on-disk
 * artifacts so it can build Ruflo tasks with embedded context; anything
 * else flows through as `extras`.
 */
export interface Phase1Dossier {
    /** The user's original natural-language query. */
    readonly scenarioQuery: string;
    /** Trace id for the current pipeline run. */
    readonly traceId: string;
    /** Absolute path to the run directory (~/.agentics/runs/<traceId>). */
    readonly runDir: string;
    /** Optional artifact-label → absolute path map (same shape the existing task builders consume). */
    readonly artifacts?: Record<string, string>;
    /** Optional free-form extras (enrichment agent output, remote diligence findings). */
    readonly extras?: Record<string, unknown>;
}
/**
 * Execution context passed by auto-chain / the ADR-093 dependency gate when
 * invoking the Ruflo primary executor. Keeps the invocation side-effect-free
 * wrt. cwd — callers supply explicit output locations.
 */
export interface RufloExecutionContext {
    /** Absolute path the Ruflo swarm should write under (typically runDir/.ruflo-cache/<phase>). */
    readonly outputDir: string;
    /** Detected target language (used by the Phase 5 coverage / impl builders). Default: typescript. */
    readonly language?: string;
    /** Any upstream agentics-dev diligence results that should be woven into the task descriptions. */
    readonly agenticsResults?: AgenticsServiceResult[];
    /** Max agents in the local swarm (defaults to DEFAULT_MAX_AGENTS). */
    readonly maxAgents?: number;
}
/** A single implementation wave containing ordered tasks and a focused prompt. */
export interface ImplementationWave {
    /** Wave number (1=foundation, 2=core, 3=dependent, 4=cross-cutting). */
    readonly wave: number;
    /** Human-readable wave label. */
    readonly label: string;
    /** Bounded context names included in this wave. */
    readonly contexts: string[];
    /** Focused implementation prompt for this wave. */
    readonly prompt: string;
    /** Tasks belonging to this wave. */
    readonly tasks: RufloTask[];
    /** Prior wave numbers that must complete before this wave. */
    readonly dependsOn: number[];
}
/** Phase-specific configuration for the Ruflo swarm. */
export interface RufloPhaseConfig {
    /** Pipeline phase number (2-6). */
    readonly phase: number;
    /** Human-readable phase label. */
    readonly label: string;
    /** The user's original natural language query. */
    readonly scenarioQuery: string;
    /** Run directory (~/.agentics/runs/<traceId>). */
    readonly runDir: string;
    /** Trace ID for this pipeline run. */
    readonly traceId: string;
    /** Tasks to dispatch to the swarm. */
    readonly tasks: RufloTask[];
    /** Agentics agent results from this phase's dispatch. */
    readonly agenticsResults: AgenticsServiceResult[];
    /** Artifact file paths from prior phases (key=label, value=absolute path). */
    readonly priorArtifacts: Record<string, string>;
    /** Target directory for swarm output. */
    readonly outputDir: string;
    /** Maximum agents in the swarm (default: 8). */
    readonly maxAgents?: number;
    /** Swarm timeout in ms (default: 600000 = 10 min). */
    readonly timeoutMs?: number;
}
/** Result of a Ruflo phase execution. */
export interface RufloPhaseResult {
    /** Whether the swarm was invoked at all. */
    readonly invoked: boolean;
    /** Whether ruflo was available. */
    readonly rufloAvailable: boolean;
    /** Number of files generated/modified. */
    readonly filesModified: number;
    /** Number of tasks created. */
    readonly tasksCreated: number;
    /** Whether the swarm completed successfully. */
    readonly swarmCompleted: boolean;
    /** Wall-clock time in ms. */
    readonly timing: number;
    /** Ruflo version string. */
    readonly version: string;
    /** Number of code files extracted from agentics agent responses. */
    readonly agentCodeFilesWritten: number;
}
/** A code file extracted from an agentics agent response. */
interface AgentCodeFile {
    readonly sourceDomain: string;
    readonly sourceAgent: string;
    readonly filePath: string;
    readonly content: string;
    readonly sizeBytes: number;
}
/**
 * Sanitize generated interface names to prevent double-prefix bugs.
 *
 * Convention:
 *   Port interfaces: {ContextName}Port (no "I" prefix)
 *   Adapters: {Implementation}{ContextName}Adapter
 *   Never double-prefix (II*, IInterface*)
 */
export declare function sanitizeInterfaceName(name: string, kind: 'port' | 'adapter' | 'interface'): string;
/**
 * Resolve the ruflo binary. Checks local node_modules, walks up, then global.
 * Result is cached for the process lifetime.
 */
export declare function resolveRufloBinary(): string | null;
export declare function checkRufloAvailable(): {
    available: boolean;
    version: string;
    binary: string;
    reason?: 'disabled-by-env' | 'binary-not-found' | 'version-probe-failed' | 'swarm-unsupported';
};
/** Test-only: clear the availability cache so the next call re-probes. */
export declare function _resetCheckRufloAvailableCache(): void;
/**
 * Analyze the DDD context map to determine bounded context dependencies.
 * Returns a map of context name -> list of context names it depends on.
 *
 * Dependency direction: if A is upstream of B (A -> B), then B depends on A.
 * Relationships like "customer-supplier", "conformist", and "anticorruption-layer"
 * mean the downstream context depends on the upstream context.
 * "shared-kernel" means mutual dependency — both go in the same wave.
 */
export declare function buildContextDependencyGraph(contextMap: {
    from: string;
    to: string;
    relationship: string;
}[], contextNames: string[]): Map<string, string[]>;
/**
 * Topologically sort bounded contexts by dependency order.
 * Contexts with no dependencies come first (foundations), then contexts
 * that depend only on already-sorted contexts, and so on.
 *
 * Returns contexts grouped by depth level (0 = no deps, 1 = depends on level 0, etc.).
 * Handles cycles by placing cyclic contexts at the deepest level encountered.
 */
export declare function topologicalSort(deps: Map<string, string[]>): string[][];
/**
 * Group topologically sorted contexts into implementation waves.
 *
 * - Wave 1 (Foundation): Database schemas, shared infrastructure, contexts with zero dependencies
 * - Wave 2 (Core): Contexts that depend only on Wave 1 contexts
 * - Wave 3 (Dependent): Contexts that depend on Wave 2 contexts
 * - Wave 4 (Cross-cutting): Frontend, tests, deployment — built AFTER domain code exists
 *
 * If there are more than 3 dependency levels, intermediate levels are merged
 * into Waves 2 and 3 proportionally.
 */
export declare function groupIntoWaves(sortedLevels: string[][], _language: string, scenarioQuery: string, artifacts: Record<string, string>): ImplementationWave[];
/**
 * Build a focused, 20-40 line implementation prompt for a single wave.
 * Each prompt tells the LLM exactly:
 *   - What to implement (specific contexts, specific ADRs)
 *   - Why this order (dependency rationale)
 *   - What's already built (prior wave output)
 *   - Concrete fields and types (from DDD aggregates)
 */
export declare function buildWavePrompt(wave: ImplementationWave, ddd: {
    contexts: {
        name: string;
        aggregates: string[];
        commands: string[];
        queries: string[];
        events: string[];
    }[];
}, adrs: {
    id: string;
    title: string;
    decision: string;
}[], tdd: {
    suites: {
        name: string;
        testCount: number;
        strategy: string;
    }[];
    approach: string;
}, language: string, priorWaveLabels: string[]): string;
/**
 * Build iterative, dependency-ordered implementation prompts.
 *
 * Instead of one monolithic prompt dumping ALL contexts, ADRs, and TDD suites,
 * this function produces a sequence of focused wave prompts. Each wave prompt
 * references only the contexts, ADRs, and tests relevant to that wave, and
 * explicitly states what prior waves have already built.
 *
 * Exported for direct use by Phase 5 wave-ordered execution.
 */
export declare function buildIterativeImplementationPrompts(artifacts: Record<string, string>, scenarioQuery: string, language: string): ImplementationWave[];
/**
 * Build a structured implementation prompt from pipeline artifacts.
 *
 * This prompt is fed to Ruflo swarms AND the 110 agentics.dev agent fleet.
 * It directs them to implement the ADRs + DDDs with high-level SPARC guidance
 * using London School TDD (outside-in, mock collaborators at seam boundaries).
 *
 * The prompt is written to disk as `implementation-prompt.md` and used as the
 * swarm objective across all phases.
 *
 * ADR-028: Now internally uses iterative wave-ordered prompts. The output is
 * a single string with clear wave boundaries for backward compatibility.
 */
export declare function buildImplementationPrompt(artifacts: Record<string, string>, scenarioQuery: string, language: string): string;
/**
 * Build and persist the implementation prompt to disk.
 * Returns the prompt text and the file path where it was written.
 */
export declare function writeImplementationPrompt(runDir: string, artifacts: Record<string, string>, scenarioQuery: string, language: string): {
    prompt: string;
    promptPath: string;
};
/**
 * Build Ruflo tasks for Phase 2: Deep Research.
 * Ruflo writes complete research dossier, not just extracts.
 */
export declare function buildPhase2Tasks(scenarioQuery: string, _artifacts: Record<string, string>): RufloTask[];
/**
 * Build Ruflo tasks for Phase 3: SPARC + TDD.
 * Ruflo writes complete SPARC specs and TDD plans from research.
 */
export declare function buildPhase3Tasks(scenarioQuery: string, _artifacts: Record<string, string>): RufloTask[];
/**
 * Build Ruflo tasks for Phase 4: ADRs + DDDs.
 * Ruflo writes complete architecture decisions and domain models.
 */
export declare function buildPhase4Tasks(scenarioQuery: string, _artifacts: Record<string, string>): RufloTask[];
/**
 * Build Ruflo tasks for Phase 5: Production Build.
 *
 * ADR-028 Change 4: Instead of creating all tasks in a flat list dispatched
 * simultaneously, tasks are now organized into dependency-ordered waves.
 * Each task carries a `wave` property and `dependsOn` references so the
 * executor can run them sequentially (wave 1 first, then 2, etc.).
 *
 * Wave structure:
 *   Wave 1 (Foundation): Database schemas, shared infra, contexts with no deps
 *   Wave 2 (Core): Independent bounded contexts
 *   Wave 3 (Dependent): Contexts that reference Wave 2 contexts
 *   Wave 4 (Cross-cutting): Frontend, tests, deployment -- AFTER domain code
 */
export declare function buildPhase5Tasks(scenarioQuery: string, _language: string, _artifacts: Record<string, string>): RufloTask[];
/**
 * Build Ruflo tasks for Phase 6: ERP Surface + Final Assembly.
 * Ruflo writes the ERP integration layer and deployment package.
 */
export declare function buildPhase6Tasks(scenarioQuery: string, artifacts: Record<string, string>): RufloTask[];
/**
 * Build Ruflo tasks for the coverage-gap slot (normally handled by the remote
 * `quality-engineering/coverage-gap-detect` agent). Under ADR-PIPELINE-091
 * the local swarm produces the same output so remote 503s do not gate the
 * pipeline. The task writes a `coverage-gaps.json` under the phase-5
 * coverage directory.
 */
export declare function buildCoverageGapTasks(dossier: Phase1Dossier, context: RufloExecutionContext): RufloTask[];
/**
 * Build Ruflo tasks for the implementation-prompts slot (normally produced
 * from SPARC + ADRs + DDD). Emits one Ruflo task per canonical SPARC section
 * so the combined output populates `plans/prompts/impl-NNN-<slug>.md` plus
 * `plans/prompts/execution-plan.json`. Matches the filename format auto-chain
 * consumes: `impl-${String(order).padStart(3, '0')}-${phase.slug}.md`.
 */
export declare function buildImplPromptsTasks(dossier: Phase1Dossier, context: RufloExecutionContext, adrs?: readonly {
    id: string;
    title: string;
    decision?: string;
}[], ddd?: readonly {
    name: string;
    aggregates?: readonly string[];
}[]): RufloTask[];
/** Phase ids accepted by `runPrimaryPhaseExecution`. */
export type PrimaryPhaseId = 'phase3-sparc' | 'phase4-adrs-ddd' | 'phase5a-prompts' | 'phase5-coverage';
/**
 * Result of `runPrimaryPhaseExecution`. Tags the output with an explicit
 * execution tier so auto-chain / the ADR-093 gate can decide whether to fall
 * through to deterministic templates. Extends `RufloPhaseResult` with the
 * tier + reason, while keeping the raw inner result for observability.
 */
export interface PrimaryPhaseExecutionResult {
    /** Phase id the execution was requested for. */
    readonly phaseId: PrimaryPhaseId;
    /** Whether the invocation produced usable artifacts. */
    readonly success: boolean;
    /**
     * Which executor produced the output.
     *  - `ruflo-local`   : local Ruflo swarm ran (may still have timed out — check swarmCompleted)
     *  - `local-fallback`: ADR-094 D8 deterministic local generator ran (Ruflo unavailable, but
     *                     Phase-1 consensus was usable). Output tagged `quality: degraded`.
     *  - `unavailable`   : neither Ruflo NOR the local fallback could produce output; caller exits.
     */
    readonly executionTier: 'ruflo-local' | 'local-fallback' | 'unavailable';
    /** Machine-readable reason when `success === false`. */
    readonly reason?: 'ruflo-not-available' | 'ruflo-disabled-by-env' | 'ruflo-timeout' | 'no-tasks-built' | 'swarm-error' | 'local-fallback-no-consensus' | 'local-fallback-write-error';
    /** Underlying Ruflo swarm result when actually invoked; undefined on the unavailable path. */
    readonly rufloResult?: RufloPhaseResult;
    /** Convenience mirror of `rufloResult?.filesModified` (0 on the unavailable path). */
    readonly filesModified: number;
    /** Wall-clock time in ms. */
    readonly timing: number;
    /** Human-readable summary. */
    readonly message: string;
}
export declare function runPrimaryPhaseExecution(phaseId: PrimaryPhaseId, dossier: Phase1Dossier, context: RufloExecutionContext, timeout?: number): Promise<PrimaryPhaseExecutionResult>;
/**
 * Execute a Ruflo agent swarm for any pipeline phase.
 *
 * This is the single entry point for Ruflo delegation across ALL phases.
 * It handles:
 *   1. Ruflo binary resolution and availability check
 *   2. Swarm initialization with anti-drift config
 *   3. Task creation with agentics agent results embedded as context
 *   4. Swarm execution with configurable timeout
 *   5. FALLBACK: When Ruflo produces 0 files, extract code from agentics
 *      agent responses and write them to disk
 *   6. File count tracking and result reporting
 *
 * The agentics agent results are injected INTO each task description,
 * giving Ruflo access to the fleet's domain expertise during generation.
 * When Ruflo can't produce code (no LLM backend), the agents' own code
 * output is extracted and used directly.
 */
export declare function executeRufloPhaseSwarm(config: RufloPhaseConfig): RufloPhaseResult;
/** Collect artifact paths available for Phase 2 (from Phase 1). */
export declare function collectPhase2Artifacts(runDir: string): Record<string, string>;
/** Collect artifact paths available for Phase 3 (from Phase 1 + 2). */
export declare function collectPhase3Artifacts(runDir: string): Record<string, string>;
/** Collect artifact paths available for Phase 4 (from Phases 1-3). */
export declare function collectPhase4Artifacts(runDir: string): Record<string, string>;
/** Collect artifact paths available for Phase 5 (from Phases 1-4). */
export declare function collectPhase5Artifacts(runDir: string): Record<string, string>;
/** Collect artifact paths available for Phase 6 (from Phases 1-5). */
export declare function collectPhase6Artifacts(runDir: string): Record<string, string>;
/**
 * Load code files from Phase 1 results.json.
 * Phase 1 invokes the full 110-agent fleet, and agents like forge/sdk and
 * forge/cli return actual code files in their response payloads. This function
 * extracts those files so they can be written to disk during later phases.
 *
 * Response structure in results.json:
 *   agents[].result.response.artifacts[].content.sdk_artifacts[].files[]
 *   agents[].result.response.artifacts[].content.files[]
 */
export declare function extractPhase1AgentCode(runDir: string): AgentCodeFile[];
/**
 * Check if real code files were produced in a directory.
 * "Real" means actual source files with content — not .gitkeep, metadata, etc.
 * Used by auto-chain to decide whether to skip template generators.
 */
export declare function hasRealCodeFiles(dir: string): boolean;
export {};
//# sourceMappingURL=ruflo-phase-executor.d.ts.map