"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildWorkerPullRequestReviewNecessityPrompt = exports.buildWorkerWorkflowPlanReviewPrompt = exports.buildWorkerWorkflowTemplateFitReviewPrompt = exports.buildWorkerTemplateUpdatePrompt = exports.buildWorkerTemplateDraftPrompt = exports.buildWorkerEventHookDraftPrompt = void 0;
exports.buildWorkerPrompt = buildWorkerPrompt;
exports.buildWorkerContinuationIssuePrompt = buildWorkerContinuationIssuePrompt;
exports.buildWorkerEventHookPrompt = buildWorkerEventHookPrompt;
exports.buildWorkerIssueDraftPrompt = buildWorkerIssueDraftPrompt;
exports.buildWorkerAiWorkflowOptionAutofillPrompt = buildWorkerAiWorkflowOptionAutofillPrompt;
exports.buildWorkerFollowupProposalReviewPrompt = buildWorkerFollowupProposalReviewPrompt;
// biome-ignore lint/nursery/noExcessiveLinesPerFile: Worker prompt rendering stays grouped so comment summarization remains auditable.
const canonical_workflow_state_1 = require("../comments/canonical-workflow-state");
const managed_comments_1 = require("../comments/managed-comments");
const workflow_update_1 = require("../comments/workflow-update");
const branding_1 = require("../core/branding");
const base_title_1 = require("../issues/base-title");
const render_1 = require("../system-prompts/render");
const comment_command_1 = require("../workflows/comment-command");
const ai_workflow_option_autofill_contract_1 = require("./ai-workflow-option-autofill-contract");
const decision_contract_1 = require("./decision-contract");
const dedicated_prompt_support_1 = require("./dedicated-prompt-support");
const event_hook_contract_1 = require("./event-hook-contract");
const followup_proposal_review_contract_1 = require("./followup-proposal-review-contract");
const issue_draft_contract_1 = require("./issue-draft-contract");
const prompt_contract_section_1 = require("./prompt-contract-section");
const prompt_repair_1 = require("./prompt-repair");
const prompt_required_skills_1 = require("./prompt-required-skills");
const prompt_selection_context_1 = require("./prompt-selection-context");
const prompt_text_1 = require("./prompt-text");
const system_prompt_names_1 = require("./system-prompt-names");
const types_1 = require("./types");
const workflow_instructions_prompt_1 = require("./workflow-instructions-prompt");
const workflow_option_template_prompt_1 = require("./workflow-option-template-prompt");
const workflow_state_prompt_1 = require("./workflow-state-prompt");
var event_hook_draft_prompt_1 = require("./event-hook-draft-prompt");
Object.defineProperty(exports, "buildWorkerEventHookDraftPrompt", { enumerable: true, get: function () { return event_hook_draft_prompt_1.buildWorkerEventHookDraftPrompt; } });
var template_draft_prompt_1 = require("./template-draft-prompt");
Object.defineProperty(exports, "buildWorkerTemplateDraftPrompt", { enumerable: true, get: function () { return template_draft_prompt_1.buildWorkerTemplateDraftPrompt; } });
var template_update_prompt_1 = require("./template-update-prompt");
Object.defineProperty(exports, "buildWorkerTemplateUpdatePrompt", { enumerable: true, get: function () { return template_update_prompt_1.buildWorkerTemplateUpdatePrompt; } });
var workflow_template_fit_review_prompt_1 = require("./workflow-template-fit-review-prompt");
Object.defineProperty(exports, "buildWorkerWorkflowTemplateFitReviewPrompt", { enumerable: true, get: function () { return workflow_template_fit_review_prompt_1.buildWorkerWorkflowTemplateFitReviewPrompt; } });
var workflow_plan_review_prompt_1 = require("./workflow-plan-review-prompt");
Object.defineProperty(exports, "buildWorkerWorkflowPlanReviewPrompt", { enumerable: true, get: function () { return workflow_plan_review_prompt_1.buildWorkerWorkflowPlanReviewPrompt; } });
var pull_request_review_necessity_prompt_1 = require("./pull-request-review-necessity-prompt");
Object.defineProperty(exports, "buildWorkerPullRequestReviewNecessityPrompt", { enumerable: true, get: function () { return pull_request_review_necessity_prompt_1.buildWorkerPullRequestReviewNecessityPrompt; } });
function buildWorkerPrompt(workerName, input) {
    const promptAssignee = resolvePromptAssignee(input.issue);
    const decisionContract = (0, decision_contract_1.buildWorkerDecisionContract)(input.workflow, input.responseLanguage);
    const responseLanguageInstruction = (0, prompt_text_1.buildResponseLanguageInstruction)(input.responseLanguage);
    const promptSections = [];
    promptSections.push(...renderSection(prompt_text_1.PROMPT_TEXT.sectionAuthoritativeInstructions, renderAuthoritativeInstructionLines(workerName, responseLanguageInstruction, input.workflow, input.systemPrompts)), ...(input.repairContext
        ? renderSection(prompt_text_1.PROMPT_TEXT.sectionRepairAttempt, (0, prompt_repair_1.renderRepairSectionLines)(input.repairContext, decisionContract))
        : []), ...renderSection(prompt_text_1.PROMPT_TEXT.sectionLatestHumanInstruction, renderLatestHumanInstructionLines(input.comments, promptAssignee)), ...renderSection(prompt_text_1.PROMPT_TEXT.sectionBaselineIssueBrief, renderBaselineIssueBrief({
        issue: input.issue,
        linkedIssue: input.linkedIssue ?? null,
        assignee: promptAssignee,
    })), ...renderSection(prompt_text_1.PROMPT_TEXT.sectionHistoricalHumanContext, renderHistoricalHumanContextLines(input.comments, promptAssignee)), ...renderSection(prompt_text_1.PROMPT_TEXT.sectionSystemReferenceOnly, renderSystemReferenceOnlyLines(input.comments)), ...(input.continuationContext
        ? renderSection(prompt_text_1.PROMPT_TEXT.sectionPreviousAttempt, renderContinuationSection(input.continuationContext))
        : []), ...renderSection(prompt_text_1.PROMPT_TEXT.sectionWorkflowContext, renderWorkflowSection(input.workflow, input.systemPrompts)), ...renderSection(prompt_text_1.PROMPT_TEXT.sectionDecisionContract, renderDecisionContract(decisionContract)));
    return promptSections.join("\n");
}
function buildWorkerContinuationIssuePrompt(workerName, input, systemPrompts) {
    const contract = (0, decision_contract_1.buildWorkerContinuationIssueContract)();
    return (0, dedicated_prompt_support_1.renderDedicatedPromptEnvelope)({
        preambleLines: (0, dedicated_prompt_support_1.renderDedicatedPromptHeader)({
            workerName,
            runDescription: "This is a dedicated continuation issue selection run.",
            instructionLines: [
                prompt_text_1.PROMPT_TEXT.introInstructions,
                "Decide only whether to reuse an existing issue as the blocker or create a new child issue.",
                "Choose reuse_existing_issue only when an existing open issue already matches the blocker and can naturally serve as the parent's blocker issue.",
                "Choose create_new_child_issue when no listed open issue is a natural match for the blocker.",
            ],
            systemPrompts,
            systemPromptNames: system_prompt_names_1.WORKER_COMMON_SYSTEM_PROMPT_NAMES,
        }),
        inputLines: [
            "Continuation issue selection input:",
            `- Origin issue ID: ${input.originIssue.id}`,
            `- Origin display ID: ${input.originIssue.displayId}`,
            `- Origin title: ${input.originIssue.title}`,
            `- Origin URL: ${input.originIssue.url}`,
            "- Origin body:",
            "```text",
            input.originIssue.body || prompt_text_1.PROMPT_TEXT.empty,
            "```",
            `- Continuation title: ${renderPromptText(input.continuation.title)}`,
            `- Continuation reason: ${renderPromptText(input.continuation.reason)}`,
            "- Open issues:",
            ...(input.openIssues.length > 0
                ? input.openIssues.map((issue) => [
                    `  - ${issue.displayId} (${issue.id}) [${issue.status}] ${issue.title}`,
                    `    URL: ${issue.url}`,
                    `    Body: ${renderPromptText(issue.body)}`,
                ].join("\n"))
                : [`  ${prompt_text_1.PROMPT_TEXT.none}`]),
        ],
        contract: {
            heading: prompt_text_1.PROMPT_TEXT.sectionDecisionContract,
            rules: contract.rules,
            example: contract.example,
        },
    });
}
function buildWorkerEventHookPrompt(workerName, input) {
    const contract = (0, event_hook_contract_1.buildWorkerEventHookContract)(input.outputLanguage);
    return (0, dedicated_prompt_support_1.renderDedicatedPromptEnvelope)({
        preambleLines: (0, dedicated_prompt_support_1.renderDedicatedPromptHeader)({
            workerName,
            runDescription: "This is a dedicated event hook run.",
            instructionLines: [
                prompt_text_1.PROMPT_TEXT.introInstructions,
                "Follow the hook Markdown instructions for this one event only.",
                "You may perform the requested notification or webhook side effect, but do not modify tracker labels, close issues, publish comments, or change workflow state.",
                "If the hook Markdown does not require any action for this event, return skipped.",
                (0, prompt_text_1.buildEventHookLanguageInstruction)(input.outputLanguage),
            ],
            systemPrompts: input.systemPrompts,
            systemPromptNames: system_prompt_names_1.WORKER_COMMON_SYSTEM_PROMPT_NAMES,
        }),
        inputLines: [
            "Event hook Markdown:",
            "```md",
            input.hookMarkdown || prompt_text_1.PROMPT_TEXT.empty,
            "```",
            "Event JSON:",
            "```json",
            JSON.stringify(input.event, null, 2),
            "```",
            ...(0, dedicated_prompt_support_1.renderDedicatedWorkspaceFields)({
                repositoryRoot: input.repositoryRoot,
                workspacePath: input.workspacePath,
                outputLanguage: input.outputLanguage,
            }),
        ],
        contract: {
            heading: prompt_text_1.PROMPT_TEXT.sectionDecisionContract,
            rules: contract.rules,
            promptSchema: contract.promptSchema,
            example: contract.example,
        },
    });
}
function buildWorkerIssueDraftPrompt(workerName, input, repairContext) {
    const contract = (0, issue_draft_contract_1.buildWorkerIssueDraftContract)(input);
    const templateLabel = input.templateKind === "pull_request" ? "pull request" : "issue";
    return (0, dedicated_prompt_support_1.renderDedicatedPromptEnvelope)({
        preambleLines: (0, dedicated_prompt_support_1.renderDedicatedPromptHeader)({
            workerName,
            runDescription: input.templateKind === "pull_request"
                ? "This is a dedicated pull request body draft run."
                : "This is a dedicated issue draft run.",
            instructionLines: [
                prompt_text_1.PROMPT_TEXT.introInstructions,
                input.templateKind === "pull_request"
                    ? "Draft only title, body, and selectedIssueTemplatePath. Do not create the pull request."
                    : "Draft only title, body, and selectedIssueTemplatePath. Do not create the issue.",
                (0, prompt_text_1.buildIssueDraftLanguageInstruction)(input.outputLanguage),
            ],
            systemPrompts: input.systemPrompts,
            systemPromptNames: system_prompt_names_1.ISSUE_DRAFT_SYSTEM_PROMPT_NAMES,
        }),
        repairLines: repairContext
            ? (0, prompt_repair_1.renderIssueDraftRepairSectionLines)(repairContext)
            : undefined,
        inputLines: [
            ...(0, dedicated_prompt_support_1.renderDedicatedPromptInputLines)({
                heading: input.templateKind === "pull_request"
                    ? "Pull request body draft input:"
                    : "Issue draft input:",
                prompt: input.prompt,
                workspace: input,
            }),
            `- Accepted at: ${input.acceptedAt}`,
            `- Display time zone: ${input.displayTimeZone}`,
            `- Available ${templateLabel} templates:`,
            ...renderIssueDraftIssueTemplateCandidates(input.availableIssueTemplates ?? []),
        ],
        contract: {
            heading: prompt_text_1.PROMPT_TEXT.sectionIssueDraftContract,
            rules: contract.rules,
            promptSchema: contract.promptSchema,
            example: contract.example,
        },
    });
}
function buildWorkerAiWorkflowOptionAutofillPrompt(workerName, input, repairContext) {
    const contract = (0, ai_workflow_option_autofill_contract_1.buildWorkerAiWorkflowOptionAutofillContract)(input);
    return (0, dedicated_prompt_support_1.renderDedicatedPromptEnvelope)({
        preambleLines: (0, dedicated_prompt_support_1.renderDedicatedPromptHeader)({
            workerName,
            runDescription: "This is a dedicated AI workflow option autofill run.",
            instructionLines: [
                prompt_text_1.PROMPT_TEXT.introInstructions,
                "Autofill only workflow metadata from the provided work item text. Do not draft title, body, selectedIssueTemplatePath, issue templates, or workflow templates.",
                "Return only workflow options that should be applied to the canonical workflow state.",
                "Return workflow null when the prompt does not request workflow options.",
            ],
            systemPrompts: input.systemPrompts,
            systemPromptNames: system_prompt_names_1.WORKER_COMMON_SYSTEM_PROMPT_NAMES,
        }),
        repairLines: repairContext
            ? (0, prompt_repair_1.renderAiWorkflowOptionAutofillRepairSectionLines)(repairContext)
            : undefined,
        inputLines: [
            ...(0, dedicated_prompt_support_1.renderDedicatedPromptInputLines)({
                heading: "AI workflow option autofill input:",
                prompt: input.prompt,
                workspace: input,
            }),
            `- Accepted at: ${input.acceptedAt}`,
            `- Display time zone: ${input.displayTimeZone}`,
            "- Selected workflow template (read-only):",
            ...(0, workflow_option_template_prompt_1.renderWorkerWorkflowOptionSelectedTemplateContext)(input.selectedWorkflowTemplate ?? null, {
                noneText: prompt_text_1.PROMPT_TEXT.none,
                renderNullableValue: renderSelectionValue,
            }),
            `- ${prompt_text_1.PROMPT_TEXT.fieldConfigSummary}:`,
            ...renderWorkflowOptionConfigSummary(input.configSummary),
        ],
        contract: {
            heading: "AI workflow option autofill contract:",
            rules: contract.rules,
            promptSchema: contract.promptSchema,
            example: contract.example,
        },
    });
}
function buildWorkerFollowupProposalReviewPrompt(workerName, input, repairContext) {
    const contract = (0, followup_proposal_review_contract_1.buildWorkerFollowupProposalReviewContract)(input);
    return (0, dedicated_prompt_support_1.renderDedicatedPromptEnvelope)({
        preambleLines: (0, dedicated_prompt_support_1.renderDedicatedPromptHeader)({
            workerName,
            runDescription: "This is a dedicated follow-up proposal review run.",
            instructionLines: [
                prompt_text_1.PROMPT_TEXT.introInstructions,
                "Apply the human review comments to the pending follow-up proposal candidates.",
                "Return the final candidates that should be created after approval. Do not create issues, edit labels, publish comments, or change workflow state.",
                "When a comment is ambiguous, keep the existing candidate instead of deleting or rewriting it.",
                (0, prompt_text_1.buildResponseLanguageInstruction)(input.outputLanguage),
            ],
            systemPrompts: input.systemPrompts,
            systemPromptNames: system_prompt_names_1.WORKER_COMMON_SYSTEM_PROMPT_NAMES,
        }),
        repairLines: repairContext
            ? (0, prompt_repair_1.renderFollowupProposalReviewRepairSectionLines)(repairContext)
            : undefined,
        inputLines: [
            "Follow-up proposal review input:",
            ...(0, dedicated_prompt_support_1.renderDedicatedWorkspaceFields)({
                repositoryRoot: input.repositoryRoot,
                workspacePath: input.workspacePath,
                outputLanguage: input.outputLanguage,
            }),
            "- Source issue:",
            "```json",
            JSON.stringify(input.sourceIssue, null, 2),
            "```",
            "- Completion summary:",
            "```json",
            JSON.stringify(input.completionSummary, null, 2),
            "```",
            "- Pending follow-up proposal:",
            "```json",
            JSON.stringify(input.proposal, null, 2),
            "```",
            "- Human review comments after the proposal was published:",
            "```json",
            JSON.stringify(input.userCommentsAfterProposal, null, 2),
            "```",
            "- Preferred follow-up workflow templates:",
            "```json",
            JSON.stringify(input.preferredWorkflowTemplates, null, 2),
            "```",
            "- Normal automatic maxIssuesPerSource limits:",
            "```json",
            JSON.stringify(input.maxIssuesPerSource, null, 2),
            "```",
        ],
        contract: {
            heading: "Follow-up proposal review contract:",
            rules: contract.rules,
            promptSchema: contract.promptSchema,
            example: contract.example,
        },
    });
}
function renderSection(title, bodyLines) {
    return [
        title,
        ...(bodyLines.length > 0 ? bodyLines : [prompt_text_1.PROMPT_TEXT.none]),
        "",
    ];
}
function renderWorkflowOptionConfigSummary(summary) {
    return [
        `  - issueCompletion.target: ${summary.issueCompletion.target}`,
        `  - issueCompletion.pullRequest.reviewPolicy: ${summary.issueCompletion.pullRequest.reviewPolicy}`,
        `  - issueCompletion.pullRequest.mergePolicy: ${summary.issueCompletion.pullRequest.mergePolicy}`,
        `  - baseBranch: ${summary.baseBranch}`,
        `  - aiRunLimits.maxRuns: ${summary.aiRunLimits.maxRuns}`,
        `  - aiRunLimits.maxHours: ${summary.aiRunLimits.maxHours ?? prompt_text_1.PROMPT_TEXT.none}`,
        `  - recurring.maxActiveChildren: ${summary.recurring.maxActiveChildren}`,
        `  - followup.maxIssuesPerSource.mainWork: ${summary.followup.maxIssuesPerSource.mainWork}`,
        `  - followup.maxIssuesPerSource.maintenance: ${summary.followup.maxIssuesPerSource.maintenance}`,
        `  - defaultReviewers: ${summary.defaultReviewers.join(", ") || prompt_text_1.PROMPT_TEXT.none}`,
        `  - foreignIssueApprovalScope: ${summary.foreignIssueApprovalScope}`,
        [
            "  - workflowStart:",
            ` newPlan=${String(summary.workflowStart.newPlan)},`,
            ` replan=${String(summary.workflowStart.replan)},`,
            ` scope=${summary.workflowStart.scope}`,
        ].join(""),
    ];
}
function renderAuthoritativeInstructionLines(workerName, responseLanguageInstruction, workflow, systemPrompts) {
    const lines = [
        prompt_text_1.PROMPT_TEXT.introOperating,
        workflow?.mode === types_1.WORKER_RUN_MODES.workflowSelect
            ? `This is the ${branding_1.SERVICE_DISPLAY_NAME} worker run. Read the latest user instruction, baseline issue brief, historical user context, system reference only, and the selection context, then decide whether to use a repository-specific candidate workflow template, use the built-in default workflow, or request a missing reusable template for the active workflow surface in this single run. Request a missing template only when the template slot is auto.`
            : prompt_text_1.PROMPT_TEXT.introRun,
        prompt_text_1.PROMPT_TEXT.introInstructions,
        prompt_text_1.PROMPT_TEXT.introSkills,
        prompt_text_1.PROMPT_TEXT.introControlPlane,
        prompt_text_1.PROMPT_TEXT.introNoWorkerCommitOrPush,
        prompt_text_1.PROMPT_TEXT.introOutcomes,
        responseLanguageInstruction,
        prompt_text_1.PROMPT_TEXT.introMixedLanguage,
        prompt_text_1.PROMPT_TEXT.introReferenceOnly,
        prompt_text_1.PROMPT_TEXT.subagentCommon,
        workerName === "codex"
            ? prompt_text_1.PROMPT_TEXT.subagentCodex
            : prompt_text_1.PROMPT_TEXT.subagentClaude,
        prompt_text_1.PROMPT_TEXT.introReturnDecision,
        ...(0, render_1.renderSystemPromptGuidance)({
            prompts: systemPrompts,
            names: system_prompt_names_1.WORKER_COMMON_SYSTEM_PROMPT_NAMES,
        }),
    ];
    if (workflow?.mode === types_1.WORKER_RUN_MODES.workflowSelect) {
        lines.splice(6, 0, prompt_text_1.PROMPT_TEXT.introSelectionContext);
    }
    return lines;
}
function renderIssueDraftIssueTemplateCandidates(candidates) {
    if (candidates.length === 0) {
        return [`  ${prompt_text_1.PROMPT_TEXT.none}`];
    }
    return candidates.flatMap((candidate) => [
        `  - ${candidate.templatePath}`,
        ...(candidate.name ? [`    name: ${candidate.name}`] : []),
        ...(candidate.description
            ? [`    description: ${candidate.description}`]
            : []),
        ...(candidate.title ? [`    title: ${candidate.title}`] : []),
        "    body:",
        "    ```markdown",
        ...candidate.body.split("\n").map((line) => `    ${line}`),
        "    ```",
    ]);
}
function renderContinuationSection(continuationContext) {
    if (!continuationContext) {
        return [];
    }
    return [
        prompt_text_1.PROMPT_TEXT.previousAttemptPreference,
        `- ${prompt_text_1.PROMPT_TEXT.fieldReason}: ${continuationContext.reason}`,
        `- ${prompt_text_1.PROMPT_TEXT.fieldOutcome}: ${continuationContext.outcome}`,
        `- ${prompt_text_1.PROMPT_TEXT.fieldWorkflowState}: ${(0, workflow_state_prompt_1.renderWorkflowStateSummary)(continuationContext.workflowState)}`,
        "Structured result:",
        JSON.stringify(continuationContext.result),
    ];
}
function renderWorkflowSection(workflow, systemPrompts) {
    if (!workflow) {
        return [];
    }
    const lines = [`- ${prompt_text_1.PROMPT_TEXT.fieldMode}: ${workflow.mode}`];
    if (workflow.workflowSurface !== undefined) {
        lines.push(`- ${prompt_text_1.PROMPT_TEXT.fieldWorkflowSurface}: ${workflow.workflowSurface}`);
    }
    if (workflow.mode === types_1.WORKER_RUN_MODES.workflowPlan) {
        lines.push(`- Planning intent: ${workflow.planningIntent ?? "new_plan"}`);
    }
    if (workflow.templateName !== null) {
        lines.push(`- ${prompt_text_1.PROMPT_TEXT.fieldTemplate}: ${workflow.templateName}`);
    }
    if (workflow.currentStepId !== undefined && workflow.currentStepId !== null) {
        lines.push(`- Current step ID: ${workflow.currentStepId}`);
    }
    if (workflow.parallelExecution !== undefined &&
        workflow.parallelExecution !== null) {
        lines.push(`- Parallel execution: ${JSON.stringify(workflow.parallelExecution)}`);
    }
    if (workflow.issueCompletion !== undefined) {
        lines.push(`- ${prompt_text_1.PROMPT_TEXT.fieldIssueCompletion}:`);
        lines.push(`  target: ${workflow.issueCompletion.target}`);
        lines.push(`  pullRequest.reviewPolicy: ${workflow.issueCompletion.pullRequest.reviewPolicy}`);
        lines.push(`  pullRequest.mergePolicy: ${workflow.issueCompletion.pullRequest.mergePolicy}`);
    }
    lines.push(...renderIssueNotesPath(workflow));
    if (workflow.startApprovalMode !== undefined) {
        lines.push(`- ${prompt_text_1.PROMPT_TEXT.fieldStartApprovalMode}: ${workflow.startApprovalMode}`);
    }
    if (workflow.mode === types_1.WORKER_RUN_MODES.workflowClosing &&
        workflow.state?.followup?.proposalPolicy !== "off" &&
        workflow.followupMaxIssuesPerSource !== undefined) {
        lines.push(`- followup.maxIssuesPerSource.mainWork: ${String(workflow.followupMaxIssuesPerSource.mainWork)}`);
        lines.push(`- followup.maxIssuesPerSource.maintenance: ${String(workflow.followupMaxIssuesPerSource.maintenance)}`);
        lines.push(`- followup.preferredWorkflowTemplates: ${formatPromptStringList(workflow.followupPreferredWorkflowTemplates ?? [])}`);
        lines.push(`- followup.autoMaintainTemplates: ${String(workflow.followupAutoMaintainTemplates ?? false)}`);
    }
    if (workflow.commandContext?.trim()) {
        lines.push(prompt_text_1.PROMPT_TEXT.fieldCommandContext);
        lines.push(workflow.commandContext.trim());
    }
    lines.push(...renderPlanReviewFeedback(workflow));
    if (workflow.mergeContext !== undefined && workflow.mergeContext !== null) {
        lines.push(prompt_text_1.PROMPT_TEXT.fieldMergeContext);
        lines.push(`  - Base branch: ${workflow.mergeContext.baseBranch}`);
        lines.push(`  - Base commit OID: ${workflow.mergeContext.baseCommitOid}`);
        lines.push(`  - Status: ${workflow.mergeContext.status}`);
        lines.push("  - Conflicted files:");
        lines.push(...(workflow.mergeContext.conflictedFiles.length > 0
            ? workflow.mergeContext.conflictedFiles.map((file) => `    - ${file}`)
            : [`    ${prompt_text_1.PROMPT_TEXT.none}`]));
    }
    lines.push(...(0, prompt_required_skills_1.renderRequiredSkills)(workflow.requiredSkills));
    lines.push(...(0, prompt_required_skills_1.renderRequiredMcp)(workflow.requiredMcp));
    if (workflow.mode === types_1.WORKER_RUN_MODES.workflowPlan &&
        workflow.templateBody?.trim()) {
        if (workflow.mode === types_1.WORKER_RUN_MODES.workflowPlan) {
            lines.push(prompt_text_1.PROMPT_TEXT.fieldTemplateSectionSemantics);
            lines.push(prompt_text_1.PROMPT_TEXT.workflowPlanTemplateRules);
            lines.push(prompt_text_1.PROMPT_TEXT.workflowPlanTemplateSectionMapping);
        }
        lines.push(prompt_text_1.PROMPT_TEXT.fieldTemplateBody);
        lines.push(workflow.templateBody.trim());
    }
    if (workflow.selection !== undefined && workflow.selection !== null) {
        lines.push(`- ${prompt_text_1.PROMPT_TEXT.fieldSelectionContext}:`);
        lines.push(...(0, prompt_selection_context_1.renderSelectionContext)(workflow.selection));
    }
    if (workflow.mode === types_1.WORKER_RUN_MODES.workflowPlan &&
        workflow.directChildWorkflows &&
        workflow.directChildWorkflows.length > 0) {
        lines.push(prompt_text_1.PROMPT_TEXT.fieldDirectChildWorkflows);
        lines.push(...renderDirectChildWorkflows(workflow));
    }
    if (workflow.mode === types_1.WORKER_RUN_MODES.workflowPlan &&
        workflow.templateReferences &&
        workflow.templateReferences.length > 0) {
        lines.push(prompt_text_1.PROMPT_TEXT.fieldTemplateReferences);
        lines.push(...renderTemplateReferences(workflow));
    }
    lines.push(...(0, workflow_state_prompt_1.renderWorkflowStateContext)(workflow));
    lines.push(...(0, workflow_instructions_prompt_1.renderWorkflowInstructions)(workflow));
    lines.push(...(0, workflow_instructions_prompt_1.renderWorkflowRefInstructions)(workflow));
    lines.push(...(0, render_1.renderSystemPromptGuidance)({
        prompts: systemPrompts,
        names: (0, system_prompt_names_1.resolveWorkflowContextSystemPromptNames)(workflow),
    }));
    return lines;
}
function renderIssueNotesPath(workflow) {
    return workflow.issueNotesPath === undefined
        ? []
        : [`- ${prompt_text_1.PROMPT_TEXT.fieldIssueNotesPath}: ${workflow.issueNotesPath}`];
}
function renderPlanReviewFeedback(workflow) {
    if (workflow.mode !== types_1.WORKER_RUN_MODES.workflowPlan ||
        workflow.planReviewFeedback === undefined ||
        workflow.planReviewFeedback === null) {
        return [];
    }
    return [
        "Plan review feedback:",
        JSON.stringify(workflow.planReviewFeedback, null, 2),
    ];
}
function renderSelectionValue(value) {
    return value === undefined || value === null ? prompt_text_1.PROMPT_TEXT.none : value;
}
function renderTemplateReferences(workflow) {
    return (workflow.templateReferences?.flatMap((reference) => {
        const lines = [
            `- ${prompt_text_1.PROMPT_TEXT.fieldSource}: ${reference.source}`,
            `  ${prompt_text_1.PROMPT_TEXT.fieldStatus}: ${reference.status}`,
            `  ${prompt_text_1.PROMPT_TEXT.fieldResolvedPath}: ${reference.resolvedPath ?? prompt_text_1.PROMPT_TEXT.none}`,
        ];
        if (reference.content !== null) {
            lines.push(`  ${prompt_text_1.PROMPT_TEXT.fieldContent}:`);
            lines.push(...reference.content.split("\n").map((line) => `  ${line}`));
        }
        return lines;
    }) ?? []);
}
function renderDirectChildWorkflows(workflow) {
    return (workflow.directChildWorkflows?.flatMap((workflowCall) => {
        return [
            `- ${prompt_text_1.PROMPT_TEXT.fieldTemplate}: ${workflowCall.templateName}`,
            `  ${prompt_text_1.PROMPT_TEXT.fieldCallSiteId}: ${workflowCall.callSiteId}`,
            `  ${prompt_text_1.PROMPT_TEXT.fieldLineNumber}: ${workflowCall.lineNumber}`,
            `  ${prompt_text_1.PROMPT_TEXT.fieldSource}: ${workflowCall.sourceLine}`,
        ];
    }) ?? []);
}
function renderDecisionContract(contract) {
    return (0, prompt_contract_section_1.renderPromptContractSection)({
        rules: contract.rules,
        promptSchema: contract.promptSchema,
        example: contract.example,
    });
}
function renderBaselineIssueBrief(input) {
    const baselineIssue = input.linkedIssue ?? input.issue;
    const lines = [
        `- ID: ${baselineIssue.id}`,
        `- Display ID: ${baselineIssue.displayId}`,
        `- Title: ${(0, base_title_1.resolveIssueBaseTitle)(baselineIssue)}`,
        `- URL: ${baselineIssue.url}`,
        `- Assignee: ${input.assignee ?? "unresolved"}`,
        `- Workflow: ${baselineIssue.workflowState.status}`,
        `- ${prompt_text_1.PROMPT_TEXT.fieldRules}: ${baselineIssue.workflowState.rules.join(", ") || prompt_text_1.PROMPT_TEXT.none}`,
    ];
    if (input.linkedIssue) {
        lines.unshift(`- ${prompt_text_1.PROMPT_TEXT.fieldReviewPriority} source issue body and user comments > source issue canonical workflow state > PR discussion`, "- If the source issue requirements and the source canonical workflow state conflict, return wait_human.", `- Execution Target: ${input.issue.displayId} (${input.issue.kind})`, `- Execution URL: ${input.issue.url}`);
    }
    return [
        ...lines,
        "",
        prompt_text_1.PROMPT_TEXT.fieldBody,
        "```text",
        baselineIssue.body || prompt_text_1.PROMPT_TEXT.empty,
        "```",
    ];
}
function renderLatestHumanInstructionLines(comments, assignee) {
    const latestUserInstruction = findLatestUserInstruction(comments);
    if (latestUserInstruction === null) {
        return [];
    }
    return [
        renderCommentInstructionLine(latestUserInstruction.comment, latestUserInstruction.text, assignee),
    ];
}
function renderHistoricalHumanContextLines(comments, assignee) {
    const latestUserInstructionIndex = findLatestUserInstructionIndex(comments);
    const historicalComments = latestUserInstructionIndex === -1
        ? comments
        : comments.slice(0, latestUserInstructionIndex);
    const lines = [];
    for (const comment of historicalComments) {
        const userInstruction = extractUserInstruction(comment);
        if (userInstruction === null) {
            continue;
        }
        lines.push(renderCommentInstructionLine(comment, userInstruction, assignee));
    }
    return lines;
}
function renderSystemReferenceOnlyLines(comments) {
    const lines = [];
    const latestWorkflowUpdateIndex = findLatestParsedWorkflowUpdateIndex(comments);
    const latestWorkflowStateIndex = findLatestParsedCanonicalWorkflowStateIndex(comments);
    for (const [index, comment] of comments.entries()) {
        if (index !== latestWorkflowUpdateIndex &&
            (0, workflow_update_1.isWorkflowUpdateComment)(comment.body) &&
            (0, workflow_update_1.parseWorkflowUpdate)(comment.body) !== null) {
            continue;
        }
        if (index !== latestWorkflowStateIndex &&
            (0, canonical_workflow_state_1.isCanonicalWorkflowStateComment)(comment.body) &&
            (0, canonical_workflow_state_1.parseCanonicalWorkflowStateComment)(comment.body) !== null) {
            continue;
        }
        const rendered = renderSystemReferenceComment(comment);
        if (rendered === null) {
            continue;
        }
        lines.push(rendered);
    }
    return lines;
}
function findLatestParsedWorkflowUpdateIndex(comments) {
    for (let index = comments.length - 1; index >= 0; index -= 1) {
        const comment = comments[index];
        if (comment &&
            (0, workflow_update_1.isWorkflowUpdateComment)(comment.body) &&
            (0, workflow_update_1.parseWorkflowUpdate)(comment.body) !== null) {
            return index;
        }
    }
    return -1;
}
function findLatestParsedCanonicalWorkflowStateIndex(comments) {
    for (let index = comments.length - 1; index >= 0; index -= 1) {
        const comment = comments[index];
        if (comment &&
            (0, canonical_workflow_state_1.isCanonicalWorkflowStateComment)(comment.body) &&
            (0, canonical_workflow_state_1.parseCanonicalWorkflowStateComment)(comment.body) !== null) {
            return index;
        }
    }
    return -1;
}
function renderCommentInstructionLine(comment, text, assignee) {
    return `${renderCommentPrefix(comment, assignee)} ${renderPromptText(text)}`;
}
function renderSystemReferenceComment(comment) {
    const workflowCommand = (0, comment_command_1.parseWorkflowCommandComment)(comment.body);
    if (workflowCommand.kind !== "none") {
        return `${renderCommentPrefix(comment)} ${prompt_text_1.PROMPT_TEXT.systemReferenceWorkflowCommand}`;
    }
    if ((0, workflow_update_1.isWorkflowUpdateComment)(comment.body)) {
        const parsed = (0, workflow_update_1.parseWorkflowUpdate)(comment.body);
        if (parsed === null) {
            return `${renderCommentPrefix(comment)} ${prompt_text_1.PROMPT_TEXT.systemReferenceWorkflowUpdate}`;
        }
        const questionActionText = parsed.needsHumanReason === "question"
            ? `, next=${renderPromptText(parsed.next)}`
            : "";
        return `${renderCommentPrefix(comment)} ${prompt_text_1.PROMPT_TEXT.systemReferenceWorkflowUpdate} (${parsed.workerOutcome ?? "no-worker-outcome"}, runs=${parsed.consecutiveAiRuns}, summary=${renderPromptText(parsed.summary)}${questionActionText})`;
    }
    if ((0, canonical_workflow_state_1.isCanonicalWorkflowStateComment)(comment.body)) {
        const parsed = (0, canonical_workflow_state_1.parseCanonicalWorkflowStateComment)(comment.body);
        if (parsed === null) {
            return `${renderCommentPrefix(comment)} ${prompt_text_1.PROMPT_TEXT.systemReferenceInvalidWorkflowState}`;
        }
        const summary = (0, canonical_workflow_state_1.summarizeCanonicalWorkflowState)(parsed, undefined, undefined, resolveIssueApproveCommandTarget(comment));
        return `${renderCommentPrefix(comment)} ${prompt_text_1.PROMPT_TEXT.systemReferenceWorkflowState} (template=${summary.workflowTemplateName}, currentStep=${renderPromptText(summary.currentStep)}, next=${renderPromptText(summary.next)}${summary.resultSummary ? `, result=${renderPromptText(summary.resultSummary)}` : ""})`;
    }
    if ((0, managed_comments_1.isManagedComment)(comment)) {
        return `${renderCommentPrefix(comment)} ${prompt_text_1.PROMPT_TEXT.systemReferenceManagedComment}`;
    }
    return null;
}
function findLatestUserInstruction(comments) {
    for (let index = comments.length - 1; index >= 0; index -= 1) {
        const comment = comments[index];
        if (!comment) {
            continue;
        }
        const text = extractUserInstruction(comment);
        if (text !== null) {
            return { comment, text };
        }
    }
    return null;
}
function findLatestUserInstructionIndex(comments) {
    for (let index = comments.length - 1; index >= 0; index -= 1) {
        const comment = comments[index];
        if (!comment) {
            continue;
        }
        if (extractUserInstruction(comment) !== null) {
            return index;
        }
    }
    return -1;
}
function extractUserInstruction(comment) {
    if ((0, managed_comments_1.isManagedComment)(comment)) {
        return null;
    }
    const parsed = (0, comment_command_1.parseWorkflowCommandComment)(comment.body);
    if (parsed.kind !== "none") {
        return null;
    }
    const text = comment.body.trim();
    return text.length > 0 ? text : null;
}
function renderPromptText(text) {
    return text.trim().replaceAll("\n", "\n  ");
}
function formatPromptStringList(values) {
    return values.length === 0
        ? "[]"
        : `[${values.map((value) => JSON.stringify(value)).join(", ")}]`;
}
function renderCommentPrefix(comment, assignee = null) {
    return `- ${comment.createdAt} ${comment.author} ${renderCommentMetadata(comment, assignee)}:`;
}
function resolvePromptAssignee(issue) {
    if (issue.assignees.length !== 1) {
        return null;
    }
    const assignee = issue.assignees[0]?.trim() ?? "";
    return assignee.length > 0 ? assignee : null;
}
function resolveIssueApproveCommandTarget(comment) {
    const issueDisplayId = /^#(\d+)$/u.exec(comment.targetDisplayId.trim());
    if (issueDisplayId) {
        return issueDisplayId[1] ?? null;
    }
    return comment.pullRequestNumber === undefined
        ? null
        : `mr:${comment.pullRequestNumber}`;
}
function renderCommentMetadata(comment, assignee) {
    const metadata = [comment.kind, comment.targetDisplayId];
    if (assignee !== null) {
        metadata.push(`role=${comment.author === assignee ? "assignee" : "non_assignee"}`);
    }
    if (comment.reviewState !== undefined && comment.reviewState !== null) {
        metadata.push(`reviewState=${comment.reviewState}`);
    }
    if (comment.path !== undefined && comment.path !== null) {
        metadata.push(`path=${comment.path}`);
    }
    if (comment.line !== undefined && comment.line !== null) {
        metadata.push(`line=${comment.line}`);
    }
    if (comment.side !== undefined && comment.side !== null) {
        metadata.push(`side=${comment.side}`);
    }
    return `[${metadata.join(" ")}]`;
}
