/**
 * V2 WorkItem Type Definitions
 *
 * A WorkItem is the unified execution primitive. Every action the system
 * takes to fulfill a Request or advance a Mission materializes as a WorkItem.
 * This replaces v1's separate delegation, scheduled-message, and event-subscription concepts.
 *
 * @module types/v2/work-item.types
 */
/**
 * Execution type — determines handler and behavior.
 */
export type WorkItemType = 'delegate' | 'project_task' | 'check' | 'notify' | 'cron_run' | 'review' | 'confirm' | 'reconcile';
/** All valid WorkItemType values. */
export declare const WORK_ITEM_TYPES: readonly WorkItemType[];
/**
 * Who is responsible for execution.
 */
export type WorkItemOwner = 'orchestrator' | 'team_lead' | 'agent' | 'system';
/** All valid WorkItemOwner values. */
export declare const WORK_ITEM_OWNERS: readonly WorkItemOwner[];
/**
 * Lifecycle statuses for a WorkItem.
 *
 * State machine (extended with acceptance/verification flow):
 *
 *   --- Creation & Scheduling ---
 *   queued → running          (executor picks up item — simple tasks)
 *   queued → proposed         (TL sends task contract to worker)
 *   queued → scheduled        (has future scheduledAt)
 *   queued → cancelled        (parent cancelled)
 *   scheduled → queued        (scheduledAt reached, trigger fires)
 *
 *   --- Acceptance Handshake ---
 *   proposed → accepted       (worker confirms understanding)
 *   proposed → rejected       (worker cannot accept — wrong fit, unclear, etc.)
 *   proposed → cancelled      (parent cancelled before acceptance)
 *   accepted → running        (worker begins execution)
 *   rejected → queued         (TL reassigns or re-scopes)
 *
 *   --- Execution ---
 *   running → done_by_worker  (worker reports completion, pending TL verification)
 *   running → failed          (execution failed, retries exhausted)
 *   running → blocked         (waiting on dependency)
 *   running → escalated       (worker escalates — scope/risk/ambiguity)
 *   running → cancelled       (parent cancelled during execution)
 *
 *   --- Verification ---
 *   done_by_worker → verified (TL verifies and accepts)
 *   done_by_worker → rejected (TL rejects — needs rework)
 *   rejected → queued         (re-queue for retry/reassignment)
 *   escalated → queued        (TL/human resolves and re-queues)
 *   escalated → cancelled     (escalation results in cancellation)
 *
 *   --- Recovery ---
 *   blocked → queued          (dependency resolved, re-queue)
 *   failed → queued           (manual retry or reconciler recovery)
 *
 *   --- Legacy Compatibility ---
 *   running → done            (simple tasks without TL verification)
 *   done is terminal (backward compatible with existing pool operations)
 */
export type WorkItemStatus = 'queued' | 'scheduled' | 'proposed' | 'accepted' | 'running' | 'blocked' | 'escalated' | 'done_by_worker' | 'verified' | 'rejected' | 'done' | 'failed' | 'cancelled';
/** All valid WorkItemStatus values. */
export declare const WORK_ITEM_STATUSES: readonly WorkItemStatus[];
/** Terminal statuses — no further transitions allowed. */
export declare const TERMINAL_WORK_ITEM_STATUSES: ReadonlySet<WorkItemStatus>;
/**
 * Broader "exited the active queue" status set used by SLA-style consumers
 * (e.g. `RequestSlaSubscriber`, `MissionReminderService`) that need to
 * treat `failed` and `rejected` as terminal for *their* purposes — even
 * though those statuses are NOT terminal in the strict state-machine sense
 * (they can transition back to `queued` via the retry path).
 *
 * Hoisted to close the canonical-set duplication anti-pattern called out
 * by Arch on PR #357 (INBOUND-1) N2. Previously each SLA caller redeclared
 * a 5-element local set; this single source of truth keeps them aligned
 * if a new "exit-the-queue" status is added in the future.
 *
 * Members:
 * - `done` / `verified` / `cancelled` — strictly terminal (cannot transition).
 * - `failed` / `rejected` — semantically "exited active queue" for SLA timer
 *   no-op + reentrancy-lock release purposes, even though the state machine
 *   permits `rejected → queued` (retry) and `failed` is not formally terminal.
 *
 * Use this set when answering "should the SLA timer / reentrancy lock
 * release based on the current WI state?", and use {@link TERMINAL_WORK_ITEM_STATUSES}
 * when answering "is the state machine done with this WI?".
 */
