"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.workerContinuationIssueSelectionSchema = exports.workerSelectionSchema = exports.workerPlanPatchSchema = exports.workerPlanSchema = exports.childIssueStepSchema = exports.workflowRefStepSchema = exports.taskStepSchema = exports.workerStartApprovalDecisionSchema = exports.workerContractSchema = exports.workerFollowupRecommendationSchema = exports.workerFollowupRecommendationItemSchema = exports.workerContinuationSchema = exports.workerStepDecisionResultSchema = exports.workerWorkflowMetadataSchema = exports.workerDecisionResultSchema = exports.WORKER_DECISION_SCHEMA_LIMITS = exports.WORKFLOW_PLANNING_TOP_LEVEL_FIELD_NAMES = exports.WORKFLOW_PLANNING_REQUIRED_PROCEED_FIELD_NAMES = exports.WORKFLOW_PLANNING_ONLY_FIELD_NAMES = exports.WORKFLOW_PLANNING_EXAMPLE_FIELDS = void 0;
exports.createWorkerFollowupRecommendationSchema = createWorkerFollowupRecommendationSchema;
exports.createWorkerPlanningDecisionFields = createWorkerPlanningDecisionFields;
// biome-ignore-all lint/nursery/noExcessiveLinesPerFile: Worker decision schema intentionally keeps the generated contract shape together.
const zod_1 = require("zod");
const types_1 = require("../workflows/types");
const constants_1 = require("./constants");
const types_2 = require("./types");
const validation_issues_1 = require("./validation-issues");
var workflow_planning_fields_1 = require("./workflow-planning-fields");
Object.defineProperty(exports, "WORKFLOW_PLANNING_EXAMPLE_FIELDS", { enumerable: true, get: function () { return workflow_planning_fields_1.WORKFLOW_PLANNING_EXAMPLE_FIELDS; } });
Object.defineProperty(exports, "WORKFLOW_PLANNING_ONLY_FIELD_NAMES", { enumerable: true, get: function () { return workflow_planning_fields_1.WORKFLOW_PLANNING_ONLY_FIELD_NAMES; } });
Object.defineProperty(exports, "WORKFLOW_PLANNING_REQUIRED_PROCEED_FIELD_NAMES", { enumerable: true, get: function () { return workflow_planning_fields_1.WORKFLOW_PLANNING_REQUIRED_PROCEED_FIELD_NAMES; } });
Object.defineProperty(exports, "WORKFLOW_PLANNING_TOP_LEVEL_FIELD_NAMES", { enumerable: true, get: function () { return workflow_planning_fields_1.WORKFLOW_PLANNING_TOP_LEVEL_FIELD_NAMES; } });
exports.WORKER_DECISION_SCHEMA_LIMITS = {
    resultSummaryCharacters: 300,
    resultItemCount: 5,
    resultItemCharacters: 240,
    resultHumanCommentCharacters: 1000,
    followupBodyCharacters: 1000,
    planningContractObjectiveCharacters: 500,
    planningContractListItemCount: 6,
    planningContractListItemCharacters: 280,
    issueTitleCharacters: 120,
    stepTitleCharacters: 120,
    stepObjectiveCharacters: 280,
    stepListItemCount: 6,
    stepListItemCharacters: 280,
    childIssueIoItemCount: 6,
    childIssueIoItemCharacters: 280,
    continuationTitleCharacters: 180,
    continuationReasonCharacters: 500,
    commitMessageCharacters: 300,
    planPatchSummaryCharacters: 300,
    planPatchReasonCharacters: 300,
    planPatchStepChangeCount: 10,
    executionGuidanceItemCount: 8,
    executionGuidanceItemCharacters: 280,
    predictedTouchedPathCount: 50,
};
function limitedString(maxCharacters, description) {
    return zod_1.z.string().max(maxCharacters).meta({
        description,
    });
}
function limitedNonEmptyString(maxCharacters, description) {
    return zod_1.z.string().min(1).max(maxCharacters).meta({
        description,
    });
}
function limitedNonEmptyTrimmedString(maxCharacters, description) {
    return zod_1.z
        .string()
        .min(1)
        .max(maxCharacters)
        .refine((value) => value.trim().length > 0, {
        message: "String must not be empty.",
    })
        .meta({
        description,
    });
}
function limitedStringList(maxItems, maxCharacters, description) {
    return zod_1.z.array(zod_1.z.string().max(maxCharacters)).max(maxItems).meta({
        description,
    });
}
function limitedNonEmptyStringList(maxItems, maxCharacters, description) {
    return zod_1.z
        .array(zod_1.z
        .string()
        .min(1)
        .max(maxCharacters)
        .refine((value) => value.trim().length > 0, {
        message: "String must not be empty.",
    }))
        .min(1)
        .max(maxItems)
        .meta({
        description,
    });
}
const workerResultFieldsShape = {
    resultSummary: limitedNonEmptyString(exports.WORKER_DECISION_SCHEMA_LIMITS.resultSummaryCharacters, "Short result summary for future worker context and human display."),
    evidence: limitedStringList(exports.WORKER_DECISION_SCHEMA_LIMITS.resultItemCount, exports.WORKER_DECISION_SCHEMA_LIMITS.resultItemCharacters, "Observable completion evidence for proceed decisions, such as command results, file or API state, tracker dependency state, child issue results, or named validation checks.").optional(),
    humanComment: limitedString(exports.WORKER_DECISION_SCHEMA_LIMITS.resultHumanCommentCharacters, "Human-facing issue comment for questions, stop reasons, or short visible notes. Optional for normal proceed. Do not use this as the completion evidence field.")
        .nullable()
        .optional(),
};
exports.workerDecisionResultSchema = zod_1.z
    .object({
    ...workerResultFieldsShape,
})
    .strict()
    .transform(types_1.buildWorkflowResultFieldsWithDefaults);
