/**
 * IVTR Orchestration Loop — State Machine
 *
 * Implements the Implement → Validate → Test → Release phase state machine
 * for per-task multi-agent enforcement. State is persisted as JSON in the
 * `ivtr_state` column on the `tasks` table.
 *
 * State machine transitions:
 *
 *   (none) ──startIvtr──► implement
 *   implement ──advanceIvtr──► validate
 *   validate  ──advanceIvtr──► test
 *   test      ──advanceIvtr──► released
 *
 *   implement | validate | test ──loopBackIvtr──► implement | validate | test
 *
 *   released ──releaseIvtr──► marks task status=done
 *
 * Evidence refs are sha256 hashes of attachment blobs stored under
 * .cleo/attachments (see ADR T796 attachment store).
 *
 * @epic T810
 * @task T811
 * @task T813
 */
import type { AcceptanceGate, TestOutputRecord } from '@cleocode/contracts';
/** The four canonical IVTR phases. */
export type IvtrPhase = 'implement' | 'validate' | 'test' | 'released';
/**
 * A single phase entry in the IVTR phase history.
 * Loop-back entries have `passed: false` and a non-null `reason`.
 */
export interface IvtrPhaseEntry {
    /** Phase name. */
    phase: IvtrPhase;
    /** Agent identity string (from session/agent registry), or null if unknown. */
    agentIdentity: string | null;
    /** ISO timestamp when this phase was started. */
    startedAt: string;
    /** ISO timestamp when this phase was completed, or null if still active. */
    completedAt: string | null;
    /** Whether this phase passed. null = in-progress. */
    passed: boolean | null;
    /** sha256 hashes of attachments produced as evidence for this phase. */
    evidenceRefs: string[];
    /** Populated on loop-back entries to explain the failure. */
    reason?: string;
}
/** Complete IVTR state for a task. */
export interface IvtrState {
    /** Task ID (e.g. 'T811'). */
    taskId: string;
    /** Current active phase. */
    currentPhase: IvtrPhase;
    /** Full ordered history of all phase entries (including loop-backs). */
    phaseHistory: IvtrPhaseEntry[];
    /** ISO timestamp when the IVTR loop was first started. */
    startedAt: string;
    /**
     * Running count of loop-backs per target phase.
     *
     * Incremented each time `loopBackIvtr` targets that phase.
     * After `MAX_LOOP_BACKS_PER_PHASE` loop-backs to the same phase, the next
     * attempt throws `E_IVTR_MAX_RETRIES` and requires HITL escalation.
     *
     * Missing on legacy states — treated as all-zeros on read.
     */
    loopBackCount: Record<IvtrPhase, number>;
}
/**
 * Start the IVTR loop for a task.
 *
 * Creates a fresh IvtrState with `currentPhase = 'implement'` and persists
 * it to the task row. Idempotent: calling again on a task that already has
 * IVTR state returns the existing state without mutation.
 *
 * @param taskId - Task ID to start the IVTR loop for.
 * @param options - Optional cwd and agent identity.
 * @returns The current (possibly new) IvtrState.
 */
export declare function startIvtr(taskId: string, options?: {
    cwd?: string;
    agentIdentity?: string;
}): Promise<IvtrState>;
/**
 * Advance the IVTR loop from the current phase to the next.
 *
 * Closes the current in-progress phase entry (marks it `passed: true`,
 * records evidence), opens a new entry for the next phase.
 *
 * Throws if:
 * - No IVTR state exists (call startIvtr first).
 * - Already at `released` (use releaseIvtr to finalise).
 *
 * @param taskId   - Task to advance.
 * @param evidence - sha256 hashes of evidence attachments from this phase.
 * @param options  - Optional cwd and agent identity for the next phase entry.
 * @returns Updated IvtrState.
 */
export declare function advanceIvtr(taskId: string, evidence: string[], options?: {
    cwd?: string;
    agentIdentity?: string;
}): Promise<IvtrState>;
/**
 * Maximum number of loop-backs allowed per phase before HITL escalation.
 *
 * After `MAX_LOOP_BACKS_PER_PHASE` loop-backs to the same phase, the next
 * attempt is rejected with `E_IVTR_MAX_RETRIES` so that a human can
 * intervene rather than the loop spinning indefinitely.
 */
export declare const MAX_LOOP_BACKS_PER_PHASE = 2;
/**
 * Error code emitted when a phase has exceeded its maximum loop-back count.
 *
 * Callers (domain handlers, orchestrators) should surface this to the operator
 * as a HITL escalation prompt — the task cannot self-heal and needs review.
 */
export declare const E_IVTR_MAX_RETRIES = "E_IVTR_MAX_RETRIES";
/**
 * Loop back to an earlier phase due to failure.
 *
 * Closes the current active phase entry as failed, appends a failure note
 * to the history, then opens a new entry for the target phase.
 *
 * Increments the `loopBackCount` for the target phase. After
 * `MAX_LOOP_BACKS_PER_PHASE` loop-backs to the same phase, subsequent
 * calls throw an error with code `E_IVTR_MAX_RETRIES`.
 *
 * @param taskId  - Task to loop back.
 * @param toPhase - Phase to rewind to. Must be 'implement', 'validate', or 'test'.
 * @param reason  - Human-readable explanation of the failure.
 * @param evidence - sha256 hashes of failure evidence attachments.
 * @param options  - Optional cwd and agent identity.
 * @returns Updated IvtrState.
 * @throws Error with message starting with `E_IVTR_MAX_RETRIES` when the
 *         per-phase loop-back limit is exceeded.
 */