export declare const SLA_TERMINAL_WORK_ITEM_STATUSES: ReadonlySet<WorkItemStatus>;
/**
 * A single unit of system execution.
 *
 * WorkItems are the internal execution primitive — users rarely see them directly.
 * They unify what v1 had as separate concepts: delegations, scheduled messages,
 * event subscriptions, cron runs, and checks.
 */
export interface WorkItem {
    /** UUID v4 */
    id: string;
    /** Parent Request (undefined for Mission-generated items) */
    requestId?: string;
    /** Parent WorkItem for sub-tasks / retries */
    parentWorkItemId?: string;
    /** Execution type — determines handler and behavior */
    type: WorkItemType;
    /** Who is responsible for execution */
    owner: WorkItemOwner;
    /** Target agent session, team, or system component */
    target?: string;
    /** Human-readable title */
    title: string;
    /** Short summary / instructions (legacy; capped at 500 chars by callers) */
    description?: string;
    /**
     * Long-form task brief in markdown. Replaces the legacy
     * `.crewly/tasks/delegated/*.md` body that v1 task-management used to
     * write to disk. Carries the full instruction set the worker reads
     * before starting. Length is capped to {@link MAX_BRIEF_MARKDOWN_BYTES}
     * by {@link validateCreateWorkItemInput} to keep `pool.json` readable
     * and within `atomicWriteJson`'s practical size budget.
     */
    briefMarkdown?: string;
    /** Lifecycle status */
    status: WorkItemStatus;
    /**
     * Worker-supplied structured output produced during execution.
     *
     * Used for the v1→V3 deprecation handoff: previously workers wrote
     * `<taskId>.output.json` files alongside the `.md` task body and the TL
     * `verify-output` skill read them. With v1 retired, this output now lives
     * on the WorkItem itself and is read via `GET /api/task-pool/items/:id`.
     *
     * Shape is intentionally `Record<string, unknown>` — the schema is
     * task-specific (an audit run, a code-gen artifact, etc.).
     */
    output?: Record<string, unknown>;
    /** When this item should execute (null = immediately) */
    scheduledAt?: string;
    /** ISO8601 timestamps */
    createdAt: string;
    startedAt?: string;
    completedAt?: string;
    /** Execution result data */
    result?: Record<string, unknown>;
    /** Error details if failed */
    error?: string;
    /**
     * Human-readable reason recorded when the item transitions to
     * `cancelled`. Surfaces in the work-item activity timeline so the
     * cancellation isn't an opaque event ("WorkItem was cancelled.").
     * Sources include: reconciler stale-pickup detection, mission
     * cascade, parent-cancel ripple, manual user cancel, etc.
     */
    cancelReason?: string;
    /**
     * Human-readable reason recorded when the item transitions to
     * `blocked` (or is created already in `blocked` because of unmet
     * dependencies). Surfaces in the work-item activity timeline so the
     * user understands WHY a WI is stuck — "Waiting on Plan WI to
     * complete" reads very differently from "Agent inactive — system
     * paused this item" reads very differently from "Worker explicitly
     * blocked with reason X". (Steve 2026-05-15 dogfood: UI showed
     * `Blocked` badge with no timeline event explaining why.)
     *
     * Sources: RequestDecomposeSubscriber (dependency-blocked at
     * create time), ReconcilerDataProvider (agent-inactive correction),
     * TaskPoolService.blockItem (explicit worker block).
     */
    blockedReason?: string;
    /** Number of retry attempts so far */
    retryCount: number;
    /** Maximum retries before permanent failure */
    maxRetries: number;
    /** Trigger ID that created or will wake this WorkItem */
    triggerId?: string;
    /** Link to ProjectTask (for durable project work) */
    projectTaskId?: string;
    /** Link to Mission (for autonomy-generated work) */
    missionId?: string;
    /** Token usage for this specific WorkItem */
    inputTokens: number;
    outputTokens: number;
    /** Cost in USD for this WorkItem */
    cost: number;
    /** Extensible metadata (dependency tracking, skill requirements, etc.) */
    metadata?: Record<string, unknown>;
    /**
     * IDs of upstream WorkItems that must reach terminal success (`done` or
     * `verified`) before this item is allowed to run. When any dep is still
     * pending at creation time, the item starts in `blocked` status and is
     * auto-promoted to `queued` by the TaskPool resolver once every dep
     * completes.
     */
    dependsOn?: string[];
}
/**
 * Input for creating a new WorkItem.
 */