const workflowResultSchema = zod_1.z
    .object({
    outcome: zod_1.z.enum([
        constants_1.WORKER_OUTCOMES.proceed,
        constants_1.WORKER_OUTCOMES.waitHuman,
        constants_1.WORKER_OUTCOMES.fail,
    ]),
    ...workerResultFieldsShape,
})
    .strict()
    .transform(types_1.buildWorkflowResultWithDefaults);
exports.workerWorkflowMetadataSchema = zod_1.z
    .object({
    mode: zod_1.z.enum([
        types_2.WORKER_RUN_MODES.workflowPlan,
        types_2.WORKER_RUN_MODES.workflowExecute,
        types_2.WORKER_RUN_MODES.workflowSelect,
        types_2.WORKER_RUN_MODES.workflowReconcileStepBatch,
        types_2.WORKER_RUN_MODES.workflowClosing,
    ]),
    templateName: zod_1.z.string().nullable(),
})
    .strict();
exports.workerStepDecisionResultSchema = zod_1.z
    .object({
    stepId: zod_1.z.string().min(1).meta({
        description: "Workflow step ID this result applies to.",
    }),
    outcome: zod_1.z.enum([
        constants_1.WORKER_OUTCOMES.proceed,
        constants_1.WORKER_OUTCOMES.waitHuman,
        constants_1.WORKER_OUTCOMES.fail,
    ]),
    result: exports.workerDecisionResultSchema,
})
    .strict();