export declare function loopBackIvtr(taskId: string, toPhase: IvtrPhase, reason: string, evidence: string[], options?: {
    cwd?: string;
    agentIdentity?: string;
}): Promise<IvtrState>;
/**
 * Attempt to release a task after all three phases have passed.
 *
 * Validates that implement, validate, and test all have at least one passing
 * phase entry. If validation passes, marks the task status = 'done' and
 * sets `currentPhase = 'released'`.
 *
 * @param taskId  - Task to release.
 * @param options - Optional cwd.
 * @returns `{ released: true }` on success, or `{ released: false, failures }` listing missing phases.
 */
export declare function releaseIvtr(taskId: string, options?: {
    cwd?: string;
}): Promise<{
    released: boolean;
    failures?: string[];
}>;
/**
 * Retrieve the current IVTR state for a task, or null if the loop has not
 * been started.
 *
 * @param taskId  - Task ID to inspect.
 * @param options - Optional cwd.
 * @returns IvtrState or null.
 */
export declare function getIvtrState(taskId: string, options?: {
    cwd?: string;
}): Promise<IvtrState | null>;
/**
 * A condensed summary of a single implement-phase evidence attachment.
 *
 * Callers who have access to the full `ImplDiffRecord` from
 * `@cleocode/contracts` SHOULD populate all optional fields. Callers that
 * only have access to the sha256 ref from `IvtrPhaseEntry.evidenceRefs` MAY
 * leave them undefined — the prompt will fall back to listing the sha256 alone.
 *
 * @see `ImplDiffRecord` in `@cleocode/contracts` for the full shape.
 */
export interface ImplEvidenceSummary {
    /** SHA-256 hex digest of the attachment blob (64 chars). */
    attachmentSha256: string;
    /** Evidence kind discriminant (e.g. `'impl-diff'`, `'lint-report'`). */
    kind: string;
    /** Relative paths of every file the diff touches. */
    filesChanged?: string[];
    /** Net lines added across all changed files. */
    linesAdded?: number;
    /** Net lines removed across all changed files. */
    linesRemoved?: number;
    /** Wall-clock duration of the implement action in milliseconds. */
    durationMs?: number;
}
/**
 * Build a resolved prompt string for the current phase's assigned agent.
 *
 * When advancing to the `validate` phase the prompt is enriched with four
 * additional sections required by T812:
 *
 * 1. **Original task spec** — always included.
 * 2. **Implement-phase evidence bundle** — all `IvtrPhaseEntry` records where
 *    `phase === 'implement'` and `passed === true`, rendered with attachment
 *    metadata (sha256, kind, filesChanged, linesAdded/Removed, duration).
 *    Callers pass the optional `evidenceBundle` to supply pre-fetched metadata
 *    from the attachment store; the function falls back to raw sha256 refs if
 *    the bundle is empty.
 * 3. **Validate-agent instructions** — how to produce a `ValidateSpecCheckRecord`
 *    (`kind: 'validate-spec-check'`) and attach it via `cleo docs add`.
 * 4. **Explicit REJECT criteria** — conditions under which the validate agent
 *    MUST trigger a loop-back to implement.
 *
 * When the target phase is `implement` and prior failures exist, a loop-back
 * context section is injected with the triggering reason and history.
 *
 * For the `test` phase, the prompt instructs the agent to run
 * `cleo verify <id> --run` and produce a `TestOutputRecord`.
 *
 * @param taskId          - Task ID (used to label the prompt).
 * @param state           - Current IvtrState (after the transition to the target phase).
 * @param taskTitle       - Short task title (from cleo show).
 * @param taskDesc        - Full task description / spec including REQ-IDs.
 * @param acceptanceGates - Optional typed AcceptanceGate objects (used by the test phase).
 * @param evidenceBundle  - Optional pre-fetched implement-phase evidence summaries
 *                          (used by the validate phase; ignored for other phases).
 * @returns Prompt string for the phase's assigned agent.
 */
export declare function resolvePhasePrompt(taskId: string, state: IvtrState, taskTitle: string, taskDesc: string, acceptanceGates?: AcceptanceGate[], evidenceBundle?: ImplEvidenceSummary[]): string;
/**
 * Result returned by autoRunGatesAndRecord.
 */
export interface AutoRunGatesResult {
    /** sha256 of the stored attachment containing the full gate-run output. */
    attachmentSha256: string;
    /** Number of gates that passed. */
    testsPassed: number;
    /** Number of gates that failed or errored. */
    testsFailed: number;
    /** The composite exit code: 0 if all gates passed, 1 otherwise. */
    exitCode: number;
    /** The synthesised EvidenceRecord (kind: 'test-output'). */
    evidenceRecord: TestOutputRecord;
}
/**
 * Execute all typed AcceptanceGates for a task atomically during an IVTR
 * --next transition with --auto-run-tests set.
 *
 * Steps performed in a single atomic operation:
 * 1. Accept the typed gates array (strings already filtered by caller).
 * 2. Run each gate via runGates().
 * 3. Serialise the results to JSON and store via AttachmentStore.
 * 4. Synthesise a TestOutputRecord carrying the sha256, pass/fail counts,
 *    and exit code.
 * 5. Append the sha256 to the active phaseHistory entry's evidenceRefs and
 *    persist the updated IvtrState.
 *
 * @param taskId          - Task ID being tested.
 * @param acceptanceItems - Mixed acceptance array from the task record (strings
 *                          are silently ignored; only typed gates are executed).
 * @param agentIdentity   - Optional agent identity string for provenance.
 * @param cwd             - Optional working directory.
 * @returns AutoRunGatesResult with the attachment sha256 and counts.
 */
export declare function autoRunGatesAndRecord(taskId: string, acceptanceItems: (string | AcceptanceGate)[], agentIdentity?: string, cwd?: string): Promise<AutoRunGatesResult>;
//# sourceMappingURL=ivtr-loop.d.ts.map