@wundam/orchex 1.0.0-rc.25 → 1.0.0-rc.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
- import*as A from"fs/promises";import{existsSync as dt}from"fs";import*as I from"path";import{DEFAULT_MODELS as ft}from"../config.js";import{existsSync as P,readFileSync as q,readdirSync as lt}from"node:fs";import*as C from"node:path";function U(n){if(P(C.join(n,"pnpm-lock.yaml"))||P(C.join(n,"pnpm-workspace.yaml")))return"pnpm";if(P(C.join(n,"yarn.lock")))return"yarn";if(P(C.join(n,"bun.lockb"))||P(C.join(n,"bun.lock")))return"bun";if(P(C.join(n,"package-lock.json")))return"npm";try{let t=C.join(n,"package.json");if(P(t)){let s=JSON.parse(q(t,"utf-8")).packageManager;if(typeof s=="string"){if(s.startsWith("pnpm"))return"pnpm";if(s.startsWith("yarn"))return"yarn";if(s.startsWith("bun"))return"bun"}}}catch{}return"npm"}function F(n,t){switch(n){case"pnpm":return`pnpm run ${t}`;case"yarn":return`yarn run ${t}`;case"bun":return`bun run ${t}`;default:return`npm run ${t}`}}function re(n,t){if(t)switch(n){case"pnpm":return`pnpm test -- ${t}`;case"yarn":return`yarn test -- ${t}`;case"bun":return`bun test -- ${t}`;default:return`npm test -- ${t}`}return F(n,"test")}function Ce(n,t){let e=t.join(" ");switch(n){case"pnpm":return`pnpm add ${e}`;case"yarn":return`yarn add ${e}`;case"bun":return`bun add ${e}`;default:return`npm install ${e}`}}function ke(n){let e={isMonorepo:!1,tool:U(n),packages:[]},s=C.join(n,"pnpm-workspace.yaml");if(P(s))return e.isMonorepo=!0,e.packages=ve(n,ut(s)),e;try{let o=C.join(n,"package.json");if(P(o)){let r=JSON.parse(q(o,"utf-8")),i=Array.isArray(r.workspaces)?r.workspaces:Array.isArray(r.workspaces?.packages)?r.workspaces.packages:null;if(i&&i.length>0)return e.isMonorepo=!0,e.packages=ve(n,i),e}}catch{}return e}function ut(n){try{let t=q(n,"utf-8"),e=[],s=!1;for(let o of t.split(`
2
- `)){let r=o.trim();if(r==="packages:"){s=!0;continue}if(s){if(r.startsWith("- ")){let i=r.slice(2).replace(/^['"]|['"]$/g,"");e.push(i)}else if(r&&!r.startsWith("#"))break}}return e}catch{return[]}}function ve(n,t){let e=[];for(let s of t){let o=s.replace(/\/?\*$/,""),r=C.join(n,o);try{let i=lt(r,{withFileTypes:!0});for(let a of i){if(!a.isDirectory())continue;let c=C.join(r,a.name,"package.json");try{if(P(c)){let l=JSON.parse(q(c,"utf-8"));typeof l.name=="string"&&e.push(l.name)}}catch{}}}catch{}}return e}var pt=new Set(["node_modules",".git","dist","build",".next",".orchex","coverage",".turbo",".cache","__pycache__",".venv","venv"]),be=500;async function Te(n,t,e){if(e.length>=be)return;let s;try{s=await A.readdir(n,{withFileTypes:!0})}catch{return}for(let o of s){if(e.length>=be)break;if(pt.has(o.name)||o.name.startsWith(".")&&o.name!==".env.example")continue;let r=I.join(n,o.name);o.isDirectory()?await Te(r,t,e):e.push(I.relative(t,r))}}async function Pe(n){let t=[];await Te(n,n,t);let e=t.sort().join(`
3
- `),s={};try{let r=await A.readFile(I.join(n,"package.json"),"utf-8");s=JSON.parse(r)}catch{}let o;try{let r=await A.readFile(I.join(n,"tsconfig.json"),"utf-8");o=JSON.parse(r)}catch{}return{fileTree:e,packageJson:s,tsconfig:o,existingFiles:t}}function mt(n,t){let e=[],s=/(?:spec|plan|design|doc):\s*(\S+\.(?:md|txt|yaml|yml))/gi,o;for(;(o=s.exec(n))!==null;)e.push(o[1]);if(t&&e.length===0){let r=/(\S+\.(?:md|txt|yaml|yml))/gi;for(;(o=r.exec(n))!==null;){let i=o[1],a=I.join(t,i);dt(a)&&e.push(i)}}return e}function ht(n,t,e){let s=e?.packageManager??"npm",o=s==="npm"?"npm run":`${s} run`,r=[];if(r.push(`You are an expert software architect using orchex, a parallel AI orchestration tool.
1
+ import*as A from"fs/promises";import{existsSync as pt}from"fs";import*as I from"path";import{DEFAULT_MODELS as mt}from"../config.js";import{existsSync as E,readFileSync as q,readdirSync as dt}from"node:fs";import*as k from"node:path";function U(n){if(E(k.join(n,"pnpm-lock.yaml"))||E(k.join(n,"pnpm-workspace.yaml")))return"pnpm";if(E(k.join(n,"yarn.lock")))return"yarn";if(E(k.join(n,"bun.lockb"))||E(k.join(n,"bun.lock")))return"bun";if(E(k.join(n,"package-lock.json")))return"npm";try{let t=k.join(n,"package.json");if(E(t)){let s=JSON.parse(q(t,"utf-8")).packageManager;if(typeof s=="string"){if(s.startsWith("pnpm"))return"pnpm";if(s.startsWith("yarn"))return"yarn";if(s.startsWith("bun"))return"bun"}}}catch{}return"npm"}function F(n,t){switch(n){case"pnpm":return`pnpm run ${t}`;case"yarn":return`yarn run ${t}`;case"bun":return`bun run ${t}`;default:return`npm run ${t}`}}function re(n,t){if(t)switch(n){case"pnpm":return`pnpm test -- ${t}`;case"yarn":return`yarn test -- ${t}`;case"bun":return`bun test -- ${t}`;default:return`npm test -- ${t}`}return F(n,"test")}function Ce(n,t){let e=t.join(" ");switch(n){case"pnpm":return`pnpm add ${e}`;case"yarn":return`yarn add ${e}`;case"bun":return`bun add ${e}`;default:return`npm install ${e}`}}function ke(n){let e={isMonorepo:!1,tool:U(n),packages:[]},s=k.join(n,"pnpm-workspace.yaml");if(E(s))return e.isMonorepo=!0,e.packages=ve(n,ft(s)),e;try{let o=k.join(n,"package.json");if(E(o)){let r=JSON.parse(q(o,"utf-8")),i=Array.isArray(r.workspaces)?r.workspaces:Array.isArray(r.workspaces?.packages)?r.workspaces.packages:null;if(i&&i.length>0)return e.isMonorepo=!0,e.packages=ve(n,i),e}}catch{}return e}function ft(n){try{let t=q(n,"utf-8"),e=[],s=!1;for(let o of t.split(`
2
+ `)){let r=o.trim();if(r==="packages:"){s=!0;continue}if(s){if(r.startsWith("- ")){let i=r.slice(2).replace(/^['"]|['"]$/g,"");e.push(i)}else if(r&&!r.startsWith("#"))break}}return e}catch{return[]}}function ve(n,t){let e=[];for(let s of t){let o=s.replace(/\/?\*$/,""),r=k.join(n,o);try{let i=dt(r,{withFileTypes:!0});for(let a of i){if(!a.isDirectory())continue;let c=k.join(r,a.name,"package.json");try{if(E(c)){let l=JSON.parse(q(c,"utf-8"));typeof l.name=="string"&&e.push(l.name)}}catch{}}}catch{}}return e}var ht=new Set(["node_modules",".git","dist","build",".next",".orchex","coverage",".turbo",".cache","__pycache__",".venv","venv"]),be=500;async function Te(n,t,e){if(e.length>=be)return;let s;try{s=await A.readdir(n,{withFileTypes:!0})}catch{return}for(let o of s){if(e.length>=be)break;if(ht.has(o.name)||o.name.startsWith(".")&&o.name!==".env.example")continue;let r=I.join(n,o.name);o.isDirectory()?await Te(r,t,e):e.push(I.relative(t,r))}}async function Ee(n){let t=[];await Te(n,n,t);let e=t.sort().join(`
3
+ `),s={};try{let r=await A.readFile(I.join(n,"package.json"),"utf-8");s=JSON.parse(r)}catch{}let o;try{let r=await A.readFile(I.join(n,"tsconfig.json"),"utf-8");o=JSON.parse(r)}catch{}return{fileTree:e,packageJson:s,tsconfig:o,existingFiles:t}}function gt(n,t){let e=[],s=/(?:spec|plan|design|doc):\s*(\S+\.(?:md|txt|yaml|yml))/gi,o;for(;(o=s.exec(n))!==null;)e.push(o[1]);if(t&&e.length===0){let r=/(\S+\.(?:md|txt|yaml|yml))/gi;for(;(o=r.exec(n))!==null;){let i=o[1],a=I.join(t,i);pt(a)&&e.push(i)}}return e}function yt(n,t,e){let s=e?.packageManager??"npm",o=s==="npm"?"npm run":`${s} run`,r=[];if(r.push(`You are an expert software architect using orchex, a parallel AI orchestration tool.
4
4
  Your task: generate a plan document in orchex format from the user's intent.
5
5
 
6
6
  ## Output Format Rules
@@ -28,6 +28,7 @@ streams:
28
28
  ## Key Rules
29
29
  - Each stream should own 1-3 files maximum.
30
30
  - Use \`reads:\` for any file the stream imports from but does not modify.
31
+ - \`reads:\` and \`owns:\` MUST list specific files, never directory paths. If you need files from a package, list each file explicitly (e.g. \`packages/auth/src/index.ts\`, NOT \`packages/auth\`). Directory paths will cause the plan to be rejected.
31
32
  - Use \`deps:\` when one stream must complete before another can start.
32
33
  - Use \`verify:\` with scoped commands (not bare \`npm test\` \u2014 scope to specific files).
33
34
  - Tests streams should depend on their implementation streams.
@@ -98,33 +99,33 @@ When a Referenced Document above contains exact code, you MUST copy it verbatim
98
99
  5. **Function signatures and imports** \u2014 use the exact names, parameters, and return types from the document.
99
100
 
100
101
  The user has already designed the implementation. Your job is ONLY to decompose it into parallel streams \u2014 do NOT redesign, improve, modernize, or update any code from the document.`),r.join(`
101
- `)}async function gt(n,t,e,s){let o=await Pe(t),r=mt(n,t),i={};for(let f of r)try{let p=I.join(t,f),m=await A.readFile(p,"utf-8");i[f]=m}catch{}let a=U(t),c=ke(t),l=ht(n,o,{specContents:Object.keys(i).length>0?i:void 0,maxStreams:s?.maxStreams,packageManager:a,monorepo:c});s?.extraContext&&(l+=`
102
+ `)}async function wt(n,t,e,s){let o=await Ee(t),r=gt(n,t),i={};for(let f of r)try{let p=I.join(t,f),m=await A.readFile(p,"utf-8");i[f]=m}catch{}let a=U(t),c=ke(t),l=yt(n,o,{specContents:Object.keys(i).length>0?i:void 0,maxStreams:s?.maxStreams,packageManager:a,monorepo:c});s?.extraContext&&(l+=`
102
103
 
103
- `+s.extraContext);let u=await e.execute({prompt:l,model:s?.model??ft[s?.provider??e.provider??"anthropic"]??"claude-sonnet-4-5-20250929",maxTokens:s?.maxTokens??16384,streamId:"_auto-plan"});if(!u.rawResponse?.trim())throw new Error(`Auto-plan generation failed: ${u.error??"Empty response from LLM"}`);let d=u.rawResponse.trim();return d.startsWith("```markdown")?(d=d.slice(11),d.endsWith("```")&&(d=d.slice(0,-3)),d=d.trim()):d.startsWith("```")&&(d=d.slice(3),d.endsWith("```")&&(d=d.slice(0,-3)),d=d.trim()),{planMarkdown:d,tokensUsed:u.tokensUsed}}import{createLogger as yt}from"../logging.js";var wt=yt("plan-parser");function xt(n){return n.replace(/^```[\s\S]*?^```/gm,"")}function St(n){let t=xt(n),e=[/`([^`]+\.(ts|js|tsx|jsx|md|sql|json|yaml|yml))`/g,/"([^"]+\.(ts|js|tsx|jsx|md|sql|json|yaml|yml))"/g,/\[([^\]]+\.(ts|js|tsx|jsx|md|sql|json|yaml|yml))\]/g,/\b(src\/[^\s,)]+\.(ts|js|tsx|jsx))/g,/\b(tests?\/[^\s,)]+\.(ts|js|tsx|jsx))/g,/\b(docs\/[^\s,)]+\.md)/g],s=new Set;for(let r of e){r.lastIndex=0;let i;for(;(i=r.exec(t))!==null;){let a=i[1].trim();a&&!a.includes(" ")&&s.add(a)}}return[...s].filter(r=>{if(r.endsWith(".js")){let i=r.replace(/\.js$/,".ts");if(s.has(i))return!1}if(r.endsWith(".jsx")){let i=r.replace(/\.jsx$/,".tsx");if(s.has(i))return!1}return!0})}function $t(n){let t=[/depends?\s+on\s+[`"]?([^`",.]+)[`"]?/gi,/requires?\s+[`"]?([^`",.]+)[`"]?/gi,/after\s+[`"]?([^`",.]+)[`"]?\s+(?:is\s+)?(?:complete|done|finished)/gi,/\bdeps?:\s*\[([^\]]+)\]/gi],e=new Set;for(let s of t){s.lastIndex=0;let o;for(;(o=s.exec(n))!==null;)if(s.source.includes("deps")){let r=o[1].split(",").map(i=>i.trim().replace(/[`"']/g,""));for(let i of r)i&&i.length>2&&i.length<50&&e.add(i)}else{let r=o[1].trim().replace(/\s+is$/i,"").replace(/[`"]/g,"");r&&r.length>2&&r.length<50&&e.add(r)}}return[...e]}function vt(n){let t=[],e=n.replace(/\r\n/g,`
104
- `),s=/^```(\w+)?[ \t]*\n(?:\/\/\s*(\S+)\n)?([\s\S]*?)^```[ \t]*$/gm,o;for(;(o=s.exec(e))!==null;)t.push({language:o[1]||"text",filename:o[2],code:o[3].trim()});return t}function Ct(n){let t=n.split(`
104
+ `+s.extraContext);let u=await e.execute({prompt:l,model:s?.model??mt[s?.provider??e.provider??"anthropic"]??"claude-sonnet-4-5-20250929",maxTokens:s?.maxTokens??16384,streamId:"_auto-plan"});if(!u.rawResponse?.trim())throw new Error(`Auto-plan generation failed: ${u.error??"Empty response from LLM"}`);let d=u.rawResponse.trim();return d.startsWith("```markdown")?(d=d.slice(11),d.endsWith("```")&&(d=d.slice(0,-3)),d=d.trim()):d.startsWith("```")&&(d=d.slice(3),d.endsWith("```")&&(d=d.slice(0,-3)),d=d.trim()),{planMarkdown:d,tokensUsed:u.tokensUsed}}import{createLogger as xt}from"../logging.js";var St=xt("plan-parser");function $t(n){return n.replace(/^```[\s\S]*?^```/gm,"")}function vt(n){let t=$t(n),e=[/`([^`]+\.(ts|js|tsx|jsx|md|sql|json|yaml|yml))`/g,/"([^"]+\.(ts|js|tsx|jsx|md|sql|json|yaml|yml))"/g,/\[([^\]]+\.(ts|js|tsx|jsx|md|sql|json|yaml|yml))\]/g,/\b(src\/[^\s,)]+\.(ts|js|tsx|jsx))/g,/\b(tests?\/[^\s,)]+\.(ts|js|tsx|jsx))/g,/\b(docs\/[^\s,)]+\.md)/g],s=new Set;for(let r of e){r.lastIndex=0;let i;for(;(i=r.exec(t))!==null;){let a=i[1].trim();a&&!a.includes(" ")&&s.add(a)}}return[...s].filter(r=>{if(r.endsWith(".js")){let i=r.replace(/\.js$/,".ts");if(s.has(i))return!1}if(r.endsWith(".jsx")){let i=r.replace(/\.jsx$/,".tsx");if(s.has(i))return!1}return!0})}function Ct(n){let t=[/depends?\s+on\s+[`"]?([^`",.]+)[`"]?/gi,/requires?\s+[`"]?([^`",.]+)[`"]?/gi,/after\s+[`"]?([^`",.]+)[`"]?\s+(?:is\s+)?(?:complete|done|finished)/gi,/\bdeps?:\s*\[([^\]]+)\]/gi],e=new Set;for(let s of t){s.lastIndex=0;let o;for(;(o=s.exec(n))!==null;)if(s.source.includes("deps")){let r=o[1].split(",").map(i=>i.trim().replace(/[`"']/g,""));for(let i of r)i&&i.length>2&&i.length<50&&e.add(i)}else{let r=o[1].trim().replace(/\s+is$/i,"").replace(/[`"]/g,"");r&&r.length>2&&r.length<50&&e.add(r)}}return[...e]}function kt(n){let t=[],e=n.replace(/\r\n/g,`
105
+ `),s=/^```(\w+)?[ \t]*\n(?:\/\/\s*(\S+)\n)?([\s\S]*?)^```[ \t]*$/gm,o;for(;(o=s.exec(e))!==null;)t.push({language:o[1]||"text",filename:o[2],code:o[3].trim()});return t}function bt(n){let t=n.split(`
105
106
  `),e=[],s=[],o=[],r=!1;for(let a of t){if(a.startsWith("```")){r=!r,o.push(a);continue}if(r){o.push(a);continue}let c=a.match(/^(#{1,6})\s+(.+)$/);if(c){s.length>0&&(s[s.length-1].content=o.join(`
106
107
  `).trim()),o=[];let l=c[1].length,u=c[2].trim(),d={level:l,title:u,content:"",codeBlocks:[],fileReferences:[],explicitDeps:[],children:[]};for(;s.length>0&&s[s.length-1].level>=l;)s.pop();s.length>0?s[s.length-1].children.push(d):e.push(d),s.push(d)}else o.push(a)}s.length>0&&(s[s.length-1].content=o.join(`
107
- `).trim());function i(a){a.codeBlocks=vt(a.content),a.fileReferences=St(a.content),a.explicitDeps=$t(a.content);for(let c of a.children)i(c)}for(let a of e)i(a);return e}function kt(n){let t=Ct(n),e=t.find(c=>c.level===1)?.title??"Untitled Plan",o=t.find(c=>c.level===1)?.content.split(`
108
+ `).trim());function i(a){a.codeBlocks=kt(a.content),a.fileReferences=vt(a.content),a.explicitDeps=Ct(a.content);for(let c of a.children)i(c)}for(let a of e)i(a);return e}function Tt(n){let t=bt(n),e=t.find(c=>c.level===1)?.title??"Untitled Plan",o=t.find(c=>c.level===1)?.content.split(`
108
109
  `).slice(0,3).join(`
109
- `)??"",r=new Set,i=[];function a(c){for(let l of c.fileReferences)r.add(l);i.push(...c.codeBlocks);for(let l of c.children)a(l)}for(let c of t)a(c);return{title:e,description:o,sections:t,allFileReferences:[...r],allCodeBlocks:i}}function V(n,t){let e=[];function s(o){o.level===t&&e.push(o);for(let r of o.children)s(r)}for(let o of n)s(o);return e}function Y(n){let t=[];function e(s){t.push(s);for(let o of s.children)e(o)}for(let s of n)e(s);return t}function ie(n){let t=n.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t:t.replace(/\s+#(?=\s|$).*/,"").trim()}function bt(n){let t={},e=n.split(`
110
+ `)??"",r=new Set,i=[];function a(c){for(let l of c.fileReferences)r.add(l);i.push(...c.codeBlocks);for(let l of c.children)a(l)}for(let c of t)a(c);return{title:e,description:o,sections:t,allFileReferences:[...r],allCodeBlocks:i}}function V(n,t){let e=[];function s(o){o.level===t&&e.push(o);for(let r of o.children)s(r)}for(let o of n)s(o);return e}function Y(n){let t=[];function e(s){t.push(s);for(let o of s.children)e(o)}for(let s of n)e(s);return t}function ie(n){let t=n.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t:t.replace(/\s+#(?=\s|$).*/,"").trim()}function Et(n){let t={},e=n.split(`
110
111
  `),s=null,o=[],r=!1,i=!1,a=[];for(let c of e){if(r&&(c.startsWith(" ")||c.startsWith(" ")||c.trim()==="")){o.push(c.replace(/^ /,"").replace(/^\t/,""));continue}else r&&(s&&(t[s]=o.join(`
111
112
  `).trim()),r=!1,s=null,o=[]);if(i&&c.match(/^\s+-\s+/)){let u=c.replace(/^\s+-\s+/,"").trim();a.push(ie(u));continue}else i&&!c.match(/^\s+-\s+/)&&c.trim()!==""&&(s&&(t[s]=a),i=!1,s=null,a=[]);let l=c.match(/^([\w-]+):\s*(.*)$/);if(l){let[,u,d]=l;if(d.startsWith("[")&&d.endsWith("]")){let f=d.slice(1,-1).split(",").map(p=>ie(p).replace(/['"]/g,""));t[u]=f.filter(p=>p.length>0);continue}if(d==="|"||d==="|-"){s=u,o=[],r=!0;continue}if(d===""){s=u,a=[],i=!0;continue}t[u]=ie(d).replace(/^["']|["']$/g,"")}}return r&&s&&(t[s]=o.join(`
112
- `).trim()),i&&s&&(t[s]=a),t}function Tt(n){let t=n.split(`
113
+ `).trim()),i&&s&&(t[s]=a),t}function Ot(n){let t=n.split(`
113
114
  `),e=[],s=t.findIndex(i=>/^streams:\s*$/.test(i));if(s===-1)return[];let o=null,r=[];for(let i=s+1;i<t.length;i++){let a=t[i],c=a.match(/^ ([\w-]+):\s*$/);if(c){o&&r.some(l=>l.trim())&&e.push({id:o,block:r.join(`
114
115
  `)}),o=c[1],r=[];continue}if(o&&(/^ /.test(a)||a.trim()==="")){r.push(a.replace(/^ /,""));continue}if(a.trim()!==""&&!/^\s/.test(a))break}return o&&r.some(i=>i.trim())&&e.push({id:o,block:r.join(`
115
- `)}),e}function Ee(n,t){let e=bt(n),s=t??e.id??"",o=e.name??"";if(!s&&!o){wt.warn({block:n.slice(0,100)},"Malformed YAML block skipped \u2014 no id or name found");return}let r={id:s,name:o};return e.deps&&(r.deps=Array.isArray(e.deps)?e.deps:[e.deps]),e.owns&&(r.owns=Array.isArray(e.owns)?e.owns:[e.owns]),e.reads&&(r.reads=Array.isArray(e.reads)?e.reads:[e.reads]),e.plan&&(r.plan=e.plan),e.verify&&(r.verify=Array.isArray(e.verify)?e.verify:[e.verify]),e.setup&&(r.setup=Array.isArray(e.setup)?e.setup:[e.setup]),r}function ae(n){let t=[];for(let e of n.codeBlocks){if(e.language!=="yaml"&&e.language!=="yml")continue;let s=Tt(e.code);if(s.length>0){for(let{id:r,block:i}of s){let a=Ee(i,r);a&&t.push(a)}continue}if(!e.code.includes("id:")&&!e.code.includes("name:"))continue;let o=Ee(e.code);o&&t.push(o)}return t}function Pt(n){return n.includes("ORCHEX PLAN TEMPLATE")}import*as E from"fs/promises";import*as L from"path";import{createLogger as Et}from"../logging.js";var G=Et("learning-engine"),J={maxOwnsCount:{code:4,docs:6,tutorial:3,"integration-guide":3,test:4,migration:3,"api-reference":4,other:4},maxReadsCount:{code:4,docs:3,tutorial:4,"integration-guide":4,test:5,migration:4,"api-reference":3,other:4},maxContextTokens:{code:14e4,docs:8e4,tutorial:1e5,"integration-guide":1e5,test:14e4,migration:16e4,"api-reference":8e4,other:1e5},globalSoftLimit:14e4,globalHardLimit:18e4,sampleCount:0,confidence:"low",lastUpdated:new Date().toISOString(),version:1},ce=20,Ot=100,Mt=50;function It(n){return n>=Ot?"high":n>=Mt?"medium":"low"}function K(n,t){let e=`${n} ${t??""}`.toLowerCase();return e.includes("test")||e.includes("spec")?"test":e.includes("migration")||e.includes("migrate")||e.includes("refactor")||e.includes("restructure")?"migration":e.includes("integration")&&(e.includes("guide")||e.includes("doc"))?"integration-guide":e.includes("tutorial")||e.includes("getting-started")||e.includes("getting started")?"tutorial":e.includes("api")&&(e.includes("ref")||e.includes("doc"))?"api-reference":e.includes("doc")||e.includes("readme")||e.includes("md")||e.includes("guide")?"docs":"code"}function Rt(n,t=ce){let e=[],s=[],o=n.filter(u=>(u.eventType==="stream_complete"||u.eventType==="stream_failed")&&u.contextTokensEstimated!==void 0);if(o.length<t)return{correlations:[],suggestedThresholds:{},insights:[`Not enough data for learning. Have ${o.length}, need ${t} samples.`],hasEnoughData:!1};let r=o.filter(u=>u.eventType==="stream_complete").length,i=r/o.length;s.push(`Overall success rate: ${(i*100).toFixed(1)}% (${r}/${o.length})`);let a=Ft(o);a.optimalRange&&(e.push({factor:"contextTokens",successRate:a.optimalSuccessRate,sampleSize:a.optimalSampleSize,threshold:a.optimalRange.max,recommendation:`Optimal context size: ${a.optimalRange.min.toLocaleString()}-${a.optimalRange.max.toLocaleString()} tokens (${(a.optimalSuccessRate*100).toFixed(1)}% success)`}),s.push(e[e.length-1].recommendation));let c=_t(o);c.softViolationSuccessRate!==void 0&&e.push({factor:"softViolation",successRate:c.softViolationSuccessRate,sampleSize:c.softViolationCount,threshold:0,recommendation:c.softViolationSuccessRate<.7?"Soft limit violations have low success rate - consider lowering soft limit":"Soft limit violations acceptable - current threshold is appropriate"});let l=jt(e,a,o.length);return{correlations:e,suggestedThresholds:l,insights:s,hasEnoughData:!0}}function Ft(n){let t=[{min:0,max:5e4},{min:5e4,max:1e5},{min:1e5,max:15e4},{min:15e4,max:2e5}],e=t[0],s=0,o=0;for(let r of t){let i=n.filter(a=>a.contextTokensEstimated!==void 0&&a.contextTokensEstimated>=r.min&&a.contextTokensEstimated<r.max);if(i.length>=5){let c=i.filter(l=>l.eventType==="stream_complete").length/i.length;c>s&&(s=c,e=r,o=i.length)}}return{optimalRange:o>=5?e:void 0,optimalSuccessRate:s,optimalSampleSize:o}}function _t(n){let t=n.filter(s=>s.budgetViolationType==="soft"),e=n.filter(s=>s.budgetViolationType==="hard");return{softViolationCount:t.length,softViolationSuccessRate:t.length>=5?t.filter(s=>s.eventType==="stream_complete").length/t.length:void 0,hardViolationCount:e.length,hardViolationSuccessRate:e.length>=5?e.filter(s=>s.eventType==="stream_complete").length/e.length:void 0}}function jt(n,t,e){let s={sampleCount:e,confidence:It(e),lastUpdated:new Date().toISOString(),version:1};return t.optimalRange&&(s.globalSoftLimit=t.optimalRange.max,s.globalHardLimit=Math.round(t.optimalRange.max*1.3)),s}function At(n,t,e=.3){if(!t.hasEnoughData)return n;let s={...n},o=t.suggestedThresholds;return o.globalSoftLimit!==void 0&&(s.globalSoftLimit=Math.round(n.globalSoftLimit*(1-e)+o.globalSoftLimit*e)),o.globalHardLimit!==void 0&&(s.globalHardLimit=Math.round(n.globalHardLimit*(1-e)+o.globalHardLimit*e)),o.sampleCount!==void 0&&(s.sampleCount=o.sampleCount),o.confidence!==void 0&&(s.confidence=o.confidence),s.lastUpdated=new Date().toISOString(),s}function Oe(n){return L.join(n,".orchex","learn","thresholds.json")}async function Lt(n,t){let e=Oe(n),s=L.dirname(e);await E.mkdir(s,{recursive:!0}),await E.writeFile(e,JSON.stringify(t,null,2),"utf-8")}async function Dt(n){let t=Oe(n);try{let e=await E.readFile(t,"utf-8"),s=JSON.parse(e);return s.version!==1?(G.warn({version:s.version},"unknown_thresholds_version"),null):s}catch{return null}}async function Me(n){return await Dt(n)??{...J}}function Nt(n,t,e){switch(e){case"owns":return n.maxOwnsCount[t]??J.maxOwnsCount.other;case"reads":return n.maxReadsCount[t]??J.maxReadsCount.other;case"tokens":return n.maxContextTokens[t]??n.globalSoftLimit}}function Ie(n){return L.join(n,".orchex","learn","events.jsonl")}function Wt(n,t,e){return{id:`learn-${Date.now()}-${n.id}`,sessionHash:"local",eventType:n.status==="complete"?"stream_complete":"stream_failed",timestamp:new Date().toISOString(),durationMs:n.executionTimeMs,success:n.status==="complete",tokensInput:n.tokensUsed?.input,tokensOutput:n.tokensUsed?.output,provider:t,model:e,contextTokensEstimated:n.contextMetrics?.estimatedTokens,contextTokensActual:n.contextMetrics?.actualTokens,contextBudgetUtilization:n.contextMetrics?.budgetUtilization,budgetViolationType:n.contextMetrics?.violationType}}async function Ut(n,t){if(t.length===0)return;let e=Ie(n),s=L.dirname(e);await E.mkdir(s,{recursive:!0});let o=t.map(r=>JSON.stringify(r)).join(`
116
+ `)}),e}function Oe(n,t){let e=Et(n),s=t??e.id??"",o=e.name??"";if(!s&&!o){St.warn({block:n.slice(0,100)},"Malformed YAML block skipped \u2014 no id or name found");return}let r={id:s,name:o};return e.deps&&(r.deps=Array.isArray(e.deps)?e.deps:[e.deps]),e.owns&&(r.owns=Array.isArray(e.owns)?e.owns:[e.owns]),e.reads&&(r.reads=Array.isArray(e.reads)?e.reads:[e.reads]),e.plan&&(r.plan=e.plan),e.verify&&(r.verify=Array.isArray(e.verify)?e.verify:[e.verify]),e.setup&&(r.setup=Array.isArray(e.setup)?e.setup:[e.setup]),r}function ae(n){let t=[];for(let e of n.codeBlocks){if(e.language!=="yaml"&&e.language!=="yml")continue;let s=Ot(e.code);if(s.length>0){for(let{id:r,block:i}of s){let a=Oe(i,r);a&&t.push(a)}continue}if(!e.code.includes("id:")&&!e.code.includes("name:"))continue;let o=Oe(e.code);o&&t.push(o)}return t}function Pt(n){return n.includes("ORCHEX PLAN TEMPLATE")}import*as O from"fs/promises";import*as D from"path";import{createLogger as Mt}from"../logging.js";var G=Mt("learning-engine"),J={maxOwnsCount:{code:4,docs:6,tutorial:3,"integration-guide":3,test:4,migration:3,"api-reference":4,other:4},maxReadsCount:{code:4,docs:3,tutorial:4,"integration-guide":4,test:5,migration:4,"api-reference":3,other:4},maxContextTokens:{code:14e4,docs:8e4,tutorial:1e5,"integration-guide":1e5,test:14e4,migration:16e4,"api-reference":8e4,other:1e5},globalSoftLimit:14e4,globalHardLimit:18e4,sampleCount:0,confidence:"low",lastUpdated:new Date().toISOString(),version:1},ce=20,It=100,Rt=50;function Ft(n){return n>=It?"high":n>=Rt?"medium":"low"}function K(n,t){let e=`${n} ${t??""}`.toLowerCase();return e.includes("test")||e.includes("spec")?"test":e.includes("migration")||e.includes("migrate")||e.includes("refactor")||e.includes("restructure")?"migration":e.includes("integration")&&(e.includes("guide")||e.includes("doc"))?"integration-guide":e.includes("tutorial")||e.includes("getting-started")||e.includes("getting started")?"tutorial":e.includes("api")&&(e.includes("ref")||e.includes("doc"))?"api-reference":e.includes("doc")||e.includes("readme")||e.includes("md")||e.includes("guide")?"docs":"code"}function _t(n,t=ce){let e=[],s=[],o=n.filter(u=>(u.eventType==="stream_complete"||u.eventType==="stream_failed")&&u.contextTokensEstimated!==void 0);if(o.length<t)return{correlations:[],suggestedThresholds:{},insights:[`Not enough data for learning. Have ${o.length}, need ${t} samples.`],hasEnoughData:!1};let r=o.filter(u=>u.eventType==="stream_complete").length,i=r/o.length;s.push(`Overall success rate: ${(i*100).toFixed(1)}% (${r}/${o.length})`);let a=jt(o);a.optimalRange&&(e.push({factor:"contextTokens",successRate:a.optimalSuccessRate,sampleSize:a.optimalSampleSize,threshold:a.optimalRange.max,recommendation:`Optimal context size: ${a.optimalRange.min.toLocaleString()}-${a.optimalRange.max.toLocaleString()} tokens (${(a.optimalSuccessRate*100).toFixed(1)}% success)`}),s.push(e[e.length-1].recommendation));let c=At(o);c.softViolationSuccessRate!==void 0&&e.push({factor:"softViolation",successRate:c.softViolationSuccessRate,sampleSize:c.softViolationCount,threshold:0,recommendation:c.softViolationSuccessRate<.7?"Soft limit violations have low success rate - consider lowering soft limit":"Soft limit violations acceptable - current threshold is appropriate"});let l=Dt(e,a,o.length);return{correlations:e,suggestedThresholds:l,insights:s,hasEnoughData:!0}}function jt(n){let t=[{min:0,max:5e4},{min:5e4,max:1e5},{min:1e5,max:15e4},{min:15e4,max:2e5}],e=t[0],s=0,o=0;for(let r of t){let i=n.filter(a=>a.contextTokensEstimated!==void 0&&a.contextTokensEstimated>=r.min&&a.contextTokensEstimated<r.max);if(i.length>=5){let c=i.filter(l=>l.eventType==="stream_complete").length/i.length;c>s&&(s=c,e=r,o=i.length)}}return{optimalRange:o>=5?e:void 0,optimalSuccessRate:s,optimalSampleSize:o}}function At(n){let t=n.filter(s=>s.budgetViolationType==="soft"),e=n.filter(s=>s.budgetViolationType==="hard");return{softViolationCount:t.length,softViolationSuccessRate:t.length>=5?t.filter(s=>s.eventType==="stream_complete").length/t.length:void 0,hardViolationCount:e.length,hardViolationSuccessRate:e.length>=5?e.filter(s=>s.eventType==="stream_complete").length/e.length:void 0}}function Dt(n,t,e){let s={sampleCount:e,confidence:Ft(e),lastUpdated:new Date().toISOString(),version:1};return t.optimalRange&&(s.globalSoftLimit=t.optimalRange.max,s.globalHardLimit=Math.round(t.optimalRange.max*1.3)),s}function Lt(n,t,e=.3){if(!t.hasEnoughData)return n;let s={...n},o=t.suggestedThresholds;return o.globalSoftLimit!==void 0&&(s.globalSoftLimit=Math.round(n.globalSoftLimit*(1-e)+o.globalSoftLimit*e)),o.globalHardLimit!==void 0&&(s.globalHardLimit=Math.round(n.globalHardLimit*(1-e)+o.globalHardLimit*e)),o.sampleCount!==void 0&&(s.sampleCount=o.sampleCount),o.confidence!==void 0&&(s.confidence=o.confidence),s.lastUpdated=new Date().toISOString(),s}function Pe(n){return D.join(n,".orchex","learn","thresholds.json")}async function Nt(n,t){let e=Pe(n),s=D.dirname(e);await O.mkdir(s,{recursive:!0}),await O.writeFile(e,JSON.stringify(t,null,2),"utf-8")}async function Wt(n){let t=Pe(n);try{let e=await O.readFile(t,"utf-8"),s=JSON.parse(e);return s.version!==1?(G.warn({version:s.version},"unknown_thresholds_version"),null):s}catch{return null}}async function Me(n){return await Wt(n)??{...J}}function Ut(n,t,e){switch(e){case"owns":return n.maxOwnsCount[t]??J.maxOwnsCount.other;case"reads":return n.maxReadsCount[t]??J.maxReadsCount.other;case"tokens":return n.maxContextTokens[t]??n.globalSoftLimit}}function Ie(n){return D.join(n,".orchex","learn","events.jsonl")}function zt(n,t,e){return{id:`learn-${Date.now()}-${n.id}`,sessionHash:"local",eventType:n.status==="complete"?"stream_complete":"stream_failed",timestamp:new Date().toISOString(),durationMs:n.executionTimeMs,success:n.status==="complete",tokensInput:n.tokensUsed?.input,tokensOutput:n.tokensUsed?.output,provider:t,model:e,contextTokensEstimated:n.contextMetrics?.estimatedTokens,contextTokensActual:n.contextMetrics?.actualTokens,contextBudgetUtilization:n.contextMetrics?.budgetUtilization,budgetViolationType:n.contextMetrics?.violationType}}async function Ht(n,t){if(t.length===0)return;let e=Ie(n),s=D.dirname(e);await O.mkdir(s,{recursive:!0});let o=t.map(r=>JSON.stringify(r)).join(`
116
117
  `)+`
117
- `;await E.appendFile(e,o,"utf-8")}async function zt(n){let t=Ie(n);try{let e=await E.readFile(t,"utf-8"),s=[];for(let o of e.split(`
118
- `))if(o.trim())try{s.push(JSON.parse(o))}catch{}return s}catch{return[]}}async function Ht(n){let t=await zt(n);if(t.length<ce)return G.debug({eventCount:t.length,minRequired:ce},"learning_skipped_insufficient_data"),null;let e=Rt(t);if(!e.hasEnoughData)return G.debug({insights:e.insights},"learning_insufficient_context_data"),e;let s=await Me(n),o=At(s,e);return await Lt(n,o),G.info({sampleCount:o.sampleCount,confidence:o.confidence,globalSoftLimit:o.globalSoftLimit,globalHardLimit:o.globalHardLimit},"learning_cycle_completed"),e}var Bt=["tests","migrations","docs","types","styles","core"],qt=["types","migrations","styles","core","tests","docs"];function Vt(n){let t=n.toLowerCase(),e=t.split("/").pop()??t;for(let s of Bt)switch(s){case"tests":if(t.includes("/test")||t.includes("/__tests__/")||e.includes(".test.")||e.includes(".spec.")||e.startsWith("test_")||e.endsWith("_test.ts")||e.endsWith("_test.js"))return"tests";break;case"migrations":if(t.includes("/migration")||e.includes("migration")||e.endsWith(".sql"))return"migrations";break;case"docs":if(t.endsWith(".md")||t.includes("/docs/")||t.includes("/documentation/"))return"docs";break;case"types":if(e.includes("types")||e.includes("schema")||e.includes("interface")||e==="index.d.ts")return"types";break;case"styles":if(t.endsWith(".css")||t.endsWith(".scss")||t.endsWith(".less")||t.endsWith(".sass")||t.includes("/styles/"))return"styles";break}return"core"}var Yt={types:["type","interface","schema","define","definition","typescript","zod"],migrations:["migrate","migration","schema","table","column","database","sql","alter"],core:["implement","create","add","configure","setup","install","build"],tests:["test","verify","check","assert","coverage","spec","expect"],docs:["document","readme","guide","example","usage","api reference"],styles:["style","css","scss","theme","design","token","color","layout"]};function Gt(n,t,e){let s=n.split(`
119
- `),o=Yt[t],r=e.map(a=>(a.split("/").pop()??a).toLowerCase().replace(/\.[^.]+$/,"")),i=s.filter(a=>{let c=a.toLowerCase();return!!(o.some(l=>c.includes(l))||r.some(l=>c.includes(l)))});return i.length>0?i.join(`
118
+ `;await O.appendFile(e,o,"utf-8")}async function Bt(n){let t=Ie(n);try{let e=await O.readFile(t,"utf-8"),s=[];for(let o of e.split(`
119
+ `))if(o.trim())try{s.push(JSON.parse(o))}catch{}return s}catch{return[]}}async function qt(n){let t=await Bt(n);if(t.length<ce)return G.debug({eventCount:t.length,minRequired:ce},"learning_skipped_insufficient_data"),null;let e=_t(t);if(!e.hasEnoughData)return G.debug({insights:e.insights},"learning_insufficient_context_data"),e;let s=await Me(n),o=Lt(s,e);return await Nt(n,o),G.info({sampleCount:o.sampleCount,confidence:o.confidence,globalSoftLimit:o.globalSoftLimit,globalHardLimit:o.globalHardLimit},"learning_cycle_completed"),e}var Vt=["tests","migrations","docs","types","styles","core"],Yt=["types","migrations","styles","core","tests","docs"];function Gt(n){let t=n.toLowerCase(),e=t.split("/").pop()??t;for(let s of Vt)switch(s){case"tests":if(t.includes("/test")||t.includes("/__tests__/")||e.includes(".test.")||e.includes(".spec.")||e.startsWith("test_")||e.endsWith("_test.ts")||e.endsWith("_test.js"))return"tests";break;case"migrations":if(t.includes("/migration")||e.includes("migration")||e.endsWith(".sql"))return"migrations";break;case"docs":if(t.endsWith(".md")||t.includes("/docs/")||t.includes("/documentation/"))return"docs";break;case"types":if(e.includes("types")||e.includes("schema")||e.includes("interface")||e==="index.d.ts")return"types";break;case"styles":if(t.endsWith(".css")||t.endsWith(".scss")||t.endsWith(".less")||t.endsWith(".sass")||t.includes("/styles/"))return"styles";break}return"core"}var Jt={types:["type","interface","schema","define","definition","typescript","zod"],migrations:["migrate","migration","schema","table","column","database","sql","alter"],core:["implement","create","add","configure","setup","install","build"],tests:["test","verify","check","assert","coverage","spec","expect"],docs:["document","readme","guide","example","usage","api reference"],styles:["style","css","scss","theme","design","token","color","layout"]};function Kt(n,t,e){let s=n.split(`
120
+ `),o=Jt[t],r=e.map(a=>(a.split("/").pop()??a).toLowerCase().replace(/\.[^.]+$/,"")),i=s.filter(a=>{let c=a.toLowerCase();return!!(o.some(l=>c.includes(l))||r.some(l=>c.includes(l)))});return i.length>0?i.join(`
120
121
  `):`${n}
121
122
 
122
- Files: ${e.join(", ")}`}function Jt(n,t){let e=n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40);return t?`${t}-${e}`:e}function Fe(n){let t=[],e=[],s=/^\s*[-*]?\s*(?:Create|Modify|Test):\s*`([^`]+)`/gim,o;for(;(o=s.exec(n))!==null;){let a=o[1].replace(/:\d+(-\d+)?$/,"").trim();a&&a.includes(".")&&t.push(a)}let r=/\*\*(?:New\s+)?[Ff]ile:\*\*\s*`([^`]+)`/gi;for(;(o=r.exec(n))!==null;){let a=o[1].replace(/:\d+(-\d+)?$/,"").trim();a&&a.includes(".")&&t.push(a)}let i=/^\s*[-*]?\s*(?:Reads?|Imports?):\s*`([^`]+)`/gim;for(;(o=i.exec(n))!==null;){let a=o[1].replace(/:\d+(-\d+)?$/,"").trim();a&&a.includes(".")&&e.push(a)}return{owned:t,reads:e}}function _e(n,t){let e=new Set,s=new Set(t),o=/(?:import\s+(?:[\s\S]*?\s+from\s+)?|import\s*\()['"]([^'"]+)['"]/g,r=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g;for(let i of n){let a=[],c;for(o.lastIndex=0;(c=o.exec(i.code))!==null;)a.push(c[1]);for(r.lastIndex=0;(c=r.exec(i.code))!==null;)a.push(c[1]);for(let l of a){let u=Kt(l,i.filename);u&&(s.has(u)||t.some(d=>d.endsWith("/"+u))||e.add(u))}}return[...e]}function Kt(n,t){if(!n.startsWith(".")&&!n.startsWith("src/")&&!n.startsWith("tests/")&&!n.startsWith("lib/")||n.startsWith("node:"))return null;let e;if(n.startsWith(".")){if(!t)return null;let s=t.split("/");s.pop();let o=s.join("/"),r=[...o?o.split("/"):[]];for(let i of n.split("/"))i!=="."&&(i===".."?r.pop():r.push(i));e=r.join("/")}else e=n;return e.endsWith(".js")&&(e=e.replace(/\.js$/,".ts")),e.includes(".")||(e=e+".ts"),e}function Qt(n,t){let e=new Set,s=new Set,o=n.content.match(/reads:\s*\[([^\]]+)\]/i);if(o){let d=o[1].split(",").map(f=>f.trim().replace(/[`"']/g,""));for(let f of d)f&&f.includes(".")&&s.add(f)}let r=z(n),i=je(r),a=Fe(i);for(let d of a.owned)s.has(d)||e.add(d);let c=Q(n,t);for(let d of c)d.filename&&d.filename.includes(".")&&!s.has(d.filename)&&e.add(d.filename);let l=/owns:\s*\[([^\]]+)\]/gi,u;for(;(u=l.exec(i))!==null;){let d=u[1].split(",").map(f=>f.trim().replace(/[`"']/g,""));for(let f of d)f&&f.includes(".")&&!s.has(f)&&e.add(f)}return[...e]}function je(n){return n.replace(/^```[^\n]*\n[\s\S]*?^```\s*$/gm,"")}function z(n){let t=n.content;for(let e of n.children)t+=`
123
+ Files: ${e.join(", ")}`}function Qt(n,t){let e=n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40);return t?`${t}-${e}`:e}function Fe(n){let t=[],e=[],s=/^\s*[-*]?\s*(?:Create|Modify|Test):\s*`([^`]+)`/gim,o;for(;(o=s.exec(n))!==null;){let a=o[1].replace(/:\d+(-\d+)?$/,"").trim();a&&a.includes(".")&&t.push(a)}let r=/\*\*(?:New\s+)?[Ff]ile:\*\*\s*`([^`]+)`/gi;for(;(o=r.exec(n))!==null;){let a=o[1].replace(/:\d+(-\d+)?$/,"").trim();a&&a.includes(".")&&t.push(a)}let i=/^\s*[-*]?\s*(?:Reads?|Imports?):\s*`([^`]+)`/gim;for(;(o=i.exec(n))!==null;){let a=o[1].replace(/:\d+(-\d+)?$/,"").trim();a&&a.includes(".")&&e.push(a)}return{owned:t,reads:e}}function _e(n,t){let e=new Set,s=new Set(t),o=/(?:import\s+(?:[\s\S]*?\s+from\s+)?|import\s*\()['"]([^'"]+)['"]/g,r=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g;for(let i of n){let a=[],c;for(o.lastIndex=0;(c=o.exec(i.code))!==null;)a.push(c[1]);for(r.lastIndex=0;(c=r.exec(i.code))!==null;)a.push(c[1]);for(let l of a){let u=Xt(l,i.filename);u&&(s.has(u)||t.some(d=>d.endsWith("/"+u))||e.add(u))}}return[...e]}function Xt(n,t){if(!n.startsWith(".")&&!n.startsWith("src/")&&!n.startsWith("tests/")&&!n.startsWith("lib/")||n.startsWith("node:"))return null;let e;if(n.startsWith(".")){if(!t)return null;let s=t.split("/");s.pop();let o=s.join("/"),r=[...o?o.split("/"):[]];for(let i of n.split("/"))i!=="."&&(i===".."?r.pop():r.push(i));e=r.join("/")}else e=n;return e.endsWith(".js")&&(e=e.replace(/\.js$/,".ts")),e.includes(".")||(e=e+".ts"),e}function Zt(n,t){let e=new Set,s=new Set,o=n.content.match(/reads:\s*\[([^\]]+)\]/i);if(o){let d=o[1].split(",").map(f=>f.trim().replace(/[`"']/g,""));for(let f of d)f&&f.includes(".")&&s.add(f)}let r=z(n),i=je(r),a=Fe(i);for(let d of a.owned)s.has(d)||e.add(d);let c=Q(n,t);for(let d of c)d.filename&&d.filename.includes(".")&&!s.has(d.filename)&&e.add(d.filename);let l=/owns:\s*\[([^\]]+)\]/gi,u;for(;(u=l.exec(i))!==null;){let d=u[1].split(",").map(f=>f.trim().replace(/[`"']/g,""));for(let f of d)f&&f.includes(".")&&!s.has(f)&&e.add(f)}return[...e]}function je(n){return n.replace(/^```[^\n]*\n[\s\S]*?^```\s*$/gm,"")}function z(n){let t=n.content;for(let e of n.children)t+=`
123
124
  `+e.title+`
124
- `+z(e);return t}function Q(n,t){let e=[...t];for(let s of n.children){e.push(...s.codeBlocks);for(let o of s.children)e.push(...Q(o,[]))}return e}function Xt(n){let t=n.split(`
125
- `);for(let e of t){let s=e.trim();if(!s||/^-{3,}$/.test(s)||/^\*\*[^*]+\*\*$/.test(s)&&s.split(/\s+/).length<=3)continue;if(s.split(/\s+/).filter(r=>r.length>0).length>3)return s.length>150?s.slice(0,147)+"...":s}return""}function Zt(n,t,e=3e3){let s=z(n);if(s.length<=e||n.children.length<3)return s.slice(0,e);let o=[],r=n.content.trim();r&&o.push(r.slice(0,300));for(let c=0;c<n.children.length;c++){let l=n.children[c],u=l.title,d=Xt(l.content),p=(l.fileReferences||[]).filter(h=>t.includes(h)),m=`${c+1}. ${u}`;p.length>0&&(m+=` (${p.join(", ")})`),d&&(m+=` \u2014 ${d}`),o.push(m)}let i=0,a=[];for(let c of o){if(i+c.length+1>e&&a.length>0)break;a.push(c),i+=c.length+1}return a.join(`
126
- `)}function en(n,t){let e=new Set,s=z(n),o=je(s),r=o.match(/reads:\s*\[([^\]]+)\]/i);if(r){let l=r[1].split(",").map(u=>u.trim().replace(/[`"']/g,""));for(let u of l)u&&u.includes(".")&&!t.includes(u)&&e.add(u)}let i=Fe(o);for(let l of i.reads)t.includes(l)||e.add(l);let a=Q(n,n.codeBlocks),c=_e(a,t);for(let l of c)t.includes(l)||e.add(l);return[...e]}function Ae(n){let t=new Map;for(let e of n){let s=Vt(e);t.has(s)||t.set(s,[]),t.get(s).push(e)}return t}function Le(n){if(n._fromYaml)return{split:!1,reasons:[]};let e=[];n.ownedFiles.length>4&&e.push(`Owns ${n.ownedFiles.length} files (max recommended: 4)`);let s=(n.description.match(/\band\b/gi)??[]).length;if(s>2&&e.push(`Description has ${s} "and" conjunctions (suggests multiple tasks)`),n.ownedFiles.length>1){let o=Ae(n.ownedFiles);if(o.size>1){let r=[...o.keys()].join(", ");e.push(`Files belong to ${o.size} different concerns (${r})`)}}return{split:e.length>0,reasons:e}}function tn(n){let t=K(n.name,n.plan||"");return{id:n.id,name:n.name,description:n.plan||"",category:t,ownedFiles:n.owns||[],readFiles:n.reads||[],explicitDeps:n.deps||[],codeExamples:[],isAtomic:!0,_fromYaml:!0,_verify:n.verify,_setup:n.setup}}function nn(n,t,e){let s=[],o=Y(n.sections);for(let r of o){let i=ae(r);if(e){let a=r.codeBlocks.filter(c=>c.language==="yaml"||c.language==="yml");e.yamlBlocksFound+=a.length,e.yamlBlocksParsed+=i.length}for(let a of i){t&&!a.id.startsWith(t)&&(a.id=`${t}-${a.id}`);let c=tn(a),l=Le(c);l.split&&(c.isAtomic=!1,c.suggestedSplit=l.reasons),s.push(c)}}return s}function sn(n){let t=Y(n.sections);for(let e of t)if(ae(e).length>0)return!0;return!1}function on(n){if(["test plan","implementation order","security checklist","gap inventory","task order","dependency order","execution order","deployment order","wave order"].some(r=>n.includes(r)))return!0;let e=["checklist","inventory","roadmap","timeline","schedule"],s=n.split(/[\s:]+/).filter(r=>r.length>0),o=s[s.length-1]??"";return!!e.includes(o)}function rn(n,t={}){let{deliverableLevel:e=2,prefix:s,preferYaml:o=!0,diagnostics:r}=t;if(o&&sn(n)){r&&(r.extractionPath="yaml");let l=nn(n,s,r);return r&&(r.deliverableCount=l.length),l}if(r){let l=Y(n.sections);for(let u of l)r.yamlBlocksFound+=u.codeBlocks.filter(d=>d.language==="yaml"||d.language==="yml").length;r.extractionPath="markdown"}let i=[],a=V(n.sections,e);if(r)for(let l of[2,3,4])r.sectionsFound[l]=V(n.sections,l).length;for(let l of a){let S=function(_){for(let j of _.fileReferences)m.includes(j)||h.includes(j)||T&&!v.has(j)||h.push(j);for(let j of _.children)S(j)};var c=S;let u=l.title.toLowerCase(),f=u.split(/[\s:]+/).filter(_=>_.length>0)[0]??"";if(u.includes("overview")&&a.indexOf(l)===0||f==="summary"||u==="summary: task order"||f==="conclusion"||f==="introduction"||f==="context"||f==="background"||f==="appendix"||f==="references"||f==="changelog"||f==="prerequisites"||on(u)){r&&r.sectionsFilteredAsMeta.push(l.title);continue}let p=Jt(l.title,s),m=Qt(l,l.codeBlocks),h=en(l,m),y=Q(l,l.codeBlocks),v=new Set(_e(y,m)),T=v.size>0;for(let _ of l.children)S(_);let x=z(l),g=K(l.title,x),w={id:p,name:l.title,description:Zt(l,m),category:g,ownedFiles:m,readFiles:h,explicitDeps:l.explicitDeps,codeExamples:y,isAtomic:!0,childCount:l.children.length},$e=Le(w);$e.split&&(w.isAtomic=!1,w.suggestedSplit=$e.reasons),i.push(w)}return r&&(r.deliverableCount=i.length),i}function an(n,t){let e=(n.language||"").toLowerCase(),s=n.code.toLowerCase();switch(t){case"migrations":return e==="sql"||s.includes("create table")||s.includes("alter table");case"types":return(e==="typescript"||e==="ts")&&(s.includes("export type ")||s.includes("export interface ")||s.includes("z.object"));case"tests":return s.includes("describe(")||s.includes("it(")||s.includes("expect(");case"docs":return e==="markdown"||e==="md";case"styles":return e==="css"||e==="scss"||e==="less"||e==="sass";case"core":return(e==="typescript"||e==="ts"||e==="javascript"||e==="js")&&!s.includes("export type ")&&!s.includes("export interface ")&&!s.includes("describe(")&&!s.includes("it(");default:return!1}}function cn(n){if(n._fromYaml)return[{...n,isAtomic:!0}];let e=Ae(n.ownedFiles);if(e.size<=1)return[{...n,isAtomic:!0}];let s=[],o=null,r=0;for(let i of qt){let a=e.get(i);if(!a||a.length===0)continue;r++;let c=`${n.id}-${i}`,l=`${n.name} (${i})`,u=Gt(n.description,i,a),d=[];r===1&&n.explicitDeps.length>0&&d.push(...n.explicitDeps),o&&d.push(o);let f=[];switch(i){case"types":break;case"core":case"migrations":f=[...n.readFiles];break;case"tests":f=[...e.get("core")||[]];break;case"docs":f=[...e.get("core")||e.get("types")||[]];break}let p=n.codeExamples.filter(m=>m.filename&&a.some(h=>m.filename===h)?!0:m.filename?!1:an(m,i));s.push({id:c,name:l,description:u,category:n.category,ownedFiles:a,readFiles:f,explicitDeps:d,codeExamples:p,isAtomic:!0}),o=c}return s}function ln(n){let t=[];for(let e of n)e.isAtomic?t.push(e):t.push(...cn(e));return t}function Re(n){let t=[];return t.push(`${n.id}:`),t.push(` Name: ${n.name}`),t.push(` Category: ${n.category}`),t.push(` Owns: ${n.ownedFiles.join(", ")||"(none)"}`),n.readFiles.length>0&&t.push(` Reads: ${n.readFiles.join(", ")}`),n.explicitDeps.length>0&&t.push(` Deps: ${n.explicitDeps.join(", ")}`),n.isAtomic||t.push(` \u26A0\uFE0F Should split: ${n.suggestedSplit?.join("; ")}`),t.join(`
127
- `)}function un(n){let t=n.filter(o=>o.isAtomic),e=n.filter(o=>!o.isAtomic),s=`=== Deliverables Report ===
125
+ `+z(e);return t}function Q(n,t){let e=[...t];for(let s of n.children){e.push(...s.codeBlocks);for(let o of s.children)e.push(...Q(o,[]))}return e}function en(n){let t=n.split(`
126
+ `);for(let e of t){let s=e.trim();if(!s||/^-{3,}$/.test(s)||/^\*\*[^*]+\*\*$/.test(s)&&s.split(/\s+/).length<=3)continue;if(s.split(/\s+/).filter(r=>r.length>0).length>3)return s.length>150?s.slice(0,147)+"...":s}return""}function tn(n,t,e=3e3){let s=z(n);if(s.length<=e||n.children.length<3)return s.slice(0,e);let o=[],r=n.content.trim();r&&o.push(r.slice(0,300));for(let c=0;c<n.children.length;c++){let l=n.children[c],u=l.title,d=en(l.content),p=(l.fileReferences||[]).filter(h=>t.includes(h)),m=`${c+1}. ${u}`;p.length>0&&(m+=` (${p.join(", ")})`),d&&(m+=` \u2014 ${d}`),o.push(m)}let i=0,a=[];for(let c of o){if(i+c.length+1>e&&a.length>0)break;a.push(c),i+=c.length+1}return a.join(`
127
+ `)}function nn(n,t){let e=new Set,s=z(n),o=je(s),r=o.match(/reads:\s*\[([^\]]+)\]/i);if(r){let l=r[1].split(",").map(u=>u.trim().replace(/[`"']/g,""));for(let u of l)u&&u.includes(".")&&!t.includes(u)&&e.add(u)}let i=Fe(o);for(let l of i.reads)t.includes(l)||e.add(l);let a=Q(n,n.codeBlocks),c=_e(a,t);for(let l of c)t.includes(l)||e.add(l);return[...e]}function Ae(n){let t=new Map;for(let e of n){let s=Gt(e);t.has(s)||t.set(s,[]),t.get(s).push(e)}return t}function De(n){if(n._fromYaml)return{split:!1,reasons:[]};let e=[];n.ownedFiles.length>4&&e.push(`Owns ${n.ownedFiles.length} files (max recommended: 4)`);let s=(n.description.match(/\band\b/gi)??[]).length;if(s>2&&e.push(`Description has ${s} "and" conjunctions (suggests multiple tasks)`),n.ownedFiles.length>1){let o=Ae(n.ownedFiles);if(o.size>1){let r=[...o.keys()].join(", ");e.push(`Files belong to ${o.size} different concerns (${r})`)}}return{split:e.length>0,reasons:e}}function sn(n){let t=K(n.name,n.plan||"");return{id:n.id,name:n.name,description:n.plan||"",category:t,ownedFiles:n.owns||[],readFiles:n.reads||[],explicitDeps:n.deps||[],codeExamples:[],isAtomic:!0,_fromYaml:!0,_verify:n.verify,_setup:n.setup}}function on(n,t,e){let s=[],o=Y(n.sections);for(let r of o){let i=ae(r);if(e){let a=r.codeBlocks.filter(c=>c.language==="yaml"||c.language==="yml");e.yamlBlocksFound+=a.length,e.yamlBlocksParsed+=i.length}for(let a of i){t&&!a.id.startsWith(t)&&(a.id=`${t}-${a.id}`);let c=sn(a),l=De(c);l.split&&(c.isAtomic=!1,c.suggestedSplit=l.reasons),s.push(c)}}return s}function rn(n){let t=Y(n.sections);for(let e of t)if(ae(e).length>0)return!0;return!1}function an(n){if(["test plan","implementation order","security checklist","gap inventory","task order","dependency order","execution order","deployment order","wave order"].some(r=>n.includes(r)))return!0;let e=["checklist","inventory","roadmap","timeline","schedule"],s=n.split(/[\s:]+/).filter(r=>r.length>0),o=s[s.length-1]??"";return!!e.includes(o)}function cn(n,t={}){let{deliverableLevel:e=2,prefix:s,preferYaml:o=!0,diagnostics:r}=t;if(o&&rn(n)){r&&(r.extractionPath="yaml");let l=on(n,s,r);return r&&(r.deliverableCount=l.length),l}if(r){let l=Y(n.sections);for(let u of l)r.yamlBlocksFound+=u.codeBlocks.filter(d=>d.language==="yaml"||d.language==="yml").length;r.extractionPath="markdown"}let i=[],a=V(n.sections,e);if(r)for(let l of[2,3,4])r.sectionsFound[l]=V(n.sections,l).length;for(let l of a){let S=function(_){for(let j of _.fileReferences)m.includes(j)||h.includes(j)||T&&!C.has(j)||h.push(j);for(let j of _.children)S(j)};var c=S;let u=l.title.toLowerCase(),f=u.split(/[\s:]+/).filter(_=>_.length>0)[0]??"";if(u.includes("overview")&&a.indexOf(l)===0||f==="summary"||u==="summary: task order"||f==="conclusion"||f==="introduction"||f==="context"||f==="background"||f==="appendix"||f==="references"||f==="changelog"||f==="prerequisites"||an(u)){r&&r.sectionsFilteredAsMeta.push(l.title);continue}let p=Qt(l.title,s),m=Zt(l,l.codeBlocks),h=nn(l,m),y=Q(l,l.codeBlocks),C=new Set(_e(y,m)),T=C.size>0;for(let _ of l.children)S(_);let x=z(l),g=K(l.title,x),w={id:p,name:l.title,description:tn(l,m),category:g,ownedFiles:m,readFiles:h,explicitDeps:l.explicitDeps,codeExamples:y,isAtomic:!0,childCount:l.children.length},$e=De(w);$e.split&&(w.isAtomic=!1,w.suggestedSplit=$e.reasons),i.push(w)}return r&&(r.deliverableCount=i.length),i}function ln(n,t){let e=(n.language||"").toLowerCase(),s=n.code.toLowerCase();switch(t){case"migrations":return e==="sql"||s.includes("create table")||s.includes("alter table");case"types":return(e==="typescript"||e==="ts")&&(s.includes("export type ")||s.includes("export interface ")||s.includes("z.object"));case"tests":return s.includes("describe(")||s.includes("it(")||s.includes("expect(");case"docs":return e==="markdown"||e==="md";case"styles":return e==="css"||e==="scss"||e==="less"||e==="sass";case"core":return(e==="typescript"||e==="ts"||e==="javascript"||e==="js")&&!s.includes("export type ")&&!s.includes("export interface ")&&!s.includes("describe(")&&!s.includes("it(");default:return!1}}function un(n){if(n._fromYaml)return[{...n,isAtomic:!0}];let e=Ae(n.ownedFiles);if(e.size<=1)return[{...n,isAtomic:!0}];let s=[],o=null,r=0;for(let i of Yt){let a=e.get(i);if(!a||a.length===0)continue;r++;let c=`${n.id}-${i}`,l=`${n.name} (${i})`,u=Kt(n.description,i,a),d=[];r===1&&n.explicitDeps.length>0&&d.push(...n.explicitDeps),o&&d.push(o);let f=[];switch(i){case"types":break;case"core":case"migrations":f=[...n.readFiles];break;case"tests":f=[...e.get("core")||[]];break;case"docs":f=[...e.get("core")||e.get("types")||[]];break}let p=n.codeExamples.filter(m=>m.filename&&a.some(h=>m.filename===h)?!0:m.filename?!1:ln(m,i));s.push({id:c,name:l,description:u,category:n.category,ownedFiles:a,readFiles:f,explicitDeps:d,codeExamples:p,isAtomic:!0}),o=c}return s}function dn(n){let t=[];for(let e of n)e.isAtomic?t.push(e):t.push(...un(e));return t}function Re(n){let t=[];return t.push(`${n.id}:`),t.push(` Name: ${n.name}`),t.push(` Category: ${n.category}`),t.push(` Owns: ${n.ownedFiles.join(", ")||"(none)"}`),n.readFiles.length>0&&t.push(` Reads: ${n.readFiles.join(", ")}`),n.explicitDeps.length>0&&t.push(` Deps: ${n.explicitDeps.join(", ")}`),n.isAtomic||t.push(` \u26A0\uFE0F Should split: ${n.suggestedSplit?.join("; ")}`),t.join(`
128
+ `)}function fn(n){let t=n.filter(o=>o.isAtomic),e=n.filter(o=>!o.isAtomic),s=`=== Deliverables Report ===
128
129
 
129
130
  `;if(s+=`Total: ${n.length} deliverables
130
131
  `,s+=` ${t.length} atomic (ready for streams)
@@ -138,22 +139,23 @@ Files: ${e.join(", ")}`}function Jt(n,t){let e=n.toLowerCase().replace(/[^a-z0-9
138
139
 
139
140
  `;for(let o of t)s+=Re(o)+`
140
141
 
141
- `;return s}var De=["-types","-migrations","-core","-tests","-docs"];function le(n,t){let e=De.find(a=>n.id.endsWith(a));if(!e)return n;let s=n.id.slice(0,-e.length),o=t.filter(a=>De.some(c=>a.id===`${s}${c}`));if(o.length<=1)return n;let r=o.find(a=>a.id===`${s}-core`);if(r)return r;let i=["-migrations","-types"];for(let a of i){let c=o.find(l=>l.id===`${s}${a}`);if(c)return c}return n}function dn(n,t){let e=n.toLowerCase().trim(),s=t.find(c=>c.id===n);if(s)return s;let o=t.find(c=>c.name.toLowerCase()===e);if(o)return le(o,t);let r=t.find(c=>c.id.includes(e)||e.includes(c.id));if(r)return le(r,t);let i=e.split(/[\s-_]+/).filter(c=>c.length>2),a=t.find(c=>{let l=c.name.toLowerCase().split(/[\s-_]+/);return i.filter(d=>l.some(f=>f.includes(d)||d.includes(f))).length>=i.length*.5});if(a)return le(a,t)}function fn(n){let t=`${n.name} ${n.description}`.toLowerCase();return/\b(cleanup|clean\s*up|remove|delete|drop)\b/.test(t)}function pn(n){let t=[],e=new Map;for(let r of n)if(!fn(r))for(let i of r.ownedFiles)e.set(i,r);for(let r of n)for(let i of r.readFiles){let a=e.get(i);a&&a.id!==r.id&&t.push({from:r.id,to:a.id,reason:"file-ownership",explanation:`${r.id} reads ${i} which is owned by ${a.id}`})}let s=new Set(t.map(r=>`${r.from}\u2192${r.to}`)),o=new Set;for(let r of t){let i=`${r.to}\u2192${r.from}`;s.has(i)&&(o.add(`${r.from}\u2192${r.to}`),o.add(i))}return t.filter(r=>!o.has(`${r.from}\u2192${r.to}`))}function mn(n){let t=[];for(let e of n){if(e.category==="test"){let s=e.id.replace(/-tests?$/,"").replace(/^tests?-/,""),o=n.find(r=>r.id!==e.id&&r.category==="code"&&(r.id===s||r.id===`${s}-core`||r.id===`${s}-service`||r.id===`${s}-implementation`));o&&t.push({from:e.id,to:o.id,reason:"content-pattern",explanation:`${e.id} (test) depends on ${o.id} (implementation)`})}if(e.category==="docs"||e.category==="tutorial"){let s=e.id.replace(/^docs?-/,"").replace(/-docs?$/,"").replace(/^tutorials?-/,"").replace(/-tutorials?$/,""),o=n.filter(i=>i.id!==e.id&&i.category==="code"),r=o.find(i=>i.id===s)||o.find(i=>i.id===`${s}-service`||i.id===`${s}-core`||i.id===`${s}-implementation`)||o.find(i=>i.id.startsWith(`${s}-`)&&!i.id.includes("types"));r&&t.push({from:e.id,to:r.id,reason:"content-pattern",explanation:`${e.id} (${e.category}) documents ${r.id}`})}}return t}function hn(n,t){let e=[];for(let s of n)for(let o of s.explicitDeps){let r=dn(o,n);if(r&&r.id!==s.id)e.push({from:s.id,to:r.id,reason:"explicit",explanation:`${s.id} explicitly depends on "${o}" (matched ${r.id})`});else if(!r){let i=`Stream '${s.id}': unmatched explicit dep '${o}'`;t?.diagnostics?.unmatchedDeps.push(i),t?.diagnostics?.warnings.push(i)}}return e}function Ne(n){let t=[],e=new Set,s=new Set,o=[];function r(i){e.add(i),s.add(i),o.push(i);let a=n.get(i)||[];for(let c of a)if(!e.has(c))r(c);else if(s.has(c)){let l=o.indexOf(c);if(l!==-1){let u=[...o.slice(l),c];t.push(u)}}o.pop(),s.delete(i)}for(let i of n.keys())e.has(i)||r(i);return t}function gn(n,t,e){let s=0,o=new Set;for(let r of n){let i=[];for(let f=0;f<r.length-1;f++)i.push({from:r[f],to:r[f+1]});let a=[];for(let f of i){let p=t.find(m=>m.from===f.from&&m.to===f.to&&!o.has(`${m.from}\u2192${m.to}`));p&&a.push(p)}if(a.length===0||!a.every(f=>f.reason==="file-ownership"))continue;let l=a.reduce((f,p)=>{let m=e.get(f.from)?.length??0,h=e.get(p.from)?.length??0;return h<m||h===m&&p.from<f.from?p:f}),u=t.indexOf(l);u!==-1&&t.splice(u,1);let d=e.get(l.from);if(d){let f=d.indexOf(l.to);f!==-1&&d.splice(f,1)}o.add(`${l.from}\u2192${l.to}`),s++}return{broken:s}}function yn(n,t){let e=[...hn(n,t),...pn(n),...mn(n)],s=new Set,o=[];for(let a of e){let c=`${a.from}\u2192${a.to}`;s.has(c)||(s.add(c),o.push(a))}let r=new Map;for(let a of n)r.set(a.id,[]);for(let a of o){let c=r.get(a.from)||[];c.includes(a.to)||c.push(a.to),r.set(a.from,c)}let i=Ne(r);if(i.length>0){let{broken:a}=gn(i,o,r);a>0&&(i=Ne(r))}return{dependencies:r,edges:o,cycles:i,isAcyclic:i.length===0}}function wn(n){let t=["=== Dependency Analysis ===",""];if(t.push(`Total edges: ${n.edges.length}`),t.push(`Acyclic: ${n.isAcyclic?"Yes \u2713":"No \u26A0\uFE0F"}`),n.cycles.length>0){t.push(""),t.push("--- Cycles Detected ---");for(let e of n.cycles)t.push(` ${e.join(" \u2192 ")}`)}t.push(""),t.push("--- Dependencies by Deliverable ---");for(let[e,s]of n.dependencies)s.length>0&&t.push(`${e}: ${s.join(", ")}`);t.push(""),t.push("--- Edge Details ---");for(let e of n.edges)t.push(`${e.from} \u2192 ${e.to} (${e.reason})`),t.push(` ${e.explanation}`);return t.join(`
142
- `)}import*as k from"node:fs";import*as $ from"node:path";var We={maxOwnsCount:4,maxReadsCount:4,maxDirectories:2,maxPlanConjunctions:4,warnOnMixedActions:!0,warnOnMixedFileTypes:!0,requireVerifyCommands:!0},ue=class{config;constructor(t=We){this.config=t}analyzeStream(t,e){let s=[],o=e.owns||[],r=e.reads||[],i=e.plan||"",a=e.verify||[],c=o.length,l=r.length,u=this.countDirectories(o),d=this.countConjunctions(i),f=a.length,p=this.detectActionTypes(i),m=this.detectFileTypes([...o,...r]),h={ownsCount:c,readsCount:l,directoriesAffected:u,planConjunctions:d,verifyCommands:f,actionTypes:p,fileTypes:m};c>this.config.maxOwnsCount&&u>this.config.maxDirectories?s.push({type:"high_owns_complexity",severity:"error",message:`Stream owns ${c} files across ${u} directories`,details:`Consider splitting into smaller streams. Threshold: ${this.config.maxOwnsCount} files across ${this.config.maxDirectories} directories`,streamName:t}):c>this.config.maxOwnsCount&&s.push({type:"high_owns_count",severity:"warning",message:`Stream owns ${c} files (threshold: ${this.config.maxOwnsCount})`,details:"Consider splitting into smaller, more focused streams",streamName:t}),l>this.config.maxReadsCount&&s.push({type:"high_reads_count",severity:"warning",message:`Stream reads ${l} files (threshold: ${this.config.maxReadsCount})`,details:"Too many dependencies may indicate unclear scope or context bloat",streamName:t}),d>this.config.maxPlanConjunctions&&s.push({type:"compound_plan",severity:"warning",message:`Plan contains ${d} 'and' conjunctions (threshold: ${this.config.maxPlanConjunctions})`,details:"Complex plans with multiple actions should be split into separate streams",streamName:t}),this.config.warnOnMixedActions&&this.hasMixedActions(p)&&s.push({type:"mixed_actions",severity:"warning",message:"Stream mixes structural changes with content changes",details:`Detected actions: ${p.join(", ")}. Consider separating setup/structure from implementation`,streamName:t}),this.hasUnboundedTutorial(i,o)&&s.push({type:"unbounded_tutorial",severity:"error",message:"Stream appears to create tutorial/documentation without specific file ownership",details:"Tutorial or documentation streams must specify exact files in owns[]",streamName:t}),this.config.warnOnMixedFileTypes&&m.size>3&&s.push({type:"mixed_file_types",severity:"info",message:`Stream touches ${m.size} different file types`,details:`File types: ${Array.from(m).join(", ")}. Consider organizing by concern`,streamName:t}),this.config.requireVerifyCommands&&f===0&&c>0&&s.push({type:"no_verify",severity:"warning",message:"Stream has no verify commands",details:"Add verify commands to ensure implementation correctness",streamName:t}),(!i||i.trim().length===0)&&s.push({type:"empty_plan",severity:"error",message:"Stream has no plan description",details:"Every stream must have a clear plan describing what it does",streamName:t}),this.hasVaguePlan(i)&&s.push({type:"vague_plan",severity:"info",message:"Plan may be too vague or generic",details:"Use specific, actionable language describing exact changes",streamName:t});let y=this.calculateQualityScore(s,h);return{streamName:t,qualityScore:y,issues:s,metrics:h}}analyzeStreams(t){let e=[];for(let[r,i]of Object.entries(t))e.push(this.analyzeStream(r,i));let s=this.countIssuesBySeverity(e),o=this.calculateOverallScore(e);return{streams:e,overallScore:o,totalIssues:s}}countDirectories(t){let e=new Set;for(let s of t){let o=s.substring(0,s.lastIndexOf("/"));o?e.add(o):e.add(".")}return e.size}countConjunctions(t){let s=t.toLowerCase().match(/\band\b/g);return s?s.length:0}detectActionTypes(t){let e=t.toLowerCase(),s=[],o=[{type:"create",pattern:/\b(create|add|implement|build)\b/},{type:"update",pattern:/\b(update|modify|change|edit|refactor)\b/},{type:"delete",pattern:/\b(delete|remove)\b/},{type:"configure",pattern:/\b(configure|setup|install)\b/},{type:"test",pattern:/\b(test|verify)\b/},{type:"document",pattern:/\b(document|write|tutorial)\b/}];for(let{type:r,pattern:i}of o)i.test(e)&&s.push(r);return s}detectFileTypes(t){let e=new Set;for(let s of t){let o=s.substring(s.lastIndexOf(".")+1).toLowerCase();o&&o!==s&&e.add(o)}return e}hasMixedActions(t){let e=["create","delete","configure"],s=["update","document"],o=t.some(i=>e.includes(i)),r=t.some(i=>s.includes(i));return o&&r}hasUnboundedTutorial(t,e){let s=t.toLowerCase();return/\b(tutorial|guide|documentation|example)\b/.test(s)&&e.length===0}hasVaguePlan(t){let e=t.toLowerCase(),s=["various","some","multiple","general","misc","other","stuff","things"];for(let o of s)if(e.includes(o))return!0;return t.trim().split(/\s+/).length<5}calculateQualityScore(t,e){let s=100;for(let o of t)switch(o.severity){case"error":s-=20;break;case"warning":s-=10;break;case"info":s-=5;break}return e.verifyCommands>0&&(s+=5),e.ownsCount>0&&e.ownsCount<=3&&(s+=5),e.planConjunctions===0&&(s+=5),Math.max(0,Math.min(100,s))}calculateOverallScore(t){if(t.length===0)return 0;let e=t.reduce((s,o)=>s+o.qualityScore,0);return Math.round(e/t.length)}countIssuesBySeverity(t){let e={errors:0,warnings:0,info:0};for(let s of t)for(let o of s.issues)switch(o.severity){case"error":e.errors++;break;case"warning":e.warnings++;break;case"info":e.info++;break}return e}};function H(n){return new ue({...We,...n})}import{createLogger as xn}from"../logging.js";var Sn=xn("topology-optimizer");function $n(n){let t=new Map,e=[...n.keys()];function s(o,r){let i=new Set,a=[o];for(;a.length>0;){let c=a.shift();if(!i.has(c)){i.add(c);for(let l of n.get(c)??[])l!==r&&!i.has(l)&&a.push(l)}}return i}for(let o of e){let r=n.get(o)??[],i=[];for(let a of r){let c=r.filter(u=>u!==a),l=!1;for(let u of c)if(s(u,o).has(a)){l=!0;break}l||i.push(a)}t.set(o,i)}return t}function vn(n){let t=new Map,e=new Map;for(let r of n){t.set(r.id,r.deps.length);for(let i of r.deps)e.has(i)||e.set(i,[]),e.get(i).push(r.id);e.has(r.id)||e.set(r.id,[])}let s=n.filter(r=>r.deps.length===0).map(r=>r.id),o=0;for(;s.length>0;){let r=s.shift();o++;for(let i of e.get(r)??[])t.set(i,(t.get(i)??1)-1),t.get(i)===0&&s.push(i)}return o===n.length}function Cn(n){let t=[],e=new Set,s=new Map(n.map(o=>[o.id,[...o.deps]]));for(;s.size>0;){let o=[];for(let[r,i]of s)i.every(a=>e.has(a))&&o.push(r);if(o.length===0)break;for(let r of o)s.delete(r),e.add(r);t.push(o)}return t}function de(n){let t=[],e=n.reduce((f,p)=>f+p.deps.length,0),s=new Map(n.map(f=>[f.id,[...f.deps]])),o=$n(s);t.push("transitive-reduction");let r=n.map(f=>({...f,deps:o.get(f.id)??f.deps})),i=r.reduce((f,p)=>f+p.deps.length,0),a=e-i;a>0&&Sn.info({edgesRemoved:a,original:e},"transitive_reduction_applied");let c=Cn(r),l=vn(r),u=Math.max(0,...c.map(f=>f.length)),d=c.length===1?"parallel":u===1?"sequential":"mixed";return{streams:r,waves:c,report:{originalEdgeCount:e,edgesRemoved:a,waveCount:c.length,classification:d,passesApplied:t},isValid:l}}var kn={code:12e4,test:9e4,docs:6e4,tutorial:9e4,"integration-guide":9e4,"api-reference":6e4,migration:18e4,other:12e4};function bn(n,t=5,e=4e3){let s=n.description.trim();if(s.split(/\s+/).filter(r=>r.length>0).length<t){let r=Tn(n.category),i=n.ownedFiles.join(", ")||"the target files";s=`${r} ${n.name}. ${s}. Target: ${i}`}if(n.codeExamples.length>0){let r=[],i=0;for(let a of n.codeExamples){let c=`\`\`\`${a.language||""}
142
+ `;return s}var Le=["-types","-migrations","-core","-tests","-docs"];function le(n,t){let e=Le.find(a=>n.id.endsWith(a));if(!e)return n;let s=n.id.slice(0,-e.length),o=t.filter(a=>Le.some(c=>a.id===`${s}${c}`));if(o.length<=1)return n;let r=o.find(a=>a.id===`${s}-core`);if(r)return r;let i=["-migrations","-types"];for(let a of i){let c=o.find(l=>l.id===`${s}${a}`);if(c)return c}return n}function pn(n,t){let e=n.toLowerCase().trim(),s=t.find(c=>c.id===n);if(s)return s;let o=t.find(c=>c.name.toLowerCase()===e);if(o)return le(o,t);let r=t.find(c=>c.id.includes(e)||e.includes(c.id));if(r)return le(r,t);let i=e.split(/[\s-_]+/).filter(c=>c.length>2),a=t.find(c=>{let l=c.name.toLowerCase().split(/[\s-_]+/);return i.filter(d=>l.some(f=>f.includes(d)||d.includes(f))).length>=i.length*.5});if(a)return le(a,t)}function mn(n){let t=`${n.name} ${n.description}`.toLowerCase();return/\b(cleanup|clean\s*up|remove|delete|drop)\b/.test(t)}function hn(n){let t=[],e=new Map;for(let r of n)if(!mn(r))for(let i of r.ownedFiles)e.set(i,r);for(let r of n)for(let i of r.readFiles){let a=e.get(i);a&&a.id!==r.id&&t.push({from:r.id,to:a.id,reason:"file-ownership",explanation:`${r.id} reads ${i} which is owned by ${a.id}`})}let s=new Set(t.map(r=>`${r.from}\u2192${r.to}`)),o=new Set;for(let r of t){let i=`${r.to}\u2192${r.from}`;s.has(i)&&(o.add(`${r.from}\u2192${r.to}`),o.add(i))}return t.filter(r=>!o.has(`${r.from}\u2192${r.to}`))}function gn(n){let t=[];for(let e of n){if(e.category==="test"){let s=e.id.replace(/-tests?$/,"").replace(/^tests?-/,""),o=n.find(r=>r.id!==e.id&&r.category==="code"&&(r.id===s||r.id===`${s}-core`||r.id===`${s}-service`||r.id===`${s}-implementation`));o&&t.push({from:e.id,to:o.id,reason:"content-pattern",explanation:`${e.id} (test) depends on ${o.id} (implementation)`})}if(e.category==="docs"||e.category==="tutorial"){let s=e.id.replace(/^docs?-/,"").replace(/-docs?$/,"").replace(/^tutorials?-/,"").replace(/-tutorials?$/,""),o=n.filter(i=>i.id!==e.id&&i.category==="code"),r=o.find(i=>i.id===s)||o.find(i=>i.id===`${s}-service`||i.id===`${s}-core`||i.id===`${s}-implementation`)||o.find(i=>i.id.startsWith(`${s}-`)&&!i.id.includes("types"));r&&t.push({from:e.id,to:r.id,reason:"content-pattern",explanation:`${e.id} (${e.category}) documents ${r.id}`})}}return t}function yn(n,t){let e=[];for(let s of n)for(let o of s.explicitDeps){let r=pn(o,n);if(r&&r.id!==s.id)e.push({from:s.id,to:r.id,reason:"explicit",explanation:`${s.id} explicitly depends on "${o}" (matched ${r.id})`});else if(!r){let i=`Stream '${s.id}': unmatched explicit dep '${o}'`;t?.diagnostics?.unmatchedDeps.push(i),t?.diagnostics?.warnings.push(i)}}return e}function Ne(n){let t=[],e=new Set,s=new Set,o=[];function r(i){e.add(i),s.add(i),o.push(i);let a=n.get(i)||[];for(let c of a)if(!e.has(c))r(c);else if(s.has(c)){let l=o.indexOf(c);if(l!==-1){let u=[...o.slice(l),c];t.push(u)}}o.pop(),s.delete(i)}for(let i of n.keys())e.has(i)||r(i);return t}function wn(n,t,e){let s=0,o=new Set;for(let r of n){let i=[];for(let f=0;f<r.length-1;f++)i.push({from:r[f],to:r[f+1]});let a=[];for(let f of i){let p=t.find(m=>m.from===f.from&&m.to===f.to&&!o.has(`${m.from}\u2192${m.to}`));p&&a.push(p)}if(a.length===0||!a.every(f=>f.reason==="file-ownership"))continue;let l=a.reduce((f,p)=>{let m=e.get(f.from)?.length??0,h=e.get(p.from)?.length??0;return h<m||h===m&&p.from<f.from?p:f}),u=t.indexOf(l);u!==-1&&t.splice(u,1);let d=e.get(l.from);if(d){let f=d.indexOf(l.to);f!==-1&&d.splice(f,1)}o.add(`${l.from}\u2192${l.to}`),s++}return{broken:s}}function xn(n,t){let e=[...yn(n,t),...hn(n),...gn(n)],s=new Set,o=[];for(let a of e){let c=`${a.from}\u2192${a.to}`;s.has(c)||(s.add(c),o.push(a))}let r=new Map;for(let a of n)r.set(a.id,[]);for(let a of o){let c=r.get(a.from)||[];c.includes(a.to)||c.push(a.to),r.set(a.from,c)}let i=Ne(r);if(i.length>0){let{broken:a}=wn(i,o,r);a>0&&(i=Ne(r))}return{dependencies:r,edges:o,cycles:i,isAcyclic:i.length===0}}function Sn(n){let t=["=== Dependency Analysis ===",""];if(t.push(`Total edges: ${n.edges.length}`),t.push(`Acyclic: ${n.isAcyclic?"Yes \u2713":"No \u26A0\uFE0F"}`),n.cycles.length>0){t.push(""),t.push("--- Cycles Detected ---");for(let e of n.cycles)t.push(` ${e.join(" \u2192 ")}`)}t.push(""),t.push("--- Dependencies by Deliverable ---");for(let[e,s]of n.dependencies)s.length>0&&t.push(`${e}: ${s.join(", ")}`);t.push(""),t.push("--- Edge Details ---");for(let e of n.edges)t.push(`${e.from} \u2192 ${e.to} (${e.reason})`),t.push(` ${e.explanation}`);return t.join(`
143
+ `)}import*as $ from"node:fs";import*as v from"node:path";var We={maxOwnsCount:4,maxReadsCount:4,maxDirectories:2,maxPlanConjunctions:4,warnOnMixedActions:!0,warnOnMixedFileTypes:!0,requireVerifyCommands:!0},ue=class{config;constructor(t=We){this.config=t}analyzeStream(t,e){let s=[],o=e.owns||[],r=e.reads||[],i=e.plan||"",a=e.verify||[],c=o.length,l=r.length,u=this.countDirectories(o),d=this.countConjunctions(i),f=a.length,p=this.detectActionTypes(i),m=this.detectFileTypes([...o,...r]),h={ownsCount:c,readsCount:l,directoriesAffected:u,planConjunctions:d,verifyCommands:f,actionTypes:p,fileTypes:m};c>this.config.maxOwnsCount&&u>this.config.maxDirectories?s.push({type:"high_owns_complexity",severity:"error",message:`Stream owns ${c} files across ${u} directories`,details:`Consider splitting into smaller streams. Threshold: ${this.config.maxOwnsCount} files across ${this.config.maxDirectories} directories`,streamName:t}):c>this.config.maxOwnsCount&&s.push({type:"high_owns_count",severity:"warning",message:`Stream owns ${c} files (threshold: ${this.config.maxOwnsCount})`,details:"Consider splitting into smaller, more focused streams",streamName:t}),l>this.config.maxReadsCount&&s.push({type:"high_reads_count",severity:"warning",message:`Stream reads ${l} files (threshold: ${this.config.maxReadsCount})`,details:"Too many dependencies may indicate unclear scope or context bloat",streamName:t}),d>this.config.maxPlanConjunctions&&s.push({type:"compound_plan",severity:"warning",message:`Plan contains ${d} 'and' conjunctions (threshold: ${this.config.maxPlanConjunctions})`,details:"Complex plans with multiple actions should be split into separate streams",streamName:t}),this.config.warnOnMixedActions&&this.hasMixedActions(p)&&s.push({type:"mixed_actions",severity:"warning",message:"Stream mixes structural changes with content changes",details:`Detected actions: ${p.join(", ")}. Consider separating setup/structure from implementation`,streamName:t}),this.hasUnboundedTutorial(i,o)&&s.push({type:"unbounded_tutorial",severity:"error",message:"Stream appears to create tutorial/documentation without specific file ownership",details:"Tutorial or documentation streams must specify exact files in owns[]",streamName:t}),this.config.warnOnMixedFileTypes&&m.size>3&&s.push({type:"mixed_file_types",severity:"info",message:`Stream touches ${m.size} different file types`,details:`File types: ${Array.from(m).join(", ")}. Consider organizing by concern`,streamName:t}),this.config.requireVerifyCommands&&f===0&&c>0&&s.push({type:"no_verify",severity:"warning",message:"Stream has no verify commands",details:"Add verify commands to ensure implementation correctness",streamName:t}),(!i||i.trim().length===0)&&s.push({type:"empty_plan",severity:"error",message:"Stream has no plan description",details:"Every stream must have a clear plan describing what it does",streamName:t}),this.hasVaguePlan(i)&&s.push({type:"vague_plan",severity:"info",message:"Plan may be too vague or generic",details:"Use specific, actionable language describing exact changes",streamName:t});let y=this.calculateQualityScore(s,h);return{streamName:t,qualityScore:y,issues:s,metrics:h}}analyzeStreams(t){let e=[];for(let[r,i]of Object.entries(t))e.push(this.analyzeStream(r,i));let s=this.countIssuesBySeverity(e),o=this.calculateOverallScore(e);return{streams:e,overallScore:o,totalIssues:s}}countDirectories(t){let e=new Set;for(let s of t){let o=s.substring(0,s.lastIndexOf("/"));o?e.add(o):e.add(".")}return e.size}countConjunctions(t){let s=t.toLowerCase().match(/\band\b/g);return s?s.length:0}detectActionTypes(t){let e=t.toLowerCase(),s=[],o=[{type:"create",pattern:/\b(create|add|implement|build)\b/},{type:"update",pattern:/\b(update|modify|change|edit|refactor)\b/},{type:"delete",pattern:/\b(delete|remove)\b/},{type:"configure",pattern:/\b(configure|setup|install)\b/},{type:"test",pattern:/\b(test|verify)\b/},{type:"document",pattern:/\b(document|write|tutorial)\b/}];for(let{type:r,pattern:i}of o)i.test(e)&&s.push(r);return s}detectFileTypes(t){let e=new Set;for(let s of t){let o=s.substring(s.lastIndexOf(".")+1).toLowerCase();o&&o!==s&&e.add(o)}return e}hasMixedActions(t){let e=["create","delete","configure"],s=["update","document"],o=t.some(i=>e.includes(i)),r=t.some(i=>s.includes(i));return o&&r}hasUnboundedTutorial(t,e){let s=t.toLowerCase();return/\b(tutorial|guide|documentation|example)\b/.test(s)&&e.length===0}hasVaguePlan(t){let e=t.toLowerCase(),s=["various","some","multiple","general","misc","other","stuff","things"];for(let o of s)if(e.includes(o))return!0;return t.trim().split(/\s+/).length<5}calculateQualityScore(t,e){let s=100;for(let o of t)switch(o.severity){case"error":s-=20;break;case"warning":s-=10;break;case"info":s-=5;break}return e.verifyCommands>0&&(s+=5),e.ownsCount>0&&e.ownsCount<=3&&(s+=5),e.planConjunctions===0&&(s+=5),Math.max(0,Math.min(100,s))}calculateOverallScore(t){if(t.length===0)return 0;let e=t.reduce((s,o)=>s+o.qualityScore,0);return Math.round(e/t.length)}countIssuesBySeverity(t){let e={errors:0,warnings:0,info:0};for(let s of t)for(let o of s.issues)switch(o.severity){case"error":e.errors++;break;case"warning":e.warnings++;break;case"info":e.info++;break}return e}};function H(n){return new ue({...We,...n})}import{createLogger as $n}from"../logging.js";var vn=$n("topology-optimizer");function Cn(n){let t=new Map,e=[...n.keys()];function s(o,r){let i=new Set,a=[o];for(;a.length>0;){let c=a.shift();if(!i.has(c)){i.add(c);for(let l of n.get(c)??[])l!==r&&!i.has(l)&&a.push(l)}}return i}for(let o of e){let r=n.get(o)??[],i=[];for(let a of r){let c=r.filter(u=>u!==a),l=!1;for(let u of c)if(s(u,o).has(a)){l=!0;break}l||i.push(a)}t.set(o,i)}return t}function kn(n){let t=new Map,e=new Map;for(let r of n){t.set(r.id,r.deps.length);for(let i of r.deps)e.has(i)||e.set(i,[]),e.get(i).push(r.id);e.has(r.id)||e.set(r.id,[])}let s=n.filter(r=>r.deps.length===0).map(r=>r.id),o=0;for(;s.length>0;){let r=s.shift();o++;for(let i of e.get(r)??[])t.set(i,(t.get(i)??1)-1),t.get(i)===0&&s.push(i)}return o===n.length}function bn(n){let t=[],e=new Set,s=new Map(n.map(o=>[o.id,[...o.deps]]));for(;s.size>0;){let o=[];for(let[r,i]of s)i.every(a=>e.has(a))&&o.push(r);if(o.length===0)break;for(let r of o)s.delete(r),e.add(r);t.push(o)}return t}function de(n){let t=[],e=n.reduce((f,p)=>f+p.deps.length,0),s=new Map(n.map(f=>[f.id,[...f.deps]])),o=Cn(s);t.push("transitive-reduction");let r=n.map(f=>({...f,deps:o.get(f.id)??f.deps})),i=r.reduce((f,p)=>f+p.deps.length,0),a=e-i;a>0&&vn.info({edgesRemoved:a,original:e},"transitive_reduction_applied");let c=bn(r),l=kn(r),u=Math.max(0,...c.map(f=>f.length)),d=c.length===1?"parallel":u===1?"sequential":"mixed";return{streams:r,waves:c,report:{originalEdgeCount:e,edgesRemoved:a,waveCount:c.length,classification:d,passesApplied:t},isValid:l}}var Tn={code:12e4,test:9e4,docs:6e4,tutorial:9e4,"integration-guide":9e4,"api-reference":6e4,migration:18e4,other:12e4};function En(n,t=5,e=4e3){let s=n.description.trim();if(s.split(/\s+/).filter(r=>r.length>0).length<t){let r=On(n.category),i=n.ownedFiles.join(", ")||"the target files";s=`${r} ${n.name}. ${s}. Target: ${i}`}if(n.codeExamples.length>0){let r=[],i=0;for(let a of n.codeExamples){let c=`\`\`\`${a.language||""}
143
144
  ${a.code}
144
145
  \`\`\``;if(i+c.length>e)break;r.push(c),i+=c.length}r.length>0&&(s+=`
145
146
 
146
147
  Reference code:
147
148
  `+r.join(`
148
149
 
149
- `))}return s}function Tn(n){switch(n){case"code":return"Implement";case"test":return"Write tests for";case"docs":return"Document";case"tutorial":return"Create tutorial for";case"integration-guide":return"Write integration guide for";case"api-reference":return"Generate API reference for";case"migration":return"Migrate";default:return"Complete"}}function Pn(n,t="npm"){let e=[];if(n.ownedFiles.some(o=>o.endsWith(".ts")||o.endsWith(".tsx")||o.endsWith(".js")||o.endsWith(".jsx"))&&e.push(F(t,"build")),n.category==="test"){let o=n.ownedFiles.find(r=>r.includes(".test."));o?e.push(re(t,o)):e.push(re(t))}return e}function En(n,t,e,s="npm"){let o=[],r=[];for(let i of n){if(t!=="test"&&/vitest|jest/.test(i)&&!/build|tsc/.test(i)){r.push(`Verify command '${i}' uses a test runner but stream category is '${t}'. Replaced with '${F(s,"build")}'.`),o.push(F(s,"build"));continue}let a=i.match(/(?:vitest|jest)\s+(?:run\s+)?(\S+\.(?:ts|tsx|js|jsx))/);if(a){let c=a[1];if(!e.some(u=>c.includes(u)||u.includes(c))){r.push(`Verify command references '${c}' which is not in this stream's owned files. Replaced with '${F(s,"build")}'.`),o.push(F(s,"build"));continue}}o.push(i)}return{commands:[...new Set(o)],warnings:r}}function On(n,t,e={}){let{minPlanLength:s=5,estimateTimeout:o=!0,defaultVerify:r}=e,i=n,a=e.projectDir?U(e.projectDir):"npm",c=i._verify||r||Pn(n,a),l=i._setup,{commands:u,warnings:d}=En(c,n.category,n.ownedFiles,a);if(d.length>0&&e.diagnostics)for(let h of d)e.diagnostics.warnings.push(`${n.id}: verify_warning - ${h}`);let p=(i._verify!==void 0||i._setup!==void 0)&&n.description.length>=s?n.description:bn(n,s),m={name:n.name,deps:t.length>0?t:void 0,owns:n.ownedFiles.length>0?n.ownedFiles:void 0,reads:n.readFiles.length>0?n.readFiles:void 0,plan:p,verify:u.length>0?u:void 0,setup:l&&l.length>0?l:void 0};if(o){let h=kn[n.category],y=Math.max(1,Math.ceil(n.ownedFiles.length/2));m.timeoutMs=h*y}return m}function Mn(n,t,e={}){let{validateAntiPatterns:s=!0}=e,o={},r=[],i=[];t.isAcyclic||r.push(`Dependency graph has cycles: ${t.cycles.map(l=>l.join(" \u2192 ")).join("; ")}`);let a=s?H():null;for(let l of n){let u=t.dependencies.get(l.id)||[],d=On(l,u,e);if(a){let h=a.analyzeStream(l.id,{name:d.name,deps:d.deps||[],owns:d.owns||[],reads:d.reads||[],plan:d.plan,verify:d.verify||[]});if(h.issues.length>0){i.push(h);for(let y of h.issues)r.push(`${l.id}: ${y.type} - ${y.message}`)}}let f=l.childCount,p=d.plan?.length??0,m=(d.owns||[]).length;if(f!==void 0&&f>=5&&p>2500?r.push(`${l.id}: too_complex - ${f} sub-sections, ${m} owned files, ~${p} char plan. Consider: use YAML stream definitions for manual decomposition, or set deliverable_level: 3`):f!==void 0&&f>=3&&p>3500&&r.push(`${l.id}: too_complex - ${f} sub-sections, ~${p} char plan. Consider: use YAML stream definitions for finer control`),e.projectDir){let h=d.owns||[];for(let y of h)try{let v=$.join(e.projectDir,y),S=k.readFileSync(v,"utf-8").split(`
150
- `).length;if(S>800){let x=`${l.id}: large_file_critical - ${y} is ${S} lines (>800). Consider splitting this stream to reduce file scope`;r.push(x),e.diagnostics&&e.diagnostics.warnings.push(x)}else if(S>500&&h.length>=3){let x=`${l.id}: large_file_risk - ${y} is ${S} lines, stream owns ${h.length} files. Consider splitting to reduce complexity`;r.push(x),e.diagnostics&&e.diagnostics.warnings.push(x)}}catch{}}if(l.ownedFiles.length===0){let h=`Stream '${l.id}' has no owned files. It can read but not write. If this is unintentional, check your Create:/Modify: syntax (must use backtick-quoted paths).`;r.push(h),e.diagnostics&&e.diagnostics.warnings.push(h)}o[l.id]=d}if(e.projectDir){let l=_n(o,e.projectDir);r.push(...l.warnings);for(let[u,d]of Object.entries(l.streams))o[u]=d}let c=Object.entries(o).map(([l,u])=>({id:l,owns:u.owns??[],reads:u.reads??[],deps:u.deps??[]}));if(c.length>0){let l=de(c);e.diagnostics&&(e.diagnostics.topologyReport=l.report);for(let u of l.streams)o[u.id]&&(o[u.id]={...o[u.id],deps:u.deps.length>0?u.deps:void 0});l.report.edgesRemoved>0&&r.push(`Topology optimization: removed ${l.report.edgesRemoved} redundant edge(s)`)}return{streams:o,warnings:r,antiPatterns:s?i:void 0,count:n.length}}function In(n){let t=["=== Generated Streams ===",""];if(t.push(`Total: ${n.count} streams`),n.warnings.length>0){t.push(""),t.push("--- Warnings ---");for(let e of n.warnings)t.push(`\u26A0\uFE0F ${e}`)}t.push(""),t.push("--- Stream Definitions ---");for(let[e,s]of Object.entries(n.streams))t.push(""),t.push(`${e}:`),t.push(` name: ${s.name}`),s.deps&&s.deps.length>0&&t.push(` deps: [${s.deps.join(", ")}]`),s.owns&&s.owns.length>0&&t.push(` owns: [${s.owns.join(", ")}]`),s.reads&&s.reads.length>0&&t.push(` reads: [${s.reads.join(", ")}]`),s.plan&&t.push(` plan: ${s.plan.slice(0,80)}${s.plan.length>80?"...":""}`),s.verify&&s.verify.length>0&&t.push(` verify: [${s.verify.join(", ")}]`),s.timeoutMs&&t.push(` timeoutMs: ${s.timeoutMs}`);return t.join(`
151
- `)}function Rn(n){return n.streams}var Ue=/(?:npm\s+install|pnpm\s+add|yarn\s+add|pip\s+install|bun\s+add)\s+(.+)/gi,ze=/install\s+(?:dependencies|packages)\s*:\s*\n((?:\s+[-*]\s+.+\n?)+)/gi;function He(n){let t=n.replace(/^\s*[-*]\s*/,"").trim();return t=t.replace(/\s*\(.*?\)\s*$/,"").trim(),t=t.replace(/[`"']/g,"").trim(),/^@?[a-z0-9][\w./-]*$/i.test(t)?t:null}function Fn(n,t="npm"){let e=new Set;for(let s of Object.values(n)){let o=s.plan??"",r;for(Ue.lastIndex=0;(r=Ue.exec(o))!==null;){let i=r[1].split(/\s+/).filter(a=>a&&!a.startsWith("-"));for(let a of i){let c=He(a);c&&e.add(c)}}for(ze.lastIndex=0;(r=ze.exec(o))!==null;){let i=r[1].split(`
152
- `);for(let a of i){let c=He(a);c&&e.add(c)}}}return e.size===0?[]:[Ce(t,[...e])]}function _n(n,t){let e=[];if(!t)return{streams:n,warnings:e};let s={},o=new Set;for(let r of Object.values(n))for(let i of r.owns||[])o.add(i);for(let[r,i]of Object.entries(n)){let a=[...i.owns||[]],c=[...i.reads||[]];for(let u of a){let d=$.join(t,u);if(!k.existsSync(d)){let f=$.dirname(d);k.existsSync(f)||e.push(`${r}: path_not_found - owns path "${u}" not found and parent directory does not exist`)}}let l=[];for(let u=0;u<c.length;u++){let d=c[u];if(o.has(d))continue;let f=$.join(t,d);if(!k.existsSync(f)){let p=$.basename(d),m=jn(t,p);m.matches===1&&m.path?(e.push(`${r}: path_corrected - reads path "${d}" corrected to "${m.path}" (only match found)`),c[u]=m.path):m.matches>1?e.push(`${r}: path_ambiguous - reads path "${d}" not found, ${m.matches} candidates exist`):(e.push(`${r}: path_removed - reads path "${d}" not found on disk, removed from reads`),l.push(u))}}for(let u=l.length-1;u>=0;u--)c.splice(l[u],1);s[r]={...i,owns:a,reads:c}}return{streams:s,warnings:e}}function jn(n,t){let e=[],s=["src","tests","lib","scripts"];for(let r of s){let i=$.join(n,r);k.existsSync(i)&&Be(i,t,e)}let o=$.join(n,t);return k.existsSync(o)&&k.statSync(o).isFile()&&e.push(t),e.length===1?{matches:1,path:e[0]}:{matches:e.length}}function Be(n,t,e,s){let o=s||$.dirname(n);try{let r=k.readdirSync(n,{withFileTypes:!0});for(let i of r){if(i.name==="node_modules"||i.name===".git"||i.name==="dist")continue;let a=$.join(n,i.name);i.isDirectory()?Be(a,t,e,o):i.name===t&&e.push($.relative(o,a))}}catch{}}function An(n,t,e,s,o){let r=new Set;for(let d of Object.values(n))for(let f of d.owns??[])r.add(f);let i=0;if(o)for(let d of Object.values(o))d.estimatedCostUsd&&(i+=d.estimatedCostUsd);let a=t.map(d=>({number:d.number,streams:d.streams.map(f=>{let p=n[f],m=o?.[f];return{id:f,name:p?.name??f,owns:p?.owns??[],reads:p?.reads??[],deps:p?.deps??[],provider:m?.provider,model:m?.model,estimatedCostUsd:m?.estimatedCostUsd,modelFallback:m?.fallback}})})),c=[...e];if(s)for(let d of s)c.push(`Sequential edit conflict: ${d.suggestion}`);if(o)for(let[d,f]of Object.entries(o))f.fallback&&c.push(`${d}: ${f.fallback}`);let l=100;c.length>0&&(l-=c.length*5);let u=Object.values(n).filter(d=>!d.owns||d.owns.length===0).length;return l-=u*10,l=Math.max(0,Math.min(100,l)),{summary:{streamCount:Object.keys(n).length,waveCount:t.length,fileCount:r.size,estimatedCostUsd:i>0?i:void 0},waves:a,warnings:c,qualityScore:l}}function Ln(n){return!n||n===0?"":n<.01?" ~< $0.01":` ~$${n.toFixed(2)}`}function Dn(n){let t=[],e=n.summary.estimatedCostUsd?`, est. ~$${n.summary.estimatedCostUsd.toFixed(2)}`:"";t.push(`Plan Preview: ${n.summary.streamCount} streams, ${n.summary.waveCount} waves, ${n.summary.fileCount} files${e}`),t.push(`Quality Score: ${n.qualityScore}/100`),t.push("");for(let s of n.waves){t.push(`Wave ${s.number}:`);for(let o of s.streams){let r=o.deps.length>0?` (deps: ${o.deps.join(", ")})`:"",i=o.model?` (${o.model})`:"",a=Ln(o.estimatedCostUsd);t.push(` ${o.id}: ${o.name}${i}${a}${r}`),o.owns.length>0&&t.push(` owns: ${o.owns.join(", ")}`),o.reads.length>0&&t.push(` reads: ${o.reads.join(", ")}`)}t.push("")}if(n.warnings.length>0){t.push("Warnings:");for(let s of n.warnings)t.push(` - ${s}`);t.push("")}return t.join(`
153
- `)}function qe(n){let t=new Map;for(let[r,i]of Object.entries(n))for(let a of i.owns??[]){let c=t.get(a)??[];c.push(r),t.set(a,c)}let e=new Map;function s(r,i=new Set){if(e.has(r))return e.get(r);if(i.has(r))return new Set;i.add(r);let a=n[r]?.deps??[],c=new Set(a);for(let l of a)for(let u of s(l,i))c.add(u);return e.set(r,c),c}for(let r of Object.keys(n))s(r);let o=[];for(let[r,i]of t){if(i.length<2)continue;let a=[];for(let c=0;c<i.length;c++){let l=!1;for(let u=0;u<i.length;u++){if(c===u)continue;let d=e.get(i[c])??new Set,f=e.get(i[u])??new Set;if(d.has(i[u])||f.has(i[c])){l=!0;break}}l||a.push(i[c])}a.length>=2&&o.push({file:r,streams:a,suggestion:`${r} is modified by ${a.join(" and ")} in the same wave. Split into separate waves by adding a dependency edge, or merge into one stream.`})}return o}function Nn(n){let t=qe(n),e=0,s=[];for(let o of t)for(let r=1;r<o.streams.length;r++){let i=n[o.streams[r]],a=o.streams[r-1],c=i.deps??[];c.includes(a)||(c.push(a),i.deps=c,e++,s.push(`Added dep: ${o.streams[r]} \u2192 ${a} (shared file: ${o.file})`))}return{edgesAdded:e,fixes:s}}function Wn(){return{yamlBlocksFound:0,yamlBlocksParsed:0,yamlParseErrors:[],extractionPath:null,sectionsFound:{},sectionsFilteredAsMeta:[],deliverableCount:0,splitCount:0,unmatchedDeps:[],ownershipConflicts:[],warnings:[]}}function Un(n){let t=new Map;for(let[s,o]of Object.entries(n))for(let r of o.owns||[]){let i=t.get(r)||[];i.push(s),t.set(r,i)}let e=[];for(let[s,o]of t)o.length>1&&e.push(`${s} owned by: ${o.join(", ")}`);return e}import{randomUUID as es}from"crypto";var zn=[{pattern:/model.*not.found|not_found_error.*model|Model ".*" not found/i,category:"model_not_found",retryable:!1,selfHealable:!1,suggestion:"Model not found. Check the model name in your configuration and ensure it is available for your API key."},{pattern:/invalid api key|api key.*expired|authentication failed|(?<!\d)401(?!\d)|unauthorized/i,category:"auth_error",retryable:!1,selfHealable:!1,suggestion:"Authentication error. Check your API key configuration and ensure it is valid and not expired."},{pattern:/cloud api error: 5\d{2}|502 bad gateway|503 service unavailable|504 gateway timeout|internal server error|overloaded_error/i,category:"server_error",retryable:!0,selfHealable:!1,suggestion:"Cloud server error. Transport retries exhausted \u2014 try again later or switch to local mode."},{pattern:/timed?\s*out|ETIMEDOUT|deadline|timeout/i,category:"timeout",retryable:!1,selfHealable:!1,suggestion:"Timeout is an infrastructure issue. Consider increasing stream timeout or reducing scope."},{pattern:/network error|ECONNREFUSED|ECONNRESET|EHOSTUNREACH|socket hang up/i,category:"network",retryable:!1,selfHealable:!1,suggestion:"Network connectivity issue. Check API endpoint availability and network configuration."},{pattern:/rate limit|too many requests|429|quota exceeded/i,category:"rate_limit",retryable:!1,selfHealable:!1,suggestion:"Rate limited by API. Wait before retrying or reduce parallel stream count."},{pattern:/old_?content.*not found|edit.*mismatch|does not match|oldContent/i,category:"edit_mismatch",retryable:!0,selfHealable:!0,suggestion:"The file content changed since context was built. Re-read the file and retry with updated content."},{pattern:/invalid.*artifact|parse.*error|orchex-artifact.*not found|JSON\.parse/i,category:"invalid_artifact",retryable:!0,selfHealable:!0,suggestion:"The agent produced malformed output. Retry with clearer instructions about the artifact format."},{pattern:/ENOENT|EACCES|EPERM|ENOSPC|no such file|permission denied/i,category:"environment",retryable:!1,selfHealable:!1,suggestion:"File system error. Check file paths and permissions."},{pattern:/ownership violation|outside owned files|SECURITY.*path traversal|SECURITY.*absolute path/i,category:"ownership_violation",retryable:!0,selfHealable:!0,suggestion:"File operation attempted outside owned files. The fix stream should only modify files in the owns list, or the owns list should be updated to include the new file."},{pattern:/test.*fail|expect.*received|assertion.*error|FAIL\s+tests\//i,category:"test_failure",retryable:!0,selfHealable:!0,suggestion:"Tests are failing. Include the test error output in the retry prompt so the agent can fix the issue."},{pattern:/lint|eslint|prettier|formatting/i,category:"lint_error",retryable:!0,selfHealable:!0,suggestion:"Lint or formatting error. Include the lint output in the retry prompt."},{pattern:/TypeError|ReferenceError|SyntaxError|Cannot find module|cannot find name|TS\d{4}/i,category:"runtime_error",retryable:!0,selfHealable:!0,suggestion:"Code has type or runtime errors. Include the error output and relevant type definitions in the retry prompt."}];function fe(n,t){for(let{pattern:s,category:o,retryable:r,selfHealable:i,suggestion:a}of zn)if(s.test(n))return{category:o,retryable:r,selfHealable:i,suggestion:a};let e=t==="artifact"||t==="verify";return{category:"unknown",retryable:e,selfHealable:e,suggestion:e?"Unknown code error. Retry with the full error message included in the prompt.":`Unknown infrastructure error (origin: ${t??"unspecified"}). Check API key, model availability, and network connectivity.`}}import{loadManifest as Ve,saveManifest as Ye}from"../manifest.js";import{createLogger as Hn}from"../logging.js";var pe=Hn("fix-stream-manager");async function Bn(n){let t=await Ve(n),e={skipped:[],warnings:[]},s=Object.entries(t.streams).filter(([o,r])=>r.parentStreamId!==void 0);for(let[o,r]of s)r.status==="pending"&&Gn(t,r.parentStreamId)&&(t.streams[o].status="skipped",t.streams[o].error="Parent stream completed; fix no longer needed",e.skipped.push(o));return e.skipped.length>0&&await Ye(n,t),e}async function qn(n,t){let e=await Ve(n),s={skipped:[],warnings:[]},o=Jn(e,t);for(let a of o){let c=e.streams[a];c.status==="pending"?(e.streams[a].status="skipped",e.streams[a].error=`Ancestor '${t}' completed; fix no longer needed`,s.skipped.push(a)):c.status==="in_progress"&&(e.streams[a].status="skipped",e.streams[a].error=`Sibling fix already resolved this stream (completed: '${t}')`,s.skipped.push(a))}let r=!1,i=e.streams[t];if(i?.parentStreamId){let a=i.parentStreamId;for(;e.streams[a]?.parentStreamId;)a=e.streams[a].parentStreamId;let c=e.streams[a];c&&c.status==="failed"&&(e.streams[a].status="complete",delete e.streams[a].error,r=!0,pe.info({fixStreamId:t,rootStreamId:a},"fix_stream_propagated_completion_to_root"))}return(s.skipped.length>0||r)&&await Ye(n,e),s}function X(n,t){let e=n.streams[t];if(!e||!e.parentStreamId)return null;let s=[t],o=e.parentStreamId,r=new Set;for(;o&&!r.has(o);){r.add(o);let i=n.streams[o];if(!i)break;if(s.unshift(o),!i.parentStreamId)return{rootStreamId:o,fixChain:s.slice(1),rootStatus:i.status??"pending"};o=i.parentStreamId}return null}function Vn(n,t){return n.streams[t]?.parentStreamId!==void 0}function Yn(n,t){return X(n,t)?.rootStreamId??t}function Gn(n,t){let e=t,s=new Set;for(;e;){if(s.has(e)){pe.warn({streamId:e},"circular_reference_in_fix_chain");break}s.add(e);let o=n.streams[e];if(!o){pe.warn({parentId:e},"fix_stream_orphaned_parent");break}if(o.status==="complete")return!0;e=o.parentStreamId}return!1}function Jn(n,t){let e=[];for(let[s,o]of Object.entries(n.streams))o.parentStreamId&&Kn(n,s,t)&&e.push(s);return e}function Kn(n,t,e){let s=n.streams[t]?.parentStreamId,o=new Set;for(;s&&!o.has(s);){if(o.add(s),s===e)return!0;s=n.streams[s]?.parentStreamId}return!1}var Je=3;function Ke(n,t){let e=0,s=t;for(;s;){let o=n.streams[s];if(!o)break;e+=o.attempts??0,s=o.parentStreamId}return e}function Ge(n,t){return X(n,t)?.rootStreamId??t}function Qe(n,t){let e=Ge(n,t);for(let[s,o]of Object.entries(n.streams)){if(s===t||!o.parentStreamId||o.status!=="pending"&&o.status!=="in_progress")continue;if(Ge(n,s)===e)return!0}return!1}function Qn(n,t,e,s){let o=n.streams[t];if(!o||o.status==="failed"&&o.error?.startsWith("Setup failed:"))return null;let r=o.error??"",i=e??fe(r);if(!i.selfHealable||Qe(n,t)||Ke(n,t)>=Je)return null;let l=(o.attempts??0)+1,u=`${t}-fix-${l}`,d=t,f=[`## Fix Attempt #${l} for "${o.name}"`,"","### Original Plan",o.plan??"(no plan)","","### Error That Occurred","```",r,"```","",`### Error Category: ${i.category}`,"",`### Suggestion: ${i.suggestion}`,"","### Instructions",`This is a retry of the failed stream "${t}".`,"Fix the issue described above. The original files are in your owns list.","Make sure to address the specific error before implementing the rest of the plan.",...s?["","### Upstream Dependency Warning",`Your error references '${s.errorRef}' which is likely defined by upstream stream '${s.suspectStreamId}'.`,`That stream owns: ${s.suspectFiles.join(", ")}`,"Before fixing your own code, verify that the upstream dependency exports the types/values you need.","If the upstream output is incorrect (wrong type names, missing exports), this fix will fail again.","In that case, the issue will be escalated to fix the upstream stream directly."]:[]].join(`
154
- `),p={name:`${o.name} (Fix #${l})`,deps:o.deps??[],owns:o.owns??[],reads:o.reads??[],plan:f,setup:o.setup??[],verify:o.verify??[],status:"pending",attempts:0,parentStreamId:d};return{fixStreamId:u,fixStream:p,analysis:{category:i.category,suggestion:i.suggestion}}}function Xn(n,t){let e=n.streams[t];if(!e?.error)return null;let s=e.deps??[];if(s.length===0)return null;let o=/(?:Cannot find (?:name|module) '(\w+)'|Type '(\w+)'|has no (?:exported )?member '(\w+)'|is not assignable to type '(\w+)'|does not exist on type '(\w+)'|Property '(\w+)' does not exist)/gi,r=new Set,i;for(;(i=o.exec(e.error))!==null;){let a=i[1]||i[2]||i[3]||i[4]||i[5]||i[6];a&&r.add(a)}if(r.size===0)return null;for(let a of s){let c=n.streams[a];if(!c||c.status!=="complete")continue;let l=c.owns??[];if(l.length===0)continue;let u=l.filter(d=>d.endsWith(".ts")||d.endsWith(".tsx")||d.endsWith(".d.ts"));if(u.length!==0)for(let d of r){let f=d.toLowerCase();if(u.some(m=>{let h=m.toLowerCase();return h.includes("type")||h.includes("index")||h.includes(f)||h.includes("model")||h.includes("schema")||h.includes("interface")}))return{suspectStreamId:a,errorRef:d,suspectFiles:u}}}return null}function me(n,t){if(t.length<2)return null;let e=new Map;for(let d of t){let f=n.streams[d];f?.error&&e.set(d,f.error)}if(e.size<2)return null;let s=/(?:Cannot find (?:name|module)|Type '(\w+)'|has no (?:exported )?member '(\w+)'|is not assignable|does not exist on type '(\w+)')/.source,o=new Map;for(let[d,f]of e){let p=new RegExp(s,"gi"),m,h=new Set;for(;(m=p.exec(f))!==null;){let y=m[1]||m[2]||m[3]||m[0];h.add(y)}for(let y of h){let v=o.get(y)??[];v.push(d),o.set(y,v)}}let r="",i=0;for(let[d,f]of o)f.length>i&&(r=d,i=f.length);if(i<2)return null;let a=o.get(r),c=new Map;for(let d of a){let f=n.streams[d];for(let p of f?.deps??[])c.set(p,(c.get(p)??0)+1)}let l="",u=0;for(let[d,f]of c)n.streams[d]?.status==="complete"&&f>u&&(l=d,u=f);return l?{rootCauseStreamId:l,reason:`Stream '${l}' completed but ${a.length} downstream streams failed with errors referencing '${r}'`,affectedStreamIds:a,commonErrorPattern:r}:null}function Zn(n,t){let e=t.rootCauseStreamId,s=n.streams[e];if(!s||s.status!=="failed"||Ke(n,e)>=Je||Qe(n,e))return null;let i=(s.attempts??0)+1,a=`${e}-fix-${i}`,c=[];for(let d of t.affectedStreamIds.slice(0,3)){let f=n.streams[d];f?.error&&c.push(`- ${f.name}: ${f.error.slice(0,200)}`)}let l=[`## Root Cause Fix #${i} for "${s.name}"`,"","### Original Plan",s.plan??"(no plan)","","### Problem Identified",`This stream completed but its output caused ${t.affectedStreamIds.length} downstream streams to fail.`,`All downstream errors reference: **${t.commonErrorPattern}**`,"","### Downstream Error Samples",...c,"","### Instructions",`This stream's output is incorrect. The code you produce must define '${t.commonErrorPattern}' correctly`,"so that downstream streams importing from this file can compile successfully.","Re-read the original plan carefully and ensure your output matches the specified types, exports, and signatures exactly.","Pay special attention to type definitions, enum values, and const arrays \u2014 they must match what downstream code expects."].join(`
155
- `),u={name:`${s.name} (Root Cause Fix #${i})`,deps:s.deps??[],owns:s.owns??[],reads:s.reads??[],plan:l,setup:s.setup??[],verify:s.verify??[],status:"pending",attempts:0,parentStreamId:e};return{fixStreamId:a,fixStream:u,analysis:{category:"runtime_error",suggestion:t.reason}}}function ts(n,t,e){let s=100,o=n.filter(r=>r.status==="failed").length;return s-=o*20,s-=e*10,s+=t*5,Math.max(0,Math.min(100,s))}function ns(n,t,e){let s=n.runId??es(),o=new Date().toISOString(),r=[];for(let g of t)r.push(...g.streams);let i=new Set;for(let g of t)if(g.fixStreamsGenerated)for(let w of g.fixStreamsGenerated)i.add(w);for(let[g,w]of Object.entries(n.streams))w.parentStreamId&&i.add(g);let a=new Map;for(let g of r)a.set(g.id,g);let c=[...a.values()].map(g=>({id:g.id,name:g.name,status:g.status,tokensUsed:g.tokensUsed,executionTimeMs:g.executionTimeMs,selfHealCount:i.has(g.id)?1:0,errorCategory:g.errorDetail?.category,errorMessage:g.error,errorSuggestion:g.errorDetail?.suggestion,errorRetryable:g.errorDetail?.retryable,errorSelfHealable:g.errorDetail?.selfHealable,provider:g.provider,model:g.model,filesChanged:g.filesChanged})),l=0,u=0,d={};for(let g of r)if(g.tokensUsed){l+=g.tokensUsed.input,u+=g.tokensUsed.output;let w=g.provider??"unknown";d[w]||(d[w]={input:0,output:0}),d[w].input+=g.tokensUsed.input,d[w].output+=g.tokensUsed.output}let f=0,p=0;for(let g of t)g.timing&&(f+=g.timing.parallelMs,p+=g.timing.sequentialMs);let m=new Set;for(let g of r)if(g.filesChanged)for(let w of g.filesChanged)m.add(w);let h=0;for(let g of t)g.streams.length>0&&g.streams.every(w=>w.status==="complete")&&h++;let y={};for(let g of r)if(g.status==="failed"&&g.errorDetail?.category){let w=g.errorDetail.category;y[w]=(y[w]??0)+1}let v,T=r.filter(g=>g.status==="failed").map(g=>g.id);if(T.length>=2){let g=me(n,T);g&&(v=g)}let S=i.size,x=ts(r,h,S);return{runId:s,timestamp:o,feature:n.feature,planQualityScore:x,streamResults:c,waveEfficiency:{parallelMs:f,sequentialMs:p,timeSavedMs:Math.max(0,p-f)},autoPlanAccuracy:e?.autoPlanEdits!==void 0?{editsBeforeApproval:e.autoPlanEdits}:void 0,tokenUsage:{totalInput:l,totalOutput:u,byProvider:d},fileChangeImpact:{filesCreated:0,filesModified:m.size,totalFilesChanged:m.size},failurePatterns:y,failureCorrelation:v,totalWaves:t.length,totalStreams:a.size}}async function ss(n,t){let{mkdir:e,writeFile:s}=await import("fs/promises"),{join:o}=await import("path"),r=o(n,".orchex","reports");await e(r,{recursive:!0});let i=o(r,`${t.runId}.json`);return await s(i,JSON.stringify(t,null,2),"utf-8"),i}import{formatDuration as os}from"../types.js";function rs(n,t){let e=[];if(n.waveEfficiency.timeSavedMs>0&&n.totalStreams>1){let r=os(n.waveEfficiency.timeSavedMs),i=n.waveEfficiency.sequentialMs>0?Math.round(n.waveEfficiency.timeSavedMs/n.waveEfficiency.sequentialMs*100):0;e.push(`${n.totalStreams} streams ran in parallel across ${n.totalWaves} wave(s), saving ${r} (${i}%).`)}else n.totalStreams>1&&e.push(`${n.totalStreams} streams executed across ${n.totalWaves} wave(s).`);let s=Object.entries(n.failurePatterns);if(s.length>0){s.sort((c,l)=>l[1]-c[1]);let[r,i]=s[0],a=s.reduce((c,[,l])=>c+l,0);r==="type_error"?e.push(`${r} was the most common failure (${i}/${a}). Consider adding a types-only stream first.`):e.push(`${r} was the most common failure (${i}/${a}).`)}if(t&&t.length>0){let r=t.reduce((a,c)=>a+c.planQualityScore,0)/t.length,i=n.planQualityScore-r;i>10?e.push(`Plan quality improved from ${Math.round(r)} to ${n.planQualityScore} \u2014 orchex is learning your patterns.`):i<-10?e.push(`Plan quality dropped from ${Math.round(r)} to ${n.planQualityScore}. Review the failure patterns above.`):e.push(`Plan quality score: ${n.planQualityScore}/100 (consistent with previous runs at ~${Math.round(r)}).`)}else e.push(`Plan quality score: ${n.planQualityScore}/100.`);let o=n.tokenUsage.totalInput+n.tokenUsage.totalOutput;if(o>0&&e.length<3){let r=Object.keys(n.tokenUsage.byProvider);r.length>1&&e.push(`Used ${r.length} providers: ${r.join(", ")} \u2014 total ${o.toLocaleString()} tokens.`)}return e.slice(0,3)}import*as b from"fs/promises";import*as R from"path";var Xe=".first-run-complete";async function is(n){let t=R.join(n,".orchex");try{await b.access(t)}catch{return!0}try{return await b.access(R.join(t,Xe)),!1}catch{}try{let e=R.join(t,"archive");if((await b.readdir(e)).length>0)return!1}catch{}try{let e=R.join(t,"reports");if((await b.readdir(e)).some(o=>o.endsWith(".json")))return!1}catch{}try{let e=R.join(t,"learn","events.jsonl");if((await b.stat(e)).size>0)return!1}catch{}return!0}async function as(n){let t=R.join(n,".orchex");await b.mkdir(t,{recursive:!0}),await b.writeFile(R.join(t,Xe),new Date().toISOString(),"utf-8")}function cs(){return["Welcome to orchex! This looks like your first time using orchex in this project.","","Try a quick demo to see orchestration in action:",' orchex run "Add a hello world API endpoint to this project"',"","Or use the MCP auto tool in your AI assistant:",' auto({ prompt: "Add a health check endpoint" })',"","Orchex will generate a plan, show you a preview, and execute in parallel.","Learn more: https://orchex.dev/docs/user-guide/quickstart"].join(`
156
- `)}import*as B from"fs/promises";import*as O from"path";async function ls(n,t){if(!t.confirm)throw new Error("Reset learning requires --confirm flag. This permanently deletes learning data.");let e=[],s=O.join(n,".orchex","learn"),o=O.join(n,".orchex","reports");t.patternsOnly?await Z(O.join(s,"patterns.json"),e):t.reportsOnly?await Ze(o,e,".json"):(await Z(O.join(s,"thresholds.json"),e),await Z(O.join(s,"events.jsonl"),e),await Z(O.join(s,"patterns.json"),e),await Ze(o,e,".json"));let r=t.patternsOnly?"patterns":t.reportsOnly?"reports":"all learning data";return{deleted:e,totalDeleted:e.length,message:e.length>0?`Reset ${r}: ${e.length} file(s) deleted.`:`No ${r} found to delete.`}}async function Z(n,t){try{await B.unlink(n),t.push(O.basename(n))}catch(e){if(e.code!=="ENOENT")throw e}}async function Ze(n,t,e){try{let s=await B.readdir(n);for(let o of s)e&&!o.endsWith(e)||(await B.unlink(O.join(n,o)),t.push(o))}catch(s){if(s.code!=="ENOENT")throw s}}import{createLogger as us}from"../logging.js";var ds=us("iteration-evaluator");function fs(n){let{streamResults:t,iterationNumber:e,maxIterations:s,intent:o}=n;if(e>=s){let d=t.filter(f=>f.status==="failed"||!f.verifyPassed).length;return{complete:!0,reason:`Reached max iterations (${s})${d>0?` with ${d} unresolved failure(s)`:""}`,failureSummary:d>0?t.filter(f=>f.status==="failed").map(f=>`${f.id}: ${f.error}`).join("; "):void 0}}let r=t.filter(d=>d.status==="failed"),i=t.filter(d=>d.status==="complete"&&!d.verifyPassed);if(r.length===0&&i.length===0)return{complete:!0,reason:`All ${t.length} stream(s) completed and verified successfully`};let c=[];for(let d of r)c.push(`Stream "${d.id}" failed: ${d.error??"unknown error"}`);for(let d of i)c.push(`Stream "${d.id}" verify failed: ${d.verifyError??"verification error"}`);let l=c.join("; "),u=`Fix the following issues from the previous attempt to "${o}": ${l}`;return ds.info({iteration:e,failed:r.length,verifyFailed:i.length},"iteration_incomplete"),{complete:!1,reason:`${r.length} stream(s) failed, ${i.length} verification(s) failed`,nextIntent:u,failureSummary:l}}var ps={id:"documentation-set",name:"Documentation Set",description:"Multiple documentation files (guides, tutorials, API references) that should be created independently",keywords:["docs","documentation","guide","tutorial","readme","api reference","multiple pages"],patterns:["Multiple .md files in docs/","Creating 3+ documentation files","Tutorial series","API documentation pages"],streamStructure:[{namePattern:"docs-{topic}",purpose:"Create documentation for a specific topic",dependsOn:[],ownsPatterns:["docs/{topic}/**/*.md"],readsPatterns:["src/**/*.ts","README.md"],planOutline:"Research implementation \u2192 Write documentation \u2192 Add examples \u2192 Review completeness"}],guidelines:["Split by logical topic, not file count","Each stream should own 1-3 related doc files","Order dependencies: concepts \u2192 API reference \u2192 tutorials \u2192 advanced guides","Streams can run in parallel if topics are independent","Keep related examples with their topic"]},ms={id:"code-feature",name:"Code Feature Implementation",description:"Multi-component feature with types, implementation, tests, and documentation",keywords:["feature","implement","add","create","types","tests","integration"],patterns:["Types \u2192 Implementation \u2192 Tests \u2192 Docs","Multiple source files with dependencies","Test files alongside implementation","Integration with existing code"],streamStructure:[{namePattern:"{feature}-types",purpose:"Define interfaces, types, and schemas",dependsOn:[],ownsPatterns:["src/types/{feature}.ts","src/schemas/{feature}.ts"],readsPatterns:["src/types.ts"],planOutline:"Analyze requirements \u2192 Define types \u2192 Add validation schemas \u2192 Export types"},{namePattern:"{feature}-core",purpose:"Core feature implementation",dependsOn:["{feature}-types"],ownsPatterns:["src/{feature}/*.ts"],readsPatterns:["src/types/{feature}.ts","src/utils/*.ts"],planOutline:"Implement core logic \u2192 Add error handling \u2192 Integrate with existing systems"},{namePattern:"{feature}-tests",purpose:"Unit and integration tests",dependsOn:["{feature}-core"],ownsPatterns:["tests/{feature}.test.ts"],readsPatterns:["src/{feature}/*.ts"],planOutline:"Write unit tests \u2192 Add integration tests \u2192 Test edge cases \u2192 Verify coverage"},{namePattern:"{feature}-docs",purpose:"Documentation and examples",dependsOn:["{feature}-core"],ownsPatterns:["docs/{feature}/*.md"],readsPatterns:["src/{feature}/*.ts"],planOutline:"Document API \u2192 Add usage examples \u2192 Write integration guide"}],guidelines:["Always start with types to establish contracts","Core implementation depends on types being defined","Tests and docs can run in parallel after core is complete","Keep streams focused: one stream = one responsibility","If a file has 200+ lines, consider splitting implementation into multiple streams"]},hs={id:"migration",name:"Migration",description:"Migrating code, data, or structure with backward compatibility",keywords:["migration","migrate","refactor","rename","move","deprecate","backward compatible"],patterns:["From old to new","Rename/move files or functions","Change data structure","Update multiple call sites","Maintain backward compatibility"],streamStructure:[{namePattern:"{migration}-new-implementation",purpose:"Create new implementation alongside old one",dependsOn:[],ownsPatterns:["src/{new}/*.ts"],readsPatterns:["src/{old}/*.ts"],planOutline:"Implement new version \u2192 Match old API \u2192 Add compatibility layer"},{namePattern:"{migration}-migrate-{component}",purpose:"Migrate specific component to new implementation",dependsOn:["{migration}-new-implementation"],ownsPatterns:["src/{component}/**/*.ts"],readsPatterns:["src/{new}/*.ts","src/{old}/*.ts"],planOutline:"Update imports \u2192 Replace function calls \u2192 Update tests \u2192 Verify behavior"},{namePattern:"{migration}-deprecate-old",purpose:"Mark old implementation as deprecated",dependsOn:["{migration}-migrate-*"],ownsPatterns:["src/{old}/*.ts"],readsPatterns:[],planOutline:"Add deprecation notices \u2192 Update docs \u2192 Plan removal timeline"}],guidelines:["Create new before removing old","Migrate in small, independent chunks (by component/module)","Each migration stream should be independently testable","Keep deprecation as the final step","Ensure each stream leaves the codebase in a working state"]},gs={id:"tutorial",name:"Tutorial Series",description:"Progressive tutorial series from basics to advanced",keywords:["tutorial","guide","example","walkthrough","getting started","beginner","advanced"],patterns:["Multiple tutorial steps","Progressive complexity","Beginner \u2192 Intermediate \u2192 Advanced","Examples with documentation"],streamStructure:[{namePattern:"tutorial-{level}-{topic}",purpose:"Create tutorial for specific level and topic",dependsOn:["tutorial-{previous-level}-*"],ownsPatterns:["docs/tutorials/{level}-{topic}.md","examples/{topic}/**/*"],readsPatterns:["src/**/*.ts","docs/tutorials/{previous}*.md"],planOutline:"Define learning objectives \u2192 Write tutorial \u2192 Create working example \u2192 Add exercises"}],guidelines:["Order by prerequisite knowledge: basics \u2192 intermediate \u2192 advanced","Each tutorial should be self-contained but build on previous concepts","Include working code examples","Beginner tutorials can run in parallel if they cover different topics","Advanced tutorials depend on relevant beginner/intermediate tutorials"]},ys={id:"api-reference",name:"API Reference",description:"Comprehensive API documentation for modules, classes, and functions",keywords:["api","reference","documentation","modules","classes","functions","methods"],patterns:["Documenting multiple modules","Class/function reference","Method documentation","Parameter and return type docs"],streamStructure:[{namePattern:"api-{module}-reference",purpose:"Create API reference for a specific module",dependsOn:[],ownsPatterns:["docs/api/{module}.md"],readsPatterns:["src/{module}/**/*.ts"],planOutline:"Extract types/interfaces \u2192 Document functions \u2192 Add examples \u2192 Cross-link related APIs"}],guidelines:["Split by module or logical grouping","All API reference streams can run in parallel","Include type signatures and examples","Cross-reference related APIs","Keep each stream to 1-2 related modules"]},ws=[ps,ms,hs,gs,ys];function ee(n){let t=n.toLowerCase(),e=null;for(let s of ws){let o=0;for(let r of s.keywords)t.includes(r.toLowerCase())&&(o+=2);for(let r of s.patterns){let i=r.toLowerCase().split(/[\s/,]+/).filter(c=>c.length>2);i.filter(c=>t.includes(c)).length>=i.length/2&&(o+=1)}o>0&&(!e||o>e.score)&&(e={template:s,score:o})}return e&&e.score>=3?e.template:null}function he(n,t){let e=[];if(n.id==="documentation-set"){let s=t.topics||[];for(let o of s)e.push({name:`docs-${o}`,deps:[],owns:[`docs/${o}/**/*.md`],reads:["src/**/*.ts","README.md"],plan:`Research ${o} implementation \u2192 Write documentation \u2192 Add examples \u2192 Review completeness`})}else if(n.id==="code-feature"){let s=t.featureName;e.push({name:`${s}-types`,deps:[],owns:[`src/types/${s}.ts`],reads:["src/types.ts"],plan:"Analyze requirements \u2192 Define types \u2192 Add validation schemas \u2192 Export types"},{name:`${s}-core`,deps:[`${s}-types`],owns:[`src/${s}/*.ts`],reads:[`src/types/${s}.ts`,"src/utils/*.ts"],plan:"Implement core logic \u2192 Add error handling \u2192 Integrate with existing systems"},{name:`${s}-tests`,deps:[`${s}-core`],owns:[`tests/${s}.test.ts`],reads:[`src/${s}/*.ts`],plan:"Write unit tests \u2192 Add integration tests \u2192 Test edge cases \u2192 Verify coverage"},{name:`${s}-docs`,deps:[`${s}-core`],owns:[`docs/${s}/*.md`],reads:[`src/${s}/*.ts`],plan:"Document API \u2192 Add usage examples \u2192 Write integration guide"})}else if(n.id==="migration"){let s=t.featureName,o=t.components||[];e.push({name:`${s}-new-implementation`,deps:[],owns:[`src/${s}-new/*.ts`],reads:[`src/${s}-old/*.ts`],plan:"Implement new version \u2192 Match old API \u2192 Add compatibility layer"});for(let r of o)e.push({name:`${s}-migrate-${r}`,deps:[`${s}-new-implementation`],owns:[`src/${r}/**/*.ts`],reads:[`src/${s}-new/*.ts`,`src/${s}-old/*.ts`],plan:"Update imports \u2192 Replace function calls \u2192 Update tests \u2192 Verify behavior"});e.push({name:`${s}-deprecate-old`,deps:o.map(r=>`${s}-migrate-${r}`),owns:[`src/${s}-old/*.ts`],reads:[],plan:"Add deprecation notices \u2192 Update docs \u2192 Plan removal timeline"})}else if(n.id==="tutorial"){let s=t.topics||[];for(let o of s)e.push({name:`tutorial-${o}`,deps:[],owns:[`docs/tutorials/${o}.md`,`examples/${o}/**/*`],reads:["src/**/*.ts"],plan:"Define learning objectives \u2192 Write tutorial \u2192 Create working example \u2192 Add exercises"})}else if(n.id==="api-reference"){let s=t.modules||[];for(let o of s)e.push({name:`api-${o}-reference`,deps:[],owns:[`docs/api/${o}.md`],reads:[`src/${o}/**/*.ts`],plan:"Extract types/interfaces \u2192 Document functions \u2192 Add examples \u2192 Cross-link related APIs"})}return e}function xs(n){let t=n.owns||[],e=n.reads||[];if(t.length>5)return{originalStream:n.name,reason:`Stream owns ${t.length} files, which may be too many for a single stream`,guidance:["Consider grouping related files together","Split by logical component or responsibility","Create dependencies between resulting streams if needed"],suggestedStreams:[]};if(e.length>10)return{originalStream:n.name,reason:`Stream reads ${e.length} files, which may indicate broad scope`,guidance:["Reading many files often means the stream is doing too much","Consider splitting into smaller, focused streams","Each stream should ideally read 3-5 context files"],suggestedStreams:[]};let s=`${n.name} ${n.plan||""}`,o=ee(s);return o&&["multiple","all","complete","full","entire"].some(a=>n.name.toLowerCase().includes(a))?{originalStream:n.name,reason:"Stream name suggests broad scope that could be split",template:o,guidance:o.guidelines,suggestedStreams:[]}:null}function Ss(n,t,e){if(e.issues.length===0)return null;let s=e.issues.some(l=>l.severity==="error"),o=e.issues.some(l=>l.severity==="warning"),r=`${t.name??n} ${t.plan??""}`,i=ee(r),a=null;if(i){let l=n.replace(/-/g,"_");a=he(i,{featureName:l})}let c="";s?c=`Stream "${n}" has critical issues:
150
+ `))}return s}function On(n){switch(n){case"code":return"Implement";case"test":return"Write tests for";case"docs":return"Document";case"tutorial":return"Create tutorial for";case"integration-guide":return"Write integration guide for";case"api-reference":return"Generate API reference for";case"migration":return"Migrate";default:return"Complete"}}function Pn(n,t="npm"){let e=[];if(n.ownedFiles.some(o=>o.endsWith(".ts")||o.endsWith(".tsx")||o.endsWith(".js")||o.endsWith(".jsx"))&&e.push(F(t,"build")),n.category==="test"){let o=n.ownedFiles.find(r=>r.includes(".test."));o?e.push(re(t,o)):e.push(re(t))}return e}function Mn(n,t,e,s="npm"){let o=[],r=[];for(let i of n){if(t!=="test"&&/vitest|jest/.test(i)&&!/build|tsc/.test(i)){r.push(`Verify command '${i}' uses a test runner but stream category is '${t}'. Replaced with '${F(s,"build")}'.`),o.push(F(s,"build"));continue}let a=i.match(/(?:vitest|jest)\s+(?:run\s+)?(\S+\.(?:ts|tsx|js|jsx))/);if(a){let c=a[1];if(!e.some(u=>c.includes(u)||u.includes(c))){r.push(`Verify command references '${c}' which is not in this stream's owned files. Replaced with '${F(s,"build")}'.`),o.push(F(s,"build"));continue}}o.push(i)}return{commands:[...new Set(o)],warnings:r}}function In(n,t,e={}){let{minPlanLength:s=5,estimateTimeout:o=!0,defaultVerify:r}=e,i=n,a=e.projectDir?U(e.projectDir):"npm",c=i._verify||r||Pn(n,a),l=i._setup,{commands:u,warnings:d}=Mn(c,n.category,n.ownedFiles,a);if(d.length>0&&e.diagnostics)for(let h of d)e.diagnostics.warnings.push(`${n.id}: verify_warning - ${h}`);let p=(i._verify!==void 0||i._setup!==void 0)&&n.description.length>=s?n.description:En(n,s),m={name:n.name,deps:t.length>0?t:void 0,owns:n.ownedFiles.length>0?n.ownedFiles:void 0,reads:n.readFiles.length>0?n.readFiles:void 0,plan:p,verify:u.length>0?u:void 0,setup:l&&l.length>0?l:void 0};if(o){let h=Tn[n.category],y=Math.max(1,Math.ceil(n.ownedFiles.length/2));m.timeoutMs=h*y}return m}function Rn(n,t,e={}){let{validateAntiPatterns:s=!0}=e,o={},r=[],i=[];t.isAcyclic||r.push(`Dependency graph has cycles: ${t.cycles.map(l=>l.join(" \u2192 ")).join("; ")}`);let a=s?H():null;for(let l of n){let u=t.dependencies.get(l.id)||[],d=In(l,u,e);if(a){let h=a.analyzeStream(l.id,{name:d.name,deps:d.deps||[],owns:d.owns||[],reads:d.reads||[],plan:d.plan,verify:d.verify||[]});if(h.issues.length>0){i.push(h);for(let y of h.issues)r.push(`${l.id}: ${y.type} - ${y.message}`)}}let f=l.childCount,p=d.plan?.length??0,m=(d.owns||[]).length;if(f!==void 0&&f>=5&&p>2500?r.push(`${l.id}: too_complex - ${f} sub-sections, ${m} owned files, ~${p} char plan. Consider: use YAML stream definitions for manual decomposition, or set deliverable_level: 3`):f!==void 0&&f>=3&&p>3500&&r.push(`${l.id}: too_complex - ${f} sub-sections, ~${p} char plan. Consider: use YAML stream definitions for finer control`),e.projectDir){let h=d.owns||[];for(let y of h)try{let C=v.join(e.projectDir,y),S=$.readFileSync(C,"utf-8").split(`
151
+ `).length;if(S>800){let x=`${l.id}: large_file_critical - ${y} is ${S} lines (>800). Consider splitting this stream to reduce file scope`;r.push(x),e.diagnostics&&e.diagnostics.warnings.push(x)}else if(S>500&&h.length>=3){let x=`${l.id}: large_file_risk - ${y} is ${S} lines, stream owns ${h.length} files. Consider splitting to reduce complexity`;r.push(x),e.diagnostics&&e.diagnostics.warnings.push(x)}}catch{}}if(l.ownedFiles.length===0){let h=`Stream '${l.id}' has no owned files. It can read but not write. If this is unintentional, check your Create:/Modify: syntax (must use backtick-quoted paths).`;r.push(h),e.diagnostics&&e.diagnostics.warnings.push(h)}o[l.id]=d}if(e.projectDir){let l=An(o,e.projectDir);r.push(...l.warnings);for(let[u,d]of Object.entries(l.streams))o[u]=d}let c=Object.entries(o).map(([l,u])=>({id:l,owns:u.owns??[],reads:u.reads??[],deps:u.deps??[]}));if(c.length>0){let l=de(c);e.diagnostics&&(e.diagnostics.topologyReport=l.report);for(let u of l.streams)o[u.id]&&(o[u.id]={...o[u.id],deps:u.deps.length>0?u.deps:void 0});l.report.edgesRemoved>0&&r.push(`Topology optimization: removed ${l.report.edgesRemoved} redundant edge(s)`)}return{streams:o,warnings:r,antiPatterns:s?i:void 0,count:n.length}}function Fn(n){let t=["=== Generated Streams ===",""];if(t.push(`Total: ${n.count} streams`),n.warnings.length>0){t.push(""),t.push("--- Warnings ---");for(let e of n.warnings)t.push(`\u26A0\uFE0F ${e}`)}t.push(""),t.push("--- Stream Definitions ---");for(let[e,s]of Object.entries(n.streams))t.push(""),t.push(`${e}:`),t.push(` name: ${s.name}`),s.deps&&s.deps.length>0&&t.push(` deps: [${s.deps.join(", ")}]`),s.owns&&s.owns.length>0&&t.push(` owns: [${s.owns.join(", ")}]`),s.reads&&s.reads.length>0&&t.push(` reads: [${s.reads.join(", ")}]`),s.plan&&t.push(` plan: ${s.plan.slice(0,80)}${s.plan.length>80?"...":""}`),s.verify&&s.verify.length>0&&t.push(` verify: [${s.verify.join(", ")}]`),s.timeoutMs&&t.push(` timeoutMs: ${s.timeoutMs}`);return t.join(`
152
+ `)}function _n(n){return n.streams}var Ue=/(?:npm\s+install|pnpm\s+add|yarn\s+add|pip\s+install|bun\s+add)\s+(.+)/gi,ze=/install\s+(?:dependencies|packages)\s*:\s*\n((?:\s+[-*]\s+.+\n?)+)/gi;function He(n){let t=n.replace(/^\s*[-*]\s*/,"").trim();return t=t.replace(/\s*\(.*?\)\s*$/,"").trim(),t=t.replace(/[`"']/g,"").trim(),/^@?[a-z0-9][\w./-]*$/i.test(t)?t:null}function jn(n,t="npm"){let e=new Set;for(let s of Object.values(n)){let o=s.plan??"",r;for(Ue.lastIndex=0;(r=Ue.exec(o))!==null;){let i=r[1].split(/\s+/).filter(a=>a&&!a.startsWith("-"));for(let a of i){let c=He(a);c&&e.add(c)}}for(ze.lastIndex=0;(r=ze.exec(o))!==null;){let i=r[1].split(`
153
+ `);for(let a of i){let c=He(a);c&&e.add(c)}}}return e.size===0?[]:[Ce(t,[...e])]}function An(n,t){let e=[];if(!t)return{streams:n,warnings:e};let s={},o=new Set;for(let r of Object.values(n))for(let i of r.owns||[])o.add(i);for(let[r,i]of Object.entries(n)){let a=[...i.owns||[]],c=[...i.reads||[]];for(let u of a){let d=v.join(t,u);if($.existsSync(d))try{$.statSync(d).isDirectory()&&e.push(`${r}: path_invalid - owns path "${u}" is a directory, not a file (owns must list specific files)`)}catch{}else{let f=v.dirname(d);$.existsSync(f)||e.push(`${r}: path_not_found - owns path "${u}" not found and parent directory does not exist`)}}let l=[];for(let u=0;u<c.length;u++){let d=c[u];if(o.has(d))continue;let f=v.join(t,d);if($.existsSync(f)){try{$.statSync(f).isDirectory()&&(e.push(`${r}: path_removed - reads path "${d}" is a directory, not a file (reads must list specific files); removed from reads`),l.push(u))}catch{}continue}let p=v.basename(d),m=Dn(t,p);m.matches===1&&m.path?(e.push(`${r}: path_corrected - reads path "${d}" corrected to "${m.path}" (only match found)`),c[u]=m.path):m.matches>1?e.push(`${r}: path_ambiguous - reads path "${d}" not found, ${m.matches} candidates exist`):(e.push(`${r}: path_removed - reads path "${d}" not found on disk, removed from reads`),l.push(u))}for(let u=l.length-1;u>=0;u--)c.splice(l[u],1);s[r]={...i,owns:a,reads:c}}return{streams:s,warnings:e}}function Dn(n,t){let e=[],s=["src","tests","lib","scripts"];for(let r of s){let i=v.join(n,r);$.existsSync(i)&&Be(i,t,e)}let o=v.join(n,t);return $.existsSync(o)&&$.statSync(o).isFile()&&e.push(t),e.length===1?{matches:1,path:e[0]}:{matches:e.length}}function Be(n,t,e,s){let o=s||v.dirname(n);try{let r=$.readdirSync(n,{withFileTypes:!0});for(let i of r){if(i.name==="node_modules"||i.name===".git"||i.name==="dist")continue;let a=v.join(n,i.name);i.isDirectory()?Be(a,t,e,o):i.name===t&&e.push(v.relative(o,a))}}catch{}}function Ln(n,t,e,s,o){let r=new Set;for(let d of Object.values(n))for(let f of d.owns??[])r.add(f);let i=0;if(o)for(let d of Object.values(o))d.estimatedCostUsd&&(i+=d.estimatedCostUsd);let a=t.map(d=>({number:d.number,streams:d.streams.map(f=>{let p=n[f],m=o?.[f];return{id:f,name:p?.name??f,owns:p?.owns??[],reads:p?.reads??[],deps:p?.deps??[],provider:m?.provider,model:m?.model,estimatedCostUsd:m?.estimatedCostUsd,modelFallback:m?.fallback}})})),c=[...e];if(s)for(let d of s)c.push(`Sequential edit conflict: ${d.suggestion}`);if(o)for(let[d,f]of Object.entries(o))f.fallback&&c.push(`${d}: ${f.fallback}`);let l=100;c.length>0&&(l-=c.length*5);let u=Object.values(n).filter(d=>!d.owns||d.owns.length===0).length;return l-=u*10,l=Math.max(0,Math.min(100,l)),{summary:{streamCount:Object.keys(n).length,waveCount:t.length,fileCount:r.size,estimatedCostUsd:i>0?i:void 0},waves:a,warnings:c,qualityScore:l}}function Nn(n){return!n||n===0?"":n<.01?" ~< $0.01":` ~$${n.toFixed(2)}`}function Wn(n){let t=[],e=n.summary.estimatedCostUsd?`, est. ~$${n.summary.estimatedCostUsd.toFixed(2)}`:"";t.push(`Plan Preview: ${n.summary.streamCount} streams, ${n.summary.waveCount} waves, ${n.summary.fileCount} files${e}`),t.push(`Quality Score: ${n.qualityScore}/100`),t.push("");for(let s of n.waves){t.push(`Wave ${s.number}:`);for(let o of s.streams){let r=o.deps.length>0?` (deps: ${o.deps.join(", ")})`:"",i=o.model?` (${o.model})`:"",a=Nn(o.estimatedCostUsd);t.push(` ${o.id}: ${o.name}${i}${a}${r}`),o.owns.length>0&&t.push(` owns: ${o.owns.join(", ")}`),o.reads.length>0&&t.push(` reads: ${o.reads.join(", ")}`)}t.push("")}if(n.warnings.length>0){t.push("Warnings:");for(let s of n.warnings)t.push(` - ${s}`);t.push("")}return t.join(`
154
+ `)}function qe(n){let t=new Map;for(let[r,i]of Object.entries(n))for(let a of i.owns??[]){let c=t.get(a)??[];c.push(r),t.set(a,c)}let e=new Map;function s(r,i=new Set){if(e.has(r))return e.get(r);if(i.has(r))return new Set;i.add(r);let a=n[r]?.deps??[],c=new Set(a);for(let l of a)for(let u of s(l,i))c.add(u);return e.set(r,c),c}for(let r of Object.keys(n))s(r);let o=[];for(let[r,i]of t){if(i.length<2)continue;let a=[];for(let c=0;c<i.length;c++){let l=!1;for(let u=0;u<i.length;u++){if(c===u)continue;let d=e.get(i[c])??new Set,f=e.get(i[u])??new Set;if(d.has(i[u])||f.has(i[c])){l=!0;break}}l||a.push(i[c])}a.length>=2&&o.push({file:r,streams:a,suggestion:`${r} is modified by ${a.join(" and ")} in the same wave. Split into separate waves by adding a dependency edge, or merge into one stream.`})}return o}function Un(n){let t=qe(n),e=0,s=[];for(let o of t)for(let r=1;r<o.streams.length;r++){let i=n[o.streams[r]],a=o.streams[r-1],c=i.deps??[];c.includes(a)||(c.push(a),i.deps=c,e++,s.push(`Added dep: ${o.streams[r]} \u2192 ${a} (shared file: ${o.file})`))}return{edgesAdded:e,fixes:s}}function zn(){return{yamlBlocksFound:0,yamlBlocksParsed:0,yamlParseErrors:[],extractionPath:null,sectionsFound:{},sectionsFilteredAsMeta:[],deliverableCount:0,splitCount:0,unmatchedDeps:[],ownershipConflicts:[],warnings:[]}}function Hn(n){let t=new Map;for(let[s,o]of Object.entries(n))for(let r of o.owns||[]){let i=t.get(r)||[];i.push(s),t.set(r,i)}let e=[];for(let[s,o]of t)o.length>1&&e.push(`${s} owned by: ${o.join(", ")}`);return e}import{randomUUID as os}from"crypto";import{existsSync as Zn,statSync as es}from"node:fs";import*as Je from"node:path";var Bn=[{pattern:/model.*not.found|not_found_error.*model|Model ".*" not found/i,category:"model_not_found",retryable:!1,selfHealable:!1,suggestion:"Model not found. Check the model name in your configuration and ensure it is available for your API key."},{pattern:/invalid api key|api key.*expired|authentication failed|(?<!\d)401(?!\d)|unauthorized/i,category:"auth_error",retryable:!1,selfHealable:!1,suggestion:"Authentication error. Check your API key configuration and ensure it is valid and not expired."},{pattern:/cloud api error: 5\d{2}|502 bad gateway|503 service unavailable|504 gateway timeout|internal server error|overloaded_error/i,category:"server_error",retryable:!0,selfHealable:!1,suggestion:"Cloud server error. Transport retries exhausted \u2014 try again later or switch to local mode."},{pattern:/timed?\s*out|ETIMEDOUT|deadline|timeout/i,category:"timeout",retryable:!1,selfHealable:!1,suggestion:"Timeout is an infrastructure issue. Consider increasing stream timeout or reducing scope."},{pattern:/network error|ECONNREFUSED|ECONNRESET|EHOSTUNREACH|socket hang up/i,category:"network",retryable:!1,selfHealable:!1,suggestion:"Network connectivity issue. Check API endpoint availability and network configuration."},{pattern:/rate limit|too many requests|429|quota exceeded/i,category:"rate_limit",retryable:!1,selfHealable:!1,suggestion:"Rate limited by API. Wait before retrying or reduce parallel stream count."},{pattern:/old_?content.*not found|edit.*mismatch|does not match|oldContent/i,category:"edit_mismatch",retryable:!0,selfHealable:!0,suggestion:"The file content changed since context was built. Re-read the file and retry with updated content."},{pattern:/invalid.*artifact|parse.*error|orchex-artifact.*not found|JSON\.parse/i,category:"invalid_artifact",retryable:!0,selfHealable:!0,suggestion:"The agent produced malformed output. Retry with clearer instructions about the artifact format."},{pattern:/ENOENT|EACCES|EPERM|ENOSPC|no such file|permission denied/i,category:"environment",retryable:!1,selfHealable:!1,suggestion:"File system error. Check file paths and permissions."},{pattern:/ownership violation|outside owned files|SECURITY.*path traversal|SECURITY.*absolute path/i,category:"ownership_violation",retryable:!0,selfHealable:!0,suggestion:"File operation attempted outside owned files. The fix stream should only modify files in the owns list, or the owns list should be updated to include the new file."},{pattern:/test.*fail|expect.*received|assertion.*error|FAIL\s+tests\//i,category:"test_failure",retryable:!0,selfHealable:!0,suggestion:"Tests are failing. Include the test error output in the retry prompt so the agent can fix the issue."},{pattern:/lint|eslint|prettier|formatting/i,category:"lint_error",retryable:!0,selfHealable:!0,suggestion:"Lint or formatting error. Include the lint output in the retry prompt."},{pattern:/TypeError|ReferenceError|SyntaxError|Cannot find module|cannot find name|TS\d{4}/i,category:"runtime_error",retryable:!0,selfHealable:!0,suggestion:"Code has type or runtime errors. Include the error output and relevant type definitions in the retry prompt."}];function fe(n,t){for(let{pattern:s,category:o,retryable:r,selfHealable:i,suggestion:a}of Bn)if(s.test(n))return{category:o,retryable:r,selfHealable:i,suggestion:a};let e=t==="artifact"||t==="verify";return{category:"unknown",retryable:e,selfHealable:e,suggestion:e?"Unknown code error. Retry with the full error message included in the prompt.":`Unknown infrastructure error (origin: ${t??"unspecified"}). Check API key, model availability, and network connectivity.`}}import{loadManifest as Ve,saveManifest as Ye}from"../manifest.js";import{createLogger as qn}from"../logging.js";var pe=qn("fix-stream-manager");async function Vn(n){let t=await Ve(n),e={skipped:[],warnings:[]},s=Object.entries(t.streams).filter(([o,r])=>r.parentStreamId!==void 0);for(let[o,r]of s)r.status==="pending"&&Kn(t,r.parentStreamId)&&(t.streams[o].status="skipped",t.streams[o].error="Parent stream completed; fix no longer needed",e.skipped.push(o));return e.skipped.length>0&&await Ye(n,t),e}async function Yn(n,t){let e=await Ve(n),s={skipped:[],warnings:[]},o=Qn(e,t);for(let a of o){let c=e.streams[a];c.status==="pending"?(e.streams[a].status="skipped",e.streams[a].error=`Ancestor '${t}' completed; fix no longer needed`,s.skipped.push(a)):c.status==="in_progress"&&(e.streams[a].status="skipped",e.streams[a].error=`Sibling fix already resolved this stream (completed: '${t}')`,s.skipped.push(a))}let r=!1,i=e.streams[t];if(i?.parentStreamId){let a=i.parentStreamId;for(;e.streams[a]?.parentStreamId;)a=e.streams[a].parentStreamId;let c=e.streams[a];c&&c.status==="failed"&&(e.streams[a].status="complete",delete e.streams[a].error,r=!0,pe.info({fixStreamId:t,rootStreamId:a},"fix_stream_propagated_completion_to_root"))}return(s.skipped.length>0||r)&&await Ye(n,e),s}function X(n,t){let e=n.streams[t];if(!e||!e.parentStreamId)return null;let s=[t],o=e.parentStreamId,r=new Set;for(;o&&!r.has(o);){r.add(o);let i=n.streams[o];if(!i)break;if(s.unshift(o),!i.parentStreamId)return{rootStreamId:o,fixChain:s.slice(1),rootStatus:i.status??"pending"};o=i.parentStreamId}return null}function Gn(n,t){return n.streams[t]?.parentStreamId!==void 0}function Jn(n,t){return X(n,t)?.rootStreamId??t}function Kn(n,t){let e=t,s=new Set;for(;e;){if(s.has(e)){pe.warn({streamId:e},"circular_reference_in_fix_chain");break}s.add(e);let o=n.streams[e];if(!o){pe.warn({parentId:e},"fix_stream_orphaned_parent");break}if(o.status==="complete")return!0;e=o.parentStreamId}return!1}function Qn(n,t){let e=[];for(let[s,o]of Object.entries(n.streams))o.parentStreamId&&Xn(n,s,t)&&e.push(s);return e}function Xn(n,t,e){let s=n.streams[t]?.parentStreamId,o=new Set;for(;s&&!o.has(s);){if(o.add(s),s===e)return!0;s=n.streams[s]?.parentStreamId}return!1}var Ke=3;function Qe(n,t){if(!n||n.length===0)return"";let e=[],s=[];for(let r of n)try{let i=Je.resolve(t,r);Zn(i)&&es(i).isFile()?e.push(r):s.push(r)}catch{}if(e.length===0&&s.length===0)return"";let o=["","### Disk State (for files you own)"];if(e.length>0){o.push(""),o.push("The following files currently exist on disk from a previous attempt:");for(let r of e)o.push(`- ${r}`)}if(s.length>0){o.push(""),o.push("The following files do NOT exist on disk:");for(let r of s)o.push(`- ${r}`)}return o.push(""),o.push('IMPORTANT: For files that already exist, use operation type `edit` or `replace`, NEVER `create`. Using `create` on an existing file will fail with "Conflicts detected" and this fix attempt will be wasted.'),s.length>0&&o.push("For files that do NOT exist, use `create`."),o.join(`
155
+ `)}function Xe(n,t){let e=0,s=t;for(;s;){let o=n.streams[s];if(!o)break;e+=o.attempts??0,s=o.parentStreamId}return e}function Ge(n,t){return X(n,t)?.rootStreamId??t}function Ze(n,t){let e=Ge(n,t);for(let[s,o]of Object.entries(n.streams)){if(s===t||!o.parentStreamId||o.status!=="pending"&&o.status!=="in_progress")continue;if(Ge(n,s)===e)return!0}return!1}function ts(n,t,e,s,o){let r=n.streams[t];if(!r||r.status==="failed"&&r.error?.startsWith("Setup failed:"))return null;let i=r.error??"",a=e??fe(i);if(!a.selfHealable||Ze(n,t)||Xe(n,t)>=Ke)return null;let u=(r.attempts??0)+1,d=`${t}-fix-${u}`,f=t,p=o?Qe(r.owns??[],o):"",m=[`## Fix Attempt #${u} for "${r.name}"`,"","### Original Plan",r.plan??"(no plan)","","### Error That Occurred","```",i,"```","",`### Error Category: ${a.category}`,"",`### Suggestion: ${a.suggestion}`,"","### Instructions",`This is a retry of the failed stream "${t}".`,"Fix the issue described above. The original files are in your owns list.","Make sure to address the specific error before implementing the rest of the plan.",...s?["","### Upstream Dependency Warning",`Your error references '${s.errorRef}' which is likely defined by upstream stream '${s.suspectStreamId}'.`,`That stream owns: ${s.suspectFiles.join(", ")}`,"Before fixing your own code, verify that the upstream dependency exports the types/values you need.","If the upstream output is incorrect (wrong type names, missing exports), this fix will fail again.","In that case, the issue will be escalated to fix the upstream stream directly."]:[],...p?[p]:[]].join(`
156
+ `),h={name:`${r.name} (Fix #${u})`,deps:r.deps??[],owns:r.owns??[],reads:r.reads??[],plan:m,setup:r.setup??[],verify:r.verify??[],status:"pending",attempts:0,parentStreamId:f};return{fixStreamId:d,fixStream:h,analysis:{category:a.category,suggestion:a.suggestion}}}function ns(n,t){let e=n.streams[t];if(!e?.error)return null;let s=e.deps??[];if(s.length===0)return null;let o=/(?:Cannot find (?:name|module) '(\w+)'|Type '(\w+)'|has no (?:exported )?member '(\w+)'|is not assignable to type '(\w+)'|does not exist on type '(\w+)'|Property '(\w+)' does not exist)/gi,r=new Set,i;for(;(i=o.exec(e.error))!==null;){let a=i[1]||i[2]||i[3]||i[4]||i[5]||i[6];a&&r.add(a)}if(r.size===0)return null;for(let a of s){let c=n.streams[a];if(!c||c.status!=="complete")continue;let l=c.owns??[];if(l.length===0)continue;let u=l.filter(d=>d.endsWith(".ts")||d.endsWith(".tsx")||d.endsWith(".d.ts"));if(u.length!==0)for(let d of r){let f=d.toLowerCase();if(u.some(m=>{let h=m.toLowerCase();return h.includes("type")||h.includes("index")||h.includes(f)||h.includes("model")||h.includes("schema")||h.includes("interface")}))return{suspectStreamId:a,errorRef:d,suspectFiles:u}}}return null}function me(n,t){if(t.length<2)return null;let e=new Map;for(let d of t){let f=n.streams[d];f?.error&&e.set(d,f.error)}if(e.size<2)return null;let s=/(?:Cannot find (?:name|module)|Type '(\w+)'|has no (?:exported )?member '(\w+)'|is not assignable|does not exist on type '(\w+)')/.source,o=new Map;for(let[d,f]of e){let p=new RegExp(s,"gi"),m,h=new Set;for(;(m=p.exec(f))!==null;){let y=m[1]||m[2]||m[3]||m[0];h.add(y)}for(let y of h){let C=o.get(y)??[];C.push(d),o.set(y,C)}}let r="",i=0;for(let[d,f]of o)f.length>i&&(r=d,i=f.length);if(i<2)return null;let a=o.get(r),c=new Map;for(let d of a){let f=n.streams[d];for(let p of f?.deps??[])c.set(p,(c.get(p)??0)+1)}let l="",u=0;for(let[d,f]of c)n.streams[d]?.status==="complete"&&f>u&&(l=d,u=f);return l?{rootCauseStreamId:l,reason:`Stream '${l}' completed but ${a.length} downstream streams failed with errors referencing '${r}'`,affectedStreamIds:a,commonErrorPattern:r}:null}function ss(n,t,e){let s=t.rootCauseStreamId,o=n.streams[s];if(!o||o.status!=="failed"||Xe(n,s)>=Ke||Ze(n,s))return null;let a=(o.attempts??0)+1,c=`${s}-fix-${a}`,l=[];for(let p of t.affectedStreamIds.slice(0,3)){let m=n.streams[p];m?.error&&l.push(`- ${m.name}: ${m.error.slice(0,200)}`)}let u=e?Qe(o.owns??[],e):"",d=[`## Root Cause Fix #${a} for "${o.name}"`,"","### Original Plan",o.plan??"(no plan)","","### Problem Identified",`This stream completed but its output caused ${t.affectedStreamIds.length} downstream streams to fail.`,`All downstream errors reference: **${t.commonErrorPattern}**`,"","### Downstream Error Samples",...l,"","### Instructions",`This stream's output is incorrect. The code you produce must define '${t.commonErrorPattern}' correctly`,"so that downstream streams importing from this file can compile successfully.","Re-read the original plan carefully and ensure your output matches the specified types, exports, and signatures exactly.","Pay special attention to type definitions, enum values, and const arrays \u2014 they must match what downstream code expects.",...u?[u]:[]].join(`
157
+ `),f={name:`${o.name} (Root Cause Fix #${a})`,deps:o.deps??[],owns:o.owns??[],reads:o.reads??[],plan:d,setup:o.setup??[],verify:o.verify??[],status:"pending",attempts:0,parentStreamId:s};return{fixStreamId:c,fixStream:f,analysis:{category:"runtime_error",suggestion:t.reason}}}function rs(n,t,e){let s=100,o=n.filter(r=>r.status==="failed").length;return s-=o*20,s-=e*10,s+=t*5,Math.max(0,Math.min(100,s))}function is(n,t,e){let s=n.runId??os(),o=new Date().toISOString(),r=[];for(let g of t)r.push(...g.streams);let i=new Set;for(let g of t)if(g.fixStreamsGenerated)for(let w of g.fixStreamsGenerated)i.add(w);for(let[g,w]of Object.entries(n.streams))w.parentStreamId&&i.add(g);let a=new Map;for(let g of r)a.set(g.id,g);let c=[...a.values()].map(g=>({id:g.id,name:g.name,status:g.status,tokensUsed:g.tokensUsed,executionTimeMs:g.executionTimeMs,selfHealCount:i.has(g.id)?1:0,errorCategory:g.errorDetail?.category,errorMessage:g.error,errorSuggestion:g.errorDetail?.suggestion,errorRetryable:g.errorDetail?.retryable,errorSelfHealable:g.errorDetail?.selfHealable,provider:g.provider,model:g.model,filesChanged:g.filesChanged})),l=0,u=0,d={};for(let g of r)if(g.tokensUsed){l+=g.tokensUsed.input,u+=g.tokensUsed.output;let w=g.provider??"unknown";d[w]||(d[w]={input:0,output:0}),d[w].input+=g.tokensUsed.input,d[w].output+=g.tokensUsed.output}let f=0,p=0;for(let g of t)g.timing&&(f+=g.timing.parallelMs,p+=g.timing.sequentialMs);let m=new Set;for(let g of r)if(g.filesChanged)for(let w of g.filesChanged)m.add(w);let h=0;for(let g of t)g.streams.length>0&&g.streams.every(w=>w.status==="complete")&&h++;let y={};for(let g of r)if(g.status==="failed"&&g.errorDetail?.category){let w=g.errorDetail.category;y[w]=(y[w]??0)+1}let C,T=r.filter(g=>g.status==="failed").map(g=>g.id);if(T.length>=2){let g=me(n,T);g&&(C=g)}let S=i.size,x=rs(r,h,S);return{runId:s,timestamp:o,feature:n.feature,planQualityScore:x,streamResults:c,waveEfficiency:{parallelMs:f,sequentialMs:p,timeSavedMs:Math.max(0,p-f)},autoPlanAccuracy:e?.autoPlanEdits!==void 0?{editsBeforeApproval:e.autoPlanEdits}:void 0,tokenUsage:{totalInput:l,totalOutput:u,byProvider:d},fileChangeImpact:{filesCreated:0,filesModified:m.size,totalFilesChanged:m.size},failurePatterns:y,failureCorrelation:C,totalWaves:t.length,totalStreams:a.size}}async function as(n,t){let{mkdir:e,writeFile:s}=await import("fs/promises"),{join:o}=await import("path"),r=o(n,".orchex","reports");await e(r,{recursive:!0});let i=o(r,`${t.runId}.json`);return await s(i,JSON.stringify(t,null,2),"utf-8"),i}import{formatDuration as cs}from"../types.js";function ls(n,t){let e=[];if(n.waveEfficiency.timeSavedMs>0&&n.totalStreams>1){let r=cs(n.waveEfficiency.timeSavedMs),i=n.waveEfficiency.sequentialMs>0?Math.round(n.waveEfficiency.timeSavedMs/n.waveEfficiency.sequentialMs*100):0;e.push(`${n.totalStreams} streams ran in parallel across ${n.totalWaves} wave(s), saving ${r} (${i}%).`)}else n.totalStreams>1&&e.push(`${n.totalStreams} streams executed across ${n.totalWaves} wave(s).`);let s=Object.entries(n.failurePatterns);if(s.length>0){s.sort((c,l)=>l[1]-c[1]);let[r,i]=s[0],a=s.reduce((c,[,l])=>c+l,0);r==="type_error"?e.push(`${r} was the most common failure (${i}/${a}). Consider adding a types-only stream first.`):e.push(`${r} was the most common failure (${i}/${a}).`)}if(t&&t.length>0){let r=t.reduce((a,c)=>a+c.planQualityScore,0)/t.length,i=n.planQualityScore-r;i>10?e.push(`Plan quality improved from ${Math.round(r)} to ${n.planQualityScore} \u2014 orchex is learning your patterns.`):i<-10?e.push(`Plan quality dropped from ${Math.round(r)} to ${n.planQualityScore}. Review the failure patterns above.`):e.push(`Plan quality score: ${n.planQualityScore}/100 (consistent with previous runs at ~${Math.round(r)}).`)}else e.push(`Plan quality score: ${n.planQualityScore}/100.`);let o=n.tokenUsage.totalInput+n.tokenUsage.totalOutput;if(o>0&&e.length<3){let r=Object.keys(n.tokenUsage.byProvider);r.length>1&&e.push(`Used ${r.length} providers: ${r.join(", ")} \u2014 total ${o.toLocaleString()} tokens.`)}return e.slice(0,3)}import*as b from"fs/promises";import*as R from"path";var et=".first-run-complete";async function us(n){let t=R.join(n,".orchex");try{await b.access(t)}catch{return!0}try{return await b.access(R.join(t,et)),!1}catch{}try{let e=R.join(t,"archive");if((await b.readdir(e)).length>0)return!1}catch{}try{let e=R.join(t,"reports");if((await b.readdir(e)).some(o=>o.endsWith(".json")))return!1}catch{}try{let e=R.join(t,"learn","events.jsonl");if((await b.stat(e)).size>0)return!1}catch{}return!0}async function ds(n){let t=R.join(n,".orchex");await b.mkdir(t,{recursive:!0}),await b.writeFile(R.join(t,et),new Date().toISOString(),"utf-8")}function fs(){return["Welcome to orchex! This looks like your first time using orchex in this project.","","Try a quick demo to see orchestration in action:",' orchex run "Add a hello world API endpoint to this project"',"","Or use the MCP auto tool in your AI assistant:",' auto({ prompt: "Add a health check endpoint" })',"","Orchex will generate a plan, show you a preview, and execute in parallel.","Learn more: https://orchex.dev/docs/user-guide/quickstart"].join(`
158
+ `)}import*as B from"fs/promises";import*as P from"path";async function ps(n,t){if(!t.confirm)throw new Error("Reset learning requires --confirm flag. This permanently deletes learning data.");let e=[],s=P.join(n,".orchex","learn"),o=P.join(n,".orchex","reports");t.patternsOnly?await Z(P.join(s,"patterns.json"),e):t.reportsOnly?await tt(o,e,".json"):(await Z(P.join(s,"thresholds.json"),e),await Z(P.join(s,"events.jsonl"),e),await Z(P.join(s,"patterns.json"),e),await tt(o,e,".json"));let r=t.patternsOnly?"patterns":t.reportsOnly?"reports":"all learning data";return{deleted:e,totalDeleted:e.length,message:e.length>0?`Reset ${r}: ${e.length} file(s) deleted.`:`No ${r} found to delete.`}}async function Z(n,t){try{await B.unlink(n),t.push(P.basename(n))}catch(e){if(e.code!=="ENOENT")throw e}}async function tt(n,t,e){try{let s=await B.readdir(n);for(let o of s)e&&!o.endsWith(e)||(await B.unlink(P.join(n,o)),t.push(o))}catch(s){if(s.code!=="ENOENT")throw s}}import{createLogger as ms}from"../logging.js";var hs=ms("iteration-evaluator");function gs(n){let{streamResults:t,iterationNumber:e,maxIterations:s,intent:o}=n;if(e>=s){let d=t.filter(f=>f.status==="failed"||!f.verifyPassed).length;return{complete:!0,reason:`Reached max iterations (${s})${d>0?` with ${d} unresolved failure(s)`:""}`,failureSummary:d>0?t.filter(f=>f.status==="failed").map(f=>`${f.id}: ${f.error}`).join("; "):void 0}}let r=t.filter(d=>d.status==="failed"),i=t.filter(d=>d.status==="complete"&&!d.verifyPassed);if(r.length===0&&i.length===0)return{complete:!0,reason:`All ${t.length} stream(s) completed and verified successfully`};let c=[];for(let d of r)c.push(`Stream "${d.id}" failed: ${d.error??"unknown error"}`);for(let d of i)c.push(`Stream "${d.id}" verify failed: ${d.verifyError??"verification error"}`);let l=c.join("; "),u=`Fix the following issues from the previous attempt to "${o}": ${l}`;return hs.info({iteration:e,failed:r.length,verifyFailed:i.length},"iteration_incomplete"),{complete:!1,reason:`${r.length} stream(s) failed, ${i.length} verification(s) failed`,nextIntent:u,failureSummary:l}}var ys={id:"documentation-set",name:"Documentation Set",description:"Multiple documentation files (guides, tutorials, API references) that should be created independently",keywords:["docs","documentation","guide","tutorial","readme","api reference","multiple pages"],patterns:["Multiple .md files in docs/","Creating 3+ documentation files","Tutorial series","API documentation pages"],streamStructure:[{namePattern:"docs-{topic}",purpose:"Create documentation for a specific topic",dependsOn:[],ownsPatterns:["docs/{topic}/**/*.md"],readsPatterns:["src/**/*.ts","README.md"],planOutline:"Research implementation \u2192 Write documentation \u2192 Add examples \u2192 Review completeness"}],guidelines:["Split by logical topic, not file count","Each stream should own 1-3 related doc files","Order dependencies: concepts \u2192 API reference \u2192 tutorials \u2192 advanced guides","Streams can run in parallel if topics are independent","Keep related examples with their topic"]},ws={id:"code-feature",name:"Code Feature Implementation",description:"Multi-component feature with types, implementation, tests, and documentation",keywords:["feature","implement","add","create","types","tests","integration"],patterns:["Types \u2192 Implementation \u2192 Tests \u2192 Docs","Multiple source files with dependencies","Test files alongside implementation","Integration with existing code"],streamStructure:[{namePattern:"{feature}-types",purpose:"Define interfaces, types, and schemas",dependsOn:[],ownsPatterns:["src/types/{feature}.ts","src/schemas/{feature}.ts"],readsPatterns:["src/types.ts"],planOutline:"Analyze requirements \u2192 Define types \u2192 Add validation schemas \u2192 Export types"},{namePattern:"{feature}-core",purpose:"Core feature implementation",dependsOn:["{feature}-types"],ownsPatterns:["src/{feature}/*.ts"],readsPatterns:["src/types/{feature}.ts","src/utils/*.ts"],planOutline:"Implement core logic \u2192 Add error handling \u2192 Integrate with existing systems"},{namePattern:"{feature}-tests",purpose:"Unit and integration tests",dependsOn:["{feature}-core"],ownsPatterns:["tests/{feature}.test.ts"],readsPatterns:["src/{feature}/*.ts"],planOutline:"Write unit tests \u2192 Add integration tests \u2192 Test edge cases \u2192 Verify coverage"},{namePattern:"{feature}-docs",purpose:"Documentation and examples",dependsOn:["{feature}-core"],ownsPatterns:["docs/{feature}/*.md"],readsPatterns:["src/{feature}/*.ts"],planOutline:"Document API \u2192 Add usage examples \u2192 Write integration guide"}],guidelines:["Always start with types to establish contracts","Core implementation depends on types being defined","Tests and docs can run in parallel after core is complete","Keep streams focused: one stream = one responsibility","If a file has 200+ lines, consider splitting implementation into multiple streams"]},xs={id:"migration",name:"Migration",description:"Migrating code, data, or structure with backward compatibility",keywords:["migration","migrate","refactor","rename","move","deprecate","backward compatible"],patterns:["From old to new","Rename/move files or functions","Change data structure","Update multiple call sites","Maintain backward compatibility"],streamStructure:[{namePattern:"{migration}-new-implementation",purpose:"Create new implementation alongside old one",dependsOn:[],ownsPatterns:["src/{new}/*.ts"],readsPatterns:["src/{old}/*.ts"],planOutline:"Implement new version \u2192 Match old API \u2192 Add compatibility layer"},{namePattern:"{migration}-migrate-{component}",purpose:"Migrate specific component to new implementation",dependsOn:["{migration}-new-implementation"],ownsPatterns:["src/{component}/**/*.ts"],readsPatterns:["src/{new}/*.ts","src/{old}/*.ts"],planOutline:"Update imports \u2192 Replace function calls \u2192 Update tests \u2192 Verify behavior"},{namePattern:"{migration}-deprecate-old",purpose:"Mark old implementation as deprecated",dependsOn:["{migration}-migrate-*"],ownsPatterns:["src/{old}/*.ts"],readsPatterns:[],planOutline:"Add deprecation notices \u2192 Update docs \u2192 Plan removal timeline"}],guidelines:["Create new before removing old","Migrate in small, independent chunks (by component/module)","Each migration stream should be independently testable","Keep deprecation as the final step","Ensure each stream leaves the codebase in a working state"]},Ss={id:"tutorial",name:"Tutorial Series",description:"Progressive tutorial series from basics to advanced",keywords:["tutorial","guide","example","walkthrough","getting started","beginner","advanced"],patterns:["Multiple tutorial steps","Progressive complexity","Beginner \u2192 Intermediate \u2192 Advanced","Examples with documentation"],streamStructure:[{namePattern:"tutorial-{level}-{topic}",purpose:"Create tutorial for specific level and topic",dependsOn:["tutorial-{previous-level}-*"],ownsPatterns:["docs/tutorials/{level}-{topic}.md","examples/{topic}/**/*"],readsPatterns:["src/**/*.ts","docs/tutorials/{previous}*.md"],planOutline:"Define learning objectives \u2192 Write tutorial \u2192 Create working example \u2192 Add exercises"}],guidelines:["Order by prerequisite knowledge: basics \u2192 intermediate \u2192 advanced","Each tutorial should be self-contained but build on previous concepts","Include working code examples","Beginner tutorials can run in parallel if they cover different topics","Advanced tutorials depend on relevant beginner/intermediate tutorials"]},$s={id:"api-reference",name:"API Reference",description:"Comprehensive API documentation for modules, classes, and functions",keywords:["api","reference","documentation","modules","classes","functions","methods"],patterns:["Documenting multiple modules","Class/function reference","Method documentation","Parameter and return type docs"],streamStructure:[{namePattern:"api-{module}-reference",purpose:"Create API reference for a specific module",dependsOn:[],ownsPatterns:["docs/api/{module}.md"],readsPatterns:["src/{module}/**/*.ts"],planOutline:"Extract types/interfaces \u2192 Document functions \u2192 Add examples \u2192 Cross-link related APIs"}],guidelines:["Split by module or logical grouping","All API reference streams can run in parallel","Include type signatures and examples","Cross-reference related APIs","Keep each stream to 1-2 related modules"]},vs=[ys,ws,xs,Ss,$s];function ee(n){let t=n.toLowerCase(),e=null;for(let s of vs){let o=0;for(let r of s.keywords)t.includes(r.toLowerCase())&&(o+=2);for(let r of s.patterns){let i=r.toLowerCase().split(/[\s/,]+/).filter(c=>c.length>2);i.filter(c=>t.includes(c)).length>=i.length/2&&(o+=1)}o>0&&(!e||o>e.score)&&(e={template:s,score:o})}return e&&e.score>=3?e.template:null}function he(n,t){let e=[];if(n.id==="documentation-set"){let s=t.topics||[];for(let o of s)e.push({name:`docs-${o}`,deps:[],owns:[`docs/${o}/**/*.md`],reads:["src/**/*.ts","README.md"],plan:`Research ${o} implementation \u2192 Write documentation \u2192 Add examples \u2192 Review completeness`})}else if(n.id==="code-feature"){let s=t.featureName;e.push({name:`${s}-types`,deps:[],owns:[`src/types/${s}.ts`],reads:["src/types.ts"],plan:"Analyze requirements \u2192 Define types \u2192 Add validation schemas \u2192 Export types"},{name:`${s}-core`,deps:[`${s}-types`],owns:[`src/${s}/*.ts`],reads:[`src/types/${s}.ts`,"src/utils/*.ts"],plan:"Implement core logic \u2192 Add error handling \u2192 Integrate with existing systems"},{name:`${s}-tests`,deps:[`${s}-core`],owns:[`tests/${s}.test.ts`],reads:[`src/${s}/*.ts`],plan:"Write unit tests \u2192 Add integration tests \u2192 Test edge cases \u2192 Verify coverage"},{name:`${s}-docs`,deps:[`${s}-core`],owns:[`docs/${s}/*.md`],reads:[`src/${s}/*.ts`],plan:"Document API \u2192 Add usage examples \u2192 Write integration guide"})}else if(n.id==="migration"){let s=t.featureName,o=t.components||[];e.push({name:`${s}-new-implementation`,deps:[],owns:[`src/${s}-new/*.ts`],reads:[`src/${s}-old/*.ts`],plan:"Implement new version \u2192 Match old API \u2192 Add compatibility layer"});for(let r of o)e.push({name:`${s}-migrate-${r}`,deps:[`${s}-new-implementation`],owns:[`src/${r}/**/*.ts`],reads:[`src/${s}-new/*.ts`,`src/${s}-old/*.ts`],plan:"Update imports \u2192 Replace function calls \u2192 Update tests \u2192 Verify behavior"});e.push({name:`${s}-deprecate-old`,deps:o.map(r=>`${s}-migrate-${r}`),owns:[`src/${s}-old/*.ts`],reads:[],plan:"Add deprecation notices \u2192 Update docs \u2192 Plan removal timeline"})}else if(n.id==="tutorial"){let s=t.topics||[];for(let o of s)e.push({name:`tutorial-${o}`,deps:[],owns:[`docs/tutorials/${o}.md`,`examples/${o}/**/*`],reads:["src/**/*.ts"],plan:"Define learning objectives \u2192 Write tutorial \u2192 Create working example \u2192 Add exercises"})}else if(n.id==="api-reference"){let s=t.modules||[];for(let o of s)e.push({name:`api-${o}-reference`,deps:[],owns:[`docs/api/${o}.md`],reads:[`src/${o}/**/*.ts`],plan:"Extract types/interfaces \u2192 Document functions \u2192 Add examples \u2192 Cross-link related APIs"})}return e}function Cs(n){let t=n.owns||[],e=n.reads||[];if(t.length>5)return{originalStream:n.name,reason:`Stream owns ${t.length} files, which may be too many for a single stream`,guidance:["Consider grouping related files together","Split by logical component or responsibility","Create dependencies between resulting streams if needed"],suggestedStreams:[]};if(e.length>10)return{originalStream:n.name,reason:`Stream reads ${e.length} files, which may indicate broad scope`,guidance:["Reading many files often means the stream is doing too much","Consider splitting into smaller, focused streams","Each stream should ideally read 3-5 context files"],suggestedStreams:[]};let s=`${n.name} ${n.plan||""}`,o=ee(s);return o&&["multiple","all","complete","full","entire"].some(a=>n.name.toLowerCase().includes(a))?{originalStream:n.name,reason:"Stream name suggests broad scope that could be split",template:o,guidance:o.guidelines,suggestedStreams:[]}:null}function ks(n,t,e){if(e.issues.length===0)return null;let s=e.issues.some(l=>l.severity==="error"),o=e.issues.some(l=>l.severity==="warning"),r=`${t.name??n} ${t.plan??""}`,i=ee(r),a=null;if(i){let l=n.replace(/-/g,"_");a=he(i,{featureName:l})}let c="";s?c=`Stream "${n}" has critical issues:
157
159
  `:o?c=`Stream "${n}" has potential issues:
158
160
  `:c=`Stream "${n}" has suggestions:
159
161
  `;for(let l of e.issues){let u=l.severity==="error"?"\u274C":l.severity==="warning"?"\u26A0\uFE0F":"\u2139\uFE0F";c+=` ${u} ${l.message}
@@ -163,23 +165,23 @@ Reference code:
163
165
  `;for(let l of a){let u=l.owns?.join(", ")??"TBD";c+=` \u2022 ${l.name}: ${u}
164
166
  `}c+=`
165
167
  Accept suggested split? [Y/n/edit]`}else c+=`
166
- No template match. Consider manual split or ignore.`;return{streamId:n,violations:e.issues,qualityScore:e.qualityScore,templateMatch:i,suggestedSplit:a,message:c,action:s?"accept_split":o?"modify":"ignore"}}function $s(n,t){let e=t??H(),s=[];for(let[o,r]of Object.entries(n)){let i=e.analyzeStream(o,r),a=Ss(o,r,i);a&&s.push(a)}return s.sort((o,r)=>{let i=o.violations.some(u=>u.severity==="error"),a=r.violations.some(u=>u.severity==="error");if(i&&!a)return-1;if(!i&&a)return 1;let c=o.violations.some(u=>u.severity==="warning"),l=r.violations.some(u=>u.severity==="warning");return c&&!l?-1:!c&&l?1:0}),s}function vs(n){let t=n.filter(r=>r.violations.some(i=>i.severity==="error")).length,e=n.filter(r=>r.violations.some(i=>i.severity==="warning")&&!r.violations.some(i=>i.severity==="error")).length,s=n.filter(r=>r.templateMatch!==null).length,o="";if(n.length===0)o="\u2705 All streams passed validation. No issues detected.";else if(o=`Stream Validation Summary:
168
+ No template match. Consider manual split or ignore.`;return{streamId:n,violations:e.issues,qualityScore:e.qualityScore,templateMatch:i,suggestedSplit:a,message:c,action:s?"accept_split":o?"modify":"ignore"}}function bs(n,t){let e=t??H(),s=[];for(let[o,r]of Object.entries(n)){let i=e.analyzeStream(o,r),a=ks(o,r,i);a&&s.push(a)}return s.sort((o,r)=>{let i=o.violations.some(u=>u.severity==="error"),a=r.violations.some(u=>u.severity==="error");if(i&&!a)return-1;if(!i&&a)return 1;let c=o.violations.some(u=>u.severity==="warning"),l=r.violations.some(u=>u.severity==="warning");return c&&!l?-1:!c&&l?1:0}),s}function Ts(n){let t=n.filter(r=>r.violations.some(i=>i.severity==="error")).length,e=n.filter(r=>r.violations.some(i=>i.severity==="warning")&&!r.violations.some(i=>i.severity==="error")).length,s=n.filter(r=>r.templateMatch!==null).length,o="";if(n.length===0)o="\u2705 All streams passed validation. No issues detected.";else if(o=`Stream Validation Summary:
167
169
  `,o+=` ${t} stream${t!==1?"s":""} with errors
168
170
  `,o+=` ${e} stream${e!==1?"s":""} with warnings
169
171
  `,o+=` ${s} template match${s!==1?"es":""} found
170
172
  `,t>0){o+=`
171
173
  \u274C Critical issues (must fix):
172
174
  `;for(let r of n.filter(i=>i.violations.some(a=>a.severity==="error"))){let i=r.violations.filter(a=>a.severity==="error").map(a=>a.type);o+=` \u2022 ${r.streamId}: ${i.join(", ")}
173
- `}}return{totalStreams:n.length,errorCount:t,warningCount:e,templateMatches:s,summary:o}}function Cs(n){let t=new Map;for(let[l,u]of Object.entries(n))for(let d of u.owns??[]){let f=t.get(d)??[];f.push(l),t.set(d,f)}let e=new Map;function s(l){return e.has(l)||e.set(l,l),e.get(l)!==l&&e.set(l,s(e.get(l))),e.get(l)}function o(l,u){let d=s(l),f=s(u);d!==f&&(d<f?e.set(f,d):e.set(d,f))}for(let[,l]of t)if(!(l.length<2))for(let u=1;u<l.length;u++)o(l[0],l[u]);let r=new Map;for(let l of Object.keys(n)){let u=s(l),d=r.get(u)??[];d.push(l),r.set(u,d)}let i={},a=[],c=new Map;for(let[,l]of r){if(l.length===1){let x=l[0];i[x]=n[x],c.set(x,x);continue}l.sort();let u=l[0],d=[],f=new Set,p=new Set,m=new Set,h=[],y=[];for(let x of l){let g=n[x];d.push(g.name);for(let w of g.owns??[])f.add(w);for(let w of g.reads??[])p.add(w);for(let w of g.deps??[])m.add(w);for(let w of g.verify??[])h.includes(w)||h.push(w);g.plan&&y.push(`## ${g.name}
175
+ `}}return{totalStreams:n.length,errorCount:t,warningCount:e,templateMatches:s,summary:o}}function Es(n){let t=new Map;for(let[l,u]of Object.entries(n))for(let d of u.owns??[]){let f=t.get(d)??[];f.push(l),t.set(d,f)}let e=new Map;function s(l){return e.has(l)||e.set(l,l),e.get(l)!==l&&e.set(l,s(e.get(l))),e.get(l)}function o(l,u){let d=s(l),f=s(u);d!==f&&(d<f?e.set(f,d):e.set(d,f))}for(let[,l]of t)if(!(l.length<2))for(let u=1;u<l.length;u++)o(l[0],l[u]);let r=new Map;for(let l of Object.keys(n)){let u=s(l),d=r.get(u)??[];d.push(l),r.set(u,d)}let i={},a=[],c=new Map;for(let[,l]of r){if(l.length===1){let x=l[0];i[x]=n[x],c.set(x,x);continue}l.sort();let u=l[0],d=[],f=new Set,p=new Set,m=new Set,h=[],y=[];for(let x of l){let g=n[x];d.push(g.name);for(let w of g.owns??[])f.add(w);for(let w of g.reads??[])p.add(w);for(let w of g.deps??[])m.add(w);for(let w of g.verify??[])h.includes(w)||h.push(w);g.plan&&y.push(`## ${g.name}
174
176
 
175
- ${g.plan}`),c.set(x,u)}for(let x of f)p.delete(x);let v=new Set(l);for(let x of v)m.delete(x);let T,S=[];for(let x of l){let g=n[x];g.timeoutMs&&(!T||g.timeoutMs>T)&&(T=g.timeoutMs);for(let w of g.setup??[])S.includes(w)||S.push(w)}i[u]={name:d.join(" + "),owns:[...f],reads:[...p],deps:[...m],plan:y.join(`
177
+ ${g.plan}`),c.set(x,u)}for(let x of f)p.delete(x);let C=new Set(l);for(let x of C)m.delete(x);let T,S=[];for(let x of l){let g=n[x];g.timeoutMs&&(!T||g.timeoutMs>T)&&(T=g.timeoutMs);for(let w of g.setup??[])S.includes(w)||S.push(w)}i[u]={name:d.join(" + "),owns:[...f],reads:[...p],deps:[...m],plan:y.join(`
176
178
 
177
179
  ---
178
180
 
179
- `),verify:h,setup:S.length>0?S:void 0,timeoutMs:T},a.push(`Merged [${l.join(", ")}] \u2192 ${u} (shared files: ${[...f].filter(x=>(t.get(x)??[]).length>1).join(", ")})`)}for(let[l,u]of Object.entries(i)){let d=u.deps??[],f=[...new Set(d.map(p=>c.get(p)??p))].filter(p=>p!==l);u.deps=f}return{streams:i,merges:a}}function ks(n){return n.isTestGeneration?{provider:void 0,confidence:.3,reason:"Test generation works well with any provider \u2014 use your default."}:n.isStructuralChange&&(n.totalOwnedLines>500||n.fileCount>4)?{provider:"anthropic",confidence:.7,reason:`Structural edits across ${n.fileCount} files (${n.totalOwnedLines} lines) \u2014 Claude handles complex multi-file reasoning best.`}:!n.isStructuralChange&&n.totalOwnedLines<200&&n.fileCount<=2?{provider:"openai",model:"gpt-4.1-mini",confidence:.6,reason:`Simple transform (${n.totalOwnedLines} lines, ${n.fileCount} files) \u2014 GPT-4.1-mini is cost-effective for small tasks.`}:n.isStructuralChange?{provider:"anthropic",confidence:.5,reason:`Structural changes across ${n.fileCount} files \u2014 Claude recommended for refactoring tasks.`}:{provider:void 0,confidence:.2,reason:"No strong provider preference for this task type \u2014 use your configured default."}}function bs(n,t,e){let s=n.toLowerCase(),o=s.includes("test")||s.includes("spec")||t.some(a=>a.includes(".test.")||a.includes(".spec.")||a.startsWith("tests/")),i=["refactor","restructure","reorganize","migrate","rewrite","split","merge","move","rename","extract","inline","new module","new class","new service","new component"].some(a=>s.includes(a));return{totalOwnedLines:e,isStructuralChange:i,isTestGeneration:o,fileCount:t.length}}import*as D from"fs/promises";import*as ge from"path";import*as te from"yaml";import{exec as Ts}from"child_process";import{promisify as Ps}from"util";var et=Ps(Ts);async function Es(n,t){let e=ge.join(n,".orchex","active","manifest.yaml"),s=await D.readFile(e,"utf-8"),o=te.parse(s),r=new Set(t);for(let[i,a]of Object.entries(o.streams))a.status==="pending"&&(r.has(i)||(o.streams[i].status="skipped"));await D.writeFile(e,te.stringify(o,{indent:2,lineWidth:0}),"utf-8")}async function Os(n,t,e){let s=[],o=[];for(let r of e){let i=ge.join(n,r);try{let{stdout:a}=await et(`git ls-files "${r}"`,{cwd:n});if(a.trim())await et(`git checkout HEAD -- "${r}"`,{cwd:n}),s.push(r);else try{await D.unlink(i),s.push(r)}catch(c){c.code!=="ENOENT"&&o.push(`Failed to delete ${r}: ${c.message}`)}}catch(a){if(a.message?.includes("did not match any"))continue;o.push(`Failed to rollback ${r}: ${a.message}`)}}return{streamId:t,reverted:s,errors:o}}import*as ot from"fs";import*as ye from"path";import{createLogger as Rs}from"../logging.js";var ne={"claude-opus-4-5-20251101":{input:.015,output:.075},"claude-sonnet-4-5-20250929":{input:.003,output:.015},"claude-sonnet-4-20250514":{input:.003,output:.015},"claude-3-5-sonnet-20241022":{input:.003,output:.015},"claude-3-opus-20240229":{input:.015,output:.075},"claude-3-haiku-20240307":{input:25e-5,output:.00125},"gpt-4.5-turbo":{input:.005,output:.015},"gpt-4-turbo":{input:.01,output:.03},"gpt-4-turbo-preview":{input:.01,output:.03},"gpt-4o":{input:.005,output:.015},"gpt-4o-mini":{input:15e-5,output:6e-4},"o1-preview":{input:.015,output:.06},"o1-mini":{input:.003,output:.012},"o3-mini":{input:.0011,output:.0044},"gpt-3.5-turbo":{input:5e-4,output:.0015},"gemini-2.5-pro":{input:.00125,output:.01},"gemini-2.0-flash":{input:1e-4,output:4e-4},"gemini-1.5-pro":{input:.00125,output:.005},"gemini-1.5-flash":{input:75e-6,output:3e-4},"gemini-pro":{input:125e-6,output:375e-6},"deepseek-chat":{input:28e-5,output:42e-5},"deepseek-coder":{input:28e-5,output:42e-5},"deepseek-reasoner":{input:55e-5,output:.00219},"llama3.3:70b":{input:0,output:0},"llama3.2:latest":{input:0,output:0},"mistral:latest":{input:0,output:0},default:{input:.003,output:.015}},Ms=.9;function tt(n){if(ne[n])return ne[n];let t=n.toLowerCase();for(let[e,s]of Object.entries(ne))if(e!=="default"&&t.includes(e.split("-").slice(0,2).join("-")))return s;return ne.default}function nt(n,t,e,s){let o=tt(e),r=n/1e3*o.input,i=t/1e3*o.output,a=r+i,c;s&&s>0&&(c=s/1e3*o.input*Ms);let l=a-(c??0);return{inputTokens:n,outputTokens:t,inputCost:r,outputCost:i,totalCost:a,cacheHitTokens:s,cacheDiscount:c,finalCost:l,model:e}}function Is(n,t,e=.3){let s=Math.ceil(n*e);return nt(n,s,t)}var ar=Rs("smart-router"),st={anthropic:"claude-sonnet-4-5-20250929",openai:"gpt-4.1",google:"gemini-2.5-pro",deepseek:"deepseek-chat",ollama:"llama3.3:70b"};function Fs(n){let t=[...n.owns,...n.reads??[]],e=n.name.toLowerCase(),s=(n.plan??"").toLowerCase();return t.some(o=>o.match(/\.(md|mdx|txt|rst)$/))||e.includes("doc")||e.includes("readme")?"docs":t.some(o=>o.includes(".test.")||o.includes(".spec.")||o.includes("__tests__"))||e.includes("test")?"test":t.some(o=>o.includes("migration"))||e.includes("migrat")?"migration":n.owns.length>=3||(n.estimatedLines??0)>500||s.includes("refactor")||s.includes("restructur")?"complex-code":"simple-code"}function _s(n,t){switch(n){case"docs":return{provider:"deepseek",model:"deepseek-chat",reasoning:`Routed documentation stream "${t.name}" to cheapest provider (DeepSeek)`};case"test":return{provider:"openai",model:"gpt-4o",reasoning:`Routed test stream "${t.name}" to mid-tier provider (GPT-4o)`};case"migration":return{provider:"google",model:"gemini-2.5-pro",reasoning:`Routed migration stream "${t.name}" to cost-effective provider (Gemini)`};case"complex-code":return{provider:"anthropic",model:"claude-sonnet-4-5-20250929",reasoning:`Routed complex code stream "${t.name}" (${t.owns.length} files${(t.estimatedLines??0)>500?", large file edits":""}) to premium provider (Claude)`};default:return{provider:"openai",model:"gpt-4o",reasoning:`Routed simple code stream "${t.name}" to balanced provider (GPT-4o)`}}}function js(n){switch(n){case"docs":return["gemini","openai","anthropic"];case"test":return["anthropic","gemini","deepseek"];case"migration":return["openai","anthropic","deepseek"];case"complex-code":return["openai","gemini","deepseek"];default:return["anthropic","gemini","deepseek"]}}function As(n,t,e){let s=e?.availableProviders,o=e?.registryModels,r=(c,l)=>o?.[c]?.length?o[c].includes(l)?l:o[c][0]:l;if(t.overrides?.[n.id]){let c=t.overrides[n.id];return{provider:c.provider,model:c.model,reasoning:"User override"}}if(t.defaultProvider){let c=t.defaultModel??st[t.defaultProvider]??t.defaultProvider,l=r(t.defaultProvider,c);return{provider:t.defaultProvider,model:l,reasoning:"User default provider preference"}}let i=Fs(n),a=_s(i,n);if(s&&!s.has(a.provider)){let c=js(i);for(let l of c)if(s.has(l)){let u=r(l,st[l]??l);return{provider:l,model:u,reasoning:`${a.reasoning} \u2014 ${a.provider} not available, fell back to ${l}`}}}return a.model=r(a.provider,a.model),a}function Ls(n){let t=n??ye.join(process.env.HOME??"",".orchex"),e=ye.join(t,"config.json");try{let s=ot.readFileSync(e,"utf-8"),o=JSON.parse(s);return{defaultProvider:o.routing?.defaultProvider,defaultModel:o.routing?.defaultModel,overrides:o.routing?.overrides}}catch{return{}}}import*as N from"fs/promises";import*as se from"path";var M;(function(n){n.STREAM_COUNT_SWEET_SPOT="stream-count-sweet-spot",n.DEPENDENCY_ORDERING="dependency-ordering",n.FILE_PER_STREAM="file-per-stream",n.WAVE_EFFICIENCY="wave-efficiency",n.PROVIDER_PERFORMANCE="provider-performance",n.SELF_HEAL_PATTERN="self-heal-pattern",n.TIME_OF_DAY="time-of-day"})(M||(M={}));function Ds(n){let t=n.streamResults.filter(r=>r.status==="complete").length,e=n.streamResults.filter(r=>r.status==="failed").length,s=n.streamResults.filter(r=>r.status==="skipped").length,o=n.streamResults.reduce((r,i)=>r+(i.executionTimeMs??0),0);return{id:n.runId,feature:n.feature,timestamp:n.timestamp,success:n.planQualityScore>=80,totalStreams:n.totalStreams,completedStreams:t,failedStreams:e,skippedStreams:s,totalWaves:n.totalWaves,executionTimeMs:o,streams:n.streamResults.map(r=>({id:r.id,name:r.name,status:r.status,wave:0,filesOwned:0,executionTimeMs:r.executionTimeMs??0,tokensUsed:r.tokensUsed??{input:0,output:0},errorCategory:r.errorCategory}))}}var Ns=5;function Ws(n){if(n.length<Ns)return[];let t=[],e=[Us,zs,Hs,Bs,qs,Vs,Ys];for(let s of e){let o=s(n);o&&t.push(o)}return t}function Us(n){let t={low:{total:0,success:0,ids:[]},mid:{total:0,success:0,ids:[]},high:{total:0,success:0,ids:[]}};for(let u of n){let d=u.totalStreams<=5?"low":u.totalStreams<=8?"mid":"high";t[d].total++,u.success&&t[d].success++,t[d].ids.push(u.id)}if(t.low.total<3&&t.mid.total<3||t.high.total<2&&t.mid.total<2)return null;let e=t.low.total>0?t.low.success/t.low.total:0,s=t.high.total>0?t.high.success/t.high.total:0,o=t.mid.total>0?t.mid.success/t.mid.total:0,r=Math.max(e,o),i=Math.min(e,o,s);if(r-i<.2)return null;let a=e>=o?"low (1-5 streams)":"mid (6-8 streams)",c=Math.max(e,o),l=[...t.low.ids,...t.mid.ids,...t.high.ids];return{type:M.STREAM_COUNT_SWEET_SPOT,description:`Plans with ${a} succeed ${(c*100).toFixed(0)}% of the time`,confidence:Math.min(n.length/20,1),recommendation:`Prefer ${a.includes("low")?"3-5":"6-8"} streams per plan. Larger plans (${t.high.total>0?`>8 streams: ${(s*100).toFixed(0)}% success`:"not enough data"}) tend to fail more.`,evidence:{reportIds:l,metric:"streamCount",values:{"low_1-5_rate":`${(e*100).toFixed(0)}%`,"mid_6-8_rate":`${(o*100).toFixed(0)}%`,"high_9+_rate":`${(s*100).toFixed(0)}%`,low_count:t.low.total,high_count:t.high.total}}}}function zs(n){let t=0,e=0,s=0,o=0,r=[];for(let c of n){for(let l of c.streams)l.filesOwned<=4?(e++,l.status==="complete"&&t++):(o++,l.status==="complete"&&s++);r.push(c.id)}if(e<5||o<3)return null;let i=t/e,a=s/o;return i-a<.15?null:{type:M.FILE_PER_STREAM,description:`Streams with <=4 files succeed ${(i*100).toFixed(0)}%, streams with >4 files succeed ${(a*100).toFixed(0)}%`,confidence:Math.min((e+o)/30,1),recommendation:"Keep streams to 4 or fewer owned files. Split larger streams into focused units.",evidence:{reportIds:r,metric:"filesPerStream",values:{low_files_success_rate:`${(i*100).toFixed(0)}%`,high_files_success_rate:`${(a*100).toFixed(0)}%`,low_files_count:e,high_files_count:o}}}}function Hs(n){let t={},e=0,s=[];for(let c of n){for(let l of c.streams)l.status==="failed"&&l.errorCategory&&(t[l.errorCategory]=(t[l.errorCategory]||0)+1,e++);c.failedStreams>0&&s.push(c.id)}if(e<3)return null;let o=Object.entries(t).sort((c,l)=>l[1]-c[1]),[r,i]=o[0],a=i/e*100;return{type:M.SELF_HEAL_PATTERN,description:`${r} errors are the most common failure (${a.toFixed(0)}% of all errors)`,confidence:Math.min(e/15,1),recommendation:`Focus on preventing ${r} errors. Consider adding targeted verify commands or adjusting prompts to avoid this error type.`,evidence:{reportIds:s,metric:"errorCategories",values:Object.fromEntries(o.map(([c,l])=>[c,`${l} (${(l/e*100).toFixed(0)}%)`]))}}}function Bs(n){let t=0,e=0,s=0,o=0,r=[];for(let c of n){let l=new Set(c.streams.filter(u=>!u.name.toLowerCase().includes("test")).map(u=>u.id));for(let u of c.streams){if(!u.name.toLowerCase().includes("test"))continue;u.deps&&u.deps.some(p=>l.has(p))?(t++,u.status==="complete"&&e++):(s++,u.status==="complete"&&o++)}r.push(c.id)}if(t<3||s<3)return null;let i=e/t,a=o/s;return i-a<.15?null:{type:M.DEPENDENCY_ORDERING,description:`Test streams with impl dependencies succeed ${(i*100).toFixed(0)}%, without: ${(a*100).toFixed(0)}%`,confidence:Math.min((t+s)/15,1),recommendation:"Always add implementation streams as dependencies of test streams. Place tests in later waves.",evidence:{reportIds:r,metric:"dependencyOrdering",values:{with_deps_rate:`${(i*100).toFixed(0)}%`,without_deps_rate:`${(a*100).toFixed(0)}%`,with_deps_count:t,without_deps_count:s}}}}function qs(n){let t={low:{total:0,success:0},high:{total:0,success:0}},e=[];for(let c of n){let l=c.totalWaves<=3?"low":"high";t[l].total++,c.success&&t[l].success++,e.push(c.id)}if(t.low.total<3||t.high.total<3)return null;let s=t.low.success/t.low.total,o=t.high.success/t.high.total;if(Math.abs(s-o)<.15)return null;let r=s>=o?"low":"high",i=r==="low"?s:o,a=r==="low"?"1-3":"4+";return{type:M.WAVE_EFFICIENCY,description:`Orchestrations with ${a} waves succeed ${(i*100).toFixed(0)}%`,confidence:Math.min(n.length/15,1),recommendation:`Prefer ${a} waves for best results. ${r==="low"?"Keep dependency depth shallow.":"More waves indicates better dependency structure."}`,evidence:{reportIds:e,metric:"waveCount",values:{"low_1-3_rate":`${(s*100).toFixed(0)}%`,"high_4+_rate":`${(o*100).toFixed(0)}%`,low_count:t.low.total,high_count:t.high.total}}}}function Vs(n){let t={},e=[];for(let c of n){for(let l of c.streams){let u=l.provider??c.provider??"unknown";u!=="unknown"&&(t[u]||(t[u]={total:0,success:0}),t[u].total++,l.status==="complete"&&t[u].success++)}e.push(c.id)}let s=Object.entries(t).filter(([c,l])=>l.total>=3);if(s.length<2)return null;let o=s.map(([c,l])=>({name:c,rate:l.success/l.total,total:l.total})),r=o.sort((c,l)=>l.rate-c.rate),i=r[0],a=r[r.length-1];return i.rate-a.rate<.1?null:{type:M.PROVIDER_PERFORMANCE,description:`${i.name} succeeds ${(i.rate*100).toFixed(0)}%, ${a.name}: ${(a.rate*100).toFixed(0)}%`,confidence:Math.min(s.reduce((c,[l,u])=>c+u.total,0)/30,1),recommendation:`${i.name} performs best in your project. Consider using it as the default provider.`,evidence:{reportIds:e,metric:"providerPerformance",values:Object.fromEntries(o.map(c=>[c.name,`${(c.rate*100).toFixed(0)}% (n=${c.total})`]))}}}function Ys(n){let t={morning:{total:0,success:0},afternoon:{total:0,success:0},evening:{total:0,success:0},night:{total:0,success:0}},e=[];for(let c of n){let l=new Date(c.timestamp).getHours(),u=l<6?"night":l<12?"morning":l<18?"afternoon":"evening";t[u].total++,c.success&&t[u].success++,e.push(c.id)}let s=Object.entries(t).filter(([c,l])=>l.total>=3);if(s.length<2)return null;let o=s.map(([c,l])=>({name:c,rate:l.success/l.total,total:l.total})),r=o.sort((c,l)=>l.rate-c.rate),i=r[0],a=r[r.length-1];return i.rate-a.rate<.2?null:{type:M.TIME_OF_DAY,description:`${i.name} runs succeed ${(i.rate*100).toFixed(0)}%, ${a.name}: ${(a.rate*100).toFixed(0)}%`,confidence:Math.min(n.length/20,1),recommendation:`Orchestrations during ${i.name} hours have the highest success rate. This may correlate with API rate limit availability.`,evidence:{reportIds:e,metric:"timeOfDay",values:Object.fromEntries(o.map(c=>[c.name,`${(c.rate*100).toFixed(0)}% (n=${c.total})`]))}}}function Gs(n){if(n.length===0)return"No significant patterns detected yet. Need more execution history.";let t=["=== Detected Patterns ===",""];for(let e of n){let s=e.confidence>=.7?"HIGH":e.confidence>=.4?"MEDIUM":"LOW";t.push(`[${s}] ${e.description}`),t.push(` Recommendation: ${e.recommendation}`),t.push("")}return t.join(`
180
- `)}function Js(n){if(n.length===0)return"";let t=n.filter(e=>e.confidence>=.4).map(e=>`- ${e.recommendation}`).join(`
181
+ `),verify:h,setup:S.length>0?S:void 0,timeoutMs:T},a.push(`Merged [${l.join(", ")}] \u2192 ${u} (shared files: ${[...f].filter(x=>(t.get(x)??[]).length>1).join(", ")})`)}for(let[l,u]of Object.entries(i)){let d=u.deps??[],f=[...new Set(d.map(p=>c.get(p)??p))].filter(p=>p!==l);u.deps=f}return{streams:i,merges:a}}function Os(n){return n.isTestGeneration?{provider:void 0,confidence:.3,reason:"Test generation works well with any provider \u2014 use your default."}:n.isStructuralChange&&(n.totalOwnedLines>500||n.fileCount>4)?{provider:"anthropic",confidence:.7,reason:`Structural edits across ${n.fileCount} files (${n.totalOwnedLines} lines) \u2014 Claude handles complex multi-file reasoning best.`}:!n.isStructuralChange&&n.totalOwnedLines<200&&n.fileCount<=2?{provider:"openai",model:"gpt-4.1-mini",confidence:.6,reason:`Simple transform (${n.totalOwnedLines} lines, ${n.fileCount} files) \u2014 GPT-4.1-mini is cost-effective for small tasks.`}:n.isStructuralChange?{provider:"anthropic",confidence:.5,reason:`Structural changes across ${n.fileCount} files \u2014 Claude recommended for refactoring tasks.`}:{provider:void 0,confidence:.2,reason:"No strong provider preference for this task type \u2014 use your configured default."}}function Ps(n,t,e){let s=n.toLowerCase(),o=s.includes("test")||s.includes("spec")||t.some(a=>a.includes(".test.")||a.includes(".spec.")||a.startsWith("tests/")),i=["refactor","restructure","reorganize","migrate","rewrite","split","merge","move","rename","extract","inline","new module","new class","new service","new component"].some(a=>s.includes(a));return{totalOwnedLines:e,isStructuralChange:i,isTestGeneration:o,fileCount:t.length}}import*as L from"fs/promises";import*as ge from"path";import*as te from"yaml";import{exec as Ms}from"child_process";import{promisify as Is}from"util";var nt=Is(Ms);async function Rs(n,t){let e=ge.join(n,".orchex","active","manifest.yaml"),s=await L.readFile(e,"utf-8"),o=te.parse(s),r=new Set(t);for(let[i,a]of Object.entries(o.streams))a.status==="pending"&&(r.has(i)||(o.streams[i].status="skipped"));await L.writeFile(e,te.stringify(o,{indent:2,lineWidth:0}),"utf-8")}async function Fs(n,t,e){let s=[],o=[];for(let r of e){let i=ge.join(n,r);try{let{stdout:a}=await nt(`git ls-files "${r}"`,{cwd:n});if(a.trim())await nt(`git checkout HEAD -- "${r}"`,{cwd:n}),s.push(r);else try{await L.unlink(i),s.push(r)}catch(c){c.code!=="ENOENT"&&o.push(`Failed to delete ${r}: ${c.message}`)}}catch(a){if(a.message?.includes("did not match any"))continue;o.push(`Failed to rollback ${r}: ${a.message}`)}}return{streamId:t,reverted:s,errors:o}}import*as it from"fs";import*as ye from"path";import{createLogger as As}from"../logging.js";var ne={"claude-opus-4-5-20251101":{input:.015,output:.075},"claude-sonnet-4-5-20250929":{input:.003,output:.015},"claude-sonnet-4-20250514":{input:.003,output:.015},"claude-3-5-sonnet-20241022":{input:.003,output:.015},"claude-3-opus-20240229":{input:.015,output:.075},"claude-3-haiku-20240307":{input:25e-5,output:.00125},"gpt-4.5-turbo":{input:.005,output:.015},"gpt-4-turbo":{input:.01,output:.03},"gpt-4-turbo-preview":{input:.01,output:.03},"gpt-4o":{input:.005,output:.015},"gpt-4o-mini":{input:15e-5,output:6e-4},"o1-preview":{input:.015,output:.06},"o1-mini":{input:.003,output:.012},"o3-mini":{input:.0011,output:.0044},"gpt-3.5-turbo":{input:5e-4,output:.0015},"gemini-2.5-pro":{input:.00125,output:.01},"gemini-2.0-flash":{input:1e-4,output:4e-4},"gemini-1.5-pro":{input:.00125,output:.005},"gemini-1.5-flash":{input:75e-6,output:3e-4},"gemini-pro":{input:125e-6,output:375e-6},"deepseek-chat":{input:28e-5,output:42e-5},"deepseek-coder":{input:28e-5,output:42e-5},"deepseek-reasoner":{input:55e-5,output:.00219},"llama3.3:70b":{input:0,output:0},"llama3.2:latest":{input:0,output:0},"mistral:latest":{input:0,output:0},default:{input:.003,output:.015}},_s=.9;function st(n){if(ne[n])return ne[n];let t=n.toLowerCase();for(let[e,s]of Object.entries(ne))if(e!=="default"&&t.includes(e.split("-").slice(0,2).join("-")))return s;return ne.default}function ot(n,t,e,s){let o=st(e),r=n/1e3*o.input,i=t/1e3*o.output,a=r+i,c;s&&s>0&&(c=s/1e3*o.input*_s);let l=a-(c??0);return{inputTokens:n,outputTokens:t,inputCost:r,outputCost:i,totalCost:a,cacheHitTokens:s,cacheDiscount:c,finalCost:l,model:e}}function js(n,t,e=.3){let s=Math.ceil(n*e);return ot(n,s,t)}var fr=As("smart-router"),rt={anthropic:"claude-sonnet-4-5-20250929",openai:"gpt-4.1",google:"gemini-2.5-pro",deepseek:"deepseek-chat",ollama:"llama3.3:70b"};function Ds(n){let t=[...n.owns,...n.reads??[]],e=n.name.toLowerCase(),s=(n.plan??"").toLowerCase();return t.some(o=>o.match(/\.(md|mdx|txt|rst)$/))||e.includes("doc")||e.includes("readme")?"docs":t.some(o=>o.includes(".test.")||o.includes(".spec.")||o.includes("__tests__"))||e.includes("test")?"test":t.some(o=>o.includes("migration"))||e.includes("migrat")?"migration":n.owns.length>=3||(n.estimatedLines??0)>500||s.includes("refactor")||s.includes("restructur")?"complex-code":"simple-code"}function Ls(n,t){switch(n){case"docs":return{provider:"deepseek",model:"deepseek-chat",reasoning:`Routed documentation stream "${t.name}" to cheapest provider (DeepSeek)`};case"test":return{provider:"openai",model:"gpt-4o",reasoning:`Routed test stream "${t.name}" to mid-tier provider (GPT-4o)`};case"migration":return{provider:"google",model:"gemini-2.5-pro",reasoning:`Routed migration stream "${t.name}" to cost-effective provider (Gemini)`};case"complex-code":return{provider:"anthropic",model:"claude-sonnet-4-5-20250929",reasoning:`Routed complex code stream "${t.name}" (${t.owns.length} files${(t.estimatedLines??0)>500?", large file edits":""}) to premium provider (Claude)`};default:return{provider:"openai",model:"gpt-4o",reasoning:`Routed simple code stream "${t.name}" to balanced provider (GPT-4o)`}}}function Ns(n){switch(n){case"docs":return["gemini","openai","anthropic"];case"test":return["anthropic","gemini","deepseek"];case"migration":return["openai","anthropic","deepseek"];case"complex-code":return["openai","gemini","deepseek"];default:return["anthropic","gemini","deepseek"]}}function Ws(n,t,e){let s=e?.availableProviders,o=e?.registryModels,r=(c,l)=>o?.[c]?.length?o[c].includes(l)?l:o[c][0]:l;if(t.overrides?.[n.id]){let c=t.overrides[n.id];return{provider:c.provider,model:c.model,reasoning:"User override"}}if(t.defaultProvider){let c=t.defaultModel??rt[t.defaultProvider]??t.defaultProvider,l=r(t.defaultProvider,c);return{provider:t.defaultProvider,model:l,reasoning:"User default provider preference"}}let i=Ds(n),a=Ls(i,n);if(s&&!s.has(a.provider)){let c=Ns(i);for(let l of c)if(s.has(l)){let u=r(l,rt[l]??l);return{provider:l,model:u,reasoning:`${a.reasoning} \u2014 ${a.provider} not available, fell back to ${l}`}}}return a.model=r(a.provider,a.model),a}function Us(n){let t=n??ye.join(process.env.HOME??"",".orchex"),e=ye.join(t,"config.json");try{let s=it.readFileSync(e,"utf-8"),o=JSON.parse(s);return{defaultProvider:o.routing?.defaultProvider,defaultModel:o.routing?.defaultModel,overrides:o.routing?.overrides}}catch{return{}}}import*as N from"fs/promises";import*as se from"path";var M;(function(n){n.STREAM_COUNT_SWEET_SPOT="stream-count-sweet-spot",n.DEPENDENCY_ORDERING="dependency-ordering",n.FILE_PER_STREAM="file-per-stream",n.WAVE_EFFICIENCY="wave-efficiency",n.PROVIDER_PERFORMANCE="provider-performance",n.SELF_HEAL_PATTERN="self-heal-pattern",n.TIME_OF_DAY="time-of-day"})(M||(M={}));function zs(n){let t=n.streamResults.filter(r=>r.status==="complete").length,e=n.streamResults.filter(r=>r.status==="failed").length,s=n.streamResults.filter(r=>r.status==="skipped").length,o=n.streamResults.reduce((r,i)=>r+(i.executionTimeMs??0),0);return{id:n.runId,feature:n.feature,timestamp:n.timestamp,success:n.planQualityScore>=80,totalStreams:n.totalStreams,completedStreams:t,failedStreams:e,skippedStreams:s,totalWaves:n.totalWaves,executionTimeMs:o,streams:n.streamResults.map(r=>({id:r.id,name:r.name,status:r.status,wave:0,filesOwned:0,executionTimeMs:r.executionTimeMs??0,tokensUsed:r.tokensUsed??{input:0,output:0},errorCategory:r.errorCategory}))}}var Hs=5;function Bs(n){if(n.length<Hs)return[];let t=[],e=[qs,Vs,Ys,Gs,Js,Ks,Qs];for(let s of e){let o=s(n);o&&t.push(o)}return t}function qs(n){let t={low:{total:0,success:0,ids:[]},mid:{total:0,success:0,ids:[]},high:{total:0,success:0,ids:[]}};for(let u of n){let d=u.totalStreams<=5?"low":u.totalStreams<=8?"mid":"high";t[d].total++,u.success&&t[d].success++,t[d].ids.push(u.id)}if(t.low.total<3&&t.mid.total<3||t.high.total<2&&t.mid.total<2)return null;let e=t.low.total>0?t.low.success/t.low.total:0,s=t.high.total>0?t.high.success/t.high.total:0,o=t.mid.total>0?t.mid.success/t.mid.total:0,r=Math.max(e,o),i=Math.min(e,o,s);if(r-i<.2)return null;let a=e>=o?"low (1-5 streams)":"mid (6-8 streams)",c=Math.max(e,o),l=[...t.low.ids,...t.mid.ids,...t.high.ids];return{type:M.STREAM_COUNT_SWEET_SPOT,description:`Plans with ${a} succeed ${(c*100).toFixed(0)}% of the time`,confidence:Math.min(n.length/20,1),recommendation:`Prefer ${a.includes("low")?"3-5":"6-8"} streams per plan. Larger plans (${t.high.total>0?`>8 streams: ${(s*100).toFixed(0)}% success`:"not enough data"}) tend to fail more.`,evidence:{reportIds:l,metric:"streamCount",values:{"low_1-5_rate":`${(e*100).toFixed(0)}%`,"mid_6-8_rate":`${(o*100).toFixed(0)}%`,"high_9+_rate":`${(s*100).toFixed(0)}%`,low_count:t.low.total,high_count:t.high.total}}}}function Vs(n){let t=0,e=0,s=0,o=0,r=[];for(let c of n){for(let l of c.streams)l.filesOwned<=4?(e++,l.status==="complete"&&t++):(o++,l.status==="complete"&&s++);r.push(c.id)}if(e<5||o<3)return null;let i=t/e,a=s/o;return i-a<.15?null:{type:M.FILE_PER_STREAM,description:`Streams with <=4 files succeed ${(i*100).toFixed(0)}%, streams with >4 files succeed ${(a*100).toFixed(0)}%`,confidence:Math.min((e+o)/30,1),recommendation:"Keep streams to 4 or fewer owned files. Split larger streams into focused units.",evidence:{reportIds:r,metric:"filesPerStream",values:{low_files_success_rate:`${(i*100).toFixed(0)}%`,high_files_success_rate:`${(a*100).toFixed(0)}%`,low_files_count:e,high_files_count:o}}}}function Ys(n){let t={},e=0,s=[];for(let c of n){for(let l of c.streams)l.status==="failed"&&l.errorCategory&&(t[l.errorCategory]=(t[l.errorCategory]||0)+1,e++);c.failedStreams>0&&s.push(c.id)}if(e<3)return null;let o=Object.entries(t).sort((c,l)=>l[1]-c[1]),[r,i]=o[0],a=i/e*100;return{type:M.SELF_HEAL_PATTERN,description:`${r} errors are the most common failure (${a.toFixed(0)}% of all errors)`,confidence:Math.min(e/15,1),recommendation:`Focus on preventing ${r} errors. Consider adding targeted verify commands or adjusting prompts to avoid this error type.`,evidence:{reportIds:s,metric:"errorCategories",values:Object.fromEntries(o.map(([c,l])=>[c,`${l} (${(l/e*100).toFixed(0)}%)`]))}}}function Gs(n){let t=0,e=0,s=0,o=0,r=[];for(let c of n){let l=new Set(c.streams.filter(u=>!u.name.toLowerCase().includes("test")).map(u=>u.id));for(let u of c.streams){if(!u.name.toLowerCase().includes("test"))continue;u.deps&&u.deps.some(p=>l.has(p))?(t++,u.status==="complete"&&e++):(s++,u.status==="complete"&&o++)}r.push(c.id)}if(t<3||s<3)return null;let i=e/t,a=o/s;return i-a<.15?null:{type:M.DEPENDENCY_ORDERING,description:`Test streams with impl dependencies succeed ${(i*100).toFixed(0)}%, without: ${(a*100).toFixed(0)}%`,confidence:Math.min((t+s)/15,1),recommendation:"Always add implementation streams as dependencies of test streams. Place tests in later waves.",evidence:{reportIds:r,metric:"dependencyOrdering",values:{with_deps_rate:`${(i*100).toFixed(0)}%`,without_deps_rate:`${(a*100).toFixed(0)}%`,with_deps_count:t,without_deps_count:s}}}}function Js(n){let t={low:{total:0,success:0},high:{total:0,success:0}},e=[];for(let c of n){let l=c.totalWaves<=3?"low":"high";t[l].total++,c.success&&t[l].success++,e.push(c.id)}if(t.low.total<3||t.high.total<3)return null;let s=t.low.success/t.low.total,o=t.high.success/t.high.total;if(Math.abs(s-o)<.15)return null;let r=s>=o?"low":"high",i=r==="low"?s:o,a=r==="low"?"1-3":"4+";return{type:M.WAVE_EFFICIENCY,description:`Orchestrations with ${a} waves succeed ${(i*100).toFixed(0)}%`,confidence:Math.min(n.length/15,1),recommendation:`Prefer ${a} waves for best results. ${r==="low"?"Keep dependency depth shallow.":"More waves indicates better dependency structure."}`,evidence:{reportIds:e,metric:"waveCount",values:{"low_1-3_rate":`${(s*100).toFixed(0)}%`,"high_4+_rate":`${(o*100).toFixed(0)}%`,low_count:t.low.total,high_count:t.high.total}}}}function Ks(n){let t={},e=[];for(let c of n){for(let l of c.streams){let u=l.provider??c.provider??"unknown";u!=="unknown"&&(t[u]||(t[u]={total:0,success:0}),t[u].total++,l.status==="complete"&&t[u].success++)}e.push(c.id)}let s=Object.entries(t).filter(([c,l])=>l.total>=3);if(s.length<2)return null;let o=s.map(([c,l])=>({name:c,rate:l.success/l.total,total:l.total})),r=o.sort((c,l)=>l.rate-c.rate),i=r[0],a=r[r.length-1];return i.rate-a.rate<.1?null:{type:M.PROVIDER_PERFORMANCE,description:`${i.name} succeeds ${(i.rate*100).toFixed(0)}%, ${a.name}: ${(a.rate*100).toFixed(0)}%`,confidence:Math.min(s.reduce((c,[l,u])=>c+u.total,0)/30,1),recommendation:`${i.name} performs best in your project. Consider using it as the default provider.`,evidence:{reportIds:e,metric:"providerPerformance",values:Object.fromEntries(o.map(c=>[c.name,`${(c.rate*100).toFixed(0)}% (n=${c.total})`]))}}}function Qs(n){let t={morning:{total:0,success:0},afternoon:{total:0,success:0},evening:{total:0,success:0},night:{total:0,success:0}},e=[];for(let c of n){let l=new Date(c.timestamp).getHours(),u=l<6?"night":l<12?"morning":l<18?"afternoon":"evening";t[u].total++,c.success&&t[u].success++,e.push(c.id)}let s=Object.entries(t).filter(([c,l])=>l.total>=3);if(s.length<2)return null;let o=s.map(([c,l])=>({name:c,rate:l.success/l.total,total:l.total})),r=o.sort((c,l)=>l.rate-c.rate),i=r[0],a=r[r.length-1];return i.rate-a.rate<.2?null:{type:M.TIME_OF_DAY,description:`${i.name} runs succeed ${(i.rate*100).toFixed(0)}%, ${a.name}: ${(a.rate*100).toFixed(0)}%`,confidence:Math.min(n.length/20,1),recommendation:`Orchestrations during ${i.name} hours have the highest success rate. This may correlate with API rate limit availability.`,evidence:{reportIds:e,metric:"timeOfDay",values:Object.fromEntries(o.map(c=>[c.name,`${(c.rate*100).toFixed(0)}% (n=${c.total})`]))}}}function Xs(n){if(n.length===0)return"No significant patterns detected yet. Need more execution history.";let t=["=== Detected Patterns ===",""];for(let e of n){let s=e.confidence>=.7?"HIGH":e.confidence>=.4?"MEDIUM":"LOW";t.push(`[${s}] ${e.description}`),t.push(` Recommendation: ${e.recommendation}`),t.push("")}return t.join(`
182
+ `)}function Zs(n){if(n.length===0)return"";let t=n.filter(e=>e.confidence>=.4).map(e=>`- ${e.recommendation}`).join(`
181
183
  `);return t?["## Project-Specific Guidance (from execution history)","","Based on this project's past orchestration runs:",t,"","Apply these recommendations when generating the plan."].join(`
182
- `):""}function rt(n){return se.join(n,".orchex","learn","patterns.json")}async function Ks(n,t){let e=rt(n),s=se.dirname(e);await N.mkdir(s,{recursive:!0}),await N.writeFile(e,JSON.stringify(t,null,2),"utf-8")}async function Qs(n){let t=rt(n);try{let e=await N.readFile(t,"utf-8");return JSON.parse(e)}catch{return[]}}function we(n){let t=[],e=/(?:import|export)\s+.*?from\s+['"](.+?)['"]/g,s;for(;(s=e.exec(n))!==null;)t.push(s[1]);let o=/require\s*\(\s*['"](.+?)['"]\s*\)/g;for(;(s=o.exec(n))!==null;)t.push(s[1]);return t}function xe(n,t){if(!t.startsWith("."))return null;let e=n.substring(0,n.lastIndexOf("/")),s=t.replace(/\.js$/,""),o=[...e.split("/"),...s.split("/")],r=[];for(let a of o)a===".."?r.pop():a!=="."&&r.push(a);let i=r.join("/");return i.endsWith(".ts")?i:i+".ts"}var W={CODE:3.5,COMMENTS:4.5,WHITESPACE:6,JSON:3.8,MARKDOWN:4.2};function Xs(n,t,e){let s=new Set([...n]),o=new Set,r=[...n],i=[],a=new Map;for(let l of n)a.set(l,[]);for(;r.length>0;){let l=r.shift();if(o.has(l))continue;o.add(l);let u=e[l];if(!u)continue;let d=we(u);for(let f of d){let p=xe(l,f);if(p&&e[p]){if(o.has(p)){let m=a.get(l)||[];i.push(`Circular dependency detected: ${[...m,l,p].join(" \u2192 ")}`)}else if(!s.has(p)){s.add(p),r.push(p);let m=a.get(l)||[];a.set(p,[...m,l])}}}}for(let l of t)s.add(l);let c=Object.keys(e).filter(l=>!s.has(l));return{needed:[...s],pruned:c,warnings:i.length>0?i:void 0}}function Zs(n,t,e){let s=[];return e.length>100&&s.push({content:e,type:"system_prompt",reusable:!0,estimatedTokens:oe(e)}),n.length>500&&s.push({content:n,type:"project_context",reusable:!0,estimatedTokens:oe(n)}),t.length>500&&s.push({content:t,type:"stream_context",reusable:!0,estimatedTokens:oe(t)}),s}function oe(n){if(!n||n.length===0)return 0;let t=n.trim().startsWith("{")||n.trim().startsWith("["),e=/^#+\s|^-\s|^\*\s|^\d+\.\s/m.test(n);if(t)return Math.ceil(n.length/W.JSON);if(e)return Math.ceil(n.length/W.MARKDOWN);let s=n.split(`
183
- `),o=0,r=0,i=0,a=0;for(let f of s){let p=f.trim();if(o+=f.length,p.length===0){a+=f.length;continue}if(p.startsWith("//")||p.startsWith("/*")||p.startsWith("*")||p.startsWith("#"))i+=f.length;else{r+=f.length;let m=f.length-p.length;a+=m,r-=m}}let c=Math.ceil(r/W.CODE),l=Math.ceil(i/W.COMMENTS),u=Math.ceil(a/W.WHITESPACE),d=Math.ceil((o-r-i-a)/W.COMMENTS);return c+l+u+d}var it={anthropic:2e5,openai:128e3,gemini:1e6,deepseek:128e3,ollama:128e3,default:1e5},at={"claude-opus-4-5-20251101":2e5,"claude-sonnet-4-5-20250929":2e5,"claude-sonnet-4-20250514":2e5,"claude-3-5-sonnet-20241022":2e5,"claude-3-opus-20240229":2e5,"claude-3-haiku-20240307":2e5,"gpt-4.5-turbo":128e3,"gpt-4-turbo":128e3,"gpt-4-turbo-preview":128e3,"gpt-4o":128e3,"gpt-4o-mini":128e3,"o1-preview":128e3,"o1-mini":128e3,"o3-mini":2e5,"gpt-3.5-turbo":16385,"gemini-2.5-pro":1e6,"gemini-2.0-flash":1e6,"gemini-1.5-pro":1e6,"gemini-1.5-flash":1e6,"gemini-pro":32768,"deepseek-chat":128e3,"deepseek-coder":128e3,"deepseek-reasoner":128e3,"llama3.3:70b":128e3,"llama3.2:latest":128e3,"mistral:latest":32e3},eo=.7,to=.9,no=.8;function ct(n,t){return t&&at[t]?at[t]:it[n]??it.default}function so(n,t,e){let s=ct(t,e),o=n?.softLimitTokens??Math.floor(s*eo),r=n?.hardLimitTokens??Math.floor(s*to),i=n?.enforcementLevel??"warn",a=n?.warningThreshold??no;return{enforcementLevel:i,softLimitTokens:o,hardLimitTokens:r,warningThreshold:a,provider:t,model:e}}function oo(n,t,e){let s=t-e,o=Math.round(s/e*100);if(n==="none")return"";let r=[`Context is ${o}% over the ${n} limit.`,"Consider:",' - Reducing the number of files in "reads"'," - Splitting the stream into smaller tasks"," - Using file patterns instead of directories"," - Extracting only function signatures instead of full files"];return n==="hard"&&r.push(" - Or increase the hard limit in contextBudget settings"),r.join(`
184
- `)}function ro(n,t){let e=ct(t.provider,t.model),{softLimitTokens:s,hardLimitTokens:o,warningThreshold:r,enforcementLevel:i}=t,a="none",c=s;n>=o?(a="hard",c=o):n>=s&&(a="soft",c=s);let l=n/s,u=!0;a==="hard"&&i==="hard"?u=!1:a==="soft"&&i==="soft"&&(u=!0);let d;if(a!=="none"){let p=a==="hard"?"hard limit":"soft limit";d=`Context size (${n.toLocaleString()} tokens) exceeds ${p} (${c.toLocaleString()} tokens)`,u||(d+=". Execution blocked.")}else l>=r&&(d=`Context size at ${Math.round(l*100)}% of soft limit (${n.toLocaleString()} / ${s.toLocaleString()} tokens)`);let f=a!=="none"?oo(a,n,c):void 0;return{allowed:u,violationType:a,estimatedTokens:n,budgetLimit:c,utilizationRatio:l,warning:d,suggestion:f,providerLimit:e}}var Se=class extends Error{checkResult;streamId;constructor(t,e){let s=e?` for stream "${e}"`:"";super(`Context budget exceeded${s}: ${t.warning}`),this.checkResult=t,this.streamId=e,this.name="ContextBudgetExceededError"}};function io(n,t,e=300,s=10,o=120,r=!1){let i=n.split(/\r?\n/);if(i.length<e||t.length===0)return n;let a=t.map(h=>new RegExp(ao(h),"i")),c=[];for(let h=0;h<i.length;++h)a.some(y=>y.test(i[h]))&&c.push(h);let l=new Set;for(let h of c)for(let y=Math.max(0,h-s);y<=Math.min(i.length-1,h+s);++y)l.add(y);if(l.size<Math.min(20,s*2)){for(let h=0;h<Math.min(s*2,i.length);++h)l.add(h);for(let h=Math.max(0,i.length-s*2);h<i.length;++h)l.add(h)}let d=Array.from(l).sort((h,y)=>h-y).slice(0,o),f=-2,p=[],m=r?String(i.length).length:0;for(let h of d)h>f+1&&p.length>0&&p.push("..."),r?p.push(`${String(h+1).padStart(m)}: ${i[h]}`):p.push(i[h]),f=h;return p.join(`
185
- `)}function ao(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}export{Se as ContextBudgetExceededError,J as DEFAULT_THRESHOLDS,Ds as adaptReport,fe as analyzeError,me as analyzeFailureCorrelation,Ut as appendLocalEvents,Es as applyPartialApproval,he as applyTemplate,Nn as autoFixSequentialEdits,Cs as autoMergeOwnershipConflicts,yn as buildDependencyGraph,K as categorizeStream,ro as checkBudget,bs as classifyTask,Bn as cleanupOrphanFixStreams,so as createBudgetConfig,H as createDetector,Wn as createDiagnostics,Un as detectOwnershipConflicts,Ws as detectPatterns,qe as detectSequentialEdits,Xn as detectUpstreamSuspect,Is as estimatePlannedCost,oe as estimateTokens,fs as evaluateCompletion,rn as extractDeliverables,we as extractImports,Fn as extractPrerequisites,io as extractRelevantChunks,ee as findMatchingTemplate,un as formatDeliverablesReport,wn as formatDependencyReport,Gs as formatPatterns,An as formatPlanPreview,Dn as formatPlanPreviewText,In as formatStreamsForReview,Pe as gatherProjectContext,$s as generateAllSuggestions,Zs as generateCachingHints,Qn as generateFixStream,rs as generateLearningSummary,gt as generatePlan,ns as generateReport,Zn as generateRootCauseFixStream,Mn as generateStreams,cs as getFirstRunSuggestion,X as getFixChainInfo,tt as getModelCosts,Yn as getOriginalStreamId,Nt as getRecommendedLimit,V as getSectionsAtLevel,vs as getSuggestionsSummary,Me as getThresholds,is as isFirstRun,Vn as isFixStream,Pt as isUnpopulatedTemplate,Qs as loadPatterns,Ls as loadRoutingRules,as as markFirstRunComplete,qn as onStreamComplete,de as optimizeTopology,kt as parsePlanDocument,Js as patternsToPromptHints,ln as processDeliverables,Xs as pruneUnusedFiles,ls as resetLearning,xe as resolveImportPath,Os as rollbackStream,As as routeStream,Ht as runLearningCycle,Ks as savePatterns,ss as saveReportLocally,Wt as streamResultToTelemetryEvent,ks as suggestProvider,xs as suggestSplit,Rn as toInitFormat};
184
+ `):""}function at(n){return se.join(n,".orchex","learn","patterns.json")}async function eo(n,t){let e=at(n),s=se.dirname(e);await N.mkdir(s,{recursive:!0}),await N.writeFile(e,JSON.stringify(t,null,2),"utf-8")}async function to(n){let t=at(n);try{let e=await N.readFile(t,"utf-8");return JSON.parse(e)}catch{return[]}}function we(n){let t=[],e=/(?:import|export)\s+.*?from\s+['"](.+?)['"]/g,s;for(;(s=e.exec(n))!==null;)t.push(s[1]);let o=/require\s*\(\s*['"](.+?)['"]\s*\)/g;for(;(s=o.exec(n))!==null;)t.push(s[1]);return t}function xe(n,t){if(!t.startsWith("."))return null;let e=n.substring(0,n.lastIndexOf("/")),s=t.replace(/\.js$/,""),o=[...e.split("/"),...s.split("/")],r=[];for(let a of o)a===".."?r.pop():a!=="."&&r.push(a);let i=r.join("/");return i.endsWith(".ts")?i:i+".ts"}var W={CODE:3.5,COMMENTS:4.5,WHITESPACE:6,JSON:3.8,MARKDOWN:4.2};function no(n,t,e){let s=new Set([...n]),o=new Set,r=[...n],i=[],a=new Map;for(let l of n)a.set(l,[]);for(;r.length>0;){let l=r.shift();if(o.has(l))continue;o.add(l);let u=e[l];if(!u)continue;let d=we(u);for(let f of d){let p=xe(l,f);if(p&&e[p]){if(o.has(p)){let m=a.get(l)||[];i.push(`Circular dependency detected: ${[...m,l,p].join(" \u2192 ")}`)}else if(!s.has(p)){s.add(p),r.push(p);let m=a.get(l)||[];a.set(p,[...m,l])}}}}for(let l of t)s.add(l);let c=Object.keys(e).filter(l=>!s.has(l));return{needed:[...s],pruned:c,warnings:i.length>0?i:void 0}}function so(n,t,e){let s=[];return e.length>100&&s.push({content:e,type:"system_prompt",reusable:!0,estimatedTokens:oe(e)}),n.length>500&&s.push({content:n,type:"project_context",reusable:!0,estimatedTokens:oe(n)}),t.length>500&&s.push({content:t,type:"stream_context",reusable:!0,estimatedTokens:oe(t)}),s}function oe(n){if(!n||n.length===0)return 0;let t=n.trim().startsWith("{")||n.trim().startsWith("["),e=/^#+\s|^-\s|^\*\s|^\d+\.\s/m.test(n);if(t)return Math.ceil(n.length/W.JSON);if(e)return Math.ceil(n.length/W.MARKDOWN);let s=n.split(`
185
+ `),o=0,r=0,i=0,a=0;for(let f of s){let p=f.trim();if(o+=f.length,p.length===0){a+=f.length;continue}if(p.startsWith("//")||p.startsWith("/*")||p.startsWith("*")||p.startsWith("#"))i+=f.length;else{r+=f.length;let m=f.length-p.length;a+=m,r-=m}}let c=Math.ceil(r/W.CODE),l=Math.ceil(i/W.COMMENTS),u=Math.ceil(a/W.WHITESPACE),d=Math.ceil((o-r-i-a)/W.COMMENTS);return c+l+u+d}var ct={anthropic:2e5,openai:128e3,gemini:1e6,deepseek:128e3,ollama:128e3,default:1e5},lt={"claude-opus-4-5-20251101":2e5,"claude-sonnet-4-5-20250929":2e5,"claude-sonnet-4-20250514":2e5,"claude-3-5-sonnet-20241022":2e5,"claude-3-opus-20240229":2e5,"claude-3-haiku-20240307":2e5,"gpt-4.5-turbo":128e3,"gpt-4-turbo":128e3,"gpt-4-turbo-preview":128e3,"gpt-4o":128e3,"gpt-4o-mini":128e3,"o1-preview":128e3,"o1-mini":128e3,"o3-mini":2e5,"gpt-3.5-turbo":16385,"gemini-2.5-pro":1e6,"gemini-2.0-flash":1e6,"gemini-1.5-pro":1e6,"gemini-1.5-flash":1e6,"gemini-pro":32768,"deepseek-chat":128e3,"deepseek-coder":128e3,"deepseek-reasoner":128e3,"llama3.3:70b":128e3,"llama3.2:latest":128e3,"mistral:latest":32e3},oo=.7,ro=.9,io=.8;function ut(n,t){return t&&lt[t]?lt[t]:ct[n]??ct.default}function ao(n,t,e){let s=ut(t,e),o=n?.softLimitTokens??Math.floor(s*oo),r=n?.hardLimitTokens??Math.floor(s*ro),i=n?.enforcementLevel??"warn",a=n?.warningThreshold??io;return{enforcementLevel:i,softLimitTokens:o,hardLimitTokens:r,warningThreshold:a,provider:t,model:e}}function co(n,t,e){let s=t-e,o=Math.round(s/e*100);if(n==="none")return"";let r=[`Context is ${o}% over the ${n} limit.`,"Consider:",' - Reducing the number of files in "reads"'," - Splitting the stream into smaller tasks"," - Using file patterns instead of directories"," - Extracting only function signatures instead of full files"];return n==="hard"&&r.push(" - Or increase the hard limit in contextBudget settings"),r.join(`
186
+ `)}function lo(n,t){let e=ut(t.provider,t.model),{softLimitTokens:s,hardLimitTokens:o,warningThreshold:r,enforcementLevel:i}=t,a="none",c=s;n>=o?(a="hard",c=o):n>=s&&(a="soft",c=s);let l=n/s,u=!0;a==="hard"&&i==="hard"?u=!1:a==="soft"&&i==="soft"&&(u=!0);let d;if(a!=="none"){let p=a==="hard"?"hard limit":"soft limit";d=`Context size (${n.toLocaleString()} tokens) exceeds ${p} (${c.toLocaleString()} tokens)`,u||(d+=". Execution blocked.")}else l>=r&&(d=`Context size at ${Math.round(l*100)}% of soft limit (${n.toLocaleString()} / ${s.toLocaleString()} tokens)`);let f=a!=="none"?co(a,n,c):void 0;return{allowed:u,violationType:a,estimatedTokens:n,budgetLimit:c,utilizationRatio:l,warning:d,suggestion:f,providerLimit:e}}var Se=class extends Error{checkResult;streamId;constructor(t,e){let s=e?` for stream "${e}"`:"";super(`Context budget exceeded${s}: ${t.warning}`),this.checkResult=t,this.streamId=e,this.name="ContextBudgetExceededError"}};function uo(n,t,e=300,s=10,o=120,r=!1){let i=n.split(/\r?\n/);if(i.length<e||t.length===0)return n;let a=t.map(h=>new RegExp(fo(h),"i")),c=[];for(let h=0;h<i.length;++h)a.some(y=>y.test(i[h]))&&c.push(h);let l=new Set;for(let h of c)for(let y=Math.max(0,h-s);y<=Math.min(i.length-1,h+s);++y)l.add(y);if(l.size<Math.min(20,s*2)){for(let h=0;h<Math.min(s*2,i.length);++h)l.add(h);for(let h=Math.max(0,i.length-s*2);h<i.length;++h)l.add(h)}let d=Array.from(l).sort((h,y)=>h-y).slice(0,o),f=-2,p=[],m=r?String(i.length).length:0;for(let h of d)h>f+1&&p.length>0&&p.push("..."),r?p.push(`${String(h+1).padStart(m)}: ${i[h]}`):p.push(i[h]),f=h;return p.join(`
187
+ `)}function fo(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}export{Se as ContextBudgetExceededError,J as DEFAULT_THRESHOLDS,zs as adaptReport,fe as analyzeError,me as analyzeFailureCorrelation,Ht as appendLocalEvents,Rs as applyPartialApproval,he as applyTemplate,Un as autoFixSequentialEdits,Es as autoMergeOwnershipConflicts,xn as buildDependencyGraph,K as categorizeStream,lo as checkBudget,Ps as classifyTask,Vn as cleanupOrphanFixStreams,ao as createBudgetConfig,H as createDetector,zn as createDiagnostics,Hn as detectOwnershipConflicts,Bs as detectPatterns,qe as detectSequentialEdits,ns as detectUpstreamSuspect,js as estimatePlannedCost,oe as estimateTokens,gs as evaluateCompletion,cn as extractDeliverables,we as extractImports,jn as extractPrerequisites,uo as extractRelevantChunks,ee as findMatchingTemplate,fn as formatDeliverablesReport,Sn as formatDependencyReport,Xs as formatPatterns,Ln as formatPlanPreview,Wn as formatPlanPreviewText,Fn as formatStreamsForReview,Ee as gatherProjectContext,bs as generateAllSuggestions,so as generateCachingHints,ts as generateFixStream,ls as generateLearningSummary,wt as generatePlan,is as generateReport,ss as generateRootCauseFixStream,Rn as generateStreams,fs as getFirstRunSuggestion,X as getFixChainInfo,st as getModelCosts,Jn as getOriginalStreamId,Ut as getRecommendedLimit,V as getSectionsAtLevel,Ts as getSuggestionsSummary,Me as getThresholds,us as isFirstRun,Gn as isFixStream,Pt as isUnpopulatedTemplate,to as loadPatterns,Us as loadRoutingRules,ds as markFirstRunComplete,Yn as onStreamComplete,de as optimizeTopology,Tt as parsePlanDocument,Zs as patternsToPromptHints,dn as processDeliverables,no as pruneUnusedFiles,ps as resetLearning,xe as resolveImportPath,Fs as rollbackStream,Ws as routeStream,qt as runLearningCycle,eo as savePatterns,as as saveReportLocally,zt as streamResultToTelemetryEvent,Os as suggestProvider,Cs as suggestSplit,_n as toInitFormat};
@@ -29,6 +29,24 @@ export async function gatherStreamFileContext(projectDir, stream) {
29
29
  if (!absolutePath.startsWith(resolvedProjectDir)) {
30
30
  continue;
31
31
  }
32
+ // Stat first — confirm the path is a regular file before reading.
33
+ // Skip directories, symlinks-to-dirs, sockets, etc. silently.
34
+ // The validator (validateAndCorrectPaths) is the primary gate;
35
+ // this is defense-in-depth for streams added directly via the API.
36
+ let stat;
37
+ try {
38
+ stat = await fs.stat(absolutePath);
39
+ }
40
+ catch (statErr) {
41
+ if (statErr.code === 'ENOENT') {
42
+ continue;
43
+ }
44
+ throw statErr;
45
+ }
46
+ if (!stat.isFile()) {
47
+ log.debug({ file: filePath }, 'gather_skip_non_file');
48
+ continue;
49
+ }
32
50
  const content = await fs.readFile(absolutePath, 'utf-8');
33
51
  context.push({ path: filePath, content });
34
52
  }
@@ -823,7 +841,7 @@ async function executeWaveInternal(projectDir, executor, options, logger) {
823
841
  // the manifest, so it must see the latest state to compute waves correctly.
824
842
  await saveManifest(projectDir, currentManifest);
825
843
  // Generate fix stream for root cause (after save so addStream sees current state)
826
- const rootFix = generateRootCauseFixStream(currentManifest, correlation);
844
+ const rootFix = generateRootCauseFixStream(currentManifest, correlation, projectDir);
827
845
  if (rootFix) {
828
846
  await addStream(projectDir, rootFix.fixStreamId, rootFix.fixStream);
829
847
  fixStreamsGenerated.push(rootFix.fixStreamId);
@@ -888,7 +906,7 @@ async function executeWaveInternal(projectDir, executor, options, logger) {
888
906
  delete currentManifest.streams[parentId].error;
889
907
  }
890
908
  await saveManifest(projectDir, currentManifest);
891
- const rootFix = generateRootCauseFixStream(currentManifest, singleCorrelation);
909
+ const rootFix = generateRootCauseFixStream(currentManifest, singleCorrelation, projectDir);
892
910
  if (rootFix) {
893
911
  await addStream(projectDir, rootFix.fixStreamId, rootFix.fixStream);
894
912
  fixStreamsGenerated.push(rootFix.fixStreamId);
@@ -908,7 +926,8 @@ async function executeWaveInternal(projectDir, executor, options, logger) {
908
926
  }
909
927
  // Pass the in-memory errorDetail (computed with origin hint) so generateFixStream
910
928
  // can use the correct selfHealable flag rather than re-analyzing without origin.
911
- const fixResult = generateFixStream(currentManifest, sr.id, sr.errorDetail, suspect);
929
+ // projectDir enables disk-state aware fix prompts (Bug 21 mitigation).
930
+ const fixResult = generateFixStream(currentManifest, sr.id, sr.errorDetail, suspect, projectDir);
912
931
  if (fixResult) {
913
932
  await addStream(projectDir, fixResult.fixStreamId, fixResult.fixStream);
914
933
  fixStreamsGenerated.push(fixResult.fixStreamId);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@wundam/orchex",
3
3
  "mcpName": "io.github.wundam/orchex",
4
- "version": "1.0.0-rc.25",
4
+ "version": "1.0.0-rc.27",
5
5
  "description": "Autopilot AI orchestration — auto-plan, parallelize, and execute with ownership enforcement",
6
6
  "type": "module",
7
7
  "main": "dist/index.js",