exports.workerContinuationSchema = zod_1.z
    .discriminatedUnion("strategy", [
    zod_1.z
        .object({
        strategy: zod_1.z.literal(types_2.WORKER_CONTINUATION_STRATEGIES.replanSameIssue),
        reason: limitedNonEmptyTrimmedString(exports.WORKER_DECISION_SCHEMA_LIMITS.continuationReasonCharacters, "Detailed reason for same-issue replanning."),
    })
        .strict(),
    zod_1.z
        .object({
        strategy: zod_1.z.literal(types_2.WORKER_CONTINUATION_STRATEGIES.spawnChildIssue),
        title: zod_1.z
            .string()
            .min(1)
            .max(exports.WORKER_DECISION_SCHEMA_LIMITS.continuationTitleCharacters)
            .refine((value) => value.trim().length > 0, {
            message: "String must not be empty.",
        })
            .meta({
            description: "Short child issue title shown to users. Do not include objective, outputs, or doneWhen details.",
        }),
        reason: limitedNonEmptyTrimmedString(exports.WORKER_DECISION_SCHEMA_LIMITS.continuationReasonCharacters, "Detailed reason for creating or reusing an unplanned child issue."),
    })
        .strict(),
])
    .meta({
    description: "Execution-time continuation. Only allowed for workflow_execute, workflow_reconcile_step_batch, or workflow_closing proceed decisions.",
});
exports.workerFollowupRecommendationItemSchema = zod_1.z
    .object({
    category: zod_1.z.enum(types_1.WORKFLOW_FOLLOWUP_RECOMMENDATION_CATEGORIES).meta({
        description: "Follow-up category: mainWork for source issue main-work continuation, maintenance for future workflow or execution environment improvement.",
    }),
    title: zod_1.z
        .string()
        .min(1)
        .max(exports.WORKER_DECISION_SCHEMA_LIMITS.continuationTitleCharacters)
        .refine((value) => value.trim().length > 0, {
        message: "String must not be empty.",
    })
        .meta({
        description: "Concise title seed for one independent post-completion follow-up issue.",
    }),
    body: zod_1.z
        .string()
        .min(1)
        .max(exports.WORKER_DECISION_SCHEMA_LIMITS.followupBodyCharacters)
        .refine((value) => value.trim().length > 0, {
        message: "String must not be empty.",
    })
        .meta({
        description: "Concise request body for one independent post-completion follow-up issue.",
    }),
    reason: limitedNonEmptyString(exports.WORKER_DECISION_SCHEMA_LIMITS.resultItemCharacters, "Short reason why this follow-up issue is useful and independent."),
    workflowTemplate: zod_1.z
        .string()
        .transform((value, context) => {
        const normalized = (0, types_1.normalizeFollowupWorkflowTemplateCandidate)(value);
        if (normalized === null) {
            (0, validation_issues_1.addWorkerZodValidationIssue)(context, {
                path: [],
                message: "workflowTemplate must be no_template or a valid follow-up workflow template path.",
            });
            return zod_1.z.NEVER;
        }
        return normalized;
    })
        .optional()
        .meta({
        description: "Optional follow-up workflow template path, or no_template. Do not use auto or auto_select.",
    }),
    proposalApproval: zod_1.z.enum(types_1.FOLLOWUP_ITEM_PROPOSAL_APPROVALS).optional().meta({
        description: "When workflow.state.followup.proposalApproval is confirm_if_needed, choose auto for clearly necessary follow-up issues and confirm for uncertain proposals.",
    }),
})
    .strict();
