var F=Object.defineProperty;var f=(e,t)=>F(e,"name",{value:t,configurable:!0});import{createRequire as O}from"node:module";import{readLastRunSummary as T}from"@visulima/task-runner";import{a as k}from"./failure-log-Dxafk3t4.js";import{F as j,H as D,ab as y,ac as _,ad as N,ae as R,af as A,ag as B}from"../packem_chunks/bin.js";import{a as $,C as b,M as H,z as W}from"./readFileSync-DseCu8sg-DEq4Fn3a.js";import{w as q,b as L,r as Y}from"./ai-analysis-3QD_RS6F.js";const C=O(import.meta.url),l=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,I=f(e=>{if(typeof l<"u"&&l.versions&&l.versions.node){const[t,a]=l.versions.node.split(".").map(Number);if(t>22||t===22&&a>=3||t===20&&a>=16)return l.getBuiltinModule(e)}return C(e)},"__cjs_getBuiltinModule"),{readFile:E,writeFile:M}=I("node:fs/promises");var z=Object.defineProperty,m=f((e,t)=>z(e,"name",{value:t,configurable:!0}),"u");const J=32*1024,K=m((e,t)=>{if(e.length<=t)return e;const a=e.slice(-t),o=e.length-a.length;return`[…${String(o)} bytes truncated from head…]
${a}`},"truncateHead"),U=m(async(e,t)=>t===void 0?T(e,{dataDirectory:j(e)}):D(e,t),"loadSummary"),ge=m(async(e,t,a={})=>{const o=a.terminalOutputLimit??J,[r,n]=await Promise.all([k(e,t),U(e,a.runId)]),i=n?y(n,t):void 0;if(!r&&!i)return;let s,c;if(n&&i){const d=await _(e,n.id),g=d?y(d,t):void 0;s=N(i.hashDetails,g?.hashDetails),c=d?.id}const h=r?.terminalOutput??"";return{command:r?.command??void 0,cwd:r?.cwd??void 0,dependencies:i?.dependencies??[],duration:i?.duration,exitCode:r?.exitCode??i?.exitCode,hash:i?.hash??r?.hash,hashDetails:i?.hashDetails,hashDiff:s,previousRunId:c,project:i?.target.project,runId:n?.id??r?.runId,status:r?.status??(i?G(i):void 0),target:i?.target.target,taskId:t,terminalOutput:K(h,o),terminalOutputCaptured:!!r,timestamp:r?.timestamp??i?.endTime??i?.startTime}},"aggregateFailureContext"),G=m(e=>{if(e.exitCode!==void 0&&e.exitCode!==0)return"failure";switch(e.cacheStatus){case"HIT":return"local-cache";case"REMOTE_HIT":return"remote-cache";case"SKIPPED":return"skipped";default:return e.exitCode===0?"success":void 0}},"mapCacheStatusToTaskStatus");var V=Object.defineProperty,u=f((e,t)=>V(e,"name",{value:t,configurable:!0}),"a");const Q=3600*1e3,S=80,X=new Set(["high","low","medium"]),Z=u(()=>`You are an expert software engineer helping fix a failing build/test/lint task.

You will be given:
- The terminal output (stdout/stderr) from the failed task.
- Optional metadata: command, working directory, project, task hash, and a diff describing what changed in the task's hash inputs since the previous run that did not fail.

Your job:
1. Identify the root cause from the terminal output.
2. Propose a minimal set of source-file patches that fix the cause.
3. If you cannot determine a safe fix, set "cannotFix" with a clear, actionable explanation.

Constraints:
- Patches MUST be exact string replacements. The "oldString" must appear verbatim in the named file. Paths are relative to the working directory.
- Each "oldString" must be unique within its file. Include surrounding context so the match is unambiguous.
- Do NOT include unrelated cleanup, formatting changes, or speculative refactors.
- If the failure is environmental (missing tool, network) or requires running commands, prefer "cannotFix" over a guess.
- Keep "explanation" short (1-3 sentences). Reserve "reason" on each patch for why that specific edit fixes the cause.

Respond ONLY with valid JSON in this exact structure:
{
  "explanation": "Brief root-cause analysis and what the fix does.",
  "confidence": "low|medium|high",
  "patches": [
    {
      "file": "path/relative/to/cwd.ts",
      "oldString": "exact text to find",
      "newString": "exact replacement text",
      "reason": "why this change fixes it"
    }
  ],
  "cannotFix": "optional — set when no safe patch can be proposed"
}`,"buildSystemPrompt"),v=u((e,t)=>{const a=[];if(t.added.length>0&&a.push(`  added: ${t.added.join(", ")}`),t.changed.length>0&&a.push(`  changed: ${t.changed.join(", ")}`),t.removed.length>0&&a.push(`  removed: ${t.removed.join(", ")}`),a.length!==0)return`- ${e}:
${a.join(`
`)}`},"formatBucket"),ee=u(e=>{if(!e.hashDiff)return"No hash-diff available — there is no previous run to compare against.";const t=[];e.hashDiff.commandChanged&&t.push("- command line changed since previous run");const a=v("file inputs",e.hashDiff.nodes),o=v("implicit deps",e.hashDiff.implicitDeps),r=v("runtime/env",e.hashDiff.runtime);return a&&t.push(a),o&&t.push(o),r&&t.push(r),t.length===0?"No detectable changes between this run and the previous run.":t.join(`
`)},"buildHashDiffSummary"),te=u(e=>{const t=[`Task: ${e.taskId}`];return e.project&&t.push(`Project: ${e.project}`),e.target&&t.push(`Target: ${e.target}`),e.command&&t.push(`Command: ${e.command}`),e.cwd&&t.push(`CWD: ${e.cwd}`),e.exitCode!==void 0&&t.push(`Exit code: ${String(e.exitCode)}`),e.hash&&t.push(`Task hash: ${e.hash}`),t.push("","Hash-diff since previous run:",ee(e),""),e.terminalOutputCaptured?t.push("Terminal output:","```",e.terminalOutput,"```"):t.push("Terminal output: <no failure log was captured for this task>",'Set "cannotFix" and tell the user to re-run with `vis run` so logs can be captured.'),t.join(`
`)},"buildUserPrompt"),ae=u(e=>`${Z()}

${te(e)}`,"buildFixPrompt"),ie=u((e,t)=>{const a=Array.isArray(e.patches)?e.patches:[],o=[];for(const n of a)typeof n.file!="string"||n.file.length===0||typeof n.oldString!="string"||n.oldString.length===0||typeof n.newString=="string"&&o.push({file:n.file,newString:n.newString,oldString:n.oldString,reason:typeof n.reason=="string"&&n.reason.length>0?n.reason:void 0});const r=typeof e.cannotFix=="string"&&e.cannotFix.length>0?e.cannotFix:void 0;return{cannotFix:r,confidence:X.has(e.confidence)?e.confidence:"low",explanation:typeof e.explanation=="string"?e.explanation:"",patches:r?[]:o,provider:t}},"normalizeFixProposal"),ne=u((e,t)=>{const a=q(e);return!a||typeof a!="object"?{cannotFix:"AI response was not valid JSON.",confidence:"low",explanation:"Failed to parse AI response.",patches:[],provider:t}:ie(a,t)},"parseFixResponse"),re=u((e,t)=>R({cwd:t.cwd??null,flow:"ai-fix",hash:t.hash??null,provider:e,taskId:t.taskId,terminalOutput:t.terminalOutput,terminalOutputCaptured:t.terminalOutputCaptured}),"buildFixCacheKey"),ve=u(async(e,t,a={})=>{const o=L(a.config);if(!o){t.warn(`No AI provider available — install one of: claude, gemini, copilot, codex.
`);return}const r=a.cache!==!1,n=re(o.name,e);if(r){const i=A(n);if(i)return t.info(`Using cached fix proposal from ${i.provider}.
`),i}t.info(`Generating fix proposal with ${o.name}...
`);try{const i=await Y(o,ae(e)),s=ne(i,o.name);return r&&s.patches.length>0&&!s.cannotFix&&B(n,s,Q),s}catch(i){const s=i instanceof Error?i.message:String(i);t.warn(`AI fix proposal failed (${s}).
`);return}},"runFixAnalysis"),se=u((e,t,a)=>$(a)?b(a):b(H(t??e,a)),"resolvePatchPath"),oe=u((e,t)=>{const a=W(e,t);return a===""?!0:!a.startsWith("..")&&!$(a)},"isInsideWorkspace"),ce=u((e,t,a)=>{const o=e.indexOf(t),r=Math.max(0,o-S),n=Math.min(e.length,o+t.length+S),i=e.slice(r,n);return{previewAfter:`${e.slice(r,o)}${a}${e.slice(o+t.length,n)}`,previewBefore:i}},"buildPreview"),xe=u(async(e,t,a,o={})=>{const r=o.dryRun===!0,n=new Map,i=[];for(const s of a.patches){const c=se(e,t,s.file);if(!oe(e,c)){i.push({absolutePath:c,patch:s,status:"outside-workspace"});continue}let h=n.get(c);if(h===void 0){try{h=await E(c,"utf8")}catch(p){const w=p.code;i.push({absolutePath:c,error:w==="ENOENT"?void 0:p.message,patch:s,status:w==="ENOENT"?"missing-file":"error"});continue}n.set(c,h)}const d=h.indexOf(s.oldString);if(d===-1){i.push({absolutePath:c,patch:s,status:"no-match"});continue}if(h.indexOf(s.oldString,d+s.oldString.length)!==-1){i.push({absolutePath:c,patch:s,status:"ambiguous-match"});continue}const{previewAfter:g,previewBefore:P}=ce(h,s.oldString,s.newString),x=`${h.slice(0,d)}${s.newString}${h.slice(d+s.oldString.length)}`;if(!r)try{await M(c,x,"utf8")}catch(p){n.delete(c),i.push({absolutePath:c,error:p.message,patch:s,status:"error"});continue}n.set(c,x),i.push({absolutePath:c,patch:s,previewAfter:g,previewBefore:P,status:"applied"})}return i},"applyFixProposal");export{ge as a,ve as b,xe as c,se as r};
