/**
 * OwlCoda Native Task Store
 *
 * In-memory task management backing the Task* tools.
 * Tasks persist for the session lifetime.
 *
 * Upstream parity notes:
 * - Upstream uses utils/tasks.ts with file-backed JSON storage
 * - Supports task lists, hooks, teammate ownership
 * - Our version: in-memory Map with same field structure
 *
 * Execution layer (re-introduced 0.13.31):
 *   When `TaskCreate` is given a `command` and it has cleared the bash
 *   risk classifier (see tools/task-create.ts), we spawn a bash child
 *   here and store its handle in `runningProcesses`. Stdout / stderr are
 *   buffered on the Task itself so `TaskOutput` can surface them when
 *   the task hits a terminal state. Exit is event-driven (`child.on('exit')`),
 *   never polled. `TaskStop` writes status='cancelled' BEFORE sending
 *   SIGTERM so the exit handler doesn't race the stop and overwrite
 *   `cancelled` with `completed`. `resetTaskStore` SIGKILLs any survivors
 *   so test runs don't leak processes.
 *
 * Task Execution Mode v1 (Slice 1, 0.14.19+):
 *   Tasks can now carry a structured execution plan: `deliverables` and
 *   `steps`. Steps track state, expected artifacts, and verification.
 *   Use `updateTaskStep` / `getCurrentOrNextStep` / `taskHasOpenRequiredSteps`
 *   to drive the task execution loop.
 */
import type { BashRiskClassification } from '../bash-risk.js';
import type { TaskPathScope } from '../protocol/types.js';
/** Task status values matching upstream TaskStatusSchema. */
export type TaskStatus = 'pending' | 'in_progress' | 'completed' | 'cancelled' | 'blocked';
export type TaskStepStatus = 'pending' | 'in_progress' | 'completed' | 'failed' | 'blocked' | 'cancelled';
export type TaskStepAction = {
    kind: 'local_tool';
    recommendedTools?: string[];
} | {
    kind: 'subagent';
    agentType?: string;
    prompt?: string;
} | {
    kind: 'manual';
    reason: string;
};
export type TaskVerificationKind = 'file_exists' | 'file_contains' | 'artifact_count' | 'verification_pack' | 'command' | 'none';
export interface TaskVerificationRequiredMarker {
    marker: string;
    label?: string;
}
export interface TaskVerificationCheck {
    id: string;
    kind: TaskVerificationKind;
    packId?: 'html_deck' | string;
    path?: string;
    pattern?: string;
    root?: string;
    glob?: string;
    min?: number;
    deckPath?: string;
    expectedSections?: number;
    buildNotesPath?: string;
    requiredMarkers?: Array<string | TaskVerificationRequiredMarker>;
    minFileSizeBytes?: number;
    minSectionBytes?: number;
    forbiddenTerms?: string[];
    command?: string;
    expectedExitCode?: number;
    reason?: string;
}
export interface TaskVerificationResult {
    checkId: string;
    passed: boolean;
    detail?: string;
    checkedAt: string;
    metadata?: Record<string, unknown>;
}
export interface TaskStep {
    id: string;
    title: string;
    description: string;
    status: TaskStepStatus;
    action: TaskStepAction;
    expectedArtifacts: TaskPathScope[];
    verification: TaskVerificationCheck[];
    verificationResults: TaskVerificationResult[];
    touchedPaths: string[];
    startedAt?: string;
    completedAt?: string;
    failureReason?: string;
}
/** Result of a step update operation — allows callers to surface errors via ToolResult. */
export type TaskStepUpdateResult = {
    ok: true;
    task: Task;
    step: TaskStep;
} | {
    ok: false;
    reason: string;
};
export interface Task {
    id: string;
    subject: string;
    description: string;
    status: TaskStatus;
    activeForm?: string;
    metadata?: Record<string, unknown>;
    blocks: string[];
    blockedBy: string[];
    owner?: string;
    createdAt: string;
    updatedAt: string;
    /** Optional bash command this task is executing. */
    command?: string;
    /** Working directory for `command` (defaults to process.cwd()). */
    cwd?: string;
    /** Captured stdout (only populated for command-backed tasks). */
    stdout?: string;
    /** Captured stderr (only populated for command-backed tasks). */
    stderr?: string;
    /** Exit code from the spawned child (after natural exit). */
    exitCode?: number;
    /** Spawn-level error message, if any. */
    error?: string;
    /** Risk classification recorded at spawn time for audit. */
    bashRisk?: BashRiskClassification;
    /** Structured deliverable paths for this task (Slice 1). */
    deliverables?: TaskPathScope[];
    /** Ordered execution steps (Slice 1). Undefined = pure TODO task (backward compat). */
    steps?: TaskStep[];
    /** ID of the currently active step (Slice 1). */
    currentStepId?: string;
}
/** Create a new task. */
export declare function createTask(opts: {
    subject: string;
    description: string;
    activeForm?: string;
    metadata?: Record<string, unknown>;
    command?: string;
    cwd?: string;
    bashRisk?: BashRiskClassification;
    deliverables?: TaskPathScope[];
    steps?: Array<Omit<Partial<TaskStep>, 'status'> & {
        title: string;
        description: string;
    }>;
}): Task;
/** Get a step from a task by step ID. */
export declare function getTaskStep(taskId: string, stepId: string): TaskStep | undefined;
/**
 * Update a task step's mutable fields.
 *
 * Enforces transition rules:
 *   - Only one step may be `in_progress` per task (unless another is already in_progress)
 *   - `completed` requires all verification results to be passed (or none exist)
 *   - `failed` and `blocked` require `failureReason`
 *   - `completed` cannot be reopened (returns error)
 */