exports.workerFollowupRecommendationSchema = zod_1.z
    .object({
    recommended: zod_1.z.boolean().meta({
        description: "Whether one or more follow-up issues should be created after this source issue completes.",
    }),
    reason: limitedNonEmptyString(exports.WORKER_DECISION_SCHEMA_LIMITS.resultItemCharacters, "Short reason for the follow-up recommendation decision."),
    items: zod_1.z.array(exports.workerFollowupRecommendationItemSchema).meta({
        description: "Deduplicated follow-up issue requests, ordered by value and independence.",
    }),
})
    .strict()
    .superRefine((recommendation, context) => {
    if (recommendation.recommended && recommendation.items.length === 0) {
        (0, validation_issues_1.addWorkerZodValidationIssue)(context, {
            path: ["items"],
            message: "items must include at least one follow-up request when recommended is true.",
        });
    }
    if (!recommendation.recommended && recommendation.items.length > 0) {
        (0, validation_issues_1.addWorkerZodValidationIssue)(context, {
            path: ["items"],
            message: "items must be empty when recommended is false.",
        });
    }
})
    .meta({
    description: "Final completion follow-up recommendation for independent post-completion work. Use only when follow-up proposal policy is enabled for the source issue.",
});
function createWorkerFollowupRecommendationSchema(maxItems, proposalApproval = "auto") {
    return exports.workerFollowupRecommendationSchema.superRefine((recommendation, context) => {
        const itemCounts = {
            mainWork: 0,
            maintenance: 0,
        };
        for (const item of recommendation.items) {
            if (!isFollowupRecommendationItemCapped({ item, proposalApproval })) {
                continue;
            }
            itemCounts[item.category] += 1;
        }
        for (const category of types_1.WORKFLOW_FOLLOWUP_RECOMMENDATION_CATEGORIES) {
            if (itemCounts[category] > maxItems[category]) {
                (0, validation_issues_1.addWorkerZodValidationIssue)(context, {
                    path: ["items"],
                    message: `items must include at most ${String(maxItems[category])} ${category} follow-up request(s).`,
                });
            }
        }
        if (recommendation.recommended &&
            proposalApproval === "auto" &&
            maxItems.mainWork === 0 &&
            maxItems.maintenance === 0) {
            (0, validation_issues_1.addWorkerZodValidationIssue)(context, {
                path: ["items"],
                message: "recommended must be false when both follow-up category limits are 0.",
            });
        }
    });
}
function isFollowupRecommendationItemCapped(input) {
    switch (input.proposalApproval) {
        case "auto":
            return true;
        case "confirm":
            return false;
        case "confirm_if_needed":
            return input.item.proposalApproval === "auto";
    }
}
exports.workerContractSchema = zod_1.z
    .object({
    objective: limitedNonEmptyString(exports.WORKER_DECISION_SCHEMA_LIMITS.planningContractObjectiveCharacters, "Planning contract objective."),
    instructions: limitedNonEmptyStringList(exports.WORKER_DECISION_SCHEMA_LIMITS.planningContractListItemCount, exports.WORKER_DECISION_SCHEMA_LIMITS.planningContractListItemCharacters, "Optional concrete instructions for the contract.").optional(),
    doneWhen: limitedNonEmptyStringList(exports.WORKER_DECISION_SCHEMA_LIMITS.planningContractListItemCount, exports.WORKER_DECISION_SCHEMA_LIMITS.planningContractListItemCharacters, "Observable completion evidence for the contract, such as command results, file or API state, tracker dependencies, or child issue results."),
    inputs: limitedStringList(exports.WORKER_DECISION_SCHEMA_LIMITS.planningContractListItemCount, exports.WORKER_DECISION_SCHEMA_LIMITS.planningContractListItemCharacters, "Inputs or prerequisites for the contract."),
    outputs: limitedStringList(exports.WORKER_DECISION_SCHEMA_LIMITS.planningContractListItemCount, exports.WORKER_DECISION_SCHEMA_LIMITS.planningContractListItemCharacters, "Expected outputs for the contract."),
})
    .strict()
    .meta({
    description: "Workflow planning contract.",
});
exports.workerStartApprovalDecisionSchema = zod_1.z
    .object({
    required: zod_1.z.boolean().meta({
        description: "Whether explicit /alpaca start approval is required before executing this plan.",
    }),
    reason: zod_1.z.string().min(1).meta({
        description: "Specific reason for the workflow-start approval decision.",
    }),
})
    .strict()
    .meta({
    description: "Workflow-start approval decision for adaptive start modes.",
});
function createWorkerPlanningDecisionFields(options) {
    const includePlan = options?.includePlan ?? true;
    const includePlanPatch = options?.includePlanPatch ?? true;
    return {
        issueTitle: zod_1.z
            .string()
            .trim()
            .min(1)
            .max(exports.WORKER_DECISION_SCHEMA_LIMITS.issueTitleCharacters)
            .optional()
            .meta({
            description: "Short user-visible issue title for the planned work. Do not include recurring prefixes, timestamps, parent issue suffixes, or /alpaca.",
        }),
        contract: exports.workerContractSchema.optional().meta({
            description: "Workflow planning contract. Required for initial planning proceed decisions; optional changed metadata for replan and revise_plan.",
        }),
        ...(includePlan
            ? {
                plan: exports.workerPlanSchema.nullable().optional().meta({
                    description: "Initial full workflow plan. Required only when planningIntent is new_plan.",
                }),
            }
            : {}),
        ...(includePlanPatch
            ? {
                planPatch: exports.workerPlanPatchSchema.nullable().optional().meta({
                    description: "Incremental workflow plan patch. Required only when planningIntent is replan or revise_plan.",
                }),
            }
            : {}),
        executionGuidance: zod_1.z
            .array(zod_1.z
            .string()
            .min(1)
            .max(exports.WORKER_DECISION_SCHEMA_LIMITS.executionGuidanceItemCharacters))
            .max(exports.WORKER_DECISION_SCHEMA_LIMITS.executionGuidanceItemCount)
            .optional()
            .meta({
            description: "Issue-wide constraints for every execution step. Required for initial planning proceed decisions; optional changed metadata for replan and revise_plan.",
        }),
        predictedTouchedPaths: zod_1.z
            .array(zod_1.z.string())
            .max(exports.WORKER_DECISION_SCHEMA_LIMITS.predictedTouchedPathCount)
            .optional()
            .meta({
            description: "Minimum repo-tracked paths that must be edited. Required for initial planning proceed decisions; optional changed metadata for replan and revise_plan.",
        }),
        workflowStartApproval: exports.workerStartApprovalDecisionSchema.optional().meta({
            description: "Required for workflow_plan proceed decisions when workflow.startApprovalMode is conservative or aggressive; otherwise omit.",
        }),
    };
}
function createWorkerPlanStepCommonFields(descriptions) {
    return {
        id: zod_1.z.string().min(1).meta({
            description: "Stable plan step identifier.",
        }),
        title: limitedNonEmptyString(exports.WORKER_DECISION_SCHEMA_LIMITS.stepTitleCharacters, descriptions.title),
        objective: limitedNonEmptyString(exports.WORKER_DECISION_SCHEMA_LIMITS.stepObjectiveCharacters, descriptions.objective),
        instructions: limitedNonEmptyStringList(exports.WORKER_DECISION_SCHEMA_LIMITS.stepListItemCount, exports.WORKER_DECISION_SCHEMA_LIMITS.stepListItemCharacters, descriptions.instructions),
        doneWhen: limitedNonEmptyStringList(exports.WORKER_DECISION_SCHEMA_LIMITS.stepListItemCount, exports.WORKER_DECISION_SCHEMA_LIMITS.stepListItemCharacters, descriptions.doneWhen),
        humanHandoffWhen: limitedStringList(exports.WORKER_DECISION_SCHEMA_LIMITS.stepListItemCount, exports.WORKER_DECISION_SCHEMA_LIMITS.stepListItemCharacters, "Conditions that require handing off to a human."),
        dependsOnStepIds: zod_1.z.array(zod_1.z.string()).meta({
            description: descriptions.dependsOnStepIds,
        }),
        result: workflowResultSchema.nullable().optional().meta({
            description: descriptions.result,
        }),
    };
}
const taskStepCommonFields = createWorkerPlanStepCommonFields({
    title: "Responsibility-based step title.",
    objective: "Concrete objective for this step.",
    instructions: "Concrete instructions for this step.",
    doneWhen: "Observable completion evidence for this step, such as command results, file or API state, tracker dependencies, or child issue results.",
    dependsOnStepIds: "Plan step IDs that must be completed before this step can run.",
    result: "Use null for an incomplete step. Include a workflow result only if the step is already completed.",
});
exports.taskStepSchema = zod_1.z
    .object({
    id: taskStepCommonFields.id,
    kind: zod_1.z.literal("task").meta({
        description: "Use task for a normal work step that does not expand a nested workflow.",
    }),
    title: taskStepCommonFields.title,
    objective: taskStepCommonFields.objective,
    instructions: taskStepCommonFields.instructions,
    doneWhen: taskStepCommonFields.doneWhen,
    humanHandoffWhen: taskStepCommonFields.humanHandoffWhen,
    dependsOnStepIds: taskStepCommonFields.dependsOnStepIds,
    result: taskStepCommonFields.result,
})
    .strict()
    .meta({
    description: "Task step schema. Omit targetTemplateName, callSiteId, sourceTemplateName, sourceTemplateDigest, and expansionGroupId on task steps.",
});
const workflowRefStepCommonFields = createWorkerPlanStepCommonFields({
    title: "Human-facing workflow_ref step title in the configured output language.",
    objective: "Concrete objective for this nested workflow expansion.",
    instructions: "Concrete instructions for this workflow_ref step.",
    doneWhen: "Observable completion evidence for this workflow_ref step, such as command results, file or API state, tracker dependencies, or child issue results.",
    dependsOnStepIds: "Plan step IDs that must be completed before this step can run.",
    result: "Use null for an incomplete step. Include a workflow result only if the step is already completed.",
});
exports.workflowRefStepSchema = zod_1.z
    .object({
    id: workflowRefStepCommonFields.id,
    kind: zod_1.z.literal("workflow_ref").meta({
        description: "Use workflow_ref only for a direct child workflow expansion step.",
    }),
    title: workflowRefStepCommonFields.title,
    objective: workflowRefStepCommonFields.objective,
    instructions: workflowRefStepCommonFields.instructions,
    doneWhen: workflowRefStepCommonFields.doneWhen,
    humanHandoffWhen: workflowRefStepCommonFields.humanHandoffWhen,
    dependsOnStepIds: workflowRefStepCommonFields.dependsOnStepIds,
    targetTemplateName: zod_1.z.string().min(1).meta({
        description: "Direct child template name to expand.",
    }),
    callSiteId: zod_1.z.string().min(1).meta({
        description: "Control-plane-provided direct child workflow call-site ID.",
    }),
    sourceTemplateName: zod_1.z.string().min(1).meta({
        description: "Parent template name that owns this direct child workflow call site.",
    }),
    sourceTemplateDigest: zod_1.z.string().min(1).meta({
        description: "Parent template digest for this direct child workflow call site.",
    }),
    expansionGroupId: zod_1.z.string().min(1).meta({
        description: "Stable expansion group identifier for this direct child workflow call site.",
    }),
    result: workflowRefStepCommonFields.result,
})
    .strict()
    .meta({
    description: "Workflow_ref step schema.",
});
const workerChildIssueBindingHintsSchema = zod_1.z
    .object({
    milestoneRef: zod_1.z.string().min(1).optional().meta({
        description: "Optional milestone reference for the child issue.",
    }),
    projectRef: zod_1.z.string().min(1).optional().meta({
        description: "Optional project reference for the child issue.",
    }),
})
    .strict()
    .meta({
    description: "Optional binding hints for a controller child_issue plan step.",
});
const childIssueStepCommonFields = createWorkerPlanStepCommonFields({
    title: "Child issue title shown to users.",
    objective: "Concrete objective for the child issue step.",
    instructions: "Concrete instructions for the child issue.",
    doneWhen: "Observable completion evidence for the child issue, such as command results, file or API state, tracker dependencies, or child issue results.",
    dependsOnStepIds: "Plan step IDs that must be completed before this child issue can start.",
    result: "Use null for an incomplete child issue step. The control plane updates this field after child issue completion.",
});
exports.childIssueStepSchema = zod_1.z
    .object({
    id: childIssueStepCommonFields.id,
    kind: zod_1.z.literal("child_issue").meta({
        description: "Use child_issue for parent-blocking work with its own objective, outputs, completion checks, and at least one separate-tracking reason such as independent deliverable, evidence bundle, review or integration boundary, materially different responsibility area, or likely multiple AI cycles.",
    }),
    childKey: zod_1.z.string().min(1).meta({
        description: "Stable child issue key within the parent issue.",
    }),
    title: childIssueStepCommonFields.title,
    objective: childIssueStepCommonFields.objective,
    instructions: childIssueStepCommonFields.instructions,
    doneWhen: childIssueStepCommonFields.doneWhen,
    humanHandoffWhen: childIssueStepCommonFields.humanHandoffWhen,
    dependsOnStepIds: childIssueStepCommonFields.dependsOnStepIds,
    childIssueRef: zod_1.z.string().min(1).nullable().optional().meta({
        description: "Control-plane-owned child issue reference. Omit or set null during planning.",
    }),
    suggestedTemplate: zod_1.z.string().min(1).nullable().optional().meta({
        description: "Suggested workflow template for the child issue.",
    }),
    bindingHints: workerChildIssueBindingHintsSchema
        .nullable()
        .optional()
        .meta({
        description: "Optional binding hints for the child issue.",
    }),
    inputs: limitedStringList(exports.WORKER_DECISION_SCHEMA_LIMITS.childIssueIoItemCount, exports.WORKER_DECISION_SCHEMA_LIMITS.childIssueIoItemCharacters, "Inputs or prerequisites for the child issue."),
    outputs: limitedStringList(exports.WORKER_DECISION_SCHEMA_LIMITS.childIssueIoItemCount, exports.WORKER_DECISION_SCHEMA_LIMITS.childIssueIoItemCharacters, "Expected outputs for the child issue."),
    result: childIssueStepCommonFields.result,
})
    .strict()
    .meta({
    description: "Child_issue step schema. Use this for issue-target plans that delegate parent-blocking work with its own objective, outputs, completion checks, and at least one separate-tracking reason such as independent deliverable, evidence bundle, review or integration boundary, materially different responsibility area, or likely multiple AI cycles.",
});
const workerPlanStepSchema = zod_1.z.discriminatedUnion("kind", [
    exports.taskStepSchema,
    exports.workflowRefStepSchema,
    exports.childIssueStepSchema,
]);
exports.workerPlanSchema = zod_1.z
    .object({
    steps: zod_1.z.array(workerPlanStepSchema).min(1).meta({
        description: "Ordered plan steps. Each step must set kind explicitly to task, workflow_ref, or child_issue.",
    }),
})
    .strict()
    .meta({
    description: "Workflow planning output for planning runs. Use task steps for same-issue work, workflow_ref steps for direct child workflow expansion, and child_issue steps for parent-blocking work with its own objective, outputs, completion checks, and at least one separate-tracking reason such as independent deliverable, evidence bundle, review or integration boundary, materially different responsibility area, or likely multiple AI cycles.",
});
const workerAddStepChangeSchema = zod_1.z
    .object({
    action: zod_1.z.literal("add_step"),
    afterStepId: zod_1.z.string().min(1).nullable().optional().meta({
        description: "Existing step id to insert after. Omit or null to insert at the beginning.",
    }),
    replacementForStepIds: zod_1.z.array(zod_1.z.string().min(1)).optional().meta({
        description: "Existing same-plan step ids that this new step replaces for the current goal. Do not delete those old steps.",
    }),
    step: workerPlanStepSchema.meta({
        description: "New incomplete workflow step to add.",
    }),
    reason: limitedNonEmptyString(exports.WORKER_DECISION_SCHEMA_LIMITS.planPatchReasonCharacters, "Why this step is being added."),
})
    .strict();