export interface CreateWorkItemInput {
    /**
     * Optional deterministic id. When omitted a random uuid is generated. Supply
     * a stable id when the WorkItem represents an idempotent occurrence (e.g. a
     * cron fire keyed to its slot) so re-creating the same occurrence is a no-op
     * via the pool's `(id)` dedup instead of a duplicate.
     */
    id?: string;
    requestId?: string;
    parentWorkItemId?: string;
    type: WorkItemType;
    owner: WorkItemOwner;
    target?: string;
    title: string;
    description?: string;
    /**
     * Long-form task brief in markdown. See {@link WorkItem.briefMarkdown}
     * for rationale. Validated against {@link MAX_BRIEF_MARKDOWN_BYTES}.
     */
    briefMarkdown?: string;
    scheduledAt?: string;
    maxRetries?: number;
    triggerId?: string;
    projectTaskId?: string;
    missionId?: string;
    metadata?: Record<string, unknown>;
    /** Upstream WorkItem IDs that must reach terminal success before this runs. */
    dependsOn?: string[];
}
/**
 * Input for updating an existing WorkItem.
 */
export interface UpdateWorkItemInput {
    status?: WorkItemStatus;
    target?: string;
    result?: Record<string, unknown>;
    /** Worker-supplied structured output — see {@link WorkItem.output}. */
    output?: Record<string, unknown>;
    error?: string;
    inputTokens?: number;
    outputTokens?: number;
    cost?: number;
}
/**
 * Map of valid status transitions for WorkItems.
 *
 * Includes both the original simple flow (queued→running→done) and
 * the extended acceptance/verification flow (proposed→accepted→running→done_by_worker→verified).
 */
export declare const WORK_ITEM_TRANSITIONS: Record<WorkItemStatus, ReadonlySet<WorkItemStatus>>;
/**
 * Defines which roles are allowed to trigger specific status transitions.
 *
 * Format: `from→to` key maps to a set of allowed WorkItemOwner roles.
 * If a transition is not listed here, any role may trigger it (backward compatible).
 * The 'system' role (reconciler) can always trigger any valid transition.
 */
export declare const TRANSITION_PERMISSIONS: Record<string, ReadonlySet<WorkItemOwner>>;
/**
 * Checks whether a role is permitted to trigger a specific status transition.
 *
 * If no explicit permission is defined for a transition, it is considered
 * open to all roles (backward compatible). The 'system' role always has
 * permission for any valid transition.
 *
 * @param from - Current status
 * @param to - Desired next status
 * @param actorRole - Role of the agent/system attempting the transition
 * @returns True if the role is permitted to trigger this transition
 */
export declare function isTransitionPermitted(from: WorkItemStatus, to: WorkItemStatus, actorRole: WorkItemOwner): boolean;
/**
 * Checks whether a string is a valid WorkItemType.
 *
 * @param value - The string to check
 * @returns True if value is a valid WorkItemType
 */
export declare function isValidWorkItemType(value: string): value is WorkItemType;
/**
 * Checks whether a string is a valid WorkItemStatus.
 *
 * @param value - The string to check
 * @returns True if value is a valid WorkItemStatus
 */
export declare function isValidWorkItemStatus(value: string): value is WorkItemStatus;
/**
 * Checks whether a string is a valid WorkItemOwner.
 *
 * @param value - The string to check
 * @returns True if value is a valid WorkItemOwner
 */
export declare function isValidWorkItemOwner(value: string): value is WorkItemOwner;
/**
 * Checks whether a WorkItem status transition is valid.
 *
 * @param from - Current status
 * @param to - Desired next status
 * @returns True if transition is allowed
 */
export declare function isValidWorkItemTransition(from: WorkItemStatus, to: WorkItemStatus): boolean;
/**
 * Validates that an unknown value is structurally a valid WorkItem.
 *
 * @param value - Unknown value to validate
 * @returns True if value conforms to the WorkItem interface
 */