export declare function updateTaskStep(taskId: string, stepId: string, updates: Partial<Pick<TaskStep, 'status' | 'touchedPaths' | 'verificationResults' | 'failureReason'>>): TaskStepUpdateResult;
/**
 * Returns the current active step or the next pending step.
 * Priority: in_progress > first pending.
 * blocked steps are returned (not skipped) so callers know the plan is stuck.
 */
export declare function getCurrentOrNextStep(taskId: string): TaskStep | undefined;
/**
 * Returns true if the task has any required steps that are not yet done.
 * A step is "open" if its status is pending, in_progress, failed, or blocked.
 * Tasks without steps always return false (pure TODO task).
 */
export declare function taskHasOpenRequiredSteps(task: Task): boolean;
/** Find the latest task with open required steps (for next-step auto-select). */
export declare function findLatestOpenTask(): Task | undefined;
export interface NextStepResult {
    taskId: string;
    hasNext: boolean;
    nextStep?: TaskStep;
    reason?: 'no_tasks' | 'no_open_steps' | 'blocked';
}
/**
 * Find the next executable step for a given task (or the latest open task if taskId omitted).
 *
 * Rules:
 *   - in_progress step: return it (it's already active)
 *   - first pending step: return it
 *   - blocked step as next: return it with reason='blocked'
 *   - no open steps: hasNext=false, reason='no_open_steps'
 *   - no tasks at all: hasNext=false, reason='no_tasks'
 */
export declare function findNextStep(taskId?: string): NextStepResult;
/** Get a task by ID. */
export declare function getTask(id: string): Task | undefined;
/** List all tasks. */
export declare function listTasks(): Task[];
/** Update a task's fields. Returns the updated task or undefined if not found. */
export declare function updateTask(id: string, updates: Partial<Pick<Task, 'subject' | 'description' | 'status' | 'activeForm' | 'metadata'>>): Task | undefined;
/** Add a blocking relationship: taskId blocks blockedId. */
export declare function blockTask(taskId: string, blockedId: string): boolean;
/** Delete a task. */
export declare function deleteTask(id: string): boolean;
/**
 * Stop a task: set status='cancelled' BEFORE signalling the child. This
 * ordering matters — the exit handler reads `task.status` to decide
 * whether to keep `cancelled` or transition to `completed`. If we
 * SIGTERM'd first, a fast-exiting child would race past us and the
 * handler would write `completed` over the user's stop request.
 */
export declare function stopTask(id: string): Task | undefined;
/** Reset store (for testing). SIGKILLs any survivor children. */
export declare function resetTaskStore(): void;
/**
 * Spawn the task's bash command and wire stdout/stderr/exit handlers.
 * Caller is responsible for having ALREADY classified the command with
 * `classifyBashCommand` and concluded it is safe to spawn — this fn does
 * NOT re-check risk.
 *
 * Returns immediately; the task transitions to terminal state via the
 * `exit` event. Caller can `await waitForTask(id, timeout)` if it needs
 * to block.
 */
export declare function spawnTaskCommand(taskId: string): void;
/** True iff this task currently has a live child process. */
export declare function hasRunningProcess(taskId: string): boolean;
/** Test/debug helper. */
export declare function _processCount(): number;