const workerUpdateStepChangeSchema = zod_1.z
    .object({
    action: zod_1.z.literal("update_step"),
    stepId: zod_1.z.string().min(1).meta({
        description: "Existing incomplete step id to update.",
    }),
    step: workerPlanStepSchema.meta({
        description: "Replacement definition for the existing incomplete step.",
    }),
    reason: limitedNonEmptyString(exports.WORKER_DECISION_SCHEMA_LIMITS.planPatchReasonCharacters, "Why this step is being updated."),
})
    .strict();
const workerRemoveStepChangeSchema = zod_1.z
    .object({
    action: zod_1.z.literal("remove_step"),
    stepId: zod_1.z.string().min(1).meta({
        description: "Existing step id to remove only when it has no completed evidence or durable side effects.",
    }),
    reason: limitedNonEmptyString(exports.WORKER_DECISION_SCHEMA_LIMITS.planPatchReasonCharacters, "Why this step is being removed."),
})
    .strict();
const workerMoveStepChangeSchema = zod_1.z
    .object({
    action: zod_1.z.literal("move_step"),
    stepId: zod_1.z.string().min(1).meta({
        description: "Existing incomplete task or unmaterialized child_issue step id to move without changing its contents or dependencies.",
    }),
    afterStepId: zod_1.z.string().min(1).nullable().optional().meta({
        description: "Existing step id to move after. Omit or null to move to the beginning.",
    }),
    reason: limitedNonEmptyString(exports.WORKER_DECISION_SCHEMA_LIMITS.planPatchReasonCharacters, "Why this step is being moved."),
})
    .strict();