export declare function isWorkItem(value: unknown): value is WorkItem;
/**
 * Validates CreateWorkItemInput and returns an array of error messages.
 *
 * @param input - The creation input to validate
 * @returns Array of validation error strings (empty = valid)
 */
export declare function validateCreateWorkItemInput(input: CreateWorkItemInput): string[];
/**
 * Maximum size of {@link WorkItem.briefMarkdown} in UTF-8 bytes.
 *
 * Replaces the legacy `.crewly/tasks/delegated/*.md` files which had no
 * size cap. 16 KB is enough to carry a typical TL-to-worker dispatch
 * brief (~ 3000 words) plus a small spec excerpt; longer briefs should
 * reference an attached file via `metadata` rather than inlining the
 * full body so `pool.json` stays human-readable and `atomicWriteJson`
 * stays fast.
 */
export declare const MAX_BRIEF_MARKDOWN_BYTES: number;
/** Default max retries for WorkItems. */
export declare const DEFAULT_MAX_RETRIES = 3;
/**
 * Creates a new WorkItem with sensible defaults.
 *
 * @param input - Required and optional creation fields
 * @returns A fully populated WorkItem object
 *
 * @example
 * ```typescript
 * const workItem = createWorkItem({
 *   type: 'delegate',
 *   owner: 'agent',
 *   target: 'crewly-product-leo-member-n',
 *   title: 'Implement TaskPoolService',
 * });
 * ```
 */
export declare function createWorkItem(input: CreateWorkItemInput): WorkItem;
/**
 * Structured contract that a Team Lead sends when delegating a task.
 *
 * The worker must confirm understanding before execution begins.
 * This prevents misaligned expectations and reduces costly late-stage rework.
 */
export interface TaskContract {
    /** What the worker must achieve */
    goal: string;
    /** What is explicitly out of scope */
    nonGoals: string[];
    /** Specific, verifiable conditions for "done" */
    acceptanceCriteria: string[];
    /** Expected deliverable structure */
    outputFormat: string;
    /** When to stop and report back (time, complexity, risk thresholds) */
    cutoffConditions: string[];
    /** Situations that require immediate escalation */
    escalationTriggers: string[];
    /** If true, worker may skip classification gate and proceed directly */
    preClassified?: boolean;
}
/**
 * Worker's structured confirmation of a received Task Contract.
 *
 * TL reviews this before allowing the task to enter 'running' status.
 */
export interface TaskAcceptance {
    /** Worker's understanding of the goal */
    understoodGoal: string;
    /** How the worker intends to accomplish it */
    plannedApproach: string;
    /** What the worker will NOT do */
    outOfScope: string[];
    /** Risks or blockers the worker foresees */
    identifiedRisks: string[];
}
/** Target for an alignment request. */
export type AlignmentTarget = 'team_lead' | 'human';
/**
 * Reason categories for why a worker cannot proceed with direct execution.
 */
export type AlignmentReason = 'scope_change' | 'priority_resource' | 'ownership_authority' | 'ambiguity_tradeoff' | 'high_risk';
/**
 * A structured escalation from a worker who determines that direct execution
 * is inappropriate for the current task.
 *
 * This replaces unstructured "I'm blocked" messages with actionable information
 * that enables fast decision-making by TLs or humans.
 */
export interface AlignmentRequest {
    /** The task the worker was asked to do */
    currentTask: string;
    /** What triggered the escalation */
    discoveredIssue: string;
    /** Category of alignment needed */
    reason: AlignmentReason;
    /** Why direct execution is inappropriate */
    whyCannotExecute: string;
    /** 2-3 possible approaches with impact analysis */
    options: AlignmentOption[];
    /** Worker's recommended path */
    recommendation: string;
    /** What the TL/human needs to decide */
    decisionNeeded: string;
    /** Who should make this decision */
    target: AlignmentTarget;
}
/**
 * A single option in an Alignment Request.
 */
export interface AlignmentOption {
    /** Brief description of the approach */
    description: string;
    /** Expected positive outcomes */
    pros: string[];
    /** Expected negative outcomes or risks */
    cons: string[];
    /** Estimated effort/impact level */
    impact: 'low' | 'medium' | 'high';
}
//# sourceMappingURL=work-item.types.d.ts.map