exports.workerPlanPatchSchema = zod_1.z
    .object({
    basePlanRevision: zod_1.z.number().int().safe().nonnegative().meta({
        description: "Exact current workflow.state.planRevision this patch was generated from. Do not use workflow state version.",
    }),
    intent: zod_1.z.enum(["replan", "revise_plan"]).meta({
        description: "Planning intent for this incremental patch.",
    }),
    summary: limitedNonEmptyString(exports.WORKER_DECISION_SCHEMA_LIMITS.planPatchSummaryCharacters, "Short human-facing summary of what the patch changes."),
    scope: zod_1.z
        .object({
        issueRef: zod_1.z.string().min(1).meta({
            description: "Issue display reference this patch applies to.",
        }),
    })
        .strict(),
    stepChanges: zod_1.z
        .array(zod_1.z.discriminatedUnion("action", [
        workerAddStepChangeSchema,
        workerUpdateStepChangeSchema,
        workerRemoveStepChangeSchema,
        workerMoveStepChangeSchema,
    ]))
        .max(exports.WORKER_DECISION_SCHEMA_LIMITS.planPatchStepChangeCount)
        .meta({
        description: "Real step changes only. Omit unchanged steps instead of preserving them.",
    }),
    childIssueDecisions: zod_1.z
        .array(zod_1.z
        .object({
        childKey: zod_1.z.string().min(1),
        childIssueRef: zod_1.z.string().min(1).nullable().optional(),
        action: zod_1.z.enum([
            "queue_child_issue_replan",
            "detach_child_issue",
            "cancel_child_issue",
        ]),
        reason: limitedNonEmptyString(exports.WORKER_DECISION_SCHEMA_LIMITS.planPatchReasonCharacters, "Why this child issue decision is being made."),
    })
        .strict())
        .meta({
        description: "Explicit decisions for materialized child issues whose parent relationship or contract changed.",
    }),
    workflowRefChanges: zod_1.z
        .array(zod_1.z
        .object({
        callSiteId: zod_1.z.string().min(1),
        expansionGroupId: zod_1.z.string().min(1),
        originSubtreeKey: zod_1.z.string().min(1).optional(),
        action: zod_1.z.enum(["refresh_workflow_ref", "remove_workflow_ref"]),
        reason: limitedNonEmptyString(exports.WORKER_DECISION_SCHEMA_LIMITS.planPatchReasonCharacters, "Why this workflow_ref change is being made."),
    })
        .strict())
        .meta({
        description: "Explicit refresh/remove decisions for workflow_ref call sites or expanded subtrees.",
    }),
})
    .strict()
    .meta({
    description: "Incremental workflow planning output for replan and revise_plan runs.",
});
exports.workerSelectionSchema = zod_1.z
    .discriminatedUnion("action", [
    zod_1.z
        .object({
        action: zod_1.z.literal(types_2.WORKER_WORKFLOW_SELECTION_ACTIONS.useTemplate),
        templateName: zod_1.z.string().min(1).meta({
            description: "Selected workflow template name.",
        }),
    })
        .strict(),
    zod_1.z
        .object({
        action: zod_1.z.literal(types_2.WORKER_WORKFLOW_SELECTION_ACTIONS.noTemplate),
    })
        .strict(),
    zod_1.z
        .object({
        action: zod_1.z.literal(types_2.WORKER_WORKFLOW_SELECTION_ACTIONS.requestTemplate),
    })
        .strict(),
])
    .meta({
    description: "Workflow selection output for selection runs. Choose a repository-specific template, choose the built-in default workflow, or request a missing workflow template before planning begins only when the template slot is auto.",
});
exports.workerContinuationIssueSelectionSchema = zod_1.z
    .object({
    action: zod_1.z.enum([
        types_2.WORKER_CONTINUATION_ISSUE_ACTIONS.reuseExistingIssue,
        types_2.WORKER_CONTINUATION_ISSUE_ACTIONS.createNewChildIssue,
    ]),
    targetIssueId: zod_1.z.string().min(1).optional(),
})
    .strict()
    .superRefine((decision, context) => {
    if (decision.action ===
        types_2.WORKER_CONTINUATION_ISSUE_ACTIONS.reuseExistingIssue &&
        decision.targetIssueId === undefined) {
        (0, validation_issues_1.addWorkerZodValidationIssue)(context, {
            path: ["targetIssueId"],
            message: "targetIssueId is required when action is reuse_existing_issue.",
        });
    }
    if (decision.action !==
        types_2.WORKER_CONTINUATION_ISSUE_ACTIONS.reuseExistingIssue &&
        decision.targetIssueId !== undefined) {
        (0, validation_issues_1.addWorkerZodValidationIssue)(context, {
            path: ["targetIssueId"],
            message: "targetIssueId is only allowed when action is reuse_existing_issue.",
        });
    }
});
