olympus-ai 4.4.21 → 4.5.0

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.
Files changed (76) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/dist/features/workflow-engine/bolts/bolt-executor.d.ts +29 -0
  3. package/dist/features/workflow-engine/bolts/bolt-executor.d.ts.map +1 -0
  4. package/dist/features/workflow-engine/bolts/bolt-executor.js +96 -0
  5. package/dist/features/workflow-engine/bolts/bolt-executor.js.map +1 -0
  6. package/dist/features/workflow-engine/bolts/bolt-planner.d.ts +35 -0
  7. package/dist/features/workflow-engine/bolts/bolt-planner.d.ts.map +1 -0
  8. package/dist/features/workflow-engine/bolts/bolt-planner.js +284 -0
  9. package/dist/features/workflow-engine/bolts/bolt-planner.js.map +1 -0
  10. package/dist/features/workflow-engine/bolts/bolt-reviewer.d.ts +36 -0
  11. package/dist/features/workflow-engine/bolts/bolt-reviewer.d.ts.map +1 -0
  12. package/dist/features/workflow-engine/bolts/bolt-reviewer.js +108 -0
  13. package/dist/features/workflow-engine/bolts/bolt-reviewer.js.map +1 -0
  14. package/dist/features/workflow-engine/bolts/bolt-spec-validator.d.ts +9 -0
  15. package/dist/features/workflow-engine/bolts/bolt-spec-validator.d.ts.map +1 -0
  16. package/dist/features/workflow-engine/bolts/bolt-spec-validator.js +30 -0
  17. package/dist/features/workflow-engine/bolts/bolt-spec-validator.js.map +1 -0
  18. package/dist/features/workflow-engine/bolts/express-bolt-factory.d.ts +25 -0
  19. package/dist/features/workflow-engine/bolts/express-bolt-factory.d.ts.map +1 -0
  20. package/dist/features/workflow-engine/bolts/express-bolt-factory.js +60 -0
  21. package/dist/features/workflow-engine/bolts/express-bolt-factory.js.map +1 -0
  22. package/dist/features/workflow-engine/checkpoint.d.ts +5 -1
  23. package/dist/features/workflow-engine/checkpoint.d.ts.map +1 -1
  24. package/dist/features/workflow-engine/checkpoint.js +35 -0
  25. package/dist/features/workflow-engine/checkpoint.js.map +1 -1
  26. package/dist/features/workflow-engine/construction/decomposition.d.ts +19 -6
  27. package/dist/features/workflow-engine/construction/decomposition.d.ts.map +1 -1
  28. package/dist/features/workflow-engine/construction/decomposition.js +39 -7
  29. package/dist/features/workflow-engine/construction/decomposition.js.map +1 -1
  30. package/dist/features/workflow-engine/construction/executor.d.ts +5 -1
  31. package/dist/features/workflow-engine/construction/executor.d.ts.map +1 -1
  32. package/dist/features/workflow-engine/construction/executor.js +66 -35
  33. package/dist/features/workflow-engine/construction/executor.js.map +1 -1
  34. package/dist/features/workflow-engine/construction/regression-baseline.d.ts +1 -1
  35. package/dist/features/workflow-engine/construction/regression-baseline.js +1 -1
  36. package/dist/features/workflow-engine/construction/unit-stage-runner.d.ts.map +1 -1
  37. package/dist/features/workflow-engine/construction/unit-stage-runner.js +13 -2
  38. package/dist/features/workflow-engine/construction/unit-stage-runner.js.map +1 -1
  39. package/dist/features/workflow-engine/engine.js +1 -1
  40. package/dist/features/workflow-engine/engine.js.map +1 -1
  41. package/dist/features/workflow-engine/inception/stages/workflow-planning.js +2 -2
  42. package/dist/features/workflow-engine/inception/stages/workflow-planning.js.map +1 -1
  43. package/dist/features/workflow-engine/index.d.ts +15 -6
  44. package/dist/features/workflow-engine/index.d.ts.map +1 -1
  45. package/dist/features/workflow-engine/index.js +10 -5
  46. package/dist/features/workflow-engine/index.js.map +1 -1
  47. package/dist/features/workflow-engine/manifest.d.ts +1 -0
  48. package/dist/features/workflow-engine/manifest.d.ts.map +1 -1
  49. package/dist/features/workflow-engine/manifest.js +8 -0
  50. package/dist/features/workflow-engine/manifest.js.map +1 -1
  51. package/dist/features/workflow-engine/phase-types.d.ts +119 -3
  52. package/dist/features/workflow-engine/phase-types.d.ts.map +1 -1
  53. package/dist/features/workflow-engine/phase-types.js +13 -0
  54. package/dist/features/workflow-engine/phase-types.js.map +1 -1
  55. package/dist/features/workflow-engine/workflow-bridge.d.ts +1 -0
  56. package/dist/features/workflow-engine/workflow-bridge.d.ts.map +1 -1
  57. package/dist/features/workflow-engine/workflow-bridge.js +46 -0
  58. package/dist/features/workflow-engine/workflow-bridge.js.map +1 -1
  59. package/dist/features/workflow-engine/workflow-routing.d.ts +1 -1
  60. package/dist/features/workflow-engine/workflow-routing.d.ts.map +1 -1
  61. package/dist/features/workflow-engine/workflow-routing.js +10 -10
  62. package/dist/features/workflow-engine/workflow-routing.js.map +1 -1
  63. package/dist/hooks/olympus-hooks.cjs +265 -265
  64. package/dist/installer/index.d.ts +1 -1
  65. package/dist/installer/index.d.ts.map +1 -1
  66. package/dist/installer/index.js +1 -1
  67. package/dist/installer/index.js.map +1 -1
  68. package/package.json +1 -1
  69. package/resources/rules/common/process-overview.md +17 -0
  70. package/resources/rules/construction/bolt-planning.md +143 -0
  71. package/resources/rules/construction/bolt-review.md +115 -0
  72. package/resources/rules/construction/code-generation.md +25 -7
  73. package/resources/rules/inception/units-generation.md +2 -2
  74. package/resources/rules/inception/workflow-planning.md +1 -1
  75. package/resources/skills/continue/SKILL.md +2 -1
  76. package/resources/skills/plan/SKILL.md +3 -3
@@ -1,29 +1,38 @@
1
1
  #!/usr/bin/env node
2
2
  // Olympus Hooks Bundle - Generated by esbuild
3
- "use strict";var wk=Object.create;var So=Object.defineProperty;var kk=Object.getOwnPropertyDescriptor;var _k=Object.getOwnPropertyNames;var Sk=Object.getPrototypeOf,vk=Object.prototype.hasOwnProperty;var U=(e,t)=>()=>(e&&(t=e(e=0)),t);var q=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),he=(e,t)=>{for(var n in t)So(e,n,{get:t[n],enumerable:!0})},yl=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of _k(t))!vk.call(e,o)&&o!==n&&So(e,o,{get:()=>t[o],enumerable:!(r=kk(t,o))||r.enumerable});return e};var T=(e,t,n)=>(n=e!=null?wk(Sk(e)):{},yl(t||!e||!e.__esModule?So(n,"default",{value:e,enumerable:!0}):n,e)),Tk=e=>yl(So({},"__esModule",{value:!0}),e);var ki,Ql=U(()=>{"use strict";ki={maxAgeInDays:30,maxArchiveCount:5}});function _i(e){if(!e.token_usage)return null;let{token_usage:t}=e;return typeof t.input_tokens!="number"||typeof t.output_tokens!="number"||typeof t.total_tokens!="number"||typeof t.estimated!="boolean"?null:t}function Wn(e){return _i(e)?.total_tokens||0}var Xl=U(()=>{"use strict"});function Hk(e){let t=(0,Gn.basename)(e);(!t||/^[A-Za-z]:[\\/]?$/.test(e)||/^[A-Za-z]:$/.test(t))&&(t="root");let n=t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"").substring(0,30);n||(n="unknown");let r=(0,eu.createHash)("sha256").update(e).digest("hex").substring(0,8);return`${n}-${r}`}function yn(e){return(0,Gn.join)(de(),"projects",Hk(e))}function Si(e){try{(0,Zl.mkdirSync)(yn(e),{recursive:!0})}catch(t){t.code!=="EEXIST"&&console.error("Failed to create project directory:",t)}}var Gn,Bk,Zl,eu,tu=U(()=>{"use strict";Gn=require("path"),Bk=require("child_process"),Zl=require("fs"),eu=require("crypto");we();Ge()});function de(){return process.env.OLYMPUS_TEST_LEARNING_DIR?process.env.OLYMPUS_TEST_LEARNING_DIR:(0,se.join)((0,ru.homedir)(),".claude","olympus","learning")}function kt(e){return(0,se.join)(e,".olympus","learning")}function su(e){let t=(0,se.resolve)(e);return(0,ou.createHash)("sha256").update(t).digest("hex").substring(0,16)}function Hn(e){let t=de();if((0,z.existsSync)(t)||(0,z.mkdirSync)(t,{recursive:!0}),e){let n=kt(e);(0,z.existsSync)(n)||(0,z.mkdirSync)(n,{recursive:!0})}}function qk(e,t=ki){try{let n=(0,se.dirname)(e),r=(0,se.basename)(e,".jsonl"),o=(0,z.readdirSync)(n),s=new RegExp(`^${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\..*\\.old\\.jsonl$`),i=o.filter(d=>s.test(d)).map(d=>{let p=d.match(/\.(\d{4}-\d{2}-\d{2})T/),f=p?new Date(p[1]):null;return{filename:d,filepath:(0,se.join)(n,d),timestamp:f}}).filter(d=>d.timestamp!==null&&!isNaN(d.timestamp.getTime())).sort((d,p)=>p.timestamp.getTime()-d.timestamp.getTime()),a=t.maxAgeInDays??30,c=t.maxArchiveCount??5,l=new Date(Date.now()-a*24*60*60*1e3),u=0;for(let d=0;d<i.length;d++){let p=i[d],f=p.timestamp<l,m=d>=c;if(f||m)try{(0,z.unlinkSync)(p.filepath),u++}catch{}}u>0&&console.log(`[Olympus Learning] Pruned ${u} old archives`)}catch(n){console.error("[Olympus Learning] Failed to prune archives:",n)}}function Bn(e,t=Vk,n=ki){if((0,z.existsSync)(e))try{let o=(0,z.readFileSync)(e,"utf-8").split(`
4
- `).filter(s=>s.trim()).length;if(o>=t){let s=new Date().toISOString().replace(/[:.]/g,"-"),i=e.replace(".jsonl",`.${s}.old.jsonl`);(0,z.renameSync)(e,i),console.log(`[Olympus Learning] Archived ${o} entries to ${i}`),qk(e,n)}}catch(r){console.error(`[Olympus Learning] Failed to rotate ${e}:`,r)}}function Xt(e){if(e.project_path&&typeof e.project_path=="string")try{Si(e.project_path);let n=(0,se.join)(yn(e.project_path),"feedback-log.jsonl");Bn(n),(0,z.appendFileSync)(n,JSON.stringify(e)+`
5
- `,"utf-8");return}catch(n){console.error("[Olympus Learning] Project write failed, using global fallback:",n)}Hn();let t=(0,se.join)(de(),"feedback-log.jsonl");Bn(t),(0,z.appendFileSync)(t,JSON.stringify(e)+`
6
- `,"utf-8")}function Co(e){let t=e?(0,se.join)(yn(e),"feedback-log.jsonl"):(0,se.join)(de(),"feedback-log.jsonl");return(0,z.existsSync)(t)?(0,z.readFileSync)(t,"utf-8").split(`
7
- `).filter(r=>r.trim()).map(r=>JSON.parse(r)):[]}function Yk(e){let t=e.filter(o=>o.event_type==="revision"||o.event_type==="cancellation"),n=new Map;for(let o of t){let s=o.extracted_lesson||o.feedback_category||"unknown",i=n.get(s);i?(i.count++,i.examples.length<3&&i.examples.push(o.user_message.substring(0,100))):n.set(s,{count:1,examples:[o.user_message.substring(0,100)]})}let r=[];for(let[o,s]of n)s.count>=2&&r.push({pattern:o,count:s.count,examples:s.examples});return r}function Kk(e){let t=[];return e>=.85&&t.push("high success rate"),t}function Jk(e,t){let n=[];return e<.6&&n.push("low success rate"),t>2&&n.push("frequently cancelled"),n}function Ro(e,t,n){let r=t.filter(m=>m.agent_used===e);if(r.length===0)return null;let o=r.length,s=r.filter(m=>m.event_type==="success").length,i=r.filter(m=>m.event_type==="revision").length,a=r.filter(m=>m.event_type==="cancellation").length,c=o>0?s/o:0,l,u=r.filter(m=>_i(m)!==null);if(u.length>0){let m=u.filter(S=>S.event_type==="success"),g=u.filter(S=>S.event_type==="revision"||S.event_type==="cancellation"),y=u.reduce((S,b)=>S+Wn(b),0),w=m.reduce((S,b)=>S+Wn(b),0),k=g.reduce((S,b)=>S+Wn(b),0),h=m.length>0?w/m.length:0,v=g.length>0?k/g.length:0;if(l={avg_tokens_per_success:h,avg_tokens_per_failure:v,total_tokens:y,invocation_count:u.length,efficiency_score:h,trend:"insufficient_data"},u.length>=10){let S=Math.floor(u.length/2),b=u.slice(0,S),_=u.slice(S),j=b.reduce(($,N)=>$+Wn(N),0)/b.length,A=_.reduce(($,N)=>$+Wn(N),0)/_.length-j,C=j*.1;Math.abs(A)<C?l.trend="stable":A<0?l.trend="improving":l.trend="declining"}}let d={agent_name:e,total_invocations:o,success_count:s,revision_count:i,cancellation_count:a,success_rate:c,failure_patterns:Yk(r),strong_areas:Kk(c),weak_areas:Jk(c,a),last_updated:new Date().toISOString(),token_efficiency:l};if(n)try{let m=(0,se.join)(yn(n),"agent-performance.json"),g=ke(m,{});g[e]=d,at(m,g)}catch(m){console.error("[Olympus Learning] Failed to write project agent performance:",m)}let p=(0,se.join)(de(),"agent-performance.json"),f=ke(p,{});return f[e]=d,at(p,f),d}function Vn(e){let t=e?(0,se.join)(yn(e),"agent-performance.json"):(0,se.join)(de(),"agent-performance.json");return ke(t,{})}function ke(e,t){if(!(0,z.existsSync)(e))return t;try{return JSON.parse((0,z.readFileSync)(e,"utf-8"))}catch(n){return console.error(`[Olympus Learning] Failed to read ${e}:`,n),t}}function at(e,t){try{let n=(0,se.dirname)(e);n&&!(0,z.existsSync)(n)&&(0,z.mkdirSync)(n,{recursive:!0}),(0,z.writeFileSync)(e,JSON.stringify(t,null,2),"utf-8")}catch(n){console.error(`[Olympus Learning] Failed to write ${e}:`,n)}}function iu(e,t){if(t)try{Si(t);let r=(0,se.join)(yn(t),"session-summaries.jsonl");Bn(r,nu),(0,z.appendFileSync)(r,JSON.stringify(e)+`
8
- `,"utf-8");return}catch(r){console.error("[Olympus Learning] Project session summary write failed, using global fallback:",r)}Hn();let n=(0,se.join)(de(),"session-summaries.jsonl");Bn(n,nu),(0,z.appendFileSync)(n,JSON.stringify(e)+`
9
- `,"utf-8")}var ru,se,z,ou,Vk,nu,we=U(()=>{"use strict";ru=require("os"),se=require("path"),z=require("fs"),ou=require("crypto");Ql();Xl();tu();Vk=1e4,nu=500});function wn(e,t){return!t||t.sample_count<5?1e4:e&&t.by_task_type[e]!==void 0?t.by_task_type[e]:t.overall_avg}var vi=U(()=>{"use strict"});function uu(e){return(0,cu.join)(e,".olympus","session-state.json")}function au(e,t){let n=wn();return{session_id:e||(0,lu.randomUUID)(),started_at:new Date().toISOString(),last_updated:new Date().toISOString(),recent_prompts:[],pending_completion:null,todo_snapshot:null,token_budget:{session_baseline:n,current_usage:0,input_tokens:0,output_tokens:0,warning_threshold:1.5,warning_issued:!1,started_at:new Date().toISOString()},discovery_volume:{session_count:0,daily_count:0,daily_reset_at:new Date().toISOString()},resolved_project_root:null}}function Q(e,t){let n=uu(e),r=ke(n,null);if(!r)return au(t,e);let o=new Date(r.last_updated).getTime();if(Date.now()-o>Qk)return au(t,e);if(t&&r.session_id!==t&&(r.session_id=t),r.token_budget)r.token_budget.input_tokens===void 0&&(r.token_budget.input_tokens=0),r.token_budget.output_tokens===void 0&&(r.token_budget.output_tokens=0);else{let i=wn();r.token_budget={session_baseline:i,current_usage:0,input_tokens:0,output_tokens:0,warning_threshold:1.5,warning_issued:!1,started_at:r.started_at}}return r.discovery_volume||(r.discovery_volume={session_count:0,daily_count:0,daily_reset_at:new Date().toISOString()}),r.resolved_project_root===void 0&&(r.resolved_project_root=null),r}function ee(e,t){let n=uu(e);t.last_updated=new Date().toISOString(),at(n,t)}function du(e,t,n){let r={prompt:t,timestamp:new Date().toISOString(),detected_feedback:n};return e.recent_prompts=[r,...e.recent_prompts].slice(0,zk),e.last_updated=new Date().toISOString(),e}function pu(e,t,n){return e.pending_completion={claimed_at:new Date().toISOString(),task_description:t,agent_used:n},e.last_updated=new Date().toISOString(),e}function fu(e){return e.pending_completion=null,e.last_updated=new Date().toISOString(),e}function xo(e){if(!e.pending_completion?.claimed_at)return!1;let t=new Date(e.pending_completion.claimed_at).getTime();return Date.now()-t<300*1e3}function mu(e,t){let n=wn();return e.token_budget={session_baseline:n,current_usage:0,input_tokens:0,output_tokens:0,warning_threshold:1.5,warning_issued:!1,started_at:new Date().toISOString()},e.last_updated=new Date().toISOString(),e}function gu(e,t){return e.token_budget||(e.token_budget={session_baseline:wn(),current_usage:0,input_tokens:0,output_tokens:0,warning_threshold:1.5,warning_issued:!1,started_at:new Date().toISOString()}),e.token_budget.current_usage+=t,e.last_updated=new Date().toISOString(),e}function hu(e){return e.token_budget&&(e.token_budget.warning_issued=!0,e.last_updated=new Date().toISOString()),e}function yu(e){if(!e.token_budget||e.token_budget.warning_issued)return!1;let t=e.token_budget.session_baseline*e.token_budget.warning_threshold;return e.token_budget.current_usage>=t}function wu(e){e.discovery_volume||(e.discovery_volume={session_count:0,daily_count:0,daily_reset_at:new Date().toISOString()});let t=new Date(e.discovery_volume.daily_reset_at),n=new Date;return n.toDateString()!==t.toDateString()&&(e.discovery_volume.daily_count=0,e.discovery_volume.daily_reset_at=n.toISOString()),e.discovery_volume.session_count++,e.discovery_volume.daily_count++,e.last_updated=n.toISOString(),e}function ku(e,t){if(!e.discovery_volume)return!1;let n=new Date(e.discovery_volume.daily_reset_at);return new Date().toDateString()!==n.toDateString()?!1:e.discovery_volume.session_count>=t.maxPerSession||e.discovery_volume.daily_count>=t.maxPerDay}var cu,lu,zk,Qk,Ge=U(()=>{"use strict";cu=require("path");we();lu=require("crypto");vi();zk=10,Qk=1800*1e3});var pe=q(Ei=>{"use strict";Ei.fromCallback=function(e){return Object.defineProperty(function(...t){if(typeof t[t.length-1]=="function")e.apply(this,t);else return new Promise((n,r)=>{t.push((o,s)=>o!=null?r(o):n(s)),e.apply(this,t)})},"name",{value:e.name})};Ei.fromPromise=function(e){return Object.defineProperty(function(...t){let n=t[t.length-1];if(typeof n!="function")return e.apply(this,t);t.pop(),e.apply(this,t).then(r=>n(null,r),n)},"name",{value:e.name})}});var bu=q((rA,Eu)=>{var Zt=require("constants"),Zk=process.cwd,Po=null,e_=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return Po||(Po=Zk.call(process)),Po};try{process.cwd()}catch{}typeof process.chdir=="function"&&(bi=process.chdir,process.chdir=function(e){Po=null,bi.call(process,e)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,bi));var bi;Eu.exports=t_;function t_(e){Zt.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&t(e),e.lutimes||n(e),e.chown=s(e.chown),e.fchown=s(e.fchown),e.lchown=s(e.lchown),e.chmod=r(e.chmod),e.fchmod=r(e.fchmod),e.lchmod=r(e.lchmod),e.chownSync=i(e.chownSync),e.fchownSync=i(e.fchownSync),e.lchownSync=i(e.lchownSync),e.chmodSync=o(e.chmodSync),e.fchmodSync=o(e.fchmodSync),e.lchmodSync=o(e.lchmodSync),e.stat=a(e.stat),e.fstat=a(e.fstat),e.lstat=a(e.lstat),e.statSync=c(e.statSync),e.fstatSync=c(e.fstatSync),e.lstatSync=c(e.lstatSync),e.chmod&&!e.lchmod&&(e.lchmod=function(u,d,p){p&&process.nextTick(p)},e.lchmodSync=function(){}),e.chown&&!e.lchown&&(e.lchown=function(u,d,p,f){f&&process.nextTick(f)},e.lchownSync=function(){}),e_==="win32"&&(e.rename=typeof e.rename!="function"?e.rename:(function(u){function d(p,f,m){var g=Date.now(),y=0;u(p,f,function w(k){if(k&&(k.code==="EACCES"||k.code==="EPERM"||k.code==="EBUSY")&&Date.now()-g<6e4){setTimeout(function(){e.stat(f,function(h,v){h&&h.code==="ENOENT"?u(p,f,w):m(k)})},y),y<100&&(y+=10);return}m&&m(k)})}return Object.setPrototypeOf&&Object.setPrototypeOf(d,u),d})(e.rename)),e.read=typeof e.read!="function"?e.read:(function(u){function d(p,f,m,g,y,w){var k;if(w&&typeof w=="function"){var h=0;k=function(v,S,b){if(v&&v.code==="EAGAIN"&&h<10)return h++,u.call(e,p,f,m,g,y,k);w.apply(this,arguments)}}return u.call(e,p,f,m,g,y,k)}return Object.setPrototypeOf&&Object.setPrototypeOf(d,u),d})(e.read),e.readSync=typeof e.readSync!="function"?e.readSync:(function(u){return function(d,p,f,m,g){for(var y=0;;)try{return u.call(e,d,p,f,m,g)}catch(w){if(w.code==="EAGAIN"&&y<10){y++;continue}throw w}}})(e.readSync);function t(u){u.lchmod=function(d,p,f){u.open(d,Zt.O_WRONLY|Zt.O_SYMLINK,p,function(m,g){if(m){f&&f(m);return}u.fchmod(g,p,function(y){u.close(g,function(w){f&&f(y||w)})})})},u.lchmodSync=function(d,p){var f=u.openSync(d,Zt.O_WRONLY|Zt.O_SYMLINK,p),m=!0,g;try{g=u.fchmodSync(f,p),m=!1}finally{if(m)try{u.closeSync(f)}catch{}else u.closeSync(f)}return g}}function n(u){Zt.hasOwnProperty("O_SYMLINK")&&u.futimes?(u.lutimes=function(d,p,f,m){u.open(d,Zt.O_SYMLINK,function(g,y){if(g){m&&m(g);return}u.futimes(y,p,f,function(w){u.close(y,function(k){m&&m(w||k)})})})},u.lutimesSync=function(d,p,f){var m=u.openSync(d,Zt.O_SYMLINK),g,y=!0;try{g=u.futimesSync(m,p,f),y=!1}finally{if(y)try{u.closeSync(m)}catch{}else u.closeSync(m)}return g}):u.futimes&&(u.lutimes=function(d,p,f,m){m&&process.nextTick(m)},u.lutimesSync=function(){})}function r(u){return u&&function(d,p,f){return u.call(e,d,p,function(m){l(m)&&(m=null),f&&f.apply(this,arguments)})}}function o(u){return u&&function(d,p){try{return u.call(e,d,p)}catch(f){if(!l(f))throw f}}}function s(u){return u&&function(d,p,f,m){return u.call(e,d,p,f,function(g){l(g)&&(g=null),m&&m.apply(this,arguments)})}}function i(u){return u&&function(d,p,f){try{return u.call(e,d,p,f)}catch(m){if(!l(m))throw m}}}function a(u){return u&&function(d,p,f){typeof p=="function"&&(f=p,p=null);function m(g,y){y&&(y.uid<0&&(y.uid+=4294967296),y.gid<0&&(y.gid+=4294967296)),f&&f.apply(this,arguments)}return p?u.call(e,d,p,m):u.call(e,d,m)}}function c(u){return u&&function(d,p){var f=p?u.call(e,d,p):u.call(e,d);return f&&(f.uid<0&&(f.uid+=4294967296),f.gid<0&&(f.gid+=4294967296)),f}}function l(u){if(!u||u.code==="ENOSYS")return!0;var d=!process.getuid||process.getuid()!==0;return!!(d&&(u.code==="EINVAL"||u.code==="EPERM"))}}});var xu=q((oA,Ru)=>{var Cu=require("stream").Stream;Ru.exports=n_;function n_(e){return{ReadStream:t,WriteStream:n};function t(r,o){if(!(this instanceof t))return new t(r,o);Cu.call(this);var s=this;this.path=r,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=64*1024,o=o||{};for(var i=Object.keys(o),a=0,c=i.length;a<c;a++){var l=i[a];this[l]=o[l]}if(this.encoding&&this.setEncoding(this.encoding),this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.end===void 0)this.end=1/0;else if(typeof this.end!="number")throw TypeError("end must be a Number");if(this.start>this.end)throw new Error("start must be <= end");this.pos=this.start}if(this.fd!==null){process.nextTick(function(){s._read()});return}e.open(this.path,this.flags,this.mode,function(u,d){if(u){s.emit("error",u),s.readable=!1;return}s.fd=d,s.emit("open",d),s._read()})}function n(r,o){if(!(this instanceof n))return new n(r,o);Cu.call(this),this.path=r,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,o=o||{};for(var s=Object.keys(o),i=0,a=s.length;i<a;i++){var c=s[i];this[c]=o[c]}if(this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.start<0)throw new Error("start must be >= zero");this.pos=this.start}this.busy=!1,this._queue=[],this.fd===null&&(this._open=e.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}});var Iu=q((sA,Pu)=>{"use strict";Pu.exports=o_;var r_=Object.getPrototypeOf||function(e){return e.__proto__};function o_(e){if(e===null||typeof e!="object")return e;if(e instanceof Object)var t={__proto__:r_(e)};else var t=Object.create(null);return Object.getOwnPropertyNames(e).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(e,n))}),t}});var Yn=q((iA,xi)=>{var ne=require("fs"),s_=bu(),i_=xu(),a_=Iu(),Io=require("util"),_e,Oo;typeof Symbol=="function"&&typeof Symbol.for=="function"?(_e=Symbol.for("graceful-fs.queue"),Oo=Symbol.for("graceful-fs.previous")):(_e="___graceful-fs.queue",Oo="___graceful-fs.previous");function c_(){}function $u(e,t){Object.defineProperty(e,_e,{get:function(){return t}})}var kn=c_;Io.debuglog?kn=Io.debuglog("gfs4"):/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&(kn=function(){var e=Io.format.apply(Io,arguments);e="GFS4: "+e.split(/\n/).join(`
10
- GFS4: `),console.error(e)});ne[_e]||(Au=global[_e]||[],$u(ne,Au),ne.close=(function(e){function t(n,r){return e.call(ne,n,function(o){o||Ou(),typeof r=="function"&&r.apply(this,arguments)})}return Object.defineProperty(t,Oo,{value:e}),t})(ne.close),ne.closeSync=(function(e){function t(n){e.apply(ne,arguments),Ou()}return Object.defineProperty(t,Oo,{value:e}),t})(ne.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&process.on("exit",function(){kn(ne[_e]),require("assert").equal(ne[_e].length,0)}));var Au;global[_e]||$u(global,ne[_e]);xi.exports=Ci(a_(ne));process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!ne.__patched&&(xi.exports=Ci(ne),ne.__patched=!0);function Ci(e){s_(e),e.gracefulify=Ci,e.createReadStream=S,e.createWriteStream=b;var t=e.readFile;e.readFile=n;function n(R,A,C){return typeof A=="function"&&(C=A,A=null),$(R,A,C);function $(N,x,E,M){return t(N,x,function(F){F&&(F.code==="EMFILE"||F.code==="ENFILE")?qn([$,[N,x,E],F,M||Date.now(),Date.now()]):typeof E=="function"&&E.apply(this,arguments)})}}var r=e.writeFile;e.writeFile=o;function o(R,A,C,$){return typeof C=="function"&&($=C,C=null),N(R,A,C,$);function N(x,E,M,F,K){return r(x,E,M,function(V){V&&(V.code==="EMFILE"||V.code==="ENFILE")?qn([N,[x,E,M,F],V,K||Date.now(),Date.now()]):typeof F=="function"&&F.apply(this,arguments)})}}var s=e.appendFile;s&&(e.appendFile=i);function i(R,A,C,$){return typeof C=="function"&&($=C,C=null),N(R,A,C,$);function N(x,E,M,F,K){return s(x,E,M,function(V){V&&(V.code==="EMFILE"||V.code==="ENFILE")?qn([N,[x,E,M,F],V,K||Date.now(),Date.now()]):typeof F=="function"&&F.apply(this,arguments)})}}var a=e.copyFile;a&&(e.copyFile=c);function c(R,A,C,$){return typeof C=="function"&&($=C,C=0),N(R,A,C,$);function N(x,E,M,F,K){return a(x,E,M,function(V){V&&(V.code==="EMFILE"||V.code==="ENFILE")?qn([N,[x,E,M,F],V,K||Date.now(),Date.now()]):typeof F=="function"&&F.apply(this,arguments)})}}var l=e.readdir;e.readdir=d;var u=/^v[0-5]\./;function d(R,A,C){typeof A=="function"&&(C=A,A=null);var $=u.test(process.version)?function(E,M,F,K){return l(E,N(E,M,F,K))}:function(E,M,F,K){return l(E,M,N(E,M,F,K))};return $(R,A,C);function N(x,E,M,F){return function(K,V){K&&(K.code==="EMFILE"||K.code==="ENFILE")?qn([$,[x,E,M],K,F||Date.now(),Date.now()]):(V&&V.sort&&V.sort(),typeof M=="function"&&M.call(this,K,V))}}}if(process.version.substr(0,4)==="v0.8"){var p=i_(e);w=p.ReadStream,h=p.WriteStream}var f=e.ReadStream;f&&(w.prototype=Object.create(f.prototype),w.prototype.open=k);var m=e.WriteStream;m&&(h.prototype=Object.create(m.prototype),h.prototype.open=v),Object.defineProperty(e,"ReadStream",{get:function(){return w},set:function(R){w=R},enumerable:!0,configurable:!0}),Object.defineProperty(e,"WriteStream",{get:function(){return h},set:function(R){h=R},enumerable:!0,configurable:!0});var g=w;Object.defineProperty(e,"FileReadStream",{get:function(){return g},set:function(R){g=R},enumerable:!0,configurable:!0});var y=h;Object.defineProperty(e,"FileWriteStream",{get:function(){return y},set:function(R){y=R},enumerable:!0,configurable:!0});function w(R,A){return this instanceof w?(f.apply(this,arguments),this):w.apply(Object.create(w.prototype),arguments)}function k(){var R=this;j(R.path,R.flags,R.mode,function(A,C){A?(R.autoClose&&R.destroy(),R.emit("error",A)):(R.fd=C,R.emit("open",C),R.read())})}function h(R,A){return this instanceof h?(m.apply(this,arguments),this):h.apply(Object.create(h.prototype),arguments)}function v(){var R=this;j(R.path,R.flags,R.mode,function(A,C){A?(R.destroy(),R.emit("error",A)):(R.fd=C,R.emit("open",C))})}function S(R,A){return new e.ReadStream(R,A)}function b(R,A){return new e.WriteStream(R,A)}var _=e.open;e.open=j;function j(R,A,C,$){return typeof C=="function"&&($=C,C=null),N(R,A,C,$);function N(x,E,M,F,K){return _(x,E,M,function(V,hn){V&&(V.code==="EMFILE"||V.code==="ENFILE")?qn([N,[x,E,M,F],V,K||Date.now(),Date.now()]):typeof F=="function"&&F.apply(this,arguments)})}}return e}function qn(e){kn("ENQUEUE",e[0].name,e[1]),ne[_e].push(e),Ri()}var Ao;function Ou(){for(var e=Date.now(),t=0;t<ne[_e].length;++t)ne[_e][t].length>2&&(ne[_e][t][3]=e,ne[_e][t][4]=e);Ri()}function Ri(){if(clearTimeout(Ao),Ao=void 0,ne[_e].length!==0){var e=ne[_e].shift(),t=e[0],n=e[1],r=e[2],o=e[3],s=e[4];if(o===void 0)kn("RETRY",t.name,n),t.apply(null,n);else if(Date.now()-o>=6e4){kn("TIMEOUT",t.name,n);var i=n.pop();typeof i=="function"&&i.call(null,r)}else{var a=Date.now()-s,c=Math.max(s-o,1),l=Math.min(c*1.2,100);a>=l?(kn("RETRY",t.name,n),t.apply(null,n.concat([o]))):ne[_e].push(e)}Ao===void 0&&(Ao=setTimeout(Ri,0))}}});var Re=q(Dt=>{"use strict";var Du=pe().fromCallback,Ce=Yn(),l_=["access","appendFile","chmod","chown","close","copyFile","cp","fchmod","fchown","fdatasync","fstat","fsync","ftruncate","futimes","glob","lchmod","lchown","lutimes","link","lstat","mkdir","mkdtemp","open","opendir","readdir","readFile","readlink","realpath","rename","rm","rmdir","stat","statfs","symlink","truncate","unlink","utimes","writeFile"].filter(e=>typeof Ce[e]=="function");Object.assign(Dt,Ce);l_.forEach(e=>{Dt[e]=Du(Ce[e])});Dt.exists=function(e,t){return typeof t=="function"?Ce.exists(e,t):new Promise(n=>Ce.exists(e,n))};Dt.read=function(e,t,n,r,o,s){return typeof s=="function"?Ce.read(e,t,n,r,o,s):new Promise((i,a)=>{Ce.read(e,t,n,r,o,(c,l,u)=>{if(c)return a(c);i({bytesRead:l,buffer:u})})})};Dt.write=function(e,t,...n){return typeof n[n.length-1]=="function"?Ce.write(e,t,...n):new Promise((r,o)=>{Ce.write(e,t,...n,(s,i,a)=>{if(s)return o(s);r({bytesWritten:i,buffer:a})})})};Dt.readv=function(e,t,...n){return typeof n[n.length-1]=="function"?Ce.readv(e,t,...n):new Promise((r,o)=>{Ce.readv(e,t,...n,(s,i,a)=>{if(s)return o(s);r({bytesRead:i,buffers:a})})})};Dt.writev=function(e,t,...n){return typeof n[n.length-1]=="function"?Ce.writev(e,t,...n):new Promise((r,o)=>{Ce.writev(e,t,...n,(s,i,a)=>{if(s)return o(s);r({bytesWritten:i,buffers:a})})})};typeof Ce.realpath.native=="function"?Dt.realpath.native=Du(Ce.realpath.native):process.emitWarning("fs.realpath.native is not a function. Is fs being monkey-patched?","Warning","fs-extra-WARN0003")});var Fu=q((cA,Nu)=>{"use strict";var u_=require("path");Nu.exports.checkPath=function(t){if(process.platform==="win32"&&/[<>:"|?*]/.test(t.replace(u_.parse(t).root,""))){let r=new Error(`Path contains invalid characters: ${t}`);throw r.code="EINVAL",r}}});var Uu=q((lA,Pi)=>{"use strict";var ju=Re(),{checkPath:Mu}=Fu(),Lu=e=>{let t={mode:511};return typeof e=="number"?e:{...t,...e}.mode};Pi.exports.makeDir=async(e,t)=>(Mu(e),ju.mkdir(e,{mode:Lu(t),recursive:!0}));Pi.exports.makeDirSync=(e,t)=>(Mu(e),ju.mkdirSync(e,{mode:Lu(t),recursive:!0}))});var ct=q((uA,Wu)=>{"use strict";var d_=pe().fromPromise,{makeDir:p_,makeDirSync:Ii}=Uu(),Ai=d_(p_);Wu.exports={mkdirs:Ai,mkdirsSync:Ii,mkdirp:Ai,mkdirpSync:Ii,ensureDir:Ai,ensureDirSync:Ii}});var en=q((dA,Bu)=>{"use strict";var f_=pe().fromPromise,Gu=Re();function m_(e){return Gu.access(e).then(()=>!0).catch(()=>!1)}Bu.exports={pathExists:f_(m_),pathExistsSync:Gu.existsSync}});var Oi=q((pA,Hu)=>{"use strict";var Kn=Re(),g_=pe().fromPromise;async function h_(e,t,n){let r=await Kn.open(e,"r+"),o=null;try{await Kn.futimes(r,t,n)}finally{try{await Kn.close(r)}catch(s){o=s}}if(o)throw o}function y_(e,t,n){let r=Kn.openSync(e,"r+");return Kn.futimesSync(r,t,n),Kn.closeSync(r)}Hu.exports={utimesMillis:g_(h_),utimesMillisSync:y_}});var _n=q((fA,Ku)=>{"use strict";var Jn=Re(),fe=require("path"),Vu=pe().fromPromise;function w_(e,t,n){let r=n.dereference?o=>Jn.stat(o,{bigint:!0}):o=>Jn.lstat(o,{bigint:!0});return Promise.all([r(e),r(t).catch(o=>{if(o.code==="ENOENT")return null;throw o})]).then(([o,s])=>({srcStat:o,destStat:s}))}function k_(e,t,n){let r,o=n.dereference?i=>Jn.statSync(i,{bigint:!0}):i=>Jn.lstatSync(i,{bigint:!0}),s=o(e);try{r=o(t)}catch(i){if(i.code==="ENOENT")return{srcStat:s,destStat:null};throw i}return{srcStat:s,destStat:r}}async function __(e,t,n,r){let{srcStat:o,destStat:s}=await w_(e,t,r);if(s){if(Nr(o,s)){let i=fe.basename(e),a=fe.basename(t);if(n==="move"&&i!==a&&i.toLowerCase()===a.toLowerCase())return{srcStat:o,destStat:s,isChangingCase:!0};throw new Error("Source and destination must not be the same.")}if(o.isDirectory()&&!s.isDirectory())throw new Error(`Cannot overwrite non-directory '${t}' with directory '${e}'.`);if(!o.isDirectory()&&s.isDirectory())throw new Error(`Cannot overwrite directory '${t}' with non-directory '${e}'.`)}if(o.isDirectory()&&$i(e,t))throw new Error($o(e,t,n));return{srcStat:o,destStat:s}}function S_(e,t,n,r){let{srcStat:o,destStat:s}=k_(e,t,r);if(s){if(Nr(o,s)){let i=fe.basename(e),a=fe.basename(t);if(n==="move"&&i!==a&&i.toLowerCase()===a.toLowerCase())return{srcStat:o,destStat:s,isChangingCase:!0};throw new Error("Source and destination must not be the same.")}if(o.isDirectory()&&!s.isDirectory())throw new Error(`Cannot overwrite non-directory '${t}' with directory '${e}'.`);if(!o.isDirectory()&&s.isDirectory())throw new Error(`Cannot overwrite directory '${t}' with non-directory '${e}'.`)}if(o.isDirectory()&&$i(e,t))throw new Error($o(e,t,n));return{srcStat:o,destStat:s}}async function qu(e,t,n,r){let o=fe.resolve(fe.dirname(e)),s=fe.resolve(fe.dirname(n));if(s===o||s===fe.parse(s).root)return;let i;try{i=await Jn.stat(s,{bigint:!0})}catch(a){if(a.code==="ENOENT")return;throw a}if(Nr(t,i))throw new Error($o(e,n,r));return qu(e,t,s,r)}function Yu(e,t,n,r){let o=fe.resolve(fe.dirname(e)),s=fe.resolve(fe.dirname(n));if(s===o||s===fe.parse(s).root)return;let i;try{i=Jn.statSync(s,{bigint:!0})}catch(a){if(a.code==="ENOENT")return;throw a}if(Nr(t,i))throw new Error($o(e,n,r));return Yu(e,t,s,r)}function Nr(e,t){return t.ino!==void 0&&t.dev!==void 0&&t.ino===e.ino&&t.dev===e.dev}function $i(e,t){let n=fe.resolve(e).split(fe.sep).filter(o=>o),r=fe.resolve(t).split(fe.sep).filter(o=>o);return n.every((o,s)=>r[s]===o)}function $o(e,t,n){return`Cannot ${n} '${e}' to a subdirectory of itself, '${t}'.`}Ku.exports={checkPaths:Vu(__),checkPathsSync:S_,checkParentPaths:Vu(qu),checkParentPathsSync:Yu,isSrcSubdir:$i,areIdentical:Nr}});var zu=q((mA,Ju)=>{"use strict";async function v_(e,t){let n=[];for await(let r of e)n.push(t(r).then(()=>null,o=>o??new Error("unknown error")));await Promise.all(n.map(r=>r.then(o=>{if(o!==null)throw o})))}Ju.exports={asyncIteratorConcurrentProcess:v_}});var td=q((gA,ed)=>{"use strict";var ve=Re(),Fr=require("path"),{mkdirs:T_}=ct(),{pathExists:E_}=en(),{utimesMillis:b_}=Oi(),jr=_n(),{asyncIteratorConcurrentProcess:C_}=zu();async function R_(e,t,n={}){typeof n=="function"&&(n={filter:n}),n.clobber="clobber"in n?!!n.clobber:!0,n.overwrite="overwrite"in n?!!n.overwrite:n.clobber,n.preserveTimestamps&&process.arch==="ia32"&&process.emitWarning(`Using the preserveTimestamps option in 32-bit node is not recommended;
3
+ "use strict";var b_=Object.create;var So=Object.defineProperty;var T_=Object.getOwnPropertyDescriptor;var E_=Object.getOwnPropertyNames;var C_=Object.getPrototypeOf,R_=Object.prototype.hasOwnProperty;var U=(e,t)=>()=>(e&&(t=e(e=0)),t);var q=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),he=(e,t)=>{for(var n in t)So(e,n,{get:t[n],enumerable:!0})},Sl=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of E_(t))!R_.call(e,o)&&o!==n&&So(e,o,{get:()=>t[o],enumerable:!(r=T_(t,o))||r.enumerable});return e};var b=(e,t,n)=>(n=e!=null?b_(C_(e)):{},Sl(t||!e||!e.__esModule?So(n,"default",{value:e,enumerable:!0}):n,e)),x_=e=>Sl(So({},"__esModule",{value:!0}),e);var Si,tu=U(()=>{"use strict";Si={maxAgeInDays:30,maxArchiveCount:5}});function vi(e){if(!e.token_usage)return null;let{token_usage:t}=e;return typeof t.input_tokens!="number"||typeof t.output_tokens!="number"||typeof t.total_tokens!="number"||typeof t.estimated!="boolean"?null:t}function Wn(e){return vi(e)?.total_tokens||0}var nu=U(()=>{"use strict"});function J_(e){let t=(0,Bn.basename)(e);(!t||/^[A-Za-z]:[\\/]?$/.test(e)||/^[A-Za-z]:$/.test(t))&&(t="root");let n=t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"").substring(0,30);n||(n="unknown");let r=(0,ou.createHash)("sha256").update(e).digest("hex").substring(0,8);return`${n}-${r}`}function yn(e){return(0,Bn.join)(pe(),"projects",J_(e))}function bi(e){try{(0,ru.mkdirSync)(yn(e),{recursive:!0})}catch(t){t.code!=="EEXIST"&&console.error("Failed to create project directory:",t)}}var Bn,K_,ru,ou,su=U(()=>{"use strict";Bn=require("path"),K_=require("child_process"),ru=require("fs"),ou=require("crypto");we();Be()});function pe(){return process.env.OLYMPUS_TEST_LEARNING_DIR?process.env.OLYMPUS_TEST_LEARNING_DIR:(0,se.join)((0,au.homedir)(),".claude","olympus","learning")}function _t(e){return(0,se.join)(e,".olympus","learning")}function lu(e){let t=(0,se.resolve)(e);return(0,cu.createHash)("sha256").update(t).digest("hex").substring(0,16)}function Hn(e){let t=pe();if((0,z.existsSync)(t)||(0,z.mkdirSync)(t,{recursive:!0}),e){let n=_t(e);(0,z.existsSync)(n)||(0,z.mkdirSync)(n,{recursive:!0})}}function Q_(e,t=Si){try{let n=(0,se.dirname)(e),r=(0,se.basename)(e,".jsonl"),o=(0,z.readdirSync)(n),s=new RegExp(`^${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\..*\\.old\\.jsonl$`),i=o.filter(d=>s.test(d)).map(d=>{let p=d.match(/\.(\d{4}-\d{2}-\d{2})T/),f=p?new Date(p[1]):null;return{filename:d,filepath:(0,se.join)(n,d),timestamp:f}}).filter(d=>d.timestamp!==null&&!isNaN(d.timestamp.getTime())).sort((d,p)=>p.timestamp.getTime()-d.timestamp.getTime()),a=t.maxAgeInDays??30,c=t.maxArchiveCount??5,l=new Date(Date.now()-a*24*60*60*1e3),u=0;for(let d=0;d<i.length;d++){let p=i[d],f=p.timestamp<l,m=d>=c;if(f||m)try{(0,z.unlinkSync)(p.filepath),u++}catch{}}u>0&&console.log(`[Olympus Learning] Pruned ${u} old archives`)}catch(n){console.error("[Olympus Learning] Failed to prune archives:",n)}}function Gn(e,t=z_,n=Si){if((0,z.existsSync)(e))try{let o=(0,z.readFileSync)(e,"utf-8").split(`
4
+ `).filter(s=>s.trim()).length;if(o>=t){let s=new Date().toISOString().replace(/[:.]/g,"-"),i=e.replace(".jsonl",`.${s}.old.jsonl`);(0,z.renameSync)(e,i),console.log(`[Olympus Learning] Archived ${o} entries to ${i}`),Q_(e,n)}}catch(r){console.error(`[Olympus Learning] Failed to rotate ${e}:`,r)}}function Xt(e){if(e.project_path&&typeof e.project_path=="string")try{bi(e.project_path);let n=(0,se.join)(yn(e.project_path),"feedback-log.jsonl");Gn(n),(0,z.appendFileSync)(n,JSON.stringify(e)+`
5
+ `,"utf-8");return}catch(n){console.error("[Olympus Learning] Project write failed, using global fallback:",n)}Hn();let t=(0,se.join)(pe(),"feedback-log.jsonl");Gn(t),(0,z.appendFileSync)(t,JSON.stringify(e)+`
6
+ `,"utf-8")}function Co(e){let t=e?(0,se.join)(yn(e),"feedback-log.jsonl"):(0,se.join)(pe(),"feedback-log.jsonl");return(0,z.existsSync)(t)?(0,z.readFileSync)(t,"utf-8").split(`
7
+ `).filter(r=>r.trim()).map(r=>JSON.parse(r)):[]}function X_(e){let t=e.filter(o=>o.event_type==="revision"||o.event_type==="cancellation"),n=new Map;for(let o of t){let s=o.extracted_lesson||o.feedback_category||"unknown",i=n.get(s);i?(i.count++,i.examples.length<3&&i.examples.push(o.user_message.substring(0,100))):n.set(s,{count:1,examples:[o.user_message.substring(0,100)]})}let r=[];for(let[o,s]of n)s.count>=2&&r.push({pattern:o,count:s.count,examples:s.examples});return r}function Z_(e){let t=[];return e>=.85&&t.push("high success rate"),t}function ek(e,t){let n=[];return e<.6&&n.push("low success rate"),t>2&&n.push("frequently cancelled"),n}function Ro(e,t,n){let r=t.filter(m=>m.agent_used===e);if(r.length===0)return null;let o=r.length,s=r.filter(m=>m.event_type==="success").length,i=r.filter(m=>m.event_type==="revision").length,a=r.filter(m=>m.event_type==="cancellation").length,c=o>0?s/o:0,l,u=r.filter(m=>vi(m)!==null);if(u.length>0){let m=u.filter(S=>S.event_type==="success"),g=u.filter(S=>S.event_type==="revision"||S.event_type==="cancellation"),y=u.reduce((S,E)=>S+Wn(E),0),w=m.reduce((S,E)=>S+Wn(E),0),_=g.reduce((S,E)=>S+Wn(E),0),h=m.length>0?w/m.length:0,v=g.length>0?_/g.length:0;if(l={avg_tokens_per_success:h,avg_tokens_per_failure:v,total_tokens:y,invocation_count:u.length,efficiency_score:h,trend:"insufficient_data"},u.length>=10){let S=Math.floor(u.length/2),E=u.slice(0,S),k=u.slice(S),j=E.reduce(($,N)=>$+Wn(N),0)/E.length,O=k.reduce(($,N)=>$+Wn(N),0)/k.length-j,C=j*.1;Math.abs(O)<C?l.trend="stable":O<0?l.trend="improving":l.trend="declining"}}let d={agent_name:e,total_invocations:o,success_count:s,revision_count:i,cancellation_count:a,success_rate:c,failure_patterns:X_(r),strong_areas:Z_(c),weak_areas:ek(c,a),last_updated:new Date().toISOString(),token_efficiency:l};if(n)try{let m=(0,se.join)(yn(n),"agent-performance.json"),g=_e(m,{});g[e]=d,at(m,g)}catch(m){console.error("[Olympus Learning] Failed to write project agent performance:",m)}let p=(0,se.join)(pe(),"agent-performance.json"),f=_e(p,{});return f[e]=d,at(p,f),d}function Vn(e){let t=e?(0,se.join)(yn(e),"agent-performance.json"):(0,se.join)(pe(),"agent-performance.json");return _e(t,{})}function _e(e,t){if(!(0,z.existsSync)(e))return t;try{return JSON.parse((0,z.readFileSync)(e,"utf-8"))}catch(n){return console.error(`[Olympus Learning] Failed to read ${e}:`,n),t}}function at(e,t){try{let n=(0,se.dirname)(e);n&&!(0,z.existsSync)(n)&&(0,z.mkdirSync)(n,{recursive:!0}),(0,z.writeFileSync)(e,JSON.stringify(t,null,2),"utf-8")}catch(n){console.error(`[Olympus Learning] Failed to write ${e}:`,n)}}function uu(e,t){if(t)try{bi(t);let r=(0,se.join)(yn(t),"session-summaries.jsonl");Gn(r,iu),(0,z.appendFileSync)(r,JSON.stringify(e)+`
8
+ `,"utf-8");return}catch(r){console.error("[Olympus Learning] Project session summary write failed, using global fallback:",r)}Hn();let n=(0,se.join)(pe(),"session-summaries.jsonl");Gn(n,iu),(0,z.appendFileSync)(n,JSON.stringify(e)+`
9
+ `,"utf-8")}var au,se,z,cu,z_,iu,we=U(()=>{"use strict";au=require("os"),se=require("path"),z=require("fs"),cu=require("crypto");tu();nu();su();z_=1e4,iu=500});function wn(e,t){return!t||t.sample_count<5?1e4:e&&t.by_task_type[e]!==void 0?t.by_task_type[e]:t.overall_avg}var Ti=U(()=>{"use strict"});function mu(e){return(0,pu.join)(e,".olympus","session-state.json")}function du(e,t){let n=wn();return{session_id:e||(0,fu.randomUUID)(),started_at:new Date().toISOString(),last_updated:new Date().toISOString(),recent_prompts:[],pending_completion:null,todo_snapshot:null,token_budget:{session_baseline:n,current_usage:0,input_tokens:0,output_tokens:0,warning_threshold:1.5,warning_issued:!1,started_at:new Date().toISOString()},discovery_volume:{session_count:0,daily_count:0,daily_reset_at:new Date().toISOString()},resolved_project_root:null}}function Q(e,t){let n=mu(e),r=_e(n,null);if(!r)return du(t,e);let o=new Date(r.last_updated).getTime();if(Date.now()-o>nk)return du(t,e);if(t&&r.session_id!==t&&(r.session_id=t),r.token_budget)r.token_budget.input_tokens===void 0&&(r.token_budget.input_tokens=0),r.token_budget.output_tokens===void 0&&(r.token_budget.output_tokens=0);else{let i=wn();r.token_budget={session_baseline:i,current_usage:0,input_tokens:0,output_tokens:0,warning_threshold:1.5,warning_issued:!1,started_at:r.started_at}}return r.discovery_volume||(r.discovery_volume={session_count:0,daily_count:0,daily_reset_at:new Date().toISOString()}),r.resolved_project_root===void 0&&(r.resolved_project_root=null),r}function ee(e,t){let n=mu(e);t.last_updated=new Date().toISOString(),at(n,t)}function gu(e,t,n){let r={prompt:t,timestamp:new Date().toISOString(),detected_feedback:n};return e.recent_prompts=[r,...e.recent_prompts].slice(0,tk),e.last_updated=new Date().toISOString(),e}function hu(e,t,n){return e.pending_completion={claimed_at:new Date().toISOString(),task_description:t,agent_used:n},e.last_updated=new Date().toISOString(),e}function yu(e){return e.pending_completion=null,e.last_updated=new Date().toISOString(),e}function xo(e){if(!e.pending_completion?.claimed_at)return!1;let t=new Date(e.pending_completion.claimed_at).getTime();return Date.now()-t<300*1e3}function wu(e,t){let n=wn();return e.token_budget={session_baseline:n,current_usage:0,input_tokens:0,output_tokens:0,warning_threshold:1.5,warning_issued:!1,started_at:new Date().toISOString()},e.last_updated=new Date().toISOString(),e}function _u(e,t){return e.token_budget||(e.token_budget={session_baseline:wn(),current_usage:0,input_tokens:0,output_tokens:0,warning_threshold:1.5,warning_issued:!1,started_at:new Date().toISOString()}),e.token_budget.current_usage+=t,e.last_updated=new Date().toISOString(),e}function ku(e){return e.token_budget&&(e.token_budget.warning_issued=!0,e.last_updated=new Date().toISOString()),e}function Su(e){if(!e.token_budget||e.token_budget.warning_issued)return!1;let t=e.token_budget.session_baseline*e.token_budget.warning_threshold;return e.token_budget.current_usage>=t}function vu(e){e.discovery_volume||(e.discovery_volume={session_count:0,daily_count:0,daily_reset_at:new Date().toISOString()});let t=new Date(e.discovery_volume.daily_reset_at),n=new Date;return n.toDateString()!==t.toDateString()&&(e.discovery_volume.daily_count=0,e.discovery_volume.daily_reset_at=n.toISOString()),e.discovery_volume.session_count++,e.discovery_volume.daily_count++,e.last_updated=n.toISOString(),e}function bu(e,t){if(!e.discovery_volume)return!1;let n=new Date(e.discovery_volume.daily_reset_at);return new Date().toDateString()!==n.toDateString()?!1:e.discovery_volume.session_count>=t.maxPerSession||e.discovery_volume.daily_count>=t.maxPerDay}var pu,fu,tk,nk,Be=U(()=>{"use strict";pu=require("path");we();fu=require("crypto");Ti();tk=10,nk=1800*1e3});var fe=q(Ci=>{"use strict";Ci.fromCallback=function(e){return Object.defineProperty(function(...t){if(typeof t[t.length-1]=="function")e.apply(this,t);else return new Promise((n,r)=>{t.push((o,s)=>o!=null?r(o):n(s)),e.apply(this,t)})},"name",{value:e.name})};Ci.fromPromise=function(e){return Object.defineProperty(function(...t){let n=t[t.length-1];if(typeof n!="function")return e.apply(this,t);t.pop(),e.apply(this,t).then(r=>n(null,r),n)},"name",{value:e.name})}});var Pu=q((yI,xu)=>{var Zt=require("constants"),ok=process.cwd,Po=null,sk=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return Po||(Po=ok.call(process)),Po};try{process.cwd()}catch{}typeof process.chdir=="function"&&(Ri=process.chdir,process.chdir=function(e){Po=null,Ri.call(process,e)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,Ri));var Ri;xu.exports=ik;function ik(e){Zt.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&t(e),e.lutimes||n(e),e.chown=s(e.chown),e.fchown=s(e.fchown),e.lchown=s(e.lchown),e.chmod=r(e.chmod),e.fchmod=r(e.fchmod),e.lchmod=r(e.lchmod),e.chownSync=i(e.chownSync),e.fchownSync=i(e.fchownSync),e.lchownSync=i(e.lchownSync),e.chmodSync=o(e.chmodSync),e.fchmodSync=o(e.fchmodSync),e.lchmodSync=o(e.lchmodSync),e.stat=a(e.stat),e.fstat=a(e.fstat),e.lstat=a(e.lstat),e.statSync=c(e.statSync),e.fstatSync=c(e.fstatSync),e.lstatSync=c(e.lstatSync),e.chmod&&!e.lchmod&&(e.lchmod=function(u,d,p){p&&process.nextTick(p)},e.lchmodSync=function(){}),e.chown&&!e.lchown&&(e.lchown=function(u,d,p,f){f&&process.nextTick(f)},e.lchownSync=function(){}),sk==="win32"&&(e.rename=typeof e.rename!="function"?e.rename:(function(u){function d(p,f,m){var g=Date.now(),y=0;u(p,f,function w(_){if(_&&(_.code==="EACCES"||_.code==="EPERM"||_.code==="EBUSY")&&Date.now()-g<6e4){setTimeout(function(){e.stat(f,function(h,v){h&&h.code==="ENOENT"?u(p,f,w):m(_)})},y),y<100&&(y+=10);return}m&&m(_)})}return Object.setPrototypeOf&&Object.setPrototypeOf(d,u),d})(e.rename)),e.read=typeof e.read!="function"?e.read:(function(u){function d(p,f,m,g,y,w){var _;if(w&&typeof w=="function"){var h=0;_=function(v,S,E){if(v&&v.code==="EAGAIN"&&h<10)return h++,u.call(e,p,f,m,g,y,_);w.apply(this,arguments)}}return u.call(e,p,f,m,g,y,_)}return Object.setPrototypeOf&&Object.setPrototypeOf(d,u),d})(e.read),e.readSync=typeof e.readSync!="function"?e.readSync:(function(u){return function(d,p,f,m,g){for(var y=0;;)try{return u.call(e,d,p,f,m,g)}catch(w){if(w.code==="EAGAIN"&&y<10){y++;continue}throw w}}})(e.readSync);function t(u){u.lchmod=function(d,p,f){u.open(d,Zt.O_WRONLY|Zt.O_SYMLINK,p,function(m,g){if(m){f&&f(m);return}u.fchmod(g,p,function(y){u.close(g,function(w){f&&f(y||w)})})})},u.lchmodSync=function(d,p){var f=u.openSync(d,Zt.O_WRONLY|Zt.O_SYMLINK,p),m=!0,g;try{g=u.fchmodSync(f,p),m=!1}finally{if(m)try{u.closeSync(f)}catch{}else u.closeSync(f)}return g}}function n(u){Zt.hasOwnProperty("O_SYMLINK")&&u.futimes?(u.lutimes=function(d,p,f,m){u.open(d,Zt.O_SYMLINK,function(g,y){if(g){m&&m(g);return}u.futimes(y,p,f,function(w){u.close(y,function(_){m&&m(w||_)})})})},u.lutimesSync=function(d,p,f){var m=u.openSync(d,Zt.O_SYMLINK),g,y=!0;try{g=u.futimesSync(m,p,f),y=!1}finally{if(y)try{u.closeSync(m)}catch{}else u.closeSync(m)}return g}):u.futimes&&(u.lutimes=function(d,p,f,m){m&&process.nextTick(m)},u.lutimesSync=function(){})}function r(u){return u&&function(d,p,f){return u.call(e,d,p,function(m){l(m)&&(m=null),f&&f.apply(this,arguments)})}}function o(u){return u&&function(d,p){try{return u.call(e,d,p)}catch(f){if(!l(f))throw f}}}function s(u){return u&&function(d,p,f,m){return u.call(e,d,p,f,function(g){l(g)&&(g=null),m&&m.apply(this,arguments)})}}function i(u){return u&&function(d,p,f){try{return u.call(e,d,p,f)}catch(m){if(!l(m))throw m}}}function a(u){return u&&function(d,p,f){typeof p=="function"&&(f=p,p=null);function m(g,y){y&&(y.uid<0&&(y.uid+=4294967296),y.gid<0&&(y.gid+=4294967296)),f&&f.apply(this,arguments)}return p?u.call(e,d,p,m):u.call(e,d,m)}}function c(u){return u&&function(d,p){var f=p?u.call(e,d,p):u.call(e,d);return f&&(f.uid<0&&(f.uid+=4294967296),f.gid<0&&(f.gid+=4294967296)),f}}function l(u){if(!u||u.code==="ENOSYS")return!0;var d=!process.getuid||process.getuid()!==0;return!!(d&&(u.code==="EINVAL"||u.code==="EPERM"))}}});var Ou=q((wI,Iu)=>{var Au=require("stream").Stream;Iu.exports=ak;function ak(e){return{ReadStream:t,WriteStream:n};function t(r,o){if(!(this instanceof t))return new t(r,o);Au.call(this);var s=this;this.path=r,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=64*1024,o=o||{};for(var i=Object.keys(o),a=0,c=i.length;a<c;a++){var l=i[a];this[l]=o[l]}if(this.encoding&&this.setEncoding(this.encoding),this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.end===void 0)this.end=1/0;else if(typeof this.end!="number")throw TypeError("end must be a Number");if(this.start>this.end)throw new Error("start must be <= end");this.pos=this.start}if(this.fd!==null){process.nextTick(function(){s._read()});return}e.open(this.path,this.flags,this.mode,function(u,d){if(u){s.emit("error",u),s.readable=!1;return}s.fd=d,s.emit("open",d),s._read()})}function n(r,o){if(!(this instanceof n))return new n(r,o);Au.call(this),this.path=r,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,o=o||{};for(var s=Object.keys(o),i=0,a=s.length;i<a;i++){var c=s[i];this[c]=o[c]}if(this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.start<0)throw new Error("start must be >= zero");this.pos=this.start}this.busy=!1,this._queue=[],this.fd===null&&(this._open=e.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}});var Du=q((_I,$u)=>{"use strict";$u.exports=lk;var ck=Object.getPrototypeOf||function(e){return e.__proto__};function lk(e){if(e===null||typeof e!="object")return e;if(e instanceof Object)var t={__proto__:ck(e)};else var t=Object.create(null);return Object.getOwnPropertyNames(e).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(e,n))}),t}});var Yn=q((kI,Ai)=>{var ne=require("fs"),uk=Pu(),dk=Ou(),pk=Du(),Ao=require("util"),ke,Oo;typeof Symbol=="function"&&typeof Symbol.for=="function"?(ke=Symbol.for("graceful-fs.queue"),Oo=Symbol.for("graceful-fs.previous")):(ke="___graceful-fs.queue",Oo="___graceful-fs.previous");function fk(){}function ju(e,t){Object.defineProperty(e,ke,{get:function(){return t}})}var _n=fk;Ao.debuglog?_n=Ao.debuglog("gfs4"):/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&(_n=function(){var e=Ao.format.apply(Ao,arguments);e="GFS4: "+e.split(/\n/).join(`
10
+ GFS4: `),console.error(e)});ne[ke]||(Nu=global[ke]||[],ju(ne,Nu),ne.close=(function(e){function t(n,r){return e.call(ne,n,function(o){o||Fu(),typeof r=="function"&&r.apply(this,arguments)})}return Object.defineProperty(t,Oo,{value:e}),t})(ne.close),ne.closeSync=(function(e){function t(n){e.apply(ne,arguments),Fu()}return Object.defineProperty(t,Oo,{value:e}),t})(ne.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&process.on("exit",function(){_n(ne[ke]),require("assert").equal(ne[ke].length,0)}));var Nu;global[ke]||ju(global,ne[ke]);Ai.exports=xi(pk(ne));process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!ne.__patched&&(Ai.exports=xi(ne),ne.__patched=!0);function xi(e){uk(e),e.gracefulify=xi,e.createReadStream=S,e.createWriteStream=E;var t=e.readFile;e.readFile=n;function n(R,O,C){return typeof O=="function"&&(C=O,O=null),$(R,O,C);function $(N,x,T,M){return t(N,x,function(F){F&&(F.code==="EMFILE"||F.code==="ENFILE")?qn([$,[N,x,T],F,M||Date.now(),Date.now()]):typeof T=="function"&&T.apply(this,arguments)})}}var r=e.writeFile;e.writeFile=o;function o(R,O,C,$){return typeof C=="function"&&($=C,C=null),N(R,O,C,$);function N(x,T,M,F,K){return r(x,T,M,function(V){V&&(V.code==="EMFILE"||V.code==="ENFILE")?qn([N,[x,T,M,F],V,K||Date.now(),Date.now()]):typeof F=="function"&&F.apply(this,arguments)})}}var s=e.appendFile;s&&(e.appendFile=i);function i(R,O,C,$){return typeof C=="function"&&($=C,C=null),N(R,O,C,$);function N(x,T,M,F,K){return s(x,T,M,function(V){V&&(V.code==="EMFILE"||V.code==="ENFILE")?qn([N,[x,T,M,F],V,K||Date.now(),Date.now()]):typeof F=="function"&&F.apply(this,arguments)})}}var a=e.copyFile;a&&(e.copyFile=c);function c(R,O,C,$){return typeof C=="function"&&($=C,C=0),N(R,O,C,$);function N(x,T,M,F,K){return a(x,T,M,function(V){V&&(V.code==="EMFILE"||V.code==="ENFILE")?qn([N,[x,T,M,F],V,K||Date.now(),Date.now()]):typeof F=="function"&&F.apply(this,arguments)})}}var l=e.readdir;e.readdir=d;var u=/^v[0-5]\./;function d(R,O,C){typeof O=="function"&&(C=O,O=null);var $=u.test(process.version)?function(T,M,F,K){return l(T,N(T,M,F,K))}:function(T,M,F,K){return l(T,M,N(T,M,F,K))};return $(R,O,C);function N(x,T,M,F){return function(K,V){K&&(K.code==="EMFILE"||K.code==="ENFILE")?qn([$,[x,T,M],K,F||Date.now(),Date.now()]):(V&&V.sort&&V.sort(),typeof M=="function"&&M.call(this,K,V))}}}if(process.version.substr(0,4)==="v0.8"){var p=dk(e);w=p.ReadStream,h=p.WriteStream}var f=e.ReadStream;f&&(w.prototype=Object.create(f.prototype),w.prototype.open=_);var m=e.WriteStream;m&&(h.prototype=Object.create(m.prototype),h.prototype.open=v),Object.defineProperty(e,"ReadStream",{get:function(){return w},set:function(R){w=R},enumerable:!0,configurable:!0}),Object.defineProperty(e,"WriteStream",{get:function(){return h},set:function(R){h=R},enumerable:!0,configurable:!0});var g=w;Object.defineProperty(e,"FileReadStream",{get:function(){return g},set:function(R){g=R},enumerable:!0,configurable:!0});var y=h;Object.defineProperty(e,"FileWriteStream",{get:function(){return y},set:function(R){y=R},enumerable:!0,configurable:!0});function w(R,O){return this instanceof w?(f.apply(this,arguments),this):w.apply(Object.create(w.prototype),arguments)}function _(){var R=this;j(R.path,R.flags,R.mode,function(O,C){O?(R.autoClose&&R.destroy(),R.emit("error",O)):(R.fd=C,R.emit("open",C),R.read())})}function h(R,O){return this instanceof h?(m.apply(this,arguments),this):h.apply(Object.create(h.prototype),arguments)}function v(){var R=this;j(R.path,R.flags,R.mode,function(O,C){O?(R.destroy(),R.emit("error",O)):(R.fd=C,R.emit("open",C))})}function S(R,O){return new e.ReadStream(R,O)}function E(R,O){return new e.WriteStream(R,O)}var k=e.open;e.open=j;function j(R,O,C,$){return typeof C=="function"&&($=C,C=null),N(R,O,C,$);function N(x,T,M,F,K){return k(x,T,M,function(V,hn){V&&(V.code==="EMFILE"||V.code==="ENFILE")?qn([N,[x,T,M,F],V,K||Date.now(),Date.now()]):typeof F=="function"&&F.apply(this,arguments)})}}return e}function qn(e){_n("ENQUEUE",e[0].name,e[1]),ne[ke].push(e),Pi()}var Io;function Fu(){for(var e=Date.now(),t=0;t<ne[ke].length;++t)ne[ke][t].length>2&&(ne[ke][t][3]=e,ne[ke][t][4]=e);Pi()}function Pi(){if(clearTimeout(Io),Io=void 0,ne[ke].length!==0){var e=ne[ke].shift(),t=e[0],n=e[1],r=e[2],o=e[3],s=e[4];if(o===void 0)_n("RETRY",t.name,n),t.apply(null,n);else if(Date.now()-o>=6e4){_n("TIMEOUT",t.name,n);var i=n.pop();typeof i=="function"&&i.call(null,r)}else{var a=Date.now()-s,c=Math.max(s-o,1),l=Math.min(c*1.2,100);a>=l?(_n("RETRY",t.name,n),t.apply(null,n.concat([o]))):ne[ke].push(e)}Io===void 0&&(Io=setTimeout(Pi,0))}}});var Re=q(Dt=>{"use strict";var Mu=fe().fromCallback,Ce=Yn(),mk=["access","appendFile","chmod","chown","close","copyFile","cp","fchmod","fchown","fdatasync","fstat","fsync","ftruncate","futimes","glob","lchmod","lchown","lutimes","link","lstat","mkdir","mkdtemp","open","opendir","readdir","readFile","readlink","realpath","rename","rm","rmdir","stat","statfs","symlink","truncate","unlink","utimes","writeFile"].filter(e=>typeof Ce[e]=="function");Object.assign(Dt,Ce);mk.forEach(e=>{Dt[e]=Mu(Ce[e])});Dt.exists=function(e,t){return typeof t=="function"?Ce.exists(e,t):new Promise(n=>Ce.exists(e,n))};Dt.read=function(e,t,n,r,o,s){return typeof s=="function"?Ce.read(e,t,n,r,o,s):new Promise((i,a)=>{Ce.read(e,t,n,r,o,(c,l,u)=>{if(c)return a(c);i({bytesRead:l,buffer:u})})})};Dt.write=function(e,t,...n){return typeof n[n.length-1]=="function"?Ce.write(e,t,...n):new Promise((r,o)=>{Ce.write(e,t,...n,(s,i,a)=>{if(s)return o(s);r({bytesWritten:i,buffer:a})})})};Dt.readv=function(e,t,...n){return typeof n[n.length-1]=="function"?Ce.readv(e,t,...n):new Promise((r,o)=>{Ce.readv(e,t,...n,(s,i,a)=>{if(s)return o(s);r({bytesRead:i,buffers:a})})})};Dt.writev=function(e,t,...n){return typeof n[n.length-1]=="function"?Ce.writev(e,t,...n):new Promise((r,o)=>{Ce.writev(e,t,...n,(s,i,a)=>{if(s)return o(s);r({bytesWritten:i,buffers:a})})})};typeof Ce.realpath.native=="function"?Dt.realpath.native=Mu(Ce.realpath.native):process.emitWarning("fs.realpath.native is not a function. Is fs being monkey-patched?","Warning","fs-extra-WARN0003")});var Uu=q((vI,Lu)=>{"use strict";var gk=require("path");Lu.exports.checkPath=function(t){if(process.platform==="win32"&&/[<>:"|?*]/.test(t.replace(gk.parse(t).root,""))){let r=new Error(`Path contains invalid characters: ${t}`);throw r.code="EINVAL",r}}});var Hu=q((bI,Ii)=>{"use strict";var Wu=Re(),{checkPath:Bu}=Uu(),Gu=e=>{let t={mode:511};return typeof e=="number"?e:{...t,...e}.mode};Ii.exports.makeDir=async(e,t)=>(Bu(e),Wu.mkdir(e,{mode:Gu(t),recursive:!0}));Ii.exports.makeDirSync=(e,t)=>(Bu(e),Wu.mkdirSync(e,{mode:Gu(t),recursive:!0}))});var ct=q((TI,Vu)=>{"use strict";var hk=fe().fromPromise,{makeDir:yk,makeDirSync:Oi}=Hu(),$i=hk(yk);Vu.exports={mkdirs:$i,mkdirsSync:Oi,mkdirp:$i,mkdirpSync:Oi,ensureDir:$i,ensureDirSync:Oi}});var en=q((EI,Yu)=>{"use strict";var wk=fe().fromPromise,qu=Re();function _k(e){return qu.access(e).then(()=>!0).catch(()=>!1)}Yu.exports={pathExists:wk(_k),pathExistsSync:qu.existsSync}});var Di=q((CI,Ku)=>{"use strict";var Kn=Re(),kk=fe().fromPromise;async function Sk(e,t,n){let r=await Kn.open(e,"r+"),o=null;try{await Kn.futimes(r,t,n)}finally{try{await Kn.close(r)}catch(s){o=s}}if(o)throw o}function vk(e,t,n){let r=Kn.openSync(e,"r+");return Kn.futimesSync(r,t,n),Kn.closeSync(r)}Ku.exports={utimesMillis:kk(Sk),utimesMillisSync:vk}});var kn=q((RI,Xu)=>{"use strict";var Jn=Re(),me=require("path"),Ju=fe().fromPromise;function bk(e,t,n){let r=n.dereference?o=>Jn.stat(o,{bigint:!0}):o=>Jn.lstat(o,{bigint:!0});return Promise.all([r(e),r(t).catch(o=>{if(o.code==="ENOENT")return null;throw o})]).then(([o,s])=>({srcStat:o,destStat:s}))}function Tk(e,t,n){let r,o=n.dereference?i=>Jn.statSync(i,{bigint:!0}):i=>Jn.lstatSync(i,{bigint:!0}),s=o(e);try{r=o(t)}catch(i){if(i.code==="ENOENT")return{srcStat:s,destStat:null};throw i}return{srcStat:s,destStat:r}}async function Ek(e,t,n,r){let{srcStat:o,destStat:s}=await bk(e,t,r);if(s){if(Nr(o,s)){let i=me.basename(e),a=me.basename(t);if(n==="move"&&i!==a&&i.toLowerCase()===a.toLowerCase())return{srcStat:o,destStat:s,isChangingCase:!0};throw new Error("Source and destination must not be the same.")}if(o.isDirectory()&&!s.isDirectory())throw new Error(`Cannot overwrite non-directory '${t}' with directory '${e}'.`);if(!o.isDirectory()&&s.isDirectory())throw new Error(`Cannot overwrite directory '${t}' with non-directory '${e}'.`)}if(o.isDirectory()&&Ni(e,t))throw new Error($o(e,t,n));return{srcStat:o,destStat:s}}function Ck(e,t,n,r){let{srcStat:o,destStat:s}=Tk(e,t,r);if(s){if(Nr(o,s)){let i=me.basename(e),a=me.basename(t);if(n==="move"&&i!==a&&i.toLowerCase()===a.toLowerCase())return{srcStat:o,destStat:s,isChangingCase:!0};throw new Error("Source and destination must not be the same.")}if(o.isDirectory()&&!s.isDirectory())throw new Error(`Cannot overwrite non-directory '${t}' with directory '${e}'.`);if(!o.isDirectory()&&s.isDirectory())throw new Error(`Cannot overwrite directory '${t}' with non-directory '${e}'.`)}if(o.isDirectory()&&Ni(e,t))throw new Error($o(e,t,n));return{srcStat:o,destStat:s}}async function zu(e,t,n,r){let o=me.resolve(me.dirname(e)),s=me.resolve(me.dirname(n));if(s===o||s===me.parse(s).root)return;let i;try{i=await Jn.stat(s,{bigint:!0})}catch(a){if(a.code==="ENOENT")return;throw a}if(Nr(t,i))throw new Error($o(e,n,r));return zu(e,t,s,r)}function Qu(e,t,n,r){let o=me.resolve(me.dirname(e)),s=me.resolve(me.dirname(n));if(s===o||s===me.parse(s).root)return;let i;try{i=Jn.statSync(s,{bigint:!0})}catch(a){if(a.code==="ENOENT")return;throw a}if(Nr(t,i))throw new Error($o(e,n,r));return Qu(e,t,s,r)}function Nr(e,t){return t.ino!==void 0&&t.dev!==void 0&&t.ino===e.ino&&t.dev===e.dev}function Ni(e,t){let n=me.resolve(e).split(me.sep).filter(o=>o),r=me.resolve(t).split(me.sep).filter(o=>o);return n.every((o,s)=>r[s]===o)}function $o(e,t,n){return`Cannot ${n} '${e}' to a subdirectory of itself, '${t}'.`}Xu.exports={checkPaths:Ju(Ek),checkPathsSync:Ck,checkParentPaths:Ju(zu),checkParentPathsSync:Qu,isSrcSubdir:Ni,areIdentical:Nr}});var ed=q((xI,Zu)=>{"use strict";async function Rk(e,t){let n=[];for await(let r of e)n.push(t(r).then(()=>null,o=>o??new Error("unknown error")));await Promise.all(n.map(r=>r.then(o=>{if(o!==null)throw o})))}Zu.exports={asyncIteratorConcurrentProcess:Rk}});var sd=q((PI,od)=>{"use strict";var ve=Re(),Fr=require("path"),{mkdirs:xk}=ct(),{pathExists:Pk}=en(),{utimesMillis:Ak}=Di(),jr=kn(),{asyncIteratorConcurrentProcess:Ik}=ed();async function Ok(e,t,n={}){typeof n=="function"&&(n={filter:n}),n.clobber="clobber"in n?!!n.clobber:!0,n.overwrite="overwrite"in n?!!n.overwrite:n.clobber,n.preserveTimestamps&&process.arch==="ia32"&&process.emitWarning(`Using the preserveTimestamps option in 32-bit node is not recommended;
11
11
 
12
- see https://github.com/jprichardson/node-fs-extra/issues/269`,"Warning","fs-extra-WARN0001");let{srcStat:r,destStat:o}=await jr.checkPaths(e,t,"copy",n);if(await jr.checkParentPaths(e,r,t,"copy"),!await Xu(e,t,n))return;let i=Fr.dirname(t);await E_(i)||await T_(i),await Zu(o,e,t,n)}async function Xu(e,t,n){return n.filter?n.filter(e,t):!0}async function Zu(e,t,n,r){let s=await(r.dereference?ve.stat:ve.lstat)(t);if(s.isDirectory())return A_(s,e,t,n,r);if(s.isFile()||s.isCharacterDevice()||s.isBlockDevice())return x_(s,e,t,n,r);if(s.isSymbolicLink())return O_(e,t,n,r);throw s.isSocket()?new Error(`Cannot copy a socket file: ${t}`):s.isFIFO()?new Error(`Cannot copy a FIFO pipe: ${t}`):new Error(`Unknown file: ${t}`)}async function x_(e,t,n,r,o){if(!t)return Qu(e,n,r,o);if(o.overwrite)return await ve.unlink(r),Qu(e,n,r,o);if(o.errorOnExist)throw new Error(`'${r}' already exists`)}async function Qu(e,t,n,r){if(await ve.copyFile(t,n),r.preserveTimestamps){P_(e.mode)&&await I_(n,e.mode);let o=await ve.stat(t);await b_(n,o.atime,o.mtime)}return ve.chmod(n,e.mode)}function P_(e){return(e&128)===0}function I_(e,t){return ve.chmod(e,t|128)}async function A_(e,t,n,r,o){t||await ve.mkdir(r),await C_(await ve.opendir(n),async s=>{let i=Fr.join(n,s.name),a=Fr.join(r,s.name);if(await Xu(i,a,o)){let{destStat:l}=await jr.checkPaths(i,a,"copy",o);await Zu(l,i,a,o)}}),t||await ve.chmod(r,e.mode)}async function O_(e,t,n,r){let o=await ve.readlink(t);if(r.dereference&&(o=Fr.resolve(process.cwd(),o)),!e)return ve.symlink(o,n);let s=null;try{s=await ve.readlink(n)}catch(i){if(i.code==="EINVAL"||i.code==="UNKNOWN")return ve.symlink(o,n);throw i}if(r.dereference&&(s=Fr.resolve(process.cwd(),s)),o!==s){if(jr.isSrcSubdir(o,s))throw new Error(`Cannot copy '${o}' to a subdirectory of itself, '${s}'.`);if(jr.isSrcSubdir(s,o))throw new Error(`Cannot overwrite '${s}' with '${o}'.`)}return await ve.unlink(n),ve.symlink(o,n)}ed.exports=R_});var id=q((hA,sd)=>{"use strict";var xe=Yn(),Mr=require("path"),$_=ct().mkdirsSync,D_=Oi().utimesMillisSync,Lr=_n();function N_(e,t,n){typeof n=="function"&&(n={filter:n}),n=n||{},n.clobber="clobber"in n?!!n.clobber:!0,n.overwrite="overwrite"in n?!!n.overwrite:n.clobber,n.preserveTimestamps&&process.arch==="ia32"&&process.emitWarning(`Using the preserveTimestamps option in 32-bit node is not recommended;
12
+ see https://github.com/jprichardson/node-fs-extra/issues/269`,"Warning","fs-extra-WARN0001");let{srcStat:r,destStat:o}=await jr.checkPaths(e,t,"copy",n);if(await jr.checkParentPaths(e,r,t,"copy"),!await nd(e,t,n))return;let i=Fr.dirname(t);await Pk(i)||await xk(i),await rd(o,e,t,n)}async function nd(e,t,n){return n.filter?n.filter(e,t):!0}async function rd(e,t,n,r){let s=await(r.dereference?ve.stat:ve.lstat)(t);if(s.isDirectory())return Fk(s,e,t,n,r);if(s.isFile()||s.isCharacterDevice()||s.isBlockDevice())return $k(s,e,t,n,r);if(s.isSymbolicLink())return jk(e,t,n,r);throw s.isSocket()?new Error(`Cannot copy a socket file: ${t}`):s.isFIFO()?new Error(`Cannot copy a FIFO pipe: ${t}`):new Error(`Unknown file: ${t}`)}async function $k(e,t,n,r,o){if(!t)return td(e,n,r,o);if(o.overwrite)return await ve.unlink(r),td(e,n,r,o);if(o.errorOnExist)throw new Error(`'${r}' already exists`)}async function td(e,t,n,r){if(await ve.copyFile(t,n),r.preserveTimestamps){Dk(e.mode)&&await Nk(n,e.mode);let o=await ve.stat(t);await Ak(n,o.atime,o.mtime)}return ve.chmod(n,e.mode)}function Dk(e){return(e&128)===0}function Nk(e,t){return ve.chmod(e,t|128)}async function Fk(e,t,n,r,o){t||await ve.mkdir(r),await Ik(await ve.opendir(n),async s=>{let i=Fr.join(n,s.name),a=Fr.join(r,s.name);if(await nd(i,a,o)){let{destStat:l}=await jr.checkPaths(i,a,"copy",o);await rd(l,i,a,o)}}),t||await ve.chmod(r,e.mode)}async function jk(e,t,n,r){let o=await ve.readlink(t);if(r.dereference&&(o=Fr.resolve(process.cwd(),o)),!e)return ve.symlink(o,n);let s=null;try{s=await ve.readlink(n)}catch(i){if(i.code==="EINVAL"||i.code==="UNKNOWN")return ve.symlink(o,n);throw i}if(r.dereference&&(s=Fr.resolve(process.cwd(),s)),o!==s){if(jr.isSrcSubdir(o,s))throw new Error(`Cannot copy '${o}' to a subdirectory of itself, '${s}'.`);if(jr.isSrcSubdir(s,o))throw new Error(`Cannot overwrite '${s}' with '${o}'.`)}return await ve.unlink(n),ve.symlink(o,n)}od.exports=Ok});var ud=q((AI,ld)=>{"use strict";var xe=Yn(),Mr=require("path"),Mk=ct().mkdirsSync,Lk=Di().utimesMillisSync,Lr=kn();function Uk(e,t,n){typeof n=="function"&&(n={filter:n}),n=n||{},n.clobber="clobber"in n?!!n.clobber:!0,n.overwrite="overwrite"in n?!!n.overwrite:n.clobber,n.preserveTimestamps&&process.arch==="ia32"&&process.emitWarning(`Using the preserveTimestamps option in 32-bit node is not recommended;
13
13
 
14
- see https://github.com/jprichardson/node-fs-extra/issues/269`,"Warning","fs-extra-WARN0002");let{srcStat:r,destStat:o}=Lr.checkPathsSync(e,t,"copy",n);if(Lr.checkParentPathsSync(e,r,t,"copy"),n.filter&&!n.filter(e,t))return;let s=Mr.dirname(t);return xe.existsSync(s)||$_(s),nd(o,e,t,n)}function nd(e,t,n,r){let s=(r.dereference?xe.statSync:xe.lstatSync)(t);if(s.isDirectory())return G_(s,e,t,n,r);if(s.isFile()||s.isCharacterDevice()||s.isBlockDevice())return F_(s,e,t,n,r);if(s.isSymbolicLink())return V_(e,t,n,r);throw s.isSocket()?new Error(`Cannot copy a socket file: ${t}`):s.isFIFO()?new Error(`Cannot copy a FIFO pipe: ${t}`):new Error(`Unknown file: ${t}`)}function F_(e,t,n,r,o){return t?j_(e,n,r,o):rd(e,n,r,o)}function j_(e,t,n,r){if(r.overwrite)return xe.unlinkSync(n),rd(e,t,n,r);if(r.errorOnExist)throw new Error(`'${n}' already exists`)}function rd(e,t,n,r){return xe.copyFileSync(t,n),r.preserveTimestamps&&M_(e.mode,t,n),Di(n,e.mode)}function M_(e,t,n){return L_(e)&&U_(n,e),W_(t,n)}function L_(e){return(e&128)===0}function U_(e,t){return Di(e,t|128)}function Di(e,t){return xe.chmodSync(e,t)}function W_(e,t){let n=xe.statSync(e);return D_(t,n.atime,n.mtime)}function G_(e,t,n,r,o){return t?od(n,r,o):B_(e.mode,n,r,o)}function B_(e,t,n,r){return xe.mkdirSync(n),od(t,n,r),Di(n,e)}function od(e,t,n){let r=xe.opendirSync(e);try{let o;for(;(o=r.readSync())!==null;)H_(o.name,e,t,n)}finally{r.closeSync()}}function H_(e,t,n,r){let o=Mr.join(t,e),s=Mr.join(n,e);if(r.filter&&!r.filter(o,s))return;let{destStat:i}=Lr.checkPathsSync(o,s,"copy",r);return nd(i,o,s,r)}function V_(e,t,n,r){let o=xe.readlinkSync(t);if(r.dereference&&(o=Mr.resolve(process.cwd(),o)),e){let s;try{s=xe.readlinkSync(n)}catch(i){if(i.code==="EINVAL"||i.code==="UNKNOWN")return xe.symlinkSync(o,n);throw i}if(r.dereference&&(s=Mr.resolve(process.cwd(),s)),o!==s){if(Lr.isSrcSubdir(o,s))throw new Error(`Cannot copy '${o}' to a subdirectory of itself, '${s}'.`);if(Lr.isSrcSubdir(s,o))throw new Error(`Cannot overwrite '${s}' with '${o}'.`)}return q_(o,n)}else return xe.symlinkSync(o,n)}function q_(e,t){return xe.unlinkSync(t),xe.symlinkSync(e,t)}sd.exports=N_});var Do=q((yA,ad)=>{"use strict";var Y_=pe().fromPromise;ad.exports={copy:Y_(td()),copySync:id()}});var Ur=q((wA,ld)=>{"use strict";var cd=Yn(),K_=pe().fromCallback;function J_(e,t){cd.rm(e,{recursive:!0,force:!0},t)}function z_(e){cd.rmSync(e,{recursive:!0,force:!0})}ld.exports={remove:K_(J_),removeSync:z_}});var yd=q((kA,hd)=>{"use strict";var Q_=pe().fromPromise,pd=Re(),fd=require("path"),md=ct(),gd=Ur(),ud=Q_(async function(t){let n;try{n=await pd.readdir(t)}catch{return md.mkdirs(t)}return Promise.all(n.map(r=>gd.remove(fd.join(t,r))))});function dd(e){let t;try{t=pd.readdirSync(e)}catch{return md.mkdirsSync(e)}t.forEach(n=>{n=fd.join(e,n),gd.removeSync(n)})}hd.exports={emptyDirSync:dd,emptydirSync:dd,emptyDir:ud,emptydir:ud}});var Sd=q((_A,_d)=>{"use strict";var X_=pe().fromPromise,wd=require("path"),Nt=Re(),kd=ct();async function Z_(e){let t;try{t=await Nt.stat(e)}catch{}if(t&&t.isFile())return;let n=wd.dirname(e),r=null;try{r=await Nt.stat(n)}catch(o){if(o.code==="ENOENT"){await kd.mkdirs(n),await Nt.writeFile(e,"");return}else throw o}r.isDirectory()?await Nt.writeFile(e,""):await Nt.readdir(n)}function eS(e){let t;try{t=Nt.statSync(e)}catch{}if(t&&t.isFile())return;let n=wd.dirname(e);try{Nt.statSync(n).isDirectory()||Nt.readdirSync(n)}catch(r){if(r&&r.code==="ENOENT")kd.mkdirsSync(n);else throw r}Nt.writeFileSync(e,"")}_d.exports={createFile:X_(Z_),createFileSync:eS}});var Cd=q((SA,bd)=>{"use strict";var tS=pe().fromPromise,vd=require("path"),tn=Re(),Td=ct(),{pathExists:nS}=en(),{areIdentical:Ed}=_n();async function rS(e,t){let n;try{n=await tn.lstat(t)}catch{}let r;try{r=await tn.lstat(e)}catch(i){throw i.message=i.message.replace("lstat","ensureLink"),i}if(n&&Ed(r,n))return;let o=vd.dirname(t);await nS(o)||await Td.mkdirs(o),await tn.link(e,t)}function oS(e,t){let n;try{n=tn.lstatSync(t)}catch{}try{let s=tn.lstatSync(e);if(n&&Ed(s,n))return}catch(s){throw s.message=s.message.replace("lstat","ensureLink"),s}let r=vd.dirname(t);return tn.existsSync(r)||Td.mkdirsSync(r),tn.linkSync(e,t)}bd.exports={createLink:tS(rS),createLinkSync:oS}});var xd=q((vA,Rd)=>{"use strict";var nn=require("path"),Wr=Re(),{pathExists:sS}=en(),iS=pe().fromPromise;async function aS(e,t){if(nn.isAbsolute(e)){try{await Wr.lstat(e)}catch(s){throw s.message=s.message.replace("lstat","ensureSymlink"),s}return{toCwd:e,toDst:e}}let n=nn.dirname(t),r=nn.join(n,e);if(await sS(r))return{toCwd:r,toDst:e};try{await Wr.lstat(e)}catch(s){throw s.message=s.message.replace("lstat","ensureSymlink"),s}return{toCwd:e,toDst:nn.relative(n,e)}}function cS(e,t){if(nn.isAbsolute(e)){if(!Wr.existsSync(e))throw new Error("absolute srcpath does not exist");return{toCwd:e,toDst:e}}let n=nn.dirname(t),r=nn.join(n,e);if(Wr.existsSync(r))return{toCwd:r,toDst:e};if(!Wr.existsSync(e))throw new Error("relative srcpath does not exist");return{toCwd:e,toDst:nn.relative(n,e)}}Rd.exports={symlinkPaths:iS(aS),symlinkPathsSync:cS}});var Ad=q((TA,Id)=>{"use strict";var Pd=Re(),lS=pe().fromPromise;async function uS(e,t){if(t)return t;let n;try{n=await Pd.lstat(e)}catch{return"file"}return n&&n.isDirectory()?"dir":"file"}function dS(e,t){if(t)return t;let n;try{n=Pd.lstatSync(e)}catch{return"file"}return n&&n.isDirectory()?"dir":"file"}Id.exports={symlinkType:lS(uS),symlinkTypeSync:dS}});var Nd=q((EA,Dd)=>{"use strict";var pS=pe().fromPromise,Od=require("path"),_t=Re(),{mkdirs:fS,mkdirsSync:mS}=ct(),{symlinkPaths:gS,symlinkPathsSync:hS}=xd(),{symlinkType:yS,symlinkTypeSync:wS}=Ad(),{pathExists:kS}=en(),{areIdentical:$d}=_n();async function _S(e,t,n){let r;try{r=await _t.lstat(t)}catch{}if(r&&r.isSymbolicLink()){let[a,c]=await Promise.all([_t.stat(e),_t.stat(t)]);if($d(a,c))return}let o=await gS(e,t);e=o.toDst;let s=await yS(o.toCwd,n),i=Od.dirname(t);return await kS(i)||await fS(i),_t.symlink(e,t,s)}function SS(e,t,n){let r;try{r=_t.lstatSync(t)}catch{}if(r&&r.isSymbolicLink()){let a=_t.statSync(e),c=_t.statSync(t);if($d(a,c))return}let o=hS(e,t);e=o.toDst,n=wS(o.toCwd,n);let s=Od.dirname(t);return _t.existsSync(s)||mS(s),_t.symlinkSync(e,t,n)}Dd.exports={createSymlink:pS(_S),createSymlinkSync:SS}});var Bd=q((bA,Gd)=>{"use strict";var{createFile:Fd,createFileSync:jd}=Sd(),{createLink:Md,createLinkSync:Ld}=Cd(),{createSymlink:Ud,createSymlinkSync:Wd}=Nd();Gd.exports={createFile:Fd,createFileSync:jd,ensureFile:Fd,ensureFileSync:jd,createLink:Md,createLinkSync:Ld,ensureLink:Md,ensureLinkSync:Ld,createSymlink:Ud,createSymlinkSync:Wd,ensureSymlink:Ud,ensureSymlinkSync:Wd}});var No=q((CA,Hd)=>{function vS(e,{EOL:t=`
15
- `,finalEOL:n=!0,replacer:r=null,spaces:o}={}){let s=n?t:"";return JSON.stringify(e,r,o).replace(/\n/g,t)+s}function TS(e){return Buffer.isBuffer(e)&&(e=e.toString("utf8")),e.replace(/^\uFEFF/,"")}Hd.exports={stringify:vS,stripBom:TS}});var Kd=q((RA,Yd)=>{var zn;try{zn=Yn()}catch{zn=require("fs")}var Fo=pe(),{stringify:Vd,stripBom:qd}=No();async function ES(e,t={}){typeof t=="string"&&(t={encoding:t});let n=t.fs||zn,r="throws"in t?t.throws:!0,o=await Fo.fromCallback(n.readFile)(e,t);o=qd(o);let s;try{s=JSON.parse(o,t?t.reviver:null)}catch(i){if(r)throw i.message=`${e}: ${i.message}`,i;return null}return s}var bS=Fo.fromPromise(ES);function CS(e,t={}){typeof t=="string"&&(t={encoding:t});let n=t.fs||zn,r="throws"in t?t.throws:!0;try{let o=n.readFileSync(e,t);return o=qd(o),JSON.parse(o,t.reviver)}catch(o){if(r)throw o.message=`${e}: ${o.message}`,o;return null}}async function RS(e,t,n={}){let r=n.fs||zn,o=Vd(t,n);await Fo.fromCallback(r.writeFile)(e,o,n)}var xS=Fo.fromPromise(RS);function PS(e,t,n={}){let r=n.fs||zn,o=Vd(t,n);return r.writeFileSync(e,o,n)}Yd.exports={readFile:bS,readFileSync:CS,writeFile:xS,writeFileSync:PS}});var zd=q((xA,Jd)=>{"use strict";var jo=Kd();Jd.exports={readJson:jo.readFile,readJsonSync:jo.readFileSync,writeJson:jo.writeFile,writeJsonSync:jo.writeFileSync}});var Mo=q((PA,Zd)=>{"use strict";var IS=pe().fromPromise,Ni=Re(),Qd=require("path"),Xd=ct(),AS=en().pathExists;async function OS(e,t,n="utf-8"){let r=Qd.dirname(e);return await AS(r)||await Xd.mkdirs(r),Ni.writeFile(e,t,n)}function $S(e,...t){let n=Qd.dirname(e);Ni.existsSync(n)||Xd.mkdirsSync(n),Ni.writeFileSync(e,...t)}Zd.exports={outputFile:IS(OS),outputFileSync:$S}});var tp=q((IA,ep)=>{"use strict";var{stringify:DS}=No(),{outputFile:NS}=Mo();async function FS(e,t,n={}){let r=DS(t,n);await NS(e,r,n)}ep.exports=FS});var rp=q((AA,np)=>{"use strict";var{stringify:jS}=No(),{outputFileSync:MS}=Mo();function LS(e,t,n){let r=jS(t,n);MS(e,r,n)}np.exports=LS});var sp=q((OA,op)=>{"use strict";var US=pe().fromPromise,Pe=zd();Pe.outputJson=US(tp());Pe.outputJsonSync=rp();Pe.outputJSON=Pe.outputJson;Pe.outputJSONSync=Pe.outputJsonSync;Pe.writeJSON=Pe.writeJson;Pe.writeJSONSync=Pe.writeJsonSync;Pe.readJSON=Pe.readJson;Pe.readJSONSync=Pe.readJsonSync;op.exports=Pe});var up=q(($A,lp)=>{"use strict";var WS=Re(),ip=require("path"),{copy:GS}=Do(),{remove:cp}=Ur(),{mkdirp:BS}=ct(),{pathExists:HS}=en(),ap=_n();async function VS(e,t,n={}){let r=n.overwrite||n.clobber||!1,{srcStat:o,isChangingCase:s=!1}=await ap.checkPaths(e,t,"move",n);await ap.checkParentPaths(e,o,t,"move");let i=ip.dirname(t);return ip.parse(i).root!==i&&await BS(i),qS(e,t,r,s)}async function qS(e,t,n,r){if(!r){if(n)await cp(t);else if(await HS(t))throw new Error("dest already exists.")}try{await WS.rename(e,t)}catch(o){if(o.code!=="EXDEV")throw o;await YS(e,t,n)}}async function YS(e,t,n){return await GS(e,t,{overwrite:n,errorOnExist:!0,preserveTimestamps:!0}),cp(e)}lp.exports=VS});var gp=q((DA,mp)=>{"use strict";var pp=Yn(),ji=require("path"),KS=Do().copySync,fp=Ur().removeSync,JS=ct().mkdirpSync,dp=_n();function zS(e,t,n){n=n||{};let r=n.overwrite||n.clobber||!1,{srcStat:o,isChangingCase:s=!1}=dp.checkPathsSync(e,t,"move",n);return dp.checkParentPathsSync(e,o,t,"move"),QS(t)||JS(ji.dirname(t)),XS(e,t,r,s)}function QS(e){let t=ji.dirname(e);return ji.parse(t).root===t}function XS(e,t,n,r){if(r)return Fi(e,t,n);if(n)return fp(t),Fi(e,t,n);if(pp.existsSync(t))throw new Error("dest already exists.");return Fi(e,t,n)}function Fi(e,t,n){try{pp.renameSync(e,t)}catch(r){if(r.code!=="EXDEV")throw r;return ZS(e,t,n)}}function ZS(e,t,n){return KS(e,t,{overwrite:n,errorOnExist:!0,preserveTimestamps:!0}),fp(e)}mp.exports=zS});var yp=q((NA,hp)=>{"use strict";var ev=pe().fromPromise;hp.exports={move:ev(up()),moveSync:gp()}});var X=q((FA,wp)=>{"use strict";wp.exports={...Re(),...Do(),...yd(),...Bd(),...sp(),...ct(),...yp(),...Mo(),...en(),...Ur()}});var _p={};he(_p,{archiveWorkflow:()=>Li,clearCache:()=>rv,deleteWorkflow:()=>ov,findActiveWorkflow:()=>sv,invalidateCache:()=>Ft,listWorkflows:()=>oe,loadCheckpoint:()=>I,saveCheckpoint:()=>O});function Mi(e,t){return`${e}:${t}`}function nv(e){return Date.now()-e.timestamp<tv}function kp(e){if(e.current_stage==="idea"&&(e.current_stage="intent"),!(!e.construction_units||Array.isArray(e.construction_units)))for(let t of Object.values(e.construction_units)){if(t.stages||(t.stages={}),!t.stages["test-generation"]){let n=t.code_generation_status==="completed";t.stages["test-generation"]={status:n?"skipped":"not_started",artifact_path:null,completed_at:null}}t.quality_validation_status===void 0&&(t.quality_validation_status="not_started"),t.mutation_validation_status===void 0&&(t.mutation_validation_status="not_started"),t.traceability_status===void 0&&(t.traceability_status="not_started"),t.contract_validation_status===void 0&&(t.contract_validation_status="not_started"),t.coverage_status===void 0&&(t.coverage_status="not_started"),t.coverage_percentage===void 0&&(t.coverage_percentage=null),t.critical_gap_count===void 0&&(t.critical_gap_count=0),t.security_scan_status===void 0&&(t.security_scan_status="not_started"),t.security_findings_critical===void 0&&(t.security_findings_critical=0),t.security_findings_warning===void 0&&(t.security_findings_warning=0),t.security_findings_info===void 0&&(t.security_findings_info=0),t.feature_doc_status===void 0&&(t.feature_doc_status="not_started"),t.feature_doc_path===void 0&&(t.feature_doc_path=null),t.recreation_readiness_score===void 0&&(t.recreation_readiness_score=null),t.recreation_readiness_dimensions===void 0&&(t.recreation_readiness_dimensions=null),t.adr_count===void 0&&(t.adr_count=0),t.impact_scan_status===void 0&&(t.impact_scan_status="not_started")}}function rv(){Gr.clear()}function Ft(e,t){let n=Mi(e,t);Gr.delete(n)}async function O(e,t){let n=(0,Be.join)(e,St,t.workflow_id),r=(0,Be.join)(n,Br);try{if(t.updated_at=new Date().toISOString(),t.schema_version="3.0.0",await re.default.ensureDir(n),JSON.stringify(t).length>1e4){let a=JSON.stringify(t);await re.default.writeFile(r,a,"utf-8")}else await re.default.writeJson(r,t,{spaces:2});let i=Mi(e,t.workflow_id);Gr.set(i,{checkpoint:structuredClone(t),timestamp:Date.now(),dirty:!1})}catch(o){let s=o;throw s.code==="ENOSPC"?(console.error("[Checkpoint] Failed to save checkpoint: Disk full"),console.error("[Checkpoint] Please free up disk space and try again."),console.error(`[Checkpoint] Attempted path: ${r}`),new Error("Failed to save checkpoint: Disk is full. Please free up space and retry.")):s.code==="EACCES"||s.code==="EPERM"?(console.error("[Checkpoint] Failed to save checkpoint: Permission denied"),console.error(`[Checkpoint] Path: ${r}`),new Error(`Failed to save checkpoint: Permission denied for ${r}`)):s.code==="EROFS"?(console.error("[Checkpoint] Failed to save checkpoint: Read-only filesystem"),console.error(`[Checkpoint] Path: ${r}`),new Error("Failed to save checkpoint: Filesystem is read-only")):(console.error("[Checkpoint] Failed to save checkpoint:",s.message),console.error(`[Checkpoint] Workflow ID: ${t.workflow_id}`),console.error(`[Checkpoint] Path: ${r}`),new Error(`Failed to save checkpoint for workflow ${t.workflow_id}: ${s.message}`))}}async function I(e,t){let n=Mi(e,t),r=Gr.get(n);if(r&&nv(r)){let s=structuredClone(r.checkpoint);return kp(s),s}let o=(0,Be.join)(e,St,t,Br);try{let s=await re.default.readFile(o,"utf-8"),i=JSON.parse(s);return i.schema_version?i.schema_version!=="3.0.0"?(console.warn(`[Checkpoint] Unknown checkpoint schema version ${i.schema_version} for workflow ${t}`),console.warn("[Checkpoint] Expected 3.0.0"),null):(i.current_stage==="idea"&&console.warn(`[Checkpoint] Migrating legacy 'idea' stage to 'intent' for workflow ${t}`),kp(i),Gr.set(n,{checkpoint:structuredClone(i),timestamp:Date.now(),dirty:!1}),i):(console.warn(`[Checkpoint] Checkpoint ${t} missing schema_version, treating as invalid`),console.warn("[Checkpoint] Checkpoint may be corrupt or from an older version"),console.warn(`[Checkpoint] Consider deleting: ${o}`),null)}catch(s){let i=s,a=i;return a.code==="ENOENT"?null:i.name==="SyntaxError"||i.message.includes("JSON")?(console.warn(`[Checkpoint] Corrupt checkpoint detected for workflow ${t}`),console.warn(`[Checkpoint] Path: ${o}`),console.warn(`[Checkpoint] Error: ${i.message}`),console.warn("[Checkpoint] To reset this workflow, delete the checkpoint file and start over"),null):a.code==="EACCES"||a.code==="EPERM"?(console.warn(`[Checkpoint] Permission denied reading checkpoint ${t}`),console.warn(`[Checkpoint] Path: ${o}`),null):(console.warn(`[Checkpoint] Failed to load checkpoint ${t}: ${i.message}`),console.warn(`[Checkpoint] Path: ${o}`),null)}}async function oe(e){let t=(0,Be.join)(e,St);try{if(!await re.default.pathExists(t))return[];let r=await re.default.readdir(t,{withFileTypes:!0}),o=[];for(let s of r){if(!s.isDirectory()||s.name==="completed")continue;let i=(0,Be.join)(t,s.name,Br);if(await re.default.pathExists(i))try{let a=await re.default.readFile(i,"utf-8"),c=JSON.parse(a);c.workflow_id&&o.push(c.workflow_id)}catch{}}return o}catch(n){let r=n;return r.code==="EACCES"||r.code==="EPERM"?console.warn(`[Checkpoint] Permission denied reading ${t}`):console.warn(`[Checkpoint] Failed to list workflows: ${r.message}`),[]}}async function ov(e,t){let n=(0,Be.join)(e,St,t);try{await re.default.remove(n)}catch(r){let o=r;if(o.code==="ENOENT")return;if(o.code==="EACCES"||o.code==="EPERM"){console.warn(`[Checkpoint] Permission denied deleting workflow ${t}`),console.warn(`[Checkpoint] Path: ${n}`),console.warn("[Checkpoint] Manual deletion may be required");return}console.warn(`[Checkpoint] Failed to delete workflow ${t}: ${o.message}`),console.warn(`[Checkpoint] Path: ${n}`)}}async function Li(e,t){let n=await I(e,t);if(!n||n.status!=="complete")return;let r=(0,Be.join)(e,St,t),o=(0,Be.join)(e,St,"completed",t),s=(0,Be.join)(o,Br);if(await re.default.pathExists(s))try{let i=await re.default.readFile(s,"utf-8");if(JSON.parse(i).workflow_id===t){console.log(`[Checkpoint] Workflow ${t} already archived at ${o}`);return}}catch{await re.default.remove(o)}else await re.default.pathExists(o)&&await re.default.remove(o);n.archived_at=new Date().toISOString(),n.archived_path=`${St}/completed/${t}`,await O(e,n);try{await re.default.move(r,o,{overwrite:!1}),Ft(e,t),console.log(`[Checkpoint] Workflow archived to ${St}/completed/${t}/`)}catch(i){let a=i,c=a.code==="EBUSY"&&process.platform==="win32"?" \u2014 try closing open files in the workflow directory":"";console.warn(`[Checkpoint] Failed to move workflow folder (non-fatal): ${a.message}${c}`)}try{let i=(0,Be.join)(e,".olympus","plans",`${t}-plan.md`);if(await re.default.pathExists(i)){let a=`
14
+ see https://github.com/jprichardson/node-fs-extra/issues/269`,"Warning","fs-extra-WARN0002");let{srcStat:r,destStat:o}=Lr.checkPathsSync(e,t,"copy",n);if(Lr.checkParentPathsSync(e,r,t,"copy"),n.filter&&!n.filter(e,t))return;let s=Mr.dirname(t);return xe.existsSync(s)||Mk(s),id(o,e,t,n)}function id(e,t,n,r){let s=(r.dereference?xe.statSync:xe.lstatSync)(t);if(s.isDirectory())return Yk(s,e,t,n,r);if(s.isFile()||s.isCharacterDevice()||s.isBlockDevice())return Wk(s,e,t,n,r);if(s.isSymbolicLink())return zk(e,t,n,r);throw s.isSocket()?new Error(`Cannot copy a socket file: ${t}`):s.isFIFO()?new Error(`Cannot copy a FIFO pipe: ${t}`):new Error(`Unknown file: ${t}`)}function Wk(e,t,n,r,o){return t?Bk(e,n,r,o):ad(e,n,r,o)}function Bk(e,t,n,r){if(r.overwrite)return xe.unlinkSync(n),ad(e,t,n,r);if(r.errorOnExist)throw new Error(`'${n}' already exists`)}function ad(e,t,n,r){return xe.copyFileSync(t,n),r.preserveTimestamps&&Gk(e.mode,t,n),Fi(n,e.mode)}function Gk(e,t,n){return Hk(e)&&Vk(n,e),qk(t,n)}function Hk(e){return(e&128)===0}function Vk(e,t){return Fi(e,t|128)}function Fi(e,t){return xe.chmodSync(e,t)}function qk(e,t){let n=xe.statSync(e);return Lk(t,n.atime,n.mtime)}function Yk(e,t,n,r,o){return t?cd(n,r,o):Kk(e.mode,n,r,o)}function Kk(e,t,n,r){return xe.mkdirSync(n),cd(t,n,r),Fi(n,e)}function cd(e,t,n){let r=xe.opendirSync(e);try{let o;for(;(o=r.readSync())!==null;)Jk(o.name,e,t,n)}finally{r.closeSync()}}function Jk(e,t,n,r){let o=Mr.join(t,e),s=Mr.join(n,e);if(r.filter&&!r.filter(o,s))return;let{destStat:i}=Lr.checkPathsSync(o,s,"copy",r);return id(i,o,s,r)}function zk(e,t,n,r){let o=xe.readlinkSync(t);if(r.dereference&&(o=Mr.resolve(process.cwd(),o)),e){let s;try{s=xe.readlinkSync(n)}catch(i){if(i.code==="EINVAL"||i.code==="UNKNOWN")return xe.symlinkSync(o,n);throw i}if(r.dereference&&(s=Mr.resolve(process.cwd(),s)),o!==s){if(Lr.isSrcSubdir(o,s))throw new Error(`Cannot copy '${o}' to a subdirectory of itself, '${s}'.`);if(Lr.isSrcSubdir(s,o))throw new Error(`Cannot overwrite '${s}' with '${o}'.`)}return Qk(o,n)}else return xe.symlinkSync(o,n)}function Qk(e,t){return xe.unlinkSync(t),xe.symlinkSync(e,t)}ld.exports=Uk});var Do=q((II,dd)=>{"use strict";var Xk=fe().fromPromise;dd.exports={copy:Xk(sd()),copySync:ud()}});var Ur=q((OI,fd)=>{"use strict";var pd=Yn(),Zk=fe().fromCallback;function eS(e,t){pd.rm(e,{recursive:!0,force:!0},t)}function tS(e){pd.rmSync(e,{recursive:!0,force:!0})}fd.exports={remove:Zk(eS),removeSync:tS}});var Sd=q(($I,kd)=>{"use strict";var nS=fe().fromPromise,hd=Re(),yd=require("path"),wd=ct(),_d=Ur(),md=nS(async function(t){let n;try{n=await hd.readdir(t)}catch{return wd.mkdirs(t)}return Promise.all(n.map(r=>_d.remove(yd.join(t,r))))});function gd(e){let t;try{t=hd.readdirSync(e)}catch{return wd.mkdirsSync(e)}t.forEach(n=>{n=yd.join(e,n),_d.removeSync(n)})}kd.exports={emptyDirSync:gd,emptydirSync:gd,emptyDir:md,emptydir:md}});var Ed=q((DI,Td)=>{"use strict";var rS=fe().fromPromise,vd=require("path"),Nt=Re(),bd=ct();async function oS(e){let t;try{t=await Nt.stat(e)}catch{}if(t&&t.isFile())return;let n=vd.dirname(e),r=null;try{r=await Nt.stat(n)}catch(o){if(o.code==="ENOENT"){await bd.mkdirs(n),await Nt.writeFile(e,"");return}else throw o}r.isDirectory()?await Nt.writeFile(e,""):await Nt.readdir(n)}function sS(e){let t;try{t=Nt.statSync(e)}catch{}if(t&&t.isFile())return;let n=vd.dirname(e);try{Nt.statSync(n).isDirectory()||Nt.readdirSync(n)}catch(r){if(r&&r.code==="ENOENT")bd.mkdirsSync(n);else throw r}Nt.writeFileSync(e,"")}Td.exports={createFile:rS(oS),createFileSync:sS}});var Ad=q((NI,Pd)=>{"use strict";var iS=fe().fromPromise,Cd=require("path"),tn=Re(),Rd=ct(),{pathExists:aS}=en(),{areIdentical:xd}=kn();async function cS(e,t){let n;try{n=await tn.lstat(t)}catch{}let r;try{r=await tn.lstat(e)}catch(i){throw i.message=i.message.replace("lstat","ensureLink"),i}if(n&&xd(r,n))return;let o=Cd.dirname(t);await aS(o)||await Rd.mkdirs(o),await tn.link(e,t)}function lS(e,t){let n;try{n=tn.lstatSync(t)}catch{}try{let s=tn.lstatSync(e);if(n&&xd(s,n))return}catch(s){throw s.message=s.message.replace("lstat","ensureLink"),s}let r=Cd.dirname(t);return tn.existsSync(r)||Rd.mkdirsSync(r),tn.linkSync(e,t)}Pd.exports={createLink:iS(cS),createLinkSync:lS}});var Od=q((FI,Id)=>{"use strict";var nn=require("path"),Wr=Re(),{pathExists:uS}=en(),dS=fe().fromPromise;async function pS(e,t){if(nn.isAbsolute(e)){try{await Wr.lstat(e)}catch(s){throw s.message=s.message.replace("lstat","ensureSymlink"),s}return{toCwd:e,toDst:e}}let n=nn.dirname(t),r=nn.join(n,e);if(await uS(r))return{toCwd:r,toDst:e};try{await Wr.lstat(e)}catch(s){throw s.message=s.message.replace("lstat","ensureSymlink"),s}return{toCwd:e,toDst:nn.relative(n,e)}}function fS(e,t){if(nn.isAbsolute(e)){if(!Wr.existsSync(e))throw new Error("absolute srcpath does not exist");return{toCwd:e,toDst:e}}let n=nn.dirname(t),r=nn.join(n,e);if(Wr.existsSync(r))return{toCwd:r,toDst:e};if(!Wr.existsSync(e))throw new Error("relative srcpath does not exist");return{toCwd:e,toDst:nn.relative(n,e)}}Id.exports={symlinkPaths:dS(pS),symlinkPathsSync:fS}});var Nd=q((jI,Dd)=>{"use strict";var $d=Re(),mS=fe().fromPromise;async function gS(e,t){if(t)return t;let n;try{n=await $d.lstat(e)}catch{return"file"}return n&&n.isDirectory()?"dir":"file"}function hS(e,t){if(t)return t;let n;try{n=$d.lstatSync(e)}catch{return"file"}return n&&n.isDirectory()?"dir":"file"}Dd.exports={symlinkType:mS(gS),symlinkTypeSync:hS}});var Ld=q((MI,Md)=>{"use strict";var yS=fe().fromPromise,Fd=require("path"),kt=Re(),{mkdirs:wS,mkdirsSync:_S}=ct(),{symlinkPaths:kS,symlinkPathsSync:SS}=Od(),{symlinkType:vS,symlinkTypeSync:bS}=Nd(),{pathExists:TS}=en(),{areIdentical:jd}=kn();async function ES(e,t,n){let r;try{r=await kt.lstat(t)}catch{}if(r&&r.isSymbolicLink()){let[a,c]=await Promise.all([kt.stat(e),kt.stat(t)]);if(jd(a,c))return}let o=await kS(e,t);e=o.toDst;let s=await vS(o.toCwd,n),i=Fd.dirname(t);return await TS(i)||await wS(i),kt.symlink(e,t,s)}function CS(e,t,n){let r;try{r=kt.lstatSync(t)}catch{}if(r&&r.isSymbolicLink()){let a=kt.statSync(e),c=kt.statSync(t);if(jd(a,c))return}let o=SS(e,t);e=o.toDst,n=bS(o.toCwd,n);let s=Fd.dirname(t);return kt.existsSync(s)||_S(s),kt.symlinkSync(e,t,n)}Md.exports={createSymlink:yS(ES),createSymlinkSync:CS}});var Yd=q((LI,qd)=>{"use strict";var{createFile:Ud,createFileSync:Wd}=Ed(),{createLink:Bd,createLinkSync:Gd}=Ad(),{createSymlink:Hd,createSymlinkSync:Vd}=Ld();qd.exports={createFile:Ud,createFileSync:Wd,ensureFile:Ud,ensureFileSync:Wd,createLink:Bd,createLinkSync:Gd,ensureLink:Bd,ensureLinkSync:Gd,createSymlink:Hd,createSymlinkSync:Vd,ensureSymlink:Hd,ensureSymlinkSync:Vd}});var No=q((UI,Kd)=>{function RS(e,{EOL:t=`
15
+ `,finalEOL:n=!0,replacer:r=null,spaces:o}={}){let s=n?t:"";return JSON.stringify(e,r,o).replace(/\n/g,t)+s}function xS(e){return Buffer.isBuffer(e)&&(e=e.toString("utf8")),e.replace(/^\uFEFF/,"")}Kd.exports={stringify:RS,stripBom:xS}});var Xd=q((WI,Qd)=>{var zn;try{zn=Yn()}catch{zn=require("fs")}var Fo=fe(),{stringify:Jd,stripBom:zd}=No();async function PS(e,t={}){typeof t=="string"&&(t={encoding:t});let n=t.fs||zn,r="throws"in t?t.throws:!0,o=await Fo.fromCallback(n.readFile)(e,t);o=zd(o);let s;try{s=JSON.parse(o,t?t.reviver:null)}catch(i){if(r)throw i.message=`${e}: ${i.message}`,i;return null}return s}var AS=Fo.fromPromise(PS);function IS(e,t={}){typeof t=="string"&&(t={encoding:t});let n=t.fs||zn,r="throws"in t?t.throws:!0;try{let o=n.readFileSync(e,t);return o=zd(o),JSON.parse(o,t.reviver)}catch(o){if(r)throw o.message=`${e}: ${o.message}`,o;return null}}async function OS(e,t,n={}){let r=n.fs||zn,o=Jd(t,n);await Fo.fromCallback(r.writeFile)(e,o,n)}var $S=Fo.fromPromise(OS);function DS(e,t,n={}){let r=n.fs||zn,o=Jd(t,n);return r.writeFileSync(e,o,n)}Qd.exports={readFile:AS,readFileSync:IS,writeFile:$S,writeFileSync:DS}});var ep=q((BI,Zd)=>{"use strict";var jo=Xd();Zd.exports={readJson:jo.readFile,readJsonSync:jo.readFileSync,writeJson:jo.writeFile,writeJsonSync:jo.writeFileSync}});var Mo=q((GI,rp)=>{"use strict";var NS=fe().fromPromise,ji=Re(),tp=require("path"),np=ct(),FS=en().pathExists;async function jS(e,t,n="utf-8"){let r=tp.dirname(e);return await FS(r)||await np.mkdirs(r),ji.writeFile(e,t,n)}function MS(e,...t){let n=tp.dirname(e);ji.existsSync(n)||np.mkdirsSync(n),ji.writeFileSync(e,...t)}rp.exports={outputFile:NS(jS),outputFileSync:MS}});var sp=q((HI,op)=>{"use strict";var{stringify:LS}=No(),{outputFile:US}=Mo();async function WS(e,t,n={}){let r=LS(t,n);await US(e,r,n)}op.exports=WS});var ap=q((VI,ip)=>{"use strict";var{stringify:BS}=No(),{outputFileSync:GS}=Mo();function HS(e,t,n){let r=BS(t,n);GS(e,r,n)}ip.exports=HS});var lp=q((qI,cp)=>{"use strict";var VS=fe().fromPromise,Pe=ep();Pe.outputJson=VS(sp());Pe.outputJsonSync=ap();Pe.outputJSON=Pe.outputJson;Pe.outputJSONSync=Pe.outputJsonSync;Pe.writeJSON=Pe.writeJson;Pe.writeJSONSync=Pe.writeJsonSync;Pe.readJSON=Pe.readJson;Pe.readJSONSync=Pe.readJsonSync;cp.exports=Pe});var mp=q((YI,fp)=>{"use strict";var qS=Re(),up=require("path"),{copy:YS}=Do(),{remove:pp}=Ur(),{mkdirp:KS}=ct(),{pathExists:JS}=en(),dp=kn();async function zS(e,t,n={}){let r=n.overwrite||n.clobber||!1,{srcStat:o,isChangingCase:s=!1}=await dp.checkPaths(e,t,"move",n);await dp.checkParentPaths(e,o,t,"move");let i=up.dirname(t);return up.parse(i).root!==i&&await KS(i),QS(e,t,r,s)}async function QS(e,t,n,r){if(!r){if(n)await pp(t);else if(await JS(t))throw new Error("dest already exists.")}try{await qS.rename(e,t)}catch(o){if(o.code!=="EXDEV")throw o;await XS(e,t,n)}}async function XS(e,t,n){return await YS(e,t,{overwrite:n,errorOnExist:!0,preserveTimestamps:!0}),pp(e)}fp.exports=zS});var _p=q((KI,wp)=>{"use strict";var hp=Yn(),Li=require("path"),ZS=Do().copySync,yp=Ur().removeSync,ev=ct().mkdirpSync,gp=kn();function tv(e,t,n){n=n||{};let r=n.overwrite||n.clobber||!1,{srcStat:o,isChangingCase:s=!1}=gp.checkPathsSync(e,t,"move",n);return gp.checkParentPathsSync(e,o,t,"move"),nv(t)||ev(Li.dirname(t)),rv(e,t,r,s)}function nv(e){let t=Li.dirname(e);return Li.parse(t).root===t}function rv(e,t,n,r){if(r)return Mi(e,t,n);if(n)return yp(t),Mi(e,t,n);if(hp.existsSync(t))throw new Error("dest already exists.");return Mi(e,t,n)}function Mi(e,t,n){try{hp.renameSync(e,t)}catch(r){if(r.code!=="EXDEV")throw r;return ov(e,t,n)}}function ov(e,t,n){return ZS(e,t,{overwrite:n,errorOnExist:!0,preserveTimestamps:!0}),yp(e)}wp.exports=tv});var Sp=q((JI,kp)=>{"use strict";var sv=fe().fromPromise;kp.exports={move:sv(mp()),moveSync:_p()}});var X=q((zI,vp)=>{"use strict";vp.exports={...Re(),...Do(),...Sd(),...Yd(),...lp(),...ct(),...Sp(),...Mo(),...en(),...Ur()}});var Tp={};he(Tp,{archiveWorkflow:()=>Wi,clearCache:()=>uv,deleteWorkflow:()=>dv,findActiveWorkflow:()=>pv,getResumePoint:()=>lv,invalidateCache:()=>Ft,listWorkflows:()=>oe,loadCheckpoint:()=>I,saveCheckpoint:()=>A});function Ui(e,t){return`${e}:${t}`}function av(e){return Date.now()-e.timestamp<iv}function bp(e){if(e.current_stage==="idea"&&(e.current_stage="intent"),e.construction_bolts===void 0&&(e.construction_bolts={}),e.active_bolt_id===void 0&&(e.active_bolt_id=null),e.active_bolt_stage===void 0&&(e.active_bolt_stage=null),!(!e.construction_units||Array.isArray(e.construction_units)))for(let t of Object.values(e.construction_units)){if(t.stages||(t.stages={}),!t.stages["test-generation"]){let n=t.code_generation_status==="completed";t.stages["test-generation"]={status:n?"skipped":"not_started",artifact_path:null,completed_at:null,failure_count:0,last_error:null}}for(let n of Object.values(t.stages))n.failure_count===void 0&&(n.failure_count=0),n.last_error===void 0&&(n.last_error=null);t.quality_validation_status===void 0&&(t.quality_validation_status="not_started"),t.mutation_validation_status===void 0&&(t.mutation_validation_status="not_started"),t.traceability_status===void 0&&(t.traceability_status="not_started"),t.contract_validation_status===void 0&&(t.contract_validation_status="not_started"),t.coverage_status===void 0&&(t.coverage_status="not_started"),t.coverage_percentage===void 0&&(t.coverage_percentage=null),t.critical_gap_count===void 0&&(t.critical_gap_count=0),t.security_scan_status===void 0&&(t.security_scan_status="not_started"),t.security_findings_critical===void 0&&(t.security_findings_critical=0),t.security_findings_warning===void 0&&(t.security_findings_warning=0),t.security_findings_info===void 0&&(t.security_findings_info=0),t.feature_doc_status===void 0&&(t.feature_doc_status="not_started"),t.feature_doc_path===void 0&&(t.feature_doc_path=null),t.recreation_readiness_score===void 0&&(t.recreation_readiness_score=null),t.recreation_readiness_dimensions===void 0&&(t.recreation_readiness_dimensions=null),t.adr_count===void 0&&(t.adr_count=0),t.impact_scan_status===void 0&&(t.impact_scan_status="not_started")}}function lv(e){let t=e.active_bolt_id;if(t==null)return null;if(e.active_bolt_stage!=null)return{boltId:t,stage:e.active_bolt_stage};let n=e.construction_bolts?.[t];if(!n)return null;for(let r of cv){let o=n.stages[r];if(o.status!=="completed"&&o.status!=="skipped")return{boltId:t,stage:r}}return null}function uv(){Br.clear()}function Ft(e,t){let n=Ui(e,t);Br.delete(n)}async function A(e,t){let n=(0,Ge.join)(e,St,t.workflow_id),r=(0,Ge.join)(n,Gr);try{if(t.updated_at=new Date().toISOString(),t.schema_version="3.0.0",await re.default.ensureDir(n),JSON.stringify(t).length>1e4){let a=JSON.stringify(t);await re.default.writeFile(r,a,"utf-8")}else await re.default.writeJson(r,t,{spaces:2});let i=Ui(e,t.workflow_id);Br.set(i,{checkpoint:structuredClone(t),timestamp:Date.now(),dirty:!1})}catch(o){let s=o;throw s.code==="ENOSPC"?(console.error("[Checkpoint] Failed to save checkpoint: Disk full"),console.error("[Checkpoint] Please free up disk space and try again."),console.error(`[Checkpoint] Attempted path: ${r}`),new Error("Failed to save checkpoint: Disk is full. Please free up space and retry.")):s.code==="EACCES"||s.code==="EPERM"?(console.error("[Checkpoint] Failed to save checkpoint: Permission denied"),console.error(`[Checkpoint] Path: ${r}`),new Error(`Failed to save checkpoint: Permission denied for ${r}`)):s.code==="EROFS"?(console.error("[Checkpoint] Failed to save checkpoint: Read-only filesystem"),console.error(`[Checkpoint] Path: ${r}`),new Error("Failed to save checkpoint: Filesystem is read-only")):(console.error("[Checkpoint] Failed to save checkpoint:",s.message),console.error(`[Checkpoint] Workflow ID: ${t.workflow_id}`),console.error(`[Checkpoint] Path: ${r}`),new Error(`Failed to save checkpoint for workflow ${t.workflow_id}: ${s.message}`))}}async function I(e,t){let n=Ui(e,t),r=Br.get(n);if(r&&av(r)){let s=structuredClone(r.checkpoint);return bp(s),s}let o=(0,Ge.join)(e,St,t,Gr);try{let s=await re.default.readFile(o,"utf-8"),i=JSON.parse(s);return i.schema_version?i.schema_version!=="3.0.0"?(console.warn(`[Checkpoint] Unknown checkpoint schema version ${i.schema_version} for workflow ${t}`),console.warn("[Checkpoint] Expected 3.0.0"),null):(i.current_stage==="idea"&&console.warn(`[Checkpoint] Migrating legacy 'idea' stage to 'intent' for workflow ${t}`),bp(i),Br.set(n,{checkpoint:structuredClone(i),timestamp:Date.now(),dirty:!1}),i):(console.warn(`[Checkpoint] Checkpoint ${t} missing schema_version, treating as invalid`),console.warn("[Checkpoint] Checkpoint may be corrupt or from an older version"),console.warn(`[Checkpoint] Consider deleting: ${o}`),null)}catch(s){let i=s,a=i;return a.code==="ENOENT"?null:i.name==="SyntaxError"||i.message.includes("JSON")?(console.warn(`[Checkpoint] Corrupt checkpoint detected for workflow ${t}`),console.warn(`[Checkpoint] Path: ${o}`),console.warn(`[Checkpoint] Error: ${i.message}`),console.warn("[Checkpoint] To reset this workflow, delete the checkpoint file and start over"),null):a.code==="EACCES"||a.code==="EPERM"?(console.warn(`[Checkpoint] Permission denied reading checkpoint ${t}`),console.warn(`[Checkpoint] Path: ${o}`),null):(console.warn(`[Checkpoint] Failed to load checkpoint ${t}: ${i.message}`),console.warn(`[Checkpoint] Path: ${o}`),null)}}async function oe(e){let t=(0,Ge.join)(e,St);try{if(!await re.default.pathExists(t))return[];let r=await re.default.readdir(t,{withFileTypes:!0}),o=[];for(let s of r){if(!s.isDirectory()||s.name==="completed")continue;let i=(0,Ge.join)(t,s.name,Gr);if(await re.default.pathExists(i))try{let a=await re.default.readFile(i,"utf-8"),c=JSON.parse(a);c.workflow_id&&o.push(c.workflow_id)}catch{}}return o}catch(n){let r=n;return r.code==="EACCES"||r.code==="EPERM"?console.warn(`[Checkpoint] Permission denied reading ${t}`):console.warn(`[Checkpoint] Failed to list workflows: ${r.message}`),[]}}async function dv(e,t){let n=(0,Ge.join)(e,St,t);try{await re.default.remove(n)}catch(r){let o=r;if(o.code==="ENOENT")return;if(o.code==="EACCES"||o.code==="EPERM"){console.warn(`[Checkpoint] Permission denied deleting workflow ${t}`),console.warn(`[Checkpoint] Path: ${n}`),console.warn("[Checkpoint] Manual deletion may be required");return}console.warn(`[Checkpoint] Failed to delete workflow ${t}: ${o.message}`),console.warn(`[Checkpoint] Path: ${n}`)}}async function Wi(e,t){let n=await I(e,t);if(!n||n.status!=="complete")return;let r=(0,Ge.join)(e,St,t),o=(0,Ge.join)(e,St,"completed",t),s=(0,Ge.join)(o,Gr);if(await re.default.pathExists(s))try{let i=await re.default.readFile(s,"utf-8");if(JSON.parse(i).workflow_id===t){console.log(`[Checkpoint] Workflow ${t} already archived at ${o}`);return}}catch{await re.default.remove(o)}else await re.default.pathExists(o)&&await re.default.remove(o);n.archived_at=new Date().toISOString(),n.archived_path=`${St}/completed/${t}`,await A(e,n);try{await re.default.move(r,o,{overwrite:!1}),Ft(e,t),console.log(`[Checkpoint] Workflow archived to ${St}/completed/${t}/`)}catch(i){let a=i,c=a.code==="EBUSY"&&process.platform==="win32"?" \u2014 try closing open files in the workflow directory":"";console.warn(`[Checkpoint] Failed to move workflow folder (non-fatal): ${a.message}${c}`)}try{let i=(0,Ge.join)(e,".olympus","plans",`${t}-plan.md`);if(await re.default.pathExists(i)){let a=`
16
16
 
17
17
  ---
18
18
  _This workflow was archived to \`${St}/completed/${t}/\` on ${n.archived_at}_
19
- `;await re.default.appendFile(i,a,"utf-8")}}catch{}}async function sv(e){let t=(0,Be.join)(e,St);try{if(!await re.default.pathExists(t))return null;let r=await re.default.readdir(t,{withFileTypes:!0});for(let o of r){if(!o.isDirectory()||o.name==="completed")continue;let s=(0,Be.join)(t,o.name,Br);if(await re.default.pathExists(s))try{let i=await re.default.readFile(s,"utf-8"),a=JSON.parse(i);if(a.schema_version==="3.0.0"&&a.status!=="complete"&&a.status!=="archived"&&a.status!=="deferred")return{workflowId:a.workflow_id,checkpoint:a}}catch{}}return null}catch{return null}}var re,Be,St,Br,Gr,tv,me=U(()=>{"use strict";re=T(X(),1),Be=require("path"),St="aidlc-docs",Br="checkpoint.json",Gr=new Map,tv=5e3});var Tp={};he(Tp,{computeVerification:()=>Lo,generateValidationQuestions:()=>vp,getAdaptiveThreshold:()=>uv,getConformanceThreshold:()=>pv,recordAlignmentResult:()=>dv,runAlignmentCheck:()=>Wi,runDualValidation:()=>Qn});function cv(e){return e.replace(/^---\n[\s\S]*?\n---\n/,"")}function Ui(e){let t=new Map,n=e.split(`
19
+ `;await re.default.appendFile(i,a,"utf-8")}}catch{}}async function pv(e){let t=(0,Ge.join)(e,St);try{if(!await re.default.pathExists(t))return null;let r=await re.default.readdir(t,{withFileTypes:!0});for(let o of r){if(!o.isDirectory()||o.name==="completed")continue;let s=(0,Ge.join)(t,o.name,Gr);if(await re.default.pathExists(s))try{let i=await re.default.readFile(s,"utf-8"),a=JSON.parse(i);if(a.schema_version==="3.0.0"&&a.status!=="complete"&&a.status!=="archived"&&a.status!=="deferred")return{workflowId:a.workflow_id,checkpoint:a}}catch{}}return null}catch{return null}}var re,Ge,St,Gr,Br,iv,cv,le=U(()=>{"use strict";re=b(X(),1),Ge=require("path"),St="aidlc-docs",Gr="checkpoint.json",Br=new Map,iv=5e3;cv=["elaboration","code_generation","build_and_test","review"]});var Rp={};he(Rp,{computeVerification:()=>Lo,generateValidationQuestions:()=>Cp,getAdaptiveThreshold:()=>yv,getConformanceThreshold:()=>_v,recordAlignmentResult:()=>wv,runAlignmentCheck:()=>Gi,runDualValidation:()=>Qn});function gv(e){return e.replace(/^---\n[\s\S]*?\n---\n/,"")}function Bi(e){let t=new Map,n=e.split(`
20
20
  `),r=null,o=[];for(let s of n){let i=s.match(/^##\s+(.+)$/);i?(r&&t.set(r,o.join(`
21
21
  `)),r=i[1].trim(),o=[]):r&&o.push(s)}return r&&t.set(r,o.join(`
22
22
  `)),t}function Hr(e){let t=[],n=e.split(`
23
- `);for(let r of n){let o=r.match(/^\s*[-*+]\s+(?:\[[ x]\]\s+)?(.+)$/);o&&t.push(o[1].trim())}return t}function lv(e,t){let n=cv(e);if(t==="intent-to-unit"){let i=Ui(n),a=[],c=i.get("Business Requirements");c&&a.push(...Hr(c));let l=i.get("Implementation Plan");return l&&a.push(...Hr(l)),a}if(t==="unit-to-bolt"){let i=Ui(n),a=[],c=i.get("Acceptance Criteria");c&&a.push(...Hr(c));let l=i.get("Target Files");return l&&a.push(...Hr(l)),a}let r=Ui(n),o=av[t],s=[];for(let i of o){let a=r.get(i);if(a){let c=Hr(a);s.push(...c)}}return s}function Lo(e,t,n){try{let r=lv(e,n);if(r.length===0)return{conformance_score:100,coverage_percentage:100,missing_items:[],passed:!0};let o=t.toLowerCase(),s=[],i=0;for(let d of r){let p=d.toLowerCase();o.includes(p)?i++:s.push(d)}let a=Math.round(i/r.length*100),c=a,l=Sp[n],u=a>=l;return{conformance_score:a,coverage_percentage:c,missing_items:s,passed:u}}catch(r){return console.error("[Alignment] Verification computation failed:",r),{conformance_score:0,coverage_percentage:0,missing_items:["Verification computation error"],passed:!1}}}function vp(e){let t=iv[e];return[{question:t.verification,answer:null,answered_by:null,passed:null},{question:t.validation,answer:null,answered_by:null,passed:null}]}function Wi(e,t,n,r,o){try{let s=Lo(e,t,o),i=vp(o),a=i.every(f=>f.answer!==null),c=i.every(f=>f.passed===!0),u={alignment_score:a&&c?100:0,alignment_questions:i,passed:c},d=s.passed&&u.passed;return{source_artifact_id:n,target_artifact_id:r,verification:s,validation:u,alignment_passed:d,checked_at:new Date().toISOString()}}catch(s){return console.error("[Alignment] Alignment check failed:",s),{source_artifact_id:n,target_artifact_id:r,verification:{conformance_score:0,coverage_percentage:0,missing_items:["Alignment check error"],passed:!1},validation:{alignment_score:0,alignment_questions:[],passed:!1},alignment_passed:!1,checked_at:new Date().toISOString()}}}function Qn(e,t,n,r,o,s,i,a){let c=Wi(t,e,s,i,r),l=Wi(n,e,a,i,o),u=c.alignment_passed&&l.alignment_passed;return{parentCheck:c,rootCheck:l,passed:u}}function uv(e,t){let n=0;t>=2&&(n+=10),t>=3&&(n+=10);let r=e-n;return Math.max(0,r)}function dv(e,t){try{let n=W(e);if(!n){console.error(`[Alignment] Manifest not found at ${e}`);return}n.alignment_checks.push(t),H(e,n)}catch(n){console.error("[Alignment] Failed to record alignment result:",n)}}function pv(e){return Sp[e]}var Sp,iv,av,Uo=U(()=>{"use strict";Z();Sp={"intent-to-unit":95,"unit-to-bolt":100,"unit-to-intent":80,"bolt-to-intent":70},iv={"intent-to-unit":{verification:"Does the UNIT cover its assigned scope from the INTENT?",validation:"Will this UNIT produce a working module that contributes to the feature?"},"unit-to-bolt":{verification:"Does the BOLT cover all acceptance criteria from the UNIT?",validation:"Does this BOLT deliver meaningful, testable progress?"},"unit-to-intent":{verification:"Does this UNIT contribute to the INTENT's problem statement?",validation:"Does this UNIT help achieve the INTENT's success metrics?"},"bolt-to-intent":{verification:"Does this BOLT contribute to solving the INTENT's stated problem?",validation:"Is this BOLT still aligned with the original INTENT's goals?"}},av={"intent-to-unit":["Business Requirements","Implementation Plan"],"unit-to-bolt":["Acceptance Criteria","Target Files"],"unit-to-intent":["Problem Statement","Success Metrics"],"bolt-to-intent":["Problem Statement","Success Metrics"]}});var vn={};he(vn,{addGateAuditEntry:()=>Fe,cascadeInvalidation:()=>mv,computeChecksum:()=>Wo,createManifest:()=>Bi,detectStaleArtifacts:()=>fv,getArtifactById:()=>yv,getArtifactsByPhase:()=>wv,getBoltArtifacts:()=>Et,getBoltsByStatus:()=>Vi,getUnitArtifacts:()=>Sn,isWorkflowComplete:()=>bp,linkArtifacts:()=>Hi,loadManifest:()=>W,normalizePath:()=>Gi,recoverManifest:()=>hv,registerArtifact:()=>Ne,revalidateStaleArtifacts:()=>_v,runAlignmentCheck:()=>gv,saveManifest:()=>H,transitionToActive:()=>qi,transitionToDraft:()=>Cp,transitionToFulfilled:()=>Yi,transitionToStale:()=>xp,transitionToViolated:()=>Rp,updateContractStatus:()=>Tt,updatePhaseStatus:()=>jt});function Gi(e){return e.replace(/\\/g,"/")}function rn(){return{status:"not_started",started_at:null,completed_at:null,gate_result:null,gate_bypassed:!1,bypass_reason:null}}function Bi(e,t,n){let r=vt.join(n,"aidlc-docs",e),o=vt.join(r,"manifest.json");try{Te.default.ensureDirSync(r);let s=new Date().toISOString(),i={schema_version:"2.0.0",workflow_id:e,feature_name:t,created_at:s,updated_at:s,phases:{discovery:rn(),inception:rn(),construction:rn(),operations:rn()},depth_assessment:null,artifacts:[],links:[],risks:[],gate_audit:[],metrics:null,alignment_checks:[],risk_tier:null};return Te.default.writeFileSync(o,JSON.stringify(i,null,2),"utf-8"),o}catch(s){throw console.error(`Failed to create manifest at ${o}:`,s),s}}function W(e){try{if(!Te.default.existsSync(e))return null;let t=Te.default.readFileSync(e,"utf-8");return JSON.parse(t)}catch(t){return console.error(`Failed to load manifest at ${e}:`,t),null}}function H(e,t){try{t.updated_at=new Date().toISOString(),Te.default.writeFileSync(e,JSON.stringify(t,null,2),"utf-8")}catch(n){throw console.error(`Failed to save manifest at ${e}:`,n),n}}function Wo(e){try{if(!Te.default.existsSync(e))return null;let t=Te.default.readFileSync(e),n=(0,Ep.createHash)("sha256");return n.update(t),n.digest("hex")}catch(t){return console.error(`Failed to compute checksum for ${e}:`,t),null}}function Ne(e,t){try{let n=W(e);if(!n)throw new Error(`Manifest not found at ${e}`);let r=new Date().toISOString(),o=Gi(t.path),s=n.artifacts.findIndex(a=>a.id===t.id),i=Wo(t.path);if(s>=0){let a=n.artifacts[s];n.artifacts[s]={...a,...t,path:o,updated_at:r,contract_version:a.contract_version+1,checksum:i}}else{let a={...t,path:o,created_at:r,updated_at:r,contract_version:1,contract_status:"draft",stale_reason:null,checksum:i};n.artifacts.push(a)}H(e,n)}catch(n){throw console.error(`Failed to register artifact in ${e}:`,n),n}}function Hi(e,t){try{let n=W(e);if(!n)throw new Error(`Manifest not found at ${e}`);let r=n.artifacts.some(i=>i.id===t.source_id),o=n.artifacts.some(i=>i.id===t.target_id);if(!r)throw new Error(`Source artifact not found: ${t.source_id}`);if(!o)throw new Error(`Target artifact not found: ${t.target_id}`);n.links.some(i=>i.source_id===t.source_id&&i.target_id===t.target_id&&i.link_type===t.link_type)||(n.links.push(t),H(e,n))}catch(n){throw console.error(`Failed to link artifacts in ${e}:`,n),n}}function fv(e){try{let t=W(e);if(!t)return[];let n=[];for(let r of t.artifacts)if(r.checksum&&r.write_complete){let o=Wo(r.path);o&&o!==r.checksum&&n.push(r.id)}return n}catch(t){return console.error(`Failed to detect stale artifacts in ${e}:`,t),[]}}function mv(e,t){try{let n=W(e);if(!n)return;let r=new Set,o=[t];for(;o.length>0;){let s=o.shift();if(r.has(s))continue;r.add(s);let i=n.artifacts.find(c=>c.id===s);if(i){let c=s===t?"Artifact content was modified":`Parent artifact ${s} was modified`;kv(i,c)}let a=n.links.filter(c=>c.source_id===s);for(let c of a)r.has(c.target_id)||o.push(c.target_id)}H(e,n)}catch(n){console.error(`Failed to cascade invalidation in ${e}:`,n)}}function gv(e,t,n){try{let r=W(e);if(!r)return;let o=new Date().toISOString(),a={source_artifact_id:t,target_artifact_id:n,verification:{conformance_score:0,coverage_percentage:0,missing_items:[],passed:!1},validation:{alignment_score:0,alignment_questions:[],passed:!1},alignment_passed:!1,checked_at:o};r.alignment_checks.push(a),H(e,r)}catch(r){console.error(`Failed to run alignment check in ${e}:`,r)}}function hv(e,t){try{let n=vt.join(e,"aidlc-docs",t);if(!Te.default.existsSync(n))return null;let r=new Date().toISOString(),o={schema_version:"2.0.0",workflow_id:t,feature_name:"Recovered Workflow",created_at:r,updated_at:r,phases:{discovery:rn(),inception:rn(),construction:rn(),operations:rn()},depth_assessment:null,artifacts:[],links:[],risks:[],gate_audit:[],metrics:null,alignment_checks:[],risk_tier:null},s=Te.default.readdirSync(n,{recursive:!0,withFileTypes:!0});for(let i of s)if(i.isFile()&&i.name!=="manifest.json"){let a=vt.join(i.path,i.name),c=vt.relative(n,a),l=Gi(a),u={id:`recovered-${Date.now()}-${o.artifacts.length}`,type:vt.extname(i.name)||"unknown",phase:"inception",stage:"intent",path:l,created_at:r,updated_at:r,validation_passed:null,write_complete:!0,checksum:Wo(a),contract_status:"draft",contract_version:1,stale_reason:null};o.artifacts.push(u)}return o}catch(n){return console.error(`Failed to recover manifest for workflow ${t}:`,n),null}}function jt(e,t,n,r,o){try{let s=W(e);if(!s)return;s.phases[t].status=n,r!==void 0&&(s.phases[t].started_at=r),o!==void 0&&(s.phases[t].completed_at=o),H(e,s)}catch(s){console.error(`Failed to update phase status in ${e}:`,s)}}function Fe(e,t){try{let n=W(e);if(!n)return;let r={...t,timestamp:new Date().toISOString()};n.gate_audit.push(r),H(e,n)}catch(n){console.error(`Failed to add gate audit entry in ${e}:`,n)}}function yv(e,t){return e.artifacts.find(n=>n.id===t)}function wv(e,t){return e.artifacts.filter(n=>n.phase===t)}function Tt(e,t,n,r){try{switch(n){case"draft":Cp(e,t);break;case"active":qi(e,t);break;case"fulfilled":Yi(e,t);break;case"violated":Rp(e,t);break;case"stale":if(!r)throw new Error('staleReason is required when setting status to "stale"');xp(e,t,r);break}}catch(o){console.error(`Failed to update contract status in ${e}:`,o)}}function Sn(e){return e.artifacts.filter(t=>t.stage==="unit")}function Et(e,t){let n=e.artifacts.filter(r=>r.stage==="code-generation");if(t){let r=new Set(e.links.filter(o=>o.source_id===t&&(o.link_type==="derives"||o.link_type==="implements")).map(o=>o.target_id));return n.filter(o=>r.has(o.id))}return n}function Vi(e,t){return e.artifacts.filter(n=>n.stage==="code-generation"&&n.contract_status===t)}function bp(e){let t=e.artifacts.filter(n=>n.stage==="code-generation");return t.length===0?!1:t.every(n=>n.contract_status==="fulfilled")}function kv(e,t){return e.contract_status==="stale"||e.contract_status==="violated"?!1:(e.contract_status="stale",e.stale_reason=t,e.statusHistory||(e.statusHistory=[]),e.statusHistory.push({status:"stale",timestamp:new Date().toISOString()}),!0)}function Cp(e,t){let n=W(e);if(!n)throw new Error(`Manifest not found at ${e}`);let r=n.artifacts.find(o=>o.id===t);if(!r)throw new Error(`Artifact ${t} not found in manifest`);if(r.contract_status!=="violated"&&r.contract_status!=="stale")throw new Error(`Cannot transition from '${r.contract_status}' to 'draft'`);r.contract_status="draft",r.stale_reason=null,r.statusHistory||(r.statusHistory=[]),r.statusHistory.push({status:"draft",timestamp:new Date().toISOString()}),H(e,n)}function qi(e,t){let n=W(e);if(!n)throw new Error(`Manifest not found at ${e}`);let r=n.artifacts.find(o=>o.id===t);if(!r)throw new Error(`Artifact ${t} not found in manifest`);if(r.contract_status!=="draft"&&r.contract_status!=="stale")throw new Error(`Cannot transition from '${r.contract_status}' to 'active'`);r.contract_status="active",r.stale_reason=null,r.statusHistory||(r.statusHistory=[]),r.statusHistory.push({status:"active",timestamp:new Date().toISOString()}),H(e,n)}function Yi(e,t){let n=W(e);if(!n)throw new Error(`Manifest not found at ${e}`);let r=n.artifacts.find(o=>o.id===t);if(!r)throw new Error(`Artifact ${t} not found in manifest`);if(r.contract_status!=="active")throw new Error(`Cannot transition from '${r.contract_status}' to 'fulfilled'`);r.contract_status="fulfilled",r.stale_reason=null,r.statusHistory||(r.statusHistory=[]),r.statusHistory.push({status:"fulfilled",timestamp:new Date().toISOString()}),H(e,n)}function Rp(e,t){let n=W(e);if(!n)throw new Error(`Manifest not found at ${e}`);let r=n.artifacts.find(o=>o.id===t);if(!r)throw new Error(`Artifact ${t} not found in manifest`);if(r.contract_status!=="active")throw new Error(`Cannot transition from '${r.contract_status}' to 'violated'`);r.contract_status="violated",r.stale_reason=null,r.statusHistory||(r.statusHistory=[]),r.statusHistory.push({status:"violated",timestamp:new Date().toISOString()}),H(e,n)}function xp(e,t,n){let r=W(e);if(!r)throw new Error(`Manifest not found at ${e}`);let o=r.artifacts.find(s=>s.id===t);if(!o)throw new Error(`Artifact ${t} not found in manifest`);if(o.contract_status!=="active"&&o.contract_status!=="fulfilled")throw new Error(`Cannot transition from '${o.contract_status}' to 'stale'`);o.contract_status="stale",o.stale_reason=n,o.statusHistory||(o.statusHistory=[]),o.statusHistory.push({status:"stale",timestamp:new Date().toISOString()}),H(e,r)}async function _v(e,t){let n={restored:[],stillStale:[],errors:[]},r=vt.join(e,"aidlc-docs",t,"manifest.json"),o=W(r);if(!o)return n.errors.push("Manifest not found"),n;let s=o.artifacts.filter(i=>i.contract_status==="stale");for(let i of s)try{let a=o.links.find(w=>w.target_id===i.id);if(!a){n.stillStale.push(i.id);continue}let c=o.artifacts.find(w=>w.id===a.source_id);if(!c){n.stillStale.push(i.id);continue}let l=o.artifacts.find(w=>w.stage==="intent");if(!l){n.stillStale.push(i.id);continue}let u=Te.default.existsSync(i.path)?Te.default.readFileSync(i.path,"utf-8"):null,d=Te.default.existsSync(c.path)?Te.default.readFileSync(c.path,"utf-8"):null,p=Te.default.existsSync(l.path)?Te.default.readFileSync(l.path,"utf-8"):null;if(!u||!d||!p){n.stillStale.push(i.id);continue}let{runDualValidation:f}=await Promise.resolve().then(()=>(Uo(),Tp)),m,g;if(i.stage==="unit")m="intent-to-unit",g="unit-to-intent";else if(i.stage==="code-generation")m="unit-to-bolt",g="bolt-to-intent";else{n.stillStale.push(i.id);continue}f(u,d,p,m,g,c.id,i.id,l.id).passed?(i.contract_status="active",i.stale_reason=null,i.statusHistory||(i.statusHistory=[]),i.statusHistory.push({status:"active",timestamp:new Date().toISOString()}),n.restored.push(i.id)):n.stillStale.push(i.id)}catch(a){n.errors.push(`Error revalidating ${i.id}: ${a}`),n.stillStale.push(i.id)}return H(r,o),n}var Te,vt,Ep,Z=U(()=>{"use strict";Te=T(X(),1),vt=T(require("path"),1),Ep=require("crypto")});async function Pp(e,t){let n=L.join(e,"aidlc-docs",t),r=L.join(n,"checkpoint.json");try{await ie.ensureDir(n),await ie.ensureDir(L.join(n,"inception")),await ie.ensureDir(L.join(n,"construction")),await ie.ensureDir(L.join(n,"construction","design")),await ie.ensureDir(L.join(n,"operations")),await ie.pathExists(r)||await ie.writeJson(r,{workflow_id:t,current_stage:"intent",created_at:new Date().toISOString(),updated_at:new Date().toISOString()},{spaces:2})}catch(o){let s=o;throw s.code==="ENOSPC"?(console.error("[Artifacts] Failed to create workflow directory: Disk full"),console.error("[Artifacts] Please free up disk space and try again."),console.error(`[Artifacts] Attempted path: ${n}`),new Error("Failed to create workflow directory: Disk is full. Please free up space and retry.")):s.code==="EACCES"||s.code==="EPERM"?(console.error("[Artifacts] Failed to create workflow directory: Permission denied"),console.error(`[Artifacts] Path: ${n}`),new Error(`Failed to create workflow directory: Permission denied for ${n}`)):s.code==="EROFS"?(console.error("[Artifacts] Failed to create workflow directory: Read-only filesystem"),console.error(`[Artifacts] Path: ${n}`),new Error("Failed to create workflow directory: Filesystem is read-only")):(console.error(`[Artifacts] Failed to create workflow directory: ${s.message}`),console.error(`[Artifacts] Workflow ID: ${t}`),console.error(`[Artifacts] Path: ${n}`),new Error(`Failed to create workflow directory for ${t}: ${s.message}`))}}function lt(e,t,n,r,o){let s=L.join(e,"aidlc-docs",t);switch(n){case"intent":return L.join(s,"inception","intent.md");case"nfr":return L.join(s,"inception","requirements","nfr.md");case"unit":if(!r)throw new Error("artifactId is required for unit artifacts");return L.join(s,"construction",r,"spec.md");case"code-generation":if(!r)throw new Error("artifactId is required for code-generation artifacts");if(!o)throw new Error("unitId is required for code-generation artifacts");return L.join(s,"construction",o,`${r}.md`);case"validation-report":if(!r)throw new Error("artifactId is required for validation-report artifacts");return L.join(s,"construction",r,"validation-report.md");case"interfaces":return L.join(s,"construction","design","interfaces.json");case"data-flow":return L.join(s,"construction","design","data-flow.json");case"components":return L.join(s,"construction","design","components.json");case"deploy-guide":return L.join(s,"operations","deploy-guide.md");case"runbook":return L.join(s,"operations","runbook.md");case"monitoring":return L.join(s,"operations","monitoring.json");case"release-notes":return L.join(s,"operations","release-notes.md");case"state":return L.join(s,"state.md");case"audit":return L.join(s,"audit.md");case"analysis-plan":return L.join(s,"discovery","analysis-plan.md");case"current-state-analysis":return L.join(s,"discovery","current-state-analysis.md");case"regression-baseline":return L.join(s,"discovery","regression-baseline.md");case"change-impact":return L.join(s,"discovery","change-impact.md");case"static-model":return L.join(s,"discovery","static-model.md");case"dynamic-model":return L.join(s,"discovery","dynamic-model.md");case"WORKFLOW_ROUTING":return L.join(s,"inception","plans","workflow-routing.md");case"requirements-qa":return L.join(s,"inception","requirements","requirements-analysis-questions.md");case"requirements":return L.join(s,"inception","requirements","requirements.md");case"personas":return L.join(s,"inception","user-stories","personas.md");case"user-stories":return L.join(s,"inception","user-stories","stories.md");case"execution-plan":return L.join(s,"inception","plans","execution-plan.md");case"units-generation":return L.join(s,"inception","application-design","unit-of-work.md");case"unit-dependency":return L.join(s,"inception","application-design","unit-of-work-dependency.md");case"unit-story-map":return L.join(s,"inception","application-design","unit-of-work-story-map.md");default:throw new Error(`Unknown artifact type: ${n}`)}}async function Xn(e,t,n,r,o,s){let i=lt(e,t,n,o,s),a=await ie.pathExists(i);try{await ie.ensureDir(L.dirname(i)),await ie.writeFile(i,r,"utf-8")}catch(c){let l=c;throw l.code==="ENOSPC"?(console.error(`[Artifacts] Failed to write ${n} artifact: Disk full`),console.error("[Artifacts] Please free up disk space and try again."),console.error(`[Artifacts] Path: ${i}`),new Error(`Failed to write ${n} artifact: Disk is full. Please free up space and retry.`)):l.code==="EACCES"||l.code==="EPERM"?(console.error(`[Artifacts] Failed to write ${n} artifact: Permission denied`),console.error(`[Artifacts] Path: ${i}`),new Error(`Failed to write ${n} artifact: Permission denied for ${i}`)):l.code==="EROFS"?(console.error(`[Artifacts] Failed to write ${n} artifact: Read-only filesystem`),console.error(`[Artifacts] Path: ${i}`),new Error(`Failed to write ${n} artifact: Filesystem is read-only`)):(console.error(`[Artifacts] Failed to write ${n} artifact: ${l.message}`),console.error(`[Artifacts] Path: ${i}`),new Error(`Failed to write ${n} artifact: ${l.message}`))}if(a)try{let c=L.join(e,"aidlc-docs",t,"manifest.json"),{cascadeInvalidation:l,loadManifest:u,saveManifest:d,computeChecksum:p}=await Promise.resolve().then(()=>(Z(),vn)),f=u(c);if(f){let m=i.replace(/\\/g,"/"),g=f.artifacts.find(y=>y.path===m||y.path.endsWith(L.basename(i)));if(g){let y=p(i);y&&(g.checksum=y,g.updated_at=new Date().toISOString(),d(c,f)),l(c,g.id)}}}catch(c){console.error("[Artifacts] Cascade invalidation after write failed:",c)}}async function Ki(e,t){let n=L.join(e,"aidlc-docs",t,"discovery");await ie.ensureDir(n)}async function Ip(e,t,n){let r=L.join(e,"aidlc-docs",t,"audit.md");await ie.ensureDir(L.dirname(r)),await ie.pathExists(r)?await ie.appendFile(r,`
23
+ `);for(let r of n){let o=r.match(/^\s*[-*+]\s+(?:\[[ x]\]\s+)?(.+)$/);o&&t.push(o[1].trim())}return t}function hv(e,t){let n=gv(e);if(t==="intent-to-unit"){let i=Bi(n),a=[],c=i.get("Business Requirements");c&&a.push(...Hr(c));let l=i.get("Implementation Plan");return l&&a.push(...Hr(l)),a}if(t==="unit-to-bolt"){let i=Bi(n),a=[],c=i.get("Acceptance Criteria");c&&a.push(...Hr(c));let l=i.get("Target Files");return l&&a.push(...Hr(l)),a}let r=Bi(n),o=mv[t],s=[];for(let i of o){let a=r.get(i);if(a){let c=Hr(a);s.push(...c)}}return s}function Lo(e,t,n){try{let r=hv(e,n);if(r.length===0)return{conformance_score:100,coverage_percentage:100,missing_items:[],passed:!0};let o=t.toLowerCase(),s=[],i=0;for(let d of r){let p=d.toLowerCase();o.includes(p)?i++:s.push(d)}let a=Math.round(i/r.length*100),c=a,l=Ep[n],u=a>=l;return{conformance_score:a,coverage_percentage:c,missing_items:s,passed:u}}catch(r){return console.error("[Alignment] Verification computation failed:",r),{conformance_score:0,coverage_percentage:0,missing_items:["Verification computation error"],passed:!1}}}function Cp(e){let t=fv[e];return[{question:t.verification,answer:null,answered_by:null,passed:null},{question:t.validation,answer:null,answered_by:null,passed:null}]}function Gi(e,t,n,r,o){try{let s=Lo(e,t,o),i=Cp(o),a=i.every(f=>f.answer!==null),c=i.every(f=>f.passed===!0),u={alignment_score:a&&c?100:0,alignment_questions:i,passed:c},d=s.passed&&u.passed;return{source_artifact_id:n,target_artifact_id:r,verification:s,validation:u,alignment_passed:d,checked_at:new Date().toISOString()}}catch(s){return console.error("[Alignment] Alignment check failed:",s),{source_artifact_id:n,target_artifact_id:r,verification:{conformance_score:0,coverage_percentage:0,missing_items:["Alignment check error"],passed:!1},validation:{alignment_score:0,alignment_questions:[],passed:!1},alignment_passed:!1,checked_at:new Date().toISOString()}}}function Qn(e,t,n,r,o,s,i,a){let c=Gi(t,e,s,i,r),l=Gi(n,e,a,i,o),u=c.alignment_passed&&l.alignment_passed;return{parentCheck:c,rootCheck:l,passed:u}}function yv(e,t){let n=0;t>=2&&(n+=10),t>=3&&(n+=10);let r=e-n;return Math.max(0,r)}function wv(e,t){try{let n=W(e);if(!n){console.error(`[Alignment] Manifest not found at ${e}`);return}n.alignment_checks.push(t),G(e,n)}catch(n){console.error("[Alignment] Failed to record alignment result:",n)}}function _v(e){return Ep[e]}var Ep,fv,mv,Uo=U(()=>{"use strict";Z();Ep={"intent-to-unit":95,"unit-to-bolt":100,"unit-to-intent":80,"bolt-to-intent":70},fv={"intent-to-unit":{verification:"Does the UNIT cover its assigned scope from the INTENT?",validation:"Will this UNIT produce a working module that contributes to the feature?"},"unit-to-bolt":{verification:"Does the BOLT cover all acceptance criteria from the UNIT?",validation:"Does this BOLT deliver meaningful, testable progress?"},"unit-to-intent":{verification:"Does this UNIT contribute to the INTENT's problem statement?",validation:"Does this UNIT help achieve the INTENT's success metrics?"},"bolt-to-intent":{verification:"Does this BOLT contribute to solving the INTENT's stated problem?",validation:"Is this BOLT still aligned with the original INTENT's goals?"}},mv={"intent-to-unit":["Business Requirements","Implementation Plan"],"unit-to-bolt":["Acceptance Criteria","Target Files"],"unit-to-intent":["Problem Statement","Success Metrics"],"bolt-to-intent":["Problem Statement","Success Metrics"]}});var vn={};he(vn,{addArtifactLink:()=>kv,addGateAuditEntry:()=>Fe,cascadeInvalidation:()=>vv,computeChecksum:()=>Wo,createManifest:()=>Vi,detectStaleArtifacts:()=>Sv,getArtifactById:()=>Ev,getArtifactsByPhase:()=>Cv,getBoltArtifacts:()=>Tt,getBoltsByStatus:()=>Yi,getUnitArtifacts:()=>Sn,isWorkflowComplete:()=>Pp,linkArtifacts:()=>qi,loadManifest:()=>W,normalizePath:()=>Hi,recoverManifest:()=>Tv,registerArtifact:()=>Ne,revalidateStaleArtifacts:()=>xv,runAlignmentCheck:()=>bv,saveManifest:()=>G,transitionToActive:()=>Ki,transitionToDraft:()=>Ap,transitionToFulfilled:()=>Ji,transitionToStale:()=>Op,transitionToViolated:()=>Ip,updateContractStatus:()=>bt,updatePhaseStatus:()=>jt});function Hi(e){return e.replace(/\\/g,"/")}function rn(){return{status:"not_started",started_at:null,completed_at:null,gate_result:null,gate_bypassed:!1,bypass_reason:null}}function Vi(e,t,n){let r=vt.join(n,"aidlc-docs",e),o=vt.join(r,"manifest.json");try{be.default.ensureDirSync(r);let s=new Date().toISOString(),i={schema_version:"2.0.0",workflow_id:e,feature_name:t,created_at:s,updated_at:s,phases:{discovery:rn(),inception:rn(),construction:rn(),operations:rn()},depth_assessment:null,artifacts:[],links:[],risks:[],gate_audit:[],metrics:null,alignment_checks:[],risk_tier:null};return be.default.writeFileSync(o,JSON.stringify(i,null,2),"utf-8"),o}catch(s){throw console.error(`Failed to create manifest at ${o}:`,s),s}}function W(e){try{if(!be.default.existsSync(e))return null;let t=be.default.readFileSync(e,"utf-8");return JSON.parse(t)}catch(t){return console.error(`Failed to load manifest at ${e}:`,t),null}}function G(e,t){try{t.updated_at=new Date().toISOString(),be.default.writeFileSync(e,JSON.stringify(t,null,2),"utf-8")}catch(n){throw console.error(`Failed to save manifest at ${e}:`,n),n}}function Wo(e){try{if(!be.default.existsSync(e))return null;let t=be.default.readFileSync(e),n=(0,xp.createHash)("sha256");return n.update(t),n.digest("hex")}catch(t){return console.error(`Failed to compute checksum for ${e}:`,t),null}}function Ne(e,t){try{let n=W(e);if(!n)throw new Error(`Manifest not found at ${e}`);let r=new Date().toISOString(),o=Hi(t.path),s=n.artifacts.findIndex(a=>a.id===t.id),i=Wo(t.path);if(s>=0){let a=n.artifacts[s];n.artifacts[s]={...a,...t,path:o,updated_at:r,contract_version:a.contract_version+1,checksum:i}}else{let a={...t,path:o,created_at:r,updated_at:r,contract_version:1,contract_status:"draft",stale_reason:null,checksum:i};n.artifacts.push(a)}G(e,n)}catch(n){throw console.error(`Failed to register artifact in ${e}:`,n),n}}function qi(e,t){try{let n=W(e);if(!n)throw new Error(`Manifest not found at ${e}`);let r=n.artifacts.some(i=>i.id===t.source_id),o=n.artifacts.some(i=>i.id===t.target_id);if(!r)throw new Error(`Source artifact not found: ${t.source_id}`);if(!o)throw new Error(`Target artifact not found: ${t.target_id}`);n.links.some(i=>i.source_id===t.source_id&&i.target_id===t.target_id&&i.link_type===t.link_type)||(n.links.push(t),G(e,n))}catch(n){throw console.error(`Failed to link artifacts in ${e}:`,n),n}}function kv(e,t,n,r){e.links.some(s=>s.source_id===t&&s.target_id===n&&s.link_type===r)||e.links.push({source_id:t,target_id:n,link_type:r})}function Sv(e){try{let t=W(e);if(!t)return[];let n=[];for(let r of t.artifacts)if(r.checksum&&r.write_complete){let o=Wo(r.path);o&&o!==r.checksum&&n.push(r.id)}return n}catch(t){return console.error(`Failed to detect stale artifacts in ${e}:`,t),[]}}function vv(e,t){try{let n=W(e);if(!n)return;let r=new Set,o=[t];for(;o.length>0;){let s=o.shift();if(r.has(s))continue;r.add(s);let i=n.artifacts.find(c=>c.id===s);if(i){let c=s===t?"Artifact content was modified":`Parent artifact ${s} was modified`;Rv(i,c)}let a=n.links.filter(c=>c.source_id===s);for(let c of a)r.has(c.target_id)||o.push(c.target_id)}G(e,n)}catch(n){console.error(`Failed to cascade invalidation in ${e}:`,n)}}function bv(e,t,n){try{let r=W(e);if(!r)return;let o=new Date().toISOString(),a={source_artifact_id:t,target_artifact_id:n,verification:{conformance_score:0,coverage_percentage:0,missing_items:[],passed:!1},validation:{alignment_score:0,alignment_questions:[],passed:!1},alignment_passed:!1,checked_at:o};r.alignment_checks.push(a),G(e,r)}catch(r){console.error(`Failed to run alignment check in ${e}:`,r)}}function Tv(e,t){try{let n=vt.join(e,"aidlc-docs",t);if(!be.default.existsSync(n))return null;let r=new Date().toISOString(),o={schema_version:"2.0.0",workflow_id:t,feature_name:"Recovered Workflow",created_at:r,updated_at:r,phases:{discovery:rn(),inception:rn(),construction:rn(),operations:rn()},depth_assessment:null,artifacts:[],links:[],risks:[],gate_audit:[],metrics:null,alignment_checks:[],risk_tier:null},s=be.default.readdirSync(n,{recursive:!0,withFileTypes:!0});for(let i of s)if(i.isFile()&&i.name!=="manifest.json"){let a=vt.join(i.path,i.name),c=vt.relative(n,a),l=Hi(a),u={id:`recovered-${Date.now()}-${o.artifacts.length}`,type:vt.extname(i.name)||"unknown",phase:"inception",stage:"intent",path:l,created_at:r,updated_at:r,validation_passed:null,write_complete:!0,checksum:Wo(a),contract_status:"draft",contract_version:1,stale_reason:null};o.artifacts.push(u)}return o}catch(n){return console.error(`Failed to recover manifest for workflow ${t}:`,n),null}}function jt(e,t,n,r,o){try{let s=W(e);if(!s)return;s.phases[t].status=n,r!==void 0&&(s.phases[t].started_at=r),o!==void 0&&(s.phases[t].completed_at=o),G(e,s)}catch(s){console.error(`Failed to update phase status in ${e}:`,s)}}function Fe(e,t){try{let n=W(e);if(!n)return;let r={...t,timestamp:new Date().toISOString()};n.gate_audit.push(r),G(e,n)}catch(n){console.error(`Failed to add gate audit entry in ${e}:`,n)}}function Ev(e,t){return e.artifacts.find(n=>n.id===t)}function Cv(e,t){return e.artifacts.filter(n=>n.phase===t)}function bt(e,t,n,r){try{switch(n){case"draft":Ap(e,t);break;case"active":Ki(e,t);break;case"fulfilled":Ji(e,t);break;case"violated":Ip(e,t);break;case"stale":if(!r)throw new Error('staleReason is required when setting status to "stale"');Op(e,t,r);break}}catch(o){console.error(`Failed to update contract status in ${e}:`,o)}}function Sn(e){return e.artifacts.filter(t=>t.stage==="unit")}function Tt(e,t){let n=e.artifacts.filter(r=>r.stage==="code-generation");if(t){let r=new Set(e.links.filter(o=>o.source_id===t&&(o.link_type==="derives"||o.link_type==="implements")).map(o=>o.target_id));return n.filter(o=>r.has(o.id))}return n}function Yi(e,t){return e.artifacts.filter(n=>n.stage==="code-generation"&&n.contract_status===t)}function Pp(e){let t=e.artifacts.filter(n=>n.stage==="code-generation");return t.length===0?!1:t.every(n=>n.contract_status==="fulfilled")}function Rv(e,t){return e.contract_status==="stale"||e.contract_status==="violated"?!1:(e.contract_status="stale",e.stale_reason=t,e.statusHistory||(e.statusHistory=[]),e.statusHistory.push({status:"stale",timestamp:new Date().toISOString()}),!0)}function Ap(e,t){let n=W(e);if(!n)throw new Error(`Manifest not found at ${e}`);let r=n.artifacts.find(o=>o.id===t);if(!r)throw new Error(`Artifact ${t} not found in manifest`);if(r.contract_status!=="violated"&&r.contract_status!=="stale")throw new Error(`Cannot transition from '${r.contract_status}' to 'draft'`);r.contract_status="draft",r.stale_reason=null,r.statusHistory||(r.statusHistory=[]),r.statusHistory.push({status:"draft",timestamp:new Date().toISOString()}),G(e,n)}function Ki(e,t){let n=W(e);if(!n)throw new Error(`Manifest not found at ${e}`);let r=n.artifacts.find(o=>o.id===t);if(!r)throw new Error(`Artifact ${t} not found in manifest`);if(r.contract_status!=="draft"&&r.contract_status!=="stale")throw new Error(`Cannot transition from '${r.contract_status}' to 'active'`);r.contract_status="active",r.stale_reason=null,r.statusHistory||(r.statusHistory=[]),r.statusHistory.push({status:"active",timestamp:new Date().toISOString()}),G(e,n)}function Ji(e,t){let n=W(e);if(!n)throw new Error(`Manifest not found at ${e}`);let r=n.artifacts.find(o=>o.id===t);if(!r)throw new Error(`Artifact ${t} not found in manifest`);if(r.contract_status!=="active")throw new Error(`Cannot transition from '${r.contract_status}' to 'fulfilled'`);r.contract_status="fulfilled",r.stale_reason=null,r.statusHistory||(r.statusHistory=[]),r.statusHistory.push({status:"fulfilled",timestamp:new Date().toISOString()}),G(e,n)}function Ip(e,t){let n=W(e);if(!n)throw new Error(`Manifest not found at ${e}`);let r=n.artifacts.find(o=>o.id===t);if(!r)throw new Error(`Artifact ${t} not found in manifest`);if(r.contract_status!=="active")throw new Error(`Cannot transition from '${r.contract_status}' to 'violated'`);r.contract_status="violated",r.stale_reason=null,r.statusHistory||(r.statusHistory=[]),r.statusHistory.push({status:"violated",timestamp:new Date().toISOString()}),G(e,n)}function Op(e,t,n){let r=W(e);if(!r)throw new Error(`Manifest not found at ${e}`);let o=r.artifacts.find(s=>s.id===t);if(!o)throw new Error(`Artifact ${t} not found in manifest`);if(o.contract_status!=="active"&&o.contract_status!=="fulfilled")throw new Error(`Cannot transition from '${o.contract_status}' to 'stale'`);o.contract_status="stale",o.stale_reason=n,o.statusHistory||(o.statusHistory=[]),o.statusHistory.push({status:"stale",timestamp:new Date().toISOString()}),G(e,r)}async function xv(e,t){let n={restored:[],stillStale:[],errors:[]},r=vt.join(e,"aidlc-docs",t,"manifest.json"),o=W(r);if(!o)return n.errors.push("Manifest not found"),n;let s=o.artifacts.filter(i=>i.contract_status==="stale");for(let i of s)try{let a=o.links.find(w=>w.target_id===i.id);if(!a){n.stillStale.push(i.id);continue}let c=o.artifacts.find(w=>w.id===a.source_id);if(!c){n.stillStale.push(i.id);continue}let l=o.artifacts.find(w=>w.stage==="intent");if(!l){n.stillStale.push(i.id);continue}let u=be.default.existsSync(i.path)?be.default.readFileSync(i.path,"utf-8"):null,d=be.default.existsSync(c.path)?be.default.readFileSync(c.path,"utf-8"):null,p=be.default.existsSync(l.path)?be.default.readFileSync(l.path,"utf-8"):null;if(!u||!d||!p){n.stillStale.push(i.id);continue}let{runDualValidation:f}=await Promise.resolve().then(()=>(Uo(),Rp)),m,g;if(i.stage==="unit")m="intent-to-unit",g="unit-to-intent";else if(i.stage==="code-generation")m="unit-to-bolt",g="bolt-to-intent";else{n.stillStale.push(i.id);continue}f(u,d,p,m,g,c.id,i.id,l.id).passed?(i.contract_status="active",i.stale_reason=null,i.statusHistory||(i.statusHistory=[]),i.statusHistory.push({status:"active",timestamp:new Date().toISOString()}),n.restored.push(i.id)):n.stillStale.push(i.id)}catch(a){n.errors.push(`Error revalidating ${i.id}: ${a}`),n.stillStale.push(i.id)}return G(r,o),n}var be,vt,xp,Z=U(()=>{"use strict";be=b(X(),1),vt=b(require("path"),1),xp=require("crypto")});async function $p(e,t){let n=L.join(e,"aidlc-docs",t),r=L.join(n,"checkpoint.json");try{await ie.ensureDir(n),await ie.ensureDir(L.join(n,"inception")),await ie.ensureDir(L.join(n,"construction")),await ie.ensureDir(L.join(n,"construction","design")),await ie.ensureDir(L.join(n,"operations")),await ie.pathExists(r)||await ie.writeJson(r,{workflow_id:t,current_stage:"intent",created_at:new Date().toISOString(),updated_at:new Date().toISOString()},{spaces:2})}catch(o){let s=o;throw s.code==="ENOSPC"?(console.error("[Artifacts] Failed to create workflow directory: Disk full"),console.error("[Artifacts] Please free up disk space and try again."),console.error(`[Artifacts] Attempted path: ${n}`),new Error("Failed to create workflow directory: Disk is full. Please free up space and retry.")):s.code==="EACCES"||s.code==="EPERM"?(console.error("[Artifacts] Failed to create workflow directory: Permission denied"),console.error(`[Artifacts] Path: ${n}`),new Error(`Failed to create workflow directory: Permission denied for ${n}`)):s.code==="EROFS"?(console.error("[Artifacts] Failed to create workflow directory: Read-only filesystem"),console.error(`[Artifacts] Path: ${n}`),new Error("Failed to create workflow directory: Filesystem is read-only")):(console.error(`[Artifacts] Failed to create workflow directory: ${s.message}`),console.error(`[Artifacts] Workflow ID: ${t}`),console.error(`[Artifacts] Path: ${n}`),new Error(`Failed to create workflow directory for ${t}: ${s.message}`))}}function lt(e,t,n,r,o){let s=L.join(e,"aidlc-docs",t);switch(n){case"intent":return L.join(s,"inception","intent.md");case"nfr":return L.join(s,"inception","requirements","nfr.md");case"unit":if(!r)throw new Error("artifactId is required for unit artifacts");return L.join(s,"construction",r,"spec.md");case"code-generation":if(!r)throw new Error("artifactId is required for code-generation artifacts");if(!o)throw new Error("unitId is required for code-generation artifacts");return L.join(s,"construction",o,`${r}.md`);case"validation-report":if(!r)throw new Error("artifactId is required for validation-report artifacts");return L.join(s,"construction",r,"validation-report.md");case"interfaces":return L.join(s,"construction","design","interfaces.json");case"data-flow":return L.join(s,"construction","design","data-flow.json");case"components":return L.join(s,"construction","design","components.json");case"deploy-guide":return L.join(s,"operations","deploy-guide.md");case"runbook":return L.join(s,"operations","runbook.md");case"monitoring":return L.join(s,"operations","monitoring.json");case"release-notes":return L.join(s,"operations","release-notes.md");case"state":return L.join(s,"state.md");case"audit":return L.join(s,"audit.md");case"analysis-plan":return L.join(s,"discovery","analysis-plan.md");case"current-state-analysis":return L.join(s,"discovery","current-state-analysis.md");case"regression-baseline":return L.join(s,"discovery","regression-baseline.md");case"change-impact":return L.join(s,"discovery","change-impact.md");case"static-model":return L.join(s,"discovery","static-model.md");case"dynamic-model":return L.join(s,"discovery","dynamic-model.md");case"WORKFLOW_ROUTING":return L.join(s,"inception","plans","workflow-routing.md");case"requirements-qa":return L.join(s,"inception","requirements","requirements-analysis-questions.md");case"requirements":return L.join(s,"inception","requirements","requirements.md");case"personas":return L.join(s,"inception","user-stories","personas.md");case"user-stories":return L.join(s,"inception","user-stories","stories.md");case"execution-plan":return L.join(s,"inception","plans","execution-plan.md");case"units-generation":return L.join(s,"inception","application-design","unit-of-work.md");case"unit-dependency":return L.join(s,"inception","application-design","unit-of-work-dependency.md");case"unit-story-map":return L.join(s,"inception","application-design","unit-of-work-story-map.md");default:throw new Error(`Unknown artifact type: ${n}`)}}async function Xn(e,t,n,r,o,s){let i=lt(e,t,n,o,s),a=await ie.pathExists(i);try{await ie.ensureDir(L.dirname(i)),await ie.writeFile(i,r,"utf-8")}catch(c){let l=c;throw l.code==="ENOSPC"?(console.error(`[Artifacts] Failed to write ${n} artifact: Disk full`),console.error("[Artifacts] Please free up disk space and try again."),console.error(`[Artifacts] Path: ${i}`),new Error(`Failed to write ${n} artifact: Disk is full. Please free up space and retry.`)):l.code==="EACCES"||l.code==="EPERM"?(console.error(`[Artifacts] Failed to write ${n} artifact: Permission denied`),console.error(`[Artifacts] Path: ${i}`),new Error(`Failed to write ${n} artifact: Permission denied for ${i}`)):l.code==="EROFS"?(console.error(`[Artifacts] Failed to write ${n} artifact: Read-only filesystem`),console.error(`[Artifacts] Path: ${i}`),new Error(`Failed to write ${n} artifact: Filesystem is read-only`)):(console.error(`[Artifacts] Failed to write ${n} artifact: ${l.message}`),console.error(`[Artifacts] Path: ${i}`),new Error(`Failed to write ${n} artifact: ${l.message}`))}if(a)try{let c=L.join(e,"aidlc-docs",t,"manifest.json"),{cascadeInvalidation:l,loadManifest:u,saveManifest:d,computeChecksum:p}=await Promise.resolve().then(()=>(Z(),vn)),f=u(c);if(f){let m=i.replace(/\\/g,"/"),g=f.artifacts.find(y=>y.path===m||y.path.endsWith(L.basename(i)));if(g){let y=p(i);y&&(g.checksum=y,g.updated_at=new Date().toISOString(),d(c,f)),l(c,g.id)}}}catch(c){console.error("[Artifacts] Cascade invalidation after write failed:",c)}}async function zi(e,t){let n=L.join(e,"aidlc-docs",t,"discovery");await ie.ensureDir(n)}async function Dp(e,t,n){let r=L.join(e,"aidlc-docs",t,"audit.md");await ie.ensureDir(L.dirname(r)),await ie.pathExists(r)?await ie.appendFile(r,`
24
24
  `+n,"utf-8"):await ie.writeFile(r,`# Audit Log
25
25
 
26
- ${n}`,"utf-8")}var L,ie,Ji=U(()=>{"use strict";L=T(require("path"),1),ie=T(X(),1)});var la={};he(la,{captureBaseline:()=>_T,compareAgainstBaseline:()=>ST,writeRegressionReport:()=>vT});async function _T(e,t,n){let r=Yr.default.join(e,"aidlc-docs",t,"construction");await qr.default.ensureDir(r);let o=TT(n),s="",i="";try{s=(0,sf.execSync)(n,{cwd:e,encoding:"utf-8",stdio:"pipe"})}catch(m){let g=m;s=g.stdout??"",i=g.stderr??""}let c=ET(s||i,o),l=c.filter(m=>m.status==="passed").length,u=c.filter(m=>m.status==="failed").length,d=c.filter(m=>m.status==="skipped").length,p={tests:c.map(m=>({name:m.name,filePath:m.filePath,status:m.status,duration_ms:m.duration_ms})),captured_at:new Date().toISOString(),test_command:n,framework:o,total:c.length,passed:l,failed:u,skipped:d},f=Yr.default.join(r,"regression-baseline.json");return await qr.default.writeJson(f,p,{spaces:2}),p}function ST(e,t){let n=new Map;for(let i of e.tests)n.set(i.name,i);let r=[],o=[],s=[];for(let i of t){let a=n.get(i.name);if(!a){i.status==="failed"&&r.push({name:i.name,filePath:i.filePath});continue}(a.status==="passed"||a.status==="skipped")&&i.status==="failed"&&r.push({name:i.name,filePath:i.filePath}),a.status==="failed"&&i.status==="passed"&&o.push({name:i.name,filePath:i.filePath});let c=Math.abs(i.duration_ms-a.duration_ms);c>100&&s.push({name:i.name,before_ms:a.duration_ms,after_ms:i.duration_ms,delta_ms:c})}return{new_failures:r,new_passes:o,timing_changes:s,computed_at:new Date().toISOString()}}async function vT(e,t,n,r){let o=Yr.default.join(e,"aidlc-docs",t,"construction",n,"testing");await qr.default.ensureDir(o);let s=Yr.default.join(o,"regression-report.md"),i=r.failures.map(c=>`| ${c.test_name} | ${c.file_path} | ${c.category} | ${c.rationale} |`).join(`
26
+ ${n}`,"utf-8")}var L,ie,Qi=U(()=>{"use strict";L=b(require("path"),1),ie=b(X(),1)});function pf(){return{current_level:0,total_transitions:0,rejection_count:0,rejection_rate:0,incident_count:0,last_level_change:null,level_history:[],consecutive_rejections:0,transition_history:[]}}function Te(e){try{let t=e||process.cwd(),n=(0,Ko.join)(t,ff);if(!(0,Lt.existsSync)(n))return pf();let r=(0,Lt.readFileSync)(n,"utf-8"),o=JSON.parse(r);return o.consecutive_rejections===void 0&&(o.consecutive_rejections=0),Array.isArray(o.transition_history)||(o.transition_history=[]),o}catch(t){return console.error("Error loading trust state:",t),pf()}}function pa(e,t){try{let n=t||process.cwd(),r=(0,Ko.join)(n,".olympus"),o=(0,Ko.join)(n,ff);(0,Lt.existsSync)(r)||(0,Lt.mkdirSync)(r,{recursive:!0}),(0,Lt.writeFileSync)(o,JSON.stringify(e,null,2),"utf-8")}catch(n){console.error("Error saving trust state:",n)}}function Db(e){return e.total_transitions>=50&&e.rejection_rate<.02&&e.incident_count===0?3:e.total_transitions>=20&&e.rejection_rate<.05?2:e.total_transitions>=10?1:0}function fa(e,t,n,r){let o=e.total_transitions+1,s=n?e.rejection_count+1:e.rejection_count,i=s/o,a=n?e.consecutive_rejections+1:0,c={success:t,rejected:n,metadata:r,timestamp:new Date().toISOString()},l=[...e.transition_history,c].slice(-100),u={...e,total_transitions:o,rejection_count:s,rejection_rate:i,consecutive_rejections:a,transition_history:l},d=Db(u);if(d!==e.current_level){let p={from:e.current_level,to:d,reason:d>e.current_level?"Qualification threshold met":"Metrics degraded",timestamp:new Date().toISOString()};return{...u,current_level:d,last_level_change:p.timestamp,level_history:[...e.level_history,p]}}return u}function mf(e,t){return t>=e}var Lt,Ko,ff,sn=U(()=>{"use strict";Lt=require("fs"),Ko=require("path"),ff=".olympus/trust-state.json"});function ue(e){let t={...e,id:(0,hf.randomUUID)(),timestamp:new Date().toISOString(),verified:!1,verification_count:0,last_useful:new Date().toISOString()},n=t.scope==="global"?pe():_t(t.project_path);Hn(t.project_path);let r=(0,an.join)(n,"discoveries.jsonl");return Gn(r),(0,He.appendFileSync)(r,JSON.stringify(t)+`
27
+ `,"utf-8"),t}function Nb(e){let t=(0,an.join)(pe(),"discoveries.jsonl"),n=_t(e),r=(0,an.join)(n,"discoveries.jsonl"),o=gf(t),s=gf(r),i=[...o,...s],a={technical_insight:0,workaround:0,pattern:0,gotcha:0,performance:0,dependency:0,configuration:0,planning_insight:0,workflow_gate:0,retro_insight:0};for(let l of i)a[l.category]++;let c=[...i].sort((l,u)=>u.verification_count-l.verification_count);return{project_discoveries:s,global_discoveries:o,total_discoveries:i.length,categories:a,most_useful:c.slice(0,5)}}function yf(e,t){let n=(0,an.join)(pe(),"discoveries.jsonl"),r=(0,an.join)(t,".olympus","learning","discoveries.jsonl"),o=s=>{if(!(0,He.existsSync)(s))return!1;let a=(0,He.readFileSync)(s,"utf-8").trim().split(`
28
+ `).filter(u=>u.trim()),c=!1,l=a.map(u=>{try{let d=JSON.parse(u);return d.id===e&&(c=!0,d.verification_count=(d.verification_count||0)+1,d.last_useful=new Date().toISOString()),JSON.stringify(d)}catch{return u}});if(c){let u=(0,an.dirname)(s);(0,He.existsSync)(u)||(0,He.mkdirSync)(u,{recursive:!0}),(0,He.writeFileSync)(s,l.join(`
29
+ `)+`
30
+ `,"utf-8")}return c};o(r)||o(n)}function Jo(e,t=10){let n=Nb(e),r=[...n.project_discoveries,...n.global_discoveries],o=new Date,i=r.filter(a=>a.expires_at?new Date(a.expires_at)>o:!0).map(a=>{let c=(o.getTime()-new Date(a.timestamp).getTime())/864e5,l=Math.max(.1,1-c/90),u=(a.verification_count+1)*l*a.confidence;return{discovery:a,score:u}});return i.sort((a,c)=>c.score-a.score),i.slice(0,t).map(a=>a.discovery)}function gf(e){if(!(0,He.existsSync)(e))return[];try{return(0,He.readFileSync)(e,"utf-8").split(`
31
+ `).filter(n=>n.trim()).map(n=>JSON.parse(n))}catch(t){return console.error(`[Olympus Learning] Failed to read discoveries: ${t}`),[]}}var an,He,hf,Ut=U(()=>{"use strict";an=require("path"),He=require("fs"),hf=require("crypto");we()});function wf(e,t){let n=t||"",r=n?(0,rr.join)(e,"aidlc-docs",n,"manifest.json"):(0,rr.join)(e,"aidlc-docs","manifest.json"),o=W(r),s=Te(e),i={workflowId:"",featureName:"",gateRejections:[],cascadeEvents:[],trustDecreases:[],ciFailureCount:0,totalGates:0,totalRejections:0};if(!o)return i;let a=(o.gate_audit||[]).filter(m=>m.action==="rejected").map(m=>({phase:m.phase,timestamp:m.timestamp,reason:m.reason||null,actor:m.actor})),c=[];for(let m of o.artifacts||[])if(m.statusHistory)for(let g of m.statusHistory)(g.status.toLowerCase().includes("stale")||g.status.toLowerCase().includes("violated"))&&c.push({artifactId:m.id,status:g.status,timestamp:g.timestamp});let l=(s?.level_history||[]).filter(m=>m.to<m.from).map(m=>({from:m.from,to:m.to,reason:m.reason,timestamp:m.timestamp})),u=0,d=n?(0,rr.join)(e,"aidlc-docs",n,"construction"):(0,rr.join)(e,"aidlc-docs","construction");if((0,Wt.existsSync)(d)){let m=(0,Wt.readdirSync)(d,{withFileTypes:!0}).filter(g=>g.isDirectory()&&g.name.startsWith("UNIT-")).map(g=>g.name);for(let g of m){let y=(0,rr.join)(d,g,"validation-report.md");if((0,Wt.existsSync)(y)){let _=(0,Wt.readFileSync)(y,"utf-8").split(`
32
+ `);u+=_.filter(h=>h.toLowerCase().includes("fail")).length}}}let p=(o.gate_audit||[]).length,f=a.length;return{workflowId:o.workflow_id||"",featureName:o.feature_name||"",gateRejections:a,cascadeEvents:c,trustDecreases:l,ciFailureCount:u,totalGates:p,totalRejections:f}}function _f(e){let t=[],n=new Map;for(let r of e.gateRejections){let o=(r.reason||"unspecified").toLowerCase().trim();n.has(o)||n.set(o,[]),n.get(o).push(r)}for(let[r,o]of n.entries()){let s=o.length,i=s>=3?"High":s===2?"Medium":"Low",c=`Gate rejections in ${o.map(u=>u.phase).join(", ")} with reason: "${r}"`,l=s>1?`Review and address recurring gate rejection pattern: "${r}". Consider improving upstream validation or documentation.`:`Address gate rejection: "${r}". Ensure requirements are clear before implementation.`;t.push({description:`Gate rejection pattern: ${r}`,evidence:c,suggestion:l,confidence:i,occurrences:s})}if(e.trustDecreases.length>0){let r=e.trustDecreases.length,o=r>=3?"High":r===2?"Medium":"Low",s=e.trustDecreases.map(i=>`${i.from} \u2192 ${i.to} (${i.reason})`).join("; ");t.push({description:"Trust level decreases detected",evidence:`Trust trajectory: ${s}`,suggestion:"Improve code quality and validation processes to rebuild trust. Consider more thorough review before gate submissions.",confidence:o,occurrences:r})}if(e.cascadeEvents.length>0){let r=e.cascadeEvents.length,o=r>=3?"High":r===2?"Medium":"Low",s=[...new Set(e.cascadeEvents.map(i=>i.artifactId))].join(", ");t.push({description:"Cascade invalidation events",evidence:`${r} invalidation event(s) affecting: ${s}`,suggestion:"Strengthen contract verification and dependency validation to prevent cascading failures. Consider improving artifact stability.",confidence:o,occurrences:r})}return t}var Wt,rr,kf=U(()=>{"use strict";Wt=require("fs"),rr=require("path");Z();sn();Ut()});function Fb(e){return(e.gate_audit||[]).map(t=>({timestamp:t.timestamp,phase:t.phase,action:t.action,actor:t.actor,reason:t.reason??null})).sort((t,n)=>t.timestamp.localeCompare(n.timestamp))}function jb(e){let t=e.artifacts||[],n=e.links||[];return t.filter(o=>o.stage==="intent").map(o=>{let s=n.filter(c=>c.source_id===o.id&&(c.link_type==="derives"||c.link_type==="implements")).map(c=>c.target_id).filter(c=>t.some(l=>l.id===c&&l.stage==="unit")),i=[];for(let c of s){let l=n.filter(u=>u.source_id===c&&(u.link_type==="derives"||u.link_type==="implements")).map(u=>u.target_id).filter(u=>t.some(d=>d.id===u&&d.stage==="code-generation"));i.push(...l)}let a=[...new Set(i.flatMap(c=>{let l=t.find(d=>d.id===c);if(!l)return[];let u=Et.extname(l.path).toLowerCase();return u&&u!==".md"&&u!==".json"?[l.path]:[]}))];return{intentId:o.id,unitIds:s,codeGenerationIds:[...new Set(i)],codeFiles:a}})}function Mb(e){return(e.level_history||[]).map(t=>({from:t.from,to:t.to,reason:t.reason,timestamp:t.timestamp}))}function Lb(e){let t=[];for(let n of e.artifacts||[]){if(!n.statusHistory||n.statusHistory.length<2)continue;let r=n.statusHistory;for(let o=1;o<r.length;o++){let s=r[o-1],i=r[o],a=i.status.toLowerCase();(a.includes("stale")||a.includes("violated"))&&t.push({artifactId:n.id,previousStatus:s.status,newStatus:i.status,reason:n.stale_reason??`Artifact transitioned to ${i.status}`,timestamp:i.timestamp})}}return t.sort((n,r)=>n.timestamp.localeCompare(r.timestamp))}function Sf(e){return{workflowId:e,featureName:"",generatedAt:new Date().toISOString(),timeline:[],traceabilityMatrix:[],trustHistory:[],cascadeEvents:[],retroInsights:[]}}function vf(e,t){try{let n=Et.join(e,"aidlc-docs",t,"manifest.json"),r=W(n);if(!r)return Sf(t);let o=Te(e),s=wf(e,t),a=_f(s).filter(c=>c.confidence==="High"||c.confidence==="Medium").map(c=>c.description);return{workflowId:r.workflow_id,featureName:r.feature_name,generatedAt:new Date().toISOString(),timeline:Fb(r),traceabilityMatrix:jb(r),trustHistory:Mb(o),cascadeEvents:Lb(r),retroInsights:a}}catch(n){return console.error(`Failed to generate audit document for workflow ${t}:`,n),Sf(t)}}function ma(e){let t=[];if(t.push(`# Audit Report: ${e.featureName}`),t.push(""),t.push(`Generated: ${e.generatedAt}`),t.push(`Workflow ID: ${e.workflowId}`),t.push(""),t.push("## Timeline"),t.push(""),e.timeline.length===0)t.push("_No gate decisions recorded._");else{t.push("| Timestamp | Phase | Action | Actor | Reason |"),t.push("|-----------|-------|--------|-------|--------|");for(let n of e.timeline)t.push(`| ${n.timestamp} | ${n.phase} | ${n.action} | ${n.actor} | ${n.reason??"\u2014"} |`)}if(t.push(""),t.push("## Traceability Matrix"),t.push(""),e.traceabilityMatrix.length===0)t.push("_No traceability data available._");else{t.push("| Intent | Units | Code Generation | Code Files |"),t.push("|--------|-------|-----------------|------------|");for(let n of e.traceabilityMatrix){let r=n.unitIds.length>0?n.unitIds.join(", "):"\u2014",o=n.codeGenerationIds.length>0?n.codeGenerationIds.join(", "):"\u2014",s=n.codeFiles.length>0?n.codeFiles.join(", "):"\u2014";t.push(`| ${n.intentId} | ${r} | ${o} | ${s} |`)}}if(t.push(""),t.push("## Trust History"),t.push(""),e.trustHistory.length===0)t.push("_No trust level changes recorded._");else{t.push("| From | To | Reason | Timestamp |"),t.push("|------|----|--------|-----------|");for(let n of e.trustHistory)t.push(`| ${n.from} | ${n.to} | ${n.reason} | ${n.timestamp} |`)}if(t.push(""),t.push("## Cascade Events"),t.push(""),e.cascadeEvents.length===0)t.push("_No cascade invalidation events recorded._");else for(let n of e.cascadeEvents)t.push(`- **${n.artifactId}**: \`${n.previousStatus}\` \u2192 \`${n.newStatus}\` \u2014 ${n.reason} _(${n.timestamp})_`);if(t.push(""),t.push("## Retrospective Insights"),t.push(""),e.retroInsights.length===0)t.push("_No retrospective insights available._");else for(let n of e.retroInsights)t.push(`- ${n}`);return t.push(""),t.join(`
33
+ `)}async function bf(e,t,n){let r=Et.join(e,"aidlc-docs",t),o=Et.join(r,"audit.md"),s=Et.join(r,"manifest.json");try{let i=ma(n);await Xe.ensureDir(r),await Xe.writeFile(o,i,"utf-8"),Ne(s,{id:`audit-${t}`,type:"AUDIT",phase:"operations",stage:"complete",path:o,validation_passed:null,write_complete:!0,checksum:null})}catch(i){console.error(`Failed to write audit artifact for workflow ${t}:`,i)}return o}function zo(e,t,n){try{let r=Et.join(e,"aidlc-docs",t,"audit.md");if(!Xe.existsSync(r)){let s=["# Audit Report","",`Generated: ${new Date().toISOString()}`,`Workflow ID: ${t}`,"","## Timeline","","| Timestamp | Phase | Action | Actor | Reason |","|-----------|-------|--------|-------|--------|",""].join(`
34
+ `);Xe.ensureDirSync(Et.dirname(r)),Xe.writeFileSync(r,s,"utf-8")}let o=`| ${n.timestamp} | ${n.phase} | ${n.action} | ${n.actor} | ${n.reason??"\u2014"} |
35
+ `;Xe.appendFileSync(r,o,"utf-8")}catch(r){console.error(`Failed to append to audit for workflow ${t}:`,r)}}var Xe,Et,ga=U(()=>{"use strict";Xe=b(X(),1),Et=b(require("path"),1);Z();sn();kf()});var ha={};he(ha,{captureBaseline:()=>Ub,compareAgainstBaseline:()=>Wb,writeRegressionReport:()=>Bb});async function Ub(e,t,n){let r=Yr.default.join(e,"aidlc-docs",t,"construction");await qr.default.ensureDir(r);let o=Gb(n),s="",i="";try{s=(0,Ef.execSync)(n,{cwd:e,encoding:"utf-8",stdio:"pipe"})}catch(m){let g=m;s=g.stdout??"",i=g.stderr??""}let c=Hb(s||i,o),l=c.filter(m=>m.status==="passed").length,u=c.filter(m=>m.status==="failed").length,d=c.filter(m=>m.status==="skipped").length,p={tests:c.map(m=>({name:m.name,filePath:m.filePath,status:m.status,duration_ms:m.duration_ms})),captured_at:new Date().toISOString(),test_command:n,framework:o,total:c.length,passed:l,failed:u,skipped:d},f=Yr.default.join(r,"regression-baseline.json");return await qr.default.writeJson(f,p,{spaces:2}),p}function Wb(e,t){let n=new Map;for(let i of e.tests)n.set(i.name,i);let r=[],o=[],s=[];for(let i of t){let a=n.get(i.name);if(!a){i.status==="failed"&&r.push({name:i.name,filePath:i.filePath});continue}(a.status==="passed"||a.status==="skipped")&&i.status==="failed"&&r.push({name:i.name,filePath:i.filePath}),a.status==="failed"&&i.status==="passed"&&o.push({name:i.name,filePath:i.filePath});let c=Math.abs(i.duration_ms-a.duration_ms);c>100&&s.push({name:i.name,before_ms:a.duration_ms,after_ms:i.duration_ms,delta_ms:c})}return{new_failures:r,new_passes:o,timing_changes:s,computed_at:new Date().toISOString()}}async function Bb(e,t,n,r){let o=Yr.default.join(e,"aidlc-docs",t,"construction",n,"testing");await qr.default.ensureDir(o);let s=Yr.default.join(o,"regression-report.md"),i=r.failures.map(c=>`| ${c.test_name} | ${c.file_path} | ${c.category} | ${c.rationale} |`).join(`
27
36
  `),a=`# Regression Report
28
37
 
29
38
  **Workflow ID**: ${r.workflow_id}
@@ -43,20 +52,20 @@ ${n}`,"utf-8")}var L,ie,Ji=U(()=>{"use strict";L=T(require("path"),1),ie=T(X(),1
43
52
  | Test Name | File Path | Category | Rationale |
44
53
  |---|---|---|---|
45
54
  ${i||"| _No failures_ | | | |"}
46
- `;await qr.default.writeFile(s,a,"utf-8")}function TT(e){return e.includes("vitest")?"vitest":e.includes("jest")?"jest":"unknown"}function ET(e,t){if(e.includes('"numPassedTests"'))try{let n=e.indexOf("{");if(n!==-1){let r=JSON.parse(e.slice(n)),o=[];if(Array.isArray(r.testResults))for(let s of r.testResults){let i=s.testFilePath??s.name??"unknown";for(let a of s.assertionResults??[])o.push({name:a.fullName??a.title??"unnamed",filePath:i,status:bT(a.status),duration_ms:a.duration??0})}if(o.length>0)return o}}catch{}return CT(e)}function bT(e){return e==="passed"?"passed":e==="failed"?"failed":"skipped"}function CT(e){let t=e.split(`
47
- `),n=[],r="unknown";for(let o of t){let s=o.trim(),i=s.match(/^(?:FAIL|PASS)\s+(src\S+)/);if(i){r=i[1];continue}let a=[/^[✓√]\s+(.+?)(?:\s+\((\d+)ms\)|\s+(\d+)ms)?$/,/^ok\s+\d+\s+-\s+(.+?)(?:\s+#.*)?(?:\s+(\d+)ms)?$/],c=[/^[✗×]\s+(.+?)(?:\s+\((\d+)ms\)|\s+(\d+)ms)?$/,/^not ok\s+\d+\s+-\s+(.+?)(?:\s+#.*)?(?:\s+(\d+)ms)?$/],l=!1;for(let u of a){let d=s.match(u);if(d){n.push({name:d[1].trim(),filePath:r,status:"passed",duration_ms:of(d[2]??d[3])}),l=!0;break}}if(!l)for(let u of c){let d=s.match(u);if(d){n.push({name:d[1].trim(),filePath:r,status:"failed",duration_ms:of(d[2]??d[3])});break}}}return n}function of(e){if(!e)return 0;let t=parseInt(e,10);return isNaN(t)?0:t}var qr,Yr,sf,ua=U(()=>{"use strict";qr=T(X(),1),Yr=T(require("path"),1),sf=require("child_process")});function cf(e){let t={id:(0,af.randomUUID)(),timestamp:new Date().toISOString(),session_id:e.sessionId,project_path:e.projectPath,event_type:e.success?"success":"revision",agent_used:e.agentName,original_task:e.taskDescription,user_message:`BOLT ${e.boltId} execution ${e.success?"succeeded":"failed"}`,feedback_category:e.success?"praise":"correction",confidence:1,token_usage:e.tokenUsage?{input_tokens:e.tokenUsage.input_tokens,output_tokens:e.tokenUsage.output_tokens,total_tokens:e.tokenUsage.input_tokens+e.tokenUsage.output_tokens,estimated:!0}:void 0};Xt(t)}function lf(e){let t=Co();return Ro(e,t)}var af,Yo=U(()=>{"use strict";af=require("crypto");we()});var Jo={};he(Jo,{generateArchitectureModel:()=>da,getArchitectureContext:()=>DT,initializeGreenfieldArchitectureModel:()=>OT,loadArchitectureModel:()=>pa,saveArchitectureModel:()=>Kr,updateArchitectureModel:()=>$T});function mf(e,t){let n=[],r=/export\s+interface\s+(\w+)\s*(?:<[^{]*>)?\s*\{([^}]*)\}/g,o;for(;(o=r.exec(t))!==null;)n.push({name:o[1],path:e,fields:df(o[2]),exported:!0});let s=/export\s+type\s+(\w+)\s*(?:<[^=]*>)?\s*=\s*\{([^}]*)\}/g;for(;(o=s.exec(t))!==null;)n.push({name:o[1],path:e,fields:df(o[2]),exported:!0});return n}function df(e){let t=[],n=/(\w+)\??:\s*([^;,\n]+)/g,r;for(;(r=n.exec(e))!==null;)t.push({name:r[1].trim(),type:r[2].trim()});return t}function gf(e,t){let n=[],r=/export\s+(?:async\s+)?function\s+(\w+)\s*(<[^(]*)?\(([^)]*)\)\s*(?::\s*([^\n{]+))?/g,o;for(;(o=r.exec(t))!==null;){let s=o[1],i=o[3]?o[3].trim():"",a=o[4]?o[4].trim():"void",l=`${/export\s+async\s+function/.test(o[0])?"async ":""}function ${s}(${i}): ${a}`;n.push({name:s,path:e,signature:l,exported:!0,description:""})}return n}function RT(e){let t="module";return e.name==="services"||e.name.endsWith("-service")?t="service":(e.name==="packages"||e.children.length>3)&&(t="package"),{name:e.name,path:e.path,description:`${e.name} module (${e.fileCount} files)`,type:t,fileCount:e.fileCount}}function xT(e){let t=new Set,n=[];for(let r of e){let o=Ko(r.sourceFile),s=Ko(r.importedModule);if(!o||!s||o===s)continue;let i=`${o}\u2192${s}`;if(!t.has(i)){t.add(i);let a=s.includes("test")||s.includes("spec")?"dev":"import";n.push({source:o,target:s,type:a})}}return n}function Ko(e){let r=e.replace(/\\/g,"/").split("/").filter(Boolean).filter(o=>o!=="."&&o!=="..");return r.length===0?"":r[0]==="src"&&r.length>1?r[1]:r[0]}function hf(e){let t=[];for(let n of e)t.push(n.name),t.push(...hf(n.children));return t}function yf(e){let t=[];for(let n of e)t.push(n.path),t.push(...yf(n.children));return t}function PT(e,t){let n=[],r=hf(e),o=yf(e);return r.some(s=>s==="hooks"||s.endsWith("-hook")||s.endsWith("-hooks"))&&n.push({name:"Hook Pattern",description:"Functions/modules registered as hooks for lifecycle events.",locations:o.filter(s=>s.includes("hooks")).slice(0,5)}),r.some(s=>s==="middleware"||s==="middlewares")&&n.push({name:"Middleware Chain",description:"Layered middleware processing pipeline.",locations:o.filter(s=>s.includes("middleware")).slice(0,5)}),r.some(s=>s==="factories"||s==="factory")&&n.push({name:"Factory Pattern",description:"Factory functions or classes for object creation.",locations:o.filter(s=>s.includes("factor")).slice(0,5)}),r.some(s=>s==="plugins"||s==="registry"||s==="registries")&&n.push({name:"Registry / Plugin Pattern",description:"Central registry enabling pluggable extension points.",locations:o.filter(s=>s.includes("plugin")||s.includes("registr")).slice(0,5)}),t>50&&n.push({name:"Modular Architecture",description:"Code organized into distinct feature modules with clear boundaries.",locations:e.slice(0,3).map(s=>s.path)}),n}async function IT(e,t,n){let r=[],o={".ts":"TypeScript",".tsx":"TypeScript (React)",".js":"JavaScript",".jsx":"JavaScript (React)",".py":"Python",".go":"Go",".rs":"Rust",".java":"Java",".cs":"C#",".rb":"Ruby",".swift":"Swift",".kt":"Kotlin"};for(let[s,i]of Object.entries(t))i>0&&o[s]&&r.push({category:"language",name:o[s]});if(n.some(s=>s.endsWith("package.json")))try{let s=await Lt.readFile(je.join(e,"package.json"),"utf-8"),i=JSON.parse(s),a={...i.dependencies??{},...i.devDependencies??{}},c={react:"React",vue:"Vue.js","@angular/core":"Angular",svelte:"Svelte",express:"Express",fastify:"Fastify",next:"Next.js",nuxt:"Nuxt.js"};for(let[d,p]of Object.entries(c))a[d]&&r.push({category:"framework",name:p,version:a[d]});let l={vitest:"Vitest",jest:"Jest",mocha:"Mocha",pytest:"Pytest"};for(let[d,p]of Object.entries(l))a[d]&&r.push({category:"test",name:p,version:a[d]});let u={typescript:"TypeScript Compiler",esbuild:"esbuild",webpack:"Webpack",vite:"Vite",rollup:"Rollup",turbo:"Turborepo"};for(let[d,p]of Object.entries(u))a[d]&&r.push({category:"tool",name:p,version:a[d]})}catch{}return n.some(s=>s.endsWith("Cargo.toml"))&&r.push({category:"tool",name:"Cargo"}),n.some(s=>s.endsWith("go.mod"))&&r.push({category:"tool",name:"Go Modules"}),r}async function AT(e,t){let n=[],r=[],o=new Set;for(let i of t.entryPoints)o.add(i);for(let i of Object.values(t.largestFilesByDirectory))for(let a of i)o.add(a);let s=[...o].filter(i=>i.endsWith(".ts")||i.endsWith(".tsx")).slice(0,20);for(let i of s){let a=je.isAbsolute(i)?i:je.join(e,i);try{let c=await Lt.readFile(a,"utf-8");n.push(...mf(i,c)),r.push(...gf(i,c))}catch{}}return{dataModels:n,apiSurface:r}}async function OT(e,t,n,r){let o=new Date().toISOString(),s={schemaVersion:pf,generatedAt:o,updatedAt:o,componentInventory:[],dataModels:[],apiSurface:[],dependencyGraph:[],designPatterns:[],technologyStack:n??[],designSystem:r};return await Kr(e,s),s}async function da(e,t,n){let r=new Date().toISOString(),o=t.directoryTree.map(RT),s=xT(t.importGraph),i=await IT(e,t.languageDistribution,t.configFiles),a=PT(t.directoryTree,t.sourceFiles),{dataModels:c,apiSurface:l}=await AT(e,t);if(t.agentsMdEntries&&t.agentsMdEntries.length>0)for(let u of t.agentsMdEntries)for(let d of u.pathDescriptionPairs){let p=o.find(m=>d.path.startsWith(m.path)||m.path.includes(d.path));p&&d.description&&(p.description=d.description);let f=je.dirname(d.path);f!=="."&&!o.some(m=>m.path===f)&&o.push({name:je.basename(f),path:f,description:d.description||"Key file from AGENTS.md",type:"module",fileCount:1})}return{schemaVersion:pf,generatedAt:r,updatedAt:r,componentInventory:o,dataModels:c,apiSurface:l,dependencyGraph:s,designPatterns:a,technologyStack:i,designSystem:n}}async function Kr(e,t){await Lt.ensureDir(je.join(e,".olympus")),await Lt.writeFile(je.join(e,ff),JSON.stringify(t,null,2),"utf-8")}async function pa(e){try{let t=await Lt.readFile(je.join(e,ff),"utf-8");return JSON.parse(t)}catch{return null}}async function $T(e,t){let n=await pa(e);if(!n)return null;let r=[],o=[];for(let a of t){let c=je.isAbsolute(a)?a:je.join(e,a);try{let l=await Lt.readFile(c,"utf-8");r.push(...mf(a,l)),o.push(...gf(a,l))}catch{}}let s=new Set(t),i={...n,updatedAt:new Date().toISOString(),dataModels:[...n.dataModels.filter(a=>!s.has(a.path)),...r],apiSurface:[...n.apiSurface.filter(a=>!s.has(a.path)),...o]};return await Kr(e,i),i}async function DT(e,t){let n=await pa(e);if(!n||t.length===0)return"";let r=new Set(t.map(p=>p.toLowerCase())),o=new Set;for(let p of n.dependencyGraph)r.has(p.source.toLowerCase())&&o.add(p.target.toLowerCase());let s=new Set([...r,...o]),i=n.componentInventory.filter(p=>s.has(p.name.toLowerCase())),a=n.apiSurface.filter(p=>s.has(Ko(p.path).toLowerCase())),c=n.dataModels.filter(p=>s.has(Ko(p.path).toLowerCase())),l=n.dependencyGraph.filter(p=>s.has(p.source.toLowerCase())),u=["## Architecture Context",""];if(i.length>0){u.push("### Components");for(let p of i)u.push(`- **${p.name}** (${p.type}, ${p.fileCount} files): ${p.description}`);u.push("")}if(a.length>0){u.push("### API Surface");for(let p of a.slice(0,10))u.push(`- \`${p.signature}\` in \`${p.path}\``);u.push("")}if(c.length>0){u.push("### Data Models");for(let p of c.slice(0,10)){let f=p.fields.slice(0,3).map(m=>`${m.name}: ${m.type}`).join(", ");u.push(`- **${p.name}**: { ${f}${p.fields.length>3?", ...":""} }`)}u.push("")}if(l.length>0){u.push("### Dependencies");for(let p of l.slice(0,10))u.push(`- ${p.source} \u2192 ${p.target} (${p.type})`);u.push("")}if(n.designSystem&&n.designSystem.detected&&n.designSystem.systems.length>0){u.push("### Design System");for(let p of n.designSystem.systems)u.push(`- **${p.name}** (${p.type}): ${p.path}`);u.push("")}let d=u.join(`
48
- `);return d.length>uf&&(d=d.slice(0,uf)+`
49
- ...(truncated)`),d}var je,Lt,pf,ff,uf,Jr=U(()=>{"use strict";je=T(require("path"),1),Lt=T(X(),1),pf="1.0",ff=".olympus/project-architecture.json",uf=2e3});function kf(e){try{return(0,zo.readFileSync)(e,"utf8").split(`
50
- `).length}catch{return 0}}function jT(e,t){let n=[],r=e.split(`
51
- `),o=0;for(;o<r.length;){let s=r[o],i=/^##\s+(.+)$/.exec(s);if(i){let c=i[1].trim(),l=[];for(o++;o<r.length&&!/^##/.test(r[o]);){let u=r[o].trim();u.length>0&&l.push(u),o++}l.length>0&&n.push({path:c,description:l.join(" ")});continue}let a=/^[-*]\s+\*{0,2}([^*:]+)\*{0,2}:\s*(.+)$/.exec(s);if(a){let c=a[1].trim(),l=a[2].trim();c&&l&&n.push({path:c,description:l})}o++}return{relativeFilePath:t,pathDescriptionPairs:n}}async function MT(e){let t=[];async function n(o,s){try{let i=await rr.readFile(o,"utf8"),a=jT(i,s);a.pathDescriptionPairs.length>0&&t.push(a)}catch{return}}await n(ut.join(e,"AGENTS.md"),"AGENTS.md");let r=[];try{r=await rr.readdir(e,{withFileTypes:!0})}catch{return t}for(let o of r)if(o.isDirectory()&&!o.name.startsWith(".")&&!fa.has(o.name)){let s=ut.join(e,o.name,"AGENTS.md");await n(s,ut.join(o.name,"AGENTS.md").replace(/\\/g,"/"))}return t}function _f(e,t){let n=[],r;if(t===".ts"||t===".tsx"||t===".js"||t===".jsx"){let o=/import\s+(?:.*?\s+from\s+)?['"]([^'"]+)['"]/g;for(;(r=o.exec(e))!==null;)n.push(r[1]);let s=/export\s+(?:.*?\s+from\s+)?['"]([^'"]+)['"]/g;for(;(r=s.exec(e))!==null;)n.push(r[1])}else if(t===".py"){let o=/^import\s+([^\s;#]+)/gm;for(;(r=o.exec(e))!==null;)n.push(r[1]);let s=/^from\s+([^\s;#]+)\s+import/gm;for(;(r=s.exec(e))!==null;)n.push(r[1])}else if(t===".go"){let o=/import\s+"([^"]+)"/g;for(;(r=o.exec(e))!==null;)n.push(r[1]);let s=/^\s+"([^"]+)"/gm;for(;(r=s.exec(e))!==null;)n.push(r[1])}return n}async function bn(e){let t={value:0},n={value:0},r={},o=[],s=[],i={},a=[];async function c(f,m){let g={name:ut.basename(f),path:f,fileCount:0,children:[]},y;try{y=await rr.readdir(f,{withFileTypes:!0})}catch(w){return console.error(`[brownfield-scanner] Cannot read directory ${f}:`,w),g}for(let w of y){if(w.name.startsWith(".")||fa.has(w.name))continue;let k=ut.join(f,w.name);if(w.isDirectory()){let h=await c(k,m);g.fileCount+=h.fileCount,g.children.push(h)}else if(w.isFile()){t.value+=1,g.fileCount+=1;let h=ut.extname(w.name);if(Qo.includes(h)){n.value+=1,r[h]=(r[h]??0)+1,wf.has(w.name)&&s.push(k);let S=m??"(root)";i[S]||(i[S]=[]),i[S].push({file:k,lines:kf(k)});try{let b=(0,zo.readFileSync)(k,"utf8");for(let _ of _f(b,h))o.push({sourceFile:k,importedModule:_})}catch(b){console.error(`[brownfield-scanner] Cannot read file ${k}:`,b)}}}}return g}let l=[];try{l=await rr.readdir(e,{withFileTypes:!0})}catch(f){console.error(`[brownfield-scanner] Cannot read project root ${e}:`,f)}let u=[];for(let f of l){if(f.name.startsWith("."))continue;let m=ut.join(e,f.name);if(f.isDirectory()){if(fa.has(f.name))continue;let g=await c(m,f.name);u.push(g)}else if(f.isFile()){t.value+=1;let g=ut.extname(f.name);if(Qo.includes(g)){n.value+=1,r[g]=(r[g]??0)+1,wf.has(f.name)&&s.push(m),i["(root)"]||(i["(root)"]=[]),i["(root)"].push({file:m,lines:kf(m)});try{let w=(0,zo.readFileSync)(m,"utf8");for(let k of _f(w,g))o.push({sourceFile:m,importedModule:k})}catch(w){console.error(`[brownfield-scanner] Cannot read file ${m}:`,w)}}NT.has(f.name)&&a.push(f.name)}}let d={};for(let[f,m]of Object.entries(i)){let g=m.slice().sort((y,w)=>w.lines-y.lines);d[f]=g.slice(0,3).map(y=>y.file)}let p=await MT(e);return{totalFiles:t.value,sourceFiles:n.value,directoryTree:u,languageDistribution:r,importGraph:o,entryPoints:s,largestFilesByDirectory:d,configFiles:a,...p.length>0?{agentsMdEntries:p}:{}}}function Sf(e,t=20){let n=[],r=new Set;function o(i){r.has(i)||(r.add(i),n.push(i))}if(e.agentsMdEntries&&e.agentsMdEntries.length>0)for(let i of e.agentsMdEntries)for(let a of i.pathDescriptionPairs){let c=a.description.toLowerCase();LT.some(u=>c.includes(u))&&o(a.path)}for(let i of e.entryPoints.slice(0,5))o(i);let s=Object.keys(e.largestFilesByDirectory).slice(0,10);for(let i of s){let a=e.largestFilesByDirectory[i];a&&a.length>0&&o(a[0])}for(let i of e.configFiles.slice(0,5))o(i);return n.slice(0,t)}function vf(e,t,n=15){let r=t.split(/\s+/).map(g=>g.toLowerCase().replace(/[^a-z0-9]/g,"")).filter(g=>g.length>=3&&!FT.has(g));if(r.length===0)return[];let o=new Set(e.importGraph.map(g=>g.sourceFile));for(let g of e.entryPoints)o.add(g);for(let g of Object.values(e.largestFilesByDirectory))for(let y of g)o.add(y);let s=new Map;if(e.agentsMdEntries&&e.agentsMdEntries.length>0)for(let g of e.agentsMdEntries)for(let y of g.pathDescriptionPairs)s.set(y.path,y.description.toLowerCase());let i=new Map;for(let g of e.importGraph){let y=i.get(g.sourceFile)??[];y.push(g.importedModule),i.set(g.sourceFile,y)}function a(g){let y=g.replace(/^\.+\//,"").replace(/\.js$/,"").toLowerCase();return y?Array.from(o).filter(w=>w.replace(/\\/g,"/").toLowerCase().includes(y)):[]}function c(g){let y=g.replace(/\\/g,"/");for(let[w,k]of s)if(y.includes(w)||w.includes(y))return r.filter(h=>k.includes(h)).length;return 0}let l=new Map;for(let g of o){let y=g.replace(/\\/g,"/").toLowerCase(),w=r.filter(h=>y.includes(h)).length,k=c(g)*2;(w>0||k>0)&&l.set(g,w+k)}let u=new Set(l.keys()),d=new Set(u);for(let g of u)for(let y of i.get(g)??[])for(let w of a(y))d.add(w);let p=Array.from(u).sort((g,y)=>(l.get(y)??0)-(l.get(g)??0)),f=[],m=new Set;for(let g of p)m.has(g)||(m.add(g),f.push(g));for(let g of d)m.has(g)||(m.add(g),f.push(g));return f.slice(0,n)}var ut,rr,zo,fa,NT,wf,FT,LT,ma=U(()=>{"use strict";ut=T(require("path"),1),rr=T(require("fs/promises"),1),zo=require("fs");Xo();fa=new Set(["node_modules",".git","dist","build",".olympus","aidlc-docs",".next","__pycache__",".venv","vendor","target"]),NT=new Set(["package.json","tsconfig.json","tsconfig.base.json","pyproject.toml","setup.py","setup.cfg","requirements.txt","Cargo.toml","go.mod","go.sum","Makefile","makefile","Dockerfile","docker-compose.yml","docker-compose.yaml",".eslintrc.json",".eslintrc.js","jest.config.js","jest.config.ts","vite.config.ts","vite.config.js","webpack.config.js","webpack.config.ts","rollup.config.js","rollup.config.ts","babel.config.js","babel.config.json",".babelrc","vitest.config.ts","vitest.config.js","pom.xml","build.gradle","build.gradle.kts","CMakeLists.txt","Gemfile","composer.json"]),wf=new Set(["index.ts","index.tsx","index.js","index.jsx","main.ts","main.tsx","main.js","main.jsx","app.ts","app.tsx","app.js","app.jsx","server.ts","server.js"]),FT=new Set(["the","and","for","are","but","not","you","all","can","had","her","was","one","our","out","day","get","has","him","his","how","its","may","new","now","old","see","two","who","boy","did","she","use","way","add","any","big","end","few","got","let","man","own","say","set","put","too","try","this","that","with","have","from","they","will","been","each","into","many","more","must","need","over","same","such","than","them","then","there","time","very","what","when","where","which","while","also","back","been","call","come","does","even","find","give","good","here","just","know","like","look","make","most","move","only","open","some","take","tell","than","them","thing","think","those","through","want","well","were","your"]);LT=["core","entry","main","critical","primary","central"]});var Cf={};he(Cf,{getChangedFilesSince:()=>ga,getFileLastModified:()=>bf,getGitHeadSha:()=>zr,isFileStale:()=>UT,isGitAvailable:()=>ha});async function zr(e){try{let{stdout:t}=await Zo("git",["rev-parse","HEAD"],{cwd:e,timeout:5e3}),n=t.trim();return n.length>0?n:null}catch{return null}}async function ga(e,t){try{let{stdout:n}=await Zo("git",["diff","--name-only",t],{cwd:e,timeout:1e4});return n.trim().split(`
52
- `).map(r=>r.trim()).filter(r=>r.length>0)}catch{return[]}}async function ha(e){try{return await Zo("git",["status","--porcelain"],{cwd:e,timeout:5e3}),!0}catch{return!1}}async function bf(e,t){try{let{stdout:n}=await Zo("git",["log","-1","--format=%at","--",t],{cwd:e,timeout:5e3}),r=parseInt(n.trim(),10);if(!isNaN(r)&&r>0)return r*1e3}catch(n){}try{let n=await import("fs/promises"),o=(await import("path")).join(e,t);return(await n.stat(o)).mtimeMs}catch{return null}}async function UT(e,t,n=30){let r=await bf(e,t);if(r===null)return!1;let o=Date.now()-r,s=n*24*60*60*1e3;return o>s}var Tf,Ef,Zo,es=U(()=>{"use strict";Tf=require("node:child_process"),Ef=require("node:util"),Zo=(0,Ef.promisify)(Tf.execFile)});function Pf(e){return bt.join(e,WT,GT)}async function ya(e){let t=Pf(e);try{let n=await Cn.readFile(t,"utf-8"),r=JSON.parse(n);return!r.schemaVersion||!r.createdAt?(console.warn("[DiscoveryCache] Manifest missing required fields \u2014 treating as cache miss"),null):r}catch(n){return n instanceof Error&&"code"in n&&n.code==="ENOENT"||console.warn("[DiscoveryCache] Failed to read/parse cache manifest \u2014 treating as cache miss:",n),null}}async function wa(e,t){let n=Pf(e);await Cn.ensureDir(bt.dirname(n)),await Cn.writeFile(n,JSON.stringify(t,null,2),"utf-8")}async function If(e,t,n){if(t.schemaVersion!==xf)return{stale:!0,reason:"schema-version-mismatch"};if(n&&t.toolVersion&&t.toolVersion!==n)return{stale:!0,reason:"tool-version-mismatch"};let r=Date.now()-new Date(t.updatedAt).getTime(),o=BT*24*60*60*1e3;if(r>o)return{stale:!0,reason:"cache-too-old"};if(!await ha(e))return console.warn("[DiscoveryCache] Git unavailable \u2014 staleness check using file timestamps only"),Rf(t);let i=await zr(e);return i===null?(console.warn("[DiscoveryCache] Could not read HEAD SHA \u2014 falling back to timestamps"),Rf(t)):t.gitSha===null?{stale:!0,reason:"no-cached-sha"}:i!==t.gitSha?{stale:!0,reason:"git-sha-changed",changedFiles:await ga(e,t.gitSha)}:{stale:!1}}function Rf(e){let t=e.fileTimestamps;if(!t||Object.keys(t).length===0)return{stale:!0,reason:"no-timestamps"};for(let[n,r]of Object.entries(t)){if(r===0)return{stale:!0,reason:`invalidated:${n}`};try{if(require("fs").statSync(n).mtimeMs!==r)return{stale:!0,reason:`timestamp-changed:${n}`}}catch{return{stale:!0,reason:`file-missing:${n}`}}}return{stale:!1}}async function Af(e,t,n){if(t.length===0)return n;try{let r=new Set(t.map(a=>bt.dirname(bt.resolve(e,a)))),o=await bn(e),s={...n,totalFiles:o.totalFiles,sourceFiles:o.sourceFiles,largestFilesByDirectory:{...n.largestFilesByDirectory},importGraph:n.importGraph.filter(a=>!t.some(c=>a.sourceFile.endsWith(c)||a.importedModule.endsWith(c)))};for(let a of r){let c=bt.relative(e,a);o.largestFilesByDirectory[c]!==void 0?s.largestFilesByDirectory[c]=o.largestFilesByDirectory[c]:delete s.largestFilesByDirectory[c]}let i=o.importGraph.filter(a=>t.some(c=>a.sourceFile.endsWith(c)||a.importedModule.endsWith(c)));return s.importGraph=[...s.importGraph,...i],s}catch(r){return console.error("[DiscoveryCache] Incremental rescan failed \u2014 returning existing result:",r),n}}function Of(e,t,n,r,o){let s=new Date().toISOString();return{schemaVersion:xf,toolVersion:o||"unknown",createdAt:s,updatedAt:s,gitSha:e,fileTimestamps:n,cachedArtifacts:["workspace-scan"],sourceFileCount:t.sourceFiles,agentsMdStatus:r}}var bt,Cn,xf,WT,GT,BT,$f=U(()=>{"use strict";bt=T(require("path"),1),Cn=T(X(),1);es();ma();xf="1.0",WT=bt.join(".olympus","cache"),GT="discovery-cache.json",BT=7});function qT(e){let t=new Set;for(let n of Object.keys(e.languageDistribution)){let r=HT[n];r&&t.add(r)}for(let n of e.configFiles){let r=VT[n];r&&t.add(r)}return Array.from(t)}function YT(e){let t=[];for(let r of e.directoryTree){let o=r.name;o==="src"?t.push("Uses src/ directory for source code"):o==="__tests__"||o==="tests"?t.push("Has dedicated test directory"):o==="packages"?t.push("Monorepo with packages/ directory"):o==="docs"?t.push("Has documentation directory"):o==="lib"&&t.push("Uses lib/ directory for library code")}return Object.entries(e.languageDistribution).filter(([,r])=>r>5).length>1&&t.push("Multi-language project"),t}function Nf(e,t){try{Hn(e);let n=(0,Df.join)(kt(e),"patterns.json"),r=ke(n,null),o=qT(t),s=YT(t),i;r?i={...r,tech_stack:Array.from(new Set([...r.tech_stack,...o])),conventions:Array.from(new Set([...r.conventions,...s])),learned_rules:r.learned_rules||[],common_mistakes:r.common_mistakes||[],last_updated:new Date().toISOString()}:i={project_hash:su(e),project_path:e,tech_stack:o,conventions:s,learned_rules:[],common_mistakes:[],last_updated:new Date().toISOString()},at(n,i)}catch(n){console.error("[Olympus Learning] Failed to write project patterns:",n)}}var Df,HT,VT,Ff=U(()=>{"use strict";Df=require("path");we();we();HT={".ts":"TypeScript",".tsx":"TypeScript",".js":"JavaScript",".jsx":"JavaScript",".py":"Python",".go":"Go",".rs":"Rust",".java":"Java",".c":"C",".cpp":"C++",".cs":"C#",".rb":"Ruby",".swift":"Swift",".kt":"Kotlin",".css":"CSS",".scss":"SCSS",".html":"HTML",".vue":"Vue",".svelte":"Svelte"},VT={"tsconfig.json":"TypeScript","pyproject.toml":"Python","Cargo.toml":"Rust","go.mod":"Go","pom.xml":"Java/Maven","build.gradle":"Java/Gradle","vite.config.ts":"Vite","vite.config.js":"Vite","webpack.config.js":"Webpack","webpack.config.ts":"Webpack","jest.config.js":"Jest","jest.config.ts":"Jest","vitest.config.ts":"Vitest","vitest.config.js":"Vitest","docker-compose.yml":"Docker","docker-compose.yaml":"Docker",Dockerfile:"Docker",".eslintrc.json":"ESLint",".eslintrc.js":"ESLint"}});function JT(e,t){let n=e.split(`
55
+ `;await qr.default.writeFile(s,a,"utf-8")}function Gb(e){return e.includes("vitest")?"vitest":e.includes("jest")?"jest":"unknown"}function Hb(e,t){if(e.includes('"numPassedTests"'))try{let n=e.indexOf("{");if(n!==-1){let r=JSON.parse(e.slice(n)),o=[];if(Array.isArray(r.testResults))for(let s of r.testResults){let i=s.testFilePath??s.name??"unknown";for(let a of s.assertionResults??[])o.push({name:a.fullName??a.title??"unnamed",filePath:i,status:Vb(a.status),duration_ms:a.duration??0})}if(o.length>0)return o}}catch{}return qb(e)}function Vb(e){return e==="passed"?"passed":e==="failed"?"failed":"skipped"}function qb(e){let t=e.split(`
56
+ `),n=[],r="unknown";for(let o of t){let s=o.trim(),i=s.match(/^(?:FAIL|PASS)\s+(src\S+)/);if(i){r=i[1];continue}let a=[/^[✓√]\s+(.+?)(?:\s+\((\d+)ms\)|\s+(\d+)ms)?$/,/^ok\s+\d+\s+-\s+(.+?)(?:\s+#.*)?(?:\s+(\d+)ms)?$/],c=[/^[✗×]\s+(.+?)(?:\s+\((\d+)ms\)|\s+(\d+)ms)?$/,/^not ok\s+\d+\s+-\s+(.+?)(?:\s+#.*)?(?:\s+(\d+)ms)?$/],l=!1;for(let u of a){let d=s.match(u);if(d){n.push({name:d[1].trim(),filePath:r,status:"passed",duration_ms:Tf(d[2]??d[3])}),l=!0;break}}if(!l)for(let u of c){let d=s.match(u);if(d){n.push({name:d[1].trim(),filePath:r,status:"failed",duration_ms:Tf(d[2]??d[3])});break}}}return n}function Tf(e){if(!e)return 0;let t=parseInt(e,10);return isNaN(t)?0:t}var qr,Yr,Ef,ya=U(()=>{"use strict";qr=b(X(),1),Yr=b(require("path"),1),Ef=require("child_process")});function Rf(e){let t={id:(0,Cf.randomUUID)(),timestamp:new Date().toISOString(),session_id:e.sessionId,project_path:e.projectPath,event_type:e.success?"success":"revision",agent_used:e.agentName,original_task:e.taskDescription,user_message:`BOLT ${e.boltId} execution ${e.success?"succeeded":"failed"}`,feedback_category:e.success?"praise":"correction",confidence:1,token_usage:e.tokenUsage?{input_tokens:e.tokenUsage.input_tokens,output_tokens:e.tokenUsage.output_tokens,total_tokens:e.tokenUsage.input_tokens+e.tokenUsage.output_tokens,estimated:!0}:void 0};Xt(t)}function xf(e){let t=Co();return Ro(e,t)}var Cf,Qo=U(()=>{"use strict";Cf=require("crypto");we()});var Zo={};he(Zo,{generateArchitectureModel:()=>wa,getArchitectureContext:()=>eT,initializeGreenfieldArchitectureModel:()=>Xb,loadArchitectureModel:()=>_a,saveArchitectureModel:()=>Kr,updateArchitectureModel:()=>Zb});function $f(e,t){let n=[],r=/export\s+interface\s+(\w+)\s*(?:<[^{]*>)?\s*\{([^}]*)\}/g,o;for(;(o=r.exec(t))!==null;)n.push({name:o[1],path:e,fields:Af(o[2]),exported:!0});let s=/export\s+type\s+(\w+)\s*(?:<[^=]*>)?\s*=\s*\{([^}]*)\}/g;for(;(o=s.exec(t))!==null;)n.push({name:o[1],path:e,fields:Af(o[2]),exported:!0});return n}function Af(e){let t=[],n=/(\w+)\??:\s*([^;,\n]+)/g,r;for(;(r=n.exec(e))!==null;)t.push({name:r[1].trim(),type:r[2].trim()});return t}function Df(e,t){let n=[],r=/export\s+(?:async\s+)?function\s+(\w+)\s*(<[^(]*)?\(([^)]*)\)\s*(?::\s*([^\n{]+))?/g,o;for(;(o=r.exec(t))!==null;){let s=o[1],i=o[3]?o[3].trim():"",a=o[4]?o[4].trim():"void",l=`${/export\s+async\s+function/.test(o[0])?"async ":""}function ${s}(${i}): ${a}`;n.push({name:s,path:e,signature:l,exported:!0,description:""})}return n}function Yb(e){let t="module";return e.name==="services"||e.name.endsWith("-service")?t="service":(e.name==="packages"||e.children.length>3)&&(t="package"),{name:e.name,path:e.path,description:`${e.name} module (${e.fileCount} files)`,type:t,fileCount:e.fileCount}}function Kb(e){let t=new Set,n=[];for(let r of e){let o=Xo(r.sourceFile),s=Xo(r.importedModule);if(!o||!s||o===s)continue;let i=`${o}\u2192${s}`;if(!t.has(i)){t.add(i);let a=s.includes("test")||s.includes("spec")?"dev":"import";n.push({source:o,target:s,type:a})}}return n}function Xo(e){let r=e.replace(/\\/g,"/").split("/").filter(Boolean).filter(o=>o!=="."&&o!=="..");return r.length===0?"":r[0]==="src"&&r.length>1?r[1]:r[0]}function Nf(e){let t=[];for(let n of e)t.push(n.name),t.push(...Nf(n.children));return t}function Ff(e){let t=[];for(let n of e)t.push(n.path),t.push(...Ff(n.children));return t}function Jb(e,t){let n=[],r=Nf(e),o=Ff(e);return r.some(s=>s==="hooks"||s.endsWith("-hook")||s.endsWith("-hooks"))&&n.push({name:"Hook Pattern",description:"Functions/modules registered as hooks for lifecycle events.",locations:o.filter(s=>s.includes("hooks")).slice(0,5)}),r.some(s=>s==="middleware"||s==="middlewares")&&n.push({name:"Middleware Chain",description:"Layered middleware processing pipeline.",locations:o.filter(s=>s.includes("middleware")).slice(0,5)}),r.some(s=>s==="factories"||s==="factory")&&n.push({name:"Factory Pattern",description:"Factory functions or classes for object creation.",locations:o.filter(s=>s.includes("factor")).slice(0,5)}),r.some(s=>s==="plugins"||s==="registry"||s==="registries")&&n.push({name:"Registry / Plugin Pattern",description:"Central registry enabling pluggable extension points.",locations:o.filter(s=>s.includes("plugin")||s.includes("registr")).slice(0,5)}),t>50&&n.push({name:"Modular Architecture",description:"Code organized into distinct feature modules with clear boundaries.",locations:e.slice(0,3).map(s=>s.path)}),n}async function zb(e,t,n){let r=[],o={".ts":"TypeScript",".tsx":"TypeScript (React)",".js":"JavaScript",".jsx":"JavaScript (React)",".py":"Python",".go":"Go",".rs":"Rust",".java":"Java",".cs":"C#",".rb":"Ruby",".swift":"Swift",".kt":"Kotlin"};for(let[s,i]of Object.entries(t))i>0&&o[s]&&r.push({category:"language",name:o[s]});if(n.some(s=>s.endsWith("package.json")))try{let s=await Bt.readFile(je.join(e,"package.json"),"utf-8"),i=JSON.parse(s),a={...i.dependencies??{},...i.devDependencies??{}},c={react:"React",vue:"Vue.js","@angular/core":"Angular",svelte:"Svelte",express:"Express",fastify:"Fastify",next:"Next.js",nuxt:"Nuxt.js"};for(let[d,p]of Object.entries(c))a[d]&&r.push({category:"framework",name:p,version:a[d]});let l={vitest:"Vitest",jest:"Jest",mocha:"Mocha",pytest:"Pytest"};for(let[d,p]of Object.entries(l))a[d]&&r.push({category:"test",name:p,version:a[d]});let u={typescript:"TypeScript Compiler",esbuild:"esbuild",webpack:"Webpack",vite:"Vite",rollup:"Rollup",turbo:"Turborepo"};for(let[d,p]of Object.entries(u))a[d]&&r.push({category:"tool",name:p,version:a[d]})}catch{}return n.some(s=>s.endsWith("Cargo.toml"))&&r.push({category:"tool",name:"Cargo"}),n.some(s=>s.endsWith("go.mod"))&&r.push({category:"tool",name:"Go Modules"}),r}async function Qb(e,t){let n=[],r=[],o=new Set;for(let i of t.entryPoints)o.add(i);for(let i of Object.values(t.largestFilesByDirectory))for(let a of i)o.add(a);let s=[...o].filter(i=>i.endsWith(".ts")||i.endsWith(".tsx")).slice(0,20);for(let i of s){let a=je.isAbsolute(i)?i:je.join(e,i);try{let c=await Bt.readFile(a,"utf-8");n.push(...$f(i,c)),r.push(...Df(i,c))}catch{}}return{dataModels:n,apiSurface:r}}async function Xb(e,t,n,r){let o=new Date().toISOString(),s={schemaVersion:If,generatedAt:o,updatedAt:o,componentInventory:[],dataModels:[],apiSurface:[],dependencyGraph:[],designPatterns:[],technologyStack:n??[],designSystem:r};return await Kr(e,s),s}async function wa(e,t,n){let r=new Date().toISOString(),o=t.directoryTree.map(Yb),s=Kb(t.importGraph),i=await zb(e,t.languageDistribution,t.configFiles),a=Jb(t.directoryTree,t.sourceFiles),{dataModels:c,apiSurface:l}=await Qb(e,t);if(t.agentsMdEntries&&t.agentsMdEntries.length>0)for(let u of t.agentsMdEntries)for(let d of u.pathDescriptionPairs){let p=o.find(m=>d.path.startsWith(m.path)||m.path.includes(d.path));p&&d.description&&(p.description=d.description);let f=je.dirname(d.path);f!=="."&&!o.some(m=>m.path===f)&&o.push({name:je.basename(f),path:f,description:d.description||"Key file from AGENTS.md",type:"module",fileCount:1})}return{schemaVersion:If,generatedAt:r,updatedAt:r,componentInventory:o,dataModels:c,apiSurface:l,dependencyGraph:s,designPatterns:a,technologyStack:i,designSystem:n}}async function Kr(e,t){await Bt.ensureDir(je.join(e,".olympus")),await Bt.writeFile(je.join(e,Of),JSON.stringify(t,null,2),"utf-8")}async function _a(e){try{let t=await Bt.readFile(je.join(e,Of),"utf-8");return JSON.parse(t)}catch{return null}}async function Zb(e,t){let n=await _a(e);if(!n)return null;let r=[],o=[];for(let a of t){let c=je.isAbsolute(a)?a:je.join(e,a);try{let l=await Bt.readFile(c,"utf-8");r.push(...$f(a,l)),o.push(...Df(a,l))}catch{}}let s=new Set(t),i={...n,updatedAt:new Date().toISOString(),dataModels:[...n.dataModels.filter(a=>!s.has(a.path)),...r],apiSurface:[...n.apiSurface.filter(a=>!s.has(a.path)),...o]};return await Kr(e,i),i}async function eT(e,t){let n=await _a(e);if(!n||t.length===0)return"";let r=new Set(t.map(p=>p.toLowerCase())),o=new Set;for(let p of n.dependencyGraph)r.has(p.source.toLowerCase())&&o.add(p.target.toLowerCase());let s=new Set([...r,...o]),i=n.componentInventory.filter(p=>s.has(p.name.toLowerCase())),a=n.apiSurface.filter(p=>s.has(Xo(p.path).toLowerCase())),c=n.dataModels.filter(p=>s.has(Xo(p.path).toLowerCase())),l=n.dependencyGraph.filter(p=>s.has(p.source.toLowerCase())),u=["## Architecture Context",""];if(i.length>0){u.push("### Components");for(let p of i)u.push(`- **${p.name}** (${p.type}, ${p.fileCount} files): ${p.description}`);u.push("")}if(a.length>0){u.push("### API Surface");for(let p of a.slice(0,10))u.push(`- \`${p.signature}\` in \`${p.path}\``);u.push("")}if(c.length>0){u.push("### Data Models");for(let p of c.slice(0,10)){let f=p.fields.slice(0,3).map(m=>`${m.name}: ${m.type}`).join(", ");u.push(`- **${p.name}**: { ${f}${p.fields.length>3?", ...":""} }`)}u.push("")}if(l.length>0){u.push("### Dependencies");for(let p of l.slice(0,10))u.push(`- ${p.source} \u2192 ${p.target} (${p.type})`);u.push("")}if(n.designSystem&&n.designSystem.detected&&n.designSystem.systems.length>0){u.push("### Design System");for(let p of n.designSystem.systems)u.push(`- **${p.name}** (${p.type}): ${p.path}`);u.push("")}let d=u.join(`
57
+ `);return d.length>Pf&&(d=d.slice(0,Pf)+`
58
+ ...(truncated)`),d}var je,Bt,If,Of,Pf,Jr=U(()=>{"use strict";je=b(require("path"),1),Bt=b(X(),1),If="1.0",Of=".olympus/project-architecture.json",Pf=2e3});function Mf(e){try{return(0,es.readFileSync)(e,"utf8").split(`
59
+ `).length}catch{return 0}}function rT(e,t){let n=[],r=e.split(`
60
+ `),o=0;for(;o<r.length;){let s=r[o],i=/^##\s+(.+)$/.exec(s);if(i){let c=i[1].trim(),l=[];for(o++;o<r.length&&!/^##/.test(r[o]);){let u=r[o].trim();u.length>0&&l.push(u),o++}l.length>0&&n.push({path:c,description:l.join(" ")});continue}let a=/^[-*]\s+\*{0,2}([^*:]+)\*{0,2}:\s*(.+)$/.exec(s);if(a){let c=a[1].trim(),l=a[2].trim();c&&l&&n.push({path:c,description:l})}o++}return{relativeFilePath:t,pathDescriptionPairs:n}}async function oT(e){let t=[];async function n(o,s){try{let i=await or.readFile(o,"utf8"),a=rT(i,s);a.pathDescriptionPairs.length>0&&t.push(a)}catch{return}}await n(ut.join(e,"AGENTS.md"),"AGENTS.md");let r=[];try{r=await or.readdir(e,{withFileTypes:!0})}catch{return t}for(let o of r)if(o.isDirectory()&&!o.name.startsWith(".")&&!ka.has(o.name)){let s=ut.join(e,o.name,"AGENTS.md");await n(s,ut.join(o.name,"AGENTS.md").replace(/\\/g,"/"))}return t}function Lf(e,t){let n=[],r;if(t===".ts"||t===".tsx"||t===".js"||t===".jsx"){let o=/import\s+(?:.*?\s+from\s+)?['"]([^'"]+)['"]/g;for(;(r=o.exec(e))!==null;)n.push(r[1]);let s=/export\s+(?:.*?\s+from\s+)?['"]([^'"]+)['"]/g;for(;(r=s.exec(e))!==null;)n.push(r[1])}else if(t===".py"){let o=/^import\s+([^\s;#]+)/gm;for(;(r=o.exec(e))!==null;)n.push(r[1]);let s=/^from\s+([^\s;#]+)\s+import/gm;for(;(r=s.exec(e))!==null;)n.push(r[1])}else if(t===".go"){let o=/import\s+"([^"]+)"/g;for(;(r=o.exec(e))!==null;)n.push(r[1]);let s=/^\s+"([^"]+)"/gm;for(;(r=s.exec(e))!==null;)n.push(r[1])}return n}async function En(e){let t={value:0},n={value:0},r={},o=[],s=[],i={},a=[];async function c(f,m){let g={name:ut.basename(f),path:f,fileCount:0,children:[]},y;try{y=await or.readdir(f,{withFileTypes:!0})}catch(w){return console.error(`[brownfield-scanner] Cannot read directory ${f}:`,w),g}for(let w of y){if(w.name.startsWith(".")||ka.has(w.name))continue;let _=ut.join(f,w.name);if(w.isDirectory()){let h=await c(_,m);g.fileCount+=h.fileCount,g.children.push(h)}else if(w.isFile()){t.value+=1,g.fileCount+=1;let h=ut.extname(w.name);if(ts.includes(h)){n.value+=1,r[h]=(r[h]??0)+1,jf.has(w.name)&&s.push(_);let S=m??"(root)";i[S]||(i[S]=[]),i[S].push({file:_,lines:Mf(_)});try{let E=(0,es.readFileSync)(_,"utf8");for(let k of Lf(E,h))o.push({sourceFile:_,importedModule:k})}catch(E){console.error(`[brownfield-scanner] Cannot read file ${_}:`,E)}}}}return g}let l=[];try{l=await or.readdir(e,{withFileTypes:!0})}catch(f){console.error(`[brownfield-scanner] Cannot read project root ${e}:`,f)}let u=[];for(let f of l){if(f.name.startsWith("."))continue;let m=ut.join(e,f.name);if(f.isDirectory()){if(ka.has(f.name))continue;let g=await c(m,f.name);u.push(g)}else if(f.isFile()){t.value+=1;let g=ut.extname(f.name);if(ts.includes(g)){n.value+=1,r[g]=(r[g]??0)+1,jf.has(f.name)&&s.push(m),i["(root)"]||(i["(root)"]=[]),i["(root)"].push({file:m,lines:Mf(m)});try{let w=(0,es.readFileSync)(m,"utf8");for(let _ of Lf(w,g))o.push({sourceFile:m,importedModule:_})}catch(w){console.error(`[brownfield-scanner] Cannot read file ${m}:`,w)}}tT.has(f.name)&&a.push(f.name)}}let d={};for(let[f,m]of Object.entries(i)){let g=m.slice().sort((y,w)=>w.lines-y.lines);d[f]=g.slice(0,3).map(y=>y.file)}let p=await oT(e);return{totalFiles:t.value,sourceFiles:n.value,directoryTree:u,languageDistribution:r,importGraph:o,entryPoints:s,largestFilesByDirectory:d,configFiles:a,...p.length>0?{agentsMdEntries:p}:{}}}function Uf(e,t=20){let n=[],r=new Set;function o(i){r.has(i)||(r.add(i),n.push(i))}if(e.agentsMdEntries&&e.agentsMdEntries.length>0)for(let i of e.agentsMdEntries)for(let a of i.pathDescriptionPairs){let c=a.description.toLowerCase();sT.some(u=>c.includes(u))&&o(a.path)}for(let i of e.entryPoints.slice(0,5))o(i);let s=Object.keys(e.largestFilesByDirectory).slice(0,10);for(let i of s){let a=e.largestFilesByDirectory[i];a&&a.length>0&&o(a[0])}for(let i of e.configFiles.slice(0,5))o(i);return n.slice(0,t)}function Wf(e,t,n=15){let r=t.split(/\s+/).map(g=>g.toLowerCase().replace(/[^a-z0-9]/g,"")).filter(g=>g.length>=3&&!nT.has(g));if(r.length===0)return[];let o=new Set(e.importGraph.map(g=>g.sourceFile));for(let g of e.entryPoints)o.add(g);for(let g of Object.values(e.largestFilesByDirectory))for(let y of g)o.add(y);let s=new Map;if(e.agentsMdEntries&&e.agentsMdEntries.length>0)for(let g of e.agentsMdEntries)for(let y of g.pathDescriptionPairs)s.set(y.path,y.description.toLowerCase());let i=new Map;for(let g of e.importGraph){let y=i.get(g.sourceFile)??[];y.push(g.importedModule),i.set(g.sourceFile,y)}function a(g){let y=g.replace(/^\.+\//,"").replace(/\.js$/,"").toLowerCase();return y?Array.from(o).filter(w=>w.replace(/\\/g,"/").toLowerCase().includes(y)):[]}function c(g){let y=g.replace(/\\/g,"/");for(let[w,_]of s)if(y.includes(w)||w.includes(y))return r.filter(h=>_.includes(h)).length;return 0}let l=new Map;for(let g of o){let y=g.replace(/\\/g,"/").toLowerCase(),w=r.filter(h=>y.includes(h)).length,_=c(g)*2;(w>0||_>0)&&l.set(g,w+_)}let u=new Set(l.keys()),d=new Set(u);for(let g of u)for(let y of i.get(g)??[])for(let w of a(y))d.add(w);let p=Array.from(u).sort((g,y)=>(l.get(y)??0)-(l.get(g)??0)),f=[],m=new Set;for(let g of p)m.has(g)||(m.add(g),f.push(g));for(let g of d)m.has(g)||(m.add(g),f.push(g));return f.slice(0,n)}var ut,or,es,ka,tT,jf,nT,sT,Sa=U(()=>{"use strict";ut=b(require("path"),1),or=b(require("fs/promises"),1),es=require("fs");ns();ka=new Set(["node_modules",".git","dist","build",".olympus","aidlc-docs",".next","__pycache__",".venv","vendor","target"]),tT=new Set(["package.json","tsconfig.json","tsconfig.base.json","pyproject.toml","setup.py","setup.cfg","requirements.txt","Cargo.toml","go.mod","go.sum","Makefile","makefile","Dockerfile","docker-compose.yml","docker-compose.yaml",".eslintrc.json",".eslintrc.js","jest.config.js","jest.config.ts","vite.config.ts","vite.config.js","webpack.config.js","webpack.config.ts","rollup.config.js","rollup.config.ts","babel.config.js","babel.config.json",".babelrc","vitest.config.ts","vitest.config.js","pom.xml","build.gradle","build.gradle.kts","CMakeLists.txt","Gemfile","composer.json"]),jf=new Set(["index.ts","index.tsx","index.js","index.jsx","main.ts","main.tsx","main.js","main.jsx","app.ts","app.tsx","app.js","app.jsx","server.ts","server.js"]),nT=new Set(["the","and","for","are","but","not","you","all","can","had","her","was","one","our","out","day","get","has","him","his","how","its","may","new","now","old","see","two","who","boy","did","she","use","way","add","any","big","end","few","got","let","man","own","say","set","put","too","try","this","that","with","have","from","they","will","been","each","into","many","more","must","need","over","same","such","than","them","then","there","time","very","what","when","where","which","while","also","back","been","call","come","does","even","find","give","good","here","just","know","like","look","make","most","move","only","open","some","take","tell","than","them","thing","think","those","through","want","well","were","your"]);sT=["core","entry","main","critical","primary","central"]});var Vf={};he(Vf,{getChangedFilesSince:()=>va,getFileLastModified:()=>Hf,getGitHeadSha:()=>zr,isFileStale:()=>iT,isGitAvailable:()=>ba});async function zr(e){try{let{stdout:t}=await rs("git",["rev-parse","HEAD"],{cwd:e,timeout:5e3}),n=t.trim();return n.length>0?n:null}catch{return null}}async function va(e,t){try{let{stdout:n}=await rs("git",["diff","--name-only",t],{cwd:e,timeout:1e4});return n.trim().split(`
61
+ `).map(r=>r.trim()).filter(r=>r.length>0)}catch{return[]}}async function ba(e){try{return await rs("git",["status","--porcelain"],{cwd:e,timeout:5e3}),!0}catch{return!1}}async function Hf(e,t){try{let{stdout:n}=await rs("git",["log","-1","--format=%at","--",t],{cwd:e,timeout:5e3}),r=parseInt(n.trim(),10);if(!isNaN(r)&&r>0)return r*1e3}catch(n){}try{let n=await import("fs/promises"),o=(await import("path")).join(e,t);return(await n.stat(o)).mtimeMs}catch{return null}}async function iT(e,t,n=30){let r=await Hf(e,t);if(r===null)return!1;let o=Date.now()-r,s=n*24*60*60*1e3;return o>s}var Bf,Gf,rs,os=U(()=>{"use strict";Bf=require("node:child_process"),Gf=require("node:util"),rs=(0,Gf.promisify)(Bf.execFile)});function Kf(e){return Ct.join(e,aT,cT)}async function Ta(e){let t=Kf(e);try{let n=await Cn.readFile(t,"utf-8"),r=JSON.parse(n);return!r.schemaVersion||!r.createdAt?(console.warn("[DiscoveryCache] Manifest missing required fields \u2014 treating as cache miss"),null):r}catch(n){return n instanceof Error&&"code"in n&&n.code==="ENOENT"||console.warn("[DiscoveryCache] Failed to read/parse cache manifest \u2014 treating as cache miss:",n),null}}async function Ea(e,t){let n=Kf(e);await Cn.ensureDir(Ct.dirname(n)),await Cn.writeFile(n,JSON.stringify(t,null,2),"utf-8")}async function Jf(e,t,n){if(t.schemaVersion!==Yf)return{stale:!0,reason:"schema-version-mismatch"};if(n&&t.toolVersion&&t.toolVersion!==n)return{stale:!0,reason:"tool-version-mismatch"};let r=Date.now()-new Date(t.updatedAt).getTime(),o=lT*24*60*60*1e3;if(r>o)return{stale:!0,reason:"cache-too-old"};if(!await ba(e))return console.warn("[DiscoveryCache] Git unavailable \u2014 staleness check using file timestamps only"),qf(t);let i=await zr(e);return i===null?(console.warn("[DiscoveryCache] Could not read HEAD SHA \u2014 falling back to timestamps"),qf(t)):t.gitSha===null?{stale:!0,reason:"no-cached-sha"}:i!==t.gitSha?{stale:!0,reason:"git-sha-changed",changedFiles:await va(e,t.gitSha)}:{stale:!1}}function qf(e){let t=e.fileTimestamps;if(!t||Object.keys(t).length===0)return{stale:!0,reason:"no-timestamps"};for(let[n,r]of Object.entries(t)){if(r===0)return{stale:!0,reason:`invalidated:${n}`};try{if(require("fs").statSync(n).mtimeMs!==r)return{stale:!0,reason:`timestamp-changed:${n}`}}catch{return{stale:!0,reason:`file-missing:${n}`}}}return{stale:!1}}async function zf(e,t,n){if(t.length===0)return n;try{let r=new Set(t.map(a=>Ct.dirname(Ct.resolve(e,a)))),o=await En(e),s={...n,totalFiles:o.totalFiles,sourceFiles:o.sourceFiles,largestFilesByDirectory:{...n.largestFilesByDirectory},importGraph:n.importGraph.filter(a=>!t.some(c=>a.sourceFile.endsWith(c)||a.importedModule.endsWith(c)))};for(let a of r){let c=Ct.relative(e,a);o.largestFilesByDirectory[c]!==void 0?s.largestFilesByDirectory[c]=o.largestFilesByDirectory[c]:delete s.largestFilesByDirectory[c]}let i=o.importGraph.filter(a=>t.some(c=>a.sourceFile.endsWith(c)||a.importedModule.endsWith(c)));return s.importGraph=[...s.importGraph,...i],s}catch(r){return console.error("[DiscoveryCache] Incremental rescan failed \u2014 returning existing result:",r),n}}function Qf(e,t,n,r,o){let s=new Date().toISOString();return{schemaVersion:Yf,toolVersion:o||"unknown",createdAt:s,updatedAt:s,gitSha:e,fileTimestamps:n,cachedArtifacts:["workspace-scan"],sourceFileCount:t.sourceFiles,agentsMdStatus:r}}var Ct,Cn,Yf,aT,cT,lT,Xf=U(()=>{"use strict";Ct=b(require("path"),1),Cn=b(X(),1);os();Sa();Yf="1.0",aT=Ct.join(".olympus","cache"),cT="discovery-cache.json",lT=7});function pT(e){let t=new Set;for(let n of Object.keys(e.languageDistribution)){let r=uT[n];r&&t.add(r)}for(let n of e.configFiles){let r=dT[n];r&&t.add(r)}return Array.from(t)}function fT(e){let t=[];for(let r of e.directoryTree){let o=r.name;o==="src"?t.push("Uses src/ directory for source code"):o==="__tests__"||o==="tests"?t.push("Has dedicated test directory"):o==="packages"?t.push("Monorepo with packages/ directory"):o==="docs"?t.push("Has documentation directory"):o==="lib"&&t.push("Uses lib/ directory for library code")}return Object.entries(e.languageDistribution).filter(([,r])=>r>5).length>1&&t.push("Multi-language project"),t}function em(e,t){try{Hn(e);let n=(0,Zf.join)(_t(e),"patterns.json"),r=_e(n,null),o=pT(t),s=fT(t),i;r?i={...r,tech_stack:Array.from(new Set([...r.tech_stack,...o])),conventions:Array.from(new Set([...r.conventions,...s])),learned_rules:r.learned_rules||[],common_mistakes:r.common_mistakes||[],last_updated:new Date().toISOString()}:i={project_hash:lu(e),project_path:e,tech_stack:o,conventions:s,learned_rules:[],common_mistakes:[],last_updated:new Date().toISOString()},at(n,i)}catch(n){console.error("[Olympus Learning] Failed to write project patterns:",n)}}var Zf,uT,dT,tm=U(()=>{"use strict";Zf=require("path");we();we();uT={".ts":"TypeScript",".tsx":"TypeScript",".js":"JavaScript",".jsx":"JavaScript",".py":"Python",".go":"Go",".rs":"Rust",".java":"Java",".c":"C",".cpp":"C++",".cs":"C#",".rb":"Ruby",".swift":"Swift",".kt":"Kotlin",".css":"CSS",".scss":"SCSS",".html":"HTML",".vue":"Vue",".svelte":"Svelte"},dT={"tsconfig.json":"TypeScript","pyproject.toml":"Python","Cargo.toml":"Rust","go.mod":"Go","pom.xml":"Java/Maven","build.gradle":"Java/Gradle","vite.config.ts":"Vite","vite.config.js":"Vite","webpack.config.js":"Webpack","webpack.config.ts":"Webpack","jest.config.js":"Jest","jest.config.ts":"Jest","vitest.config.ts":"Vitest","vitest.config.js":"Vitest","docker-compose.yml":"Docker","docker-compose.yaml":"Docker",Dockerfile:"Docker",".eslintrc.json":"ESLint",".eslintrc.js":"ESLint"}});function gT(e,t){let n=e.split(`
53
62
  `);return n.length<=t?e:n.slice(0,t).join(`
54
63
  `)+`
55
- ... (truncated)`}function Lf(e,t){let n=[],r=" ".repeat(t*2);for(let o of e)n.push(`${r}${o.name}/ (${o.fileCount} files)`),o.children.length>0&&n.push(Lf(o.children,t+1));return n.join(`
56
- `)}function zT(e){try{return(0,Mf.readFileSync)(e,"utf8")}catch{return"(unable to read)"}}function QT(e,t){return Qr.isAbsolute(e)?e:Qr.resolve(t,e)}function jf(e){return e.replace(/\\/g,"/")}function Uf(e){let{projectPath:t,featureName:n,scanResult:r,keyFiles:o}=e,s=Lf(r.directoryTree,0),i=Object.entries(r.languageDistribution).sort((d,p)=>p[1]-d[1]).map(([d,p])=>` ${d}: ${p} files`).join(`
57
- `),a=r.importGraph.slice(0,50).map(d=>` ${jf(d.sourceFile)} -> ${d.importedModule}`).join(`
64
+ ... (truncated)`}function om(e,t){let n=[],r=" ".repeat(t*2);for(let o of e)n.push(`${r}${o.name}/ (${o.fileCount} files)`),o.children.length>0&&n.push(om(o.children,t+1));return n.join(`
65
+ `)}function hT(e){try{return(0,rm.readFileSync)(e,"utf8")}catch{return"(unable to read)"}}function yT(e,t){return Qr.isAbsolute(e)?e:Qr.resolve(t,e)}function nm(e){return e.replace(/\\/g,"/")}function sm(e){let{projectPath:t,featureName:n,scanResult:r,keyFiles:o}=e,s=om(r.directoryTree,0),i=Object.entries(r.languageDistribution).sort((d,p)=>p[1]-d[1]).map(([d,p])=>` ${d}: ${p} files`).join(`
66
+ `),a=r.importGraph.slice(0,50).map(d=>` ${nm(d.sourceFile)} -> ${d.importedModule}`).join(`
58
67
  `),c=r.importGraph.length>50?`
59
- ... (${r.importGraph.length-50} more edges omitted)`:"",l=o.map(d=>{let p=QT(d,t),f=zT(p),m=JT(f,200);return`### ${jf(d)}
68
+ ... (${r.importGraph.length-50} more edges omitted)`:"",l=o.map(d=>{let p=yT(d,t),f=hT(p),m=gT(f,200);return`### ${nm(d)}
60
69
  \`\`\`
61
70
  ${m}
62
71
  \`\`\``}).join(`
@@ -84,9 +93,9 @@ ${l||"(no key files provided)"}
84
93
 
85
94
  Based on the above project structure and source files, produce a Static Code Model.
86
95
 
87
- ${KT}
96
+ ${mT}
88
97
 
89
- Be precise and concise. Each module row should capture the real public exports or primary function signatures where visible. Use the actual file paths from the project.`}var Qr,Mf,KT,Wf=U(()=>{"use strict";Qr=T(require("path"),1),Mf=require("fs");Z();KT=`A Static Code Model must contain these markdown sections:
98
+ Be precise and concise. Each module row should capture the real public exports or primary function signatures where visible. Use the actual file paths from the project.`}var Qr,rm,mT,im=U(()=>{"use strict";Qr=b(require("path"),1),rm=require("fs");Z();mT=`A Static Code Model must contain these markdown sections:
90
99
  ## Modules
91
100
  | Name | Path | Responsibility | Public Interface |
92
101
  |------|------|----------------|------------------|
@@ -102,7 +111,7 @@ Be precise and concise. Each module row should capture the real public exports o
102
111
  (one row per data model)
103
112
 
104
113
  ## Configuration Summary
105
- (paragraph describing configuration approach)`});async function Gf(e){let t=[];try{let n=ka.join(e,"package.json"),r={};try{let s=await _a.promises.readFile(n,"utf-8");r=JSON.parse(s)}catch{return{detected:!1,systems:[]}}let o={...r.dependencies,...r.devDependencies};if(Object.keys(o).length===0)return{detected:!1,systems:[]};for(let[s,i]of Object.entries(XT))if(s.endsWith("-*")){let a=s.slice(0,-2);for(let c of Object.keys(o))if(c.startsWith(a)){t.push({name:i,type:"component-library",path:`node_modules/${c}`,description:`Component library: ${i}`});break}}else s in o&&t.push({name:i,type:"component-library",path:`node_modules/${s}`,description:`Component library: ${i}`});for(let[s,i]of Object.entries(ZT))s in o&&t.push({name:i,type:"css-framework",path:`node_modules/${s}`,description:`CSS framework: ${i}`});for(let s of eE)try{let i=ka.join(e,s);if((await _a.promises.stat(i)).isFile()){let c="theme-config",l="Theme configuration file";s.includes("tokens")?(c="token-file",l="Design tokens file"):s.includes("tailwind")&&(c="css-framework",l="Tailwind CSS configuration"),t.push({name:s,type:c,path:s,description:l})}}catch{}return t.length===0?{detected:!1,systems:[]}:{detected:!0,systems:t}}catch{return{detected:!1,systems:[]}}}var ka,_a,XT,ZT,eE,Bf=U(()=>{"use strict";ka=T(require("path"),1),_a=require("node:fs"),XT={"@mui/material":"Material-UI (MUI)","@chakra-ui/react":"Chakra UI","@mantine/core":"Mantine",antd:"Ant Design","@radix-ui/react-*":"Radix UI",shadcn:"shadcn/ui"},ZT={tailwindcss:"Tailwind CSS",bootstrap:"Bootstrap","styled-components":"styled-components","@emotion/react":"Emotion"},eE=["tailwind.config.ts","tailwind.config.js","tailwind.config.cjs","stitches.config.ts","stitches.config.js","theme.ts","theme.js","theme.config.ts","theme.config.js","tokens.json","design-tokens.json","design-tokens.ts","design-tokens.js"]});async function rE(e){try{let n=Xe.join(e,".olympus","config.json"),r=await dt.readFile(n,"utf-8");return JSON.parse(r).deepinit_threshold??50}catch{return 50}}function oE(){try{let e=Xe.resolve(__dirname,"../../../package.json");return JSON.parse(require("fs").readFileSync(e,"utf-8")).version||"unknown"}catch{return"unknown"}}async function Hf(e){let t=0;try{let n=await dt.readdir(e,{withFileTypes:!0});for(let r of n){if(r.name.startsWith(".")||tE.has(r.name))continue;let o=Xe.join(e,r.name);if(r.isDirectory())t+=await Hf(o);else if(r.isFile()){let s=Xe.extname(r.name);Qo.includes(s)&&t++}}}catch(n){console.error(`Error reading directory ${e}:`,n)}return t}async function Rn(e){let t=await Hf(e);return{isBrownfield:t>=3,sourceFileCount:t}}function sE(e,t){return{"analysis-plan":`# Analysis Plan
114
+ (paragraph describing configuration approach)`});async function am(e){let t=[];try{let n=Ca.join(e,"package.json"),r={};try{let s=await Ra.promises.readFile(n,"utf-8");r=JSON.parse(s)}catch{return{detected:!1,systems:[]}}let o={...r.dependencies,...r.devDependencies};if(Object.keys(o).length===0)return{detected:!1,systems:[]};for(let[s,i]of Object.entries(wT))if(s.endsWith("-*")){let a=s.slice(0,-2);for(let c of Object.keys(o))if(c.startsWith(a)){t.push({name:i,type:"component-library",path:`node_modules/${c}`,description:`Component library: ${i}`});break}}else s in o&&t.push({name:i,type:"component-library",path:`node_modules/${s}`,description:`Component library: ${i}`});for(let[s,i]of Object.entries(_T))s in o&&t.push({name:i,type:"css-framework",path:`node_modules/${s}`,description:`CSS framework: ${i}`});for(let s of kT)try{let i=Ca.join(e,s);if((await Ra.promises.stat(i)).isFile()){let c="theme-config",l="Theme configuration file";s.includes("tokens")?(c="token-file",l="Design tokens file"):s.includes("tailwind")&&(c="css-framework",l="Tailwind CSS configuration"),t.push({name:s,type:c,path:s,description:l})}}catch{}return t.length===0?{detected:!1,systems:[]}:{detected:!0,systems:t}}catch{return{detected:!1,systems:[]}}}var Ca,Ra,wT,_T,kT,cm=U(()=>{"use strict";Ca=b(require("path"),1),Ra=require("node:fs"),wT={"@mui/material":"Material-UI (MUI)","@chakra-ui/react":"Chakra UI","@mantine/core":"Mantine",antd:"Ant Design","@radix-ui/react-*":"Radix UI",shadcn:"shadcn/ui"},_T={tailwindcss:"Tailwind CSS",bootstrap:"Bootstrap","styled-components":"styled-components","@emotion/react":"Emotion"},kT=["tailwind.config.ts","tailwind.config.js","tailwind.config.cjs","stitches.config.ts","stitches.config.js","theme.ts","theme.js","theme.config.ts","theme.config.js","tokens.json","design-tokens.json","design-tokens.ts","design-tokens.js"]});async function bT(e){try{let n=Ze.join(e,".olympus","config.json"),r=await dt.readFile(n,"utf-8");return JSON.parse(r).deepinit_threshold??50}catch{return 50}}function TT(){try{let e=Ze.resolve(__dirname,"../../../package.json");return JSON.parse(require("fs").readFileSync(e,"utf-8")).version||"unknown"}catch{return"unknown"}}async function lm(e){let t=0;try{let n=await dt.readdir(e,{withFileTypes:!0});for(let r of n){if(r.name.startsWith(".")||ST.has(r.name))continue;let o=Ze.join(e,r.name);if(r.isDirectory())t+=await lm(o);else if(r.isFile()){let s=Ze.extname(r.name);ts.includes(s)&&t++}}}catch(n){console.error(`Error reading directory ${e}:`,n)}return t}async function Rn(e){let t=await lm(e);return{isBrownfield:t>=3,sourceFileCount:t}}function ET(e,t){return{"analysis-plan":`# Analysis Plan
106
115
 
107
116
  ## Feature: ${t}
108
117
 
@@ -217,11 +226,11 @@ Be precise and concise. Each module row should capture the real public exports o
217
226
 
218
227
  ## Error Handling Patterns
219
228
  <!-- How errors propagate and are handled -->
220
- `,"workspace-scan":""}[e]}async function Vf(e){let{projectPath:t,workflowId:n,featureName:r,manifestPath:o}=e;try{await Ki(t,n);let s=new Date().toISOString();jt(o,"discovery","in_progress",s);let i=[];for(let h of nE){if(h==="workspace-scan")continue;let v=sE(h,r),S=lt(t,n,h);await Xn(t,n,h,v),i.push(S),Ne(o,{id:`DISCOVERY-${h}`,type:h,phase:"discovery",stage:"intent",path:S,validation_passed:null,write_complete:!0,checksum:null})}let{sourceFileCount:a,isBrownfield:c}=await Rn(t),l;if(c)try{let h,v=e.forceRescan===!0,S=v?null:await ya(t),b=oE(),_=!1;if(S&&!v){let F=await If(t,S,b);if(F.stale)if(F.changedFiles&&F.changedFiles.length>0){let K=lt(t,n,"workspace-scan");try{let V=await dt.readFile(K,"utf-8"),hn=JSON.parse(V),$e=await Af(t,F.changedFiles,hn);$e===hn&&(_=!0),h=$e}catch{h=await bn(t)}}else h=await bn(t);else{let K=lt(t,n,"workspace-scan");try{let V=await dt.readFile(K,"utf-8");h=JSON.parse(V)}catch{h=await bn(t)}}}else h=await bn(t);let j=_&&S?S.gitSha:await zr(t),R=h.agentsMdEntries&&h.agentsMdEntries.length>0?"present":"absent",A=Of(j,h,{},R,b);await wa(t,A),Nf(t,h);let C=Sf(h);if(e.includeFiles&&e.includeFiles.length>0){let F=new Set(C);for(let K of e.includeFiles)F.has(K)||C.push(K)}let $=vf(h,r),N=lt(t,n,"workspace-scan");await Xn(t,n,"workspace-scan",JSON.stringify(h,null,2)),i.push(N),Ne(o,{id:"DISCOVERY-workspace-scan",type:"workspace-scan",phase:"discovery",stage:"intent",path:N,validation_passed:null,write_complete:!0,checksum:null});let E=Uf({projectPath:t,workflowId:n,featureName:r,scanResult:h,keyFiles:C,relevantFiles:$,intentText:r}),M=Xe.join(t,"aidlc-docs",n,"discovery","static-model-prompt.md");await Ki(t,n),await dt.writeFile(M,E,"utf-8"),l={scanResult:h,keyFiles:C,relevantFiles:$,staticModelPrompt:E}}catch(h){console.error("[Discovery] Brownfield scanning failed (non-blocking):",h)}let u;try{u=await Gf(t)}catch{}let d;if(l)try{let h=await da(t,l.scanResult,u);await Kr(t,h),d=!0}catch(h){console.error("[Discovery] Architecture model generation failed (non-blocking):",h),d=!1}let p=!1,f,m=!1,g=!1,y=await rE(t),w=!1;if(l)if(l.scanResult.agentsMdEntries&&l.scanResult.agentsMdEntries.length>0){p=!0,f=l.scanResult.agentsMdEntries.length,m=!1;try{let{isFileStale:h}=await Promise.resolve().then(()=>(es(),Cf));for(let v of l.scanResult.agentsMdEntries)if(await h(t,v.relativeFilePath,30)){w=!0;break}}catch{}w&&(m=!0,g=!0);for(let h of l.scanResult.agentsMdEntries)Ne(o,{id:`DISCOVERY-agents-md-${Xe.basename(Xe.dirname(h.relativeFilePath))||"root"}`,type:"structural-map",phase:"discovery",stage:"intent",path:h.relativeFilePath,validation_passed:null,write_complete:!0,checksum:null})}else m=a>=y;else c&&(m=a>=y);try{let h=lt(t,n,"analysis-plan"),v=await dt.readFile(h,"utf-8"),S=p?`**Status**: Present (${f} file(s) found)${w?" \u2014 **Stale** (>30 days old)":""}
229
+ `,"workspace-scan":""}[e]}async function um(e){let{projectPath:t,workflowId:n,featureName:r,manifestPath:o}=e;try{await zi(t,n);let s=new Date().toISOString();jt(o,"discovery","in_progress",s);let i=[];for(let h of vT){if(h==="workspace-scan")continue;let v=ET(h,r),S=lt(t,n,h);await Xn(t,n,h,v),i.push(S),Ne(o,{id:`DISCOVERY-${h}`,type:h,phase:"discovery",stage:"intent",path:S,validation_passed:null,write_complete:!0,checksum:null})}let{sourceFileCount:a,isBrownfield:c}=await Rn(t),l;if(c)try{let h,v=e.forceRescan===!0,S=v?null:await Ta(t),E=TT(),k=!1;if(S&&!v){let F=await Jf(t,S,E);if(F.stale)if(F.changedFiles&&F.changedFiles.length>0){let K=lt(t,n,"workspace-scan");try{let V=await dt.readFile(K,"utf-8"),hn=JSON.parse(V),$e=await zf(t,F.changedFiles,hn);$e===hn&&(k=!0),h=$e}catch{h=await En(t)}}else h=await En(t);else{let K=lt(t,n,"workspace-scan");try{let V=await dt.readFile(K,"utf-8");h=JSON.parse(V)}catch{h=await En(t)}}}else h=await En(t);let j=k&&S?S.gitSha:await zr(t),R=h.agentsMdEntries&&h.agentsMdEntries.length>0?"present":"absent",O=Qf(j,h,{},R,E);await Ea(t,O),em(t,h);let C=Uf(h);if(e.includeFiles&&e.includeFiles.length>0){let F=new Set(C);for(let K of e.includeFiles)F.has(K)||C.push(K)}let $=Wf(h,r),N=lt(t,n,"workspace-scan");await Xn(t,n,"workspace-scan",JSON.stringify(h,null,2)),i.push(N),Ne(o,{id:"DISCOVERY-workspace-scan",type:"workspace-scan",phase:"discovery",stage:"intent",path:N,validation_passed:null,write_complete:!0,checksum:null});let T=sm({projectPath:t,workflowId:n,featureName:r,scanResult:h,keyFiles:C,relevantFiles:$,intentText:r}),M=Ze.join(t,"aidlc-docs",n,"discovery","static-model-prompt.md");await zi(t,n),await dt.writeFile(M,T,"utf-8"),l={scanResult:h,keyFiles:C,relevantFiles:$,staticModelPrompt:T}}catch(h){console.error("[Discovery] Brownfield scanning failed (non-blocking):",h)}let u;try{u=await am(t)}catch{}let d;if(l)try{let h=await wa(t,l.scanResult,u);await Kr(t,h),d=!0}catch(h){console.error("[Discovery] Architecture model generation failed (non-blocking):",h),d=!1}let p=!1,f,m=!1,g=!1,y=await bT(t),w=!1;if(l)if(l.scanResult.agentsMdEntries&&l.scanResult.agentsMdEntries.length>0){p=!0,f=l.scanResult.agentsMdEntries.length,m=!1;try{let{isFileStale:h}=await Promise.resolve().then(()=>(os(),Vf));for(let v of l.scanResult.agentsMdEntries)if(await h(t,v.relativeFilePath,30)){w=!0;break}}catch{}w&&(m=!0,g=!0);for(let h of l.scanResult.agentsMdEntries)Ne(o,{id:`DISCOVERY-agents-md-${Ze.basename(Ze.dirname(h.relativeFilePath))||"root"}`,type:"structural-map",phase:"discovery",stage:"intent",path:h.relativeFilePath,validation_passed:null,write_complete:!0,checksum:null})}else m=a>=y;else c&&(m=a>=y);try{let h=lt(t,n,"analysis-plan"),v=await dt.readFile(h,"utf-8"),S=p?`**Status**: Present (${f} file(s) found)${w?" \u2014 **Stale** (>30 days old)":""}
221
230
  **Files**:
222
- ${l.scanResult.agentsMdEntries.map(_=>`- \`${_.relativeFilePath}\``).join(`
223
- `)}`:"**Status**: Absent \u2014 no AGENTS.md files found in project",b=v.replace(/## AGENTS\.md Status\n<!-- Populated during brownfield scanning\. Indicates whether AGENTS\.md files were found\. -->/,`## AGENTS.md Status
224
- ${S}`);b!==v&&await dt.writeFile(h,b,"utf-8")}catch{}if(w&&l)try{let h=await ya(t);h&&(h.agentsMdStatus="stale",await wa(t,h))}catch{}try{let h=p?"pre-existing":m?"suggested":"skipped",v=p?`AGENTS.md detected (${f} file(s), stale: ${w})`:"No AGENTS.md files found";await Ip(t,n,`## Discovery \u2014 Deepinit Detection
231
+ ${l.scanResult.agentsMdEntries.map(k=>`- \`${k.relativeFilePath}\``).join(`
232
+ `)}`:"**Status**: Absent \u2014 no AGENTS.md files found in project",E=v.replace(/## AGENTS\.md Status\n<!-- Populated during brownfield scanning\. Indicates whether AGENTS\.md files were found\. -->/,`## AGENTS.md Status
233
+ ${S}`);E!==v&&await dt.writeFile(h,E,"utf-8")}catch{}if(w&&l)try{let h=await Ta(t);h&&(h.agentsMdStatus="stale",await Ea(t,h))}catch{}try{let h=p?"pre-existing":m?"suggested":"skipped",v=p?`AGENTS.md detected (${f} file(s), stale: ${w})`:"No AGENTS.md files found";await Dp(t,n,`## Discovery \u2014 Deepinit Detection
225
234
  **Timestamp**: ${new Date().toISOString()}
226
235
  **Source file count**: ${a}
227
236
  **Deepinit threshold**: ${y}
@@ -229,14 +238,14 @@ ${S}`);b!==v&&await dt.writeFile(h,b,"utf-8")}catch{}if(w&&l)try{let h=await ya(
229
238
  **AGENTS.md**: ${v}
230
239
 
231
240
  ---
232
- `)}catch{}jt(o,"discovery","blocked");let k=await I(t,n);return k&&(k.current_phase="discovery",k.phases.discovery.status="blocked",p&&g?k.deepinit_status="suggested":p?k.deepinit_status="pre-existing":m?k.deepinit_status="suggested":c?k.deepinit_status="skipped":k.deepinit_status="not_applicable",await O(t,k)),{completed:!1,gateRequired:!0,artifactsGenerated:i,sourceFileCount:a,agentsMdDetected:p,agentsMdFileCount:f,agentsMdStale:w,deepinitSuggested:m,deepinitUpdateMode:g,architectureModelGenerated:d,designSystem:u,brownfieldData:l}}catch(s){throw console.error("[Discovery] Error executing discovery phase:",s),new Error(`Discovery phase failed: ${s instanceof Error?s.message:String(s)}`)}}var Xe,dt,Qo,tE,nE,Xo=U(()=>{"use strict";Xe=T(require("path"),1),dt=T(X(),1);Ji();Z();me();ma();$f();es();Ff();Wf();Jr();Bf();Qo=[".ts",".tsx",".js",".jsx",".py",".go",".rs",".java",".c",".cpp",".cs",".rb",".swift",".kt",".css",".scss",".html",".vue",".svelte"],tE=new Set(["node_modules",".git","dist","build",".olympus","aidlc-docs",".next","__pycache__",".venv","vendor","target"]),nE=["analysis-plan","current-state-analysis","regression-baseline","change-impact","static-model","dynamic-model","workspace-scan"]});var zf={};he(zf,{PATHWAY_DISPLAY_NAMES:()=>Yf,WORKFLOW_ROUTING_FORMAT_INSTRUCTIONS:()=>wE,applyPathwayOverride:()=>Kf,buildPathwayAnnouncement:()=>uE,detectPathway:()=>Sa,generatePlanVisualization:()=>Jf,generateWorkflowRouting:()=>Ta,getPathwayDisplayName:()=>va,isPhaseIncluded:()=>os,isStageIncluded:()=>Ea,loadPathwayBehaviors:()=>aE,loadWorkflowRouting:()=>Xr,recordPathwayOverride:()=>dE,writeWorkflowRoutingArtifact:()=>rs});async function aE(e){if(!iE.includes(e))return null;let t=Ut.join(qf.homedir(),".claude","olympus","rules","common","pathway-behaviors.json"),n=Ut.join(process.cwd(),"resources","rules","common","pathway-behaviors.json"),r=s=>or.readFile(s,"utf-8").catch(()=>null),o=await r(t)??await r(n);if(o===null)return null;try{let i=JSON.parse(o)[e];return i?{rules:i.rules,qualityGateChecklist:i.quality_gate_checklist}:null}catch{return console.error("[PathwayBehaviors] Failed to parse pathway-behaviors.json"),null}}async function Sa(e,t){let{isBrownfield:n}=await Rn(e);if(!n)return"greenfield";let r=t.toLowerCase();for(let{pathway:o,keywords:s}of cE)for(let i of s)if(r.includes(i))return o;return"brownfield-enhancement"}function va(e){return Yf[e]??e}function uE(e,t,n){return{detectedPathway:e,displayName:va(e),depthScore:t,sourceFileCount:n,rationale:lE[e]}}function Kf(e,t){let n=t.pathwayType??e.detectedPathway,r=t.depthScore??e.depthScore,o=t.pathwayType!=null||t.depthScore!=null?` (overridden by user: pathway=${t.pathwayType??"unchanged"}, depthScore=${t.depthScore??"unchanged"})`:"";return{detectedPathway:n,displayName:va(n),depthScore:r,sourceFileCount:e.sourceFileCount,rationale:e.rationale+o}}function dE(e,t,n){let r=Kf(t,n);return{original_pathway_type:t.detectedPathway,original_depth_score:t.depthScore,pathway_override:n.pathwayType,depth_override:n.depthScore,pathway_type:r.detectedPathway,depth_score:r.depthScore}}function pE(e){switch(e){case"greenfield":return{discovery:!1,inception:!0,construction:!0,operations:!0};case"brownfield-enhancement":case"brownfield-refactor":case"optimization":return{discovery:!0,inception:!0,construction:!0,operations:!0};case"bugfix":return{discovery:!1,inception:!1,construction:!0,operations:!0}}}function ts(e,t,n){if(!n)switch(e){case"discovery":return t==="greenfield"?"Greenfield project \u2014 no existing codebase to analyse":t==="bugfix"?"Bug fixes skip discovery to reduce overhead":"Not applicable for this pathway";case"inception":return t==="bugfix"?"Bug fixes proceed directly to construction":"Not applicable for this pathway";default:return"Skipped for this pathway"}switch(e){case"discovery":return"Brownfield project requires existing codebase analysis";case"inception":return"Requirements and depth assessment needed before construction";case"construction":return"Core implementation phase";case"operations":return"Deployment and monitoring artifacts required"}}function fE(e,t){switch(e){case"discovery":return["brownfield-scan","analysis"];case"inception":return["workspace-detection","reverse-engineering","requirements-analysis","user-stories","workflow-planning","application-design","units-generation"];case"construction":return t==="bugfix"?["bolt-execution"]:["unit-decomposition","bolt-execution"];case"operations":return["deployment","monitoring"]}}function mE(e,t,n,r){return e==="construction"&&t==="unit-decomposition"&&r==="minimal"?"Skipped \u2014 minimal depth does not require unit decomposition":{"discovery:brownfield-scan":"Scan existing source files for architectural understanding","discovery:analysis":"Analyse change impact and regression risk","inception:intent":"Capture structured problem statement and success criteria","inception:depth-assessment":"Score 6 factors to determine workflow depth","inception:requirements":"Classify non-functional requirements and constraints","inception:workspace-detection":"Auto-detect greenfield/brownfield and determine pathway type","inception:reverse-engineering":"Reverse-engineer existing codebase architecture (brownfield only)","inception:requirements-analysis":"Structured Q&A to capture functional and non-functional requirements","inception:user-stories":"Generate user personas and stories with Given/When/Then acceptance criteria","inception:workflow-planning":"Generate execution plan with Mermaid visualization and live checkboxes","inception:application-design":"High-level component identification, service boundaries, and dependencies","inception:units-generation":"Define units of work with inter-unit dependencies and story mapping","construction:unit-decomposition":"Break intent into implementable units","construction:bolt-execution":"Execute implementation bolts with validation gates","operations:deployment":"Generate deployment guide and release notes","operations:monitoring":"Configure monitoring, runbook, and observability"}[`${e}:${t}`]??"Standard stage for this phase"}async function Ta(e){let{pathwayType:t,depthAssessment:n,sourceFileCount:r}=e,{recommended_depth:o,total_score:s,risk_tier:i}=n,a=pE(t),c={discovery:{included:a.discovery,rationale:ts("discovery",t,a.discovery)},inception:{included:a.inception,rationale:ts("inception",t,a.inception)},construction:{included:a.construction,rationale:ts("construction",t,a.construction)},operations:{included:a.operations,rationale:ts("operations",t,a.operations)}},l=["discovery","inception","construction","operations"],u=[];for(let f of l)if(a[f])for(let m of fE(f,t)){let g=f==="construction"&&m==="unit-decomposition",y=f==="inception"&&m==="reverse-engineering",w=f==="inception"&&m==="user-stories",k=f==="inception"&&m==="application-design",h=f==="inception"&&m==="units-generation",v=!0;g&&o==="minimal"&&(v=!1),y&&t==="greenfield"&&(v=!1),(w||k)&&(t==="bugfix"||t==="optimization")&&(v=!1),h&&o==="minimal"&&(v=!1),u.push({phase:f,stage:m,included:v,rationale:mE(f,m,t,o)})}let d;if(t==="bugfix")d=1;else switch(o){case"minimal":d=1;break;case"standard":d=Math.min(10,Math.max(1,Math.ceil(r/50)));break;case"comprehensive":d=Math.min(20,Math.max(2,Math.ceil(r/25)));break}let p=s<=10?"LOW":s<=20?"MEDIUM":"HIGH";return{pathway:t,risk_assessment:p,risk_tier:i.tier,phases:c,stages:u,estimated_code_generations:d,estimated_depth:o,generated_at:new Date().toISOString(),approved_at:null,approved_by:null}}function gE(e,t){let r=["discovery","inception","construction","operations"].map(s=>{let{included:i,rationale:a}=t.phases[s];return`| ${s} | ${i?"yes":"no"} | ${a} |`}).join(`
241
+ `)}catch{}jt(o,"discovery","blocked");let _=await I(t,n);return _&&(_.current_phase="discovery",_.phases.discovery.status="blocked",p&&g?_.deepinit_status="suggested":p?_.deepinit_status="pre-existing":m?_.deepinit_status="suggested":c?_.deepinit_status="skipped":_.deepinit_status="not_applicable",await A(t,_)),{completed:!1,gateRequired:!0,artifactsGenerated:i,sourceFileCount:a,agentsMdDetected:p,agentsMdFileCount:f,agentsMdStale:w,deepinitSuggested:m,deepinitUpdateMode:g,architectureModelGenerated:d,designSystem:u,brownfieldData:l}}catch(s){throw console.error("[Discovery] Error executing discovery phase:",s),new Error(`Discovery phase failed: ${s instanceof Error?s.message:String(s)}`)}}var Ze,dt,ts,ST,vT,ns=U(()=>{"use strict";Ze=b(require("path"),1),dt=b(X(),1);Qi();Z();le();Sa();Xf();os();tm();im();Jr();cm();ts=[".ts",".tsx",".js",".jsx",".py",".go",".rs",".java",".c",".cpp",".cs",".rb",".swift",".kt",".css",".scss",".html",".vue",".svelte"],ST=new Set(["node_modules",".git","dist","build",".olympus","aidlc-docs",".next","__pycache__",".venv","vendor","target"]),vT=["analysis-plan","current-state-analysis","regression-baseline","change-impact","static-model","dynamic-model","workspace-scan"]});var gm={};he(gm,{PATHWAY_DISPLAY_NAMES:()=>pm,WORKFLOW_ROUTING_FORMAT_INSTRUCTIONS:()=>MT,applyPathwayOverride:()=>fm,buildPathwayAnnouncement:()=>AT,detectPathway:()=>xa,generatePlanVisualization:()=>mm,generateWorkflowRouting:()=>Aa,getPathwayDisplayName:()=>Pa,isPhaseIncluded:()=>cs,isStageIncluded:()=>Ia,loadPathwayBehaviors:()=>RT,loadWorkflowRouting:()=>Xr,recordPathwayOverride:()=>IT,writeWorkflowRoutingArtifact:()=>as});async function RT(e){if(!CT.includes(e))return null;let t=Gt.join(dm.homedir(),".claude","olympus","rules","common","pathway-behaviors.json"),n=Gt.join(process.cwd(),"resources","rules","common","pathway-behaviors.json"),r=s=>sr.readFile(s,"utf-8").catch(()=>null),o=await r(t)??await r(n);if(o===null)return null;try{let i=JSON.parse(o)[e];return i?{rules:i.rules,qualityGateChecklist:i.quality_gate_checklist}:null}catch{return console.error("[PathwayBehaviors] Failed to parse pathway-behaviors.json"),null}}async function xa(e,t){let{isBrownfield:n}=await Rn(e);if(!n)return"greenfield";let r=t.toLowerCase();for(let{pathway:o,keywords:s}of xT)for(let i of s)if(r.includes(i))return o;return"brownfield-enhancement"}function Pa(e){return pm[e]??e}function AT(e,t,n){return{detectedPathway:e,displayName:Pa(e),depthScore:t,sourceFileCount:n,rationale:PT[e]}}function fm(e,t){let n=t.pathwayType??e.detectedPathway,r=t.depthScore??e.depthScore,o=t.pathwayType!=null||t.depthScore!=null?` (overridden by user: pathway=${t.pathwayType??"unchanged"}, depthScore=${t.depthScore??"unchanged"})`:"";return{detectedPathway:n,displayName:Pa(n),depthScore:r,sourceFileCount:e.sourceFileCount,rationale:e.rationale+o}}function IT(e,t,n){let r=fm(t,n);return{original_pathway_type:t.detectedPathway,original_depth_score:t.depthScore,pathway_override:n.pathwayType,depth_override:n.depthScore,pathway_type:r.detectedPathway,depth_score:r.depthScore}}function OT(e){switch(e){case"greenfield":return{discovery:!1,inception:!0,construction:!0,operations:!0};case"brownfield-enhancement":case"brownfield-refactor":case"optimization":return{discovery:!0,inception:!0,construction:!0,operations:!0};case"bugfix":return{discovery:!1,inception:!1,construction:!0,operations:!0}}}function ss(e,t,n){if(!n)switch(e){case"discovery":return t==="greenfield"?"Greenfield project \u2014 no existing codebase to analyse":t==="bugfix"?"Bug fixes skip discovery to reduce overhead":"Not applicable for this pathway";case"inception":return t==="bugfix"?"Bug fixes proceed directly to construction":"Not applicable for this pathway";default:return"Skipped for this pathway"}switch(e){case"discovery":return"Brownfield project requires existing codebase analysis";case"inception":return"Requirements and depth assessment needed before construction";case"construction":return"Core implementation phase";case"operations":return"Deployment and monitoring artifacts required"}}function $T(e,t){switch(e){case"discovery":return["brownfield-scan","analysis"];case"inception":return["workspace-detection","reverse-engineering","requirements-analysis","user-stories","workflow-planning","application-design","units-generation"];case"construction":return t==="bugfix"?["bolt-execution"]:["unit-decomposition","bolt-execution"];case"operations":return["deployment","monitoring"]}}function DT(e,t,n,r){return e==="construction"&&t==="unit-decomposition"&&r==="minimal"?"Skipped \u2014 minimal depth does not require unit decomposition":{"discovery:brownfield-scan":"Scan existing source files for architectural understanding","discovery:analysis":"Analyse change impact and regression risk","inception:intent":"Capture structured problem statement and success criteria","inception:depth-assessment":"Score 6 factors to determine workflow depth","inception:requirements":"Classify non-functional requirements and constraints","inception:workspace-detection":"Auto-detect greenfield/brownfield and determine pathway type","inception:reverse-engineering":"Reverse-engineer existing codebase architecture (brownfield only)","inception:requirements-analysis":"Structured Q&A to capture functional and non-functional requirements","inception:user-stories":"Generate user personas and stories with Given/When/Then acceptance criteria","inception:workflow-planning":"Generate execution plan with Mermaid visualization and live checkboxes","inception:application-design":"High-level component identification, service boundaries, and dependencies","inception:units-generation":"Define units of work with inter-unit dependencies and story mapping","construction:unit-decomposition":"Break intent into implementable units","construction:bolt-execution":"Execute implementation bolts with validation gates","operations:deployment":"Generate deployment guide and release notes","operations:monitoring":"Configure monitoring, runbook, and observability"}[`${e}:${t}`]??"Standard stage for this phase"}async function Aa(e){let{pathwayType:t,depthAssessment:n,sourceFileCount:r}=e,{recommended_depth:o,total_score:s,risk_tier:i}=n,a=OT(t),c={discovery:{included:a.discovery,rationale:ss("discovery",t,a.discovery)},inception:{included:a.inception,rationale:ss("inception",t,a.inception)},construction:{included:a.construction,rationale:ss("construction",t,a.construction)},operations:{included:a.operations,rationale:ss("operations",t,a.operations)}},l=["discovery","inception","construction","operations"],u=[];for(let f of l)if(a[f])for(let m of $T(f,t)){let g=f==="construction"&&m==="unit-decomposition",y=f==="inception"&&m==="reverse-engineering",w=f==="inception"&&m==="user-stories",_=f==="inception"&&m==="application-design",h=f==="inception"&&m==="units-generation",v=!0;g&&o==="minimal"&&(v=!1),y&&t==="greenfield"&&(v=!1),(w||_)&&(t==="bugfix"||t==="optimization")&&(v=!1),h&&o==="minimal"&&(v=!1),u.push({phase:f,stage:m,included:v,rationale:DT(f,m,t,o)})}let d;if(t==="bugfix")d=1;else switch(o){case"minimal":d=1;break;case"standard":d=Math.min(10,Math.max(1,Math.ceil(r/50)));break;case"comprehensive":d=Math.min(20,Math.max(2,Math.ceil(r/25)));break}let p=s<=10?"LOW":s<=20?"MEDIUM":"HIGH";return{pathway:t,risk_assessment:p,risk_tier:i.tier,phases:c,stages:u,estimated_bolts:d,estimated_depth:o,generated_at:new Date().toISOString(),approved_at:null,approved_by:null}}function NT(e,t){let r=["discovery","inception","construction","operations"].map(s=>{let{included:i,rationale:a}=t.phases[s];return`| ${s} | ${i?"yes":"no"} | ${a} |`}).join(`
233
242
  `),o=t.stages.map((s,i)=>`| ${i+1} | ${s.phase} | ${s.stage} | ${s.included?"yes":"no"} | ${s.rationale} |`).join(`
234
243
  `);return`# Workflow Routing: ${e}
235
244
 
236
245
  **Pathway:** ${t.pathway}
237
246
  **Risk Assessment:** ${t.risk_assessment}
238
247
  **Risk Tier:** ${t.risk_tier}
239
- **Estimated Code Generations:** ${t.estimated_code_generations}
248
+ **Estimated Bolts:** ${t.estimated_bolts}
240
249
  **Estimated Depth:** ${t.estimated_depth}
241
250
  **Generated:** ${t.generated_at}
242
251
  **Approved:** ${t.approved_at??"Pending"}
@@ -252,25 +261,25 @@ ${r}
252
261
  | # | Phase | Stage | Included | Rationale |
253
262
  |---|-------|-------|----------|-----------|
254
263
  ${o}
255
- `}async function rs(e,t,n){let r=Ut.join(e,"aidlc-docs",t,"inception","plans"),o=Ut.join(r,"workflow-routing.md"),s=Ut.posix.join("aidlc-docs",t,"inception","plans","workflow-routing.md");try{await or.mkdir(r,{recursive:!0});let a=gE(t,n),c=Jf(n),l=a+`
264
+ `}async function as(e,t,n){let r=Gt.join(e,"aidlc-docs",t,"inception","plans"),o=Gt.join(r,"workflow-routing.md"),s=Gt.posix.join("aidlc-docs",t,"inception","plans","workflow-routing.md");try{await sr.mkdir(r,{recursive:!0});let a=NT(t,n),c=mm(n),l=a+`
256
265
  ## Execution Plan Visualization
257
266
 
258
267
  `+c+`
259
- `;await or.writeFile(o,l,"utf-8")}catch(a){throw console.error("[WorkflowRouting] Failed to write artifact:",a),a}let i=Ut.join(e,"aidlc-docs",t,"manifest.json");return Ne(i,{id:`WORKFLOW-ROUTING-${t}`,type:"WORKFLOW_ROUTING",phase:"inception",stage:"intent",path:s,validation_passed:!0,write_complete:!0,checksum:null}),s}function hE(e){let t={},n=e.match(/## Phase Overview[\s\S]*?\n\|[-| ]+\|\n([\s\S]*?)(?=\n## |\n# |$)/);if(!n)return t;for(let r of n[1].trim().split(`
260
- `)){let o=r.split("|").map(s=>s.trim()).filter(Boolean);if(o.length>=3){let[s,i,...a]=o;t[s]={included:i.toLowerCase()==="yes",rationale:a.join(" | ")}}}return t}function yE(e){let t=[],n=e.match(/## Stage Details[\s\S]*?\n\|[-| ]+\|\n([\s\S]*?)(?=\n## |\n# |$)/);if(!n)return t;for(let r of n[1].trim().split(`
261
- `)){let o=r.split("|").map(s=>s.trim()).filter(Boolean);if(o.length>=5){let[s,i,a,c,...l]=o;t.push({phase:i,stage:a,included:c.toLowerCase()==="yes",rationale:l.join(" | ")})}}return t}function Xr(e,t){let n=Ut.join(e,"aidlc-docs",t,"inception","plans","workflow-routing.md");if(!(0,ns.existsSync)(n))return null;let r;try{r=(0,ns.readFileSync)(n,"utf-8")}catch(o){return console.error("[WorkflowRouting] Failed to read artifact:",o),null}try{let o=r.match(/\*\*Pathway:\*\*\s*(.+)/),s=r.match(/\*\*Risk Assessment:\*\*\s*(.+)/),i=r.match(/\*\*Risk Tier:\*\*\s*(.+)/),a=r.match(/\*\*Estimated Code Generations:\*\*\s*(\d+)/),c=r.match(/\*\*Estimated Depth:\*\*\s*(.+)/),l=r.match(/\*\*Generated:\*\*\s*(.+)/),u=r.match(/\*\*Approved:\*\*\s*(.+)/);if(!o||!s||!i||!a||!c||!l)return console.error("[WorkflowRouting] Missing required header fields"),null;let d=u?u[1].trim():"Pending",p=hE(r);return{pathway:o[1].trim(),risk_assessment:s[1].trim(),risk_tier:parseInt(i[1].trim(),10),estimated_code_generations:parseInt(a[1].trim(),10),estimated_depth:c[1].trim(),generated_at:l[1].trim(),approved_at:d==="Pending"?null:d,approved_by:null,phases:{discovery:p.discovery??{included:!0,rationale:""},inception:p.inception??{included:!0,rationale:""},construction:p.construction??{included:!0,rationale:""},operations:p.operations??{included:!0,rationale:""}},stages:yE(r)}}catch(o){return console.error("[WorkflowRouting] Failed to parse artifact:",o),null}}function os(e,t){return e.phases[t]?.included??!0}function Ea(e,t,n){return e.stages.find(o=>o.phase===t&&o.stage===n)?.included??!0}function Jf(e){let t=[];t.push("```mermaid"),t.push("flowchart TD"),t.push(""),t.push(" classDef execute fill:#4CAF50,color:#fff,stroke:#388E3C"),t.push(" classDef skip fill:#BDBDBD,color:#424242,stroke:#9E9E9E"),t.push(" classDef conditional fill:#FFA726,color:#fff,stroke:#F57C00"),t.push("");let n=["discovery","inception","construction","operations"];for(let r of n){let o=e.phases[r],s=r.charAt(0).toUpperCase()+r.slice(1);if(o.included){t.push(` subgraph ${s}["${s} Phase"]`);let i=e.stages.filter(c=>c.phase===r);for(let c of i){let l=`${r}_${c.stage.replace(/-/g,"_")}`,u=c.stage.replace(/-/g," ");c.included?(t.push(` ${l}["${u}"]`),t.push(` class ${l} execute`)):(t.push(` ${l}["${u} (SKIP)"]`),t.push(` class ${l} skip`))}let a=i.map(c=>`${r}_${c.stage.replace(/-/g,"_")}`);for(let c=0;c<a.length-1;c++)t.push(` ${a[c]} --> ${a[c+1]}`);t.push(" end")}else{let i=`${r}_skip`;t.push(` ${i}["${s} (SKIPPED)"]`),t.push(` class ${i} skip`)}t.push("")}for(let r=0;r<n.length-1;r++){let o=n[r],s=n[r+1],i=e.stages.filter(p=>p.phase===o),a=e.stages.filter(p=>p.phase===s),c=e.phases[o].included,l=e.phases[s].included,u,d;c&&i.length>0?u=`${o}_${i[i.length-1].stage.replace(/-/g,"_")}`:u=`${o}_skip`,l&&a.length>0?d=`${s}_${a[0].stage.replace(/-/g,"_")}`:d=`${s}_skip`,!c||!l?t.push(` ${u} -.-> ${d}`):t.push(` ${u} --> ${d}`)}return t.push("```"),t.join(`
262
- `)}var Ut,or,ns,qf,iE,cE,lE,Yf,wE,ss=U(()=>{"use strict";Ut=T(require("path"),1),or=T(require("fs/promises"),1),ns=require("fs"),qf=T(require("os"),1);Xo();Z();iE=["bugfix","optimization"];cE=[{pathway:"bugfix",keywords:["fix","bug","broken","regression","error","crash","issue","defect","patch"]},{pathway:"optimization",keywords:["optimize","performance","speed","cache","reduce","improve latency","memory","bottleneck"]},{pathway:"brownfield-refactor",keywords:["refactor","restructure","migrate","rewrite","reorganize","modernize","upgrade"]},{pathway:"brownfield-enhancement",keywords:["add","new","feature","implement","integrate","extend","support"]}];lE={greenfield:"No existing source files detected \u2014 greenfield project.",bugfix:"Intent keywords matched 'fix', 'bug', 'broken', 'regression', 'error', 'crash', 'issue', 'defect', or 'patch' \u2192 bugfix pathway.",optimization:"Intent keywords matched 'optimize', 'performance', 'speed', 'cache', 'reduce', 'improve latency', 'memory', or 'bottleneck' \u2192 optimization pathway.","brownfield-refactor":"Intent keywords matched 'refactor', 'restructure', 'migrate', 'rewrite', 'reorganize', 'modernize', or 'upgrade' \u2192 brownfield-refactor pathway.","brownfield-enhancement":"Intent keywords matched 'add', 'new', 'feature', 'implement', 'integrate', 'extend', or 'support' (or no keywords matched \u2014 default brownfield pathway)."},Yf={greenfield:"Greenfield","brownfield-enhancement":"Enhancement","brownfield-refactor":"Refactor",bugfix:"Bug Fix",optimization:"Optimization"};wE=`A Workflow Routing document must contain:
263
- 1. A header block with: Pathway, Risk Assessment, Risk Tier, Estimated Code Generations, Estimated Depth, Generated date, Approved date
268
+ `;await sr.writeFile(o,l,"utf-8")}catch(a){throw console.error("[WorkflowRouting] Failed to write artifact:",a),a}let i=Gt.join(e,"aidlc-docs",t,"manifest.json");return Ne(i,{id:`WORKFLOW-ROUTING-${t}`,type:"WORKFLOW_ROUTING",phase:"inception",stage:"intent",path:s,validation_passed:!0,write_complete:!0,checksum:null}),s}function FT(e){let t={},n=e.match(/## Phase Overview[\s\S]*?\n\|[-| ]+\|\n([\s\S]*?)(?=\n## |\n# |$)/);if(!n)return t;for(let r of n[1].trim().split(`
269
+ `)){let o=r.split("|").map(s=>s.trim()).filter(Boolean);if(o.length>=3){let[s,i,...a]=o;t[s]={included:i.toLowerCase()==="yes",rationale:a.join(" | ")}}}return t}function jT(e){let t=[],n=e.match(/## Stage Details[\s\S]*?\n\|[-| ]+\|\n([\s\S]*?)(?=\n## |\n# |$)/);if(!n)return t;for(let r of n[1].trim().split(`
270
+ `)){let o=r.split("|").map(s=>s.trim()).filter(Boolean);if(o.length>=5){let[s,i,a,c,...l]=o;t.push({phase:i,stage:a,included:c.toLowerCase()==="yes",rationale:l.join(" | ")})}}return t}function Xr(e,t){let n=Gt.join(e,"aidlc-docs",t,"inception","plans","workflow-routing.md");if(!(0,is.existsSync)(n))return null;let r;try{r=(0,is.readFileSync)(n,"utf-8")}catch(o){return console.error("[WorkflowRouting] Failed to read artifact:",o),null}try{let o=r.match(/\*\*Pathway:\*\*\s*(.+)/),s=r.match(/\*\*Risk Assessment:\*\*\s*(.+)/),i=r.match(/\*\*Risk Tier:\*\*\s*(.+)/),a=r.match(/\*\*Estimated (?:Bolts|Code Generations):\*\*\s*(\d+)/),c=r.match(/\*\*Estimated Depth:\*\*\s*(.+)/),l=r.match(/\*\*Generated:\*\*\s*(.+)/),u=r.match(/\*\*Approved:\*\*\s*(.+)/);if(!o||!s||!i||!a||!c||!l)return console.error("[WorkflowRouting] Missing required header fields"),null;let d=u?u[1].trim():"Pending",p=FT(r);return{pathway:o[1].trim(),risk_assessment:s[1].trim(),risk_tier:parseInt(i[1].trim(),10),estimated_bolts:parseInt(a[1].trim(),10),estimated_depth:c[1].trim(),generated_at:l[1].trim(),approved_at:d==="Pending"?null:d,approved_by:null,phases:{discovery:p.discovery??{included:!0,rationale:""},inception:p.inception??{included:!0,rationale:""},construction:p.construction??{included:!0,rationale:""},operations:p.operations??{included:!0,rationale:""}},stages:jT(r)}}catch(o){return console.error("[WorkflowRouting] Failed to parse artifact:",o),null}}function cs(e,t){return e.phases[t]?.included??!0}function Ia(e,t,n){return e.stages.find(o=>o.phase===t&&o.stage===n)?.included??!0}function mm(e){let t=[];t.push("```mermaid"),t.push("flowchart TD"),t.push(""),t.push(" classDef execute fill:#4CAF50,color:#fff,stroke:#388E3C"),t.push(" classDef skip fill:#BDBDBD,color:#424242,stroke:#9E9E9E"),t.push(" classDef conditional fill:#FFA726,color:#fff,stroke:#F57C00"),t.push("");let n=["discovery","inception","construction","operations"];for(let r of n){let o=e.phases[r],s=r.charAt(0).toUpperCase()+r.slice(1);if(o.included){t.push(` subgraph ${s}["${s} Phase"]`);let i=e.stages.filter(c=>c.phase===r);for(let c of i){let l=`${r}_${c.stage.replace(/-/g,"_")}`,u=c.stage.replace(/-/g," ");c.included?(t.push(` ${l}["${u}"]`),t.push(` class ${l} execute`)):(t.push(` ${l}["${u} (SKIP)"]`),t.push(` class ${l} skip`))}let a=i.map(c=>`${r}_${c.stage.replace(/-/g,"_")}`);for(let c=0;c<a.length-1;c++)t.push(` ${a[c]} --> ${a[c+1]}`);t.push(" end")}else{let i=`${r}_skip`;t.push(` ${i}["${s} (SKIPPED)"]`),t.push(` class ${i} skip`)}t.push("")}for(let r=0;r<n.length-1;r++){let o=n[r],s=n[r+1],i=e.stages.filter(p=>p.phase===o),a=e.stages.filter(p=>p.phase===s),c=e.phases[o].included,l=e.phases[s].included,u,d;c&&i.length>0?u=`${o}_${i[i.length-1].stage.replace(/-/g,"_")}`:u=`${o}_skip`,l&&a.length>0?d=`${s}_${a[0].stage.replace(/-/g,"_")}`:d=`${s}_skip`,!c||!l?t.push(` ${u} -.-> ${d}`):t.push(` ${u} --> ${d}`)}return t.push("```"),t.join(`
271
+ `)}var Gt,sr,is,dm,CT,xT,PT,pm,MT,ls=U(()=>{"use strict";Gt=b(require("path"),1),sr=b(require("fs/promises"),1),is=require("fs"),dm=b(require("os"),1);ns();Z();CT=["bugfix","optimization"];xT=[{pathway:"bugfix",keywords:["fix","bug","broken","regression","error","crash","issue","defect","patch"]},{pathway:"optimization",keywords:["optimize","performance","speed","cache","reduce","improve latency","memory","bottleneck"]},{pathway:"brownfield-refactor",keywords:["refactor","restructure","migrate","rewrite","reorganize","modernize","upgrade"]},{pathway:"brownfield-enhancement",keywords:["add","new","feature","implement","integrate","extend","support"]}];PT={greenfield:"No existing source files detected \u2014 greenfield project.",bugfix:"Intent keywords matched 'fix', 'bug', 'broken', 'regression', 'error', 'crash', 'issue', 'defect', or 'patch' \u2192 bugfix pathway.",optimization:"Intent keywords matched 'optimize', 'performance', 'speed', 'cache', 'reduce', 'improve latency', 'memory', or 'bottleneck' \u2192 optimization pathway.","brownfield-refactor":"Intent keywords matched 'refactor', 'restructure', 'migrate', 'rewrite', 'reorganize', 'modernize', or 'upgrade' \u2192 brownfield-refactor pathway.","brownfield-enhancement":"Intent keywords matched 'add', 'new', 'feature', 'implement', 'integrate', 'extend', or 'support' (or no keywords matched \u2014 default brownfield pathway)."},pm={greenfield:"Greenfield","brownfield-enhancement":"Enhancement","brownfield-refactor":"Refactor",bugfix:"Bug Fix",optimization:"Optimization"};MT=`A Workflow Routing document must contain:
272
+ 1. A header block with: Pathway, Risk Assessment, Risk Tier, Estimated Bolts, Estimated Depth, Generated date, Approved date
264
273
  2. A "Phase Overview" table with columns: Phase | Included | Rationale \u2014 one row per phase (discovery, inception, construction, operations)
265
274
  3. A "Stage Details" table with columns: # | Phase | Stage | Included | Rationale \u2014 one row per workflow stage
266
275
  Pathway values: greenfield | brownfield-enhancement | brownfield-refactor | bugfix | optimization
267
276
  Risk Assessment values: LOW | MEDIUM | HIGH
268
- Estimated Depth values: minimal | standard | comprehensive`});var is={};he(is,{CODE_PLAN_FORMAT_INSTRUCTIONS:()=>SE,buildCodeGenerationPrompt:()=>em,buildCodePlanPath:()=>kE,dispatchCodeGeneration:()=>_E,extractSections:()=>ba,extractTargetFiles:()=>Ca,selectAgentForCodeGeneration:()=>Zf});function kE(e,t,n){return(0,sr.join)(e,"aidlc-docs",t,"construction",n,"code-plan.md")}function ba(e,t){if(!e)return"";let n=[],r=e.split(`
277
+ Estimated Depth values: minimal | standard | comprehensive`});var us={};he(us,{CODE_PLAN_FORMAT_INSTRUCTIONS:()=>WT,buildCodeGenerationPrompt:()=>_m,buildCodePlanPath:()=>LT,dispatchCodeGeneration:()=>UT,extractSections:()=>Oa,extractTargetFiles:()=>$a,selectAgentForCodeGeneration:()=>wm});function LT(e,t,n){return(0,ir.join)(e,"aidlc-docs",t,"construction",n,"code-plan.md")}function Oa(e,t){if(!e)return"";let n=[],r=e.split(`
269
278
  `);for(let o=0;o<r.length;o++){let s=r[o],i=s.match(/^##\s+(.+)$/)||s.match(/^###\s+(.+)$/);if(i){let a=i[1].trim();if(t.some(c=>a.includes(c))){let c=[s],l=s.match(/^(#+)/)?.[1].length||2;for(let u=o+1;u<r.length;u++){let d=r[u],p=d.match(/^(#+)\s/);if(p&&p[1].length<=l)break;c.push(d)}n.push(c.join(`
270
279
  `))}}}return n.length>0?n.join(`
271
280
 
272
- `):e}function Ca(e){let t=[],n=e.split(`
273
- `),r=!1;for(let o of n){if(o.match(/^##\s+Target Files/i)||o.match(/^###\s+Target Files/i)){r=!0;continue}if(r&&o.match(/^##\s+/))break;if(r){let s=o.match(/^-\s+(.+)$/);s&&t.push(s[1].trim())}}return t}function Zf(e){let t=Ca(e),n=["olympian-low","frontend-engineer-low","oracle-low"];for(let r of n){let o=lf(r);if(o&&o.success_rate>.8&&o.total_invocations>10)return Qf(t,e)?r.startsWith("frontend")?r:"frontend-engineer-low":Xf(e)?r.startsWith("oracle")?r:"oracle-low":r.startsWith("olympian")?r:"olympian-low"}return Qf(t,e)?"frontend-engineer":Xf(e)?"oracle":"olympian"}function Qf(e,t){let n=[".tsx",".jsx",".css",".scss","/ui/","/component","/page","/layout"];for(let r of e){let o=r.toLowerCase();if(n.some(s=>o.includes(s)))return!0}return!1}function Xf(e){let t=["debug","fix","investigate","diagnose"],n=e.toLowerCase();return t.some(r=>n.includes(r))}function em(e,t,n,r,o){let s=r?`
281
+ `):e}function $a(e){let t=[],n=e.split(`
282
+ `),r=!1;for(let o of n){if(o.match(/^##\s+Target Files/i)||o.match(/^###\s+Target Files/i)){r=!0;continue}if(r&&o.match(/^##\s+/))break;if(r){let s=o.match(/^-\s+(.+)$/);s&&t.push(s[1].trim())}}return t}function wm(e){let t=$a(e),n=["olympian-low","frontend-engineer-low","oracle-low"];for(let r of n){let o=xf(r);if(o&&o.success_rate>.8&&o.total_invocations>10)return hm(t,e)?r.startsWith("frontend")?r:"frontend-engineer-low":ym(e)?r.startsWith("oracle")?r:"oracle-low":r.startsWith("olympian")?r:"olympian-low"}return hm(t,e)?"frontend-engineer":ym(e)?"oracle":"olympian"}function hm(e,t){let n=[".tsx",".jsx",".css",".scss","/ui/","/component","/page","/layout"];for(let r of e){let o=r.toLowerCase();if(n.some(s=>o.includes(s)))return!0}return!1}function ym(e){let t=["debug","fix","investigate","diagnose"],n=e.toLowerCase();return t.some(r=>n.includes(r))}function _m(e,t,n,r,o){let s=r?`
274
283
  ## Execution Protocol (Two-Part Code Generation)
275
284
  PART 1 - PLAN:
276
285
  1. Create an execution plan in a markdown file with checkboxes for each step
@@ -300,50 +309,50 @@ Generate code for this unit according to the spec above.
300
309
  - Create/modify files listed in "Target Files"
301
310
  - Write tests per "Test Requirements"
302
311
  - Meet all "Acceptance Criteria"
303
- - Do NOT modify files outside the target list without justification`}async function _E(e,t,n){let r=(0,sr.join)(e,"aidlc-docs",t),o=(0,sr.join)(r,"construction"),s=(0,sr.join)(o,n,"spec.md"),i=(0,ir.existsSync)(s)?(0,ir.readFileSync)(s,"utf-8"):"",a=(0,sr.join)(r,"inception","intent.md"),c=(0,ir.existsSync)(a)?(0,ir.readFileSync)(a,"utf-8"):"",l=ba(c,["Business Requirements","Technical Specification"]),u=ba(c,["Problem Statement","Success Metrics"]),d=Ca(i),p="";try{let{getArchitectureContext:k}=await Promise.resolve().then(()=>(Jr(),Jo)),h=[...new Set(d.map(v=>{let S=v.replace(/\\/g,"/").split("/").filter(Boolean);return S[0]==="src"&&S.length>1?S[1]:S[0]||""}).filter(Boolean))];h.length>0&&(p=await k(e,h))}catch{}let f="";try{let{loadPathwayBehaviors:k}=await Promise.resolve().then(()=>(ss(),zf)),{loadCheckpoint:h}=await Promise.resolve().then(()=>(me(),_p)),v=await h(e,t);if(v?.pathway_type){let S=await k(v.pathway_type);if(S){let b=S.rules.map(j=>`- **${j.name}**: ${j.description}`).join(`
304
- `),_=S.qualityGateChecklist.map(j=>`- [ ] ${j}`).join(`
312
+ - Do NOT modify files outside the target list without justification`}async function UT(e,t,n){let r=(0,ir.join)(e,"aidlc-docs",t),o=(0,ir.join)(r,"construction"),s=(0,ir.join)(o,n,"spec.md"),i=(0,ar.existsSync)(s)?(0,ar.readFileSync)(s,"utf-8"):"",a=(0,ir.join)(r,"inception","intent.md"),c=(0,ar.existsSync)(a)?(0,ar.readFileSync)(a,"utf-8"):"",l=Oa(c,["Business Requirements","Technical Specification"]),u=Oa(c,["Problem Statement","Success Metrics"]),d=$a(i),p="";try{let{getArchitectureContext:_}=await Promise.resolve().then(()=>(Jr(),Zo)),h=[...new Set(d.map(v=>{let S=v.replace(/\\/g,"/").split("/").filter(Boolean);return S[0]==="src"&&S.length>1?S[1]:S[0]||""}).filter(Boolean))];h.length>0&&(p=await _(e,h))}catch{}let f="";try{let{loadPathwayBehaviors:_}=await Promise.resolve().then(()=>(ls(),gm)),{loadCheckpoint:h}=await Promise.resolve().then(()=>(le(),Tp)),v=await h(e,t);if(v?.pathway_type){let S=await _(v.pathway_type);if(S){let E=S.rules.map(j=>`- **${j.name}**: ${j.description}`).join(`
313
+ `),k=S.qualityGateChecklist.map(j=>`- [ ] ${j}`).join(`
305
314
  `);f=`
306
315
  ## Pathway Rules (${v.pathway_type})
307
- ${b}
316
+ ${E}
308
317
 
309
318
  ### Quality Checklist
310
- ${_}`}}}catch{}let m="";try{let{loadArchitectureModel:k}=await Promise.resolve().then(()=>(Jr(),Jo)),h=await k(e);if(h?.designSystem?.detected&&h.designSystem.systems.length>0){let v=h.designSystem.systems.map(S=>S.name).join(", ");m=`
319
+ ${k}`}}}catch{}let m="";try{let{loadArchitectureModel:_}=await Promise.resolve().then(()=>(Jr(),Zo)),h=await _(e);if(h?.designSystem?.detected&&h.designSystem.systems.length>0){let v=h.designSystem.systems.map(S=>S.name).join(", ");m=`
311
320
  ## Design System Enforcement
312
321
  This project uses: ${v}. You MUST:
313
322
  - Use existing components from the detected design system before creating new ones
314
323
  - If you must create a new component, include a justification comment explaining why no existing component suffices
315
324
  - Do NOT duplicate functionality already provided by ${v}`}}catch{}let g=[p,f,m].filter(Boolean).join(`
316
325
 
317
- `),y=Zf(i),w=em(u,l,i,void 0,g||void 0);return{unitName:n,agentType:y,prompt:w,context:{unitSpec:i,intentSummary:l,intentSummary2:u,targetFiles:d,architectureContext:g||void 0}}}var ir,sr,SE,as=U(()=>{"use strict";ir=require("fs"),sr=require("path");Yo();SE=`A code generation plan must contain:
326
+ `),y=wm(i),w=_m(u,l,i,void 0,g||void 0);return{unitName:n,agentType:y,prompt:w,context:{unitSpec:i,intentSummary:l,intentSummary2:u,targetFiles:d,architectureContext:g||void 0}}}var ar,ir,WT,ds=U(()=>{"use strict";ar=require("fs"),ir=require("path");Qo();WT=`A code generation plan must contain:
318
327
  1. A title line: "# Code Plan: {unitName}"
319
328
  2. A checklist of implementation steps using markdown checkboxes (- [ ] step)
320
329
  3. Each step should be specific and actionable
321
330
  4. Steps should be ordered by dependency (prerequisites first)
322
331
  5. Include a "## Verification" section with test/validation checkboxes
323
- The plan file is saved at: aidlc-docs/{workflowId}/construction/{unitName}/code-plan.md`});var tm={};he(tm,{buildRegressionSummary:()=>EE,categorizeFailure:()=>vE,checkFlakyThreshold:()=>TE});function vE(e,t,n){return t!==null&&t.status==="failed"?"pre_existing_failure":n.some(r=>r.status==="passed")?"flaky":t===null?"intentional_change":"legitimate_regression"}function TE(e,t=.2){let n=e.length;return n===0?!1:e.filter(o=>o==="flaky").length/n>t}function EE(e,t){let n=t.filter(o=>o==="legitimate_regression").length,r=t.filter(o=>o==="flaky").length;return{regressions_count:n,flaky_count:r}}var nm=U(()=>{"use strict"});async function rm(e,t){let n=[];for(let r of bE){let o=e.get(r);if(!o)continue;let s;try{let i=new Promise((a,c)=>setTimeout(()=>c(new Error("timeout")),t.timeoutBudgetMs));s=await Promise.race([o(t),i])}catch(i){let a=i instanceof Error&&i.message==="timeout",c={id:`${r}-error`,severity:"error",category:a?"timeout":"runtime-error",message:a?`Validator '${r}' exceeded timeout of ${t.timeoutBudgetMs}ms`:`Validator '${r}' threw an error: ${i instanceof Error?i.message:String(i)}`};console.error(`[ValidatorPipeline] ${r} validator failed:`,i),s={status:a?"timeout":"failed",findings:[c],artifactPath:""}}n.push({validator:r,result:s})}return{results:n}}function om(e,t){if(e==="mutation"){let n=["auth","payment","security","encrypt","token","credential","password","session","permission"];if(!t.unitFiles.some(o=>n.some(s=>o.toLowerCase().includes(s))))return{skip:!0,reason:"No critical-path keywords found in unit files"}}return e==="contract"&&t.apiSurfaceFiles.length===0?{skip:!0,reason:"No API surface files in unit"}:{skip:!1}}function Ee(e){return{...e,status:"passed",findings:e.findings.map(t=>({...t,severity:"info"}))}}async function sm(e,t,n,r,o,s,i){let a=await I(e,t);if(!a||!a.construction_units)return;let c=a.construction_units[n];if(!c)return;let l=CE[r];c[l]=o,r==="coverage"&&s!==void 0&&(c.coverage_percentage=s),r==="coverage"&&i!==void 0&&(c.critical_gap_count=i),await O(e,a)}var bE,CE,xn=U(()=>{"use strict";me();bE=["quality","mutation","traceability","contract","coverage"],CE={quality:"quality_validation_status",mutation:"mutation_validation_status",traceability:"traceability_status",contract:"contract_validation_status",coverage:"coverage_status"}});function im(e){let t=[],n=/(?:^|\n)\s*(?:it|test)\s*\(\s*(['"`])([\s\S]*?)\1/g,r;for(;(r=n.exec(e))!==null;){let o=r[2]??"",s=r.index+r[0].length,i=e.slice(s),a=i.search(/\{/);if(a===-1)continue;let c=0,l=s+a,u=l;for(let p=a;p<i.length;p++){let f=i[p];if(f==="{")c++;else if(f==="}"&&(c--,c===0)){u=s+p+1;break}}let d=e.slice(l,u);t.push({name:o,body:d})}return t}function Ra(e){return/\bexpect\s*\(/.test(e)||/\bassert\s*\(/.test(e)||/\bassert\.\w+\s*\(/.test(e)}function DE(e){return!Ra(e)||IE.test(e)?!1:AE.test(e)}function NE(e){return!Ra(e)||!/\.toMatchSnapshot\s*\(|\.toMatchInlineSnapshot\s*\(/.test(e)?!1:!OE.test(e)}function FE(e){let t=0;for(let n of $E){let r=e.match(n);r&&(t+=r.length)}return t}function jE(e){let t=0;for(let n of e.split(`
324
- `)){let r=n.trim();r&&(r.startsWith("//")||r[0]==="*"||/\bvi\.fn\b|\bjest\.fn\b|\bvi\.mock\b|\bjest\.mock\b|\bmockReturnValue\b|\bmockResolvedValue\b|\bmockImplementation\b|\bstub\b/.test(r)||/^\s*expect\s*\(|^\s*assert\s*[.(]/.test(n)||/\b\w+\s*\(/.test(r)&&t++)}return t}function cs(e,t,n){let r=[],o=im(e);for(let s of o){let{name:i,body:a}=s,c={file:n,testName:i||t};if(!Ra(a)){r.push({id:`empty-body:${n}:${i}`,severity:"error",category:"empty-body",message:`Test "${i}" has no assertions (empty test body)`,location:c});continue}for(let d of RE)if(d.pattern.test(a)){r.push({id:`${d.category}:${n}:${i}`,severity:d.severity,category:d.category,message:`Test "${i}": ${d.description}`,location:c});break}DE(a)&&r.push({id:`surface-assertion:${n}:${i}`,severity:"warning",category:"surface-assertion",message:`Test "${i}": ${xE.find(d=>d.category==="surface-assertion")?.description??"Only surface assertions found"}`,location:c}),NE(a)&&r.push({id:`snapshot-overuse:${n}:${i}`,severity:"warning",category:"snapshot-overuse",message:`Test "${i}": Test relies exclusively on snapshot assertions without behavioral checks`,location:c});let l=FE(a),u=jE(a);l>3&&l>u*2&&r.push({id:`excessive-mocking:${n}:${i}`,severity:"warning",category:"excessive-mocking",message:`Test "${i}": Excessive mocking detected (${l} mocks vs ${u} real calls)`,location:{...c,testName:i}})}return r}function ls(e){let t=im(e),n=t.length;if(n===0)return{ratio:0,totalTests:0,negativeTests:0};let r=0;for(let o of t){let s=`${o.name}
325
- ${o.body}`;PE.some(i=>i.test(s))&&r++}return{ratio:r/n,totalTests:n,negativeTests:r}}var RE,xE,PE,IE,AE,OE,$E,xa=U(()=>{"use strict";RE=[{category:"tautological",severity:"error",pattern:/mockReturnValue\((['"`]?)(\w+)\1\)[^]*?\.toBe\((['"`]?)\2\3\)/,description:"Mock return value is asserted against itself (tautological assertion)"},{category:"tautological",severity:"error",pattern:/mockResolvedValue\((['"`]?)(\w+)\1\)[^]*?\.resolves\.toBe\((['"`]?)\2\3\)/,description:"Mock resolved value is asserted against itself (tautological assertion)"},{category:"trivially-true",severity:"error",pattern:/expect\((true|false)\)\.toBe\(\1\)/,description:"Literal boolean asserted against itself (trivially true assertion)"},{category:"trivially-true",severity:"error",pattern:/expect\((true|1)\)\.toBeTruthy\(\)/,description:"Always-truthy literal asserted as truthy (trivially true assertion)"},{category:"trivially-true",severity:"error",pattern:/expect\((false|0)\)\.toBeFalsy\(\)/,description:"Always-falsy literal asserted as falsy (trivially true assertion)"},{category:"trivially-true",severity:"error",pattern:/expect\(null\)\.toBeNull\(\)/,description:"Null literal asserted as null (trivially true assertion)"},{category:"trivially-true",severity:"error",pattern:/expect\(undefined\)\.toBeUndefined\(\)/,description:"Undefined literal asserted as undefined (trivially true assertion)"}],xE=[{category:"surface-assertion",severity:"warning",pattern:/(?:expect\([^)]+\)\.(?:toBeInTheDocument|toBeDefined|toBeNull|toExist|toBeVisible)\(\)[\s;,]*)+/,description:"All assertions use only surface-level existence matchers without behavioral checks"},{category:"snapshot-overuse",severity:"warning",pattern:/expect\([^)]+\)\.toMatchSnapshot\(\)/,description:"Test relies exclusively on snapshot assertions without behavioral checks"},{category:"snapshot-overuse",severity:"warning",pattern:/expect\([^)]+\)\.toMatchInlineSnapshot\(/,description:"Test relies exclusively on inline snapshot assertions without behavioral checks"}],PE=[/\bthrow\b/i,/\breject\b/i,/\berror\b/i,/\binvalid\b/i,/\bfail\b/i,/\bboundary\b/i,/\bedge\b/i,/\bnegative\b/i,/\bmissing\b/i,/\bunauthorized\b/i,/\bforbidden\b/i,/\bnot.?found\b/i,/\.toThrow\b/,/\.rejects\b/,/\.toThrowError\b/],IE=/\.(?:toBe|toEqual|toStrictEqual|toMatchObject|toHaveBeenCalledWith|toHaveBeenCalled|toHaveReturnedWith|toThrow|toResolve|toReject|toHaveLength|toBeGreaterThan|toBeLessThan|toBeCloseTo)\s*\(/g,AE=/\.(?:toContain|toBeInTheDocument|toBeDefined|toBeNull|toExist|toBeVisible|toBeUndefined|toBeTruthy|toBeFalsy)\s*\(/g,OE=/\.(?:toBe|toEqual|toStrictEqual|toMatchObject|toContain|toHaveBeenCalled|toHaveBeenCalledWith|toThrow|toReject|toBeInTheDocument|toBeDefined|toHaveLength|toBeGreaterThan|toBeLessThan)\s*\(/,$E=[/\bvi\.fn\s*\(/g,/\bjest\.fn\s*\(/g,/\bmock\s*\(/g,/\bstub\s*\(/g,/\.mockReturnValue\s*\(/g,/\.mockResolvedValue\s*\(/g,/\.mockImplementation\s*\(/g,/vi\.mock\s*\(/g,/jest\.mock\s*\(/g]});async function ME(e){if(!await sn.default.pathExists(e))return[];let n=(await sn.default.readdir(e)).filter(o=>o.endsWith(".test.ts")||o.endsWith(".test.js")||o.endsWith(".spec.ts")||o.endsWith(".spec.js")),r=[];for(let o of n){let s=Pn.default.join(e,o),i=await sn.default.readFile(s,"utf-8");r.push({filePath:s,content:i})}return r}function LE(e){let t=e.match(/(?:^|\n)\s*(?:it|test)\s*\(\s*['"`]/g);return t?t.length:0}function am(e,t,n,r,o,s){let i=e.filter(u=>u.severity==="error"),a=e.filter(u=>u.severity==="warning"),c=n-t,l=["# Quality Validation Report","","## Summary","","| Metric | Value |","|--------|-------|",`| Total tests | ${n} |`,`| Validated tests | ${t} |`,`| Rejected tests | ${c} |`,`| Warnings | ${a.length} |`,""];if(i.length>0){l.push("## Rejections",""),l.push("| Test | File | Reason |"),l.push("|------|------|--------|");for(let u of i){let d=u.location?.testName??"unknown",p=u.location?.file??"unknown";l.push(`| ${d} | ${p} | ${u.message} |`)}l.push("")}if(a.length>0){l.push("## Warnings",""),l.push("| Test | File | Warning | Details |"),l.push("|------|------|---------|---------|");for(let u of a){let d=u.location?.testName??"unknown",p=u.location?.file??"unknown";l.push(`| ${d} | ${p} | ${u.category} | ${u.message} |`)}l.push("")}return l.push("## Negative Case Coverage",""),l.push("| Metric | Value |"),l.push("|--------|-------|"),l.push(`| Total tests | ${o} |`),l.push(`| Negative tests | ${s} |`),l.push(`| Ratio | ${(r*100).toFixed(1)}% |`),l.push(`| Threshold | ${(us*100).toFixed(1)}% |`),l.push(`| Status | ${r>=us?"PASS":"BELOW THRESHOLD"} |`),l.push(""),l.join(`
326
- `)}function cm(){return async e=>{let t=Pn.default.join(e.projectPath,"aidlc-docs",e.workflowId,"construction",e.unitId,"testing"),n=Pn.default.join(t,"quality-validation.md"),r=await ME(t);if(r.length===0){let w={status:"passed",findings:[],artifactPath:n};return await sn.default.ensureDir(Pn.default.dirname(n)),await sn.default.writeFile(n,am([],0,0,0,0,0),"utf-8"),e.allowFailures?Ee(w):w}let o=[],s=0;for(let{filePath:w,content:k}of r){let h=Pn.default.basename(w),v=cs(k,h,w);o.push(...v),s+=LE(k)}let i=r.map(w=>w.content).join(`
327
- `),{ratio:a,totalTests:c,negativeTests:l}=ls(i),u=[];c>0&&a<us&&u.push({id:`negative-case-ratio:${e.unitId}`,severity:"warning",category:"negative-case-ratio",message:`Negative case ratio is ${(a*100).toFixed(1)}% (${l}/${c}), below the ${(us*100).toFixed(1)}% threshold`});let d=[...o,...u],p=d.filter(w=>w.severity==="error"),f=d.filter(w=>w.severity==="warning"),m=Math.max(0,s-p.length),g;p.length>0?g="failed":f.length>0?g="warned":g="passed",await sn.default.ensureDir(Pn.default.dirname(n)),await sn.default.writeFile(n,am(d,m,s,a,c,l),"utf-8");let y={status:g,findings:d,artifactPath:n};return e.allowFailures?Ee(y):y}}var sn,Pn,us,lm=U(()=>{"use strict";sn=T(X(),1),Pn=T(require("path"),1);xn();xa();us=.2});function UE(e){let t=[];for(let{filePath:n,content:r}of e){let o=Ie.default.basename(n).toLowerCase(),s=Pa.some(a=>new RegExp(`\\b${a}\\b`,"i").test(o)),i=Pa.some(a=>new RegExp(`\\b${a}`,"i").test(r));(s||i)&&t.push(n)}return t}function WE(e,t){let n=e.split(`
328
- `),r=[];for(let o=0;o<n.length&&!(r.length>=ds);o++){let s=o+1,i=n[o].trim();if(/===/.test(i)){r.push({filePath:t,line:s,original:i,mutated:i.replace(/===/,"!=="),faultType:"conditional-negation",context:i});continue}if(/!==/.test(i)){r.push({filePath:t,line:s,original:i,mutated:i.replace(/!==/,"==="),faultType:"conditional-negation",context:i});continue}if(/\breturn\s+true\b/.test(i)){r.push({filePath:t,line:s,original:i,mutated:i.replace(/\breturn\s+true\b/,"return false"),faultType:"return-value",context:i});continue}if(/\breturn\s+false\b/.test(i)){r.push({filePath:t,line:s,original:i,mutated:i.replace(/\breturn\s+false\b/,"return true"),faultType:"return-value",context:i});continue}if(/\breturn\s+null\b/.test(i)){r.push({filePath:t,line:s,original:i,mutated:i.replace(/\breturn\s+null\b/,"return undefined"),faultType:"return-value",context:i});continue}if(/(?<!=)>=/.test(i)){r.push({filePath:t,line:s,original:i,mutated:i.replace(/(?<!=)>=/,">"),faultType:"comparison-boundary",context:i});continue}if(/<=(?!=)/.test(i)&&!i.includes("=>")){r.push({filePath:t,line:s,original:i,mutated:i.replace(/<=(?!=)/,"<"),faultType:"comparison-boundary",context:i});continue}if(/(?<![=!<>])>(?![>=])/.test(i)&&!/=>/.test(i)){r.push({filePath:t,line:s,original:i,mutated:i.replace(/(?<![=!<>])>(?![>=])/,">="),faultType:"comparison-boundary",context:i});continue}if(/(?<![=!<>])<(?![<=])/.test(i)&&!/=>/.test(i)){r.push({filePath:t,line:s,original:i,mutated:i.replace(/(?<![=!<>])<(?![<=])/,"<="),faultType:"comparison-boundary",context:i});continue}if(/\bif\s*\(!/.test(i)){r.push({filePath:t,line:s,original:i,mutated:i.replace(/\bif\s*\(!/,"if ("),faultType:"conditional-negation",context:i});continue}if(/\bif\s*\((?!!)/.test(i)){r.push({filePath:t,line:s,original:i,mutated:i.replace(/\bif\s*\((?!!)/,"if (!"),faultType:"conditional-negation",context:i});continue}}return r.slice(0,ds)}function GE(e,t){return e.map(n=>{let r=Ie.default.basename(n.filePath,Ie.default.extname(n.filePath));for(let{filePath:o,content:s}of t)if((s.includes(r)||s.includes(Ie.default.basename(n.filePath)))&&BE(n,s)){let a=s.match(/(?:it|test)\s*\(\s*['"`]([^'"`]+)['"`]/);return{point:n,caught:!0,testFile:o,testName:a?a[1]:void 0}}return{point:n,caught:!1}})}function BE(e,t){return/expect\s*\(/.test(t)?e.faultType==="conditional-negation"?/\b(false|null|undefined|throws?|rejects?|denied|unauthorized|forbidden|invalid)\b/i.test(t)||/toBe\s*\(\s*false\s*\)/.test(t)||/toBeFalsy/.test(t)||/toThrow/.test(t)||/toReject/.test(t)||/status.*4\d\d/.test(t):e.faultType==="comparison-boundary"?/\b(0|1|limit|max|min|boundary|threshold|exactly|equal)\b/i.test(t)||/toBe\s*\(\s*\d+\s*\)/.test(t)||/toEqual/.test(t):e.faultType==="return-value"?/toBe\s*\(\s*(true|false|null|undefined)\s*\)/.test(t)||/toBeTruthy/.test(t)||/toBeFalsy/.test(t)||/toBeNull/.test(t)||/toBeUndefined/.test(t):!1:!1}function um(e,t,n){let r=["# Mutation Validation Report",""];if(n)return r.push("## Status: Skipped",""),r.push("No critical-path files were identified in this unit."),r.push("Mutation spot-check requires files containing keywords: "+Pa.join(", ")+"."),r.push(""),r.join(`
329
- `);let o=e.filter(i=>i.caught).length,s=e.filter(i=>!i.caught).length;if(r.push("## Summary",""),r.push("| Metric | Value |"),r.push("|--------|-------|"),r.push(`| Critical files analyzed | ${t.length} |`),r.push(`| Mutation points identified | ${e.length} |`),r.push(`| Caught by tests | ${o} |`),r.push(`| Uncaught (no test) | ${s} |`),r.push(""),t.length>0){r.push("## Critical Files","");for(let i of t)r.push(`- \`${Ie.default.basename(i)}\``);r.push("")}if(e.length>0){r.push("## Mutation Points",""),r.push("| File | Line | Fault Type | Original | Mutated | Status | Test Reference |"),r.push("|------|------|------------|----------|---------|--------|----------------|");for(let i of e){let a=i.caught?"CAUGHT":"UNCAUGHT",c=i.caught?i.testName?`\`${i.testName}\``:Ie.default.basename(i.testFile??""):"\u2014",l=i.point.original.length>40?i.point.original.slice(0,37)+"...":i.point.original,u=i.point.mutated.length>40?i.point.mutated.slice(0,37)+"...":i.point.mutated;r.push(`| ${Ie.default.basename(i.point.filePath)} | ${i.point.line} | ${i.point.faultType} | ${l} | ${u} | ${a} | ${c} |`)}r.push("")}return r.join(`
330
- `)}async function HE(e){let t=[];for(let n of e)try{if(await Ct.default.pathExists(n)){let r=await Ct.default.readFile(n,"utf-8");t.push({filePath:n,content:r})}}catch{}return t}async function VE(e){if(!await Ct.default.pathExists(e))return[];let n=(await Ct.default.readdir(e)).filter(o=>o.endsWith(".test.ts")||o.endsWith(".test.js")||o.endsWith(".spec.ts")||o.endsWith(".spec.js")),r=[];for(let o of n){let s=Ie.default.join(e,o),i=await Ct.default.readFile(s,"utf-8");r.push({filePath:s,content:i})}return r}function dm(){return async e=>{let t=Ie.default.join(e.projectPath,"aidlc-docs",e.workflowId,"construction",e.unitId,"testing"),n=Ie.default.join(t,"mutation-validation.md"),r=await HE(e.unitFiles),o=UE(r);if(o.length===0){await Ct.default.ensureDir(Ie.default.dirname(n)),await Ct.default.writeFile(n,um([],[],!0),"utf-8");let p={status:"skipped",findings:[],artifactPath:n};return e.allowFailures?Ee(p):p}let s=[];for(let p of r)if(o.includes(p.filePath)&&(s.push(...WE(p.content,p.filePath)),s.length>=ds))break;let i=s.slice(0,ds),a=await VE(t),c=GE(i,a),l=[];for(let p of c)p.caught||l.push({id:`mutation-uncaught:${Ie.default.basename(p.point.filePath)}:${p.point.line}`,severity:"warning",category:"uncaught-mutation",message:`Uncaught ${p.point.faultType} mutation at ${Ie.default.basename(p.point.filePath)}:${p.point.line} \u2014 \`${p.point.original}\` \u2192 \`${p.point.mutated}\``,location:{file:p.point.filePath,line:p.point.line}});let u=l.length===0?"passed":"warned";await Ct.default.ensureDir(Ie.default.dirname(n)),await Ct.default.writeFile(n,um(c,o,!1),"utf-8");let d={status:u,findings:l,artifactPath:n};return e.allowFailures?Ee(d):d}}var Ct,Ie,Pa,ds,pm=U(()=>{"use strict";Ct=T(X(),1),Ie=T(require("path"),1);xn();Pa=["auth","payment","security","encrypt","token","credential","password","session","permission"],ds=10});function qE(e){let t=e.toLowerCase();return fm.some(n=>t.includes(n))}function YE(e){let t=e.toLowerCase();for(let n of fm)if(t.includes(n))return`Criterion contains "${n}" \u2014 inherently untestable`;return"Inherently untestable"}function KE(e){let t=[],n=new Set,r=e.split(`
331
- `);for(let o=0;o<r.length;o++){let s=r[o],i=s.match(/\b(AC-\d{3}\.\d+)\b/);if(!i)continue;let a=i[1];if(n.has(a))continue;n.add(a);let c=[],l=s.replace(/\*+/g,"").replace(/^[-*]\s*/,"").trim();c.push(l);for(let u=o+1;u<Math.min(o+10,r.length);u++){let d=r[u].trim();if(/^(Given|When|Then|And|But)\b/i.test(d))c.push(d);else{if(d===""&&u>o+1)break;if(/^\*\*(AC-|FR-)/.test(d)||/^#+\s/.test(d))break}}t.push({id:a,text:c.join(" ").trim(),source:"stories.md"})}if(t.length===0){let o=1,s=/###\s+(.+)/g,i;for(;(i=s.exec(e))!==null;)t.push({id:`AC-001.${o}`,text:i[1].trim(),source:"stories.md"}),o++}return t}function mm(e){let t=[],n=new Set;for(let r of e.split(`
332
- `)){let o=r.match(/\b(FR-\d{3}\.\d+)\b/);if(!o)continue;let s=o[1];if(n.has(s))continue;n.add(s);let a=r.replace(/\*+/g,"").replace(/^[-*]\s*/,"").trim().replace(s,"").replace(/^[:\s-]+/,"").trim()||s;t.push({id:s,text:a,source:"requirements.md"})}return t}function JE(e,t){let n=mm(e);if(n.length>0)return n.map(s=>({...s,source:"spec.md"}));let r=[],o=1;for(let s of e.split(`
333
- `)){let i=s.match(/^#{2,4}\s+(.+)/);if(i){let a=i[1].trim();a.length>3&&(r.push({id:`SPEC-${t.toUpperCase()}.${o}`,text:a,source:"spec.md"}),o++)}}return r}async function zE(e){let t=Rt.default.join(e.projectPath,"aidlc-docs",e.workflowId,"inception"),n=Rt.default.join(t,"user-stories","stories.md");if(await Ze.default.pathExists(n)){let s=await Ze.default.readFile(n,"utf-8"),i=KE(s);if(i.length>0)return{type:"user-stories",criteria:i}}let r=Rt.default.join(t,"requirements","requirements.md");if(await Ze.default.pathExists(r)){let s=await Ze.default.readFile(r,"utf-8"),i=mm(s);if(i.length>0)return{type:"requirements",criteria:i}}let o=Rt.default.join(e.projectPath,"aidlc-docs",e.workflowId,"construction",e.unitId,"spec.md");if(await Ze.default.pathExists(o)){let s=await Ze.default.readFile(o,"utf-8"),i=JE(s,e.unitId);if(i.length>0)return{type:"unit-spec",criteria:i}}return null}function QE(e,t){return e.map(n=>{if(qE(n.text))return{criterion:n,tests:[],status:"Not Testable",notTestableReason:YE(n.text)};let r=[],o=n.id.toLowerCase(),s=n.text.toLowerCase().split(/\W+/).filter(a=>a.length>4);for(let{filePath:a,content:c}of t){let l=Rt.default.basename(a),u=c.toLowerCase(),d=u.includes(o),p=s.length>0&&s.some(f=>u.includes(f));if(!(!d&&!p))for(let f of c.split(`
334
- `)){let m=f.match(/(?:^|\s)(?:it|test)\s*\(\s*['"`]([^'"`]+)['"`]/);if(!m)continue;let g=m[1],y=g.toLowerCase(),w=y.includes(o),k=s.some(h=>y.includes(h));(w||k||d)&&(r.some(v=>v.file===l&&v.testName===g)||r.push({file:l,testName:g}))}}let i=r.length>0?"Covered":"Gap";return{criterion:n,tests:r,status:i}})}function XE(e,t){let n=t==="user-stories"?"User Stories (Gherkin AC)":t==="requirements"?"Requirements (FR sub-requirements)":"Unit Spec",r=e.filter(c=>c.status==="Covered").length,o=e.filter(c=>c.status==="Gap").length,s=e.filter(c=>c.status==="Not Testable").length,i=e.length,a=["# Requirement-Test Traceability Map","",`**Source**: ${n}`,"","## Summary","","| Metric | Value |","|--------|-------|",`| Total criteria | ${i} |`,`| Covered | ${r} |`,`| Gaps | ${o} |`,`| Not Testable | ${s} |`,"","## Traceability Table","","| Requirement/Criterion | Test(s) | Status |","|-----------------------|---------|--------|"];for(let c of e){let l=c.criterion.text,u=l.length>60?l.slice(0,60)+"...":l,d=`${c.criterion.id}: ${u}`,p;c.status==="Not Testable"?p=`\u2014 (${c.notTestableReason??"Not Testable"})`:c.tests.length===0?p="\u2014":p=c.tests.map(f=>`${f.file}: ${f.testName}`).join("<br>"),a.push(`| ${d} | ${p} | ${c.status} |`)}return a.push(""),a.join(`
335
- `)}async function ZE(e){if(!await Ze.default.pathExists(e))return[];let n=(await Ze.default.readdir(e)).filter(o=>o.endsWith(".test.ts")||o.endsWith(".test.js")||o.endsWith(".spec.ts")||o.endsWith(".spec.js")),r=[];for(let o of n){let s=Rt.default.join(e,o),i=await Ze.default.readFile(s,"utf-8");r.push({filePath:s,content:i})}return r}function gm(){return async e=>{let t=Rt.default.join(e.projectPath,"aidlc-docs",e.workflowId,"construction",e.unitId,"testing"),n=Rt.default.join(t,"requirement-test-map.md"),r=await zE(e);if(r===null){let d={status:"skipped",findings:[{id:`traceability:no-source:${e.unitId}`,severity:"info",category:"no-traceability-source",message:"No traceability source found (user stories, requirements, or unit spec). Traceability skipped."}],artifactPath:n};return e.allowFailures?Ee(d):d}let{criteria:o}=r;if(e.workflowDepth===0){let d=["reproduce","fix","verify"];o=o.filter(p=>{let f=p.text.toLowerCase();return d.some(m=>f.includes(m))})}let s=await ZE(t),i=QE(o,s),a=i.filter(d=>d.status==="Gap"),c=[];for(let d of a){let p=e.workflowDepth>=2?"error":"warning";c.push({id:`traceability:gap:${d.criterion.id}`,severity:p,category:"traceability-gap",message:`No test covers criterion ${d.criterion.id}: "${d.criterion.text.slice(0,80)}"`})}let l;a.length===0?l="passed":e.workflowDepth>=2?l="failed":(e.workflowDepth,l="warned"),await Ze.default.ensureDir(Rt.default.dirname(n)),await Ze.default.writeFile(n,XE(i,r.type),"utf-8");let u={status:l,findings:c,artifactPath:n};return e.allowFailures?Ee(u):u}}var Ze,Rt,fm,hm=U(()=>{"use strict";Ze=T(X(),1),Rt=T(require("path"),1);xn();fm=["deployment","infrastructure","manual review","visual inspection","ui style","not testable"]});function nb(e){let t=[],n=[];for(let r of e){let o=xt.default.extname(r).toLowerCase();if(!eb.has(o)){n.push(r),console.warn(`[ContractValidator] Skipping non-JS/TS file: ${r}`);continue}(tb.some(i=>i.test(r))||xt.default.basename(r)==="index.ts"||xt.default.basename(r)==="index.js")&&t.push(r)}return{surfaces:t,nonJsFiles:n}}function ym(e,t){let n=[],r=[],o=[],s=/export\s+(?:async\s+)?function\s+(\w+)\s*\(([^)]*)\)\s*(?::\s*([^\s{;]+(?:\s*<[^>]*>)?(?:\[\])?(?:\s*\|\s*[^\s{;]+)*))?/g,i;for(;(i=s.exec(e))!==null;){let d=i[1],p=i[2].trim(),f=(i[3]??"void").trim(),m=p===""?0:p.split(",").length;n.push({name:d,parameterCount:m,returnType:f})}let a=/export\s+const\s+(\w+)\s*=\s*(?:async\s*)?\(([^)]*)\)\s*(?::\s*([^\s=>]+))?\s*=>/g;for(;(i=a.exec(e))!==null;){let d=i[1],p=i[2].trim(),f=(i[3]??"void").trim(),m=p===""?0:p.split(",").length;n.push({name:d,parameterCount:m,returnType:f})}let c=/(?:app|router|server|fastify)\s*\.\s*(get|post|put|patch|delete|head|options)\s*\(\s*['"`]([^'"`]+)['"`]/gi;for(;(i=c.exec(e))!==null;){let d=i[1].toUpperCase(),p=i[2],f=rb(e,i.index);r.push({method:d,path:p,statusCodes:f})}let l=/export\s+(?:interface|type)\s+(\w+)\s*(?:<[^>]*>)?\s*([=\{][^}]*\}?)/gs;for(;(i=l.exec(e))!==null;){let d=i[1],p=i[2].slice(0,200).replace(/\s+/g," ").trim();o.push({name:d,definition:p})}let u=/export\s+(?:const\s+)?enum\s+(\w+)\s*\{([^}]*)\}/gs;for(;(i=u.exec(e))!==null;){let d=i[1],p=i[2].split(",").map(f=>f.trim().split("=")[0].trim()).filter(f=>f.length>0);o.push({name:`enum:${d}`,definition:p.join(",")})}return{exports:n,endpoints:r,types:o}}function rb(e,t){let n=e.slice(t,t+500),r=/\.status\s*\(\s*(\d{3})\s*\)/g,o=[],s;for(;(s=r.exec(n))!==null;){let i=parseInt(s[1],10);o.includes(i)||o.push(i)}return o}function ob(e,t){let n=[];for(let r of e.exports){let o=t.exports.find(s=>s.name===r.name);if(!o){n.push({category:"removed-export",name:r.name,before:`${r.name}(${r.parameterCount} params): ${r.returnType}`,after:"(removed)"});continue}o.parameterCount!==r.parameterCount&&n.push({category:"changed-params",name:r.name,before:`${r.parameterCount} params`,after:`${o.parameterCount} params`}),o.returnType!==r.returnType&&r.returnType!=="void"&&r.returnType!==""&&n.push({category:"changed-return-type",name:r.name,before:r.returnType,after:o.returnType})}for(let r of e.endpoints)t.endpoints.find(s=>s.method===r.method&&s.path===r.path)||n.push({category:"removed-endpoint",name:`${r.method} ${r.path}`,before:`${r.method} ${r.path}`,after:"(removed)"});for(let r of e.types){if(!r.name.startsWith("enum:"))continue;let o=t.types.find(c=>c.name===r.name);if(!o){n.push({category:"narrowed-enum",name:r.name.replace("enum:",""),before:r.definition,after:"(removed)"});continue}let s=r.definition.split(",").map(c=>c.trim()).filter(Boolean),i=o.definition.split(",").map(c=>c.trim()).filter(Boolean);s.filter(c=>!i.includes(c)).length>0&&n.push({category:"narrowed-enum",name:r.name.replace("enum:",""),before:s.join(", "),after:i.join(", ")})}return n}function wm(e,t,n,r){if(n)return["# Contract Validation Report","","## Result","","No API surfaces affected. Contract validation skipped.",""].join(`
332
+ The plan file is saved at: aidlc-docs/{workflowId}/construction/{unitName}/code-plan.md`});var km={};he(km,{buildRegressionSummary:()=>HT,categorizeFailure:()=>BT,checkFlakyThreshold:()=>GT});function BT(e,t,n){return t!==null&&t.status==="failed"?"pre_existing_failure":n.some(r=>r.status==="passed")?"flaky":t===null?"intentional_change":"legitimate_regression"}function GT(e,t=.2){let n=e.length;return n===0?!1:e.filter(o=>o==="flaky").length/n>t}function HT(e,t){let n=t.filter(o=>o==="legitimate_regression").length,r=t.filter(o=>o==="flaky").length;return{regressions_count:n,flaky_count:r}}var Sm=U(()=>{"use strict"});async function vm(e,t){let n=[];for(let r of VT){let o=e.get(r);if(!o)continue;let s;try{let i=new Promise((a,c)=>setTimeout(()=>c(new Error("timeout")),t.timeoutBudgetMs));s=await Promise.race([o(t),i])}catch(i){let a=i instanceof Error&&i.message==="timeout",c={id:`${r}-error`,severity:"error",category:a?"timeout":"runtime-error",message:a?`Validator '${r}' exceeded timeout of ${t.timeoutBudgetMs}ms`:`Validator '${r}' threw an error: ${i instanceof Error?i.message:String(i)}`};console.error(`[ValidatorPipeline] ${r} validator failed:`,i),s={status:a?"timeout":"failed",findings:[c],artifactPath:""}}n.push({validator:r,result:s})}return{results:n}}function bm(e,t){if(e==="mutation"){let n=["auth","payment","security","encrypt","token","credential","password","session","permission"];if(!t.unitFiles.some(o=>n.some(s=>o.toLowerCase().includes(s))))return{skip:!0,reason:"No critical-path keywords found in unit files"}}return e==="contract"&&t.apiSurfaceFiles.length===0?{skip:!0,reason:"No API surface files in unit"}:{skip:!1}}function Ee(e){return{...e,status:"passed",findings:e.findings.map(t=>({...t,severity:"info"}))}}async function Tm(e,t,n,r,o,s,i){let a=await I(e,t);if(!a||!a.construction_units)return;let c=a.construction_units[n];if(!c)return;let l=qT[r];c[l]=o,r==="coverage"&&s!==void 0&&(c.coverage_percentage=s),r==="coverage"&&i!==void 0&&(c.critical_gap_count=i),await A(e,a)}var VT,qT,xn=U(()=>{"use strict";le();VT=["quality","mutation","traceability","contract","coverage"],qT={quality:"quality_validation_status",mutation:"mutation_validation_status",traceability:"traceability_status",contract:"contract_validation_status",coverage:"coverage_status"}});function Em(e){let t=[],n=/(?:^|\n)\s*(?:it|test)\s*\(\s*(['"`])([\s\S]*?)\1/g,r;for(;(r=n.exec(e))!==null;){let o=r[2]??"",s=r.index+r[0].length,i=e.slice(s),a=i.search(/\{/);if(a===-1)continue;let c=0,l=s+a,u=l;for(let p=a;p<i.length;p++){let f=i[p];if(f==="{")c++;else if(f==="}"&&(c--,c===0)){u=s+p+1;break}}let d=e.slice(l,u);t.push({name:o,body:d})}return t}function Da(e){return/\bexpect\s*\(/.test(e)||/\bassert\s*\(/.test(e)||/\bassert\.\w+\s*\(/.test(e)}function eE(e){return!Da(e)||zT.test(e)?!1:QT.test(e)}function tE(e){return!Da(e)||!/\.toMatchSnapshot\s*\(|\.toMatchInlineSnapshot\s*\(/.test(e)?!1:!XT.test(e)}function nE(e){let t=0;for(let n of ZT){let r=e.match(n);r&&(t+=r.length)}return t}function rE(e){let t=0;for(let n of e.split(`
333
+ `)){let r=n.trim();r&&(r.startsWith("//")||r[0]==="*"||/\bvi\.fn\b|\bjest\.fn\b|\bvi\.mock\b|\bjest\.mock\b|\bmockReturnValue\b|\bmockResolvedValue\b|\bmockImplementation\b|\bstub\b/.test(r)||/^\s*expect\s*\(|^\s*assert\s*[.(]/.test(n)||/\b\w+\s*\(/.test(r)&&t++)}return t}function ps(e,t,n){let r=[],o=Em(e);for(let s of o){let{name:i,body:a}=s,c={file:n,testName:i||t};if(!Da(a)){r.push({id:`empty-body:${n}:${i}`,severity:"error",category:"empty-body",message:`Test "${i}" has no assertions (empty test body)`,location:c});continue}for(let d of YT)if(d.pattern.test(a)){r.push({id:`${d.category}:${n}:${i}`,severity:d.severity,category:d.category,message:`Test "${i}": ${d.description}`,location:c});break}eE(a)&&r.push({id:`surface-assertion:${n}:${i}`,severity:"warning",category:"surface-assertion",message:`Test "${i}": ${KT.find(d=>d.category==="surface-assertion")?.description??"Only surface assertions found"}`,location:c}),tE(a)&&r.push({id:`snapshot-overuse:${n}:${i}`,severity:"warning",category:"snapshot-overuse",message:`Test "${i}": Test relies exclusively on snapshot assertions without behavioral checks`,location:c});let l=nE(a),u=rE(a);l>3&&l>u*2&&r.push({id:`excessive-mocking:${n}:${i}`,severity:"warning",category:"excessive-mocking",message:`Test "${i}": Excessive mocking detected (${l} mocks vs ${u} real calls)`,location:{...c,testName:i}})}return r}function fs(e){let t=Em(e),n=t.length;if(n===0)return{ratio:0,totalTests:0,negativeTests:0};let r=0;for(let o of t){let s=`${o.name}
334
+ ${o.body}`;JT.some(i=>i.test(s))&&r++}return{ratio:r/n,totalTests:n,negativeTests:r}}var YT,KT,JT,zT,QT,XT,ZT,Na=U(()=>{"use strict";YT=[{category:"tautological",severity:"error",pattern:/mockReturnValue\((['"`]?)(\w+)\1\)[^]*?\.toBe\((['"`]?)\2\3\)/,description:"Mock return value is asserted against itself (tautological assertion)"},{category:"tautological",severity:"error",pattern:/mockResolvedValue\((['"`]?)(\w+)\1\)[^]*?\.resolves\.toBe\((['"`]?)\2\3\)/,description:"Mock resolved value is asserted against itself (tautological assertion)"},{category:"trivially-true",severity:"error",pattern:/expect\((true|false)\)\.toBe\(\1\)/,description:"Literal boolean asserted against itself (trivially true assertion)"},{category:"trivially-true",severity:"error",pattern:/expect\((true|1)\)\.toBeTruthy\(\)/,description:"Always-truthy literal asserted as truthy (trivially true assertion)"},{category:"trivially-true",severity:"error",pattern:/expect\((false|0)\)\.toBeFalsy\(\)/,description:"Always-falsy literal asserted as falsy (trivially true assertion)"},{category:"trivially-true",severity:"error",pattern:/expect\(null\)\.toBeNull\(\)/,description:"Null literal asserted as null (trivially true assertion)"},{category:"trivially-true",severity:"error",pattern:/expect\(undefined\)\.toBeUndefined\(\)/,description:"Undefined literal asserted as undefined (trivially true assertion)"}],KT=[{category:"surface-assertion",severity:"warning",pattern:/(?:expect\([^)]+\)\.(?:toBeInTheDocument|toBeDefined|toBeNull|toExist|toBeVisible)\(\)[\s;,]*)+/,description:"All assertions use only surface-level existence matchers without behavioral checks"},{category:"snapshot-overuse",severity:"warning",pattern:/expect\([^)]+\)\.toMatchSnapshot\(\)/,description:"Test relies exclusively on snapshot assertions without behavioral checks"},{category:"snapshot-overuse",severity:"warning",pattern:/expect\([^)]+\)\.toMatchInlineSnapshot\(/,description:"Test relies exclusively on inline snapshot assertions without behavioral checks"}],JT=[/\bthrow\b/i,/\breject\b/i,/\berror\b/i,/\binvalid\b/i,/\bfail\b/i,/\bboundary\b/i,/\bedge\b/i,/\bnegative\b/i,/\bmissing\b/i,/\bunauthorized\b/i,/\bforbidden\b/i,/\bnot.?found\b/i,/\.toThrow\b/,/\.rejects\b/,/\.toThrowError\b/],zT=/\.(?:toBe|toEqual|toStrictEqual|toMatchObject|toHaveBeenCalledWith|toHaveBeenCalled|toHaveReturnedWith|toThrow|toResolve|toReject|toHaveLength|toBeGreaterThan|toBeLessThan|toBeCloseTo)\s*\(/g,QT=/\.(?:toContain|toBeInTheDocument|toBeDefined|toBeNull|toExist|toBeVisible|toBeUndefined|toBeTruthy|toBeFalsy)\s*\(/g,XT=/\.(?:toBe|toEqual|toStrictEqual|toMatchObject|toContain|toHaveBeenCalled|toHaveBeenCalledWith|toThrow|toReject|toBeInTheDocument|toBeDefined|toHaveLength|toBeGreaterThan|toBeLessThan)\s*\(/,ZT=[/\bvi\.fn\s*\(/g,/\bjest\.fn\s*\(/g,/\bmock\s*\(/g,/\bstub\s*\(/g,/\.mockReturnValue\s*\(/g,/\.mockResolvedValue\s*\(/g,/\.mockImplementation\s*\(/g,/vi\.mock\s*\(/g,/jest\.mock\s*\(/g]});async function oE(e){if(!await cn.default.pathExists(e))return[];let n=(await cn.default.readdir(e)).filter(o=>o.endsWith(".test.ts")||o.endsWith(".test.js")||o.endsWith(".spec.ts")||o.endsWith(".spec.js")),r=[];for(let o of n){let s=Pn.default.join(e,o),i=await cn.default.readFile(s,"utf-8");r.push({filePath:s,content:i})}return r}function sE(e){let t=e.match(/(?:^|\n)\s*(?:it|test)\s*\(\s*['"`]/g);return t?t.length:0}function Cm(e,t,n,r,o,s){let i=e.filter(u=>u.severity==="error"),a=e.filter(u=>u.severity==="warning"),c=n-t,l=["# Quality Validation Report","","## Summary","","| Metric | Value |","|--------|-------|",`| Total tests | ${n} |`,`| Validated tests | ${t} |`,`| Rejected tests | ${c} |`,`| Warnings | ${a.length} |`,""];if(i.length>0){l.push("## Rejections",""),l.push("| Test | File | Reason |"),l.push("|------|------|--------|");for(let u of i){let d=u.location?.testName??"unknown",p=u.location?.file??"unknown";l.push(`| ${d} | ${p} | ${u.message} |`)}l.push("")}if(a.length>0){l.push("## Warnings",""),l.push("| Test | File | Warning | Details |"),l.push("|------|------|---------|---------|");for(let u of a){let d=u.location?.testName??"unknown",p=u.location?.file??"unknown";l.push(`| ${d} | ${p} | ${u.category} | ${u.message} |`)}l.push("")}return l.push("## Negative Case Coverage",""),l.push("| Metric | Value |"),l.push("|--------|-------|"),l.push(`| Total tests | ${o} |`),l.push(`| Negative tests | ${s} |`),l.push(`| Ratio | ${(r*100).toFixed(1)}% |`),l.push(`| Threshold | ${(ms*100).toFixed(1)}% |`),l.push(`| Status | ${r>=ms?"PASS":"BELOW THRESHOLD"} |`),l.push(""),l.join(`
335
+ `)}function Rm(){return async e=>{let t=Pn.default.join(e.projectPath,"aidlc-docs",e.workflowId,"construction",e.unitId,"testing"),n=Pn.default.join(t,"quality-validation.md"),r=await oE(t);if(r.length===0){let w={status:"passed",findings:[],artifactPath:n};return await cn.default.ensureDir(Pn.default.dirname(n)),await cn.default.writeFile(n,Cm([],0,0,0,0,0),"utf-8"),e.allowFailures?Ee(w):w}let o=[],s=0;for(let{filePath:w,content:_}of r){let h=Pn.default.basename(w),v=ps(_,h,w);o.push(...v),s+=sE(_)}let i=r.map(w=>w.content).join(`
336
+ `),{ratio:a,totalTests:c,negativeTests:l}=fs(i),u=[];c>0&&a<ms&&u.push({id:`negative-case-ratio:${e.unitId}`,severity:"warning",category:"negative-case-ratio",message:`Negative case ratio is ${(a*100).toFixed(1)}% (${l}/${c}), below the ${(ms*100).toFixed(1)}% threshold`});let d=[...o,...u],p=d.filter(w=>w.severity==="error"),f=d.filter(w=>w.severity==="warning"),m=Math.max(0,s-p.length),g;p.length>0?g="failed":f.length>0?g="warned":g="passed",await cn.default.ensureDir(Pn.default.dirname(n)),await cn.default.writeFile(n,Cm(d,m,s,a,c,l),"utf-8");let y={status:g,findings:d,artifactPath:n};return e.allowFailures?Ee(y):y}}var cn,Pn,ms,xm=U(()=>{"use strict";cn=b(X(),1),Pn=b(require("path"),1);xn();Na();ms=.2});function iE(e){let t=[];for(let{filePath:n,content:r}of e){let o=Ae.default.basename(n).toLowerCase(),s=Fa.some(a=>new RegExp(`\\b${a}\\b`,"i").test(o)),i=Fa.some(a=>new RegExp(`\\b${a}`,"i").test(r));(s||i)&&t.push(n)}return t}function aE(e,t){let n=e.split(`
337
+ `),r=[];for(let o=0;o<n.length&&!(r.length>=gs);o++){let s=o+1,i=n[o].trim();if(/===/.test(i)){r.push({filePath:t,line:s,original:i,mutated:i.replace(/===/,"!=="),faultType:"conditional-negation",context:i});continue}if(/!==/.test(i)){r.push({filePath:t,line:s,original:i,mutated:i.replace(/!==/,"==="),faultType:"conditional-negation",context:i});continue}if(/\breturn\s+true\b/.test(i)){r.push({filePath:t,line:s,original:i,mutated:i.replace(/\breturn\s+true\b/,"return false"),faultType:"return-value",context:i});continue}if(/\breturn\s+false\b/.test(i)){r.push({filePath:t,line:s,original:i,mutated:i.replace(/\breturn\s+false\b/,"return true"),faultType:"return-value",context:i});continue}if(/\breturn\s+null\b/.test(i)){r.push({filePath:t,line:s,original:i,mutated:i.replace(/\breturn\s+null\b/,"return undefined"),faultType:"return-value",context:i});continue}if(/(?<!=)>=/.test(i)){r.push({filePath:t,line:s,original:i,mutated:i.replace(/(?<!=)>=/,">"),faultType:"comparison-boundary",context:i});continue}if(/<=(?!=)/.test(i)&&!i.includes("=>")){r.push({filePath:t,line:s,original:i,mutated:i.replace(/<=(?!=)/,"<"),faultType:"comparison-boundary",context:i});continue}if(/(?<![=!<>])>(?![>=])/.test(i)&&!/=>/.test(i)){r.push({filePath:t,line:s,original:i,mutated:i.replace(/(?<![=!<>])>(?![>=])/,">="),faultType:"comparison-boundary",context:i});continue}if(/(?<![=!<>])<(?![<=])/.test(i)&&!/=>/.test(i)){r.push({filePath:t,line:s,original:i,mutated:i.replace(/(?<![=!<>])<(?![<=])/,"<="),faultType:"comparison-boundary",context:i});continue}if(/\bif\s*\(!/.test(i)){r.push({filePath:t,line:s,original:i,mutated:i.replace(/\bif\s*\(!/,"if ("),faultType:"conditional-negation",context:i});continue}if(/\bif\s*\((?!!)/.test(i)){r.push({filePath:t,line:s,original:i,mutated:i.replace(/\bif\s*\((?!!)/,"if (!"),faultType:"conditional-negation",context:i});continue}}return r.slice(0,gs)}function cE(e,t){return e.map(n=>{let r=Ae.default.basename(n.filePath,Ae.default.extname(n.filePath));for(let{filePath:o,content:s}of t)if((s.includes(r)||s.includes(Ae.default.basename(n.filePath)))&&lE(n,s)){let a=s.match(/(?:it|test)\s*\(\s*['"`]([^'"`]+)['"`]/);return{point:n,caught:!0,testFile:o,testName:a?a[1]:void 0}}return{point:n,caught:!1}})}function lE(e,t){return/expect\s*\(/.test(t)?e.faultType==="conditional-negation"?/\b(false|null|undefined|throws?|rejects?|denied|unauthorized|forbidden|invalid)\b/i.test(t)||/toBe\s*\(\s*false\s*\)/.test(t)||/toBeFalsy/.test(t)||/toThrow/.test(t)||/toReject/.test(t)||/status.*4\d\d/.test(t):e.faultType==="comparison-boundary"?/\b(0|1|limit|max|min|boundary|threshold|exactly|equal)\b/i.test(t)||/toBe\s*\(\s*\d+\s*\)/.test(t)||/toEqual/.test(t):e.faultType==="return-value"?/toBe\s*\(\s*(true|false|null|undefined)\s*\)/.test(t)||/toBeTruthy/.test(t)||/toBeFalsy/.test(t)||/toBeNull/.test(t)||/toBeUndefined/.test(t):!1:!1}function Pm(e,t,n){let r=["# Mutation Validation Report",""];if(n)return r.push("## Status: Skipped",""),r.push("No critical-path files were identified in this unit."),r.push("Mutation spot-check requires files containing keywords: "+Fa.join(", ")+"."),r.push(""),r.join(`
338
+ `);let o=e.filter(i=>i.caught).length,s=e.filter(i=>!i.caught).length;if(r.push("## Summary",""),r.push("| Metric | Value |"),r.push("|--------|-------|"),r.push(`| Critical files analyzed | ${t.length} |`),r.push(`| Mutation points identified | ${e.length} |`),r.push(`| Caught by tests | ${o} |`),r.push(`| Uncaught (no test) | ${s} |`),r.push(""),t.length>0){r.push("## Critical Files","");for(let i of t)r.push(`- \`${Ae.default.basename(i)}\``);r.push("")}if(e.length>0){r.push("## Mutation Points",""),r.push("| File | Line | Fault Type | Original | Mutated | Status | Test Reference |"),r.push("|------|------|------------|----------|---------|--------|----------------|");for(let i of e){let a=i.caught?"CAUGHT":"UNCAUGHT",c=i.caught?i.testName?`\`${i.testName}\``:Ae.default.basename(i.testFile??""):"\u2014",l=i.point.original.length>40?i.point.original.slice(0,37)+"...":i.point.original,u=i.point.mutated.length>40?i.point.mutated.slice(0,37)+"...":i.point.mutated;r.push(`| ${Ae.default.basename(i.point.filePath)} | ${i.point.line} | ${i.point.faultType} | ${l} | ${u} | ${a} | ${c} |`)}r.push("")}return r.join(`
339
+ `)}async function uE(e){let t=[];for(let n of e)try{if(await Rt.default.pathExists(n)){let r=await Rt.default.readFile(n,"utf-8");t.push({filePath:n,content:r})}}catch{}return t}async function dE(e){if(!await Rt.default.pathExists(e))return[];let n=(await Rt.default.readdir(e)).filter(o=>o.endsWith(".test.ts")||o.endsWith(".test.js")||o.endsWith(".spec.ts")||o.endsWith(".spec.js")),r=[];for(let o of n){let s=Ae.default.join(e,o),i=await Rt.default.readFile(s,"utf-8");r.push({filePath:s,content:i})}return r}function Am(){return async e=>{let t=Ae.default.join(e.projectPath,"aidlc-docs",e.workflowId,"construction",e.unitId,"testing"),n=Ae.default.join(t,"mutation-validation.md"),r=await uE(e.unitFiles),o=iE(r);if(o.length===0){await Rt.default.ensureDir(Ae.default.dirname(n)),await Rt.default.writeFile(n,Pm([],[],!0),"utf-8");let p={status:"skipped",findings:[],artifactPath:n};return e.allowFailures?Ee(p):p}let s=[];for(let p of r)if(o.includes(p.filePath)&&(s.push(...aE(p.content,p.filePath)),s.length>=gs))break;let i=s.slice(0,gs),a=await dE(t),c=cE(i,a),l=[];for(let p of c)p.caught||l.push({id:`mutation-uncaught:${Ae.default.basename(p.point.filePath)}:${p.point.line}`,severity:"warning",category:"uncaught-mutation",message:`Uncaught ${p.point.faultType} mutation at ${Ae.default.basename(p.point.filePath)}:${p.point.line} \u2014 \`${p.point.original}\` \u2192 \`${p.point.mutated}\``,location:{file:p.point.filePath,line:p.point.line}});let u=l.length===0?"passed":"warned";await Rt.default.ensureDir(Ae.default.dirname(n)),await Rt.default.writeFile(n,Pm(c,o,!1),"utf-8");let d={status:u,findings:l,artifactPath:n};return e.allowFailures?Ee(d):d}}var Rt,Ae,Fa,gs,Im=U(()=>{"use strict";Rt=b(X(),1),Ae=b(require("path"),1);xn();Fa=["auth","payment","security","encrypt","token","credential","password","session","permission"],gs=10});function pE(e){let t=e.toLowerCase();return Om.some(n=>t.includes(n))}function fE(e){let t=e.toLowerCase();for(let n of Om)if(t.includes(n))return`Criterion contains "${n}" \u2014 inherently untestable`;return"Inherently untestable"}function mE(e){let t=[],n=new Set,r=e.split(`
340
+ `);for(let o=0;o<r.length;o++){let s=r[o],i=s.match(/\b(AC-\d{3}\.\d+)\b/);if(!i)continue;let a=i[1];if(n.has(a))continue;n.add(a);let c=[],l=s.replace(/\*+/g,"").replace(/^[-*]\s*/,"").trim();c.push(l);for(let u=o+1;u<Math.min(o+10,r.length);u++){let d=r[u].trim();if(/^(Given|When|Then|And|But)\b/i.test(d))c.push(d);else{if(d===""&&u>o+1)break;if(/^\*\*(AC-|FR-)/.test(d)||/^#+\s/.test(d))break}}t.push({id:a,text:c.join(" ").trim(),source:"stories.md"})}if(t.length===0){let o=1,s=/###\s+(.+)/g,i;for(;(i=s.exec(e))!==null;)t.push({id:`AC-001.${o}`,text:i[1].trim(),source:"stories.md"}),o++}return t}function $m(e){let t=[],n=new Set;for(let r of e.split(`
341
+ `)){let o=r.match(/\b(FR-\d{3}\.\d+)\b/);if(!o)continue;let s=o[1];if(n.has(s))continue;n.add(s);let a=r.replace(/\*+/g,"").replace(/^[-*]\s*/,"").trim().replace(s,"").replace(/^[:\s-]+/,"").trim()||s;t.push({id:s,text:a,source:"requirements.md"})}return t}function gE(e,t){let n=$m(e);if(n.length>0)return n.map(s=>({...s,source:"spec.md"}));let r=[],o=1;for(let s of e.split(`
342
+ `)){let i=s.match(/^#{2,4}\s+(.+)/);if(i){let a=i[1].trim();a.length>3&&(r.push({id:`SPEC-${t.toUpperCase()}.${o}`,text:a,source:"spec.md"}),o++)}}return r}async function hE(e){let t=xt.default.join(e.projectPath,"aidlc-docs",e.workflowId,"inception"),n=xt.default.join(t,"user-stories","stories.md");if(await et.default.pathExists(n)){let s=await et.default.readFile(n,"utf-8"),i=mE(s);if(i.length>0)return{type:"user-stories",criteria:i}}let r=xt.default.join(t,"requirements","requirements.md");if(await et.default.pathExists(r)){let s=await et.default.readFile(r,"utf-8"),i=$m(s);if(i.length>0)return{type:"requirements",criteria:i}}let o=xt.default.join(e.projectPath,"aidlc-docs",e.workflowId,"construction",e.unitId,"spec.md");if(await et.default.pathExists(o)){let s=await et.default.readFile(o,"utf-8"),i=gE(s,e.unitId);if(i.length>0)return{type:"unit-spec",criteria:i}}return null}function yE(e,t){return e.map(n=>{if(pE(n.text))return{criterion:n,tests:[],status:"Not Testable",notTestableReason:fE(n.text)};let r=[],o=n.id.toLowerCase(),s=n.text.toLowerCase().split(/\W+/).filter(a=>a.length>4);for(let{filePath:a,content:c}of t){let l=xt.default.basename(a),u=c.toLowerCase(),d=u.includes(o),p=s.length>0&&s.some(f=>u.includes(f));if(!(!d&&!p))for(let f of c.split(`
343
+ `)){let m=f.match(/(?:^|\s)(?:it|test)\s*\(\s*['"`]([^'"`]+)['"`]/);if(!m)continue;let g=m[1],y=g.toLowerCase(),w=y.includes(o),_=s.some(h=>y.includes(h));(w||_||d)&&(r.some(v=>v.file===l&&v.testName===g)||r.push({file:l,testName:g}))}}let i=r.length>0?"Covered":"Gap";return{criterion:n,tests:r,status:i}})}function wE(e,t){let n=t==="user-stories"?"User Stories (Gherkin AC)":t==="requirements"?"Requirements (FR sub-requirements)":"Unit Spec",r=e.filter(c=>c.status==="Covered").length,o=e.filter(c=>c.status==="Gap").length,s=e.filter(c=>c.status==="Not Testable").length,i=e.length,a=["# Requirement-Test Traceability Map","",`**Source**: ${n}`,"","## Summary","","| Metric | Value |","|--------|-------|",`| Total criteria | ${i} |`,`| Covered | ${r} |`,`| Gaps | ${o} |`,`| Not Testable | ${s} |`,"","## Traceability Table","","| Requirement/Criterion | Test(s) | Status |","|-----------------------|---------|--------|"];for(let c of e){let l=c.criterion.text,u=l.length>60?l.slice(0,60)+"...":l,d=`${c.criterion.id}: ${u}`,p;c.status==="Not Testable"?p=`\u2014 (${c.notTestableReason??"Not Testable"})`:c.tests.length===0?p="\u2014":p=c.tests.map(f=>`${f.file}: ${f.testName}`).join("<br>"),a.push(`| ${d} | ${p} | ${c.status} |`)}return a.push(""),a.join(`
344
+ `)}async function _E(e){if(!await et.default.pathExists(e))return[];let n=(await et.default.readdir(e)).filter(o=>o.endsWith(".test.ts")||o.endsWith(".test.js")||o.endsWith(".spec.ts")||o.endsWith(".spec.js")),r=[];for(let o of n){let s=xt.default.join(e,o),i=await et.default.readFile(s,"utf-8");r.push({filePath:s,content:i})}return r}function Dm(){return async e=>{let t=xt.default.join(e.projectPath,"aidlc-docs",e.workflowId,"construction",e.unitId,"testing"),n=xt.default.join(t,"requirement-test-map.md"),r=await hE(e);if(r===null){let d={status:"skipped",findings:[{id:`traceability:no-source:${e.unitId}`,severity:"info",category:"no-traceability-source",message:"No traceability source found (user stories, requirements, or unit spec). Traceability skipped."}],artifactPath:n};return e.allowFailures?Ee(d):d}let{criteria:o}=r;if(e.workflowDepth===0){let d=["reproduce","fix","verify"];o=o.filter(p=>{let f=p.text.toLowerCase();return d.some(m=>f.includes(m))})}let s=await _E(t),i=yE(o,s),a=i.filter(d=>d.status==="Gap"),c=[];for(let d of a){let p=e.workflowDepth>=2?"error":"warning";c.push({id:`traceability:gap:${d.criterion.id}`,severity:p,category:"traceability-gap",message:`No test covers criterion ${d.criterion.id}: "${d.criterion.text.slice(0,80)}"`})}let l;a.length===0?l="passed":e.workflowDepth>=2?l="failed":(e.workflowDepth,l="warned"),await et.default.ensureDir(xt.default.dirname(n)),await et.default.writeFile(n,wE(i,r.type),"utf-8");let u={status:l,findings:c,artifactPath:n};return e.allowFailures?Ee(u):u}}var et,xt,Om,Nm=U(()=>{"use strict";et=b(X(),1),xt=b(require("path"),1);xn();Om=["deployment","infrastructure","manual review","visual inspection","ui style","not testable"]});function vE(e){let t=[],n=[];for(let r of e){let o=Pt.default.extname(r).toLowerCase();if(!kE.has(o)){n.push(r),console.warn(`[ContractValidator] Skipping non-JS/TS file: ${r}`);continue}(SE.some(i=>i.test(r))||Pt.default.basename(r)==="index.ts"||Pt.default.basename(r)==="index.js")&&t.push(r)}return{surfaces:t,nonJsFiles:n}}function Fm(e,t){let n=[],r=[],o=[],s=/export\s+(?:async\s+)?function\s+(\w+)\s*\(([^)]*)\)\s*(?::\s*([^\s{;]+(?:\s*<[^>]*>)?(?:\[\])?(?:\s*\|\s*[^\s{;]+)*))?/g,i;for(;(i=s.exec(e))!==null;){let d=i[1],p=i[2].trim(),f=(i[3]??"void").trim(),m=p===""?0:p.split(",").length;n.push({name:d,parameterCount:m,returnType:f})}let a=/export\s+const\s+(\w+)\s*=\s*(?:async\s*)?\(([^)]*)\)\s*(?::\s*([^\s=>]+))?\s*=>/g;for(;(i=a.exec(e))!==null;){let d=i[1],p=i[2].trim(),f=(i[3]??"void").trim(),m=p===""?0:p.split(",").length;n.push({name:d,parameterCount:m,returnType:f})}let c=/(?:app|router|server|fastify)\s*\.\s*(get|post|put|patch|delete|head|options)\s*\(\s*['"`]([^'"`]+)['"`]/gi;for(;(i=c.exec(e))!==null;){let d=i[1].toUpperCase(),p=i[2],f=bE(e,i.index);r.push({method:d,path:p,statusCodes:f})}let l=/export\s+(?:interface|type)\s+(\w+)\s*(?:<[^>]*>)?\s*([=\{][^}]*\}?)/gs;for(;(i=l.exec(e))!==null;){let d=i[1],p=i[2].slice(0,200).replace(/\s+/g," ").trim();o.push({name:d,definition:p})}let u=/export\s+(?:const\s+)?enum\s+(\w+)\s*\{([^}]*)\}/gs;for(;(i=u.exec(e))!==null;){let d=i[1],p=i[2].split(",").map(f=>f.trim().split("=")[0].trim()).filter(f=>f.length>0);o.push({name:`enum:${d}`,definition:p.join(",")})}return{exports:n,endpoints:r,types:o}}function bE(e,t){let n=e.slice(t,t+500),r=/\.status\s*\(\s*(\d{3})\s*\)/g,o=[],s;for(;(s=r.exec(n))!==null;){let i=parseInt(s[1],10);o.includes(i)||o.push(i)}return o}function TE(e,t){let n=[];for(let r of e.exports){let o=t.exports.find(s=>s.name===r.name);if(!o){n.push({category:"removed-export",name:r.name,before:`${r.name}(${r.parameterCount} params): ${r.returnType}`,after:"(removed)"});continue}o.parameterCount!==r.parameterCount&&n.push({category:"changed-params",name:r.name,before:`${r.parameterCount} params`,after:`${o.parameterCount} params`}),o.returnType!==r.returnType&&r.returnType!=="void"&&r.returnType!==""&&n.push({category:"changed-return-type",name:r.name,before:r.returnType,after:o.returnType})}for(let r of e.endpoints)t.endpoints.find(s=>s.method===r.method&&s.path===r.path)||n.push({category:"removed-endpoint",name:`${r.method} ${r.path}`,before:`${r.method} ${r.path}`,after:"(removed)"});for(let r of e.types){if(!r.name.startsWith("enum:"))continue;let o=t.types.find(c=>c.name===r.name);if(!o){n.push({category:"narrowed-enum",name:r.name.replace("enum:",""),before:r.definition,after:"(removed)"});continue}let s=r.definition.split(",").map(c=>c.trim()).filter(Boolean),i=o.definition.split(",").map(c=>c.trim()).filter(Boolean);s.filter(c=>!i.includes(c)).length>0&&n.push({category:"narrowed-enum",name:r.name.replace("enum:",""),before:s.join(", "),after:i.join(", ")})}return n}function jm(e,t,n,r){if(n)return["# Contract Validation Report","","## Result","","No API surfaces affected. Contract validation skipped.",""].join(`
336
345
  `);let o=["# Contract Validation Report","","## Summary","","| Metric | Value |","|--------|-------|",`| Exports analyzed | ${t.exports.length} |`,`| Endpoints analyzed | ${t.endpoints.length} |`,`| Breaking changes found | ${e.length} |`,"| Contract source | inferred from source code |",""];if(e.length>0){o.push("## Breaking Changes",""),o.push("| Category | Name | Before | After |"),o.push("|----------|------|--------|-------|");for(let s of e)o.push(`| ${s.category} | ${s.name} | ${s.before} | ${s.after} |`);o.push(""),o.push("> **Human Approval Required**: Breaking changes detected. Review before proceeding.","")}if(r.length>0){o.push("## Non-JS/TS Files Skipped",""),o.push("The following files were skipped (contract validation supports JS/TS only):","");for(let s of r)o.push(`- \`${s}\``);o.push("")}if(t.exports.length>0){o.push("## Exports",""),o.push("| Name | Parameters | Return Type |"),o.push("|------|-----------|-------------|");for(let s of t.exports)o.push(`| ${s.name} | ${s.parameterCount} | ${s.returnType} |`);o.push("")}if(t.endpoints.length>0){o.push("## Endpoints",""),o.push("| Method | Path | Status Codes |"),o.push("|--------|------|-------------|");for(let s of t.endpoints){let i=s.statusCodes.length>0?s.statusCodes.join(", "):"N/A";o.push(`| ${s.method} | ${s.path} | ${i} |`)}o.push("")}if(t.types.length>0){o.push("## Types",""),o.push("| Name | Definition |"),o.push("|------|-----------|");for(let s of t.types){let i=s.name.startsWith("enum:")?`enum ${s.name.slice(5)}`:s.name;o.push(`| ${i} | ${s.definition} |`)}o.push("")}return o.join(`
337
- `)}function km(){return async e=>{let t=xt.default.join(e.projectPath,"aidlc-docs",e.workflowId,"construction",e.unitId,"testing"),n=xt.default.join(t,"contract-validation.md"),r=[...new Set([...e.unitFiles,...e.apiSurfaceFiles])],{surfaces:o,nonJsFiles:s}=nb(r);if(o.length===0){let f={status:"skipped",findings:[{id:"contract:no-api-surfaces",severity:"info",category:"skip",message:"No API surfaces detected in unit files. Contract validation skipped."}],artifactPath:n};return await In.default.ensureDir(t),await In.default.writeFile(n,wm([],{exports:[],endpoints:[],types:[]},!0,s),"utf-8"),e.allowFailures?Ee(f):f}let i=[],a={exports:[],endpoints:[],types:[]},c=[];for(let f of s)c.push({id:`contract:non-js-ts:${xt.default.basename(f)}`,severity:"warning",category:"non-js-ts-file",message:`File skipped (non-JS/TS): ${f}`,location:{file:f}});for(let f of o){let m;try{m=await In.default.readFile(f,"utf-8")}catch{c.push({id:`contract:read-error:${xt.default.basename(f)}`,severity:"warning",category:"read-error",message:`Could not read API surface file: ${f}`,location:{file:f}});continue}let g=ym(m,f);if(a.exports.push(...g.exports),a.endpoints.push(...g.endpoints),a.types.push(...g.types),e.apiSurfaceFiles.includes(f)){for(let y of e.unitFiles)if(xt.default.basename(y)===xt.default.basename(f)){let w;try{w=await In.default.readFile(y,"utf-8")}catch{continue}let k=ym(w,y);i.push(...ob(g,k))}}}for(let f of i)c.push({id:`contract:breaking:${f.category}:${f.name}`,severity:"error",category:f.category,message:`Breaking change detected (${f.category}): ${f.name} \u2014 before: ${f.before}, after: ${f.after}`});let l=c.filter(f=>f.severity==="error"),u=c.filter(f=>f.severity==="warning"),d;l.length>0?d="failed":u.length>0?d="warned":d="passed",await In.default.ensureDir(t),await In.default.writeFile(n,wm(i,a,!1,s),"utf-8");let p={status:d,findings:c,artifactPath:n};return e.allowFailures?Ee(p):p}}var In,xt,eb,tb,_m=U(()=>{"use strict";In=T(X(),1),xt=T(require("path"),1);xn();eb=new Set([".ts",".tsx",".js",".jsx"]),tb=[/[/\\]routes[/\\]/,/[/\\]controllers[/\\]/,/[/\\]api[/\\]/,/[/\\]handlers[/\\]/]});function ib(e){let t=sb;try{let r=[He.default.resolve(He.default.dirname(new URL(mb.url).pathname),"../../../../resources/config/risk-keywords.json"),He.default.resolve(process.cwd(),"resources/config/risk-keywords.json")];for(let o of r){let s=o.startsWith("/")&&o[2]===":"?o.slice(1):o;if(Ae.default.existsSync(s)){t=JSON.parse(Ae.default.readFileSync(s,"utf-8"));break}}}catch(r){}let n=He.default.join(e,".olympus","config.json");if(Ae.default.existsSync(n))try{let o=JSON.parse(Ae.default.readFileSync(n,"utf-8"))["risk-keywords"];if(o)return{critical:o.critical??t.critical,moderate:o.moderate??t.moderate,low:o.low??t.low}}catch(r){}return t}function ab(e,t,n){let r=`${e.toLowerCase()}
338
- ${t.toLowerCase()}`;for(let o of n.critical)if(new RegExp(`\\b${o}\\b`,"i").test(r))return"critical";for(let o of n.moderate)if(new RegExp(`\\b${o}\\b`,"i").test(r))return"moderate";return"low"}async function cb(e,t){let n=He.default.join(e,"coverage","coverage-summary.json");if(await Ae.default.pathExists(n))try{let o=JSON.parse(await Ae.default.readFile(n,"utf-8")),s=[];for(let[i,a]of Object.entries(o))i!=="total"&&s.push({filePath:i,lineCoverage:a.lines?.pct,branchCoverage:a.branches?.pct,functionCoverage:a.functions?.pct});return{source:"instrumentation",files:s}}catch(o){}let r=[];for(let o of t){let s=He.default.parse(o),i=[He.default.join(s.dir,`${s.name}.test${s.ext}`),He.default.join(s.dir,`${s.name}.spec${s.ext}`),o.replace(/src\//,"src/__tests__/").replace(/\.(ts|js)$/,".test.$1")],a=!1;for(let c of i)if(await Ae.default.pathExists(c)){a=!0;break}r.push({filePath:o,lineCoverage:a?100:0,branchCoverage:a?100:0,functionCoverage:a?100:0})}return{source:"static-analysis",files:r}}function lb(e){return e>=90?"Exemplary":e>=75?"Commendable":e>=60?"Acceptable":""}function ub(e){let t=He.default.join(e,".olympus","config.json");if(Ae.default.existsSync(t))try{let r=JSON.parse(Ae.default.readFileSync(t,"utf-8"))["coverage-thresholds"];if(r)return{critical:r.critical??ps.critical,moderate:r.moderate??ps.moderate,low:r.low??ps.low}}catch(n){}return{...ps}}function db(e,t,n=""){let r=ub(n);return["critical","moderate","low"].map(o=>{let s=e[o],i=r[o],a=s>=i,c;return a?c="info":t>=3?c="block":t===2?c="warn":c="info",{tier:o,coverage:s,threshold:i,met:a,enforcement:c}})}function pb(e,t,n,r,o,s){let i=e.files,a=i.length,c=a>0?i.reduce((f,m)=>f+(m.lineCoverage??0),0)/a:0,l=a>0?i.reduce((f,m)=>f+(m.branchCoverage??0),0)/a:0,u=a>0?i.reduce((f,m)=>f+(m.functionCoverage??0),0)/a:0,d=[`| Source | ${e.source} |`,`| Total files | ${a} |`,`| Line coverage | ${c.toFixed(1)}% |`,`| Branch coverage | ${l.toFixed(1)}% |`,`| Function coverage | ${u.toFixed(1)}% |`];o&&d.push(`| Quality label | ${o} |`);let p=["# Coverage Report","","## Summary","","| Metric | Value |","|--------|-------|",...d,"","## Threshold Results","","| Tier | Coverage | Threshold | Met | Enforcement |","|------|----------|-----------|-----|-------------|",...n.map(f=>`| ${f.tier} | ${f.coverage.toFixed(1)}% | ${f.threshold}% | ${f.met?"yes":"no"} | ${f.met?"n/a":f.enforcement} |`),""];for(let f of["critical","moderate","low"]){let m=i.filter(k=>s.get(k.filePath)===f&&(k.lineCoverage??0)<100);if(m.length===0)continue;let g=m.slice(0,20),y=m.length>20,w=f.charAt(0).toUpperCase()+f.slice(1);p.push(`## Uncovered Files \u2014 ${w} Tier`,""),y&&p.push(`> Showing top 20 of ${m.length} files. Full list in \`coverage-detail.md\`.`,""),p.push("| File | Line % | Branch % | Function % |"),p.push("|------|--------|----------|------------|");for(let k of g){let h=k.filePath.length>60?`...${k.filePath.slice(-57)}`:k.filePath;p.push(`| ${h} | ${(k.lineCoverage??0).toFixed(1)}% | ${(k.branchCoverage??0).toFixed(1)}% | ${(k.functionCoverage??0).toFixed(1)}% |`)}p.push("")}return p.join(`
339
- `)}function fb(e,t){let n=["# Coverage Detail","",`Source: ${e.source}`,"","## All Files","","| File | Tier | Line % | Branch % | Function % |","|------|------|--------|----------|------------|"];for(let r of e.files){let o=t.get(r.filePath)??"low",s=r.filePath.length>70?`...${r.filePath.slice(-67)}`:r.filePath;n.push(`| ${s} | ${o} | ${(r.lineCoverage??0).toFixed(1)}% | ${(r.branchCoverage??0).toFixed(1)}% | ${(r.functionCoverage??0).toFixed(1)}% |`)}return n.push(""),n.join(`
340
- `)}function Sm(){return async e=>{let t=ib(e.projectPath),n=await cb(e.projectPath,e.unitFiles),r=new Map;for(let h of n.files){let v="";try{await Ae.default.pathExists(h.filePath)&&(v=await Ae.default.readFile(h.filePath,"utf-8"))}catch(S){}r.set(h.filePath,ab(h.filePath,v,t))}let o={critical:[],moderate:[],low:[]};for(let h of n.files){let v=r.get(h.filePath)??"low";o[v].push(h)}function s(h){return h.length===0?100:h.reduce((v,S)=>v+(S.lineCoverage??0),0)/h.length}let i={critical:s(o.critical),moderate:s(o.moderate),low:s(o.low)},a=db(i,e.workflowDepth,e.projectPath),c=[];for(let h of a)if(!h.met){let v=h.enforcement==="block"?"error":h.enforcement==="warn"?"warning":"info";c.push({id:`coverage-threshold:${h.tier}`,severity:v,category:"coverage-threshold",message:`${h.tier.charAt(0).toUpperCase()+h.tier.slice(1)} tier coverage is ${h.coverage.toFixed(1)}% (threshold: ${h.threshold}%)`})}for(let h of o.critical)(h.lineCoverage??0)===0&&c.push({id:`uncovered-critical:${h.filePath}`,severity:"warning",category:"uncovered-critical-file",message:`Critical-tier file has 0% coverage: ${h.filePath}`,location:{file:h.filePath}});let l=c.some(h=>h.severity==="error"),u=c.some(h=>h.severity==="warning"),d;l?d="failed":u?d="warned":d="passed";let p=n.files,f=p.length>0?p.reduce((h,v)=>h+(v.lineCoverage??0),0)/p.length:100,m=lb(f),g=He.default.join(e.projectPath,"aidlc-docs",e.workflowId,"construction",e.unitId,"testing");await Ae.default.ensureDir(g);let y=He.default.join(g,"coverage-report.md");await Ae.default.writeFile(y,pb(n,i,a,t,m,r),"utf-8"),(["critical","moderate","low"].some(h=>o[h].filter(v=>(v.lineCoverage??0)<100).length>20)||n.files.length>20)&&await Ae.default.writeFile(He.default.join(g,"coverage-detail.md"),fb(n,r),"utf-8");let k={status:d,findings:c,artifactPath:y,coverage_percentage:Math.round(f*10)/10};return e.allowFailures?Ee(k):k}}var Ae,He,mb,ps,sb,vm=U(()=>{"use strict";Ae=T(X(),1),He=T(require("path"),1);xn();mb={},ps={critical:80,moderate:60,low:40},sb={critical:["auth","payment","security","encrypt","token","credential","password","session","permission"],moderate:["validate","transform","process","persist","database","query","transaction","migrate","cache"],low:["log","format","display","util","helper","config","constant","mock","fixture"]}});var Tm={};he(Tm,{applyAllowFailures:()=>Ee,calculateNegativeCaseRatio:()=>ls,createContractValidator:()=>km,createCoverageValidator:()=>Sm,createMutationValidator:()=>dm,createQualityValidator:()=>cm,createTraceabilityValidator:()=>gm,detectAntiPatterns:()=>cs,runValidationPipeline:()=>rm,shouldSkipValidator:()=>om,updateCheckpointForValidator:()=>sm});var Em=U(()=>{"use strict";xn();lm();pm();hm();xa();_m();vm()});var $m={};he($m,{appendOlympusSection:()=>Am,categorizeChanges:()=>Rm,createNewChangelog:()=>Om,detectExistingChangelogTool:()=>bm,formatChangelogEntry:()=>xm,generateChangelogEntry:()=>gb,isKeepAChangelogFormat:()=>Pm,prependToChangelog:()=>Im,readFeatureDocSummaries:()=>Cm});function bm(e){let t=[{files:[".versionrc",".versionrc.json",".versionrc.js"],tool:"conventional-changelog"},{files:[".changeset"],tool:"changesets"},{files:["cliff.toml"],tool:"git-cliff"}];for(let{files:n,tool:r}of t)for(let o of n){let s=Zr.join(e,o);if(Me.existsSync(s))return r}return null}function Cm(e,t){let n=[];for(let r of t){let o=Zr.join(e,"construction",r,"documentation","feature-doc.md");if(!Me.existsSync(o))continue;let i=Me.readFileSync(o,"utf-8").match(/## Summary\n\n([\s\S]*?)(?=\n## |\n---|\Z)/);i&&i[1].trim()&&n.push({unitId:r,summary:i[1].trim()})}return n}function Rm(e,t){let n={added:[],changed:[],fixed:[]};for(let{summary:r}of e){let o=r.split(`
341
- `)[0].trim();o&&(t==="bugfix"?n.fixed.push(o):/(?:add|create|implement|introduce|new)/i.test(o)?n.added.push(o):/(?:fix|repair|resolve|patch|correct)/i.test(o)?n.fixed.push(o):/(?:update|change|modify|refactor|improve|enhance)/i.test(o)?n.changed.push(o):n.added.push(o))}return n}function xm(e,t,n){let r=[`## [${e}] - ${t}`,""];if(n.added.length>0){r.push("### Added","");for(let o of n.added)r.push(`- ${o}`);r.push("")}if(n.changed.length>0){r.push("### Changed","");for(let o of n.changed)r.push(`- ${o}`);r.push("")}if(n.fixed.length>0){r.push("### Fixed","");for(let o of n.fixed)r.push(`- ${o}`);r.push("")}return r.join(`
342
- `)}function Pm(e){return/^# (?:Changelog|Change\s*Log)/im.test(e)||/^## \[/m.test(e)}function Im(e,t){let n=Me.readFileSync(e,"utf-8"),r=n.match(/^## \[/m);if(r&&r.index!==void 0){let o=n.substring(0,r.index),s=n.substring(r.index);Me.writeFileSync(e,o+t+`
346
+ `)}function Mm(){return async e=>{let t=Pt.default.join(e.projectPath,"aidlc-docs",e.workflowId,"construction",e.unitId,"testing"),n=Pt.default.join(t,"contract-validation.md"),r=[...new Set([...e.unitFiles,...e.apiSurfaceFiles])],{surfaces:o,nonJsFiles:s}=vE(r);if(o.length===0){let f={status:"skipped",findings:[{id:"contract:no-api-surfaces",severity:"info",category:"skip",message:"No API surfaces detected in unit files. Contract validation skipped."}],artifactPath:n};return await An.default.ensureDir(t),await An.default.writeFile(n,jm([],{exports:[],endpoints:[],types:[]},!0,s),"utf-8"),e.allowFailures?Ee(f):f}let i=[],a={exports:[],endpoints:[],types:[]},c=[];for(let f of s)c.push({id:`contract:non-js-ts:${Pt.default.basename(f)}`,severity:"warning",category:"non-js-ts-file",message:`File skipped (non-JS/TS): ${f}`,location:{file:f}});for(let f of o){let m;try{m=await An.default.readFile(f,"utf-8")}catch{c.push({id:`contract:read-error:${Pt.default.basename(f)}`,severity:"warning",category:"read-error",message:`Could not read API surface file: ${f}`,location:{file:f}});continue}let g=Fm(m,f);if(a.exports.push(...g.exports),a.endpoints.push(...g.endpoints),a.types.push(...g.types),e.apiSurfaceFiles.includes(f)){for(let y of e.unitFiles)if(Pt.default.basename(y)===Pt.default.basename(f)){let w;try{w=await An.default.readFile(y,"utf-8")}catch{continue}let _=Fm(w,y);i.push(...TE(g,_))}}}for(let f of i)c.push({id:`contract:breaking:${f.category}:${f.name}`,severity:"error",category:f.category,message:`Breaking change detected (${f.category}): ${f.name} \u2014 before: ${f.before}, after: ${f.after}`});let l=c.filter(f=>f.severity==="error"),u=c.filter(f=>f.severity==="warning"),d;l.length>0?d="failed":u.length>0?d="warned":d="passed",await An.default.ensureDir(t),await An.default.writeFile(n,jm(i,a,!1,s),"utf-8");let p={status:d,findings:c,artifactPath:n};return e.allowFailures?Ee(p):p}}var An,Pt,kE,SE,Lm=U(()=>{"use strict";An=b(X(),1),Pt=b(require("path"),1);xn();kE=new Set([".ts",".tsx",".js",".jsx"]),SE=[/[/\\]routes[/\\]/,/[/\\]controllers[/\\]/,/[/\\]api[/\\]/,/[/\\]handlers[/\\]/]});function CE(e){let t=EE;try{let r=[Ve.default.resolve(Ve.default.dirname(new URL(DE.url).pathname),"../../../../resources/config/risk-keywords.json"),Ve.default.resolve(process.cwd(),"resources/config/risk-keywords.json")];for(let o of r){let s=o.startsWith("/")&&o[2]===":"?o.slice(1):o;if(Ie.default.existsSync(s)){t=JSON.parse(Ie.default.readFileSync(s,"utf-8"));break}}}catch(r){}let n=Ve.default.join(e,".olympus","config.json");if(Ie.default.existsSync(n))try{let o=JSON.parse(Ie.default.readFileSync(n,"utf-8"))["risk-keywords"];if(o)return{critical:o.critical??t.critical,moderate:o.moderate??t.moderate,low:o.low??t.low}}catch(r){}return t}function RE(e,t,n){let r=`${e.toLowerCase()}
347
+ ${t.toLowerCase()}`;for(let o of n.critical)if(new RegExp(`\\b${o}\\b`,"i").test(r))return"critical";for(let o of n.moderate)if(new RegExp(`\\b${o}\\b`,"i").test(r))return"moderate";return"low"}async function xE(e,t){let n=Ve.default.join(e,"coverage","coverage-summary.json");if(await Ie.default.pathExists(n))try{let o=JSON.parse(await Ie.default.readFile(n,"utf-8")),s=[];for(let[i,a]of Object.entries(o))i!=="total"&&s.push({filePath:i,lineCoverage:a.lines?.pct,branchCoverage:a.branches?.pct,functionCoverage:a.functions?.pct});return{source:"instrumentation",files:s}}catch(o){}let r=[];for(let o of t){let s=Ve.default.parse(o),i=[Ve.default.join(s.dir,`${s.name}.test${s.ext}`),Ve.default.join(s.dir,`${s.name}.spec${s.ext}`),o.replace(/src\//,"src/__tests__/").replace(/\.(ts|js)$/,".test.$1")],a=!1;for(let c of i)if(await Ie.default.pathExists(c)){a=!0;break}r.push({filePath:o,lineCoverage:a?100:0,branchCoverage:a?100:0,functionCoverage:a?100:0})}return{source:"static-analysis",files:r}}function PE(e){return e>=90?"Exemplary":e>=75?"Commendable":e>=60?"Acceptable":""}function AE(e){let t=Ve.default.join(e,".olympus","config.json");if(Ie.default.existsSync(t))try{let r=JSON.parse(Ie.default.readFileSync(t,"utf-8"))["coverage-thresholds"];if(r)return{critical:r.critical??hs.critical,moderate:r.moderate??hs.moderate,low:r.low??hs.low}}catch(n){}return{...hs}}function IE(e,t,n=""){let r=AE(n);return["critical","moderate","low"].map(o=>{let s=e[o],i=r[o],a=s>=i,c;return a?c="info":t>=3?c="block":t===2?c="warn":c="info",{tier:o,coverage:s,threshold:i,met:a,enforcement:c}})}function OE(e,t,n,r,o,s){let i=e.files,a=i.length,c=a>0?i.reduce((f,m)=>f+(m.lineCoverage??0),0)/a:0,l=a>0?i.reduce((f,m)=>f+(m.branchCoverage??0),0)/a:0,u=a>0?i.reduce((f,m)=>f+(m.functionCoverage??0),0)/a:0,d=[`| Source | ${e.source} |`,`| Total files | ${a} |`,`| Line coverage | ${c.toFixed(1)}% |`,`| Branch coverage | ${l.toFixed(1)}% |`,`| Function coverage | ${u.toFixed(1)}% |`];o&&d.push(`| Quality label | ${o} |`);let p=["# Coverage Report","","## Summary","","| Metric | Value |","|--------|-------|",...d,"","## Threshold Results","","| Tier | Coverage | Threshold | Met | Enforcement |","|------|----------|-----------|-----|-------------|",...n.map(f=>`| ${f.tier} | ${f.coverage.toFixed(1)}% | ${f.threshold}% | ${f.met?"yes":"no"} | ${f.met?"n/a":f.enforcement} |`),""];for(let f of["critical","moderate","low"]){let m=i.filter(_=>s.get(_.filePath)===f&&(_.lineCoverage??0)<100);if(m.length===0)continue;let g=m.slice(0,20),y=m.length>20,w=f.charAt(0).toUpperCase()+f.slice(1);p.push(`## Uncovered Files \u2014 ${w} Tier`,""),y&&p.push(`> Showing top 20 of ${m.length} files. Full list in \`coverage-detail.md\`.`,""),p.push("| File | Line % | Branch % | Function % |"),p.push("|------|--------|----------|------------|");for(let _ of g){let h=_.filePath.length>60?`...${_.filePath.slice(-57)}`:_.filePath;p.push(`| ${h} | ${(_.lineCoverage??0).toFixed(1)}% | ${(_.branchCoverage??0).toFixed(1)}% | ${(_.functionCoverage??0).toFixed(1)}% |`)}p.push("")}return p.join(`
348
+ `)}function $E(e,t){let n=["# Coverage Detail","",`Source: ${e.source}`,"","## All Files","","| File | Tier | Line % | Branch % | Function % |","|------|------|--------|----------|------------|"];for(let r of e.files){let o=t.get(r.filePath)??"low",s=r.filePath.length>70?`...${r.filePath.slice(-67)}`:r.filePath;n.push(`| ${s} | ${o} | ${(r.lineCoverage??0).toFixed(1)}% | ${(r.branchCoverage??0).toFixed(1)}% | ${(r.functionCoverage??0).toFixed(1)}% |`)}return n.push(""),n.join(`
349
+ `)}function Um(){return async e=>{let t=CE(e.projectPath),n=await xE(e.projectPath,e.unitFiles),r=new Map;for(let h of n.files){let v="";try{await Ie.default.pathExists(h.filePath)&&(v=await Ie.default.readFile(h.filePath,"utf-8"))}catch(S){}r.set(h.filePath,RE(h.filePath,v,t))}let o={critical:[],moderate:[],low:[]};for(let h of n.files){let v=r.get(h.filePath)??"low";o[v].push(h)}function s(h){return h.length===0?100:h.reduce((v,S)=>v+(S.lineCoverage??0),0)/h.length}let i={critical:s(o.critical),moderate:s(o.moderate),low:s(o.low)},a=IE(i,e.workflowDepth,e.projectPath),c=[];for(let h of a)if(!h.met){let v=h.enforcement==="block"?"error":h.enforcement==="warn"?"warning":"info";c.push({id:`coverage-threshold:${h.tier}`,severity:v,category:"coverage-threshold",message:`${h.tier.charAt(0).toUpperCase()+h.tier.slice(1)} tier coverage is ${h.coverage.toFixed(1)}% (threshold: ${h.threshold}%)`})}for(let h of o.critical)(h.lineCoverage??0)===0&&c.push({id:`uncovered-critical:${h.filePath}`,severity:"warning",category:"uncovered-critical-file",message:`Critical-tier file has 0% coverage: ${h.filePath}`,location:{file:h.filePath}});let l=c.some(h=>h.severity==="error"),u=c.some(h=>h.severity==="warning"),d;l?d="failed":u?d="warned":d="passed";let p=n.files,f=p.length>0?p.reduce((h,v)=>h+(v.lineCoverage??0),0)/p.length:100,m=PE(f),g=Ve.default.join(e.projectPath,"aidlc-docs",e.workflowId,"construction",e.unitId,"testing");await Ie.default.ensureDir(g);let y=Ve.default.join(g,"coverage-report.md");await Ie.default.writeFile(y,OE(n,i,a,t,m,r),"utf-8"),(["critical","moderate","low"].some(h=>o[h].filter(v=>(v.lineCoverage??0)<100).length>20)||n.files.length>20)&&await Ie.default.writeFile(Ve.default.join(g,"coverage-detail.md"),$E(n,r),"utf-8");let _={status:d,findings:c,artifactPath:y,coverage_percentage:Math.round(f*10)/10};return e.allowFailures?Ee(_):_}}var Ie,Ve,DE,hs,EE,Wm=U(()=>{"use strict";Ie=b(X(),1),Ve=b(require("path"),1);xn();DE={},hs={critical:80,moderate:60,low:40},EE={critical:["auth","payment","security","encrypt","token","credential","password","session","permission"],moderate:["validate","transform","process","persist","database","query","transaction","migrate","cache"],low:["log","format","display","util","helper","config","constant","mock","fixture"]}});var Bm={};he(Bm,{applyAllowFailures:()=>Ee,calculateNegativeCaseRatio:()=>fs,createContractValidator:()=>Mm,createCoverageValidator:()=>Um,createMutationValidator:()=>Am,createQualityValidator:()=>Rm,createTraceabilityValidator:()=>Dm,detectAntiPatterns:()=>ps,runValidationPipeline:()=>vm,shouldSkipValidator:()=>bm,updateCheckpointForValidator:()=>Tm});var Gm=U(()=>{"use strict";xn();xm();Im();Nm();Na();Lm();Wm()});var Xm={};he(Xm,{appendOlympusSection:()=>zm,categorizeChanges:()=>qm,createNewChangelog:()=>Qm,detectExistingChangelogTool:()=>Hm,formatChangelogEntry:()=>Ym,generateChangelogEntry:()=>NE,isKeepAChangelogFormat:()=>Km,prependToChangelog:()=>Jm,readFeatureDocSummaries:()=>Vm});function Hm(e){let t=[{files:[".versionrc",".versionrc.json",".versionrc.js"],tool:"conventional-changelog"},{files:[".changeset"],tool:"changesets"},{files:["cliff.toml"],tool:"git-cliff"}];for(let{files:n,tool:r}of t)for(let o of n){let s=Zr.join(e,o);if(Me.existsSync(s))return r}return null}function Vm(e,t){let n=[];for(let r of t){let o=Zr.join(e,"construction",r,"documentation","feature-doc.md");if(!Me.existsSync(o))continue;let i=Me.readFileSync(o,"utf-8").match(/## Summary\n\n([\s\S]*?)(?=\n## |\n---|\Z)/);i&&i[1].trim()&&n.push({unitId:r,summary:i[1].trim()})}return n}function qm(e,t){let n={added:[],changed:[],fixed:[]};for(let{summary:r}of e){let o=r.split(`
350
+ `)[0].trim();o&&(t==="bugfix"?n.fixed.push(o):/(?:add|create|implement|introduce|new)/i.test(o)?n.added.push(o):/(?:fix|repair|resolve|patch|correct)/i.test(o)?n.fixed.push(o):/(?:update|change|modify|refactor|improve|enhance)/i.test(o)?n.changed.push(o):n.added.push(o))}return n}function Ym(e,t,n){let r=[`## [${e}] - ${t}`,""];if(n.added.length>0){r.push("### Added","");for(let o of n.added)r.push(`- ${o}`);r.push("")}if(n.changed.length>0){r.push("### Changed","");for(let o of n.changed)r.push(`- ${o}`);r.push("")}if(n.fixed.length>0){r.push("### Fixed","");for(let o of n.fixed)r.push(`- ${o}`);r.push("")}return r.join(`
351
+ `)}function Km(e){return/^# (?:Changelog|Change\s*Log)/im.test(e)||/^## \[/m.test(e)}function Jm(e,t){let n=Me.readFileSync(e,"utf-8"),r=n.match(/^## \[/m);if(r&&r.index!==void 0){let o=n.substring(0,r.index),s=n.substring(r.index);Me.writeFileSync(e,o+t+`
343
352
  `+s)}else Me.writeFileSync(e,n+`
344
- `+t)}function Am(e,t){let n=Me.readFileSync(e,"utf-8"),r=["","<!-- Olympus AI-DLC Generated -->",t,"<!-- End Olympus AI-DLC Generated -->",""].join(`
345
- `);Me.writeFileSync(e,n+r)}function Om(e,t){let n=["# Changelog","","All notable changes to this project will be documented in this file.","","The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).",""].join(`
346
- `);Me.writeFileSync(e,n+t)}function gb(e){let t=bm(e.projectPath);if(t)return{status:"skipped",path:null,entriesAdded:0,skipReason:`Changelog managed by ${t}`};let n=Zr.join(e.projectPath,"aidlc-docs",e.workflowId),r=Cm(n,e.unitIds);if(r.length===0)return{status:"skipped",path:null,entriesAdded:0,skipReason:"No feature doc summaries found"};let o=Rm(r,e.pathway),s=new Date().toISOString().split("T")[0],i=xm(e.workflowId,s,o),a=Zr.join(e.projectPath,"CHANGELOG.md");if(Me.existsSync(a)){let l=Me.readFileSync(a,"utf-8");Pm(l)?Im(a,i):Am(a,i)}else Om(a,i);let c=o.added.length+o.changed.length+o.fixed.length;return{status:"completed",path:a,entriesAdded:c}}var Me,Zr,Dm=U(()=>{"use strict";Me=T(require("fs"),1),Zr=T(require("path"),1)});async function Nm(e,t,n){let r=ar.default.join(e,"aidlc-docs",t,"inception","requirements","nfr.md"),o=ar.default.join(e,"aidlc-docs",t,"construction",n,"spec.md"),s=ar.default.join(e,"aidlc-docs",t,"construction",n,"nfr-requirements.md"),i="";try{await An.default.pathExists(r)&&(i=await An.default.readFile(r,"utf-8"))}catch{}let a="";try{await An.default.pathExists(o)&&(a=await An.default.readFile(o,"utf-8"))}catch{}let c=a.match(/^title:\s*(.+)$/m),l=c?c[1].trim().replace(/^["']|["']$/g,""):n,u=hb(i,a,l),d=new Date().toISOString(),p=`---
353
+ `+t)}function zm(e,t){let n=Me.readFileSync(e,"utf-8"),r=["","<!-- Olympus AI-DLC Generated -->",t,"<!-- End Olympus AI-DLC Generated -->",""].join(`
354
+ `);Me.writeFileSync(e,n+r)}function Qm(e,t){let n=["# Changelog","","All notable changes to this project will be documented in this file.","","The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).",""].join(`
355
+ `);Me.writeFileSync(e,n+t)}function NE(e){let t=Hm(e.projectPath);if(t)return{status:"skipped",path:null,entriesAdded:0,skipReason:`Changelog managed by ${t}`};let n=Zr.join(e.projectPath,"aidlc-docs",e.workflowId),r=Vm(n,e.unitIds);if(r.length===0)return{status:"skipped",path:null,entriesAdded:0,skipReason:"No feature doc summaries found"};let o=qm(r,e.pathway),s=new Date().toISOString().split("T")[0],i=Ym(e.workflowId,s,o),a=Zr.join(e.projectPath,"CHANGELOG.md");if(Me.existsSync(a)){let l=Me.readFileSync(a,"utf-8");Km(l)?Jm(a,i):zm(a,i)}else Qm(a,i);let c=o.added.length+o.changed.length+o.fixed.length;return{status:"completed",path:a,entriesAdded:c}}var Me,Zr,Zm=U(()=>{"use strict";Me=b(require("fs"),1),Zr=b(require("path"),1)});async function eg(e,t,n){let r=cr.default.join(e,"aidlc-docs",t,"inception","requirements","nfr.md"),o=cr.default.join(e,"aidlc-docs",t,"construction",n,"spec.md"),s=cr.default.join(e,"aidlc-docs",t,"construction",n,"nfr-requirements.md"),i="";try{await In.default.pathExists(r)&&(i=await In.default.readFile(r,"utf-8"))}catch{}let a="";try{await In.default.pathExists(o)&&(a=await In.default.readFile(o,"utf-8"))}catch{}let c=a.match(/^title:\s*(.+)$/m),l=c?c[1].trim().replace(/^["']|["']$/g,""):n,u=FE(i,a,l),d=new Date().toISOString(),p=`---
347
356
  id: ${n}-nfr-requirements
348
357
  parent_unit: ${n}
349
358
  generated_at: ${d}
@@ -360,8 +369,8 @@ ${u||"_No specific NFRs identified for this unit. Inherit project-level defaults
360
369
 
361
370
  ## Unit Context
362
371
  ${l}
363
- `;await An.default.ensureDir(ar.default.dirname(s)),await An.default.writeFile(s,p,"utf-8");try{let f=ar.default.join(e,"aidlc-docs",t,"manifest.json");Ne(f,{id:`${n}-nfr-requirements`,type:"NFR_REQUIREMENTS",phase:"construction",stage:"unit",path:s,validation_passed:null,write_complete:!0,checksum:null})}catch(f){console.error(`[NFRRequirements] Failed to register artifact for ${n}:`,f)}return{artifactPath:s,nfrContent:u}}function hb(e,t,n){if(!e.trim())return"";let r=e.split(/(?=^## )/m).filter(a=>a.trim());if(r.length===0)return e;let o=yb(t+" "+n);if(o.length===0)return e;let i=r.map(a=>{let c=a.toLowerCase(),l=o.filter(u=>c.includes(u)).length;return{section:a,score:l}}).filter(a=>a.score>0);return i.length===0?e:i.map(a=>a.section).join(`
364
- `)}function yb(e){let t=new Set(["the","a","an","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","shall","can","need","must","ought","and","or","but","if","then","else","when","at","from","by","on","off","for","in","out","over","to","into","with","not","no","nor","as","of","this","that","these","those","it","its","all","each","any","both","few","more","most","other","some","such","than","too","very"]);return e.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(n=>n.length>3&&!t.has(n)).filter((n,r,o)=>o.indexOf(n)===r).slice(0,30)}var An,ar,Fm=U(()=>{"use strict";An=T(X(),1),ar=T(require("path"),1);Z()});var jm={};he(jm,{UnitStageRunner:()=>Ia});var Le,Wt,wb,Ia,Mm=U(()=>{"use strict";Le=T(X(),1),Wt=T(require("path"),1);Fm();wb={SHALLOW:[],MEDIUM:["functional-design","nfr-requirements"],DEEP:["functional-design","nfr-requirements","nfr-design","infrastructure-design"]},Ia=class{projectPath;workflowId;constructor(t,n){this.projectPath=t,this.workflowId=n}async executeForUnit(t,n,r,o){let s=wb[n],i=Wt.default.join(this.projectPath,"aidlc-docs",this.workflowId,"construction",t),a=["functional-design","nfr-requirements","nfr-design","infrastructure-design","code-generation"],c={unitId:t,stages:{},code_plan_path:null,code_generation_status:"not_started"};for(let u of a)c.stages[u]={status:s.includes(u)?"not_started":"skipped",artifact_path:null,completed_at:null};if(s.length===0)return console.log(`[UnitStageRunner] SHALLOW depth: skipping all design stages for ${t}`),c;console.log(`[UnitStageRunner] Running ${s.length} design stages for ${t} (${n})`);let l="";try{let u=Wt.default.join(i,"spec.md");await Le.default.pathExists(u)&&(l=await Le.default.readFile(u,"utf-8"))}catch{}for(let u of s){c.stages[u].status="in_progress";try{let d=await this.executeStage(u,t,i,l,r,o);c.stages[u].status="completed",c.stages[u].artifact_path=d,c.stages[u].completed_at=new Date().toISOString(),console.log(`[UnitStageRunner] ${t}/${u} completed -> ${d}`)}catch(d){console.error(`[UnitStageRunner] ${t}/${u} failed:`,d),c.stages[u].status="not_started"}}return await this.appendAudit(t,s,c),c}async executeStage(t,n,r,o,s,i){switch(await Le.default.ensureDir(r),t){case"functional-design":{let a=Wt.default.join(r,"functional-design.md"),c=this.buildFunctionalDesignContent(n,o,s);return await Le.default.writeFile(a,c,"utf-8"),a}case"nfr-requirements":return(await Nm(this.projectPath,this.workflowId,n)).artifactPath;case"nfr-design":{let a=Wt.default.join(r,"nfr-design.md"),c=Wt.default.join(r,"nfr-requirements.md"),l=i||"";try{await Le.default.pathExists(c)&&(l=await Le.default.readFile(c,"utf-8"))}catch{}let u=this.buildNFRDesignContent(n,o,l);return await Le.default.writeFile(a,u,"utf-8"),a}case"infrastructure-design":{let a=Wt.default.join(r,"infrastructure-design.md"),c=Wt.default.join(r,"nfr-design.md"),l="";try{await Le.default.pathExists(c)&&(l=await Le.default.readFile(c,"utf-8"))}catch{}let u=this.buildInfrastructureDesignContent(n,o,l);return await Le.default.writeFile(a,u,"utf-8"),a}default:throw new Error(`Stage '${t}' not handled by UnitStageRunner`)}}buildFunctionalDesignContent(t,n,r){let o=n.match(/^title:\s*(.+)$/m),s=o?o[1].trim().replace(/^["']|["']$/g,""):t,i=new Date().toISOString();return`---
372
+ `;await In.default.ensureDir(cr.default.dirname(s)),await In.default.writeFile(s,p,"utf-8");try{let f=cr.default.join(e,"aidlc-docs",t,"manifest.json");Ne(f,{id:`${n}-nfr-requirements`,type:"NFR_REQUIREMENTS",phase:"construction",stage:"unit",path:s,validation_passed:null,write_complete:!0,checksum:null})}catch(f){console.error(`[NFRRequirements] Failed to register artifact for ${n}:`,f)}return{artifactPath:s,nfrContent:u}}function FE(e,t,n){if(!e.trim())return"";let r=e.split(/(?=^## )/m).filter(a=>a.trim());if(r.length===0)return e;let o=jE(t+" "+n);if(o.length===0)return e;let i=r.map(a=>{let c=a.toLowerCase(),l=o.filter(u=>c.includes(u)).length;return{section:a,score:l}}).filter(a=>a.score>0);return i.length===0?e:i.map(a=>a.section).join(`
373
+ `)}function jE(e){let t=new Set(["the","a","an","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","shall","can","need","must","ought","and","or","but","if","then","else","when","at","from","by","on","off","for","in","out","over","to","into","with","not","no","nor","as","of","this","that","these","those","it","its","all","each","any","both","few","more","most","other","some","such","than","too","very"]);return e.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(n=>n.length>3&&!t.has(n)).filter((n,r,o)=>o.indexOf(n)===r).slice(0,30)}var In,cr,tg=U(()=>{"use strict";In=b(X(),1),cr=b(require("path"),1);Z()});var ng={};he(ng,{UnitStageRunner:()=>ja});var Le,Ht,ME,ja,rg=U(()=>{"use strict";Le=b(X(),1),Ht=b(require("path"),1);tg();ME={SHALLOW:[],MEDIUM:["functional-design","nfr-requirements"],DEEP:["functional-design","nfr-requirements","nfr-design","infrastructure-design"]},ja=class{projectPath;workflowId;constructor(t,n){this.projectPath=t,this.workflowId=n}async executeForUnit(t,n,r,o){let s=ME[n],i=Ht.default.join(this.projectPath,"aidlc-docs",this.workflowId,"construction",t),a=["functional-design","nfr-requirements","nfr-design","infrastructure-design","code-generation"],c={unitId:t,stages:{},code_plan_path:null,code_generation_status:"not_started"};for(let u of a)c.stages[u]={status:s.includes(u)?"not_started":"skipped",artifact_path:null,completed_at:null,failure_count:0,last_error:null};if(s.length===0)return console.log(`[UnitStageRunner] SHALLOW depth: skipping all design stages for ${t}`),c;console.log(`[UnitStageRunner] Running ${s.length} design stages for ${t} (${n})`);let l="";try{let u=Ht.default.join(i,"spec.md");await Le.default.pathExists(u)&&(l=await Le.default.readFile(u,"utf-8"))}catch{}for(let u of s){c.stages[u].status="in_progress";try{let d=await this.executeStage(u,t,i,l,r,o);c.stages[u].status="completed",c.stages[u].artifact_path=d,c.stages[u].completed_at=new Date().toISOString(),console.log(`[UnitStageRunner] ${t}/${u} completed -> ${d}`)}catch(d){if(c.stages[u].failure_count+=1,c.stages[u].last_error=d instanceof Error?d.message:String(d),c.stages[u].failure_count>=2){c.stages[u].status="failed",console.error(`[UnitStageRunner] ${t}/${u} failed after ${c.stages[u].failure_count} attempts \u2014 escalating`);break}else c.stages[u].status="not_started",console.warn(`[UnitStageRunner] ${t}/${u} failed (attempt ${c.stages[u].failure_count}/2), will retry`)}}return await this.appendAudit(t,s,c),c}async executeStage(t,n,r,o,s,i){switch(await Le.default.ensureDir(r),t){case"functional-design":{let a=Ht.default.join(r,"functional-design.md"),c=this.buildFunctionalDesignContent(n,o,s);return await Le.default.writeFile(a,c,"utf-8"),a}case"nfr-requirements":return(await eg(this.projectPath,this.workflowId,n)).artifactPath;case"nfr-design":{let a=Ht.default.join(r,"nfr-design.md"),c=Ht.default.join(r,"nfr-requirements.md"),l=i||"";try{await Le.default.pathExists(c)&&(l=await Le.default.readFile(c,"utf-8"))}catch{}let u=this.buildNFRDesignContent(n,o,l);return await Le.default.writeFile(a,u,"utf-8"),a}case"infrastructure-design":{let a=Ht.default.join(r,"infrastructure-design.md"),c=Ht.default.join(r,"nfr-design.md"),l="";try{await Le.default.pathExists(c)&&(l=await Le.default.readFile(c,"utf-8"))}catch{}let u=this.buildInfrastructureDesignContent(n,o,l);return await Le.default.writeFile(a,u,"utf-8"),a}default:throw new Error(`Stage '${t}' not handled by UnitStageRunner`)}}buildFunctionalDesignContent(t,n,r){let o=n.match(/^title:\s*(.+)$/m),s=o?o[1].trim().replace(/^["']|["']$/g,""):t,i=new Date().toISOString();return`---
365
374
  id: ${t}-functional-design
366
375
  parent_unit: ${t}
367
376
  stage: functional-design
@@ -418,22 +427,17 @@ Infrastructure resource mapping for this unit.
418
427
 
419
428
  ## Deployment Architecture
420
429
  Deployment topology and environment configuration.
421
- `}extractSection(t,n){try{let r=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`##\\s+${r}\\s*\\n([\\s\\S]*?)(?=\\n##|$)`,"i").exec(t);return o?o[1].trim():""}catch{return""}}async appendAudit(t,n,r){try{let o=Wt.default.join(this.projectPath,"aidlc-docs",this.workflowId,"audit.md"),s=new Date().toISOString(),i=n.filter(c=>r.stages[c]?.status==="completed"),a=`
430
+ `}extractSection(t,n){try{let r=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`##\\s+${r}\\s*\\n([\\s\\S]*?)(?=\\n##|$)`,"i").exec(t);return o?o[1].trim():""}catch{return""}}async appendAudit(t,n,r){try{let o=Ht.default.join(this.projectPath,"aidlc-docs",this.workflowId,"audit.md"),s=new Date().toISOString(),i=n.filter(c=>r.stages[c]?.status==="completed"),a=`
422
431
  ## ${t} Design Stages \u2014 ${s}
423
432
 
424
433
  `+i.map(c=>`- [x] ${c}: ${r.stages[c].artifact_path}`).join(`
425
434
  `)+`
426
435
  `;await Le.default.pathExists(o)?await Le.default.appendFile(o,a,"utf-8"):await Le.default.writeFile(o,`# Audit Trail
427
- ${a}`,"utf-8")}catch(o){console.error(`[UnitStageRunner] Failed to update audit for ${t}:`,o)}}}});function le(e){let t={...e,id:(0,Wm.randomUUID)(),timestamp:new Date().toISOString(),verified:!1,verification_count:0,last_useful:new Date().toISOString()},n=t.scope==="global"?de():kt(t.project_path);Hn(t.project_path);let r=(0,an.join)(n,"discoveries.jsonl");return Bn(r),(0,qe.appendFileSync)(r,JSON.stringify(t)+`
428
- `,"utf-8"),t}function Eb(e){let t=(0,an.join)(de(),"discoveries.jsonl"),n=kt(e),r=(0,an.join)(n,"discoveries.jsonl"),o=Um(t),s=Um(r),i=[...o,...s],a={technical_insight:0,workaround:0,pattern:0,gotcha:0,performance:0,dependency:0,configuration:0,planning_insight:0,workflow_gate:0,retro_insight:0};for(let l of i)a[l.category]++;let c=[...i].sort((l,u)=>u.verification_count-l.verification_count);return{project_discoveries:s,global_discoveries:o,total_discoveries:i.length,categories:a,most_useful:c.slice(0,5)}}function Gm(e,t){let n=(0,an.join)(de(),"discoveries.jsonl"),r=(0,an.join)(t,".olympus","learning","discoveries.jsonl"),o=s=>{if(!(0,qe.existsSync)(s))return!1;let a=(0,qe.readFileSync)(s,"utf-8").trim().split(`
429
- `).filter(u=>u.trim()),c=!1,l=a.map(u=>{try{let d=JSON.parse(u);return d.id===e&&(c=!0,d.verification_count=(d.verification_count||0)+1,d.last_useful=new Date().toISOString()),JSON.stringify(d)}catch{return u}});if(c){let u=(0,an.dirname)(s);(0,qe.existsSync)(u)||(0,qe.mkdirSync)(u,{recursive:!0}),(0,qe.writeFileSync)(s,l.join(`
430
- `)+`
431
- `,"utf-8")}return c};o(r)||o(n)}function ms(e,t=10){let n=Eb(e),r=[...n.project_discoveries,...n.global_discoveries],o=new Date,i=r.filter(a=>a.expires_at?new Date(a.expires_at)>o:!0).map(a=>{let c=(o.getTime()-new Date(a.timestamp).getTime())/864e5,l=Math.max(.1,1-c/90),u=(a.verification_count+1)*l*a.confidence;return{discovery:a,score:u}});return i.sort((a,c)=>c.score-a.score),i.slice(0,t).map(a=>a.discovery)}function Um(e){if(!(0,qe.existsSync)(e))return[];try{return(0,qe.readFileSync)(e,"utf-8").split(`
432
- `).filter(n=>n.trim()).map(n=>JSON.parse(n))}catch(t){return console.error(`[Olympus Learning] Failed to read discoveries: ${t}`),[]}}var an,qe,Wm,Gt=U(()=>{"use strict";an=require("path"),qe=require("fs"),Wm=require("crypto");we()});function Ub(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Wb(e){let t=e.split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ");return t.length>80?t.substring(0,77)+"...":t}function Gb(e){let{inception_stages:t,current_inception_stage:n}=e;if(!t)return[];let r=[];for(let o of Lb){let s=t[o];if(!s)continue;let i=Ub(o),a=n===o,c,l;s.status==="completed"?(c="[x]",l=s.completed_at?`(completed ${s.completed_at})`:"(completed)"):s.status==="skipped"?(c="[ ]",l=s.skip_reason?`(skipped -- ${s.skip_reason})`:"(skipped)"):(c="[ ]",l="");let u=` - ${c} ${i} ${l}`.trimEnd();a&&(u+=" <- CURRENT"),r.push(u)}return r}function Bb(e){let t=["## Progress"];for(let n of Mb){let r=e.phases[n],o,s;r?.completed_at?(o="[x]",s=`(completed ${r.completed_at})`):e.current_phase===n?(o="[ ]",s="(in progress)"):(o="[ ]",s="");let i=n.charAt(0).toUpperCase()+n.slice(1);if(t.push(`- ${o} ${i} ${s}`.trimEnd()),n==="inception"&&e.inception_stages){let a=Gb(e);t.push(...a)}}return t.join(`
433
- `)}function Hb(e){let t=["## Units of Work"];if(!e.construction_units||Object.keys(e.construction_units).length===0)return t.push(""),t.push("_No units defined yet. Populated during Units Generation._"),t.join(`
436
+ ${a}`,"utf-8")}catch(o){console.error(`[UnitStageRunner] Failed to update audit for ${t}:`,o)}}}});function sC(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function iC(e){let t=e.split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ");return t.length>80?t.substring(0,77)+"...":t}function aC(e){let{inception_stages:t,current_inception_stage:n}=e;if(!t)return[];let r=[];for(let o of oC){let s=t[o];if(!s)continue;let i=sC(o),a=n===o,c,l;s.status==="completed"?(c="[x]",l=s.completed_at?`(completed ${s.completed_at})`:"(completed)"):s.status==="skipped"?(c="[ ]",l=s.skip_reason?`(skipped -- ${s.skip_reason})`:"(skipped)"):(c="[ ]",l="");let u=` - ${c} ${i} ${l}`.trimEnd();a&&(u+=" <- CURRENT"),r.push(u)}return r}function cC(e){let t=["## Progress"];for(let n of rC){let r=e.phases[n],o,s;r?.completed_at?(o="[x]",s=`(completed ${r.completed_at})`):e.current_phase===n?(o="[ ]",s="(in progress)"):(o="[ ]",s="");let i=n.charAt(0).toUpperCase()+n.slice(1);if(t.push(`- ${o} ${i} ${s}`.trimEnd()),n==="inception"&&e.inception_stages){let a=aC(e);t.push(...a)}}return t.join(`
437
+ `)}function lC(e){let t=["## Units of Work"];if(!e.construction_units||Object.keys(e.construction_units).length===0)return t.push(""),t.push("_No units defined yet. Populated during Units Generation._"),t.join(`
434
438
  `);t.push(""),t.push("| Unit | Status |"),t.push("|------|--------|");for(let[n,r]of Object.entries(e.construction_units)){let o=r.code_generation_status;r.recreation_readiness_score!=null&&r.recreation_readiness_score>0&&(o+=` | Readiness: ${r.recreation_readiness_score}/5.0`),t.push(`| ${n} | ${o} |`)}return t.join(`
435
- `)}function Vb(e,t){let n=["## Key Artifacts",""];n.push("| Artifact | Path | Status |"),n.push("|----------|------|--------|");let r=ur.join(e,eo,t),o=[{name:"Intent Analysis",path:"inception/intent.md"},{name:"Requirements",path:"inception/requirements/requirements.md"},{name:"NFR",path:"inception/requirements/nfr.md"},{name:"User Stories",path:"inception/user-stories/stories.md"},{name:"Personas",path:"inception/user-stories/personas.md"},{name:"Workflow Plan",path:"inception/workflow-plan.md"},{name:"Unit Definitions",path:"inception/application-design/unit-of-work.md"},{name:"Dependency Matrix",path:"inception/application-design/unit-of-work-dependency.md"}];for(let s of o){let i=Bt.existsSync(ur.join(r,s.path));n.push(`| ${s.name} | ${s.path} | ${i?"created":"pending"} |`)}return n.join(`
436
- `)}function $a(e,t,n){let r=ur.join(e,eo,t,Ym);try{let o=Wb(n.feature_name),s=Bb(n),i=Hb(n),a=Vb(e,t),c=`# ${o}
439
+ `)}function uC(e,t){let n=["## Key Artifacts",""];n.push("| Artifact | Path | Status |"),n.push("|----------|------|--------|");let r=dr.join(e,eo,t),o=[{name:"Intent Analysis",path:"inception/intent.md"},{name:"Requirements",path:"inception/requirements/requirements.md"},{name:"NFR",path:"inception/requirements/nfr.md"},{name:"User Stories",path:"inception/user-stories/stories.md"},{name:"Personas",path:"inception/user-stories/personas.md"},{name:"Workflow Plan",path:"inception/workflow-plan.md"},{name:"Unit Definitions",path:"inception/application-design/unit-of-work.md"},{name:"Dependency Matrix",path:"inception/application-design/unit-of-work-dependency.md"}];for(let s of o){let i=Vt.existsSync(dr.join(r,s.path));n.push(`| ${s.name} | ${s.path} | ${i?"created":"pending"} |`)}return n.join(`
440
+ `)}function Ua(e,t,n){let r=dr.join(e,eo,t,lg);try{let o=iC(n.feature_name),s=cC(n),i=lC(n),a=uC(e,t),c=`# ${o}
437
441
 
438
442
  | Field | Value |
439
443
  |-------|-------|
@@ -461,11 +465,7 @@ ${a}
461
465
 
462
466
  Application Code: ${e} (NEVER in aidlc-docs/)
463
467
  Documentation: ${eo}/${t}/
464
- `;Bt.ensureDirSync(ur.join(e,eo,t)),Bt.writeFileSync(r,c,"utf-8")}catch(o){console.error(`[StateFile] Failed to generate state file for workflow ${t}:`,o.message)}return r}function ys(e,t,n,r){let o=ur.join(e,eo,t,Ym);try{let s=Bt.readFileSync(o,"utf-8"),i=new RegExp(`^(- \\[[ x\\-]\\] ${n}.*)$`,"im"),a=s;r==="completed"?a=a.replace(i,(u,d)=>`${d.replace(/\[[ x\-]\]/,"[x]").replace(/\s*\(.*?\)\s*$/,"").replace(/\s*← CURRENT\s*$/,"")} (completed ${new Date().toISOString()})`):r==="in_progress"?a=a.replace(i,(u,d)=>`${d.replace(/\[[ x\-]\]/,"[ ]").replace(/\s*\(.*?\)\s*$/,"").replace(/\s*← CURRENT\s*$/,"")} \u2190 CURRENT`):r==="skipped"&&(a=a.replace(i,(u,d)=>`${d.replace(/\[[ x\-]\]/,"[-]").replace(/\s*\(.*?\)\s*$/,"").replace(/\s*← CURRENT\s*$/,"")} (skipped)`));let c=/\| \*\*Last Updated\*\* \| .+? \|/,l=/^\*\*Last Updated\*\*: .+$/m;c.test(a)?a=a.replace(c,`| **Last Updated** | ${new Date().toISOString()} |`):a=a.replace(l,`**Last Updated**: ${new Date().toISOString()}`),Bt.writeFileSync(o,a,"utf-8")}catch(s){console.error(`[StateFile] Failed to update state file for workflow ${t}:`,s.message)}}var ur,Bt,eo,Ym,Mb,Lb,Da=U(()=>{"use strict";ur=T(require("path"),1),Bt=T(X(),1),eo="aidlc-docs",Ym="aidlc-state.md",Mb=["discovery","inception","construction","operations"],Lb=["workspace-detection","reverse-engineering","requirements-analysis","user-stories","workflow-planning","application-design","units-generation"]});function Km(){return{current_level:0,total_transitions:0,rejection_count:0,rejection_rate:0,incident_count:0,last_level_change:null,level_history:[],consecutive_rejections:0,transition_history:[]}}function be(e){try{let t=e||process.cwd(),n=(0,ws.join)(t,Jm);if(!(0,Ht.existsSync)(n))return Km();let r=(0,Ht.readFileSync)(n,"utf-8"),o=JSON.parse(r);return o.consecutive_rejections===void 0&&(o.consecutive_rejections=0),Array.isArray(o.transition_history)||(o.transition_history=[]),o}catch(t){return console.error("Error loading trust state:",t),Km()}}function Na(e,t){try{let n=t||process.cwd(),r=(0,ws.join)(n,".olympus"),o=(0,ws.join)(n,Jm);(0,Ht.existsSync)(r)||(0,Ht.mkdirSync)(r,{recursive:!0}),(0,Ht.writeFileSync)(o,JSON.stringify(e,null,2),"utf-8")}catch(n){console.error("Error saving trust state:",n)}}function qb(e){return e.total_transitions>=50&&e.rejection_rate<.02&&e.incident_count===0?3:e.total_transitions>=20&&e.rejection_rate<.05?2:e.total_transitions>=10?1:0}function Fa(e,t,n,r){let o=e.total_transitions+1,s=n?e.rejection_count+1:e.rejection_count,i=s/o,a=n?e.consecutive_rejections+1:0,c={success:t,rejected:n,metadata:r,timestamp:new Date().toISOString()},l=[...e.transition_history,c].slice(-100),u={...e,total_transitions:o,rejection_count:s,rejection_rate:i,consecutive_rejections:a,transition_history:l},d=qb(u);if(d!==e.current_level){let p={from:e.current_level,to:d,reason:d>e.current_level?"Qualification threshold met":"Metrics degraded",timestamp:new Date().toISOString()};return{...u,current_level:d,last_level_change:p.timestamp,level_history:[...e.level_history,p]}}return u}function zm(e,t){return t>=e}var Ht,ws,Jm,cn=U(()=>{"use strict";Ht=require("fs"),ws=require("path"),Jm=".olympus/trust-state.json"});function Qm(e,t){let n=t||"",r=n?(0,dr.join)(e,"aidlc-docs",n,"manifest.json"):(0,dr.join)(e,"aidlc-docs","manifest.json"),o=W(r),s=be(e),i={workflowId:"",featureName:"",gateRejections:[],cascadeEvents:[],trustDecreases:[],ciFailureCount:0,totalGates:0,totalRejections:0};if(!o)return i;let a=(o.gate_audit||[]).filter(m=>m.action==="rejected").map(m=>({phase:m.phase,timestamp:m.timestamp,reason:m.reason||null,actor:m.actor})),c=[];for(let m of o.artifacts||[])if(m.statusHistory)for(let g of m.statusHistory)(g.status.toLowerCase().includes("stale")||g.status.toLowerCase().includes("violated"))&&c.push({artifactId:m.id,status:g.status,timestamp:g.timestamp});let l=(s?.level_history||[]).filter(m=>m.to<m.from).map(m=>({from:m.from,to:m.to,reason:m.reason,timestamp:m.timestamp})),u=0,d=n?(0,dr.join)(e,"aidlc-docs",n,"construction"):(0,dr.join)(e,"aidlc-docs","construction");if((0,Vt.existsSync)(d)){let m=(0,Vt.readdirSync)(d,{withFileTypes:!0}).filter(g=>g.isDirectory()&&g.name.startsWith("UNIT-")).map(g=>g.name);for(let g of m){let y=(0,dr.join)(d,g,"validation-report.md");if((0,Vt.existsSync)(y)){let k=(0,Vt.readFileSync)(y,"utf-8").split(`
465
- `);u+=k.filter(h=>h.toLowerCase().includes("fail")).length}}}let p=(o.gate_audit||[]).length,f=a.length;return{workflowId:o.workflow_id||"",featureName:o.feature_name||"",gateRejections:a,cascadeEvents:c,trustDecreases:l,ciFailureCount:u,totalGates:p,totalRejections:f}}function Xm(e){let t=[],n=new Map;for(let r of e.gateRejections){let o=(r.reason||"unspecified").toLowerCase().trim();n.has(o)||n.set(o,[]),n.get(o).push(r)}for(let[r,o]of n.entries()){let s=o.length,i=s>=3?"High":s===2?"Medium":"Low",c=`Gate rejections in ${o.map(u=>u.phase).join(", ")} with reason: "${r}"`,l=s>1?`Review and address recurring gate rejection pattern: "${r}". Consider improving upstream validation or documentation.`:`Address gate rejection: "${r}". Ensure requirements are clear before implementation.`;t.push({description:`Gate rejection pattern: ${r}`,evidence:c,suggestion:l,confidence:i,occurrences:s})}if(e.trustDecreases.length>0){let r=e.trustDecreases.length,o=r>=3?"High":r===2?"Medium":"Low",s=e.trustDecreases.map(i=>`${i.from} \u2192 ${i.to} (${i.reason})`).join("; ");t.push({description:"Trust level decreases detected",evidence:`Trust trajectory: ${s}`,suggestion:"Improve code quality and validation processes to rebuild trust. Consider more thorough review before gate submissions.",confidence:o,occurrences:r})}if(e.cascadeEvents.length>0){let r=e.cascadeEvents.length,o=r>=3?"High":r===2?"Medium":"Low",s=[...new Set(e.cascadeEvents.map(i=>i.artifactId))].join(", ");t.push({description:"Cascade invalidation events",evidence:`${r} invalidation event(s) affecting: ${s}`,suggestion:"Strengthen contract verification and dependency validation to prevent cascading failures. Consider improving artifact stability.",confidence:o,occurrences:r})}return t}var Vt,dr,Zm=U(()=>{"use strict";Vt=require("fs"),dr=require("path");Z();cn();Gt()});function Yb(e){return(e.gate_audit||[]).map(t=>({timestamp:t.timestamp,phase:t.phase,action:t.action,actor:t.actor,reason:t.reason??null})).sort((t,n)=>t.timestamp.localeCompare(n.timestamp))}function Kb(e){let t=e.artifacts||[],n=e.links||[];return t.filter(o=>o.stage==="intent").map(o=>{let s=n.filter(c=>c.source_id===o.id&&(c.link_type==="derives"||c.link_type==="implements")).map(c=>c.target_id).filter(c=>t.some(l=>l.id===c&&l.stage==="unit")),i=[];for(let c of s){let l=n.filter(u=>u.source_id===c&&(u.link_type==="derives"||u.link_type==="implements")).map(u=>u.target_id).filter(u=>t.some(d=>d.id===u&&d.stage==="code-generation"));i.push(...l)}let a=[...new Set(i.flatMap(c=>{let l=t.find(d=>d.id===c);if(!l)return[];let u=Pt.extname(l.path).toLowerCase();return u&&u!==".md"&&u!==".json"?[l.path]:[]}))];return{intentId:o.id,unitIds:s,codeGenerationIds:[...new Set(i)],codeFiles:a}})}function Jb(e){return(e.level_history||[]).map(t=>({from:t.from,to:t.to,reason:t.reason,timestamp:t.timestamp}))}function zb(e){let t=[];for(let n of e.artifacts||[]){if(!n.statusHistory||n.statusHistory.length<2)continue;let r=n.statusHistory;for(let o=1;o<r.length;o++){let s=r[o-1],i=r[o],a=i.status.toLowerCase();(a.includes("stale")||a.includes("violated"))&&t.push({artifactId:n.id,previousStatus:s.status,newStatus:i.status,reason:n.stale_reason??`Artifact transitioned to ${i.status}`,timestamp:i.timestamp})}}return t.sort((n,r)=>n.timestamp.localeCompare(r.timestamp))}function eg(e){return{workflowId:e,featureName:"",generatedAt:new Date().toISOString(),timeline:[],traceabilityMatrix:[],trustHistory:[],cascadeEvents:[],retroInsights:[]}}function tg(e,t){try{let n=Pt.join(e,"aidlc-docs",t,"manifest.json"),r=W(n);if(!r)return eg(t);let o=be(e),s=Qm(e,t),a=Xm(s).filter(c=>c.confidence==="High"||c.confidence==="Medium").map(c=>c.description);return{workflowId:r.workflow_id,featureName:r.feature_name,generatedAt:new Date().toISOString(),timeline:Yb(r),traceabilityMatrix:Kb(r),trustHistory:Jb(o),cascadeEvents:zb(r),retroInsights:a}}catch(n){return console.error(`Failed to generate audit document for workflow ${t}:`,n),eg(t)}}function ja(e){let t=[];if(t.push(`# Audit Report: ${e.featureName}`),t.push(""),t.push(`Generated: ${e.generatedAt}`),t.push(`Workflow ID: ${e.workflowId}`),t.push(""),t.push("## Timeline"),t.push(""),e.timeline.length===0)t.push("_No gate decisions recorded._");else{t.push("| Timestamp | Phase | Action | Actor | Reason |"),t.push("|-----------|-------|--------|-------|--------|");for(let n of e.timeline)t.push(`| ${n.timestamp} | ${n.phase} | ${n.action} | ${n.actor} | ${n.reason??"\u2014"} |`)}if(t.push(""),t.push("## Traceability Matrix"),t.push(""),e.traceabilityMatrix.length===0)t.push("_No traceability data available._");else{t.push("| Intent | Units | Code Generation | Code Files |"),t.push("|--------|-------|-----------------|------------|");for(let n of e.traceabilityMatrix){let r=n.unitIds.length>0?n.unitIds.join(", "):"\u2014",o=n.codeGenerationIds.length>0?n.codeGenerationIds.join(", "):"\u2014",s=n.codeFiles.length>0?n.codeFiles.join(", "):"\u2014";t.push(`| ${n.intentId} | ${r} | ${o} | ${s} |`)}}if(t.push(""),t.push("## Trust History"),t.push(""),e.trustHistory.length===0)t.push("_No trust level changes recorded._");else{t.push("| From | To | Reason | Timestamp |"),t.push("|------|----|--------|-----------|");for(let n of e.trustHistory)t.push(`| ${n.from} | ${n.to} | ${n.reason} | ${n.timestamp} |`)}if(t.push(""),t.push("## Cascade Events"),t.push(""),e.cascadeEvents.length===0)t.push("_No cascade invalidation events recorded._");else for(let n of e.cascadeEvents)t.push(`- **${n.artifactId}**: \`${n.previousStatus}\` \u2192 \`${n.newStatus}\` \u2014 ${n.reason} _(${n.timestamp})_`);if(t.push(""),t.push("## Retrospective Insights"),t.push(""),e.retroInsights.length===0)t.push("_No retrospective insights available._");else for(let n of e.retroInsights)t.push(`- ${n}`);return t.push(""),t.join(`
466
- `)}async function ng(e,t,n){let r=Pt.join(e,"aidlc-docs",t),o=Pt.join(r,"audit.md"),s=Pt.join(r,"manifest.json");try{let i=ja(n);await et.ensureDir(r),await et.writeFile(o,i,"utf-8"),Ne(s,{id:`audit-${t}`,type:"AUDIT",phase:"operations",stage:"complete",path:o,validation_passed:null,write_complete:!0,checksum:null})}catch(i){console.error(`Failed to write audit artifact for workflow ${t}:`,i)}return o}function rg(e,t,n){try{let r=Pt.join(e,"aidlc-docs",t,"audit.md");if(!et.existsSync(r)){let s=["# Audit Report","",`Generated: ${new Date().toISOString()}`,`Workflow ID: ${t}`,"","## Timeline","","| Timestamp | Phase | Action | Actor | Reason |","|-----------|-------|--------|-------|--------|",""].join(`
467
- `);et.ensureDirSync(Pt.dirname(r)),et.writeFileSync(r,s,"utf-8")}let o=`| ${n.timestamp} | ${n.phase} | ${n.action} | ${n.actor} | ${n.reason??"\u2014"} |
468
- `;et.appendFileSync(r,o,"utf-8")}catch(r){console.error(`Failed to append to audit for workflow ${t}:`,r)}}var et,Pt,og=U(()=>{"use strict";et=T(X(),1),Pt=T(require("path"),1);Z();cn();Zm()});var ug={};he(ug,{InceptionOrchestrator:()=>Wa,registerStageHandler:()=>Qb});function Qb(e,t){Ua[e]=t}function sg(e,t,n=null){return{stage:e,status:t,started_at:null,completed_at:null,skip_reason:n,artifacts_generated:[],questions_file:null,answers_received:!1}}function Ma(e,t,n){return n&&!Ea(n,"inception",e)?{status:"skipped",skipReason:"Excluded by workflow routing plan"}:t==="greenfield"&&e==="reverse-engineering"?{status:"skipped",skipReason:"Greenfield project \u2014 no existing codebase to reverse-engineer"}:(t==="bugfix"||t==="optimization")&&(e==="user-stories"||e==="application-design")?{status:"skipped",skipReason:`${t} pathway does not require ${e}`}:{status:"not_started",skipReason:null}}function ig(e){for(let t of It){let n=e[t];if(n&&(n.status==="not_started"||n.status==="in_progress"))return t}return null}function Xb(e,t){let n=It.indexOf(e);for(let r=n+1;r<It.length;r++){let o=It[r],s=t[o];if(s&&(s.status==="not_started"||s.status==="in_progress"))return o}}async function Zb(e,t,n){if(!n.trust_state_path)return 0;try{let r=(0,lg.join)(e,"aidlc-docs",t,n.trust_state_path),o=await cg.readFile(r,"utf-8");return JSON.parse(o).current_level??0}catch{return 0}}function eC(e,t,n){let r=e==="workspace-detection",o=t.status==="awaiting_answers";return!(n>=3||n>=2&&!o||n>=1&&r&&!o)}function ag(e){return It.every(t=>{let n=e[t];return n&&(n.status==="completed"||n.status==="skipped")})}function tC(e){let t=e.phases?.discovery;if(!t)return!1;let n=t.status;return n==="complete"||n==="completed"}function La(e,t=null){let n=t!==null,r=new Date().toISOString();return{stage:e,status:n?"skipped":"completed",started_at:n?null:r,completed_at:r,skip_reason:t,artifacts_generated:[],questions_file:null,answers_received:!1}}var cg,lg,Ua,It,Wa,dg=U(()=>{"use strict";cg=T(X(),1),lg=require("path");me();Da();og();ss();Ua={};It=["workspace-detection","reverse-engineering","requirements-analysis","user-stories","workflow-planning","application-design","units-generation"];Wa=class{async migrateCheckpoint(t,n){let r=await I(t,n);if(!r)throw new Error(`[InceptionOrchestrator] Checkpoint not found for workflow ${n}`);if(r.inception_stages)return{migrated:!1,case:"no_migration_needed"};let o=r.pathway_type??"brownfield-enhancement";if(r.current_stage!=="intent"){let a={};for(let c of It){let{skipReason:l}=Ma(c,o,null);a[c]=La(c,l)}return r.inception_stages=a,r.current_inception_stage=void 0,await O(t,r),Ft(t,n),{migrated:!0,case:"already_past_inception"}}let s={};for(let a of It){let{status:c,skipReason:l}=Ma(a,o,null);s[a]=sg(a,c,l)}s["workspace-detection"].status!=="skipped"&&(s["workspace-detection"]=La("workspace-detection")),s["reverse-engineering"].status!=="skipped"&&tC(r)&&(s["reverse-engineering"]=La("reverse-engineering")),r.inception_stages=s;let i=ig(s);return r.current_inception_stage=i??void 0,await O(t,r),Ft(t,n),{migrated:!0,case:"paused_at_intent"}}async initialize(t,n,r,o){let s=await I(t,n);if(!s)throw new Error(`[InceptionOrchestrator] Checkpoint not found for workflow ${n}`);if(s.inception_stages)return;let i={},a;for(let c of It){let{status:l,skipReason:u}=Ma(c,r,o);i[c]=sg(c,l,u),!a&&l==="not_started"&&(a=c)}s.inception_stages=i,s.current_inception_stage=a??void 0,await O(t,s),Ft(t,n)}async executeNextStage(t,n){let r=await I(t,n);if(!r)throw new Error(`[InceptionOrchestrator] Checkpoint not found for workflow ${n}`);let o=r.inception_stages;if(!o)throw new Error(`[InceptionOrchestrator] inception_stages not initialized for workflow ${n}. Call initialize() first.`);let s=ig(o);if(!s)return{stage:"units-generation",status:"completed",requires_approval:!1,artifacts_generated:[],whats_next:"Inception is complete. Proceed to construction phase."};o[s].status="in_progress",o[s].started_at=new Date().toISOString(),r.current_inception_stage=s,await O(t,r),Ft(t,n);let i=Ua[s],a;if(i)try{a=await i(t,n,r)}catch(c){let l=c;console.error(`[InceptionOrchestrator] Stage '${s}' handler threw:`,l.message);let u=await I(t,n);return u?.inception_stages&&(u.inception_stages[s].status="not_started",u.inception_stages[s].started_at=null,await O(t,u),Ft(t,n)),{stage:s,status:"review_required",requires_approval:!0,artifacts_generated:[],review_summary:`Stage '${s}' failed with error: ${l.message}`}}else a={stage:s,status:"completed",requires_approval:!0,artifacts_generated:[],review_summary:`Stage '${s}' has no handler registered yet.`,whats_next:"This stage will be implemented in a future TODO."};return await this._postStage(t,n,s,a),a}async processAnswers(t,n,r){let o=await I(t,n);if(!o)throw new Error(`[InceptionOrchestrator] Checkpoint not found for workflow ${n}`);let s=o.inception_stages;if(!s)throw new Error(`[InceptionOrchestrator] inception_stages not initialized for workflow ${n}`);let i=s[r];if(!i||i.status!=="in_progress")throw new Error(`[InceptionOrchestrator] Stage '${r}' is not in_progress (status: ${i?.status??"unknown"})`);let a=Ua[r],c;if(a)try{c=await a(t,n,o)}catch(l){let u=l;return console.error(`[InceptionOrchestrator] processAnswers for '${r}' threw:`,u.message),{stage:r,status:"review_required",requires_approval:!0,artifacts_generated:[],review_summary:`Stage '${r}' answer processing failed: ${u.message}`}}else c={stage:r,status:"completed",requires_approval:!0,artifacts_generated:[],review_summary:`Stage '${r}' has no handler registered yet.`,whats_next:"This stage will be implemented in a future TODO."};return await this._postStage(t,n,r,c),c}async getProgress(t,n){let r=await I(t,n);if(!r)throw new Error(`[InceptionOrchestrator] Checkpoint not found for workflow ${n}`);let o=r.inception_stages??{},s=It.length,i=0,a=0;for(let c of It){let l=o[c];l&&(l.status==="completed"&&i++,l.status==="skipped"&&a++)}return{total_stages:s,completed_stages:i,skipped_stages:a,current_stage:r.current_inception_stage??null,stages:o}}async isComplete(t,n){let r=await I(t,n);return r?.inception_stages?ag(r.inception_stages):!1}async _postStage(t,n,r,o){let s=await I(t,n);if(!s?.inception_stages)return;let i=s.inception_stages,a=new Date().toISOString();o.status==="completed"?(i[r].status="completed",i[r].completed_at=a,i[r].artifacts_generated=o.artifacts_generated):o.status==="awaiting_answers"?(i[r].status="in_progress",i[r].questions_file=o.questions_file??null):o.status==="skipped"&&(i[r].status="skipped",i[r].completed_at=a),(o.status==="completed"||o.status==="skipped")&&(s.current_inception_stage=Xb(r,i)),await O(t,s),Ft(t,n);try{o.status==="completed"?ys(t,n,r,"completed"):o.status==="awaiting_answers"?ys(t,n,r,"in_progress"):o.status==="skipped"&&ys(t,n,r,"skipped")}catch(u){console.error(`[InceptionOrchestrator] Failed to update state file for stage ${r}:`,u.message)}try{let u={timestamp:a,phase:"inception",action:`Stage '${r}' ${o.status}`,actor:"ai",reason:o.review_summary??null};rg(t,n,u)}catch(u){console.error(`[InceptionOrchestrator] Failed to append to audit for stage ${r}:`,u.message)}if(ag(i))try{let u=tg(t,n);ja(u),await ng(t,n,u)}catch(u){console.error("[InceptionOrchestrator] Failed to generate final audit document:",u.message)}try{let u=await Zb(t,n,s);o.requires_approval=eC(r,o,u)}catch(u){console.error("[InceptionOrchestrator] Failed to compute trust level:",u.message),o.requires_approval=!0}let l=await I(t,n);l?.current_inception_stage&&(o.next_stage=l.current_inception_stage)}}});var yg={};he(yg,{generateCostAnalysis:()=>hg,generateDeployGuide:()=>pg,generateMonitoringConfig:()=>mg,generateOperationsArtifacts:()=>nC,generateReleaseNotes:()=>gg,generateRunbook:()=>fg});function pg(e){let{featureName:t,workflowId:n,manifest:r}=e,o=new Date().toISOString(),s=r?.artifacts?.length??0,i=r?.artifacts?.filter(c=>c.phase==="inception").length??0,a=r?.artifacts?.filter(c=>c.phase==="construction").length??0;return`---
468
+ `;Vt.ensureDirSync(dr.join(e,eo,t)),Vt.writeFileSync(r,c,"utf-8")}catch(o){console.error(`[StateFile] Failed to generate state file for workflow ${t}:`,o.message)}return r}function ks(e,t,n,r){let o=dr.join(e,eo,t,lg);try{let s=Vt.readFileSync(o,"utf-8"),i=new RegExp(`^(- \\[[ x\\-]\\] ${n}.*)$`,"im"),a=s;r==="completed"?a=a.replace(i,(u,d)=>`${d.replace(/\[[ x\-]\]/,"[x]").replace(/\s*\(.*?\)\s*$/,"").replace(/\s*← CURRENT\s*$/,"")} (completed ${new Date().toISOString()})`):r==="in_progress"?a=a.replace(i,(u,d)=>`${d.replace(/\[[ x\-]\]/,"[ ]").replace(/\s*\(.*?\)\s*$/,"").replace(/\s*← CURRENT\s*$/,"")} \u2190 CURRENT`):r==="skipped"&&(a=a.replace(i,(u,d)=>`${d.replace(/\[[ x\-]\]/,"[-]").replace(/\s*\(.*?\)\s*$/,"").replace(/\s*← CURRENT\s*$/,"")} (skipped)`));let c=/\| \*\*Last Updated\*\* \| .+? \|/,l=/^\*\*Last Updated\*\*: .+$/m;c.test(a)?a=a.replace(c,`| **Last Updated** | ${new Date().toISOString()} |`):a=a.replace(l,`**Last Updated**: ${new Date().toISOString()}`),Vt.writeFileSync(o,a,"utf-8")}catch(s){console.error(`[StateFile] Failed to update state file for workflow ${t}:`,s.message)}}var dr,Vt,eo,lg,rC,oC,Wa=U(()=>{"use strict";dr=b(require("path"),1),Vt=b(X(),1),eo="aidlc-docs",lg="aidlc-state.md",rC=["discovery","inception","construction","operations"],oC=["workspace-detection","reverse-engineering","requirements-analysis","user-stories","workflow-planning","application-design","units-generation"]});var gg={};he(gg,{InceptionOrchestrator:()=>Va,registerStageHandler:()=>dC});function dC(e,t){Ha[e]=t}function ug(e,t,n=null){return{stage:e,status:t,started_at:null,completed_at:null,skip_reason:n,artifacts_generated:[],questions_file:null,answers_received:!1}}function Ba(e,t,n){return n&&!Ia(n,"inception",e)?{status:"skipped",skipReason:"Excluded by workflow routing plan"}:t==="greenfield"&&e==="reverse-engineering"?{status:"skipped",skipReason:"Greenfield project \u2014 no existing codebase to reverse-engineer"}:(t==="bugfix"||t==="optimization")&&(e==="user-stories"||e==="application-design")?{status:"skipped",skipReason:`${t} pathway does not require ${e}`}:{status:"not_started",skipReason:null}}function dg(e){for(let t of At){let n=e[t];if(n&&(n.status==="not_started"||n.status==="in_progress"))return t}return null}function pC(e,t){let n=At.indexOf(e);for(let r=n+1;r<At.length;r++){let o=At[r],s=t[o];if(s&&(s.status==="not_started"||s.status==="in_progress"))return o}}async function fC(e,t,n){if(!n.trust_state_path)return 0;try{let r=(0,mg.join)(e,"aidlc-docs",t,n.trust_state_path),o=await fg.readFile(r,"utf-8");return JSON.parse(o).current_level??0}catch{return 0}}function mC(e,t,n){let r=e==="workspace-detection",o=t.status==="awaiting_answers";return!(n>=3||n>=2&&!o||n>=1&&r&&!o)}function pg(e){return At.every(t=>{let n=e[t];return n&&(n.status==="completed"||n.status==="skipped")})}function gC(e){let t=e.phases?.discovery;if(!t)return!1;let n=t.status;return n==="complete"||n==="completed"}function Ga(e,t=null){let n=t!==null,r=new Date().toISOString();return{stage:e,status:n?"skipped":"completed",started_at:n?null:r,completed_at:r,skip_reason:t,artifacts_generated:[],questions_file:null,answers_received:!1}}var fg,mg,Ha,At,Va,hg=U(()=>{"use strict";fg=b(X(),1),mg=require("path");le();Wa();ga();ls();Ha={};At=["workspace-detection","reverse-engineering","requirements-analysis","user-stories","workflow-planning","application-design","units-generation"];Va=class{async migrateCheckpoint(t,n){let r=await I(t,n);if(!r)throw new Error(`[InceptionOrchestrator] Checkpoint not found for workflow ${n}`);if(r.inception_stages)return{migrated:!1,case:"no_migration_needed"};let o=r.pathway_type??"brownfield-enhancement";if(r.current_stage!=="intent"){let a={};for(let c of At){let{skipReason:l}=Ba(c,o,null);a[c]=Ga(c,l)}return r.inception_stages=a,r.current_inception_stage=void 0,await A(t,r),Ft(t,n),{migrated:!0,case:"already_past_inception"}}let s={};for(let a of At){let{status:c,skipReason:l}=Ba(a,o,null);s[a]=ug(a,c,l)}s["workspace-detection"].status!=="skipped"&&(s["workspace-detection"]=Ga("workspace-detection")),s["reverse-engineering"].status!=="skipped"&&gC(r)&&(s["reverse-engineering"]=Ga("reverse-engineering")),r.inception_stages=s;let i=dg(s);return r.current_inception_stage=i??void 0,await A(t,r),Ft(t,n),{migrated:!0,case:"paused_at_intent"}}async initialize(t,n,r,o){let s=await I(t,n);if(!s)throw new Error(`[InceptionOrchestrator] Checkpoint not found for workflow ${n}`);if(s.inception_stages)return;let i={},a;for(let c of At){let{status:l,skipReason:u}=Ba(c,r,o);i[c]=ug(c,l,u),!a&&l==="not_started"&&(a=c)}s.inception_stages=i,s.current_inception_stage=a??void 0,await A(t,s),Ft(t,n)}async executeNextStage(t,n){let r=await I(t,n);if(!r)throw new Error(`[InceptionOrchestrator] Checkpoint not found for workflow ${n}`);let o=r.inception_stages;if(!o)throw new Error(`[InceptionOrchestrator] inception_stages not initialized for workflow ${n}. Call initialize() first.`);let s=dg(o);if(!s)return{stage:"units-generation",status:"completed",requires_approval:!1,artifacts_generated:[],whats_next:"Inception is complete. Proceed to construction phase."};o[s].status="in_progress",o[s].started_at=new Date().toISOString(),r.current_inception_stage=s,await A(t,r),Ft(t,n);let i=Ha[s],a;if(i)try{a=await i(t,n,r)}catch(c){let l=c;console.error(`[InceptionOrchestrator] Stage '${s}' handler threw:`,l.message);let u=await I(t,n);return u?.inception_stages&&(u.inception_stages[s].status="not_started",u.inception_stages[s].started_at=null,await A(t,u),Ft(t,n)),{stage:s,status:"review_required",requires_approval:!0,artifacts_generated:[],review_summary:`Stage '${s}' failed with error: ${l.message}`}}else a={stage:s,status:"completed",requires_approval:!0,artifacts_generated:[],review_summary:`Stage '${s}' has no handler registered yet.`,whats_next:"This stage will be implemented in a future TODO."};return await this._postStage(t,n,s,a),a}async processAnswers(t,n,r){let o=await I(t,n);if(!o)throw new Error(`[InceptionOrchestrator] Checkpoint not found for workflow ${n}`);let s=o.inception_stages;if(!s)throw new Error(`[InceptionOrchestrator] inception_stages not initialized for workflow ${n}`);let i=s[r];if(!i||i.status!=="in_progress")throw new Error(`[InceptionOrchestrator] Stage '${r}' is not in_progress (status: ${i?.status??"unknown"})`);let a=Ha[r],c;if(a)try{c=await a(t,n,o)}catch(l){let u=l;return console.error(`[InceptionOrchestrator] processAnswers for '${r}' threw:`,u.message),{stage:r,status:"review_required",requires_approval:!0,artifacts_generated:[],review_summary:`Stage '${r}' answer processing failed: ${u.message}`}}else c={stage:r,status:"completed",requires_approval:!0,artifacts_generated:[],review_summary:`Stage '${r}' has no handler registered yet.`,whats_next:"This stage will be implemented in a future TODO."};return await this._postStage(t,n,r,c),c}async getProgress(t,n){let r=await I(t,n);if(!r)throw new Error(`[InceptionOrchestrator] Checkpoint not found for workflow ${n}`);let o=r.inception_stages??{},s=At.length,i=0,a=0;for(let c of At){let l=o[c];l&&(l.status==="completed"&&i++,l.status==="skipped"&&a++)}return{total_stages:s,completed_stages:i,skipped_stages:a,current_stage:r.current_inception_stage??null,stages:o}}async isComplete(t,n){let r=await I(t,n);return r?.inception_stages?pg(r.inception_stages):!1}async _postStage(t,n,r,o){let s=await I(t,n);if(!s?.inception_stages)return;let i=s.inception_stages,a=new Date().toISOString();o.status==="completed"?(i[r].status="completed",i[r].completed_at=a,i[r].artifacts_generated=o.artifacts_generated):o.status==="awaiting_answers"?(i[r].status="in_progress",i[r].questions_file=o.questions_file??null):o.status==="skipped"&&(i[r].status="skipped",i[r].completed_at=a),(o.status==="completed"||o.status==="skipped")&&(s.current_inception_stage=pC(r,i)),await A(t,s),Ft(t,n);try{o.status==="completed"?ks(t,n,r,"completed"):o.status==="awaiting_answers"?ks(t,n,r,"in_progress"):o.status==="skipped"&&ks(t,n,r,"skipped")}catch(u){console.error(`[InceptionOrchestrator] Failed to update state file for stage ${r}:`,u.message)}try{let u={timestamp:a,phase:"inception",action:`Stage '${r}' ${o.status}`,actor:"ai",reason:o.review_summary??null};zo(t,n,u)}catch(u){console.error(`[InceptionOrchestrator] Failed to append to audit for stage ${r}:`,u.message)}if(pg(i))try{let u=vf(t,n);ma(u),await bf(t,n,u)}catch(u){console.error("[InceptionOrchestrator] Failed to generate final audit document:",u.message)}try{let u=await fC(t,n,s);o.requires_approval=mC(r,o,u)}catch(u){console.error("[InceptionOrchestrator] Failed to compute trust level:",u.message),o.requires_approval=!0}let l=await I(t,n);l?.current_inception_stage&&(o.next_stage=l.current_inception_stage)}}});var vg={};he(vg,{generateCostAnalysis:()=>Sg,generateDeployGuide:()=>yg,generateMonitoringConfig:()=>_g,generateOperationsArtifacts:()=>hC,generateReleaseNotes:()=>kg,generateRunbook:()=>wg});function yg(e){let{featureName:t,workflowId:n,manifest:r}=e,o=new Date().toISOString(),s=r?.artifacts?.length??0,i=r?.artifacts?.filter(c=>c.phase==="inception").length??0,a=r?.artifacts?.filter(c=>c.phase==="construction").length??0;return`---
469
469
  id: DEPLOY-GUIDE-001
470
470
  feature: ${n}
471
471
  created: ${o}
@@ -531,7 +531,7 @@ Generated from ${s} artifacts (${i} Inception, ${a} Construction).
531
531
 
532
532
  ---
533
533
  *Generated by Operations Phase Templates*
534
- `}function fg(e){let{featureName:t,workflowId:n}=e,r=new Date().toISOString();return`---
534
+ `}function wg(e){let{featureName:t,workflowId:n}=e,r=new Date().toISOString();return`---
535
535
  id: RUNBOOK-001
536
536
  feature: ${n}
537
537
  created: ${r}
@@ -615,7 +615,7 @@ grep -i error /var/log/service/${n}.log | tail -20
615
615
 
616
616
  ---
617
617
  *Generated by Operations Phase Templates*
618
- `}function mg(e){let{featureName:t,workflowId:n,manifest:r}=e,o=new Date().toISOString(),s=r?.risk_tier?.tier??2,i=s===3?.5:s===2?1:2,a=s===3?500:s===2?1e3:2e3,l={id:"MONITORING-001",feature:n,feature_name:t,created:o,phase:"operations",stage:"monitor",risk_tier:s,health_checks:{endpoint:"/health",interval_seconds:s===3?30:s===2?60:120,timeout_seconds:5,unhealthy_threshold:3},alerts:[{name:`${n}-error-rate`,metric:"error_rate_percent",threshold:i,window_seconds:300,severity:"critical",notification_channels:["pagerduty","slack"]},{name:`${n}-latency-p99`,metric:"latency_p99_ms",threshold:a,window_seconds:300,severity:"warning",notification_channels:["slack"]},{name:`${n}-availability`,metric:"availability_percent",threshold:99.9,comparison:"less_than",window_seconds:3600,severity:"critical",notification_channels:["pagerduty","slack"]}],dashboards:{overview:{panels:[{title:"Request Rate",metric:"request_rate",type:"timeseries"},{title:"Error Rate",metric:"error_rate_percent",type:"timeseries"},{title:"Latency (p50/p95/p99)",metric:"latency_percentiles",type:"timeseries"},{title:"Availability",metric:"availability_percent",type:"stat"}]}},logging:{level:s===3?"debug":"info",retention_days:s===3?90:s===2?60:30,structured:!0}};return JSON.stringify(l,null,2)}function gg(e){let{featureName:t,workflowId:n,manifest:r}=e,o=new Date().toISOString(),s=r?.artifacts??[],i=s.filter(m=>m.phase==="inception"),a=s.filter(m=>m.phase==="construction"),c=r?.risks??[],l=c.filter(m=>m.status==="open"),u=c.filter(m=>m.status==="mitigated"),p=(r?.gate_audit??[]).filter(m=>m.action==="approved"),f=s.map(m=>`- **${m.id}** (${m.phase}/${m.stage}): ${m.contract_status}`).join(`
618
+ `}function _g(e){let{featureName:t,workflowId:n,manifest:r}=e,o=new Date().toISOString(),s=r?.risk_tier?.tier??2,i=s===3?.5:s===2?1:2,a=s===3?500:s===2?1e3:2e3,l={id:"MONITORING-001",feature:n,feature_name:t,created:o,phase:"operations",stage:"monitor",risk_tier:s,health_checks:{endpoint:"/health",interval_seconds:s===3?30:s===2?60:120,timeout_seconds:5,unhealthy_threshold:3},alerts:[{name:`${n}-error-rate`,metric:"error_rate_percent",threshold:i,window_seconds:300,severity:"critical",notification_channels:["pagerduty","slack"]},{name:`${n}-latency-p99`,metric:"latency_p99_ms",threshold:a,window_seconds:300,severity:"warning",notification_channels:["slack"]},{name:`${n}-availability`,metric:"availability_percent",threshold:99.9,comparison:"less_than",window_seconds:3600,severity:"critical",notification_channels:["pagerduty","slack"]}],dashboards:{overview:{panels:[{title:"Request Rate",metric:"request_rate",type:"timeseries"},{title:"Error Rate",metric:"error_rate_percent",type:"timeseries"},{title:"Latency (p50/p95/p99)",metric:"latency_percentiles",type:"timeseries"},{title:"Availability",metric:"availability_percent",type:"stat"}]}},logging:{level:s===3?"debug":"info",retention_days:s===3?90:s===2?60:30,structured:!0}};return JSON.stringify(l,null,2)}function kg(e){let{featureName:t,workflowId:n,manifest:r}=e,o=new Date().toISOString(),s=r?.artifacts??[],i=s.filter(m=>m.phase==="inception"),a=s.filter(m=>m.phase==="construction"),c=r?.risks??[],l=c.filter(m=>m.status==="open"),u=c.filter(m=>m.status==="mitigated"),p=(r?.gate_audit??[]).filter(m=>m.action==="approved"),f=s.map(m=>`- **${m.id}** (${m.phase}/${m.stage}): ${m.contract_status}`).join(`
619
619
  `);return`---
620
620
  id: RELEASE-NOTES-001
621
621
  feature: ${n}
@@ -681,7 +681,7 @@ This is a new feature deployment. No migration from previous versions required.
681
681
 
682
682
  ---
683
683
  *Generated by Operations Phase Templates*
684
- `}function hg(e){let{featureName:t,workflowId:n,manifest:r}=e,o=new Date().toISOString(),s=r?.artifacts??[],i=s.filter(d=>d.stage==="code-generation"),a=s.filter(d=>d.stage==="unit"),l=(r?.gate_audit??[]).filter(d=>d.action==="rejected"),u=r?.metrics??null;return`---
684
+ `}function Sg(e){let{featureName:t,workflowId:n,manifest:r}=e,o=new Date().toISOString(),s=r?.artifacts??[],i=s.filter(d=>d.stage==="code-generation"),a=s.filter(d=>d.stage==="unit"),l=(r?.gate_audit??[]).filter(d=>d.action==="rejected"),u=r?.metrics??null;return`---
685
685
  id: COST-001
686
686
  feature: ${n}
687
687
  created: ${o}
@@ -728,27 +728,27 @@ ${l.length>2?"- High rejection rate suggests specification clarity could be impr
728
728
 
729
729
  ---
730
730
  *Generated by Operations Phase Templates*
731
- `}async function nC(e,t){let n=On.join(t,"aidlc-docs",e.workflowId,"operations");await ln.ensureDir(n);let r=[],o=e.depthLevel||"MEDIUM";return await ln.writeFile(On.join(n,"release-notes.md"),gg(e),"utf-8"),r.push("release-notes.md"),o==="SHALLOW"?{artifactsGenerated:r,operationsDir:n}:(await ln.writeFile(On.join(n,"deploy-guide.md"),pg(e),"utf-8"),r.push("deploy-guide.md"),await ln.writeFile(On.join(n,"runbook.md"),fg(e),"utf-8"),r.push("runbook.md"),await ln.writeFile(On.join(n,"monitoring.json"),mg(e),"utf-8"),r.push("monitoring.json"),await ln.writeFile(On.join(n,"cost.md"),hg(e),"utf-8"),r.push("cost.md"),{artifactsGenerated:r,operationsDir:n})}var ln,On,wg=U(()=>{"use strict";ln=T(X(),1),On=T(require("path"),1)});var Yy={};he(Yy,{formatSessionSummaryLine:()=>px});function px(e){let t;e.agents_used.length===0?t="(none)":e.agents_used.length<=4?t=e.agents_used.join(", "):t=e.agents_used.slice(0,3).join(", ")+", ...";let n=e.duration_seconds,r=Math.floor(n/60),o=n%60,s;r>0?s=`${r}m ${o}s`:s=`${o}s`;let i=e.total_tokens.toLocaleString("en-US"),a=`$${e.estimated_cost.toFixed(e.estimated_cost>=.01?2:3)}`,c=e.agents_used.length,u=`[Olympus] Session: ${c} ${c===1?"agent":"agents"} (${t}) | ${i} tokens | ${a} | ${s}`;return u.length>200&&(u=u.substring(0,197)+"..."),u}var Ky=U(()=>{"use strict"});function nw(e){if(!e)return[];let t=e.toLowerCase(),n=[];for(let[r,o]of Object.entries(mx))for(let s of o)if(t.includes(s)){n.push(r);break}return n}var mx,rw=U(()=>{"use strict";mx={simple_search:["find file","search for","locate","where is","look for","find the"],debugging:["debug","error","fix bug","why is","not working","broken","failing","crash"],implementation:["implement","add feature","create function","build","write code","develop"],refactoring:["refactor","restructure","reorganize","clean up","rename","extract"],documentation:["document","write docs","add comments","explain","readme","api docs"],analysis:["analyze","investigate","examine","review","understand","trace"]}});var iw={};he(iw,{COLD_START_FALLBACK_RATE:()=>el,getRoutingRecommendation:()=>wx});function gx(){let e=(0,sw.join)(de(),"routing-config.json"),t=ke(e,null);if(t)return t;try{at(e,ow)}catch{}return ow}function hx(e,t){for(let[n,r]of Object.entries(t)){let o=r.indexOf(e);if(o>=0)return{family:n,tierList:r,index:o}}return null}function yx(e,t){return!e||t===0?el:t*e.success_rate+(1-t)*el}function wx(e,t,n){try{let r=gx();if(!r.preferLowerTier)return null;let o=hx(e,r.agentTiers);if(!o||o.index===0)return null;let s=Vn(n),i=o.tierList.slice(0,o.index);for(let a of i){let c=s[a],l=c?.total_invocations??0,u=Math.min(1,l/5),d=yx(c,u);if(d<r.minSuccessRate||u>=1&&l<r.minDataPoints)continue;let p="";if(c?.task_patterns&&c.task_patterns.length>0){let g=nw(t);for(let y of c.task_patterns)if(g.includes(y.pattern)&&y.successfulAgents.includes(a)&&y.confidence>=.7){p=` (especially for ${y.pattern.replace(/_/g," ")} tasks)`;break}}let f=(d*100).toFixed(0);return`Based on ${l} data points, ${a} handles this type of task with ${f}% success rate${p}. Consider using ${a} instead of ${e} to save tokens.`}return null}catch{return null}}var sw,el,ow,aw=U(()=>{"use strict";sw=require("path");we();rw();el=.5,ow={minDataPoints:10,minSuccessRate:.8,preferLowerTier:!0,agentTiers:{oracle:["oracle-low","oracle-medium","oracle"],olympian:["olympian-low","olympian","olympian-high"],explore:["explore","explore-medium"],librarian:["librarian-low","librarian"],"frontend-engineer":["frontend-engineer-low","frontend-engineer","frontend-engineer-high"]}}});var rI={};he(rI,{main:()=>fk});module.exports=Tk(rI);var ai=new Map;function P(e){let t=ai.get(e.event)||[];t.push(e),t.sort((n,r)=>(n.priority??100)-(r.priority??100)),ai.set(e.event,t)}function wl(e){return ai.get(e)||[]}var Ek={ultrawork:/\b(ultrawork|ulw)\b/i,ultrathink:/\b(ultrathink|think)\b/i,olympus:/\b(olympus|orchestrate|coordinate|multi-?agent|conductor)\b/i,search:/\b(search|find|locate|lookup|explore|discover|scan|grep|query|browse|detect|trace|seek|track|pinpoint|hunt)\b|where\s+is|show\s+me|list\s+all/i,analyze:/\b(analyze|analyse|investigate|examine|research|study|deep.?dive|inspect|audit|evaluate|assess|review|diagnose|scrutinize|dissect|debug|comprehend|interpret|breakdown|understand)\b|why\s+is|how\s+does|how\s+to/i},bk=["ultrawork","ultrathink","olympus","search","analyze"];function kl(e){let t=e.replace(/```[\s\S]*?```/g,"");return t=t.replace(/~~~[\s\S]*?~~~/g,""),t=t.replace(/`[^`]+`/g,""),t}function _l(e,t){let n=[];for(let r of bk){let o=Ek[r],s=e.match(o);s&&s.index!==void 0&&n.push({type:r,keyword:s[0],position:s.index})}return n}var Sl="auto-slash-command",vo="<auto-slash-command>",To="</auto-slash-command>",vl=/^\/([a-zA-Z][\w-]*)\s*(.*)/,Tl=new Set(["ascent","cancel-ascent","help","clear","history","exit","quit"]);var Ck=/```[\s\S]*?```/g;function El(e){return e.replace(Ck,"")}function bl(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.match(vl);if(!n)return null;let[r,o,s]=n;return{command:o.toLowerCase(),args:s.trim(),raw:r}}function Cl(e){return Tl.has(e.toLowerCase())}function ci(e){let n=El(e).trim();if(!n.startsWith("/"))return null;let r=bl(n);return!r||Cl(r.command)?null:r}function li(e){return e.filter(t=>t.type==="text").map(t=>t.text||"").join(" ")}var yt=require("fs"),$t=require("path"),Pl=require("os"),Rl=(0,$t.join)((0,Pl.homedir)(),".claude");function Il(e){let t=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,n=e.match(t);if(!n)return{data:{},body:e};let[,r,o]=n,s={};for(let i of r.split(`
732
- `)){let a=i.indexOf(":");if(a===-1)continue;let c=i.slice(0,a).trim(),l=i.slice(a+1).trim();(l.startsWith('"')&&l.endsWith('"')||l.startsWith("'")&&l.endsWith("'"))&&(l=l.slice(1,-1)),s[c]=l}return{data:s,body:o}}function xl(e,t){if(!(0,yt.existsSync)(e))return[];let n;try{n=(0,yt.readdirSync)(e,{withFileTypes:!0})}catch{return[]}let r=[];for(let o of n){if(!o.isFile()||!o.name.endsWith(".md"))continue;let s=(0,$t.join)(e,o.name),i=(0,$t.basename)(o.name,".md");try{let a=(0,yt.readFileSync)(s,"utf-8"),{data:c,body:l}=Il(a),u={name:i,description:c.description||"",argumentHint:c["argument-hint"],model:c.model,agent:c.agent};r.push({name:i,path:s,metadata:u,content:l,scope:t})}catch{continue}}return r}function ui(){let e=(0,$t.join)(Rl,"commands"),t=(0,$t.join)(process.cwd(),".claude","commands"),n=(0,$t.join)(Rl,"skills"),r=xl(e,"user"),o=xl(t,"project"),s=[];if((0,yt.existsSync)(n))try{let i=(0,yt.readdirSync)(n,{withFileTypes:!0});for(let a of i){if(!a.isDirectory())continue;let c=(0,$t.join)(n,a.name,"SKILL.md");if((0,yt.existsSync)(c))try{let l=(0,yt.readFileSync)(c,"utf-8"),{data:u,body:d}=Il(l),p={name:u.name||a.name,description:u.description||"",argumentHint:u["argument-hint"],model:u.model,agent:u.agent};s.push({name:u.name||a.name,path:c,metadata:p,content:d,scope:"skill"})}catch{continue}}}catch{}return[...o,...r,...s]}function Eo(e){return ui().find(n=>n.name.toLowerCase()===e.toLowerCase())??null}function Rk(e,t){return e.replace(/\$ARGUMENTS/g,t||"(no arguments provided)")}function xk(e,t){let n=[];n.push(`<command-name>/${e.name}</command-name>
731
+ `}async function hC(e,t){let n=On.join(t,"aidlc-docs",e.workflowId,"operations");await ln.ensureDir(n);let r=[],o=e.depthLevel||"MEDIUM";return await ln.writeFile(On.join(n,"release-notes.md"),kg(e),"utf-8"),r.push("release-notes.md"),o==="SHALLOW"?{artifactsGenerated:r,operationsDir:n}:(await ln.writeFile(On.join(n,"deploy-guide.md"),yg(e),"utf-8"),r.push("deploy-guide.md"),await ln.writeFile(On.join(n,"runbook.md"),wg(e),"utf-8"),r.push("runbook.md"),await ln.writeFile(On.join(n,"monitoring.json"),_g(e),"utf-8"),r.push("monitoring.json"),await ln.writeFile(On.join(n,"cost.md"),Sg(e),"utf-8"),r.push("cost.md"),{artifactsGenerated:r,operationsDir:n})}var ln,On,bg=U(()=>{"use strict";ln=b(X(),1),On=b(require("path"),1)});var Xy={};he(Xy,{formatSessionSummaryLine:()=>Cx});function Cx(e){let t;e.agents_used.length===0?t="(none)":e.agents_used.length<=4?t=e.agents_used.join(", "):t=e.agents_used.slice(0,3).join(", ")+", ...";let n=e.duration_seconds,r=Math.floor(n/60),o=n%60,s;r>0?s=`${r}m ${o}s`:s=`${o}s`;let i=e.total_tokens.toLocaleString("en-US"),a=`$${e.estimated_cost.toFixed(e.estimated_cost>=.01?2:3)}`,c=e.agents_used.length,u=`[Olympus] Session: ${c} ${c===1?"agent":"agents"} (${t}) | ${i} tokens | ${a} | ${s}`;return u.length>200&&(u=u.substring(0,197)+"..."),u}var Zy=U(()=>{"use strict"});function aw(e){if(!e)return[];let t=e.toLowerCase(),n=[];for(let[r,o]of Object.entries(xx))for(let s of o)if(t.includes(s)){n.push(r);break}return n}var xx,cw=U(()=>{"use strict";xx={simple_search:["find file","search for","locate","where is","look for","find the"],debugging:["debug","error","fix bug","why is","not working","broken","failing","crash"],implementation:["implement","add feature","create function","build","write code","develop"],refactoring:["refactor","restructure","reorganize","clean up","rename","extract"],documentation:["document","write docs","add comments","explain","readme","api docs"],analysis:["analyze","investigate","examine","review","understand","trace"]}});var dw={};he(dw,{COLD_START_FALLBACK_RATE:()=>ol,getRoutingRecommendation:()=>Ox});function Px(){let e=(0,uw.join)(pe(),"routing-config.json"),t=_e(e,null);if(t)return t;try{at(e,lw)}catch{}return lw}function Ax(e,t){for(let[n,r]of Object.entries(t)){let o=r.indexOf(e);if(o>=0)return{family:n,tierList:r,index:o}}return null}function Ix(e,t){return!e||t===0?ol:t*e.success_rate+(1-t)*ol}function Ox(e,t,n){try{let r=Px();if(!r.preferLowerTier)return null;let o=Ax(e,r.agentTiers);if(!o||o.index===0)return null;let s=Vn(n),i=o.tierList.slice(0,o.index);for(let a of i){let c=s[a],l=c?.total_invocations??0,u=Math.min(1,l/5),d=Ix(c,u);if(d<r.minSuccessRate||u>=1&&l<r.minDataPoints)continue;let p="";if(c?.task_patterns&&c.task_patterns.length>0){let g=aw(t);for(let y of c.task_patterns)if(g.includes(y.pattern)&&y.successfulAgents.includes(a)&&y.confidence>=.7){p=` (especially for ${y.pattern.replace(/_/g," ")} tasks)`;break}}let f=(d*100).toFixed(0);return`Based on ${l} data points, ${a} handles this type of task with ${f}% success rate${p}. Consider using ${a} instead of ${e} to save tokens.`}return null}catch{return null}}var uw,ol,lw,pw=U(()=>{"use strict";uw=require("path");we();cw();ol=.5,lw={minDataPoints:10,minSuccessRate:.8,preferLowerTier:!0,agentTiers:{oracle:["oracle-low","oracle-medium","oracle"],olympian:["olympian-low","olympian","olympian-high"],explore:["explore","explore-medium"],librarian:["librarian-low","librarian"],"frontend-engineer":["frontend-engineer-low","frontend-engineer","frontend-engineer-high"]}}});var yA={};he(yA,{main:()=>w_});module.exports=x_(yA);var li=new Map;function P(e){let t=li.get(e.event)||[];t.push(e),t.sort((n,r)=>(n.priority??100)-(r.priority??100)),li.set(e.event,t)}function vl(e){return li.get(e)||[]}var P_={ultrawork:/\b(ultrawork|ulw)\b/i,ultrathink:/\b(ultrathink|think)\b/i,olympus:/\b(olympus|orchestrate|coordinate|multi-?agent|conductor)\b/i,search:/\b(search|find|locate|lookup|explore|discover|scan|grep|query|browse|detect|trace|seek|track|pinpoint|hunt)\b|where\s+is|show\s+me|list\s+all/i,analyze:/\b(analyze|analyse|investigate|examine|research|study|deep.?dive|inspect|audit|evaluate|assess|review|diagnose|scrutinize|dissect|debug|comprehend|interpret|breakdown|understand)\b|why\s+is|how\s+does|how\s+to/i},A_=["ultrawork","ultrathink","olympus","search","analyze"];function bl(e){let t=e.replace(/```[\s\S]*?```/g,"");return t=t.replace(/~~~[\s\S]*?~~~/g,""),t=t.replace(/`[^`]+`/g,""),t}function Tl(e,t){let n=[];for(let r of A_){let o=P_[r],s=e.match(o);s&&s.index!==void 0&&n.push({type:r,keyword:s[0],position:s.index})}return n}var El="auto-slash-command",vo="<auto-slash-command>",bo="</auto-slash-command>",Cl=/^\/([a-zA-Z][\w-]*)\s*(.*)/,Rl=new Set(["ascent","cancel-ascent","help","clear","history","exit","quit"]);var I_=/```[\s\S]*?```/g;function xl(e){return e.replace(I_,"")}function Pl(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.match(Cl);if(!n)return null;let[r,o,s]=n;return{command:o.toLowerCase(),args:s.trim(),raw:r}}function Al(e){return Rl.has(e.toLowerCase())}function ui(e){let n=xl(e).trim();if(!n.startsWith("/"))return null;let r=Pl(n);return!r||Al(r.command)?null:r}function di(e){return e.filter(t=>t.type==="text").map(t=>t.text||"").join(" ")}var yt=require("fs"),$t=require("path"),$l=require("os"),Il=(0,$t.join)((0,$l.homedir)(),".claude");function Dl(e){let t=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,n=e.match(t);if(!n)return{data:{},body:e};let[,r,o]=n,s={};for(let i of r.split(`
732
+ `)){let a=i.indexOf(":");if(a===-1)continue;let c=i.slice(0,a).trim(),l=i.slice(a+1).trim();(l.startsWith('"')&&l.endsWith('"')||l.startsWith("'")&&l.endsWith("'"))&&(l=l.slice(1,-1)),s[c]=l}return{data:s,body:o}}function Ol(e,t){if(!(0,yt.existsSync)(e))return[];let n;try{n=(0,yt.readdirSync)(e,{withFileTypes:!0})}catch{return[]}let r=[];for(let o of n){if(!o.isFile()||!o.name.endsWith(".md"))continue;let s=(0,$t.join)(e,o.name),i=(0,$t.basename)(o.name,".md");try{let a=(0,yt.readFileSync)(s,"utf-8"),{data:c,body:l}=Dl(a),u={name:i,description:c.description||"",argumentHint:c["argument-hint"],model:c.model,agent:c.agent};r.push({name:i,path:s,metadata:u,content:l,scope:t})}catch{continue}}return r}function pi(){let e=(0,$t.join)(Il,"commands"),t=(0,$t.join)(process.cwd(),".claude","commands"),n=(0,$t.join)(Il,"skills"),r=Ol(e,"user"),o=Ol(t,"project"),s=[];if((0,yt.existsSync)(n))try{let i=(0,yt.readdirSync)(n,{withFileTypes:!0});for(let a of i){if(!a.isDirectory())continue;let c=(0,$t.join)(n,a.name,"SKILL.md");if((0,yt.existsSync)(c))try{let l=(0,yt.readFileSync)(c,"utf-8"),{data:u,body:d}=Dl(l),p={name:u.name||a.name,description:u.description||"",argumentHint:u["argument-hint"],model:u.model,agent:u.agent};s.push({name:u.name||a.name,path:c,metadata:p,content:d,scope:"skill"})}catch{continue}}}catch{}return[...o,...r,...s]}function To(e){return pi().find(n=>n.name.toLowerCase()===e.toLowerCase())??null}function O_(e,t){return e.replace(/\$ARGUMENTS/g,t||"(no arguments provided)")}function $_(e,t){let n=[];n.push(`<command-name>/${e.name}</command-name>
733
733
  `),e.metadata.description&&n.push(`**Description**: ${e.metadata.description}
734
734
  `),t&&n.push(`**Arguments**: ${t}
735
735
  `),e.metadata.model&&n.push(`**Model**: ${e.metadata.model}
736
736
  `),e.metadata.agent&&n.push(`**Agent**: ${e.metadata.agent}
737
737
  `),n.push(`**Scope**: ${e.scope}
738
738
  `),n.push(`---
739
- `);let r=Rk(e.content||"",t);return n.push(r.trim()),t&&!e.content?.includes("$ARGUMENTS")&&(n.push(`
739
+ `);let r=O_(e.content||"",t);return n.push(r.trim()),t&&!e.content?.includes("$ARGUMENTS")&&(n.push(`
740
740
 
741
741
  ---
742
742
  `),n.push(`## User Request
743
743
  `),n.push(t)),n.join(`
744
- `)}function di(e){let t=Eo(e.command);if(!t)return{success:!1,error:`Command "/${e.command}" not found. Available commands are in ~/.claude/commands/ or .claude/commands/`};try{return{success:!0,replacementText:xk(t,e.args)}}catch(n){return{success:!1,error:`Failed to load command "/${e.command}": ${n instanceof Error?n.message:String(n)}`}}}function pi(){return ui().map(t=>({name:t.name,description:t.metadata.description,scope:t.scope}))}var bo=new Set;function Al(){return{name:Sl,processMessage:(e,t)=>{let n=li(t);if(n.includes(vo)||n.includes(To))return{detected:!1};let r=ci(n);if(!r)return{detected:!1};let o=`${e.sessionId}:${e.messageId}:${r.command}`;if(bo.has(o))return{detected:!1};bo.add(o);let s=di(r);if(s.success&&s.replacementText){let a=`${vo}
744
+ `)}function fi(e){let t=To(e.command);if(!t)return{success:!1,error:`Command "/${e.command}" not found. Available commands are in ~/.claude/commands/ or .claude/commands/`};try{return{success:!0,replacementText:$_(t,e.args)}}catch(n){return{success:!1,error:`Failed to load command "/${e.command}": ${n instanceof Error?n.message:String(n)}`}}}function mi(){return pi().map(t=>({name:t.name,description:t.metadata.description,scope:t.scope}))}var Eo=new Set;function Nl(){return{name:El,processMessage:(e,t)=>{let n=di(t);if(n.includes(vo)||n.includes(bo))return{detected:!1};let r=ui(n);if(!r)return{detected:!1};let o=`${e.sessionId}:${e.messageId}:${r.command}`;if(Eo.has(o))return{detected:!1};Eo.add(o);let s=fi(r);if(s.success&&s.replacementText){let a=`${vo}
745
745
  ${s.replacementText}
746
- ${To}`;return{detected:!0,parsedCommand:r,injectedMessage:a}}let i=`${vo}
746
+ ${bo}`;return{detected:!0,parsedCommand:r,injectedMessage:a}}let i=`${vo}
747
747
  [AUTO-SLASH-COMMAND ERROR]
748
748
  ${s.error}
749
749
 
750
750
  Original input: ${r.raw}
751
- ${To}`;return{detected:!0,parsedCommand:r,injectedMessage:i}},listCommands:()=>pi(),findCommand:e=>Eo(e),clearSession:e=>{let t=[];for(let n of bo)n.startsWith(`${e}:`)&&t.push(n);for(let n of t)bo.delete(n)}}}var Pk=[/\bultrathink\b/i,/\bthink\b/i],Ik=["\uC0DD\uAC01","\uACE0\uBBFC","\uAC80\uD1A0","\uC81C\uB300\uB85C","\u601D\u8003","\u8003\u8651","\u8003\u616E","\u8003\u3048","\u719F\u8003","\u0938\u094B\u091A","\u0935\u093F\u091A\u093E\u0930","\u062A\u0641\u0643\u064A\u0631","\u062A\u0623\u0645\u0644","\u099A\u09BF\u09A8\u09CD\u09A4\u09BE","\u09AD\u09BE\u09AC\u09A8\u09BE","\u0434\u0443\u043C\u0430\u0442\u044C","\u0434\u0443\u043C\u0430\u0439","\u0440\u0430\u0437\u043C\u044B\u0448\u043B\u044F\u0442\u044C","\u0440\u0430\u0437\u043C\u044B\u0448\u043B\u044F\u0439","pensar","pense","refletir","reflita","piensa","reflexionar","reflexiona","penser","r\xE9fl\xE9chir","r\xE9fl\xE9chis","denken","denk","nachdenken","suy ngh\u0129","c\xE2n nh\u1EAFc","d\xFC\u015F\xFCn","d\xFC\u015F\xFCnmek","pensare","pensa","riflettere","rifletti","\u0E04\u0E34\u0E14","\u0E1E\u0E34\u0E08\u0E32\u0E23\u0E13\u0E32","my\u015Bl","my\u015Ble\u0107","zastan\xF3w","nadenken","berpikir","pikir","pertimbangkan","\u0434\u0443\u043C\u0430\u0442\u0438","\u0440\u043E\u0437\u0434\u0443\u043C\u0443\u0432\u0430\u0442\u0438","\u03C3\u03BA\u03AD\u03C8\u03BF\u03C5","\u03C3\u03BA\u03AD\u03C6\u03C4\u03BF\u03BC\u03B1\u03B9","myslet","mysli","p\u0159em\xFD\u0161let","g\xE2nde\u0219te","g\xE2ndi","reflect\u0103","t\xE4nka","t\xE4nk","fundera","gondolkodj","gondolkodni","ajattele","ajatella","pohdi","t\xE6nk","t\xE6nke","overvej","tenk","tenke","gruble","\u05D7\u05E9\u05D5\u05D1","\u05DC\u05D7\u05E9\u05D5\u05D1","\u05DC\u05D4\u05E8\u05D4\u05E8"],Ak=Ik.map(e=>new RegExp(e,"i")),Ok=[...Pk,...Ak],$k=/```[\s\S]*?```/g,Dk=/`[^`]+`/g;function Nk(e){return e.replace($k,"").replace(Dk,"")}function Ol(e){let t=Nk(e);return Ok.some(n=>n.test(t))}function $l(e){return e.filter(t=>t.type==="text").map(t=>t.text||"").join("")}function fi(e){let t=e.indexOf("/");return t===-1?{prefix:"",base:e}:{prefix:e.slice(0,t+1),base:e.slice(t+1)}}function mi(e){return e.replace(/\.(\d+)/g,"-$1")}var Dl={"claude-sonnet-4-5":"claude-sonnet-4-5-high","claude-opus-4-5":"claude-opus-4-5-high","claude-3-5-sonnet":"claude-3-5-sonnet-high","claude-3-opus":"claude-3-opus-high","gpt-4":"gpt-4-high","gpt-4-turbo":"gpt-4-turbo-high","gpt-4o":"gpt-4o-high","gpt-5":"gpt-5-high","gpt-5-mini":"gpt-5-mini-high","gemini-2-pro":"gemini-2-pro-high","gemini-3-pro":"gemini-3-pro-high","gemini-3-flash":"gemini-3-flash-high"},Nl=new Set(Object.values(Dl)),Fl={anthropic:{thinking:{type:"enabled",budgetTokens:64e3},maxTokens:128e3},"amazon-bedrock":{reasoningConfig:{type:"enabled",budgetTokens:32e3},maxTokens:64e3},google:{providerOptions:{google:{thinkingConfig:{thinkingLevel:"HIGH"}}}},openai:{reasoning_effort:"high"}},Fk={anthropic:["claude-sonnet-4","claude-opus-4","claude-3"],"amazon-bedrock":["claude","anthropic"],google:["gemini-2","gemini-3"],openai:["gpt-4","gpt-5","o1","o3"]};function jl(e){let t=mi(e),{prefix:n,base:r}=fi(t);if(Nl.has(r)||r.endsWith("-high"))return null;let o=Dl[r];return o?n+o:null}function gi(e){let t=mi(e),{base:n}=fi(t);return Nl.has(n)||n.endsWith("-high")}function jk(e,t){if(e==="github-copilot"){let n=t.toLowerCase();if(n.includes("claude"))return"anthropic";if(n.includes("gemini"))return"google";if(n.includes("gpt")||n.includes("o1")||n.includes("o3"))return"openai"}return e}function Mk(e){return e in Fl}function Ml(e,t){let n=mi(t),{base:r}=fi(n);if(gi(n))return null;let o=jk(e,t);if(!Mk(o))return null;let s=Fl[o],i=Fk[o];if(!i)return null;let a=r.toLowerCase();return i.some(l=>a.includes(l.toLowerCase()))?s:null}var zt=new Map;function Lk(e){zt.delete(e)}function Ll(){return{processChatParams:(e,t)=>{let n=$l(t.parts),r={requested:!1,modelSwitched:!1,thinkingConfigInjected:!1};if(!Ol(n))return zt.set(e,r),r;r.requested=!0;let o=t.message.model;if(!o||(r.providerId=o.providerId,r.modelId=o.modelId,gi(o.modelId)))return zt.set(e,r),r;let s=jl(o.modelId),i=Ml(o.providerId,o.modelId);return s&&(t.message.model={providerId:o.providerId,modelId:s},r.modelSwitched=!0),i&&(Object.assign(t.message,i),r.thinkingConfigInjected=!0),zt.set(e,r),r},onSessionDeleted:e=>{zt.delete(e)},isRequested:e=>zt.get(e)?.requested??!1,getState:e=>zt.get(e),clear:Lk}}var ce=require("fs"),Un=require("path"),hi=require("os");function yi(e){let t=e||process.cwd(),n=(0,Un.join)(t,".olympus");return(0,Un.join)(n,"ultrawork-state.json")}function wi(){return(0,Un.join)((0,hi.homedir)(),".claude","ultrawork-state.json")}function Uk(e){let t=e||process.cwd(),n=(0,Un.join)(t,".olympus");(0,ce.existsSync)(n)||(0,ce.mkdirSync)(n,{recursive:!0})}function Wk(){let e=(0,Un.join)((0,hi.homedir)(),".claude");(0,ce.existsSync)(e)||(0,ce.mkdirSync)(e,{recursive:!0})}function Qt(e){let t=yi(e);if((0,ce.existsSync)(t))try{let r=(0,ce.readFileSync)(t,"utf-8");return JSON.parse(r)}catch{}let n=wi();if((0,ce.existsSync)(n))try{let r=(0,ce.readFileSync)(n,"utf-8");return JSON.parse(r)}catch{return null}return null}function Ul(e,t){try{Uk(t);let n=yi(t);(0,ce.writeFileSync)(n,JSON.stringify(e,null,2)),Wk();let r=wi();return(0,ce.writeFileSync)(r,JSON.stringify(e,null,2)),!0}catch{return!1}}function Wl(e,t,n){let r={active:!0,started_at:new Date().toISOString(),original_prompt:e,session_id:t,reinforcement_count:0,last_checked_at:new Date().toISOString()};return Ul(r,n)}function Gl(e){let t=yi(e);if((0,ce.existsSync)(t))try{(0,ce.unlinkSync)(t)}catch{}let n=wi();if((0,ce.existsSync)(n))try{return(0,ce.unlinkSync)(n),!0}catch{return!1}return!0}function Bl(e){let t=Qt(e);return!t||!t.active?null:(t.reinforcement_count+=1,t.last_checked_at=new Date().toISOString(),Ul(t,e)?t:null)}function Hl(e){return`<ultrawork-persistence>
751
+ ${bo}`;return{detected:!0,parsedCommand:r,injectedMessage:i}},listCommands:()=>mi(),findCommand:e=>To(e),clearSession:e=>{let t=[];for(let n of Eo)n.startsWith(`${e}:`)&&t.push(n);for(let n of t)Eo.delete(n)}}}var D_=[/\bultrathink\b/i,/\bthink\b/i],N_=["\uC0DD\uAC01","\uACE0\uBBFC","\uAC80\uD1A0","\uC81C\uB300\uB85C","\u601D\u8003","\u8003\u8651","\u8003\u616E","\u8003\u3048","\u719F\u8003","\u0938\u094B\u091A","\u0935\u093F\u091A\u093E\u0930","\u062A\u0641\u0643\u064A\u0631","\u062A\u0623\u0645\u0644","\u099A\u09BF\u09A8\u09CD\u09A4\u09BE","\u09AD\u09BE\u09AC\u09A8\u09BE","\u0434\u0443\u043C\u0430\u0442\u044C","\u0434\u0443\u043C\u0430\u0439","\u0440\u0430\u0437\u043C\u044B\u0448\u043B\u044F\u0442\u044C","\u0440\u0430\u0437\u043C\u044B\u0448\u043B\u044F\u0439","pensar","pense","refletir","reflita","piensa","reflexionar","reflexiona","penser","r\xE9fl\xE9chir","r\xE9fl\xE9chis","denken","denk","nachdenken","suy ngh\u0129","c\xE2n nh\u1EAFc","d\xFC\u015F\xFCn","d\xFC\u015F\xFCnmek","pensare","pensa","riflettere","rifletti","\u0E04\u0E34\u0E14","\u0E1E\u0E34\u0E08\u0E32\u0E23\u0E13\u0E32","my\u015Bl","my\u015Ble\u0107","zastan\xF3w","nadenken","berpikir","pikir","pertimbangkan","\u0434\u0443\u043C\u0430\u0442\u0438","\u0440\u043E\u0437\u0434\u0443\u043C\u0443\u0432\u0430\u0442\u0438","\u03C3\u03BA\u03AD\u03C8\u03BF\u03C5","\u03C3\u03BA\u03AD\u03C6\u03C4\u03BF\u03BC\u03B1\u03B9","myslet","mysli","p\u0159em\xFD\u0161let","g\xE2nde\u0219te","g\xE2ndi","reflect\u0103","t\xE4nka","t\xE4nk","fundera","gondolkodj","gondolkodni","ajattele","ajatella","pohdi","t\xE6nk","t\xE6nke","overvej","tenk","tenke","gruble","\u05D7\u05E9\u05D5\u05D1","\u05DC\u05D7\u05E9\u05D5\u05D1","\u05DC\u05D4\u05E8\u05D4\u05E8"],F_=N_.map(e=>new RegExp(e,"i")),j_=[...D_,...F_],M_=/```[\s\S]*?```/g,L_=/`[^`]+`/g;function U_(e){return e.replace(M_,"").replace(L_,"")}function Fl(e){let t=U_(e);return j_.some(n=>n.test(t))}function jl(e){return e.filter(t=>t.type==="text").map(t=>t.text||"").join("")}function gi(e){let t=e.indexOf("/");return t===-1?{prefix:"",base:e}:{prefix:e.slice(0,t+1),base:e.slice(t+1)}}function hi(e){return e.replace(/\.(\d+)/g,"-$1")}var Ml={"claude-sonnet-4-5":"claude-sonnet-4-5-high","claude-opus-4-5":"claude-opus-4-5-high","claude-3-5-sonnet":"claude-3-5-sonnet-high","claude-3-opus":"claude-3-opus-high","gpt-4":"gpt-4-high","gpt-4-turbo":"gpt-4-turbo-high","gpt-4o":"gpt-4o-high","gpt-5":"gpt-5-high","gpt-5-mini":"gpt-5-mini-high","gemini-2-pro":"gemini-2-pro-high","gemini-3-pro":"gemini-3-pro-high","gemini-3-flash":"gemini-3-flash-high"},Ll=new Set(Object.values(Ml)),Ul={anthropic:{thinking:{type:"enabled",budgetTokens:64e3},maxTokens:128e3},"amazon-bedrock":{reasoningConfig:{type:"enabled",budgetTokens:32e3},maxTokens:64e3},google:{providerOptions:{google:{thinkingConfig:{thinkingLevel:"HIGH"}}}},openai:{reasoning_effort:"high"}},W_={anthropic:["claude-sonnet-4","claude-opus-4","claude-3"],"amazon-bedrock":["claude","anthropic"],google:["gemini-2","gemini-3"],openai:["gpt-4","gpt-5","o1","o3"]};function Wl(e){let t=hi(e),{prefix:n,base:r}=gi(t);if(Ll.has(r)||r.endsWith("-high"))return null;let o=Ml[r];return o?n+o:null}function yi(e){let t=hi(e),{base:n}=gi(t);return Ll.has(n)||n.endsWith("-high")}function B_(e,t){if(e==="github-copilot"){let n=t.toLowerCase();if(n.includes("claude"))return"anthropic";if(n.includes("gemini"))return"google";if(n.includes("gpt")||n.includes("o1")||n.includes("o3"))return"openai"}return e}function G_(e){return e in Ul}function Bl(e,t){let n=hi(t),{base:r}=gi(n);if(yi(n))return null;let o=B_(e,t);if(!G_(o))return null;let s=Ul[o],i=W_[o];if(!i)return null;let a=r.toLowerCase();return i.some(l=>a.includes(l.toLowerCase()))?s:null}var zt=new Map;function H_(e){zt.delete(e)}function Gl(){return{processChatParams:(e,t)=>{let n=jl(t.parts),r={requested:!1,modelSwitched:!1,thinkingConfigInjected:!1};if(!Fl(n))return zt.set(e,r),r;r.requested=!0;let o=t.message.model;if(!o||(r.providerId=o.providerId,r.modelId=o.modelId,yi(o.modelId)))return zt.set(e,r),r;let s=Wl(o.modelId),i=Bl(o.providerId,o.modelId);return s&&(t.message.model={providerId:o.providerId,modelId:s},r.modelSwitched=!0),i&&(Object.assign(t.message,i),r.thinkingConfigInjected=!0),zt.set(e,r),r},onSessionDeleted:e=>{zt.delete(e)},isRequested:e=>zt.get(e)?.requested??!1,getState:e=>zt.get(e),clear:H_}}var ce=require("fs"),Un=require("path"),wi=require("os");function _i(e){let t=e||process.cwd(),n=(0,Un.join)(t,".olympus");return(0,Un.join)(n,"ultrawork-state.json")}function ki(){return(0,Un.join)((0,wi.homedir)(),".claude","ultrawork-state.json")}function V_(e){let t=e||process.cwd(),n=(0,Un.join)(t,".olympus");(0,ce.existsSync)(n)||(0,ce.mkdirSync)(n,{recursive:!0})}function q_(){let e=(0,Un.join)((0,wi.homedir)(),".claude");(0,ce.existsSync)(e)||(0,ce.mkdirSync)(e,{recursive:!0})}function Qt(e){let t=_i(e);if((0,ce.existsSync)(t))try{let r=(0,ce.readFileSync)(t,"utf-8");return JSON.parse(r)}catch{}let n=ki();if((0,ce.existsSync)(n))try{let r=(0,ce.readFileSync)(n,"utf-8");return JSON.parse(r)}catch{return null}return null}function Hl(e,t){try{V_(t);let n=_i(t);(0,ce.writeFileSync)(n,JSON.stringify(e,null,2)),q_();let r=ki();return(0,ce.writeFileSync)(r,JSON.stringify(e,null,2)),!0}catch{return!1}}function Vl(e,t,n){let r={active:!0,started_at:new Date().toISOString(),original_prompt:e,session_id:t,reinforcement_count:0,last_checked_at:new Date().toISOString()};return Hl(r,n)}function ql(e){let t=_i(e);if((0,ce.existsSync)(t))try{(0,ce.unlinkSync)(t)}catch{}let n=ki();if((0,ce.existsSync)(n))try{return(0,ce.unlinkSync)(n),!0}catch{return!1}return!0}function Yl(e){let t=Qt(e);return!t||!t.active?null:(t.reinforcement_count+=1,t.last_checked_at=new Date().toISOString(),Hl(t,e)?t:null)}function Kl(e){return`<ultrawork-persistence>
752
752
 
753
753
  [ULTRAWORK MODE STILL ACTIVE - Reinforcement #${e.reinforcement_count+1}]
754
754
 
@@ -769,7 +769,7 @@ Original task: ${e.original_prompt}
769
769
 
770
770
  ---
771
771
 
772
- `}var Vl=require("os"),ye=require("path");function wt(){return process.platform==="win32"}function Gk(){return(0,ye.join)((0,Vl.homedir)(),".claude")}function De(){return(0,ye.join)(Gk(),"hooks")}var ql=`<ultrawork-mode>
772
+ `}var Jl=require("os"),ye=require("path");function wt(){return process.platform==="win32"}function Y_(){return(0,ye.join)((0,Jl.homedir)(),".claude")}function De(){return(0,ye.join)(Y_(),"hooks")}var zl=`<ultrawork-mode>
773
773
 
774
774
  **MANDATORY**: You MUST say "ULTRAWORK MODE ENABLED!" to the user as your first response when this mode activates. This is non-negotiable.
775
775
 
@@ -860,7 +860,7 @@ THE USER ASKED FOR X. DELIVER EXACTLY X. NOT A SUBSET. NOT A DEMO. NOT A STARTIN
860
860
 
861
861
  ---
862
862
 
863
- `,Yl=`<think-mode>
863
+ `,Ql=`<think-mode>
864
864
 
865
865
  **ULTRATHINK MODE ENABLED** - Extended reasoning activated.
866
866
 
@@ -876,7 +876,7 @@ Use your extended thinking capabilities to provide the most thorough and well-re
876
876
 
877
877
  ---
878
878
 
879
- `;var Kl=`<search-mode>
879
+ `;var Xl=`<search-mode>
880
880
  MAXIMIZE SEARCH EFFORT. Launch multiple background agents IN PARALLEL:
881
881
  - explore agents (codebase patterns, file structures)
882
882
  - librarian agents (remote repos, official docs, GitHub examples)
@@ -886,7 +886,7 @@ NEVER stop at first result - be exhaustive.
886
886
 
887
887
  ---
888
888
 
889
- `,Jl=`<analyze-mode>
889
+ `,Zl=`<analyze-mode>
890
890
  ANALYSIS MODE. Gather context before diving deep:
891
891
 
892
892
  CONTEXT GATHERING (parallel):
@@ -902,21 +902,21 @@ SYNTHESIZE findings before proceeding.
902
902
 
903
903
  ---
904
904
 
905
- `,zl=`[SYSTEM REMINDER - TODO CONTINUATION]
905
+ `,eu=`[SYSTEM REMINDER - TODO CONTINUATION]
906
906
 
907
907
  Incomplete tasks remain in your todo list. Continue working on the next pending task.
908
908
 
909
909
  - Proceed without asking for permission
910
910
  - Mark each task complete when finished
911
- - Do not stop until all tasks are done`;var II={hooks:{UserPromptSubmit:[{hooks:[{type:"command",command:wt()?'node "%USERPROFILE%\\.claude\\hooks\\keyword-detector.mjs"':'node "$HOME/.claude/hooks/keyword-detector.mjs"'}]}],SessionStart:[{hooks:[{type:"command",command:wt()?'node "%USERPROFILE%\\.claude\\hooks\\session-start.mjs"':'node "$HOME/.claude/hooks/session-start.mjs"'}]}],Stop:[{hooks:[{type:"command",command:wt()?'node "%USERPROFILE%\\.claude\\hooks\\persistent-mode.mjs"':'node "$HOME/.claude/hooks/persistent-mode.mjs"'}]}]}},AI={hooks:{UserPromptSubmit:[{hooks:[{type:"command",command:wt()?`node "${(0,ye.join)(De(),"olympus-hooks.cjs")}" --event=UserPromptSubmit`:`node "${(0,ye.join)(De(),"olympus-hooks.cjs")}" --event=UserPromptSubmit`}]}],SessionStart:[{hooks:[{type:"command",command:wt()?`node "${(0,ye.join)(De(),"olympus-hooks.cjs")}" --event=SessionStart`:`node "${(0,ye.join)(De(),"olympus-hooks.cjs")}" --event=SessionStart`}]}],Stop:[{hooks:[{type:"command",command:wt()?`node "${(0,ye.join)(De(),"olympus-hooks.cjs")}" --event=Stop`:`node "${(0,ye.join)(De(),"olympus-hooks.cjs")}" --event=Stop`}]}],PreToolUse:[{hooks:[{type:"command",command:wt()?`node "${(0,ye.join)(De(),"olympus-hooks.cjs")}" --event=PreToolUse`:`node "${(0,ye.join)(De(),"olympus-hooks.cjs")}" --event=PreToolUse`}]}],PostToolUse:[{hooks:[{type:"command",command:wt()?`node "${(0,ye.join)(De(),"olympus-hooks.cjs")}" --event=PostToolUse`:`node "${(0,ye.join)(De(),"olympus-hooks.cjs")}" --event=PostToolUse`}]}],PostToolUseFailure:[{hooks:[{type:"command",command:wt()?`node "${(0,ye.join)(De(),"olympus-hooks.cjs")}" --event=PostToolUseFailure`:`node "${(0,ye.join)(De(),"olympus-hooks.cjs")}" --event=PostToolUseFailure`}]}],Notification:[{hooks:[{type:"command",command:wt()?`node "${(0,ye.join)(De(),"olympus-hooks.cjs")}" --event=Notification`:`node "${(0,ye.join)(De(),"olympus-hooks.cjs")}" --event=Notification`}]}]}};Ge();we();var _u=require("crypto"),Xk={correction:[{regex:/no[,.]?\s*(that's|thats)?\s*(not|wrong)/i,confidence:.9},{regex:/that's\s*(incorrect|not right|not what)/i,confidence:.9},{regex:/you\s*(misunderstood|got it wrong)/i,confidence:.85},{regex:/actually,?\s*(I|it|the)/i,confidence:.6}],rejection:[{regex:/\b(stop|cancel|abort|halt)\b/i,confidence:.95},{regex:/don't\s*(do|want|need)\s*(that|this)/i,confidence:.85},{regex:/never\s*mind/i,confidence:.9},{regex:/forget\s*(it|that|about)/i,confidence:.8}],clarification:[{regex:/I\s*(meant|wanted|asked for)/i,confidence:.85},{regex:/what I\s*(mean|want|need)/i,confidence:.8},{regex:/to clarify/i,confidence:.9},{regex:/let me\s*(rephrase|explain|be clearer)/i,confidence:.85}],explicit_preference:[{regex:/always\s+(use|do|include|add|prefer)/i,confidence:.95},{regex:/never\s+(use|do|include|add)/i,confidence:.95},{regex:/I\s*(prefer|like|want)\s*(you to)?/i,confidence:.7},{regex:/from now on/i,confidence:.9},{regex:/in the future,?\s*(please|always)/i,confidence:.85}],praise:[{regex:/\bperfect\b/i,confidence:.9},{regex:/exactly(\s+what I (wanted|needed))?/i,confidence:.85},{regex:/great(\s+job)?/i,confidence:.7},{regex:/\bthanks?\b/i,confidence:.5},{regex:/looks?\s+good/i,confidence:.75}],enhancement:[{regex:/also\s+(add|include|do)/i,confidence:.7},{regex:/can you (also|additionally)/i,confidence:.7},{regex:/one more thing/i,confidence:.75}]};function Ti(e){let t=e.replace(/```[\s\S]*?```/g,"").replace(/`[^`]+`/g,""),n=null;for(let[r,o]of Object.entries(Xk))for(let{regex:s,confidence:i}of o)s.test(t)&&(!n||i>n.confidence)&&(n={category:r,confidence:i});return n}async function Su(e){let{prompt:t,directory:n,sessionId:r}=e;if(!t||!n)return;let o=Q(n,r),s=Ti(t),i=du(o,t,s?.category);if(s){let a={id:(0,_u.randomUUID)(),timestamp:new Date().toISOString(),session_id:o.session_id,project_path:n,event_type:s.category==="explicit_preference"?"explicit_preference":"revision",original_task:o.pending_completion?.task_description,agent_used:o.pending_completion?.agent_used,user_message:t,feedback_category:s.category,confidence:s.confidence};Xt(a)}ee(n,i)}Ge();we();var vu=require("crypto");async function Tu(e){let{prompt:t,directory:n,sessionId:r}=e;if(!t||!n)return;let o=Q(n,r),s=Ti(t);if(s?.category==="praise"&&s.confidence>.7){let a={id:(0,vu.randomUUID)(),timestamp:new Date().toISOString(),session_id:o.session_id,project_path:n,event_type:"success",original_task:o.pending_completion?.task_description,agent_used:o.pending_completion?.agent_used,user_message:t,feedback_category:"praise",confidence:s.confidence};if(Xt(a),xo(o)){let c=fu(o);ee(n,c)}}}var ge=T(require("fs"),1),$n=T(require("path"),1);me();Ji();var Op=require("fs"),Ap=new Map,Sv=1e4;function vv(e){let t=Ap.get(e);if(t&&Date.now()-t.timestamp<Sv)return t.content;let n=(0,Op.readFileSync)(e,"utf-8");return Ap.set(e,{content:n,timestamp:Date.now()}),n}function Tv(e){let t=e.match(/^---\n([\s\S]*?)\n---/);if(!t)return null;let n=t[1];try{let r={},o=n.split(`
912
- `);for(let s of o){let i=s.match(/^(\w+):\s*(.+)$/);if(i){let[,a,c]=i;r[a]=c.trim()}}return r}catch{return null}}function Ev(e){return e.replace(/^---\n[\s\S]*?\n---\n/,"")}function bv(e){let t=new Map,n=e.split(`
911
+ - Do not stop until all tasks are done`;var HA={hooks:{UserPromptSubmit:[{hooks:[{type:"command",command:wt()?'node "%USERPROFILE%\\.claude\\hooks\\keyword-detector.mjs"':'node "$HOME/.claude/hooks/keyword-detector.mjs"'}]}],SessionStart:[{hooks:[{type:"command",command:wt()?'node "%USERPROFILE%\\.claude\\hooks\\session-start.mjs"':'node "$HOME/.claude/hooks/session-start.mjs"'}]}],Stop:[{hooks:[{type:"command",command:wt()?'node "%USERPROFILE%\\.claude\\hooks\\persistent-mode.mjs"':'node "$HOME/.claude/hooks/persistent-mode.mjs"'}]}]}},VA={hooks:{UserPromptSubmit:[{hooks:[{type:"command",command:wt()?`node "${(0,ye.join)(De(),"olympus-hooks.cjs")}" --event=UserPromptSubmit`:`node "${(0,ye.join)(De(),"olympus-hooks.cjs")}" --event=UserPromptSubmit`}]}],SessionStart:[{hooks:[{type:"command",command:wt()?`node "${(0,ye.join)(De(),"olympus-hooks.cjs")}" --event=SessionStart`:`node "${(0,ye.join)(De(),"olympus-hooks.cjs")}" --event=SessionStart`}]}],Stop:[{hooks:[{type:"command",command:wt()?`node "${(0,ye.join)(De(),"olympus-hooks.cjs")}" --event=Stop`:`node "${(0,ye.join)(De(),"olympus-hooks.cjs")}" --event=Stop`}]}],PreToolUse:[{hooks:[{type:"command",command:wt()?`node "${(0,ye.join)(De(),"olympus-hooks.cjs")}" --event=PreToolUse`:`node "${(0,ye.join)(De(),"olympus-hooks.cjs")}" --event=PreToolUse`}]}],PostToolUse:[{hooks:[{type:"command",command:wt()?`node "${(0,ye.join)(De(),"olympus-hooks.cjs")}" --event=PostToolUse`:`node "${(0,ye.join)(De(),"olympus-hooks.cjs")}" --event=PostToolUse`}]}],PostToolUseFailure:[{hooks:[{type:"command",command:wt()?`node "${(0,ye.join)(De(),"olympus-hooks.cjs")}" --event=PostToolUseFailure`:`node "${(0,ye.join)(De(),"olympus-hooks.cjs")}" --event=PostToolUseFailure`}]}],Notification:[{hooks:[{type:"command",command:wt()?`node "${(0,ye.join)(De(),"olympus-hooks.cjs")}" --event=Notification`:`node "${(0,ye.join)(De(),"olympus-hooks.cjs")}" --event=Notification`}]}]}};Be();we();var Tu=require("crypto"),rk={correction:[{regex:/no[,.]?\s*(that's|thats)?\s*(not|wrong)/i,confidence:.9},{regex:/that's\s*(incorrect|not right|not what)/i,confidence:.9},{regex:/you\s*(misunderstood|got it wrong)/i,confidence:.85},{regex:/actually,?\s*(I|it|the)/i,confidence:.6}],rejection:[{regex:/\b(stop|cancel|abort|halt)\b/i,confidence:.95},{regex:/don't\s*(do|want|need)\s*(that|this)/i,confidence:.85},{regex:/never\s*mind/i,confidence:.9},{regex:/forget\s*(it|that|about)/i,confidence:.8}],clarification:[{regex:/I\s*(meant|wanted|asked for)/i,confidence:.85},{regex:/what I\s*(mean|want|need)/i,confidence:.8},{regex:/to clarify/i,confidence:.9},{regex:/let me\s*(rephrase|explain|be clearer)/i,confidence:.85}],explicit_preference:[{regex:/always\s+(use|do|include|add|prefer)/i,confidence:.95},{regex:/never\s+(use|do|include|add)/i,confidence:.95},{regex:/I\s*(prefer|like|want)\s*(you to)?/i,confidence:.7},{regex:/from now on/i,confidence:.9},{regex:/in the future,?\s*(please|always)/i,confidence:.85}],praise:[{regex:/\bperfect\b/i,confidence:.9},{regex:/exactly(\s+what I (wanted|needed))?/i,confidence:.85},{regex:/great(\s+job)?/i,confidence:.7},{regex:/\bthanks?\b/i,confidence:.5},{regex:/looks?\s+good/i,confidence:.75}],enhancement:[{regex:/also\s+(add|include|do)/i,confidence:.7},{regex:/can you (also|additionally)/i,confidence:.7},{regex:/one more thing/i,confidence:.75}]};function Ei(e){let t=e.replace(/```[\s\S]*?```/g,"").replace(/`[^`]+`/g,""),n=null;for(let[r,o]of Object.entries(rk))for(let{regex:s,confidence:i}of o)s.test(t)&&(!n||i>n.confidence)&&(n={category:r,confidence:i});return n}async function Eu(e){let{prompt:t,directory:n,sessionId:r}=e;if(!t||!n)return;let o=Q(n,r),s=Ei(t),i=gu(o,t,s?.category);if(s){let a={id:(0,Tu.randomUUID)(),timestamp:new Date().toISOString(),session_id:o.session_id,project_path:n,event_type:s.category==="explicit_preference"?"explicit_preference":"revision",original_task:o.pending_completion?.task_description,agent_used:o.pending_completion?.agent_used,user_message:t,feedback_category:s.category,confidence:s.confidence};Xt(a)}ee(n,i)}Be();we();var Cu=require("crypto");async function Ru(e){let{prompt:t,directory:n,sessionId:r}=e;if(!t||!n)return;let o=Q(n,r),s=Ei(t);if(s?.category==="praise"&&s.confidence>.7){let a={id:(0,Cu.randomUUID)(),timestamp:new Date().toISOString(),session_id:o.session_id,project_path:n,event_type:"success",original_task:o.pending_completion?.task_description,agent_used:o.pending_completion?.agent_used,user_message:t,feedback_category:"praise",confidence:s.confidence};if(Xt(a),xo(o)){let c=yu(o);ee(n,c)}}}var ge=b(require("fs"),1),$n=b(require("path"),1);le();Qi();var Fp=require("fs"),Np=new Map,Pv=1e4;function Av(e){let t=Np.get(e);if(t&&Date.now()-t.timestamp<Pv)return t.content;let n=(0,Fp.readFileSync)(e,"utf-8");return Np.set(e,{content:n,timestamp:Date.now()}),n}function Iv(e){let t=e.match(/^---\n([\s\S]*?)\n---/);if(!t)return null;let n=t[1];try{let r={},o=n.split(`
912
+ `);for(let s of o){let i=s.match(/^(\w+):\s*(.+)$/);if(i){let[,a,c]=i;r[a]=c.trim()}}return r}catch{return null}}function Ov(e){return e.replace(/^---\n[\s\S]*?\n---\n/,"")}function $v(e){let t=new Map,n=e.split(`
913
913
  `),r=null,o=[];for(let s of n){let i=s.match(/^##\s+(.+)$/);i?(r&&t.set(r,o.join(`
914
914
  `)),r=i[1].trim(),o=[]):r&&o.push(s)}return r&&t.set(r,o.join(`
915
- `)),t}async function Go(e){let t=new Date().toISOString(),n=[],r;try{r=vv(e)}catch(f){let m=f;return m.code==="ENOENT"?(console.error(`[Validation] INTENT artifact not found: ${e}`),{passed:!1,coverage_percentage:0,blocking_issues:["Artifact file not found"],timestamp:t}):m.code==="EACCES"||m.code==="EPERM"?(console.error(`[Validation] Permission denied reading INTENT artifact: ${e}`),{passed:!1,coverage_percentage:0,blocking_issues:["Permission denied reading artifact file"],timestamp:t}):(console.error(`[Validation] Failed to read INTENT artifact: ${m.message}`),console.error(`[Validation] Path: ${e}`),{passed:!1,coverage_percentage:0,blocking_issues:[`Failed to read artifact: ${m.message}`],timestamp:t})}let o=Tv(r),s=["id","title","parent","status","depth_score","risk_tier"],i=!0;for(let f of s)(!o||!o[f])&&(n.push(`Frontmatter missing required field: ${f}`),i=!1);let a=Ev(r),c=bv(a),l=i?1:0,u=[()=>{let f=c.get("Business Requirements");if(!f)return"Missing Business Requirements section";let m=f.match(/US-\d{3}/g);return!m||m.length===0?"No User Stories found (expected US-NNN pattern)":null},()=>{let f=c.get("Business Requirements");if(f){let m=f.match(/US-\d{3}/g);if(m)for(let g of m){let y=f.indexOf(g),w=f.indexOf("US-",y+1);if(!(w>0?f.substring(y,w):f.substring(y)).match(/Acceptance:/i))return`User Story ${g} missing Acceptance criterion`}}return null},()=>{let f=c.get("Technical Specification");return!f||f.trim().length===0?"Technical Specification section missing or empty":null},()=>{let f=c.get("Implementation Plan");return!f||f.trim().length===0?"Implementation Plan section missing or empty":null},()=>{let f=c.get("Implementation Plan");if(!f||f.trim().length===0)return"";let m=f.match(/UNIT-\d{3}/g);return!m||m.length===0?"No Proposed UNITs found (expected UNIT-NNN pattern)":null}];for(let f of u){let m=f();m!==null?m.trim().length>0&&n.push(m):l++}let p=Math.round(l/6*100);return{passed:n.length===0,coverage_percentage:p,blocking_issues:n,timestamp:t}}var Y=T(X(),1),G=T(require("path"),1);me();var Vr=T(require("fs"),1),Ho=T(require("path"),1);var te=T(require("fs"),1),ae=T(require("path"),1);function Cv(e,t){let n=[],r=ae.join(e,"README.md");te.existsSync(r)&&n.push(r);let o=ae.join(e,"docs");if(te.existsSync(o)&&te.statSync(o).isDirectory()){let a=c=>{let l=te.readdirSync(c,{withFileTypes:!0});for(let u of l){let d=ae.join(c,u.name);u.isDirectory()?a(d):u.isFile()&&u.name.endsWith(".md")&&n.push(d)}};a(o)}let s=ae.join(e,"aidlc-docs",t,"construction");if(te.existsSync(s)&&te.statSync(s).isDirectory()){let a=te.readdirSync(s,{withFileTypes:!0});for(let c of a){if(!c.isDirectory())continue;let l=ae.join(s,c.name,"documentation");if(te.existsSync(l)&&te.statSync(l).isDirectory()){let u=te.readdirSync(l,{withFileTypes:!0});for(let d of u)d.isFile()&&d.name.endsWith(".md")&&n.push(ae.join(l,d.name))}}}let i=ae.join(e,"aidlc-docs",t,"inception");if(te.existsSync(i)&&te.statSync(i).isDirectory()){let a=c=>{let l=te.readdirSync(c,{withFileTypes:!0});for(let u of l){let d=ae.join(c,u.name);u.isDirectory()?a(d):u.isFile()&&u.name.endsWith(".md")&&n.push(d)}};a(i)}return n}function Rv(e,t){return t.filter(n=>n&&e.includes(n))}function xv(e){let t=new Set;for(let n of e){let r=ae.basename(n),o=r.replace(/\.[^.]+$/,"");o&&t.add(o),r&&t.add(r);let s=ae.basename(ae.dirname(n));s&&s!=="."&&s!==".."&&t.add(s)}return Array.from(t).filter(n=>n.length>2)}function Pv(e,t){let n=ae.join(t.outputDir,"documentation");te.mkdirSync(n,{recursive:!0});let r=[`# Impact Scan: ${t.unitId}`,"",`**Generated:** ${new Date().toISOString().split("T")[0]}`,`**Workflow:** ${t.workflowId}`,`**Unit:** ${t.unitId}`,`**Status:** ${e.status}`,""];if(e.affectedDocs.length===0)r.push("## Result","","No existing documentation references were found that require updates.","");else{r.push("## Affected Documents","",`${e.affectedDocs.length} document(s) may need updating:`,"");for(let s of e.affectedDocs)r.push(`### ${ae.basename(s.path)}`),r.push(""),r.push(`**Path:** \`${s.path}\``),r.push(`**References found:** ${s.references.join(", ")}`),r.push(`**Action needed:** ${s.description}`),r.push("")}if(e.updatedDocs&&e.updatedDocs.length>0){r.push("## Auto-Updated Documents","",`${e.updatedDocs.length} document(s) were automatically updated:`,"");for(let s of e.updatedDocs){r.push(`- \`${ae.basename(s.path)}\``);for(let i of s.updatedReferences)r.push(` - Renamed reference: ${i}`);for(let i of s.notesAdded)r.push(` - ${i}`)}r.push("")}r.push("> This is an advisory scan. Review and update affected documents as needed.","");let o=ae.join(n,"impact-scan.md");return te.writeFileSync(o,r.join(`
916
- `)),o}function Iv(e){let t=new Map;if(!e)return t;for(let[n,r]of Object.entries(e)){let o=ae.basename(n).replace(/\.[^.]+$/,""),s=ae.basename(r).replace(/\.[^.]+$/,"");o&&s&&o!==s&&t.set(o,s)}return t}function Av(e,t,n){let r=[],o=Iv(n),s=new Date().toISOString().split("T")[0];for(let i of e){let a;try{a=te.readFileSync(i.path,"utf-8")}catch{continue}let c=[],l=[],u=a;for(let[f,m]of o)u.includes(f)&&(u=u.split(f).join(m),c.push(`${f} -> ${m}`));let d=new Set(o.keys()),p=i.references.filter(f=>!d.has(f));if(p.length>0){let f=`
915
+ `)),t}async function Bo(e){let t=new Date().toISOString(),n=[],r;try{r=Av(e)}catch(f){let m=f;return m.code==="ENOENT"?(console.error(`[Validation] INTENT artifact not found: ${e}`),{passed:!1,coverage_percentage:0,blocking_issues:["Artifact file not found"],timestamp:t}):m.code==="EACCES"||m.code==="EPERM"?(console.error(`[Validation] Permission denied reading INTENT artifact: ${e}`),{passed:!1,coverage_percentage:0,blocking_issues:["Permission denied reading artifact file"],timestamp:t}):(console.error(`[Validation] Failed to read INTENT artifact: ${m.message}`),console.error(`[Validation] Path: ${e}`),{passed:!1,coverage_percentage:0,blocking_issues:[`Failed to read artifact: ${m.message}`],timestamp:t})}let o=Iv(r),s=["id","title","parent","status","depth_score","risk_tier"],i=!0;for(let f of s)(!o||!o[f])&&(n.push(`Frontmatter missing required field: ${f}`),i=!1);let a=Ov(r),c=$v(a),l=i?1:0,u=[()=>{let f=c.get("Business Requirements");if(!f)return"Missing Business Requirements section";let m=f.match(/US-\d{3}/g);return!m||m.length===0?"No User Stories found (expected US-NNN pattern)":null},()=>{let f=c.get("Business Requirements");if(f){let m=f.match(/US-\d{3}/g);if(m)for(let g of m){let y=f.indexOf(g),w=f.indexOf("US-",y+1);if(!(w>0?f.substring(y,w):f.substring(y)).match(/Acceptance:/i))return`User Story ${g} missing Acceptance criterion`}}return null},()=>{let f=c.get("Technical Specification");return!f||f.trim().length===0?"Technical Specification section missing or empty":null},()=>{let f=c.get("Implementation Plan");return!f||f.trim().length===0?"Implementation Plan section missing or empty":null},()=>{let f=c.get("Implementation Plan");if(!f||f.trim().length===0)return"";let m=f.match(/UNIT-\d{3}/g);return!m||m.length===0?"No Proposed UNITs found (expected UNIT-NNN pattern)":null}];for(let f of u){let m=f();m!==null?m.trim().length>0&&n.push(m):l++}let p=Math.round(l/6*100);return{passed:n.length===0,coverage_percentage:p,blocking_issues:n,timestamp:t}}var Y=b(X(),1),H=b(require("path"),1);le();var Vr=b(require("fs"),1),Ho=b(require("path"),1);var te=b(require("fs"),1),ae=b(require("path"),1);function Dv(e,t){let n=[],r=ae.join(e,"README.md");te.existsSync(r)&&n.push(r);let o=ae.join(e,"docs");if(te.existsSync(o)&&te.statSync(o).isDirectory()){let a=c=>{let l=te.readdirSync(c,{withFileTypes:!0});for(let u of l){let d=ae.join(c,u.name);u.isDirectory()?a(d):u.isFile()&&u.name.endsWith(".md")&&n.push(d)}};a(o)}let s=ae.join(e,"aidlc-docs",t,"construction");if(te.existsSync(s)&&te.statSync(s).isDirectory()){let a=te.readdirSync(s,{withFileTypes:!0});for(let c of a){if(!c.isDirectory())continue;let l=ae.join(s,c.name,"documentation");if(te.existsSync(l)&&te.statSync(l).isDirectory()){let u=te.readdirSync(l,{withFileTypes:!0});for(let d of u)d.isFile()&&d.name.endsWith(".md")&&n.push(ae.join(l,d.name))}}}let i=ae.join(e,"aidlc-docs",t,"inception");if(te.existsSync(i)&&te.statSync(i).isDirectory()){let a=c=>{let l=te.readdirSync(c,{withFileTypes:!0});for(let u of l){let d=ae.join(c,u.name);u.isDirectory()?a(d):u.isFile()&&u.name.endsWith(".md")&&n.push(d)}};a(i)}return n}function Nv(e,t){return t.filter(n=>n&&e.includes(n))}function Fv(e){let t=new Set;for(let n of e){let r=ae.basename(n),o=r.replace(/\.[^.]+$/,"");o&&t.add(o),r&&t.add(r);let s=ae.basename(ae.dirname(n));s&&s!=="."&&s!==".."&&t.add(s)}return Array.from(t).filter(n=>n.length>2)}function jv(e,t){let n=ae.join(t.outputDir,"documentation");te.mkdirSync(n,{recursive:!0});let r=[`# Impact Scan: ${t.unitId}`,"",`**Generated:** ${new Date().toISOString().split("T")[0]}`,`**Workflow:** ${t.workflowId}`,`**Unit:** ${t.unitId}`,`**Status:** ${e.status}`,""];if(e.affectedDocs.length===0)r.push("## Result","","No existing documentation references were found that require updates.","");else{r.push("## Affected Documents","",`${e.affectedDocs.length} document(s) may need updating:`,"");for(let s of e.affectedDocs)r.push(`### ${ae.basename(s.path)}`),r.push(""),r.push(`**Path:** \`${s.path}\``),r.push(`**References found:** ${s.references.join(", ")}`),r.push(`**Action needed:** ${s.description}`),r.push("")}if(e.updatedDocs&&e.updatedDocs.length>0){r.push("## Auto-Updated Documents","",`${e.updatedDocs.length} document(s) were automatically updated:`,"");for(let s of e.updatedDocs){r.push(`- \`${ae.basename(s.path)}\``);for(let i of s.updatedReferences)r.push(` - Renamed reference: ${i}`);for(let i of s.notesAdded)r.push(` - ${i}`)}r.push("")}r.push("> This is an advisory scan. Review and update affected documents as needed.","");let o=ae.join(n,"impact-scan.md");return te.writeFileSync(o,r.join(`
916
+ `)),o}function Mv(e){let t=new Map;if(!e)return t;for(let[n,r]of Object.entries(e)){let o=ae.basename(n).replace(/\.[^.]+$/,""),s=ae.basename(r).replace(/\.[^.]+$/,"");o&&s&&o!==s&&t.set(o,s)}return t}function Lv(e,t,n){let r=[],o=Mv(n),s=new Date().toISOString().split("T")[0];for(let i of e){let a;try{a=te.readFileSync(i.path,"utf-8")}catch{continue}let c=[],l=[],u=a;for(let[f,m]of o)u.includes(f)&&(u=u.split(f).join(m),c.push(`${f} -> ${m}`));let d=new Set(o.keys()),p=i.references.filter(f=>!d.has(f));if(p.length>0){let f=`
917
917
 
918
- <!-- Impact scan (${s}): References to ${p.join(", ")} may need manual review after recent changes. -->`;u+=f,l.push(`Advisory note added for: ${p.join(", ")}`)}if(u!==a)try{te.writeFileSync(i.path,u,"utf-8"),r.push({path:i.path,updatedReferences:c,notesAdded:l})}catch{continue}}return r}function $p(e){if(!e.modifiedFiles||e.modifiedFiles.length===0)return{status:"skipped",affectedDocs:[],reportPath:null};let t=xv(e.modifiedFiles);if(t.length===0)return{status:"skipped",affectedDocs:[],reportPath:null};let n=Cv(e.projectPath,e.workflowId),r=[];for(let c of n){let l;try{l=te.readFileSync(c,"utf-8")}catch{continue}let u=Rv(l,t);u.length>0&&r.push({path:c,references:u,description:`References to ${u.join(", ")} \u2014 verify content is still accurate after unit changes`})}if(r.length===0)return{status:"skipped",affectedDocs:[],reportPath:null};let o=ae.join(e.projectPath,"aidlc-docs",e.workflowId,"construction",e.unitId),s=[];try{s=Av(r,e.modifiedFiles,e.renamedFiles)}catch{}let i={status:"completed",affectedDocs:r,reportPath:null,updatedDocs:s.length>0?s:void 0},a=Pv(i,{unitId:e.unitId,workflowId:e.workflowId,outputDir:o});return i.reportPath=a,i}var ze=T(require("fs"),1),Je=T(require("path"),1);function Ov(e){if(!ze.existsSync(e))return 1;let n=ze.readdirSync(e).map(r=>{let o=/^ADR-(\d+)-/.exec(r);return o?parseInt(o[1],10):0}).filter(r=>r>0);return n.length===0?1:Math.max(...n)+1}function Dp(e){let t=Je.join(e.projectPath,"aidlc-docs",e.workflowId,"decisions");ze.mkdirSync(t,{recursive:!0});let n=Ov(t),r=e.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),o=String(n).padStart(3,"0"),s=`ADR-${o}-${r}.md`,i=[`# ADR-${o}: ${e.title}`,"",`**Date:** ${new Date().toISOString().split("T")[0]}`,"**Status:** Accepted",`**Unit:** ${e.unitId}`,"","## Context","",e.context,"","## Decision","",e.decision,"","## Consequences","",e.consequences,""].join(`
919
- `),a=Je.join(t,s);return ze.writeFileSync(a,i),{number:n,path:a,title:e.title}}function Np(e,t){let n=[],r=Je.join(t,"package.json"),o=new Set;if(ze.existsSync(r))try{let s=JSON.parse(ze.readFileSync(r,"utf-8"));o=new Set([...Object.keys(s.dependencies??{}),...Object.keys(s.devDependencies??{})])}catch{}for(let s of e){let i;try{i=ze.readFileSync(s,"utf-8")}catch{continue}let a=i.matchAll(/from ['"]([^./][^'"]+)['"]/g);for(let d of a){let p=d[1].split("/")[0];p&&!o.has(p)&&!p.startsWith("@types/")&&(n.push({title:`Added dependency: ${p}`,context:`Unit ${Je.basename(s)} imports from '${p}', which was not present in the existing package.json dependencies.`,decision:`Include '${p}' as a dependency to support the new functionality introduced in this unit.`,consequences:`Build and runtime environments must have '${p}' available. Adds to bundle size and supply chain surface.`}),o.add(p))}let c=i.matchAll(/export\s+(?:interface|type)\s+(\w+(?:Schema|Model|Entity|Record|Row|Document))\b/g);for(let d of c){let p=d[1];n.push({title:`New data model: ${p}`,context:`A new exported type '${p}' with persistence-related naming was introduced in ${Je.basename(s)}.`,decision:`Define '${p}' as the canonical data model for this domain concept, enforcing a consistent schema across the codebase.`,consequences:"Consumers must adopt this interface. Future migrations require updating this type and all its usages."})}let l=i.matchAll(/(?:app|router)\.(get|post|put|patch|delete)\s*\(\s*['"]([^'"]+)['"]/g);for(let d of l){let p=d[1].toUpperCase(),f=d[2];n.push({title:`API contract change: ${p} ${f}`,context:`A new route '${p} ${f}' was added in ${Je.basename(s)}.`,decision:`Expose '${p} ${f}' as a stable API endpoint for clients to consume.`,consequences:"This endpoint becomes part of the public contract. Breaking changes require versioning or deprecation notices."})}let u=Je.basename(s);if(u==="index.ts"||u==="index.js"){let d=Je.basename(Je.dirname(s));d&&d!=="."&&d!=="src"&&n.push({title:`New module: ${d}`,context:`A new module entry point was created at ${s}, establishing '${d}' as an independent module.`,decision:`Structure '${d}' as a dedicated module with its own public API surface via index.ts.`,consequences:"Other modules should import from this module's public API rather than reaching into internal files."})}}return n}var Zn=T(require("fs"),1),Lp=T(require("path"),1);function Fp(e){let t=0;return e.length>0&&t++,e.split(/\s+/).length>100&&t++,/(?:FR-|US-|acceptance|requirement|criteria)/i.test(e)&&t++,/(?:aidlc-docs|\.md|\.ts|\.js|intent|requirements)/i.test(e)&&t++,/(?:^[-*]\s|^#{1,3}\s|^\d+\.\s)/m.test(e)&&t++,Math.min(t,5)}function $v(e){let t=0;return/## Data Models/i.test(e)&&t++,/(?:interface|type|schema|entity|model|table|field|column|relation)/i.test(e)&&t++,/```[\s\S]*?(?:interface|type|schema)[\s\S]*?```/.test(e)&&t++,/(?:\.ts|\.js|\.py|\.go|models?|entities?|schemas?)\//i.test(e)&&t++,/\|.*\|.*\|/.test(e)&&t++,Math.min(t,5)}function jp(e){let t=0;return/## Architecture Decisions/i.test(e)&&t++,/## API Contracts/i.test(e)&&t++,/```/.test(e)&&t++,/(?:src\/|lib\/|import|export|function|class)\s/i.test(e)&&t++,/(?:because|therefore|instead of|trade-?off|decision|chose)/i.test(e)&&t++,Math.min(t,5)}function Dv(e){let t=0;return/## How to Test/i.test(e)&&t++,/(?:test|spec|verify|assert|expect|should|given|when|then)/i.test(e)&&t++,/(?:npm test|vitest|jest|pytest|cargo test|go test)/i.test(e)&&t++,/(?:\.test\.|\.spec\.|__tests__|test\/)/i.test(e)&&t++,/^\d+\.\s/m.test(e)&&t++,Math.min(t,5)}function Nv(e){let t=0;return/## (?:Recreation Notes|Configuration Changes)/i.test(e)&&t++,/(?:install|setup|configure|environment|\.env|npm|yarn|pip)/i.test(e)&&t++,/(?:\$\s|```(?:bash|sh|shell))/i.test(e)&&t++,/## Dependencies/i.test(e)&&t++,/(?:prerequisite|required|depends on|known limitation|## Known)/i.test(e)&&t++,Math.min(t,5)}function Mp(e){let t=[];return e.requirements_coverage<=3&&t.push(`Requirements Coverage scored ${e.requirements_coverage}/5 \u2014 add references to FR-* and US-* identifiers, include acceptance criteria traceability`),e.data_model_completeness<=3&&t.push(`Data Model Completeness scored ${e.data_model_completeness}/5 \u2014 add entity relationships, schema definitions, and type examples`),e.implementation_guidance<=3&&t.push(`Implementation Guidance scored ${e.implementation_guidance}/5 \u2014 add architecture decision rationale, API contract details, and code examples`),e.test_coverage_documentation<=3&&t.push(`Test Coverage Documentation scored ${e.test_coverage_documentation}/5 \u2014 add test approach, verification steps, and test file references`),e.bootstrap_capability<=3&&t.push(`Bootstrap Capability scored ${e.bootstrap_capability}/5 \u2014 add setup instructions, environment configuration, and dependency information`),t}function Bo(e){try{let t=Lp.join(e,".olympus","config.json");return Zn.existsSync(t)&&JSON.parse(Zn.readFileSync(t,"utf-8")).recreation_readiness_mode==="blocking"?"blocking":"advisory"}catch{return"advisory"}}function zi(e){if(e.override===!0){let c={overall_score:0,passed:!0,mode:Bo(e.projectPath),dimensions:{requirements_coverage:0,data_model_completeness:0,implementation_guidance:0,test_coverage_documentation:0,bootstrap_capability:0}};return e.overrideRationale&&(c.remediation=[`Override applied: ${e.overrideRationale}`]),c}if(e.pathway==="bugfix")return{overall_score:0,passed:!0,mode:"advisory",dimensions:{requirements_coverage:0,data_model_completeness:0,implementation_guidance:0,test_coverage_documentation:0,bootstrap_capability:0}};if(e.depth==="minimal"){let c=Bo(e.projectPath),l="";try{l=Zn.readFileSync(e.featureDocPath,"utf-8")}catch{return{overall_score:0,passed:!1,mode:c,dimensions:{requirements_coverage:0,data_model_completeness:0,implementation_guidance:0,test_coverage_documentation:0,bootstrap_capability:0},remediation:["Feature doc could not be read \u2014 ensure it exists at the expected path"]}}let u=Fp(l),d=jp(l),p=(u+d)/2,f=p>=3.5||c==="advisory",m={requirements_coverage:u,data_model_completeness:0,implementation_guidance:d,test_coverage_documentation:0,bootstrap_capability:0},g={overall_score:Math.round(p*10)/10,passed:f,mode:c,dimensions:m};return p<3.5&&(g.remediation=Mp(m)),g}let t="";try{t=Zn.readFileSync(e.featureDocPath,"utf-8")}catch{return{overall_score:0,passed:!1,mode:Bo(e.projectPath),dimensions:{requirements_coverage:0,data_model_completeness:0,implementation_guidance:0,test_coverage_documentation:0,bootstrap_capability:0},remediation:["Feature doc could not be read \u2014 ensure it exists at the expected path"]}}let n={requirements_coverage:Fp(t),data_model_completeness:$v(t),implementation_guidance:jp(t),test_coverage_documentation:Dv(t),bootstrap_capability:Nv(t)},r=Object.values(n),o=r.reduce((c,l)=>c+l,0)/r.length,s=Bo(e.projectPath),i=o>=4||s==="advisory",a={overall_score:Math.round(o*10)/10,passed:i,mode:s,dimensions:n};return o<4&&(a.remediation=Mp(n)),a}function Qi(e,t){if(t==="bugfix")return["Summary"];switch(e){case"minimal":return["Summary","Architecture Decisions","API Contracts"];case"standard":case"comprehensive":return["Summary","Architecture Decisions","API Contracts","Data Models","Configuration Changes","Dependencies","Known Limitations","How to Test","Recreation Notes"];default:return["Summary"]}}function Up(e){let t=Qi(e.depth,e.pathway),n=e.unitFiles&&e.unitFiles.length>0?e.unitFiles.map(o=>` - ${o}`).join(`
918
+ <!-- Impact scan (${s}): References to ${p.join(", ")} may need manual review after recent changes. -->`;u+=f,l.push(`Advisory note added for: ${p.join(", ")}`)}if(u!==a)try{te.writeFileSync(i.path,u,"utf-8"),r.push({path:i.path,updatedReferences:c,notesAdded:l})}catch{continue}}return r}function jp(e){if(!e.modifiedFiles||e.modifiedFiles.length===0)return{status:"skipped",affectedDocs:[],reportPath:null};let t=Fv(e.modifiedFiles);if(t.length===0)return{status:"skipped",affectedDocs:[],reportPath:null};let n=Dv(e.projectPath,e.workflowId),r=[];for(let c of n){let l;try{l=te.readFileSync(c,"utf-8")}catch{continue}let u=Nv(l,t);u.length>0&&r.push({path:c,references:u,description:`References to ${u.join(", ")} \u2014 verify content is still accurate after unit changes`})}if(r.length===0)return{status:"skipped",affectedDocs:[],reportPath:null};let o=ae.join(e.projectPath,"aidlc-docs",e.workflowId,"construction",e.unitId),s=[];try{s=Lv(r,e.modifiedFiles,e.renamedFiles)}catch{}let i={status:"completed",affectedDocs:r,reportPath:null,updatedDocs:s.length>0?s:void 0},a=jv(i,{unitId:e.unitId,workflowId:e.workflowId,outputDir:o});return i.reportPath=a,i}var ze=b(require("fs"),1),Je=b(require("path"),1);function Uv(e){if(!ze.existsSync(e))return 1;let n=ze.readdirSync(e).map(r=>{let o=/^ADR-(\d+)-/.exec(r);return o?parseInt(o[1],10):0}).filter(r=>r>0);return n.length===0?1:Math.max(...n)+1}function Mp(e){let t=Je.join(e.projectPath,"aidlc-docs",e.workflowId,"decisions");ze.mkdirSync(t,{recursive:!0});let n=Uv(t),r=e.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),o=String(n).padStart(3,"0"),s=`ADR-${o}-${r}.md`,i=[`# ADR-${o}: ${e.title}`,"",`**Date:** ${new Date().toISOString().split("T")[0]}`,"**Status:** Accepted",`**Unit:** ${e.unitId}`,"","## Context","",e.context,"","## Decision","",e.decision,"","## Consequences","",e.consequences,""].join(`
919
+ `),a=Je.join(t,s);return ze.writeFileSync(a,i),{number:n,path:a,title:e.title}}function Lp(e,t){let n=[],r=Je.join(t,"package.json"),o=new Set;if(ze.existsSync(r))try{let s=JSON.parse(ze.readFileSync(r,"utf-8"));o=new Set([...Object.keys(s.dependencies??{}),...Object.keys(s.devDependencies??{})])}catch{}for(let s of e){let i;try{i=ze.readFileSync(s,"utf-8")}catch{continue}let a=i.matchAll(/from ['"]([^./][^'"]+)['"]/g);for(let d of a){let p=d[1].split("/")[0];p&&!o.has(p)&&!p.startsWith("@types/")&&(n.push({title:`Added dependency: ${p}`,context:`Unit ${Je.basename(s)} imports from '${p}', which was not present in the existing package.json dependencies.`,decision:`Include '${p}' as a dependency to support the new functionality introduced in this unit.`,consequences:`Build and runtime environments must have '${p}' available. Adds to bundle size and supply chain surface.`}),o.add(p))}let c=i.matchAll(/export\s+(?:interface|type)\s+(\w+(?:Schema|Model|Entity|Record|Row|Document))\b/g);for(let d of c){let p=d[1];n.push({title:`New data model: ${p}`,context:`A new exported type '${p}' with persistence-related naming was introduced in ${Je.basename(s)}.`,decision:`Define '${p}' as the canonical data model for this domain concept, enforcing a consistent schema across the codebase.`,consequences:"Consumers must adopt this interface. Future migrations require updating this type and all its usages."})}let l=i.matchAll(/(?:app|router)\.(get|post|put|patch|delete)\s*\(\s*['"]([^'"]+)['"]/g);for(let d of l){let p=d[1].toUpperCase(),f=d[2];n.push({title:`API contract change: ${p} ${f}`,context:`A new route '${p} ${f}' was added in ${Je.basename(s)}.`,decision:`Expose '${p} ${f}' as a stable API endpoint for clients to consume.`,consequences:"This endpoint becomes part of the public contract. Breaking changes require versioning or deprecation notices."})}let u=Je.basename(s);if(u==="index.ts"||u==="index.js"){let d=Je.basename(Je.dirname(s));d&&d!=="."&&d!=="src"&&n.push({title:`New module: ${d}`,context:`A new module entry point was created at ${s}, establishing '${d}' as an independent module.`,decision:`Structure '${d}' as a dedicated module with its own public API surface via index.ts.`,consequences:"Other modules should import from this module's public API rather than reaching into internal files."})}}return n}var Zn=b(require("fs"),1),Gp=b(require("path"),1);function Up(e){let t=0;return e.length>0&&t++,e.split(/\s+/).length>100&&t++,/(?:FR-|US-|acceptance|requirement|criteria)/i.test(e)&&t++,/(?:aidlc-docs|\.md|\.ts|\.js|intent|requirements)/i.test(e)&&t++,/(?:^[-*]\s|^#{1,3}\s|^\d+\.\s)/m.test(e)&&t++,Math.min(t,5)}function Wv(e){let t=0;return/## Data Models/i.test(e)&&t++,/(?:interface|type|schema|entity|model|table|field|column|relation)/i.test(e)&&t++,/```[\s\S]*?(?:interface|type|schema)[\s\S]*?```/.test(e)&&t++,/(?:\.ts|\.js|\.py|\.go|models?|entities?|schemas?)\//i.test(e)&&t++,/\|.*\|.*\|/.test(e)&&t++,Math.min(t,5)}function Wp(e){let t=0;return/## Architecture Decisions/i.test(e)&&t++,/## API Contracts/i.test(e)&&t++,/```/.test(e)&&t++,/(?:src\/|lib\/|import|export|function|class)\s/i.test(e)&&t++,/(?:because|therefore|instead of|trade-?off|decision|chose)/i.test(e)&&t++,Math.min(t,5)}function Bv(e){let t=0;return/## How to Test/i.test(e)&&t++,/(?:test|spec|verify|assert|expect|should|given|when|then)/i.test(e)&&t++,/(?:npm test|vitest|jest|pytest|cargo test|go test)/i.test(e)&&t++,/(?:\.test\.|\.spec\.|__tests__|test\/)/i.test(e)&&t++,/^\d+\.\s/m.test(e)&&t++,Math.min(t,5)}function Gv(e){let t=0;return/## (?:Recreation Notes|Configuration Changes)/i.test(e)&&t++,/(?:install|setup|configure|environment|\.env|npm|yarn|pip)/i.test(e)&&t++,/(?:\$\s|```(?:bash|sh|shell))/i.test(e)&&t++,/## Dependencies/i.test(e)&&t++,/(?:prerequisite|required|depends on|known limitation|## Known)/i.test(e)&&t++,Math.min(t,5)}function Bp(e){let t=[];return e.requirements_coverage<=3&&t.push(`Requirements Coverage scored ${e.requirements_coverage}/5 \u2014 add references to FR-* and US-* identifiers, include acceptance criteria traceability`),e.data_model_completeness<=3&&t.push(`Data Model Completeness scored ${e.data_model_completeness}/5 \u2014 add entity relationships, schema definitions, and type examples`),e.implementation_guidance<=3&&t.push(`Implementation Guidance scored ${e.implementation_guidance}/5 \u2014 add architecture decision rationale, API contract details, and code examples`),e.test_coverage_documentation<=3&&t.push(`Test Coverage Documentation scored ${e.test_coverage_documentation}/5 \u2014 add test approach, verification steps, and test file references`),e.bootstrap_capability<=3&&t.push(`Bootstrap Capability scored ${e.bootstrap_capability}/5 \u2014 add setup instructions, environment configuration, and dependency information`),t}function Go(e){try{let t=Gp.join(e,".olympus","config.json");return Zn.existsSync(t)&&JSON.parse(Zn.readFileSync(t,"utf-8")).recreation_readiness_mode==="blocking"?"blocking":"advisory"}catch{return"advisory"}}function Xi(e){if(e.override===!0){let c={overall_score:0,passed:!0,mode:Go(e.projectPath),dimensions:{requirements_coverage:0,data_model_completeness:0,implementation_guidance:0,test_coverage_documentation:0,bootstrap_capability:0}};return e.overrideRationale&&(c.remediation=[`Override applied: ${e.overrideRationale}`]),c}if(e.pathway==="bugfix")return{overall_score:0,passed:!0,mode:"advisory",dimensions:{requirements_coverage:0,data_model_completeness:0,implementation_guidance:0,test_coverage_documentation:0,bootstrap_capability:0}};if(e.depth==="minimal"){let c=Go(e.projectPath),l="";try{l=Zn.readFileSync(e.featureDocPath,"utf-8")}catch{return{overall_score:0,passed:!1,mode:c,dimensions:{requirements_coverage:0,data_model_completeness:0,implementation_guidance:0,test_coverage_documentation:0,bootstrap_capability:0},remediation:["Feature doc could not be read \u2014 ensure it exists at the expected path"]}}let u=Up(l),d=Wp(l),p=(u+d)/2,f=p>=3.5||c==="advisory",m={requirements_coverage:u,data_model_completeness:0,implementation_guidance:d,test_coverage_documentation:0,bootstrap_capability:0},g={overall_score:Math.round(p*10)/10,passed:f,mode:c,dimensions:m};return p<3.5&&(g.remediation=Bp(m)),g}let t="";try{t=Zn.readFileSync(e.featureDocPath,"utf-8")}catch{return{overall_score:0,passed:!1,mode:Go(e.projectPath),dimensions:{requirements_coverage:0,data_model_completeness:0,implementation_guidance:0,test_coverage_documentation:0,bootstrap_capability:0},remediation:["Feature doc could not be read \u2014 ensure it exists at the expected path"]}}let n={requirements_coverage:Up(t),data_model_completeness:Wv(t),implementation_guidance:Wp(t),test_coverage_documentation:Bv(t),bootstrap_capability:Gv(t)},r=Object.values(n),o=r.reduce((c,l)=>c+l,0)/r.length,s=Go(e.projectPath),i=o>=4||s==="advisory",a={overall_score:Math.round(o*10)/10,passed:i,mode:s,dimensions:n};return o<4&&(a.remediation=Bp(n)),a}function Zi(e,t){if(t==="bugfix")return["Summary"];switch(e){case"minimal":return["Summary","Architecture Decisions","API Contracts"];case"standard":case"comprehensive":return["Summary","Architecture Decisions","API Contracts","Data Models","Configuration Changes","Dependencies","Known Limitations","How to Test","Recreation Notes"];default:return["Summary"]}}function Hp(e){let t=Zi(e.depth,e.pathway),n=e.unitFiles&&e.unitFiles.length>0?e.unitFiles.map(o=>` - ${o}`).join(`
920
920
  `):" (no unit files provided)",r=e.testResults?`Tests: ${e.testResults.total} total, ${e.testResults.passed} passed, ${e.testResults.failed} failed`:"No test results available";return`Generate feature documentation for unit "${e.unitId}" in workflow "${e.workflowId}".
921
921
 
922
922
  ## Context
@@ -932,8 +932,8 @@ ${t.map((o,s)=>`${s+1}. ${o}`).join(`
932
932
  `)}
933
933
 
934
934
  For each section provide detailed, accurate content based on the unit's implementation.
935
- Do not use placeholder text \u2014 write real documentation.`}function Fv(e,t){let n=Ho.join(t.outputDir,"documentation");Vr.mkdirSync(n,{recursive:!0});let r=["---",`unit: ${t.unitId}`,`workflow: ${t.workflowId}`,`depth: ${t.depth}`,`pathway: ${t.pathway}`,`generated_at: ${new Date().toISOString()}`,`sections: [${t.sections.join(", ")}]`,"recreation_readiness_score: null","---",""].join(`
936
- `),o=Ho.join(n,"feature-doc.md");return Vr.writeFileSync(o,r+e),o}function jv(e){let t=Qi(e.depth,e.pathway),n=`# Feature Documentation: ${e.unitId}
935
+ Do not use placeholder text \u2014 write real documentation.`}function Hv(e,t){let n=Ho.join(t.outputDir,"documentation");Vr.mkdirSync(n,{recursive:!0});let r=["---",`unit: ${t.unitId}`,`workflow: ${t.workflowId}`,`depth: ${t.depth}`,`pathway: ${t.pathway}`,`generated_at: ${new Date().toISOString()}`,`sections: [${t.sections.join(", ")}]`,"recreation_readiness_score: null","---",""].join(`
936
+ `),o=Ho.join(n,"feature-doc.md");return Vr.writeFileSync(o,r+e),o}function Vv(e){let t=Zi(e.depth,e.pathway),n=`# Feature Documentation: ${e.unitId}
937
937
 
938
938
  `;for(let r of t)n+=`## ${r}
939
939
 
@@ -945,28 +945,28 @@ Do not use placeholder text \u2014 write real documentation.`}function Fv(e,t){l
945
945
  `,n+=`- Passed: ${e.testResults.passed}
946
946
  `,n+=`- Failed: ${e.testResults.failed}
947
947
 
948
- `),n}function Wp(e){let t=$p({...e}),n=Np(e.modifiedFiles,e.projectPath),r=0;for(let o of n)Dp({workflowId:e.workflowId,unitId:e.unitId,projectPath:e.projectPath,...o}),r++;return{impactScan:t,adrCount:r}}function Gp(e){try{let t=Qi(e.depth,e.pathway),n=jv(e),r=Ho.join(e.projectPath,"aidlc-docs",e.workflowId,"construction",e.unitId);return{status:"completed",path:Fv(n,{unitId:e.unitId,workflowId:e.workflowId,depth:e.depth,pathway:e.pathway,sections:t,outputDir:r}),sections:t}}catch(t){return{status:"failed",path:null,sections:[],error:t instanceof Error?t.message:String(t)}}}var Mt=T(require("fs"),1),Xi=T(require("path"),1);function Mv(e){let t=[{re:/process\.env\.([A-Z_][A-Z0-9_]*)/g,groupIndex:1},{re:/import\.meta\.env\.([A-Z_][A-Z0-9_]*)/g,groupIndex:1},{re:/Deno\.env\.get\(['"]([^'"]+)['"]\)/g,groupIndex:1},{re:/os\.environ\[['"]([^'"]+)['"]\]/g,groupIndex:1},{re:/os\.getenv\(['"]([^'"]+)['"]\)/g,groupIndex:1}],n=new Set,r=[];for(let o of e){let s;try{s=Mt.readFileSync(o,"utf-8")}catch{continue}let i=s.split(`
949
- `);for(let a=0;a<i.length;a++){let c=i[a];for(let{re:l,groupIndex:u}of t){l.lastIndex=0;let d;for(;(d=l.exec(c))!==null;){let p=d[u],f=`${p}|${o}`;n.has(f)||(n.add(f),r.push({name:p,file:o,line:a+1}))}}}}return r}function Lv(e){let t=e.toUpperCase();return t.endsWith("_URL")||t.endsWith("_URI")?"https://example.com":t.endsWith("_KEY")||t.endsWith("_API_KEY")?"your-api-key-here":t.endsWith("_SECRET")||t.endsWith("_TOKEN")?"your-secret-here":t.endsWith("_PORT")?"3000":t.endsWith("_HOST")?"localhost":t.endsWith("_PASSWORD")||t.endsWith("_PASS")?"your-password-here":t.endsWith("_DATABASE")||t.endsWith("_DB")?"your-database-name":`your-${e.toLowerCase().replace(/_/g,"-")}-here`}function Uv(e,t){let n=Xi.join(t,".env.example"),r="",o=!1;try{r=Mt.readFileSync(n,"utf-8"),o=!0}catch{o=!1}let s=new Set;for(let d of r.split(`
948
+ `),n}function Vp(e){let t=jp({...e}),n=Lp(e.modifiedFiles,e.projectPath),r=0;for(let o of n)Mp({workflowId:e.workflowId,unitId:e.unitId,projectPath:e.projectPath,...o}),r++;return{impactScan:t,adrCount:r}}function qp(e){try{let t=Zi(e.depth,e.pathway),n=Vv(e),r=Ho.join(e.projectPath,"aidlc-docs",e.workflowId,"construction",e.unitId);return{status:"completed",path:Hv(n,{unitId:e.unitId,workflowId:e.workflowId,depth:e.depth,pathway:e.pathway,sections:t,outputDir:r}),sections:t}}catch(t){return{status:"failed",path:null,sections:[],error:t instanceof Error?t.message:String(t)}}}var Mt=b(require("fs"),1),ea=b(require("path"),1);function qv(e){let t=[{re:/process\.env\.([A-Z_][A-Z0-9_]*)/g,groupIndex:1},{re:/import\.meta\.env\.([A-Z_][A-Z0-9_]*)/g,groupIndex:1},{re:/Deno\.env\.get\(['"]([^'"]+)['"]\)/g,groupIndex:1},{re:/os\.environ\[['"]([^'"]+)['"]\]/g,groupIndex:1},{re:/os\.getenv\(['"]([^'"]+)['"]\)/g,groupIndex:1}],n=new Set,r=[];for(let o of e){let s;try{s=Mt.readFileSync(o,"utf-8")}catch{continue}let i=s.split(`
949
+ `);for(let a=0;a<i.length;a++){let c=i[a];for(let{re:l,groupIndex:u}of t){l.lastIndex=0;let d;for(;(d=l.exec(c))!==null;){let p=d[u],f=`${p}|${o}`;n.has(f)||(n.add(f),r.push({name:p,file:o,line:a+1}))}}}}return r}function Yv(e){let t=e.toUpperCase();return t.endsWith("_URL")||t.endsWith("_URI")?"https://example.com":t.endsWith("_KEY")||t.endsWith("_API_KEY")?"your-api-key-here":t.endsWith("_SECRET")||t.endsWith("_TOKEN")?"your-secret-here":t.endsWith("_PORT")?"3000":t.endsWith("_HOST")?"localhost":t.endsWith("_PASSWORD")||t.endsWith("_PASS")?"your-password-here":t.endsWith("_DATABASE")||t.endsWith("_DB")?"your-database-name":`your-${e.toLowerCase().replace(/_/g,"-")}-here`}function Kv(e,t){let n=ea.join(t,".env.example"),r="",o=!1;try{r=Mt.readFileSync(n,"utf-8"),o=!0}catch{o=!1}let s=new Set;for(let d of r.split(`
950
950
  `)){let p=d.trim();if(p&&!p.startsWith("#")){let f=p.indexOf("=");f!==-1&&s.add(p.substring(0,f).trim())}}let i=[...new Set(e.map(d=>d.name))],a=[],c=[];for(let d of i)s.has(d)?c.push(d):a.push(d);let l=r;if(a.length>0){let d=l.length>0&&!l.endsWith(`
951
951
  `)?`
952
- `:"",p=a.map(f=>`${f}=${Lv(f)}`).join(`
952
+ `:"",p=a.map(f=>`${f}=${Yv(f)}`).join(`
953
953
  `);l=l+d+p+`
954
- `}let u=`${n}.tmp.${Date.now()}`;return Mt.writeFileSync(u,l,"utf-8"),Mt.renameSync(u,n),{created:!o,added:a,existing:c}}function Wv(e){let t=Xi.join(e,".gitignore"),n="",r=!1;try{n=Mt.readFileSync(t,"utf-8"),r=!0}catch{r=!1}if(n.split(`
954
+ `}let u=`${n}.tmp.${Date.now()}`;return Mt.writeFileSync(u,l,"utf-8"),Mt.renameSync(u,n),{created:!o,added:a,existing:c}}function Jv(e){let t=ea.join(e,".gitignore"),n="",r=!1;try{n=Mt.readFileSync(t,"utf-8"),r=!0}catch{r=!1}if(n.split(`
955
955
  `).some(i=>i.trim()===".env"||i.trim()==="/.env"))return{created:!1,added:!1};let s=n.length>0&&!n.endsWith(`
956
956
  `)?`
957
957
  `:"";return Mt.writeFileSync(t,n+s+`.env
958
- `,"utf-8"),{created:!r,added:!0}}function Bp(e,t){let n=Mv(t);return n.length===0?{envVarsDetected:[],envExampleResult:{created:!1,added:[],existing:[]},gitignoreResult:{created:!1,added:!1}}:{envVarsDetected:n,envExampleResult:Uv(n,e),gitignoreResult:Wv(e)}}var Qe=T(X(),1),Tn=require("path"),qp=require("child_process"),Gv=["**/*.ts","**/*.js","**/*.tsx","**/*.jsx","**/*.py","**/*.java","**/*.go"],Bv=["**/node_modules/**","**/__tests__/**","**/test/**","**/fixtures/**","**/dist/**","**/*.d.ts"];function Hv(e){let t=e.replace(/\\/g,"/"),n="",r=0;for(;r<t.length;)t[r]==="*"&&t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.+/)?",r+=3):(n+=".*",r+=2):t[r]==="*"?(n+="[^/]*",r++):t[r]==="?"?(n+="[^/]",r++):(n+=t[r].replace(/[.+^${}()|[\]\\]/g,"\\$&"),r++);return new RegExp(`^${n}$`)}function Yp(e,t){return Hv(t).test(e)}function Hp(e,t){return t.some(n=>Yp(e,n))}function Kp(e){let t=[],n;try{n=Qe.readdirSync(e,{withFileTypes:!0})}catch{return t}for(let r of n){let o=(0,Tn.join)(e,r.name);r.isDirectory()?t.push(...Kp(o)):r.isFile()&&t.push(o)}return t}function Vv(e,t){let n=t.includeGlobs??Gv,r=t.excludeGlobs??Bv;return Kp(e).filter(o=>{let s=(0,Tn.relative)(e,o).replace(/\\/g,"/");return Hp(s,n)&&!Hp(s,r)})}function Zi(e,t){return(e.substring(0,t).match(/\n/g)||[]).length+1}var qv=[{name:"AWS Access Key",pattern:/AKIA[0-9A-Z]{16}/g},{name:"Generic API Key",pattern:/['"]?api[_-]?key['"]?\s*[:=]\s*['"][a-zA-Z0-9]{20,}['"]/gi},{name:"Generic Secret",pattern:/['"]?secret['"]?\s*[:=]\s*['"][a-zA-Z0-9]{20,}['"]/gi},{name:"Private Key",pattern:/-----BEGIN\s+(RSA\s+)?PRIVATE KEY-----/g},{name:"Bearer Token",pattern:/Bearer\s+[a-zA-Z0-9\-._~+/]+=*/g},{name:"Connection String",pattern:/(?:mongodb|postgres|mysql|redis):\/\/[^\s'"]+/gi},{name:"JWT Token",pattern:/eyJ[a-zA-Z0-9_-]{10,}\.[a-zA-Z0-9_-]{10,}\.[a-zA-Z0-9_-]{10,}/g}];function ea(e,t){let n=[];for(let{name:r,pattern:o}of qv){o.lastIndex=0;let s;for(;(s=o.exec(e))!==null;)n.push({id:`sec-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,category:"hardcoded-secret",severity:"critical",message:`${r} detected`,file:t,line:Zi(e,s.index),pattern:r});o.lastIndex=0}return n}var Yv=[{name:"String concatenation in SQL query",pattern:/(?:['"`]\s*\+\s*\w+.*(?:SELECT|INSERT|UPDATE|DELETE|DROP|FROM|WHERE)|(?:SELECT|INSERT|UPDATE|DELETE|DROP|FROM|WHERE).*['"`]\s*\+\s*\w+)/gi},{name:"Template literal in SQL query",pattern:/(?:\$\{[^}]+\}.*(?:SELECT|INSERT|UPDATE|DELETE|DROP|FROM|WHERE)|(?:SELECT|INSERT|UPDATE|DELETE|DROP|FROM|WHERE)[^\n]*\$\{)/gi},{name:"Unparameterized query construction",pattern:/(?:query|execute|sql)\s*\(\s*['"`].*\+/gi}];function Kv(e,t){let n=[];for(let{name:r,pattern:o}of Yv){o.lastIndex=0;let s;for(;(s=o.exec(e))!==null;)n.push({id:`sec-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,category:"sql-injection",severity:"warning",message:`${r} detected`,file:t,line:Zi(e,s.index),pattern:r});o.lastIndex=0}return n}var Jv=[{name:"innerHTML assignment",pattern:/\.innerHTML\s*=/g},{name:"dangerouslySetInnerHTML",pattern:/dangerouslySetInnerHTML/g},{name:"document.write",pattern:/document\.write\s*\(/g},{name:"eval usage",pattern:/\beval\s*\(/g}];function ta(e,t){let n=[];for(let{name:r,pattern:o}of Jv){o.lastIndex=0;let s;for(;(s=o.exec(e))!==null;)n.push({id:`sec-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,category:"xss",severity:"warning",message:`${r} detected`,file:t,line:Zi(e,s.index),pattern:r});o.lastIndex=0}return n}function Vp(e){let t=JSON.parse(e),n=[],r=t.vulnerabilities||{};for(let[o,s]of Object.entries(r)){let i=s.severity,a=i==="critical"||i==="high"?"critical":i==="moderate"?"warning":"info";n.push({id:`sec-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,category:"dependency-cve",severity:a,message:`Vulnerable dependency: ${o} (${i})`,pattern:o})}return n}function zv(e){try{let t=(0,qp.execSync)("npm audit --json",{cwd:e,timeout:6e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return Vp(t)}catch(t){try{if(t.stdout)return Vp(t.stdout)}catch{}return[]}}function Qv(e){let t=(0,Tn.join)(e,".olympus","security-ignore.json");try{if(Qe.existsSync(t))return Qe.readJsonSync(t)}catch{}return{}}function Xv(e,t){let n=t.paths||[],r=t.patterns||[],o=t.reasons||{};return e.map(s=>{if(s.file&&n.length>0){let i=s.file.replace(/\\/g,"/");for(let a of n)if(Yp(i,a)||i.includes(a.replace(/\\/g,"/")))return{...s,suppressed:!0,suppress_reason:o[a]||`Path suppressed: ${a}`}}return s.pattern&&r.includes(s.pattern)?{...s,suppressed:!0,suppress_reason:o[s.pattern]||`Pattern suppressed: ${s.pattern}`}:s})}function Zv(e){switch(e){case"hardcoded-secret":return"Hardcoded Secrets";case"sql-injection":return"SQL Injection";case"xss":return"Cross-Site Scripting (XSS)";case"dependency-cve":return"Dependency CVEs";case"risky-pattern":return"Risky Patterns"}}function eT(e,t){let{unitId:n,workflowId:r,filesScanned:o,scanDate:s}=t,i=s||new Date().toISOString(),a=e.filter(y=>!y.suppressed),c=a.filter(y=>y.severity==="critical").length,l=a.filter(y=>y.severity==="warning").length,u=a.filter(y=>y.severity==="info").length,d=e.filter(y=>y.suppressed).length,p=c>0?"failed":"passed",f=["---",`unit: ${n}`,`workflow: ${r}`,`scan_date: ${i}`,`files_scanned: ${o}`,`findings_critical: ${c}`,`findings_warning: ${l}`,`findings_info: ${u}`,`findings_suppressed: ${d}`,`status: ${p}`,"---","",`# Security Report: ${n}`,"",`**Status**: ${p==="passed"?"PASSED":"FAILED"} `,`**Scan Date**: ${i} `,`**Files Scanned**: ${o} `,"","## Summary","","| Severity | Count |","|----------|-------|",`| Critical | ${c} |`,`| Warning | ${l} |`,`| Info | ${u} |`,`| Suppressed | ${d} |`,""],m=["hardcoded-secret","sql-injection","xss","dependency-cve","risky-pattern"];for(let y of m){let w=a.filter(k=>k.category===y);if(w.length!==0){f.push(`## ${Zv(y)}`,"");for(let k of w){let h=k.file?` \u2014 \`${k.file}\`${k.line?`:${k.line}`:""}`:"";f.push(`- **[${k.severity.toUpperCase()}]** ${k.message}${h}`)}f.push("")}}let g=e.filter(y=>y.suppressed);if(g.length>0){f.push("## Suppressed Findings","");for(let y of g){let w=y.file?` \u2014 \`${y.file}\`${y.line?`:${y.line}`:""}`:"";f.push(`- ~~**[${y.severity.toUpperCase()}]** ${y.message}${w}~~ *(${y.suppress_reason||"suppressed"})*`)}f.push("")}return f.join(`
959
- `)}async function Jp(e){let t=Date.now();try{let n=Vv(e.projectPath,e),r=[];for(let c of n)try{let l=Qe.readFileSync(c,"utf-8");r.push(...ea(l,c)),r.push(...Kv(l,c)),r.push(...ta(l,c))}catch{}r.push(...zv(e.projectPath));let o=Qv(e.projectPath),s=Xv(r,o),i=(0,Tn.join)(e.projectPath,"aidlc-docs",e.workflowId,"construction",e.unitId,"security");Qe.ensureDirSync(i);let a=(0,Tn.join)(i,"security-report.md");return Qe.writeFileSync(a,eT(s,{unitId:e.unitId,workflowId:e.workflowId,outputDir:i,filesScanned:n.length}),"utf-8"),{status:"completed",findings:s,scanned_files:n.length,scan_duration_ms:Date.now()-t,report_path:a}}catch{return{status:"failed",findings:[],scanned_files:0,scan_duration_ms:Date.now()-t,report_path:""}}}var Vo=T(require("fs"),1),qo=T(require("path"),1);function tT(e){let t=e.construction_units?Object.values(e.construction_units):[],n=0,r=0,o=0,s=0,i=0,a=0,c=0,l=0,u=0,d=t.filter(_=>_.code_generation_status==="completed").length;for(let _ of t)n+=_.tests_total??0,r+=_.tests_passed??0,o+=_.tests_failed??0,_.coverage_percentage!=null&&(s+=_.coverage_percentage,i++),a+=_.security_findings_critical??0,c+=_.security_findings_warning??0,l+=_.security_findings_info??0,u+=_.regressions_count??0;let p=0,f=e.phases??{},m=0;for(let _ of["discovery","inception","construction","operations"]){let j=f[_];j&&j.status&&j.status!=="not_started"&&m++}let g=e.metrics,y={inception_ms:g?.inception_duration_ms??0,construction_ms:g?.construction_duration_ms??0,operations_ms:g?.operations_duration_ms??0},w=g?.validation_pass_rate??0,k=g?.rework_count??0,h=0;for(let _ of t){let j=_.regressions_count??0,R=_.tests_failed??0;j>0&&R===0&&(h+=j)}let v=0,S=0;for(let _ of t)_.recreation_readiness_score!=null&&(v+=_.recreation_readiness_score,S++);let b=S>0?Math.round(v/S*10)/10:null;return{tests_total:n,tests_passed:r,tests_failed:o,coverage_percentage:i>0?Math.round(s/i*10)/10:null,security_findings:{critical:a,warning:c,info:l},units_completed:d,units_total:t.length,regressions_count:u,gate_bypass_count:p,data_sources:nT(t),phases_completed:m,time_per_phase:y,validation_pass_rate:w,rework_count:k,regressions_fixed:h,average_recreation_readiness_score:b}}function nT(e){let t=e.some(i=>(i.tests_total??0)>0),n=e.some(i=>i.coverage_percentage!=null),r=e.some(i=>i.security_scan_status==="completed"),o=e.some(i=>i.feature_doc_status==="completed"),s=e.some(i=>i.recreation_readiness_score!=null);return{tests:t?"connected":"pending",coverage:n?"connected":"pending",security:r?"connected":"pending",documentation:o?"connected":"pending",recreation_readiness:s?"connected":"pending"}}function rT(e,t){let n=qo.join(t.projectPath,"aidlc-docs",t.workflowId,"quality-scorecard.md"),r=["---",`workflow: ${t.workflowId}`,`feature: "${t.featureName}"`,`generated_at: ${new Date().toISOString()}`,`tests_total: ${e.tests_total}`,`tests_passed: ${e.tests_passed}`,`tests_failed: ${e.tests_failed}`,`coverage_percentage: ${e.coverage_percentage??"null"}`,`security_critical: ${e.security_findings.critical}`,`security_warning: ${e.security_findings.warning}`,`security_info: ${e.security_findings.info}`,`units_completed: ${e.units_completed}`,`units_total: ${e.units_total}`,`regressions_count: ${e.regressions_count}`,`gate_bypass_count: ${e.gate_bypass_count}`,`phases_completed: ${e.phases_completed??0}`,`validation_pass_rate: ${e.validation_pass_rate??0}`,`rework_count: ${e.rework_count??0}`,`regressions_fixed: ${e.regressions_fixed??0}`,`average_recreation_readiness_score: ${e.average_recreation_readiness_score??"null"}`,"---",""].join(`
958
+ `,"utf-8"),{created:!r,added:!0}}function Yp(e,t){let n=qv(t);return n.length===0?{envVarsDetected:[],envExampleResult:{created:!1,added:[],existing:[]},gitignoreResult:{created:!1,added:!1}}:{envVarsDetected:n,envExampleResult:Kv(n,e),gitignoreResult:Jv(e)}}var Qe=b(X(),1),bn=require("path"),zp=require("child_process"),zv=["**/*.ts","**/*.js","**/*.tsx","**/*.jsx","**/*.py","**/*.java","**/*.go"],Qv=["**/node_modules/**","**/__tests__/**","**/test/**","**/fixtures/**","**/dist/**","**/*.d.ts"];function Xv(e){let t=e.replace(/\\/g,"/"),n="",r=0;for(;r<t.length;)t[r]==="*"&&t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.+/)?",r+=3):(n+=".*",r+=2):t[r]==="*"?(n+="[^/]*",r++):t[r]==="?"?(n+="[^/]",r++):(n+=t[r].replace(/[.+^${}()|[\]\\]/g,"\\$&"),r++);return new RegExp(`^${n}$`)}function Qp(e,t){return Xv(t).test(e)}function Kp(e,t){return t.some(n=>Qp(e,n))}function Xp(e){let t=[],n;try{n=Qe.readdirSync(e,{withFileTypes:!0})}catch{return t}for(let r of n){let o=(0,bn.join)(e,r.name);r.isDirectory()?t.push(...Xp(o)):r.isFile()&&t.push(o)}return t}function Zv(e,t){let n=t.includeGlobs??zv,r=t.excludeGlobs??Qv;return Xp(e).filter(o=>{let s=(0,bn.relative)(e,o).replace(/\\/g,"/");return Kp(s,n)&&!Kp(s,r)})}function ta(e,t){return(e.substring(0,t).match(/\n/g)||[]).length+1}var eb=[{name:"AWS Access Key",pattern:/AKIA[0-9A-Z]{16}/g},{name:"Generic API Key",pattern:/['"]?api[_-]?key['"]?\s*[:=]\s*['"][a-zA-Z0-9]{20,}['"]/gi},{name:"Generic Secret",pattern:/['"]?secret['"]?\s*[:=]\s*['"][a-zA-Z0-9]{20,}['"]/gi},{name:"Private Key",pattern:/-----BEGIN\s+(RSA\s+)?PRIVATE KEY-----/g},{name:"Bearer Token",pattern:/Bearer\s+[a-zA-Z0-9\-._~+/]+=*/g},{name:"Connection String",pattern:/(?:mongodb|postgres|mysql|redis):\/\/[^\s'"]+/gi},{name:"JWT Token",pattern:/eyJ[a-zA-Z0-9_-]{10,}\.[a-zA-Z0-9_-]{10,}\.[a-zA-Z0-9_-]{10,}/g}];function na(e,t){let n=[];for(let{name:r,pattern:o}of eb){o.lastIndex=0;let s;for(;(s=o.exec(e))!==null;)n.push({id:`sec-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,category:"hardcoded-secret",severity:"critical",message:`${r} detected`,file:t,line:ta(e,s.index),pattern:r});o.lastIndex=0}return n}var tb=[{name:"String concatenation in SQL query",pattern:/(?:['"`]\s*\+\s*\w+.*(?:SELECT|INSERT|UPDATE|DELETE|DROP|FROM|WHERE)|(?:SELECT|INSERT|UPDATE|DELETE|DROP|FROM|WHERE).*['"`]\s*\+\s*\w+)/gi},{name:"Template literal in SQL query",pattern:/(?:\$\{[^}]+\}.*(?:SELECT|INSERT|UPDATE|DELETE|DROP|FROM|WHERE)|(?:SELECT|INSERT|UPDATE|DELETE|DROP|FROM|WHERE)[^\n]*\$\{)/gi},{name:"Unparameterized query construction",pattern:/(?:query|execute|sql)\s*\(\s*['"`].*\+/gi}];function nb(e,t){let n=[];for(let{name:r,pattern:o}of tb){o.lastIndex=0;let s;for(;(s=o.exec(e))!==null;)n.push({id:`sec-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,category:"sql-injection",severity:"warning",message:`${r} detected`,file:t,line:ta(e,s.index),pattern:r});o.lastIndex=0}return n}var rb=[{name:"innerHTML assignment",pattern:/\.innerHTML\s*=/g},{name:"dangerouslySetInnerHTML",pattern:/dangerouslySetInnerHTML/g},{name:"document.write",pattern:/document\.write\s*\(/g},{name:"eval usage",pattern:/\beval\s*\(/g}];function ra(e,t){let n=[];for(let{name:r,pattern:o}of rb){o.lastIndex=0;let s;for(;(s=o.exec(e))!==null;)n.push({id:`sec-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,category:"xss",severity:"warning",message:`${r} detected`,file:t,line:ta(e,s.index),pattern:r});o.lastIndex=0}return n}function Jp(e){let t=JSON.parse(e),n=[],r=t.vulnerabilities||{};for(let[o,s]of Object.entries(r)){let i=s.severity,a=i==="critical"||i==="high"?"critical":i==="moderate"?"warning":"info";n.push({id:`sec-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,category:"dependency-cve",severity:a,message:`Vulnerable dependency: ${o} (${i})`,pattern:o})}return n}function ob(e){try{let t=(0,zp.execSync)("npm audit --json",{cwd:e,timeout:6e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return Jp(t)}catch(t){try{if(t.stdout)return Jp(t.stdout)}catch{}return[]}}function sb(e){let t=(0,bn.join)(e,".olympus","security-ignore.json");try{if(Qe.existsSync(t))return Qe.readJsonSync(t)}catch{}return{}}function ib(e,t){let n=t.paths||[],r=t.patterns||[],o=t.reasons||{};return e.map(s=>{if(s.file&&n.length>0){let i=s.file.replace(/\\/g,"/");for(let a of n)if(Qp(i,a)||i.includes(a.replace(/\\/g,"/")))return{...s,suppressed:!0,suppress_reason:o[a]||`Path suppressed: ${a}`}}return s.pattern&&r.includes(s.pattern)?{...s,suppressed:!0,suppress_reason:o[s.pattern]||`Pattern suppressed: ${s.pattern}`}:s})}function ab(e){switch(e){case"hardcoded-secret":return"Hardcoded Secrets";case"sql-injection":return"SQL Injection";case"xss":return"Cross-Site Scripting (XSS)";case"dependency-cve":return"Dependency CVEs";case"risky-pattern":return"Risky Patterns"}}function cb(e,t){let{unitId:n,workflowId:r,filesScanned:o,scanDate:s}=t,i=s||new Date().toISOString(),a=e.filter(y=>!y.suppressed),c=a.filter(y=>y.severity==="critical").length,l=a.filter(y=>y.severity==="warning").length,u=a.filter(y=>y.severity==="info").length,d=e.filter(y=>y.suppressed).length,p=c>0?"failed":"passed",f=["---",`unit: ${n}`,`workflow: ${r}`,`scan_date: ${i}`,`files_scanned: ${o}`,`findings_critical: ${c}`,`findings_warning: ${l}`,`findings_info: ${u}`,`findings_suppressed: ${d}`,`status: ${p}`,"---","",`# Security Report: ${n}`,"",`**Status**: ${p==="passed"?"PASSED":"FAILED"} `,`**Scan Date**: ${i} `,`**Files Scanned**: ${o} `,"","## Summary","","| Severity | Count |","|----------|-------|",`| Critical | ${c} |`,`| Warning | ${l} |`,`| Info | ${u} |`,`| Suppressed | ${d} |`,""],m=["hardcoded-secret","sql-injection","xss","dependency-cve","risky-pattern"];for(let y of m){let w=a.filter(_=>_.category===y);if(w.length!==0){f.push(`## ${ab(y)}`,"");for(let _ of w){let h=_.file?` \u2014 \`${_.file}\`${_.line?`:${_.line}`:""}`:"";f.push(`- **[${_.severity.toUpperCase()}]** ${_.message}${h}`)}f.push("")}}let g=e.filter(y=>y.suppressed);if(g.length>0){f.push("## Suppressed Findings","");for(let y of g){let w=y.file?` \u2014 \`${y.file}\`${y.line?`:${y.line}`:""}`:"";f.push(`- ~~**[${y.severity.toUpperCase()}]** ${y.message}${w}~~ *(${y.suppress_reason||"suppressed"})*`)}f.push("")}return f.join(`
959
+ `)}async function Zp(e){let t=Date.now();try{let n=Zv(e.projectPath,e),r=[];for(let c of n)try{let l=Qe.readFileSync(c,"utf-8");r.push(...na(l,c)),r.push(...nb(l,c)),r.push(...ra(l,c))}catch{}r.push(...ob(e.projectPath));let o=sb(e.projectPath),s=ib(r,o),i=(0,bn.join)(e.projectPath,"aidlc-docs",e.workflowId,"construction",e.unitId,"security");Qe.ensureDirSync(i);let a=(0,bn.join)(i,"security-report.md");return Qe.writeFileSync(a,cb(s,{unitId:e.unitId,workflowId:e.workflowId,outputDir:i,filesScanned:n.length}),"utf-8"),{status:"completed",findings:s,scanned_files:n.length,scan_duration_ms:Date.now()-t,report_path:a}}catch{return{status:"failed",findings:[],scanned_files:0,scan_duration_ms:Date.now()-t,report_path:""}}}var Vo=b(require("fs"),1),qo=b(require("path"),1);function lb(e){let t=e.construction_units?Object.values(e.construction_units):[],n=0,r=0,o=0,s=0,i=0,a=0,c=0,l=0,u=0,d=t.filter(k=>k.code_generation_status==="completed").length;for(let k of t)n+=k.tests_total??0,r+=k.tests_passed??0,o+=k.tests_failed??0,k.coverage_percentage!=null&&(s+=k.coverage_percentage,i++),a+=k.security_findings_critical??0,c+=k.security_findings_warning??0,l+=k.security_findings_info??0,u+=k.regressions_count??0;let p=0,f=e.phases??{},m=0;for(let k of["discovery","inception","construction","operations"]){let j=f[k];j&&j.status&&j.status!=="not_started"&&m++}let g=e.metrics,y={inception_ms:g?.inception_duration_ms??0,construction_ms:g?.construction_duration_ms??0,operations_ms:g?.operations_duration_ms??0},w=g?.validation_pass_rate??0,_=g?.rework_count??0,h=0;for(let k of t){let j=k.regressions_count??0,R=k.tests_failed??0;j>0&&R===0&&(h+=j)}let v=0,S=0;for(let k of t)k.recreation_readiness_score!=null&&(v+=k.recreation_readiness_score,S++);let E=S>0?Math.round(v/S*10)/10:null;return{tests_total:n,tests_passed:r,tests_failed:o,coverage_percentage:i>0?Math.round(s/i*10)/10:null,security_findings:{critical:a,warning:c,info:l},units_completed:d,units_total:t.length,regressions_count:u,gate_bypass_count:p,data_sources:ub(t),phases_completed:m,time_per_phase:y,validation_pass_rate:w,rework_count:_,regressions_fixed:h,average_recreation_readiness_score:E}}function ub(e){let t=e.some(i=>(i.tests_total??0)>0),n=e.some(i=>i.coverage_percentage!=null),r=e.some(i=>i.security_scan_status==="completed"),o=e.some(i=>i.feature_doc_status==="completed"),s=e.some(i=>i.recreation_readiness_score!=null);return{tests:t?"connected":"pending",coverage:n?"connected":"pending",security:r?"connected":"pending",documentation:o?"connected":"pending",recreation_readiness:s?"connected":"pending"}}function db(e,t){let n=qo.join(t.projectPath,"aidlc-docs",t.workflowId,"quality-scorecard.md"),r=["---",`workflow: ${t.workflowId}`,`feature: "${t.featureName}"`,`generated_at: ${new Date().toISOString()}`,`tests_total: ${e.tests_total}`,`tests_passed: ${e.tests_passed}`,`tests_failed: ${e.tests_failed}`,`coverage_percentage: ${e.coverage_percentage??"null"}`,`security_critical: ${e.security_findings.critical}`,`security_warning: ${e.security_findings.warning}`,`security_info: ${e.security_findings.info}`,`units_completed: ${e.units_completed}`,`units_total: ${e.units_total}`,`regressions_count: ${e.regressions_count}`,`gate_bypass_count: ${e.gate_bypass_count}`,`phases_completed: ${e.phases_completed??0}`,`validation_pass_rate: ${e.validation_pass_rate??0}`,`rework_count: ${e.rework_count??0}`,`regressions_fixed: ${e.regressions_fixed??0}`,`average_recreation_readiness_score: ${e.average_recreation_readiness_score??"null"}`,"---",""].join(`
960
960
  `),o=e.tests_total>0?Math.round(e.tests_passed/e.tests_total*100):0,s=[`# Quality Scorecard: ${t.featureName}`,"","## Test Results","","| Metric | Value |","|--------|-------|",`| Tests Total | ${e.tests_total} |`,`| Tests Passed | ${e.tests_passed} |`,`| Tests Failed | ${e.tests_failed} |`,`| Pass Rate | ${o}% |`,`| Coverage | ${e.coverage_percentage!=null?e.coverage_percentage+"%":"pending"} |`,`| Regressions | ${e.regressions_count} |`,"","## Security","","| Severity | Count |","|----------|-------|",`| Critical | ${e.security_findings.critical} |`,`| Warning | ${e.security_findings.warning} |`,`| Info | ${e.security_findings.info} |`,"","## Unit Completion","","| Metric | Value |","|--------|-------|",`| Units Completed | ${e.units_completed} |`,`| Units Total | ${e.units_total} |`,`| Gate Bypasses | ${e.gate_bypass_count} |`,"","## Methodology Metrics","","| Metric | Value |","|--------|-------|",`| Phases Completed | ${e.phases_completed??0} |`,`| Inception Time | ${e.time_per_phase?.inception_ms??0}ms |`,`| Construction Time | ${e.time_per_phase?.construction_ms??0}ms |`,`| Operations Time | ${e.time_per_phase?.operations_ms??0}ms |`,`| Validation Pass Rate | ${e.validation_pass_rate??0}% |`,`| Rework Count | ${e.rework_count??0} |`,`| Regressions Fixed | ${e.regressions_fixed??0} |`,"","## Recreation Readiness","","| Metric | Value |","|--------|-------|",`| Average Score | ${e.average_recreation_readiness_score!=null?e.average_recreation_readiness_score:"pending"} |`,"","## Data Sources","","| Source | Status |","|--------|--------|",...Object.entries(e.data_sources).map(([i,a])=>`| ${i} | ${a} |`),""].join(`
961
- `);return Vo.mkdirSync(qo.dirname(n),{recursive:!0}),Vo.writeFileSync(n,r+s),n}function zp(e,t){let n=tT(e),r=rT(n,t);return{data:n,reportPath:r}}var er=T(X(),1),Qp=T(require("path"),1),oT=10;function Xp(e,t){let n=`u-${String(t).padStart(3,"0")}`;if(!e||!e.trim())return`${n}-untitled`;let r=e.toLowerCase().replace(/[_\s]+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"");return r?r.length>60?`${n}-${r.substring(0,60).replace(/-$/,"")}`:`${n}-${r}`:`${n}-untitled`}async function na(e){try{if(!await er.default.pathExists(e))return[];let r=(await er.default.readdir(e)).filter(s=>s.startsWith("INTENT-")&&s.endsWith(".md")),o=[];for(let s of r)try{let i=Qp.default.join(e,s),c=(await er.default.readFile(i,"utf-8")).match(/^---\n([\s\S]*?)\n---/);if(!c){console.error(`No frontmatter found in ${s}`);continue}let u=c[1].split(`
962
- `),d={};for(let f of u){let m=f.match(/^(\w+):\s*(.+)$/);if(m){let[,g,y]=m;y.startsWith("[")?d[g]=JSON.parse(y.replace(/'/g,'"')):isNaN(Number(y))?d[g]=y.trim():d[g]=Number(y)}}let p={id:d.id||s.replace(".md",""),type:"intent",title:d.title||"Untitled Intent",parent_id:null,children_ids:[],status:d.status||"pending",assigned_agent:d.assigned_agent||null,estimated_effort:d.estimated_effort||0};o.push(p)}catch(i){console.error(`Failed to parse ${s}:`,i)}return o}catch(t){return console.error(`Failed to read intents from ${e}:`,t),[]}}async function ra(e){try{if(!await er.default.pathExists(e))return null;let n=await er.default.readFile(e,"utf-8"),r=[],o=n.match(/### Proposed UNITs\s*\n([\s\S]*?)(?=\n##[^#]|\n---|\Z|$)/);if(o){let s=o[1],i=/^-\s+\*\*([^*]+)\*\*:\s*(.+)$/gm,a,c=0;for(;(a=i.exec(s))!==null;){let l=a[1].trim(),u=a[2].trim(),d=Xp(l,c+1);r.push({id:d,title:l,description:u}),c++}}return{content:n,proposedUnits:r}}catch(t){return console.error(`Failed to parse intent from ${e}:`,t),null}}function oa(e,t,n=oT){let r=t;r.length>n&&(console.warn(`[decomposition] Unit specs (${r.length}) exceed maxUnits limit (${n}). Truncating to ${n}.`),r=r.slice(0,n));let o=[];for(let s=0;s<r.length;s++){let i=r[s],a=Xp(i.title,s+1),c={id:a,type:"unit",title:i.title,parent_id:e.id,children_ids:[],status:"pending",assigned_agent:null,estimated_effort:i.estimated_effort};o.push(c),e.children_ids.push(a)}return o}function sa(e){let t=new Map;function n(r,o){t.set(r.id,r);for(let s of r.children_ids){let i=o.find(a=>a.id===s);i&&n(i,o)}}for(let r of e)t.set(r.id,r);return{roots:e,nodes:t}}var tr=T(X(),1),nr=T(require("path"),1);function ef(e,t){let n=[],r=1;for(let o of e){let s=on(o.title),i=sT(t,s),a=Zp(i,"input"),c=Zp(i,"output"),l=iT(o,e);n.push({id:`IFACE-${String(r++).padStart(3,"0")}`,unit_id:o.id,name:aT(o.title),inputs:a,outputs:c,dependencies:l,description:`Interface contract for ${o.title}`})}return n}function tf(e,t){let n=[],r=1;for(let o of e){let s=t.filter(c=>c.unit_id===o.id),i=[],a=[];for(let c of s){i.push({id:`COMP-${c.id}`,name:c.name,type:"interface"});for(let l of c.dependencies){let u=t.find(d=>d.id===l);u&&a.push({from:`COMP-${u.id}`,to:`COMP-${c.id}`,data:`Data from ${u.name}`,direction:"unidirectional"})}if(lT(c)){let l=`STORE-${c.id}`;i.push({id:l,name:`${c.name}Store`,type:"store"}),a.push({from:`COMP-${c.id}`,to:l,data:"Persisted data",direction:"bidirectional"})}}n.push({id:`DFD-${String(r++).padStart(3,"0")}`,unit_id:o.id,components:i,flows:a,description:`Data flow diagram for ${o.title}`})}return n}function nf(e,t,n){let r=[],o=1;for(let s of e){let i=t.filter(u=>u.unit_id===s.id),a=n.find(u=>u.unit_id===s.id),c=a?a.components.filter(u=>u.type==="store").map(u=>u.name):[],l=uT(s,i);r.push({id:`COMP-${String(o++).padStart(3,"0")}`,unit_id:s.id,name:cT(s.title),responsibilities:l,interfaces_used:i.map(u=>u.id),data_stores:c,description:`Component design for ${s.title}`})}return r}function ia(e,t){let n=[];for(let a of e.interfaces)a.inputs.length===0&&a.outputs.length===0&&n.push(`Interface ${a.id} (${a.name}) has no inputs or outputs`);for(let a of e.dataFlows){let c=new Set(a.components.map(l=>l.id));for(let l of a.flows)c.has(l.from)||n.push(`DFD ${a.id}: Flow references invalid source component ${l.from}`),c.has(l.to)||n.push(`DFD ${a.id}: Flow references invalid target component ${l.to}`)}let r=new Set(e.interfaces.map(a=>a.id));for(let a of e.components)for(let c of a.interfaces_used)r.has(c)||n.push(`Component ${a.id} (${a.name}) references invalid interface ${c}`);for(let a of e.components)a.responsibilities.length===0&&n.push(`Component ${a.id} (${a.name}) has no defined responsibilities`);let o=dT(t),s=pT(e),i=fT(o,s);return{passed:n.length===0,coverage_percentage:i,blocking_issues:n,reviewer:"design-validator",timestamp:new Date().toISOString()}}async function rf(e,t,n){let r=nr.default.join(e,"aidlc-docs",t,"construction","design");try{await tr.default.ensureDir(r),await tr.default.writeJson(nr.default.join(r,"interfaces.json"),n.interfaces,{spaces:2}),await tr.default.writeJson(nr.default.join(r,"data-flow.json"),n.dataFlows,{spaces:2}),await tr.default.writeJson(nr.default.join(r,"components.json"),n.components,{spaces:2});let o=ia(n,"");await tr.default.writeJson(nr.default.join(r,"validation.json"),o,{spaces:2})}catch(o){throw console.error("Failed to write design artifacts:",o),o}}function on(e){let t=new Set(["the","a","an","and","or","but","in","on","at","to","for"]);return e.toLowerCase().split(/\s+/).filter(n=>n.length>2&&!t.has(n))}function sT(e,t){let n=e.split(`
961
+ `);return Vo.mkdirSync(qo.dirname(n),{recursive:!0}),Vo.writeFileSync(n,r+s),n}function ef(e,t){let n=lb(e),r=db(n,t);return{data:n,reportPath:r}}var er=b(X(),1),tf=b(require("path"),1),pb=10;function nf(e,t){let n=`UNIT-${String(t).padStart(3,"0")}`;if(!e||!e.trim())return`${n}-untitled`;let r=e.toLowerCase().replace(/[_\s]+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"");return r?r.length>60?`${n}-${r.substring(0,60).replace(/-$/,"")}`:`${n}-${r}`:`${n}-untitled`}function oa(e,t){let n=`BOLT-${String(t).padStart(3,"0")}`;if(!e||!e.trim())return`${n}-untitled`;let r=e.toLowerCase().replace(/[_\s]+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"");return r?r.length>60?`${n}-${r.substring(0,60).replace(/-$/,"")}`:`${n}-${r}`:`${n}-untitled`}async function sa(e){try{if(!await er.default.pathExists(e))return[];let r=(await er.default.readdir(e)).filter(s=>s.startsWith("INTENT-")&&s.endsWith(".md")),o=[];for(let s of r)try{let i=tf.default.join(e,s),c=(await er.default.readFile(i,"utf-8")).match(/^---\n([\s\S]*?)\n---/);if(!c){console.error(`No frontmatter found in ${s}`);continue}let u=c[1].split(`
962
+ `),d={};for(let f of u){let m=f.match(/^(\w+):\s*(.+)$/);if(m){let[,g,y]=m;y.startsWith("[")?d[g]=JSON.parse(y.replace(/'/g,'"')):isNaN(Number(y))?d[g]=y.trim():d[g]=Number(y)}}let p={id:d.id||s.replace(".md",""),type:"intent",title:d.title||"Untitled Intent",parent_id:null,children_ids:[],status:d.status||"pending",assigned_agent:d.assigned_agent||null,estimated_effort:d.estimated_effort||0};o.push(p)}catch(i){console.error(`Failed to parse ${s}:`,i)}return o}catch(t){return console.error(`Failed to read intents from ${e}:`,t),[]}}async function ia(e){try{if(!await er.default.pathExists(e))return null;let n=await er.default.readFile(e,"utf-8"),r=[],o=n.match(/### Proposed UNITs\s*\n([\s\S]*?)(?=\n##[^#]|\n---|\Z|$)/);if(o){let s=o[1],i=/^-\s+\*\*([^*]+)\*\*:\s*(.+)$/gm,a,c=0;for(;(a=i.exec(s))!==null;){let l=a[1].trim(),u=a[2].trim(),d=nf(l,c+1);r.push({id:d,title:l,description:u}),c++}}return{content:n,proposedUnits:r}}catch(t){return console.error(`Failed to parse intent from ${e}:`,t),null}}function aa(e,t,n=pb){let r=t;r.length>n&&(console.warn(`[decomposition] Unit specs (${r.length}) exceed maxUnits limit (${n}). Truncating to ${n}.`),r=r.slice(0,n));let o=[];for(let s=0;s<r.length;s++){let i=r[s],a=nf(i.title,s+1),c={id:a,type:"unit",title:i.title,parent_id:e.id,children_ids:[],status:"pending",assigned_agent:null,estimated_effort:i.estimated_effort};o.push(c),e.children_ids.push(a)}return o}function ca(e){let t=new Map;function n(r,o){t.set(r.id,r);for(let s of r.children_ids){let i=o.find(a=>a.id===s);i&&n(i,o)}}for(let r of e)t.set(r.id,r);return{roots:e,nodes:t}}var tr=b(X(),1),nr=b(require("path"),1);function of(e,t){let n=[],r=1;for(let o of e){let s=on(o.title),i=fb(t,s),a=rf(i,"input"),c=rf(i,"output"),l=mb(o,e);n.push({id:`IFACE-${String(r++).padStart(3,"0")}`,unit_id:o.id,name:gb(o.title),inputs:a,outputs:c,dependencies:l,description:`Interface contract for ${o.title}`})}return n}function sf(e,t){let n=[],r=1;for(let o of e){let s=t.filter(c=>c.unit_id===o.id),i=[],a=[];for(let c of s){i.push({id:`COMP-${c.id}`,name:c.name,type:"interface"});for(let l of c.dependencies){let u=t.find(d=>d.id===l);u&&a.push({from:`COMP-${u.id}`,to:`COMP-${c.id}`,data:`Data from ${u.name}`,direction:"unidirectional"})}if(yb(c)){let l=`STORE-${c.id}`;i.push({id:l,name:`${c.name}Store`,type:"store"}),a.push({from:`COMP-${c.id}`,to:l,data:"Persisted data",direction:"bidirectional"})}}n.push({id:`DFD-${String(r++).padStart(3,"0")}`,unit_id:o.id,components:i,flows:a,description:`Data flow diagram for ${o.title}`})}return n}function af(e,t,n){let r=[],o=1;for(let s of e){let i=t.filter(u=>u.unit_id===s.id),a=n.find(u=>u.unit_id===s.id),c=a?a.components.filter(u=>u.type==="store").map(u=>u.name):[],l=wb(s,i);r.push({id:`COMP-${String(o++).padStart(3,"0")}`,unit_id:s.id,name:hb(s.title),responsibilities:l,interfaces_used:i.map(u=>u.id),data_stores:c,description:`Component design for ${s.title}`})}return r}function la(e,t){let n=[];for(let a of e.interfaces)a.inputs.length===0&&a.outputs.length===0&&n.push(`Interface ${a.id} (${a.name}) has no inputs or outputs`);for(let a of e.dataFlows){let c=new Set(a.components.map(l=>l.id));for(let l of a.flows)c.has(l.from)||n.push(`DFD ${a.id}: Flow references invalid source component ${l.from}`),c.has(l.to)||n.push(`DFD ${a.id}: Flow references invalid target component ${l.to}`)}let r=new Set(e.interfaces.map(a=>a.id));for(let a of e.components)for(let c of a.interfaces_used)r.has(c)||n.push(`Component ${a.id} (${a.name}) references invalid interface ${c}`);for(let a of e.components)a.responsibilities.length===0&&n.push(`Component ${a.id} (${a.name}) has no defined responsibilities`);let o=_b(t),s=kb(e),i=Sb(o,s);return{passed:n.length===0,coverage_percentage:i,blocking_issues:n,reviewer:"design-validator",timestamp:new Date().toISOString()}}async function cf(e,t,n){let r=nr.default.join(e,"aidlc-docs",t,"construction","design");try{await tr.default.ensureDir(r),await tr.default.writeJson(nr.default.join(r,"interfaces.json"),n.interfaces,{spaces:2}),await tr.default.writeJson(nr.default.join(r,"data-flow.json"),n.dataFlows,{spaces:2}),await tr.default.writeJson(nr.default.join(r,"components.json"),n.components,{spaces:2});let o=la(n,"");await tr.default.writeJson(nr.default.join(r,"validation.json"),o,{spaces:2})}catch(o){throw console.error("Failed to write design artifacts:",o),o}}function on(e){let t=new Set(["the","a","an","and","or","but","in","on","at","to","for"]);return e.toLowerCase().split(/\s+/).filter(n=>n.length>2&&!t.has(n))}function fb(e,t){let n=e.split(`
963
963
  `),r=[];for(let o of n){let s=o.toLowerCase();t.some(i=>s.includes(i))&&r.push(o)}return r.join(`
964
- `)}function Zp(e,t){let n=[],r=/(\w+):\s*(\w+)/g,o;for(;(o=r.exec(e))!==null;)n.push({name:o[1],type:o[2],required:!0,description:`${t} field ${o[1]}`});return n}function iT(e,t){let n=new Set(on(e.title)),r=[];for(let o of t){if(o.id===e.id)continue;on(o.title).filter(a=>n.has(a)).length>0&&r.push(o.id)}return r}function aT(e){return e.split(/\s+/).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")+"Interface"}function cT(e){return e.split(/\s+/).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")+"Component"}function lT(e){let t=["store","save","persist","database","repository"],n=e.name.toLowerCase();return t.some(r=>n.includes(r))}function uT(e,t){let n=[];n.push(`Implement ${e.title}`);for(let r of t)r.inputs.length>0&&n.push(`Process inputs for ${r.name}`),r.outputs.length>0&&n.push(`Generate outputs for ${r.name}`);return n}function dT(e){return new Set(on(e))}function pT(e){let t=new Set;for(let n of e.interfaces)on(n.name).forEach(r=>t.add(r)),on(n.description).forEach(r=>t.add(r));for(let n of e.components)on(n.name).forEach(r=>t.add(r)),on(n.description).forEach(r=>t.add(r));return t}function fT(e,t){if(e.size===0)return 100;let n=0;for(let r of e)t.has(r)&&n++;return Math.round(n/e.size*100)}var En=require("fs"),aa=require("path"),mT=[1,2,4,8,16];function gT(e){let t=e.match(/^---\n([\s\S]*?)\n---/);if(!t)return null;let n=t[1];try{let r={},o=n.split(`
965
- `);for(let s of o){let i=s.match(/^(\w+):\s*(.+)$/);if(i){let[,a,c]=i;r[a]=c.trim()}}return r}catch{return null}}function hT(e){return e.replace(/^---\n[\s\S]*?\n---\n/,"")}function yT(e){let t=new Map,n=e.split(`
964
+ `)}function rf(e,t){let n=[],r=/(\w+):\s*(\w+)/g,o;for(;(o=r.exec(e))!==null;)n.push({name:o[1],type:o[2],required:!0,description:`${t} field ${o[1]}`});return n}function mb(e,t){let n=new Set(on(e.title)),r=[];for(let o of t){if(o.id===e.id)continue;on(o.title).filter(a=>n.has(a)).length>0&&r.push(o.id)}return r}function gb(e){return e.split(/\s+/).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")+"Interface"}function hb(e){return e.split(/\s+/).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")+"Component"}function yb(e){let t=["store","save","persist","database","repository"],n=e.name.toLowerCase();return t.some(r=>n.includes(r))}function wb(e,t){let n=[];n.push(`Implement ${e.title}`);for(let r of t)r.inputs.length>0&&n.push(`Process inputs for ${r.name}`),r.outputs.length>0&&n.push(`Generate outputs for ${r.name}`);return n}function _b(e){return new Set(on(e))}function kb(e){let t=new Set;for(let n of e.interfaces)on(n.name).forEach(r=>t.add(r)),on(n.description).forEach(r=>t.add(r));for(let n of e.components)on(n.name).forEach(r=>t.add(r)),on(n.description).forEach(r=>t.add(r));return t}function Sb(e,t){if(e.size===0)return 100;let n=0;for(let r of e)t.has(r)&&n++;return Math.round(n/e.size*100)}var Tn=require("fs"),ua=require("path"),vb=[1,2,4,8,16];function bb(e){let t=e.match(/^---\n([\s\S]*?)\n---/);if(!t)return null;let n=t[1];try{let r={},o=n.split(`
965
+ `);for(let s of o){let i=s.match(/^(\w+):\s*(.+)$/);if(i){let[,a,c]=i;r[a]=c.trim()}}return r}catch{return null}}function Tb(e){return e.replace(/^---\n[\s\S]*?\n---\n/,"")}function Eb(e){let t=new Map,n=e.split(`
966
966
  `),r=null,o=[];for(let s of n){let i=s.match(/^##\s+(.+)$/);i?(r&&t.set(r,o.join(`
967
967
  `)),r=i[1].trim(),o=[]):r&&o.push(s)}return r&&t.set(r,o.join(`
968
- `)),t}function wT(e){let t=e.split(`
969
- `),n=0;for(let r of t)r.trim().match(/^[-*+]\s+/)&&n++;return n}function kT(e,t,n){let r=[],o=null,s=gT(e);if(!s)return r.push(`${t}: Missing frontmatter`),{isValid:!1,blockingIssues:r,parentIntent:o};let i=["id","title","parent_intent","status","estimated_effort"],a=[];for(let y of i)s[y]||a.push(y);if(a.length>0)return r.push(`${t}: Missing frontmatter fields: ${a.join(", ")}`),{isValid:!1,blockingIssues:r,parentIntent:o};if(o=s.parent_intent,!n.has(o)&&!o.startsWith("intent-"))return r.push(`${t}: References non-existent parent intent: ${o}`),{isValid:!1,blockingIssues:r,parentIntent:o};let c=parseInt(s.estimated_effort,10);if(isNaN(c)||!mT.includes(c))return r.push(`${t}: Invalid effort estimate ${s.estimated_effort} (must be 1, 2, 4, 8, or 16)`),{isValid:!1,blockingIssues:r,parentIntent:o};let l=hT(e),u=yT(l),d=["Scope & Responsibility","Interface Contracts","Dependencies","Acceptance Criteria"],p=["Goal","Acceptance Criteria","Implementation Notes"],f=d.every(y=>u.has(y)),m=p.every(y=>u.has(y));if(!f&&!m){let y=d.filter(w=>!u.has(w));return r.push(`${t}: Missing sections: ${y.join(", ")}`),{isValid:!1,blockingIssues:r,parentIntent:o}}let g=u.get("Acceptance Criteria");if(g){if(wT(g)===0)return r.push(`${t}: No acceptance criteria found`),{isValid:!1,blockingIssues:r,parentIntent:o}}else return r.push(`${t}: Acceptance Criteria section is empty`),{isValid:!1,blockingIssues:r,parentIntent:o};return{isValid:!0,blockingIssues:r,parentIntent:o}}async function ca(e,t){let n=new Date().toISOString(),r=[],o;try{o=(0,En.readdirSync)(e,{withFileTypes:!0})}catch(m){let g=m;return console.error(`[Validation] Failed to read construction directory: ${g.message}`),console.error(`[Validation] Path: ${e}`),{passed:!1,coverage_percentage:0,blocking_issues:[g.code==="ENOENT"?"Units directory not found":g.code==="EACCES"||g.code==="EPERM"?"Permission denied reading units directory":`Failed to read units directory: ${g.message}`],timestamp:n}}let s=o.filter(m=>m.isDirectory()&&m.name!=="design"),i=o.filter(m=>m.isFile()&&m.name.endsWith(".md")&&m.name!=="design.md"),a=new Set,c=[];for(let m of s){let g=m.name,y=(0,aa.join)(e,m.name,"spec.md");(0,En.existsSync)(y)&&(a.add(g),c.push({unitId:g,filePath:y}))}for(let m of i){let g=m.name.replace(".md","");a.has(g)||(a.add(g),c.push({unitId:g,filePath:(0,aa.join)(e,m.name)}))}if(c.length===0)return{passed:!1,coverage_percentage:0,blocking_issues:["No unit files found in units directory"],timestamp:n};let l=new Set;try{let m=(0,En.readdirSync)(t).filter(g=>g.startsWith("INTENT-")&&g.endsWith(".md"));l=new Set(m.map(g=>g.replace(".md","")))}catch(m){let g=m;return console.error(`[Validation] Failed to read intents directory: ${g.message}`),console.error(`[Validation] Path: ${t}`),{passed:!1,coverage_percentage:0,blocking_issues:[g.code==="ENOENT"?"Intents directory not found":g.code==="EACCES"||g.code==="EPERM"?"Permission denied reading intents directory":`Failed to read intents directory: ${g.message}`],timestamp:n}}let u=new Set,d=0,p=c.length;for(let{unitId:m,filePath:g}of c){let y;try{y=(0,En.readFileSync)(g,"utf-8")}catch(k){let h=k;console.error(`[Validation] Failed to read unit file: ${h.message}`),console.error(`[Validation] Path: ${g}`);let v=h.code==="ENOENT"?`Unit file not found: ${m}`:h.code==="EACCES"||h.code==="EPERM"?`Permission denied reading unit file: ${m}`:`Failed to read unit file ${m}: ${h.message}`;r.push(v);continue}let w=kT(y,m,l);r.push(...w.blockingIssues),w.parentIntent&&l.has(w.parentIntent)&&u.add(w.parentIntent),w.isValid&&d++}for(let m of l)u.has(m)||r.push(`Intent ${m} has no unit children`);let f=Math.round(d/p*100);return{passed:r.length===0&&d===p,coverage_percentage:f,blocking_issues:r,timestamp:n}}Uo();Z();var kb={unit:"olympian","code-generation":"olympian",design:"olympian"},fs=class{projectPath;workflowId;tree=null;currentStage="unit";totalUnits=0;totalCodeGenerations=0;totalEffort=0;constructor(t,n){this.projectPath=t,this.workflowId=n}async execute(t,n={}){let{depth:r="MEDIUM",max_units:o=10,max_code_gen_per_unit:s=8,max_total_code_gen:i=50,checkpointStatus:a,onCheckpointSave:c}=n;if(a==="awaiting_dev_review")return{passed:!1,coverage_percentage:0,blocking_issues:["Construction blocked: developer review of technical specification required (Risk Tier 3)."],reviewer:"construction-executor",timestamp:new Date().toISOString()};if(console.log(`[ConstructionExecutor] Starting Construction phase execution (depth: ${r})`),(n.pathwayType==="brownfield-enhancement"||n.pathwayType==="brownfield-refactor"||n.pathwayType==="bugfix")&&n.testCommand)try{let{captureBaseline:p}=await Promise.resolve().then(()=>(ua(),la));await p(this.projectPath,this.workflowId,n.testCommand),console.log("[ConstructionExecutor] Regression baseline captured")}catch(p){console.error("[ConstructionExecutor] Baseline capture failed (non-fatal):",p)}if(r==="SHALLOW")return this.executeShallow();this.currentStage="unit";let u=await this.executeDecompositionPhase(o,s,i,r);if(!u.passed)return console.error("[ConstructionExecutor] Decomposition phase failed"),u;if(console.log("[ConstructionExecutor] Decomposition phase complete"),c)try{await c()}catch(p){console.error("[ConstructionExecutor] Checkpoint save callback failed:",p)}this.currentStage="design";let d=await this.executeDesignStage(t);return d.passed?(console.log("[ConstructionExecutor] Design stage complete"),{passed:!0,coverage_percentage:100,blocking_issues:[],reviewer:"construction-executor",timestamp:new Date().toISOString()}):(console.error("[ConstructionExecutor] Design stage failed validation"),d)}getProgress(){let t=0,n=0;if(this.tree)for(let i of this.tree.nodes.values())i.type==="unit"&&(t++,i.status==="complete"&&n++);let r=this.totalCodeGenerations,o=0,s=0;return this.currentStage==="unit"?s=t>0?Math.round(n/t*50):0:this.currentStage==="code-generation"?s=50+(r>0?Math.round(o/r*25):0):this.currentStage==="design"&&(s=100),{current_stage:this.currentStage,units_total:t,units_complete:n,code_gen_total:r,code_gen_complete:o,design_complete:this.currentStage==="design",overall_percentage:s}}getDecompositionSummary(){return{units:this.totalUnits,codeGenerations:this.totalCodeGenerations,totalEffort:this.totalEffort}}async executeCodeGenerationWithPlanApproval(t,n={}){let r=n.projectPath||this.projectPath,o=n.workflowId||this.workflowId,{buildCodePlanPath:s,dispatchCodeGeneration:i,buildCodeGenerationPrompt:a}=await Promise.resolve().then(()=>(as(),is)),c=s(r,o,t),l=await i(r,o,t),u=a(l.context.intentSummary2,l.context.intentSummary,l.context.unitSpec,c,l.context.architectureContext);return{status:"awaiting_code_plan_approval",codePlanPath:c,prompt:u}}async approveCodePlan(t,n){let{buildCodePlanPath:r,dispatchCodeGeneration:o,buildCodeGenerationPrompt:s}=await Promise.resolve().then(()=>(as(),is)),{addGateAuditEntry:i}=await Promise.resolve().then(()=>(Z(),vn)),a=r(this.projectPath,this.workflowId,t);if(!await Y.default.pathExists(a))throw new Error(`Code plan file not found at ${a}. The agent must create the plan before it can be approved.`);let l=G.default.join(this.projectPath,"aidlc-docs",this.workflowId,"manifest.json");try{i(l,{phase:"construction",action:"approved",actor:"human",reason:n||`Code plan for ${t} approved by developer`})}catch(p){console.error(`[ConstructionExecutor] Failed to record gate audit for ${t}:`,p)}let u=await o(this.projectPath,this.workflowId,t);return{status:"executing_code_plan",prompt:s(u.context.intentSummary2,u.context.intentSummary,u.context.unitSpec,void 0,u.context.architectureContext)}}async autoApproveCodePlan(t,n){let{addGateAuditEntry:r}=await Promise.resolve().then(()=>(Z(),vn)),o=G.default.join(this.projectPath,"aidlc-docs",this.workflowId,"manifest.json"),s=n>=3;try{r(o,{phase:"construction",action:"approved",actor:"trust",reason:s?`Code plan for ${t} auto-approved silently (trust level ${n})`:`Code plan for ${t} auto-approved with notification (trust level ${n})`})}catch(u){console.error(`[ConstructionExecutor] Failed to record gate audit for ${t}:`,u)}s||console.log(`[ConstructionExecutor] Code plan for ${t} auto-approved (trust level ${n})`);let{dispatchCodeGeneration:i,buildCodeGenerationPrompt:a}=await Promise.resolve().then(()=>(as(),is)),c=await i(this.projectPath,this.workflowId,t);return{status:"executing_code_plan",prompt:a(c.context.intentSummary2,c.context.intentSummary,c.context.unitSpec,void 0,c.context.architectureContext)}}async executeTestGeneration(t,n={}){let r=n.projectPath||this.projectPath,o=n.workflowId||this.workflowId,i=await I(r,o)??{schema_version:"3.0.0",workflow_id:o,feature_name:"",current_phase:"construction",current_stage:"code-generation",status:"in_progress",phases:{},manifest_path:"",trust_state_path:"",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),construction_units:{}};i.construction_units||(i.construction_units={});let a=i.construction_units[t]??{unitId:t,stages:{"functional-design":{status:"not_started",artifact_path:null,completed_at:null},"nfr-requirements":{status:"not_started",artifact_path:null,completed_at:null},"nfr-design":{status:"not_started",artifact_path:null,completed_at:null},"infrastructure-design":{status:"not_started",artifact_path:null,completed_at:null},"code-generation":{status:"not_started",artifact_path:null,completed_at:null},"test-generation":{status:"not_started",artifact_path:null,completed_at:null}},code_plan_path:null,code_generation_status:"not_started",tests_total:0,tests_passed:0,tests_failed:0,test_framework:"unknown",test_generation_status:"not_started"};a.stages["test-generation"].status="in_progress",a.test_generation_status="in_progress",i.construction_units[t]=a,await O(r,i);let c=G.default.join(r,"aidlc-docs",o,"construction",t,"testing");await Y.default.ensureDir(c);let l=G.default.join(c,"test-report.md"),u="",d=G.default.join(r,"aidlc-docs",o,"construction",t,"code","code-summary.md");try{await Y.default.pathExists(d)&&(u=await Y.default.readFile(d,"utf-8"))}catch{}let p=await this.detectTestFramework(r),f=new Date().toISOString(),m=this.buildTestReportScaffold(t,p,u,f);await Y.default.writeFile(l,m,"utf-8");let g=0,y=0,w=0,k=0,h=0;n.currentResults&&n.currentResults.length>0&&(g=n.currentResults.length,y=n.currentResults.filter(C=>C.status==="passed").length,w=n.currentResults.filter(C=>C.status==="failed").length);let v=!1,S=0,b=G.default.join(r,"aidlc-docs",o,"construction","regression-baseline.json");if(n.currentResults&&w>0&&await Y.default.pathExists(b))try{let{compareAgainstBaseline:C,writeRegressionReport:$}=await Promise.resolve().then(()=>(ua(),la)),{categorizeFailure:N,buildRegressionSummary:x}=await Promise.resolve().then(()=>(nm(),tm)),E=await Y.default.readJson(b);v=!0;let M=C(E,n.currentResults),F=[],K=[];for(let $e of M.new_failures){let Dr=E.tests.find(Jt=>Jt.name===$e.name)??null,Ke=N($e.name,Dr,[]);F.push(Ke),K.push({test_name:$e.name,file_path:$e.filePath,category:Ke,rationale:Ke==="legitimate_regression"?"Test was passing in baseline, now fails":Ke==="flaky"?"Test passed on re-run without code changes":Ke==="intentional_change"?"New test not present in baseline":"Test was already failing in baseline"})}let V=x(K.map($e=>({test_name:$e.test_name,file_path:$e.file_path})),F);k=V.regressions_count,h=V.flaky_count,S=V.regressions_count;let hn={workflow_id:o,unit_id:t,baseline_captured_at:E.captured_at,compared_at:new Date().toISOString(),failures:K,total_regressions:F.filter($e=>$e!=="pre_existing_failure").length,legitimate_regressions:V.regressions_count};await $(r,o,t,hn)}catch(C){console.error(`[ConstructionExecutor] Regression analysis failed for ${t} (non-fatal):`,C)}let _="completed",j;if(n.allowFailures!==!0&&(g===0?(_="blocked",j=`No tests detected for unit ${t}. Set allowFailures: true to override.`):v&&S>0?(_="blocked",j=`${S} legitimate regression(s) for unit ${t}. Flaky: ${h} (non-blocking). Fix regressions before proceeding.`):!v&&w>0&&(_="blocked",j=`${w} test(s) failed for unit ${t}. Set allowFailures: true to override.`)),a.stages["test-generation"].status=_==="completed"?"completed":"in_progress",a.stages["test-generation"].artifact_path=l,_==="completed"&&(a.stages["test-generation"].completed_at=f),a.tests_total=g,a.tests_passed=y,a.tests_failed=w,a.test_framework=p,a.test_generation_status=_==="completed"?"completed":"in_progress",a.regressions_count=k,a.flaky_count=h,i.construction_units[t]=a,await O(r,i),_==="completed")try{let{updateArchitectureModel:C}=await Promise.resolve().then(()=>(Jr(),Jo)),$=await this.discoverUnitFiles(r,o,t);$.length>0&&(await C(r,$),a.architecture_model_status="updated",i.construction_units[t]=a,await O(r,i))}catch(C){console.error(`[ConstructionExecutor] Architecture model update failed for ${t} (non-blocking):`,C),a.architecture_model_status="failed",i.construction_units[t]=a;try{await O(r,i)}catch{}}let R;if(_==="completed")try{let{runValidationPipeline:C,shouldSkipValidator:$,updateCheckpointForValidator:N,createQualityValidator:x,createMutationValidator:E,createTraceabilityValidator:M,createContractValidator:F,createCoverageValidator:K}=await Promise.resolve().then(()=>(Em(),Tm)),V=await this.discoverUnitFiles(r,o,t),hn=this.detectApiSurfaceFiles(V),$e=this.deriveWorkflowDepth(i),Dr={timeoutBudgetMs:3e4,allowFailures:n.allowFailures??!1,workflowDepth:$e,unitId:t,unitFiles:V,apiSurfaceFiles:hn,projectPath:r,workflowId:o},Ke=new Map;Ke.set("quality",x()),$("mutation",Dr).skip||Ke.set("mutation",E()),Ke.set("traceability",M()),$("contract",Dr).skip||Ke.set("contract",F()),Ke.set("coverage",K()),R=await C(Ke,Dr);for(let{validator:Jt,result:Ot}of R.results){let mk=Ot.status==="passed"||Ot.status==="warned"?"completed":Ot.status==="skipped"?"skipped":"in_progress",gk=Jt==="coverage"?Ot.coverage_percentage:void 0,hk=Jt==="coverage"?Ot.findings.filter(yk=>yk.category==="uncovered-critical-file").length:void 0;await N(r,o,t,Jt,mk,gk,hk)}if(!n.allowFailures){let Jt=R.results.filter(Ot=>Ot.result.status==="failed");Jt.length>0&&(_="blocked",j=`Validation blocked: ${Jt.map(Ot=>Ot.validator).join(", ")}`,a.stages["test-generation"].status="in_progress",a.test_generation_status="in_progress",i.construction_units[t]=a,await O(r,i))}}catch(C){console.error(`[ConstructionExecutor] Validation pipeline failed for ${t} (non-fatal):`,C)}return{status:_,unitId:t,tests_total:g,tests_passed:y,tests_failed:w,test_framework:p,reportPath:l,blockingReason:j,regressions_count:k,flaky_count:h,validationPipeline:R}}async validateBugfixTestRequirement(t,n={}){try{let r=n.projectPath||this.projectPath,o=n.workflowId||this.workflowId,s=await I(r,o);if(!s)return{valid:!1,reason:"checkpoint not found"};if(s.pathway_type!=="bugfix")return{valid:!0};let i=s.construction_units?.[t];return i?i.stages?.["test-generation"]?.status!=="completed"?{valid:!1,reason:"test-generation stage not completed for bugfix unit"}:(i.tests_total??0)===0?{valid:!1,reason:"bugfix unit must have at least one test (tests_total === 0)"}:{valid:!0}:{valid:!1,reason:`no unit progress found for unit ${t}`}}catch(r){let o=r instanceof Error?r.message:String(r);return console.error(`[ConstructionExecutor] validateBugfixTestRequirement error for ${t}:`,r),{valid:!1,reason:`validation error: ${o}`}}}async executeDocumentationGeneration(t,n={}){let r=n.projectPath||this.projectPath,o=n.workflowId||this.workflowId,s=await I(r,o),i=s?.depth_score?s.depth_score<=12?"minimal":s.depth_score<=20?"standard":"comprehensive":"standard",a=s?.pathway_type||"brownfield-enhancement",c=await this.discoverUnitFiles(r,o,t),l={unitId:t,workflowId:o,projectPath:r,depth:i,pathway:a,unitFiles:c},u=Gp(l),d,p=0,f=[],m;if(u.status==="completed"){try{let g=Wp({projectPath:r,workflowId:o,unitId:t,modifiedFiles:l.unitFiles||[]});d={status:g.impactScan.status,path:g.impactScan.reportPath},p=g.adrCount,g.adrEntries&&(f=g.adrEntries)}catch{}if(u.path&&a!=="bugfix"&&i!=="minimal")try{let g=s?.construction_units?.[t];m=zi({featureDocPath:u.path,projectPath:r,depth:i,pathway:a,override:g?.recreation_readiness_override,overrideRationale:g?.recreation_readiness_override_rationale??void 0})}catch{}}if(s?.construction_units?.[t]){let g=s.construction_units[t];g.feature_doc_status=u.status==="completed"?"completed":"not_started",g.feature_doc_path=u.path,g.impact_scan_status=d?.status==="completed"?"completed":"not_started",g.impact_scan_report_path=d?.path??null,g.adr_count=p,g.adr_entries=f.length>0?f:void 0,m&&(g.recreation_readiness_score=m.overall_score,g.recreation_readiness_dimensions=m.dimensions??null),u.status==="completed"&&(g.doc_generation_agent=kb["code-generation"],g.doc_generation_prompt=Up(l)),await O(r,s)}return{featureDoc:u,impactScan:d,adrCount:p,recreationReadiness:m}}async executeUnitCompletion(t,n={}){let r=n.projectPath||this.projectPath,o=n.workflowId||this.workflowId,s=await this.executeTestGeneration(t,n);if(s.status==="completed"){try{let i=await this.discoverUnitFiles(r,o,t);i.length>0&&Bp(r,i)}catch(i){console.error(`[ConstructionExecutor] Secrets management failed for ${t} (non-blocking):`,i)}try{let i=await this.discoverUnitFiles(r,o,t),a=await Jp({projectPath:r,workflowId:o,unitId:t,includeGlobs:i.length>0?i:void 0}),c=await I(r,o);if(c?.construction_units?.[t]){let l=c.construction_units[t];l.security_scan_status=a.status==="completed"?"completed":a.status==="failed"?"in_progress":"not_started",l.security_findings_critical=a.findings.filter(u=>u.severity==="critical").length,l.security_findings_warning=a.findings.filter(u=>u.severity==="warning").length,l.security_findings_info=a.findings.filter(u=>u.severity==="info").length,await O(r,c)}}catch(i){console.error(`[ConstructionExecutor] Security scan failed for ${t} (non-blocking):`,i)}if(!n.skipDocumentation){let i=await this.executeDocumentationGeneration(t,{projectPath:r,workflowId:o});return{testGeneration:s,documentation:i}}}return{testGeneration:s}}async executeSmokeTest(t={}){let n=t.projectPath||this.projectPath,r=t.workflowId||this.workflowId,o=await I(n,r);if(!o||!o.construction_units)return{status:"not_run",reportPath:null};let s=o.construction_units,i=Object.keys(s);if(i.length===0)return{status:"not_run",reportPath:null};let a=0,c=0,l=0,u=0,d=0,p=0,f=0,m=0,g=[];for(let b of i){let _=s[b],j=_.tests_total??0,R=_.tests_passed??0,A=_.tests_failed??0,C=j-R-A,$=_.regressions_count??0,N=_.flaky_count??0;j>0&&(f++,A===0&&m++),a+=j,c+=R,l+=A,u+=Math.max(0,C),d+=$,p+=N;let x=j===0?"\u26A0\uFE0F":A===0?"\u2705":"\u274C";g.push(`| ${b} | ${j} | ${R} | ${A} | ${$} | ${N} | ${x} |`)}let y=a===0?"not_run":l===0?"passed":"failed",w=G.default.join(n,"aidlc-docs",r,"construction","build-and-test");await Y.default.ensureDir(w);let k=G.default.join(w,"test-report.md"),h=new Date().toISOString(),v=`# Build-Level Test Report
968
+ `)),t}function Cb(e){let t=e.split(`
969
+ `),n=0;for(let r of t)r.trim().match(/^[-*+]\s+/)&&n++;return n}function Rb(e,t,n){let r=[],o=null,s=bb(e);if(!s)return r.push(`${t}: Missing frontmatter`),{isValid:!1,blockingIssues:r,parentIntent:o};let i=["id","title","parent_intent","status","estimated_effort"],a=[];for(let y of i)s[y]||a.push(y);if(a.length>0)return r.push(`${t}: Missing frontmatter fields: ${a.join(", ")}`),{isValid:!1,blockingIssues:r,parentIntent:o};if(o=s.parent_intent,!n.has(o)&&!o.startsWith("intent-"))return r.push(`${t}: References non-existent parent intent: ${o}`),{isValid:!1,blockingIssues:r,parentIntent:o};let c=parseInt(s.estimated_effort,10);if(isNaN(c)||!vb.includes(c))return r.push(`${t}: Invalid effort estimate ${s.estimated_effort} (must be 1, 2, 4, 8, or 16)`),{isValid:!1,blockingIssues:r,parentIntent:o};let l=Tb(e),u=Eb(l),d=["Scope & Responsibility","Interface Contracts","Dependencies","Acceptance Criteria"],p=["Goal","Acceptance Criteria","Implementation Notes"],f=d.every(y=>u.has(y)),m=p.every(y=>u.has(y));if(!f&&!m){let y=d.filter(w=>!u.has(w));return r.push(`${t}: Missing sections: ${y.join(", ")}`),{isValid:!1,blockingIssues:r,parentIntent:o}}let g=u.get("Acceptance Criteria");if(g){if(Cb(g)===0)return r.push(`${t}: No acceptance criteria found`),{isValid:!1,blockingIssues:r,parentIntent:o}}else return r.push(`${t}: Acceptance Criteria section is empty`),{isValid:!1,blockingIssues:r,parentIntent:o};return{isValid:!0,blockingIssues:r,parentIntent:o}}async function da(e,t){let n=new Date().toISOString(),r=[],o;try{o=(0,Tn.readdirSync)(e,{withFileTypes:!0})}catch(m){let g=m;return console.error(`[Validation] Failed to read construction directory: ${g.message}`),console.error(`[Validation] Path: ${e}`),{passed:!1,coverage_percentage:0,blocking_issues:[g.code==="ENOENT"?"Units directory not found":g.code==="EACCES"||g.code==="EPERM"?"Permission denied reading units directory":`Failed to read units directory: ${g.message}`],timestamp:n}}let s=o.filter(m=>m.isDirectory()&&m.name!=="design"),i=o.filter(m=>m.isFile()&&m.name.endsWith(".md")&&m.name!=="design.md"),a=new Set,c=[];for(let m of s){let g=m.name,y=(0,ua.join)(e,m.name,"spec.md");(0,Tn.existsSync)(y)&&(a.add(g),c.push({unitId:g,filePath:y}))}for(let m of i){let g=m.name.replace(".md","");a.has(g)||(a.add(g),c.push({unitId:g,filePath:(0,ua.join)(e,m.name)}))}if(c.length===0)return{passed:!1,coverage_percentage:0,blocking_issues:["No unit files found in units directory"],timestamp:n};let l=new Set;try{let m=(0,Tn.readdirSync)(t).filter(g=>g.startsWith("INTENT-")&&g.endsWith(".md"));l=new Set(m.map(g=>g.replace(".md","")))}catch(m){let g=m;return console.error(`[Validation] Failed to read intents directory: ${g.message}`),console.error(`[Validation] Path: ${t}`),{passed:!1,coverage_percentage:0,blocking_issues:[g.code==="ENOENT"?"Intents directory not found":g.code==="EACCES"||g.code==="EPERM"?"Permission denied reading intents directory":`Failed to read intents directory: ${g.message}`],timestamp:n}}let u=new Set,d=0,p=c.length;for(let{unitId:m,filePath:g}of c){let y;try{y=(0,Tn.readFileSync)(g,"utf-8")}catch(_){let h=_;console.error(`[Validation] Failed to read unit file: ${h.message}`),console.error(`[Validation] Path: ${g}`);let v=h.code==="ENOENT"?`Unit file not found: ${m}`:h.code==="EACCES"||h.code==="EPERM"?`Permission denied reading unit file: ${m}`:`Failed to read unit file ${m}: ${h.message}`;r.push(v);continue}let w=Rb(y,m,l);r.push(...w.blockingIssues),w.parentIntent&&l.has(w.parentIntent)&&u.add(w.parentIntent),w.isValid&&d++}for(let m of l)u.has(m)||r.push(`Intent ${m} has no unit children`);let f=Math.round(d/p*100);return{passed:r.length===0&&d===p,coverage_percentage:f,blocking_issues:r,timestamp:n}}Uo();Z();function lf(e,t,n){let o=(n.construction_bolts?Object.keys(n.construction_bolts).length:0)+1,s=oa(e.title,o),i=e,a=Array.isArray(i.acceptance_criteria)&&i.acceptance_criteria.length>0?i.acceptance_criteria:["Implement as described in intent"],c=Array.isArray(i.target_files)?i.target_files:[];return{id:s,type:"bolt",title:e.title,parent_id:e.id,children_ids:[],status:"pending",assigned_agent:null,estimated_effort:e.estimated_effort,parent_unit_id:e.id,sequence:1,scope:t.substring(0,500)||e.title,acceptance_criteria:a,target_files:c,dependencies:[],depth_target:1,express_mode:!0,estimated_effort_hours:e.estimated_effort}}var xb=b(require("path"),1);function Yo(){return{status:"not_started",started_at:null,completed_at:null,failure_count:0,last_error:null,artifact_path:null}}function uf(e,t){t.construction_bolts||(t.construction_bolts={});for(let n of e){let r={bolt_id:n.id,parent_unit_id:n.parent_unit_id,status:"planned",stages:{elaboration:Yo(),code_generation:Yo(),build_and_test:Yo(),review:Yo()},failure_count:0,last_error:null,review_score:null,acknowledged_by:null,acknowledged_at:null};t.construction_bolts[n.id]=r}}le();var Pb=["elaboration","code_generation","build_and_test","review"],Ab={elaboration:"onElaboration",code_generation:"onCodeGeneration",build_and_test:"onBuildAndTest",review:"onReview"},Ib={build_and_test:"built",review:"done"};async function Ob(e,t,n,r){let o=Ab[t];return t==="build_and_test"?e.onBuildAndTest(n,r,n.target_files??[]):e[o](n,r)}async function $b(e,t,n,r,o){let s=t.construction_bolts[e.id];t.active_bolt_id=e.id,s.status="in_progress",await A(n,t);for(let i of Pb){let a=s.stages[i];if(e.express_mode&&i==="elaboration"){a.status="skipped",a.completed_at=new Date().toISOString(),await A(n,t);continue}i==="review"&&(s.status="in_review",await A(n,t)),t.active_bolt_stage=i,a.status="in_progress",a.started_at=new Date().toISOString(),await A(n,t);let c=await Ob(o,i,e,n);if(c.success){a.status="completed",a.completed_at=new Date().toISOString(),c.artifact_path&&(a.artifact_path=c.artifact_path);let l=Ib[i];l&&(s.status=l),await A(n,t)}else{if(a.failure_count+=1,a.last_error=c.error??"Unknown error",s.failure_count+=1,s.last_error=a.last_error,a.failure_count>=2){a.status="failed",s.status="failed",await A(n,t);break}a.status="not_started",await A(n,t);break}}return t.active_bolt_id=null,t.active_bolt_stage=null,await A(n,t),{status:s.status,stages:{...s.stages}}}var df={execute:$b};ga();var LE={unit:"olympian","code-generation":"olympian",design:"olympian"},ys=class{projectPath;workflowId;tree=null;currentStage="unit";totalUnits=0;totalCodeGenerations=0;totalEffort=0;constructor(t,n){this.projectPath=t,this.workflowId=n}async execute(t,n={}){let{depth:r="MEDIUM",max_units:o=10,max_code_gen_per_unit:s=8,max_total_code_gen:i=50,checkpointStatus:a,onCheckpointSave:c}=n;if(a==="awaiting_dev_review")return{passed:!1,coverage_percentage:0,blocking_issues:["Construction blocked: developer review of technical specification required (Risk Tier 3)."],reviewer:"construction-executor",timestamp:new Date().toISOString()};if(console.log(`[ConstructionExecutor] Starting Construction phase execution (depth: ${r})`),(n.pathwayType==="brownfield-enhancement"||n.pathwayType==="brownfield-refactor"||n.pathwayType==="bugfix")&&n.testCommand)try{let{captureBaseline:p}=await Promise.resolve().then(()=>(ya(),ha));await p(this.projectPath,this.workflowId,n.testCommand),console.log("[ConstructionExecutor] Regression baseline captured")}catch(p){console.error("[ConstructionExecutor] Baseline capture failed (non-fatal):",p)}if(r==="SHALLOW")return this.executeShallowViaBolt();this.currentStage="unit";let u=await this.executeDecompositionPhase(o,s,i,r);if(!u.passed)return console.error("[ConstructionExecutor] Decomposition phase failed"),u;if(console.log("[ConstructionExecutor] Decomposition phase complete"),c)try{await c()}catch(p){console.error("[ConstructionExecutor] Checkpoint save callback failed:",p)}this.currentStage="design";let d=await this.executeDesignStage(t);return d.passed?(console.log("[ConstructionExecutor] Design stage complete"),{passed:!0,coverage_percentage:100,blocking_issues:[],reviewer:"construction-executor",timestamp:new Date().toISOString()}):(console.error("[ConstructionExecutor] Design stage failed validation"),d)}getProgress(){let t=0,n=0;if(this.tree)for(let i of this.tree.nodes.values())i.type==="unit"&&(t++,i.status==="complete"&&n++);let r=this.totalCodeGenerations,o=0,s=0;return this.currentStage==="unit"?s=t>0?Math.round(n/t*50):0:this.currentStage==="code-generation"?s=50+(r>0?Math.round(o/r*25):0):this.currentStage==="design"&&(s=100),{current_stage:this.currentStage,units_total:t,units_complete:n,code_gen_total:r,code_gen_complete:o,design_complete:this.currentStage==="design",overall_percentage:s}}getDecompositionSummary(){return{units:this.totalUnits,codeGenerations:this.totalCodeGenerations,totalEffort:this.totalEffort}}async handleZeroBoltUnit(t,n={}){let r=n.projectPath||this.projectPath,o=n.workflowId||this.workflowId,s=await I(r,o);return!s||Object.values(s.construction_bolts??{}).filter(a=>a.parent_unit_id===t).length>0?!1:(s.construction_units||(s.construction_units={}),s.construction_units[t]&&(s.construction_units[t].code_generation_status="completed"),zo(r,o,{timestamp:new Date().toISOString(),phase:"construction",action:`Unit ${t} auto-fulfilled (zero bolts)`,actor:"construction-executor",reason:null}),await A(r,s),console.log(`[ConstructionExecutor] Unit ${t} auto-fulfilled: 0 bolts registered`),!0)}async executeCodeGenerationWithPlanApproval(t,n={}){let r=n.projectPath||this.projectPath,o=n.workflowId||this.workflowId,{buildCodePlanPath:s,dispatchCodeGeneration:i,buildCodeGenerationPrompt:a}=await Promise.resolve().then(()=>(ds(),us)),c=s(r,o,t),l=await i(r,o,t),u=a(l.context.intentSummary2,l.context.intentSummary,l.context.unitSpec,c,l.context.architectureContext);return{status:"awaiting_code_plan_approval",codePlanPath:c,prompt:u}}async approveCodePlan(t,n){let{buildCodePlanPath:r,dispatchCodeGeneration:o,buildCodeGenerationPrompt:s}=await Promise.resolve().then(()=>(ds(),us)),{addGateAuditEntry:i}=await Promise.resolve().then(()=>(Z(),vn)),a=r(this.projectPath,this.workflowId,t);if(!await Y.default.pathExists(a))throw new Error(`Code plan file not found at ${a}. The agent must create the plan before it can be approved.`);let l=H.default.join(this.projectPath,"aidlc-docs",this.workflowId,"manifest.json");try{i(l,{phase:"construction",action:"approved",actor:"human",reason:n||`Code plan for ${t} approved by developer`})}catch(p){console.error(`[ConstructionExecutor] Failed to record gate audit for ${t}:`,p)}let u=await o(this.projectPath,this.workflowId,t);return{status:"executing_code_plan",prompt:s(u.context.intentSummary2,u.context.intentSummary,u.context.unitSpec,void 0,u.context.architectureContext)}}async autoApproveCodePlan(t,n){let{addGateAuditEntry:r}=await Promise.resolve().then(()=>(Z(),vn)),o=H.default.join(this.projectPath,"aidlc-docs",this.workflowId,"manifest.json"),s=n>=3;try{r(o,{phase:"construction",action:"approved",actor:"trust",reason:s?`Code plan for ${t} auto-approved silently (trust level ${n})`:`Code plan for ${t} auto-approved with notification (trust level ${n})`})}catch(u){console.error(`[ConstructionExecutor] Failed to record gate audit for ${t}:`,u)}s||console.log(`[ConstructionExecutor] Code plan for ${t} auto-approved (trust level ${n})`);let{dispatchCodeGeneration:i,buildCodeGenerationPrompt:a}=await Promise.resolve().then(()=>(ds(),us)),c=await i(this.projectPath,this.workflowId,t);return{status:"executing_code_plan",prompt:a(c.context.intentSummary2,c.context.intentSummary,c.context.unitSpec,void 0,c.context.architectureContext)}}async executeTestGeneration(t,n={}){let r=n.projectPath||this.projectPath,o=n.workflowId||this.workflowId,i=await I(r,o)??{schema_version:"3.0.0",workflow_id:o,feature_name:"",current_phase:"construction",current_stage:"code-generation",status:"in_progress",phases:{},manifest_path:"",trust_state_path:"",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),construction_units:{}};i.construction_units||(i.construction_units={});let a=i.construction_units[t]??{unitId:t,stages:{"functional-design":{status:"not_started",artifact_path:null,completed_at:null,failure_count:0,last_error:null},"nfr-requirements":{status:"not_started",artifact_path:null,completed_at:null,failure_count:0,last_error:null},"nfr-design":{status:"not_started",artifact_path:null,completed_at:null,failure_count:0,last_error:null},"infrastructure-design":{status:"not_started",artifact_path:null,completed_at:null,failure_count:0,last_error:null},"code-generation":{status:"not_started",artifact_path:null,completed_at:null,failure_count:0,last_error:null},"test-generation":{status:"not_started",artifact_path:null,completed_at:null,failure_count:0,last_error:null}},code_plan_path:null,code_generation_status:"not_started",tests_total:0,tests_passed:0,tests_failed:0,test_framework:"unknown",test_generation_status:"not_started"};a.stages["test-generation"].status="in_progress",a.test_generation_status="in_progress",i.construction_units[t]=a,await A(r,i);let c=H.default.join(r,"aidlc-docs",o,"construction",t,"testing");await Y.default.ensureDir(c);let l=H.default.join(c,"test-report.md"),u="",d=H.default.join(r,"aidlc-docs",o,"construction",t,"code","code-summary.md");try{await Y.default.pathExists(d)&&(u=await Y.default.readFile(d,"utf-8"))}catch{}let p=await this.detectTestFramework(r),f=new Date().toISOString(),m=this.buildTestReportScaffold(t,p,u,f);await Y.default.writeFile(l,m,"utf-8");let g=0,y=0,w=0,_=0,h=0;n.currentResults&&n.currentResults.length>0&&(g=n.currentResults.length,y=n.currentResults.filter(C=>C.status==="passed").length,w=n.currentResults.filter(C=>C.status==="failed").length);let v=!1,S=0,E=H.default.join(r,"aidlc-docs",o,"construction","regression-baseline.json");if(n.currentResults&&w>0&&await Y.default.pathExists(E))try{let{compareAgainstBaseline:C,writeRegressionReport:$}=await Promise.resolve().then(()=>(ya(),ha)),{categorizeFailure:N,buildRegressionSummary:x}=await Promise.resolve().then(()=>(Sm(),km)),T=await Y.default.readJson(E);v=!0;let M=C(T,n.currentResults),F=[],K=[];for(let $e of M.new_failures){let Dr=T.tests.find(Jt=>Jt.name===$e.name)??null,Ke=N($e.name,Dr,[]);F.push(Ke),K.push({test_name:$e.name,file_path:$e.filePath,category:Ke,rationale:Ke==="legitimate_regression"?"Test was passing in baseline, now fails":Ke==="flaky"?"Test passed on re-run without code changes":Ke==="intentional_change"?"New test not present in baseline":"Test was already failing in baseline"})}let V=x(K.map($e=>({test_name:$e.test_name,file_path:$e.file_path})),F);_=V.regressions_count,h=V.flaky_count,S=V.regressions_count;let hn={workflow_id:o,unit_id:t,baseline_captured_at:T.captured_at,compared_at:new Date().toISOString(),failures:K,total_regressions:F.filter($e=>$e!=="pre_existing_failure").length,legitimate_regressions:V.regressions_count};await $(r,o,t,hn)}catch(C){console.error(`[ConstructionExecutor] Regression analysis failed for ${t} (non-fatal):`,C)}let k="completed",j;if(n.allowFailures!==!0&&(g===0?(k="blocked",j=`No tests detected for unit ${t}. Set allowFailures: true to override.`):v&&S>0?(k="blocked",j=`${S} legitimate regression(s) for unit ${t}. Flaky: ${h} (non-blocking). Fix regressions before proceeding.`):!v&&w>0&&(k="blocked",j=`${w} test(s) failed for unit ${t}. Set allowFailures: true to override.`)),a.stages["test-generation"].status=k==="completed"?"completed":"in_progress",a.stages["test-generation"].artifact_path=l,k==="completed"&&(a.stages["test-generation"].completed_at=f),a.tests_total=g,a.tests_passed=y,a.tests_failed=w,a.test_framework=p,a.test_generation_status=k==="completed"?"completed":"in_progress",a.regressions_count=_,a.flaky_count=h,i.construction_units[t]=a,await A(r,i),k==="completed")try{let{updateArchitectureModel:C}=await Promise.resolve().then(()=>(Jr(),Zo)),$=await this.discoverUnitFiles(r,o,t);$.length>0&&(await C(r,$),a.architecture_model_status="updated",i.construction_units[t]=a,await A(r,i))}catch(C){console.error(`[ConstructionExecutor] Architecture model update failed for ${t} (non-blocking):`,C),a.architecture_model_status="failed",i.construction_units[t]=a;try{await A(r,i)}catch{}}let R;if(k==="completed")try{let{runValidationPipeline:C,shouldSkipValidator:$,updateCheckpointForValidator:N,createQualityValidator:x,createMutationValidator:T,createTraceabilityValidator:M,createContractValidator:F,createCoverageValidator:K}=await Promise.resolve().then(()=>(Gm(),Bm)),V=await this.discoverUnitFiles(r,o,t),hn=this.detectApiSurfaceFiles(V),$e=this.deriveWorkflowDepth(i),Dr={timeoutBudgetMs:3e4,allowFailures:n.allowFailures??!1,workflowDepth:$e,unitId:t,unitFiles:V,apiSurfaceFiles:hn,projectPath:r,workflowId:o},Ke=new Map;Ke.set("quality",x()),$("mutation",Dr).skip||Ke.set("mutation",T()),Ke.set("traceability",M()),$("contract",Dr).skip||Ke.set("contract",F()),Ke.set("coverage",K()),R=await C(Ke,Dr);for(let{validator:Jt,result:Ot}of R.results){let __=Ot.status==="passed"||Ot.status==="warned"?"completed":Ot.status==="skipped"?"skipped":"in_progress",k_=Jt==="coverage"?Ot.coverage_percentage:void 0,S_=Jt==="coverage"?Ot.findings.filter(v_=>v_.category==="uncovered-critical-file").length:void 0;await N(r,o,t,Jt,__,k_,S_)}if(!n.allowFailures){let Jt=R.results.filter(Ot=>Ot.result.status==="failed");Jt.length>0&&(k="blocked",j=`Validation blocked: ${Jt.map(Ot=>Ot.validator).join(", ")}`,a.stages["test-generation"].status="in_progress",a.test_generation_status="in_progress",i.construction_units[t]=a,await A(r,i))}}catch(C){console.error(`[ConstructionExecutor] Validation pipeline failed for ${t} (non-fatal):`,C)}return{status:k,unitId:t,tests_total:g,tests_passed:y,tests_failed:w,test_framework:p,reportPath:l,blockingReason:j,regressions_count:_,flaky_count:h,validationPipeline:R}}async validateBugfixTestRequirement(t,n={}){try{let r=n.projectPath||this.projectPath,o=n.workflowId||this.workflowId,s=await I(r,o);if(!s)return{valid:!1,reason:"checkpoint not found"};if(s.pathway_type!=="bugfix")return{valid:!0};let i=s.construction_units?.[t];return i?i.stages?.["test-generation"]?.status!=="completed"?{valid:!1,reason:"test-generation stage not completed for bugfix unit"}:(i.tests_total??0)===0?{valid:!1,reason:"bugfix unit must have at least one test (tests_total === 0)"}:{valid:!0}:{valid:!1,reason:`no unit progress found for unit ${t}`}}catch(r){let o=r instanceof Error?r.message:String(r);return console.error(`[ConstructionExecutor] validateBugfixTestRequirement error for ${t}:`,r),{valid:!1,reason:`validation error: ${o}`}}}async executeDocumentationGeneration(t,n={}){let r=n.projectPath||this.projectPath,o=n.workflowId||this.workflowId,s=await I(r,o),i=s?.depth_score?s.depth_score<=12?"minimal":s.depth_score<=20?"standard":"comprehensive":"standard",a=s?.pathway_type||"brownfield-enhancement",c=await this.discoverUnitFiles(r,o,t),l={unitId:t,workflowId:o,projectPath:r,depth:i,pathway:a,unitFiles:c},u=qp(l),d,p=0,f=[],m;if(u.status==="completed"){try{let g=Vp({projectPath:r,workflowId:o,unitId:t,modifiedFiles:l.unitFiles||[]});d={status:g.impactScan.status,path:g.impactScan.reportPath},p=g.adrCount,g.adrEntries&&(f=g.adrEntries)}catch{}if(u.path&&a!=="bugfix"&&i!=="minimal")try{let g=s?.construction_units?.[t];m=Xi({featureDocPath:u.path,projectPath:r,depth:i,pathway:a,override:g?.recreation_readiness_override,overrideRationale:g?.recreation_readiness_override_rationale??void 0})}catch{}}if(s?.construction_units?.[t]){let g=s.construction_units[t];g.feature_doc_status=u.status==="completed"?"completed":"not_started",g.feature_doc_path=u.path,g.impact_scan_status=d?.status==="completed"?"completed":"not_started",g.impact_scan_report_path=d?.path??null,g.adr_count=p,g.adr_entries=f.length>0?f:void 0,m&&(g.recreation_readiness_score=m.overall_score,g.recreation_readiness_dimensions=m.dimensions??null),u.status==="completed"&&(g.doc_generation_agent=LE["code-generation"],g.doc_generation_prompt=Hp(l)),await A(r,s)}return{featureDoc:u,impactScan:d,adrCount:p,recreationReadiness:m}}async executeUnitCompletion(t,n={}){let r=n.projectPath||this.projectPath,o=n.workflowId||this.workflowId,s=await this.executeTestGeneration(t,n);if(s.status==="completed"){try{let i=await this.discoverUnitFiles(r,o,t);i.length>0&&Yp(r,i)}catch(i){console.error(`[ConstructionExecutor] Secrets management failed for ${t} (non-blocking):`,i)}try{let i=await this.discoverUnitFiles(r,o,t),a=await Zp({projectPath:r,workflowId:o,unitId:t,includeGlobs:i.length>0?i:void 0}),c=await I(r,o);if(c?.construction_units?.[t]){let l=c.construction_units[t];l.security_scan_status=a.status==="completed"?"completed":a.status==="failed"?"in_progress":"not_started",l.security_findings_critical=a.findings.filter(u=>u.severity==="critical").length,l.security_findings_warning=a.findings.filter(u=>u.severity==="warning").length,l.security_findings_info=a.findings.filter(u=>u.severity==="info").length,await A(r,c)}}catch(i){console.error(`[ConstructionExecutor] Security scan failed for ${t} (non-blocking):`,i)}if(!n.skipDocumentation){let i=await this.executeDocumentationGeneration(t,{projectPath:r,workflowId:o});return{testGeneration:s,documentation:i}}}return{testGeneration:s}}async executeSmokeTest(t={}){let n=t.projectPath||this.projectPath,r=t.workflowId||this.workflowId,o=await I(n,r);if(!o||!o.construction_units)return{status:"not_run",reportPath:null};let s=o.construction_units,i=Object.keys(s);if(i.length===0)return{status:"not_run",reportPath:null};let a=0,c=0,l=0,u=0,d=0,p=0,f=0,m=0,g=[];for(let E of i){let k=s[E],j=k.tests_total??0,R=k.tests_passed??0,O=k.tests_failed??0,C=j-R-O,$=k.regressions_count??0,N=k.flaky_count??0;j>0&&(f++,O===0&&m++),a+=j,c+=R,l+=O,u+=Math.max(0,C),d+=$,p+=N;let x=j===0?"\u26A0\uFE0F":O===0?"\u2705":"\u274C";g.push(`| ${E} | ${j} | ${R} | ${O} | ${$} | ${N} | ${x} |`)}let y=a===0?"not_run":l===0?"passed":"failed",w=H.default.join(n,"aidlc-docs",r,"construction","build-and-test");await Y.default.ensureDir(w);let _=H.default.join(w,"test-report.md"),h=new Date().toISOString(),v=`# Build-Level Test Report
970
970
 
971
971
  **Workflow ID**: ${r}
972
972
  **Generated At**: ${h}
@@ -991,7 +991,7 @@ Do not use placeholder text \u2014 write real documentation.`}function Fv(e,t){l
991
991
  |------|-------|--------|--------|-------------|-------|--------|
992
992
  ${g.join(`
993
993
  `)}
994
- `;await Y.default.writeFile(k,v,"utf-8");try{let b=[],_=0,j=0,R=0;for(let N of i){let x=s[N],E=x.coverage_percentage??null,M=x.critical_gap_count??0;j+=M,E!==null&&(_+=E,R++);let F=E===null?"N/A":E>=90?"Exemplary":E>=75?"Commendable":E>=60?"Acceptable":"Below threshold";b.push(`| ${N} | ${E!==null?E+"%":"N/A"} | ${M} | ${F} |`)}let A=R>0?Math.round(_/R*10)/10:null,C=`# Workflow Coverage Report
994
+ `;await Y.default.writeFile(_,v,"utf-8");try{let E=[],k=0,j=0,R=0;for(let N of i){let x=s[N],T=x.coverage_percentage??null,M=x.critical_gap_count??0;j+=M,T!==null&&(k+=T,R++);let F=T===null?"N/A":T>=90?"Exemplary":T>=75?"Commendable":T>=60?"Acceptable":"Below threshold";E.push(`| ${N} | ${T!==null?T+"%":"N/A"} | ${M} | ${F} |`)}let O=R>0?Math.round(k/R*10)/10:null,C=`# Workflow Coverage Report
995
995
 
996
996
  **Workflow ID**: ${r}
997
997
  **Generated At**: ${h}
@@ -1000,7 +1000,7 @@ ${g.join(`
1000
1000
 
1001
1001
  | Metric | Value |
1002
1002
  |--------|-------|
1003
- | Average Coverage | ${A!==null?A+"%":"N/A"} |
1003
+ | Average Coverage | ${O!==null?O+"%":"N/A"} |
1004
1004
  | Critical Gaps (total) | ${j} |
1005
1005
  | Units with Coverage Data | ${R} / ${i.length} |
1006
1006
 
@@ -1008,9 +1008,9 @@ ${g.join(`
1008
1008
 
1009
1009
  | Unit | Coverage | Critical Gaps | Tier |
1010
1010
  |------|----------|---------------|------|
1011
- ${b.join(`
1011
+ ${E.join(`
1012
1012
  `)}
1013
- `,$=G.default.join(w,"coverage-report.md");await Y.default.writeFile($,C,"utf-8")}catch(b){console.error("[ConstructionExecutor] Workflow-level coverage report failed (non-fatal):",b)}let S={status:y,tests_total:a,tests_passed:c,tests_failed:l,tests_skipped:u,regressions_total:d,flaky_total:p,units_tested:f,units_passed:m,report_path:k,completed_at:h};o.smoke_test=S,o.updated_at=h,await O(n,o);try{let{generateChangelogEntry:b}=await Promise.resolve().then(()=>(Dm(),$m)),_=Object.keys(s);b({projectPath:n,workflowId:r,featureName:o.feature_name??r,unitIds:_,pathway:o.pathway_type??void 0})}catch(b){console.error("[ConstructionExecutor] Changelog generation failed (non-fatal):",b)}try{let b=await I(n,r);b&&zp(b,{projectPath:n,workflowId:r,featureName:b.feature_name??r})}catch(b){console.error("[ConstructionExecutor] Quality scorecard generation failed (non-fatal):",b)}return{status:y,reportPath:k}}async captureBugDescription(t,n){try{let r=n?.projectPath||this.projectPath,o=n?.workflowId||this.workflowId,i=await I(r,o)??{schema_version:"3.0.0",workflow_id:o,feature_name:"",current_phase:"construction",current_stage:"code-generation",status:"in_progress",phases:{},manifest_path:"",trust_state_path:"",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),construction_units:{}};i.bug_description=t,i.updated_at=new Date().toISOString(),await O(r,i)}catch(r){console.error("[ConstructionExecutor] captureBugDescription error:",r)}}async discoverUnitFiles(t,n,r){let o=G.default.join(t,"aidlc-docs",n,"construction",r,"code","code-summary.md");try{if(!await Y.default.pathExists(o))return[];let s=await Y.default.readFile(o,"utf-8"),i=[],a=[/[`|]\s*([\w/.\\-]+\.\w{1,5})\s*[`|]/g,/^[-*]\s+`?([\w/.\\-]+\.\w{1,5})`?\s*$/gm];for(let c of a){let l;for(;(l=c.exec(s))!==null;){let u=l[1];i.includes(u)||i.push(u)}}return i}catch{return[]}}detectApiSurfaceFiles(t){let n=[/route/i,/controller/i,/handler/i,/endpoint/i,/api\//i,/server/i,/middleware/i,/graphql/i];return t.filter(r=>n.some(o=>o.test(r)))}deriveWorkflowDepth(t){return t.pathway_type==="bugfix"?0:(t.depth_score??3)<=2?1:2}async detectTestFramework(t){let n=G.default.join(t,"package.json");try{if(!await Y.default.pathExists(n))return"unknown";let r=await Y.default.readFile(n,"utf-8"),o=JSON.parse(r),s={...o.dependencies,...o.devDependencies};return s.vitest?"vitest":s.jest?"jest":s.mocha?"mocha":"unknown"}catch{return"unknown"}}buildTestReportScaffold(t,n,r,o){let s="_No code-summary.md found \u2014 files in scope unknown._";if(r){let i=r.match(/## Files (?:created|modified|created\/modified)[^\n]*\n([\s\S]*?)(?=\n##|$)/i);i&&i[1].trim()&&(s=i[1].trim())}return`---
1013
+ `,$=H.default.join(w,"coverage-report.md");await Y.default.writeFile($,C,"utf-8")}catch(E){console.error("[ConstructionExecutor] Workflow-level coverage report failed (non-fatal):",E)}let S={status:y,tests_total:a,tests_passed:c,tests_failed:l,tests_skipped:u,regressions_total:d,flaky_total:p,units_tested:f,units_passed:m,report_path:_,completed_at:h};o.smoke_test=S,o.updated_at=h,await A(n,o);try{let{generateChangelogEntry:E}=await Promise.resolve().then(()=>(Zm(),Xm)),k=Object.keys(s);E({projectPath:n,workflowId:r,featureName:o.feature_name??r,unitIds:k,pathway:o.pathway_type??void 0})}catch(E){console.error("[ConstructionExecutor] Changelog generation failed (non-fatal):",E)}try{let E=await I(n,r);E&&ef(E,{projectPath:n,workflowId:r,featureName:E.feature_name??r})}catch(E){console.error("[ConstructionExecutor] Quality scorecard generation failed (non-fatal):",E)}return{status:y,reportPath:_}}async captureBugDescription(t,n){try{let r=n?.projectPath||this.projectPath,o=n?.workflowId||this.workflowId,i=await I(r,o)??{schema_version:"3.0.0",workflow_id:o,feature_name:"",current_phase:"construction",current_stage:"code-generation",status:"in_progress",phases:{},manifest_path:"",trust_state_path:"",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),construction_units:{}};i.bug_description=t,i.updated_at=new Date().toISOString(),await A(r,i)}catch(r){console.error("[ConstructionExecutor] captureBugDescription error:",r)}}async discoverUnitFiles(t,n,r){let o=H.default.join(t,"aidlc-docs",n,"construction",r,"code","code-summary.md");try{if(!await Y.default.pathExists(o))return[];let s=await Y.default.readFile(o,"utf-8"),i=[],a=[/[`|]\s*([\w/.\\-]+\.\w{1,5})\s*[`|]/g,/^[-*]\s+`?([\w/.\\-]+\.\w{1,5})`?\s*$/gm];for(let c of a){let l;for(;(l=c.exec(s))!==null;){let u=l[1];i.includes(u)||i.push(u)}}return i}catch{return[]}}detectApiSurfaceFiles(t){let n=[/route/i,/controller/i,/handler/i,/endpoint/i,/api\//i,/server/i,/middleware/i,/graphql/i];return t.filter(r=>n.some(o=>o.test(r)))}deriveWorkflowDepth(t){return t.pathway_type==="bugfix"?0:(t.depth_score??3)<=2?1:2}async detectTestFramework(t){let n=H.default.join(t,"package.json");try{if(!await Y.default.pathExists(n))return"unknown";let r=await Y.default.readFile(n,"utf-8"),o=JSON.parse(r),s={...o.dependencies,...o.devDependencies};return s.vitest?"vitest":s.jest?"jest":s.mocha?"mocha":"unknown"}catch{return"unknown"}}buildTestReportScaffold(t,n,r,o){let s="_No code-summary.md found \u2014 files in scope unknown._";if(r){let i=r.match(/## Files (?:created|modified|created\/modified)[^\n]*\n([\s\S]*?)(?=\n##|$)/i);i&&i[1].trim()&&(s=i[1].trim())}return`---
1014
1014
  unit_id: ${t}
1015
1015
  framework: ${n}
1016
1016
  generated_at: ${o}
@@ -1043,7 +1043,7 @@ _No failures recorded._
1043
1043
  ## Override
1044
1044
 
1045
1045
  _allowFailures was not set._
1046
- `}async executeShallow(){let t=G.default.join(this.projectPath,"aidlc-docs",this.workflowId,"inception","intent.md"),n=G.default.join(this.projectPath,"aidlc-docs",this.workflowId,"construction"),r="Shallow Implementation",o=2,s="",i=await ra(t);if(i){s=i.content;let d=s.match(/^title:\s*(.+)$/m);d&&(r=d[1].trim().replace(/^["']|["']$/g,""));let p=s.match(/^estimated_effort:\s*(\d+)/m);p&&(o=Number(p[1]))}else{let d=G.default.join(this.projectPath,"aidlc-docs",this.workflowId,"inception"),p=await na(d);if(p.length===0)return{passed:!1,coverage_percentage:0,blocking_issues:["No intent found for SHALLOW construction"],reviewer:"construction-executor",timestamp:new Date().toISOString()};r=p[0].title,o=p[0].estimated_effort}await Y.default.ensureDir(n);let a="shallow-impl",c=G.default.join(n,a);await Y.default.ensureDir(c);let l=new Date().toISOString(),u=this.formatUnitMarkdown({id:a,type:"unit",title:r,parent_id:null,children_ids:[],status:"pending",assigned_agent:null,estimated_effort:o},"none",s);await Y.default.writeFile(G.default.join(c,"spec.md"),u,"utf-8"),this.registerConstructionArtifact(a,"unit","unit",G.default.join(c,"spec.md")),this.totalCodeGenerations=1,this.totalEffort=o,console.log("[ConstructionExecutor] SHALLOW mode: created single unit for code generation from INTENT");try{await this.executeTestGeneration("shallow-impl")}catch(d){console.error("[ConstructionExecutor] Test generation failed for shallow-impl:",d)}return{passed:!0,coverage_percentage:100,blocking_issues:[],reviewer:"construction-executor",timestamp:l}}async executeDecompositionPhase(t,n,r,o="MEDIUM"){let s=G.default.join(this.projectPath,"aidlc-docs",this.workflowId,"inception"),i=G.default.join(this.projectPath,"aidlc-docs",this.workflowId,"construction");await Y.default.ensureDir(i);let a=G.default.join(s,"intent.md"),c=await ra(a),l=G.default.join(s,"intent.md"),u="";try{await Y.default.pathExists(l)&&(u=await Y.default.readFile(l,"utf-8"))}catch{}return c?this.executeDecompositionFromIntent(c,s,i,t,n,r,u,o):this.executeDecompositionFromLegacyIntents(s,i,t,n,r,u)}async executeDecompositionFromIntent(t,n,r,o,s,i,a,c="MEDIUM"){let l=t.content,u=l.match(/^title:\s*(.+)$/m),d=l.match(/^estimated_effort:\s*(\d+)/m),p=u?u[1].trim().replace(/^["']|["']$/g,""):"Untitled Intent",f=d?Number(d[1]):0,m="INTENT-001",g={id:m,type:"intent",title:p,parent_id:null,children_ids:[],status:"pending",assigned_agent:null,estimated_effort:f},y=`---
1046
+ `}async executeShallowViaBolt(){let t=H.default.join(this.projectPath,"aidlc-docs",this.workflowId,"inception","intent.md"),n="Shallow Implementation",r=2,o="",s=await ia(t);if(s){o=s.content;let d=o.match(/^title:\s*(.+)$/m);d&&(n=d[1].trim().replace(/^["']|["']$/g,""));let p=o.match(/^estimated_effort:\s*(\d+)/m);p&&(r=Number(p[1]))}else{let d=H.default.join(this.projectPath,"aidlc-docs",this.workflowId,"inception"),p=await sa(d);if(p.length===0)return{passed:!1,coverage_percentage:0,blocking_issues:["No intent found for SHALLOW construction"],reviewer:"construction-executor",timestamp:new Date().toISOString()};n=p[0].title,r=p[0].estimated_effort}let i={id:"shallow-impl",type:"unit",title:n,parent_id:null,children_ids:[],status:"pending",assigned_agent:null,estimated_effort:r},a=await I(this.projectPath,this.workflowId);if(!a)return{passed:!1,coverage_percentage:0,blocking_issues:["No checkpoint found for SHALLOW construction"],reviewer:"construction-executor",timestamp:new Date().toISOString()};let c=lf(i,o,a);uf([c],a);let l={onElaboration:async()=>({success:!0}),onCodeGeneration:async()=>({success:!0}),onBuildAndTest:async()=>({success:!0}),onReview:async()=>({success:!0})},u=await df.execute(c,a,this.projectPath,this.workflowId,l);return console.log(`[ConstructionExecutor] SHALLOW express bolt completed with status: ${u.status}`),{passed:u.status==="done",coverage_percentage:u.status==="done"?100:0,blocking_issues:u.status==="done"?[]:[`Express bolt failed with status: ${u.status}`],reviewer:"construction-executor",timestamp:new Date().toISOString()}}async executeDecompositionPhase(t,n,r,o="MEDIUM"){let s=H.default.join(this.projectPath,"aidlc-docs",this.workflowId,"inception"),i=H.default.join(this.projectPath,"aidlc-docs",this.workflowId,"construction");await Y.default.ensureDir(i);let a=H.default.join(s,"intent.md"),c=await ia(a),l=H.default.join(s,"intent.md"),u="";try{await Y.default.pathExists(l)&&(u=await Y.default.readFile(l,"utf-8"))}catch{}return c?this.executeDecompositionFromIntent(c,s,i,t,n,r,u,o):this.executeDecompositionFromLegacyIntents(s,i,t,n,r,u)}async executeDecompositionFromIntent(t,n,r,o,s,i,a,c="MEDIUM"){let l=t.content,u=l.match(/^title:\s*(.+)$/m),d=l.match(/^estimated_effort:\s*(\d+)/m),p=u?u[1].trim().replace(/^["']|["']$/g,""):"Untitled Intent",f=d?Number(d[1]):0,m="INTENT-001",g={id:m,type:"intent",title:p,parent_id:null,children_ids:[],status:"pending",assigned_agent:null,estimated_effort:f},y=`---
1047
1047
  id: ${m}
1048
1048
  title: ${p}
1049
1049
  status: pending
@@ -1067,7 +1067,7 @@ Auto-generated
1067
1067
 
1068
1068
  ## Technical Notes
1069
1069
  Generated from inception/intent.md
1070
- `;await Y.default.writeFile(G.default.join(n,`${m}.md`),y,"utf-8");let w=t.proposedUnits.map(S=>({title:S.title,estimated_effort:Math.ceil(f/Math.max(t.proposedUnits.length,1)),description:S.description}));w.length===0&&w.push({title:p,estimated_effort:f,description:`Implementation unit for ${p}`});let k=oa(g,w,o),h=[];for(let S of k){let b=G.default.join(r,S.id);await Y.default.ensureDir(b);let _=this.formatUnitMarkdown(S,g.id,l);await Y.default.writeFile(G.default.join(b,"spec.md"),_,"utf-8"),await Y.default.writeFile(G.default.join(r,`${S.id}.md`),_,"utf-8"),this.registerConstructionArtifact(S.id,"unit","unit",G.default.join(b,"spec.md")),this.linkConstructionArtifacts(m,S.id,"derives"),this.runUnitValidation(_,l,a,g.id,S.id);try{let{UnitStageRunner:j}=await Promise.resolve().then(()=>(Mm(),jm));await new j(this.projectPath,this.workflowId).executeForUnit(S.id,c,a)}catch(j){console.error(`[ConstructionExecutor] Unit stage runner failed for ${S.id}:`,j)}}this.tree=sa([g]);for(let S of k)this.tree.nodes.set(S.id,S);this.totalUnits=k.length,this.totalCodeGenerations=k.length,this.totalEffort=k.reduce((S,b)=>S+b.estimated_effort,0),console.log(`[ConstructionExecutor] Created ${k.length} units for code generation`);let v=await ca(r,n);return v.passed?h.length>0?{passed:!1,coverage_percentage:0,blocking_issues:h,reviewer:"construction-executor",timestamp:new Date().toISOString()}:{passed:!0,coverage_percentage:100,blocking_issues:[],reviewer:"construction-executor",timestamp:new Date().toISOString()}:v}async executeDecompositionFromLegacyIntents(t,n,r,o,s,i){let a=await na(t);if(a.length===0)return{passed:!1,coverage_percentage:0,blocking_issues:["No intents found in Inception phase"],reviewer:"construction-executor",timestamp:new Date().toISOString()};console.log(`[ConstructionExecutor] Found ${a.length} intents to decompose (legacy mode)`);let c="";try{let f=(await Y.default.readdir(t)).find(m=>m.startsWith("INTENT-")&&m.endsWith(".md"));f&&(c=await Y.default.readFile(G.default.join(t,f),"utf-8"))}catch{}let l=[],u=[];for(let p of a){let f=[{title:p.title,estimated_effort:p.estimated_effort,description:`Implementation unit for ${p.title}`}],m=oa(p,f,r);l.push(...m);for(let g of m){let y=G.default.join(n,`${g.id}.md`),w=this.formatUnitMarkdown(g,p.id);await Y.default.writeFile(y,w,"utf-8");let k=G.default.join(n,g.id);await Y.default.ensureDir(k),await Y.default.writeFile(G.default.join(k,"spec.md"),w,"utf-8"),this.registerConstructionArtifact(g.id,"unit","unit",G.default.join(k,"spec.md")),this.linkConstructionArtifacts(p.id,g.id,"derives"),this.runUnitValidation(w,c,i,p.id,g.id)}}console.log(`[ConstructionExecutor] Created ${l.length} units for code generation`),this.tree=sa(a);for(let p of l)this.tree.nodes.set(p.id,p);this.totalUnits=l.length,this.totalCodeGenerations=l.length,this.totalEffort=l.reduce((p,f)=>p+f.estimated_effort,0);let d=await ca(n,t);return d.passed?u.length>0?{passed:!1,coverage_percentage:0,blocking_issues:u,reviewer:"construction-executor",timestamp:new Date().toISOString()}:{passed:!0,coverage_percentage:100,blocking_issues:[],reviewer:"construction-executor",timestamp:new Date().toISOString()}:d}async executeDesignStage(t){let n=G.default.join(this.projectPath,"aidlc-docs",this.workflowId,"construction"),r=await Y.default.readdir(n,{withFileTypes:!0}),o=[];for(let l of r)if(l.isDirectory()&&l.name!=="design"){let u=G.default.join(n,l.name,"spec.md");if(await Y.default.pathExists(u)){let d=await Y.default.readFile(u,"utf-8"),p=this.parseUnitFromMarkdown(d,l.name);p&&o.push(p)}}else if(l.isFile()&&l.name.endsWith(".md")&&l.name!=="design"){let u=G.default.join(n,l.name),d=await Y.default.readFile(u,"utf-8"),p=this.parseUnitFromMarkdown(d,l.name.replace(".md",""));p&&o.push(p)}if(o.length===0)return{passed:!1,coverage_percentage:0,blocking_issues:["No units found to generate design artifacts"],reviewer:"construction-executor",timestamp:new Date().toISOString()};console.log(`[ConstructionExecutor] Generating design artifacts for ${o.length} units`);let s=ef(o,t||""),i=tf(o,s),a=nf(o,s,i);await rf(this.projectPath,this.workflowId,{interfaces:s,dataFlows:i,components:a});let c=G.default.join(this.projectPath,"aidlc-docs",this.workflowId,"construction","design");return this.registerConstructionArtifact("design-interfaces","interface-contracts","unit",G.default.join(c,"interfaces.json")),this.registerConstructionArtifact("design-data-flow","data-flow-diagram","unit",G.default.join(c,"data-flow.json")),this.registerConstructionArtifact("design-components","component-design","unit",G.default.join(c,"components.json")),t?ia({interfaces:s,dataFlows:i,components:a},t):{passed:!0,coverage_percentage:100,blocking_issues:[],reviewer:"construction-executor",timestamp:new Date().toISOString()}}runUnitValidation(t,n,r,o,s){if(!(!n||!r))try{let i=Qn(t,n,r,"intent-to-unit","unit-to-intent",o,s,`intent-${this.workflowId}`);i.passed||console.warn(`[ConstructionExecutor] Dual validation warning for ${s}: parent=${i.parentCheck.alignment_passed}, root=${i.rootCheck.alignment_passed}`)}catch(i){console.error(`[ConstructionExecutor] Dual validation error for ${s}:`,i)}}registerConstructionArtifact(t,n,r,o){try{let s=G.default.join(this.projectPath,"aidlc-docs",this.workflowId,"manifest.json");Ne(s,{id:t,type:n,phase:"construction",stage:r,path:o,validation_passed:null,write_complete:!0,checksum:null})}catch(s){console.error(`[ConstructionExecutor] Failed to register artifact ${t}:`,s)}}linkConstructionArtifacts(t,n,r){try{let o=G.default.join(this.projectPath,"aidlc-docs",this.workflowId,"manifest.json");Hi(o,{source_id:t,target_id:n,link_type:r})}catch(o){console.error(`[ConstructionExecutor] Failed to link ${t} -> ${n}:`,o)}}formatUnitMarkdown(t,n,r){let o=new Date().toISOString();return`---
1070
+ `;await Y.default.writeFile(H.default.join(n,`${m}.md`),y,"utf-8");let w=t.proposedUnits.map(S=>({title:S.title,estimated_effort:Math.ceil(f/Math.max(t.proposedUnits.length,1)),description:S.description}));w.length===0&&w.push({title:p,estimated_effort:f,description:`Implementation unit for ${p}`});let _=aa(g,w,o),h=[];for(let S of _){let E=H.default.join(r,S.id);await Y.default.ensureDir(E);let k=this.formatUnitMarkdown(S,g.id,l);await Y.default.writeFile(H.default.join(E,"spec.md"),k,"utf-8"),await Y.default.writeFile(H.default.join(r,`${S.id}.md`),k,"utf-8"),this.registerConstructionArtifact(S.id,"unit","unit",H.default.join(E,"spec.md")),this.linkConstructionArtifacts(m,S.id,"derives"),this.runUnitValidation(k,l,a,g.id,S.id);try{let{UnitStageRunner:j}=await Promise.resolve().then(()=>(rg(),ng));await new j(this.projectPath,this.workflowId).executeForUnit(S.id,c,a)}catch(j){console.error(`[ConstructionExecutor] Unit stage runner failed for ${S.id}:`,j)}}this.tree=ca([g]);for(let S of _)this.tree.nodes.set(S.id,S);this.totalUnits=_.length,this.totalCodeGenerations=_.length,this.totalEffort=_.reduce((S,E)=>S+E.estimated_effort,0),console.log(`[ConstructionExecutor] Created ${_.length} units for code generation`);let v=await da(r,n);return v.passed?h.length>0?{passed:!1,coverage_percentage:0,blocking_issues:h,reviewer:"construction-executor",timestamp:new Date().toISOString()}:{passed:!0,coverage_percentage:100,blocking_issues:[],reviewer:"construction-executor",timestamp:new Date().toISOString()}:v}async executeDecompositionFromLegacyIntents(t,n,r,o,s,i){let a=await sa(t);if(a.length===0)return{passed:!1,coverage_percentage:0,blocking_issues:["No intents found in Inception phase"],reviewer:"construction-executor",timestamp:new Date().toISOString()};console.log(`[ConstructionExecutor] Found ${a.length} intents to decompose (legacy mode)`);let c="";try{let f=(await Y.default.readdir(t)).find(m=>m.startsWith("INTENT-")&&m.endsWith(".md"));f&&(c=await Y.default.readFile(H.default.join(t,f),"utf-8"))}catch{}let l=[],u=[];for(let p of a){let f=[{title:p.title,estimated_effort:p.estimated_effort,description:`Implementation unit for ${p.title}`}],m=aa(p,f,r);l.push(...m);for(let g of m){let y=H.default.join(n,`${g.id}.md`),w=this.formatUnitMarkdown(g,p.id);await Y.default.writeFile(y,w,"utf-8");let _=H.default.join(n,g.id);await Y.default.ensureDir(_),await Y.default.writeFile(H.default.join(_,"spec.md"),w,"utf-8"),this.registerConstructionArtifact(g.id,"unit","unit",H.default.join(_,"spec.md")),this.linkConstructionArtifacts(p.id,g.id,"derives"),this.runUnitValidation(w,c,i,p.id,g.id)}}console.log(`[ConstructionExecutor] Created ${l.length} units for code generation`),this.tree=ca(a);for(let p of l)this.tree.nodes.set(p.id,p);this.totalUnits=l.length,this.totalCodeGenerations=l.length,this.totalEffort=l.reduce((p,f)=>p+f.estimated_effort,0);let d=await da(n,t);return d.passed?u.length>0?{passed:!1,coverage_percentage:0,blocking_issues:u,reviewer:"construction-executor",timestamp:new Date().toISOString()}:{passed:!0,coverage_percentage:100,blocking_issues:[],reviewer:"construction-executor",timestamp:new Date().toISOString()}:d}async executeDesignStage(t){let n=H.default.join(this.projectPath,"aidlc-docs",this.workflowId,"construction"),r=await Y.default.readdir(n,{withFileTypes:!0}),o=[];for(let l of r)if(l.isDirectory()&&l.name!=="design"){let u=H.default.join(n,l.name,"spec.md");if(await Y.default.pathExists(u)){let d=await Y.default.readFile(u,"utf-8"),p=this.parseUnitFromMarkdown(d,l.name);p&&o.push(p)}}else if(l.isFile()&&l.name.endsWith(".md")&&l.name!=="design"){let u=H.default.join(n,l.name),d=await Y.default.readFile(u,"utf-8"),p=this.parseUnitFromMarkdown(d,l.name.replace(".md",""));p&&o.push(p)}if(o.length===0)return{passed:!1,coverage_percentage:0,blocking_issues:["No units found to generate design artifacts"],reviewer:"construction-executor",timestamp:new Date().toISOString()};console.log(`[ConstructionExecutor] Generating design artifacts for ${o.length} units`);let s=of(o,t||""),i=sf(o,s),a=af(o,s,i);await cf(this.projectPath,this.workflowId,{interfaces:s,dataFlows:i,components:a});let c=H.default.join(this.projectPath,"aidlc-docs",this.workflowId,"construction","design");return this.registerConstructionArtifact("design-interfaces","interface-contracts","unit",H.default.join(c,"interfaces.json")),this.registerConstructionArtifact("design-data-flow","data-flow-diagram","unit",H.default.join(c,"data-flow.json")),this.registerConstructionArtifact("design-components","component-design","unit",H.default.join(c,"components.json")),t?la({interfaces:s,dataFlows:i,components:a},t):{passed:!0,coverage_percentage:100,blocking_issues:[],reviewer:"construction-executor",timestamp:new Date().toISOString()}}runUnitValidation(t,n,r,o,s){if(!(!n||!r))try{let i=Qn(t,n,r,"intent-to-unit","unit-to-intent",o,s,`intent-${this.workflowId}`);i.passed||console.warn(`[ConstructionExecutor] Dual validation warning for ${s}: parent=${i.parentCheck.alignment_passed}, root=${i.rootCheck.alignment_passed}`)}catch(i){console.error(`[ConstructionExecutor] Dual validation error for ${s}:`,i)}}registerConstructionArtifact(t,n,r,o){try{let s=H.default.join(this.projectPath,"aidlc-docs",this.workflowId,"manifest.json");Ne(s,{id:t,type:n,phase:"construction",stage:r,path:o,validation_passed:null,write_complete:!0,checksum:null})}catch(s){console.error(`[ConstructionExecutor] Failed to register artifact ${t}:`,s)}}linkConstructionArtifacts(t,n,r){try{let o=H.default.join(this.projectPath,"aidlc-docs",this.workflowId,"manifest.json");qi(o,{source_id:t,target_id:n,link_type:r})}catch(o){console.error(`[ConstructionExecutor] Failed to link ${t} -> ${n}:`,o)}}formatUnitMarkdown(t,n,r){let o=new Date().toISOString();return`---
1071
1071
  id: ${t.id}
1072
1072
  title: ${t.title}
1073
1073
  parent_intent: ${n}
@@ -1118,16 +1118,16 @@ Implementation details for ${t.title}.
1118
1118
  - Parent INTENT: ${n} (inception/intent.md)
1119
1119
  - Root INTENT: intent-${this.workflowId} (inception/intent.md)
1120
1120
  `}parseUnitFromMarkdown(t,n){try{let r=t.match(/^---\n([\s\S]*?)\n---/);if(!r)return null;let s=r[1].split(`
1121
- `),i={};for(let a of s){let c=a.match(/^(\w+):\s*(.+)$/);if(c){let[,l,u]=c,d=u.trim().replace(/^["']|["']$/g,"");isNaN(Number(d))?i[l]=d:i[l]=Number(d)}}return{id:n,type:"unit",title:i.title||"Untitled Unit",parent_id:i.parent_intent||null,children_ids:[],status:i.status||"pending",assigned_agent:i.assigned_agent||null,estimated_effort:i.estimated_effort||0}}catch(r){return console.error("Failed to parse unit from markdown:",r),null}}};Xo();var Lm=require("crypto"),_b={gate_rejection:"gotcha",gate_approval:"pattern",build_failure:"technical_insight",rework_required:"gotcha",contract_violation:"gotcha",trust_level_change:"planning_insight",phase_complete:"pattern",depth_override:"planning_insight",bolt_execution_complete:"workflow_gate",gate_approval_after_rejection:"workflow_gate",depth_assessment_complete:"planning_insight",execution_mode_selected:"planning_insight",retro_completed:"retro_insight"};function Ve(e,t){let n=_b[e.type],r=e.timestamp??new Date().toISOString(),o=Sb(e.type),s=vb(e).slice(0,100),i=Tb(e,t);return{id:(0,Lm.randomUUID)(),timestamp:r,session_id:t.sessionId,project_path:t.projectPath,category:n,summary:s,details:i,agent_name:e.agentName??"workflow-engine",task_context:`${t.featureName} (${e.phase}${e.stage?"/"+e.stage:""})`,files_involved:e.artifactId?[`${e.artifactId}`]:[],confidence:o,verified:e.type==="gate_approval"||e.type==="phase_complete"||e.type==="bolt_execution_complete",verification_count:0,scope:"project",last_useful:r}}function Sb(e){switch(e){case"gate_approval":case"phase_complete":return .9;case"gate_rejection":case"contract_violation":return .85;case"build_failure":case"rework_required":return .8;case"trust_level_change":return .95;case"depth_override":return .7;case"bolt_execution_complete":return .85;case"gate_approval_after_rejection":return .9;case"depth_assessment_complete":return .8;case"execution_mode_selected":return .75;default:return .5}}function vb(e){switch(e.type){case"gate_rejection":return`Gate rejected at ${e.phase}${e.stage?"/"+e.stage:""}: ${e.details}`;case"gate_approval":return`Gate approved at ${e.phase}${e.stage?"/"+e.stage:""}`;case"build_failure":return`Build failed during ${e.phase}: ${e.details}`;case"rework_required":return`Rework needed: ${e.details}`;case"contract_violation":return`Contract violated: ${e.artifactId??"unknown"} - ${e.details}`;case"trust_level_change":return`Trust level change: ${e.details}`;case"phase_complete":return`Phase ${e.phase} completed`;case"depth_override":return`Depth assessment overridden: ${e.details}`;case"bolt_execution_complete":return`BOLT execution complete at ${e.phase}${e.stage?"/"+e.stage:""}: ${e.details}`;case"gate_approval_after_rejection":return`Gate approved after rejection at ${e.phase}${e.stage?"/"+e.stage:""}`;case"depth_assessment_complete":return`Depth assessment: ${e.details}`;case"execution_mode_selected":return`Execution mode selected: ${e.details}`;default:return`Workflow event: ${e.type}`}}function Tb(e,t){let n=[`Event: ${e.type}`,`Workflow: ${t.workflowId} (${t.featureName})`,`Phase: ${e.phase}${e.stage?" / Stage: "+e.stage:""}`,`Details: ${e.details}`];return e.artifactId&&n.push(`Artifact: ${e.artifactId}`),e.agentName&&n.push(`Agent: ${e.agentName}`),t.riskTier&&n.push(`Risk Tier: ${t.riskTier.tier}`),t.depthScore!==void 0&&n.push(`Depth Score: ${t.depthScore}`),n.join(`
1122
- `)}Gt();ss();function cr(e){return Math.max(1,Math.min(5,Math.round(e)))}function bb(e){let t=cr(e.clarity),n=cr(e.complexity),r=cr(e.scope),o=cr(e.risk),s=cr(e.context),i=cr(e.preferences),a=t+n+r+o+s+i,c;a<=10?c="minimal":a<=20?c="standard":c="comprehensive";let l=a<=10,u=Cb(o,n,r),d=Bm(u);return{clarity:t,complexity:n,scope:r,risk:o,context:s,preferences:i,total_score:a,recommended_depth:c,skip_units:l,risk_tier:d}}function Cb(e,t,n){let r;e>=4?r="difficult":e>=3?r="moderate":r="easy";let o;n>=4?o="system-wide":n>=3?o="cross-cutting":o="isolated";let s;e>=4&&t>=3?s="user-facing":e>=3?s="internal":s="none";let i;return e>=5?i="major":e>=4?i="minor":i="none",{reversibility:r,blast_radius:o,data_sensitivity:s,compliance_impact:i}}function Bm(e){let t=e.reversibility==="easy"?1:e.reversibility==="moderate"?2:3,n=e.blast_radius==="isolated"?1:e.blast_radius==="cross-cutting"?2:3,r=e.data_sensitivity==="none"?1:e.data_sensitivity==="internal"?2:3,o=e.compliance_impact==="none"?1:e.compliance_impact==="minor"?2:3,s=t+n+r+o,i;s<=6?i=1:s<=9?i=2:i=3;let a=Rb(i,e);return{tier:i,rationale:a,factors:e,override_reason:null}}function Rb(e,t){let n=[];return e===1?n.push("Low risk change"):e===2?n.push("Moderate risk change"):n.push("High risk change"),t.reversibility==="difficult"&&n.push("difficult to reverse"),t.blast_radius==="system-wide"?n.push("system-wide impact"):t.blast_radius==="cross-cutting"&&n.push("cross-cutting concerns"),t.data_sensitivity==="user-facing"&&n.push("affects user data"),t.compliance_impact==="major"?n.push("major compliance implications"):t.compliance_impact==="minor"&&n.push("minor compliance considerations"),n.join(", ")+"."}function gs(e){let t=xb(e),n=Pb(t),r=Ib(t),o=Ab(t),s=Ob(t),i=$b(t),a=Db(t),c=Nb(e,t),u=bb({clarity:n,complexity:r,scope:o,risk:s,context:i,preferences:a}),d=Bm(c);return u.risk_tier=d,u}function xb(e){let t={problemStatement:"",userPersonas:"",businessConstraints:"",successMetrics:"",outOfScope:""},n=/^## (.+)$/gm,r=[],o=0,s;for(;(s=n.exec(e))!==null;)r.length>0&&(r[r.length-1].content=e.substring(o,s.index).trim()),r.push({title:s[1].trim(),content:""}),o=s.index+s[0].length;r.length>0&&(r[r.length-1].content=e.substring(o).trim());for(let i of r){let a=i.title.toLowerCase();a.includes("problem")||a.includes("statement")?t.problemStatement=i.content:a.includes("persona")||a.includes("user persona")?t.userPersonas=i.content:a.includes("business constraint")||a.includes("constraint")?t.businessConstraints=i.content:a.includes("success")||a.includes("metric")?t.successMetrics=i.content:(a.includes("out of scope")||a.includes("scope"))&&(t.outOfScope=i.content)}return t}function Pb(e){let t=e.problemStatement.length+e.userPersonas.length;return t>1e3?1:t>500?2:t>250?3:t>100?4:5}function Ib(e){let t=(e.userPersonas.match(/^[-*+]\s/gm)||[]).length,r=["component","service","module","layer","system","integration","api"].filter(s=>e.userPersonas.toLowerCase().includes(s)).length,o=t+r;return o>=10?5:o>=7?4:o>=4?3:o>=2?2:1}function Ab(e){let t=(e.businessConstraints.match(/^[-*+]\s/gm)||[]).length,n=(e.successMetrics.match(/^[-*+]\s/gm)||[]).length,r=t+n;return r>=10?5:r>=7?4:r>=4?3:r>=2?2:1}function Ob(e){let t=["security","compliance","data","migration","breaking","irreversible","pii","gdpr","authentication","payment","infrastructure","system-wide","critical"],r=(e.businessConstraints+e.userPersonas).toLowerCase(),o=t.filter(s=>r.includes(s)).length;return o>=5?5:o>=3?4:o>=2?3:o>=1?2:1}function $b(e){let t=e.outOfScope.length;return t>500?1:t>300?2:t>150?3:t>50?4:5}function Db(e){let t=["must","should","could","prefer","optional","required","nice to have"],r=(e.businessConstraints+e.userPersonas).toLowerCase(),o=t.filter(s=>r.includes(s)).length;return o>=8?5:o>=5?4:o>=3?3:o>=2?2:1}function Nb(e,t){let n=e.toLowerCase(),r="moderate";n.includes("irreversible")||n.includes("migration")||n.includes("data loss")||n.includes("breaking change")?r="difficult":(n.includes("refactor")||n.includes("new feature")||n.includes("additive"))&&(r="easy");let o="isolated";n.includes("system-wide")||n.includes("all users")||n.includes("infrastructure")||n.includes("platform")?o="system-wide":(n.includes("cross-cutting")||n.includes("multiple")||n.includes("shared"))&&(o="cross-cutting");let s="none";n.includes("pii")||n.includes("personal")||n.includes("authentication")||n.includes("payment")||n.includes("user data")||n.includes("sensitive")?s="user-facing":(n.includes("internal")||n.includes("logging")||n.includes("metrics")||n.includes("telemetry"))&&(s="internal");let i="none";return n.includes("gdpr")||n.includes("soc")||n.includes("hipaa")||n.includes("compliance")||n.includes("regulatory")?i="major":(n.includes("audit")||n.includes("policy"))&&(i="minor"),{reversibility:r,blast_radius:o,data_sensitivity:s,compliance_impact:i}}Z();var Hm=require("fs"),Fb=require("path"),jb=require("os"),hs="<!-- AIDLC-RULES-START -->",lr="<!-- AIDLC-RULES-END -->";function Vm(e){return e.includes(hs)&&e.includes(lr)}function Aa(e,t){let n=`${hs}
1121
+ `),i={};for(let a of s){let c=a.match(/^(\w+):\s*(.+)$/);if(c){let[,l,u]=c,d=u.trim().replace(/^["']|["']$/g,"");isNaN(Number(d))?i[l]=d:i[l]=Number(d)}}return{id:n,type:"unit",title:i.title||"Untitled Unit",parent_id:i.parent_intent||null,children_ids:[],status:i.status||"pending",assigned_agent:i.assigned_agent||null,estimated_effort:i.estimated_effort||0}}catch(r){return console.error("Failed to parse unit from markdown:",r),null}}};ns();var og=require("crypto"),UE={gate_rejection:"gotcha",gate_approval:"pattern",build_failure:"technical_insight",rework_required:"gotcha",contract_violation:"gotcha",trust_level_change:"planning_insight",phase_complete:"pattern",depth_override:"planning_insight",bolt_execution_complete:"workflow_gate",gate_approval_after_rejection:"workflow_gate",depth_assessment_complete:"planning_insight",execution_mode_selected:"planning_insight",retro_completed:"retro_insight"};function qe(e,t){let n=UE[e.type],r=e.timestamp??new Date().toISOString(),o=WE(e.type),s=BE(e).slice(0,100),i=GE(e,t);return{id:(0,og.randomUUID)(),timestamp:r,session_id:t.sessionId,project_path:t.projectPath,category:n,summary:s,details:i,agent_name:e.agentName??"workflow-engine",task_context:`${t.featureName} (${e.phase}${e.stage?"/"+e.stage:""})`,files_involved:e.artifactId?[`${e.artifactId}`]:[],confidence:o,verified:e.type==="gate_approval"||e.type==="phase_complete"||e.type==="bolt_execution_complete",verification_count:0,scope:"project",last_useful:r}}function WE(e){switch(e){case"gate_approval":case"phase_complete":return .9;case"gate_rejection":case"contract_violation":return .85;case"build_failure":case"rework_required":return .8;case"trust_level_change":return .95;case"depth_override":return .7;case"bolt_execution_complete":return .85;case"gate_approval_after_rejection":return .9;case"depth_assessment_complete":return .8;case"execution_mode_selected":return .75;default:return .5}}function BE(e){switch(e.type){case"gate_rejection":return`Gate rejected at ${e.phase}${e.stage?"/"+e.stage:""}: ${e.details}`;case"gate_approval":return`Gate approved at ${e.phase}${e.stage?"/"+e.stage:""}`;case"build_failure":return`Build failed during ${e.phase}: ${e.details}`;case"rework_required":return`Rework needed: ${e.details}`;case"contract_violation":return`Contract violated: ${e.artifactId??"unknown"} - ${e.details}`;case"trust_level_change":return`Trust level change: ${e.details}`;case"phase_complete":return`Phase ${e.phase} completed`;case"depth_override":return`Depth assessment overridden: ${e.details}`;case"bolt_execution_complete":return`BOLT execution complete at ${e.phase}${e.stage?"/"+e.stage:""}: ${e.details}`;case"gate_approval_after_rejection":return`Gate approved after rejection at ${e.phase}${e.stage?"/"+e.stage:""}`;case"depth_assessment_complete":return`Depth assessment: ${e.details}`;case"execution_mode_selected":return`Execution mode selected: ${e.details}`;default:return`Workflow event: ${e.type}`}}function GE(e,t){let n=[`Event: ${e.type}`,`Workflow: ${t.workflowId} (${t.featureName})`,`Phase: ${e.phase}${e.stage?" / Stage: "+e.stage:""}`,`Details: ${e.details}`];return e.artifactId&&n.push(`Artifact: ${e.artifactId}`),e.agentName&&n.push(`Agent: ${e.agentName}`),t.riskTier&&n.push(`Risk Tier: ${t.riskTier.tier}`),t.depthScore!==void 0&&n.push(`Depth Score: ${t.depthScore}`),n.join(`
1122
+ `)}Ut();ls();function lr(e){return Math.max(1,Math.min(5,Math.round(e)))}function HE(e){let t=lr(e.clarity),n=lr(e.complexity),r=lr(e.scope),o=lr(e.risk),s=lr(e.context),i=lr(e.preferences),a=t+n+r+o+s+i,c;a<=10?c="minimal":a<=20?c="standard":c="comprehensive";let l=a<=10,u=VE(o,n,r),d=sg(u);return{clarity:t,complexity:n,scope:r,risk:o,context:s,preferences:i,total_score:a,recommended_depth:c,skip_units:l,risk_tier:d}}function VE(e,t,n){let r;e>=4?r="difficult":e>=3?r="moderate":r="easy";let o;n>=4?o="system-wide":n>=3?o="cross-cutting":o="isolated";let s;e>=4&&t>=3?s="user-facing":e>=3?s="internal":s="none";let i;return e>=5?i="major":e>=4?i="minor":i="none",{reversibility:r,blast_radius:o,data_sensitivity:s,compliance_impact:i}}function sg(e){let t=e.reversibility==="easy"?1:e.reversibility==="moderate"?2:3,n=e.blast_radius==="isolated"?1:e.blast_radius==="cross-cutting"?2:3,r=e.data_sensitivity==="none"?1:e.data_sensitivity==="internal"?2:3,o=e.compliance_impact==="none"?1:e.compliance_impact==="minor"?2:3,s=t+n+r+o,i;s<=6?i=1:s<=9?i=2:i=3;let a=qE(i,e);return{tier:i,rationale:a,factors:e,override_reason:null}}function qE(e,t){let n=[];return e===1?n.push("Low risk change"):e===2?n.push("Moderate risk change"):n.push("High risk change"),t.reversibility==="difficult"&&n.push("difficult to reverse"),t.blast_radius==="system-wide"?n.push("system-wide impact"):t.blast_radius==="cross-cutting"&&n.push("cross-cutting concerns"),t.data_sensitivity==="user-facing"&&n.push("affects user data"),t.compliance_impact==="major"?n.push("major compliance implications"):t.compliance_impact==="minor"&&n.push("minor compliance considerations"),n.join(", ")+"."}function ws(e){let t=YE(e),n=KE(t),r=JE(t),o=zE(t),s=QE(t),i=XE(t),a=ZE(t),c=eC(e,t),u=HE({clarity:n,complexity:r,scope:o,risk:s,context:i,preferences:a}),d=sg(c);return u.risk_tier=d,u}function YE(e){let t={problemStatement:"",userPersonas:"",businessConstraints:"",successMetrics:"",outOfScope:""},n=/^## (.+)$/gm,r=[],o=0,s;for(;(s=n.exec(e))!==null;)r.length>0&&(r[r.length-1].content=e.substring(o,s.index).trim()),r.push({title:s[1].trim(),content:""}),o=s.index+s[0].length;r.length>0&&(r[r.length-1].content=e.substring(o).trim());for(let i of r){let a=i.title.toLowerCase();a.includes("problem")||a.includes("statement")?t.problemStatement=i.content:a.includes("persona")||a.includes("user persona")?t.userPersonas=i.content:a.includes("business constraint")||a.includes("constraint")?t.businessConstraints=i.content:a.includes("success")||a.includes("metric")?t.successMetrics=i.content:(a.includes("out of scope")||a.includes("scope"))&&(t.outOfScope=i.content)}return t}function KE(e){let t=e.problemStatement.length+e.userPersonas.length;return t>1e3?1:t>500?2:t>250?3:t>100?4:5}function JE(e){let t=(e.userPersonas.match(/^[-*+]\s/gm)||[]).length,r=["component","service","module","layer","system","integration","api"].filter(s=>e.userPersonas.toLowerCase().includes(s)).length,o=t+r;return o>=10?5:o>=7?4:o>=4?3:o>=2?2:1}function zE(e){let t=(e.businessConstraints.match(/^[-*+]\s/gm)||[]).length,n=(e.successMetrics.match(/^[-*+]\s/gm)||[]).length,r=t+n;return r>=10?5:r>=7?4:r>=4?3:r>=2?2:1}function QE(e){let t=["security","compliance","data","migration","breaking","irreversible","pii","gdpr","authentication","payment","infrastructure","system-wide","critical"],r=(e.businessConstraints+e.userPersonas).toLowerCase(),o=t.filter(s=>r.includes(s)).length;return o>=5?5:o>=3?4:o>=2?3:o>=1?2:1}function XE(e){let t=e.outOfScope.length;return t>500?1:t>300?2:t>150?3:t>50?4:5}function ZE(e){let t=["must","should","could","prefer","optional","required","nice to have"],r=(e.businessConstraints+e.userPersonas).toLowerCase(),o=t.filter(s=>r.includes(s)).length;return o>=8?5:o>=5?4:o>=3?3:o>=2?2:1}function eC(e,t){let n=e.toLowerCase(),r="moderate";n.includes("irreversible")||n.includes("migration")||n.includes("data loss")||n.includes("breaking change")?r="difficult":(n.includes("refactor")||n.includes("new feature")||n.includes("additive"))&&(r="easy");let o="isolated";n.includes("system-wide")||n.includes("all users")||n.includes("infrastructure")||n.includes("platform")?o="system-wide":(n.includes("cross-cutting")||n.includes("multiple")||n.includes("shared"))&&(o="cross-cutting");let s="none";n.includes("pii")||n.includes("personal")||n.includes("authentication")||n.includes("payment")||n.includes("user data")||n.includes("sensitive")?s="user-facing":(n.includes("internal")||n.includes("logging")||n.includes("metrics")||n.includes("telemetry"))&&(s="internal");let i="none";return n.includes("gdpr")||n.includes("soc")||n.includes("hipaa")||n.includes("compliance")||n.includes("regulatory")?i="major":(n.includes("audit")||n.includes("policy"))&&(i="minor"),{reversibility:r,blast_radius:o,data_sensitivity:s,compliance_impact:i}}Z();var ig=require("fs"),tC=require("path"),nC=require("os"),_s="<!-- AIDLC-RULES-START -->",ur="<!-- AIDLC-RULES-END -->";function ag(e){return e.includes(_s)&&e.includes(ur)}function Ma(e,t){let n=`${_s}
1123
1123
  ${t}
1124
- ${lr}`;if(Vm(e)){let o=e.indexOf(hs),s=e.indexOf(lr)+lr.length,i=e.slice(0,o).replace(/\s+$/,""),a=e.slice(s).replace(/^\s+/,"");return a?`${n}
1124
+ ${ur}`;if(ag(e)){let o=e.indexOf(_s),s=e.indexOf(ur)+ur.length,i=e.slice(0,o).replace(/\s+$/,""),a=e.slice(s).replace(/^\s+/,"");return a?`${n}
1125
1125
 
1126
1126
  ${a}`:n}let r=e.replace(/^\s+/,"");return r?`${n}
1127
1127
 
1128
- ${r}`:n}function qm(e){if(!Vm(e))return e;let t=e.indexOf(hs),n=e.indexOf(lr)+lr.length,r=e.slice(0,t).replace(/\s+$/,""),o=e.slice(n).replace(/^\s+/,"");return r&&o?`${r}
1128
+ ${r}`:n}function cg(e){if(!ag(e))return e;let t=e.indexOf(_s),n=e.indexOf(ur)+ur.length,r=e.slice(0,t).replace(/\s+$/,""),o=e.slice(n).replace(/^\s+/,"");return r&&o?`${r}
1129
1129
 
1130
- ${o}`:r||o||""}function Oa(e,t){return`# AI-DLC Workflow Rules (Olympus-Native)
1130
+ ${o}`:r||o||""}function La(e,t){return`# AI-DLC Workflow Rules (Olympus-Native)
1131
1131
 
1132
1132
  ## Active Workflow
1133
1133
  - **Workflow ID**: \`${e}\`
@@ -1138,8 +1138,8 @@ ${o}`:r||o||""}function Oa(e,t){return`# AI-DLC Workflow Rules (Olympus-Native)
1138
1138
 
1139
1139
  All workflow stages, agent delegation, directory layout, and rules are defined in the
1140
1140
  global \`~/.claude/CLAUDE.md\` (installed by Olympus). This block only tracks the active
1141
- workflow identity \u2014 do NOT search for a separate core-workflow.md file.`}var rC=["set up","build out","roll out","hook up","wire up","spin up","build","create","add","implement","design","make","develop","configure","integrate","fix","update","refactor","migrate","deploy","setup","establish","introduce","enable","write","construct","generate","define","prepare"];function Ba(e){let t=e.trim();t=t.replace(/\.[a-z]{1,4}$/i,"");let n=[...rC].sort((s,i)=>i.length-s.length);for(let s of n){let i=new RegExp(`^${s}\\s+`,"i");if(i.test(t)){t=t.replace(i,"");break}}t=t.replace(/^(?:a|an|the)\s+/i,"");let r=t.replace(/\s+(?:for|with|using|via|in|to|on|at|from|into|across|through|about|of)\s+.+$/i,"").trim();r.length>0&&(t=r);let o=t.toLowerCase().replace(/[_\s]+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"");if(o.length>40){let s=o.substring(0,40),i=s.lastIndexOf("-");o=i>0?s.substring(0,i):s,o=o.replace(/-$/,"")}if(!o)throw new Error("Feature name produced an empty workflow ID after sanitization");if(o==="completed")throw new Error("'completed' is a reserved directory name and cannot be used as a workflow ID");return o}var Ga=["intent","unit","code-generation","complete"];function oC(e){let t=Ga.indexOf(e);return t===-1||t>=Ga.length-1?"complete":Ga[t+1]}var ks=class{projectPath;featureName;workflowId;interruptHandler=null;constructor(t,n){this.projectPath=t,this.featureName=n,this.workflowId=Ba(n)}async start(t){let n={schema_version:"3.0.0",workflow_id:this.workflowId,feature_name:this.featureName,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),current_phase:"inception",current_stage:"intent",status:"in_progress",origin:"hook-init",phases:{discovery:{status:"not_started",started_at:null,completed_at:null,gate_result:null,gate_bypassed:!1,bypass_reason:null},inception:{status:"in_progress",started_at:new Date().toISOString(),completed_at:null,gate_result:null,gate_bypassed:!1,bypass_reason:null},construction:{status:"not_started",started_at:null,completed_at:null,gate_result:null,gate_bypassed:!1,bypass_reason:null},operations:{status:"not_started",started_at:null,completed_at:null,gate_result:null,gate_bypassed:!1,bypass_reason:null}},manifest_path:`aidlc-docs/${this.workflowId}/manifest.json`,trust_state_path:".olympus/trust-state.json",resume_context:{initial_prompt:t}};try{await Pp(this.projectPath,this.workflowId)}catch(o){let s=o;throw console.error(`[WorkflowEngine] Failed to initialize workflow directory: ${s.message}`),new Error(`Failed to start workflow: Could not create directory structure - ${s.message}`)}let r=$n.join(this.projectPath,"aidlc-docs",this.workflowId,"manifest.json");if(!ge.existsSync(r))try{Bi(this.workflowId,this.featureName,this.projectPath)}catch(o){console.warn(`[WorkflowEngine] Failed to create manifest: ${o.message}`)}try{await O(this.projectPath,n)}catch(o){let s=o;throw console.error(`[WorkflowEngine] Failed to save initial checkpoint: ${s.message}`),new Error(`Failed to start workflow: Could not save checkpoint - ${s.message}`)}try{let s=(await Rn(this.projectPath)).sourceFileCount??0,i=await Sa(this.projectPath,t),a=gs(t),c=await Ta({projectPath:this.projectPath,workflowId:this.workflowId,intentText:t,depthAssessment:a,pathwayType:i,sourceFileCount:s}),l=await rs(this.projectPath,this.workflowId,c),u=await I(this.projectPath,this.workflowId);if(u){u.workflow_routing_path=l,u.pathway_type=i;let d=["discovery","inception","construction","operations"];u.skipped_phases=d.filter(p=>!os(c,p)),await O(this.projectPath,u)}if(console.log(`[WorkflowEngine] Generated Workflow Routing: pathway=${i}, depth=${c.estimated_depth}, code-generations=${c.estimated_code_generations}`),c.stages.some(d=>!d.included)){let d=c.stages.filter(p=>!p.included).map(p=>`${p.phase}/${p.stage}`);console.log(`[WorkflowEngine] Stages excluded by plan: ${d.join(", ")}`)}}catch(o){console.warn(`[WorkflowEngine] Failed to generate Workflow Routing: ${o.message}`),console.warn("[WorkflowEngine] Workflow will proceed without adaptive phase selection")}try{let s=(await I(this.projectPath,this.workflowId))?.pathway_type;if(!s){let{isBrownfield:u}=await Rn(this.projectPath);s=u?"brownfield-enhancement":"greenfield"}let i=$n.join(this.projectPath,".claude","CLAUDE.md"),a=ge.existsSync(i)?ge.readFileSync(i,"utf-8"):"",c=Oa(this.workflowId,s),l=Aa(a,c);ge.mkdirSync($n.join(this.projectPath,".claude"),{recursive:!0}),ge.writeFileSync(i,l,"utf-8"),console.log("[WorkflowEngine] Injected AI-DLC rules into .claude/CLAUDE.md")}catch(o){console.error("[WorkflowEngine] Failed to inject AI-DLC rules into CLAUDE.md:",o)}}async resume(){let t;try{t=await I(this.projectPath,this.workflowId)}catch(r){let o=r;throw console.error(`[WorkflowEngine] Failed to load checkpoint for resume: ${o.message}`),new Error(`Failed to resume workflow: Could not load checkpoint - ${o.message}`)}if(!t)throw console.error(`[WorkflowEngine] No checkpoint found for workflow: ${this.workflowId}`),console.error("[WorkflowEngine] Available workflows: Run 'olympus workflow list' to see workflows"),new Error(`No checkpoint found for workflow: ${this.workflowId}`);if(t.status==="complete")return"Workflow already complete";if(t.status==="paused"){t.status="in_progress";try{await O(this.projectPath,t)}catch(r){let o=r;throw console.error(`[WorkflowEngine] Failed to update checkpoint status: ${o.message}`),new Error(`Failed to resume workflow: Could not save checkpoint - ${o.message}`)}}try{let r=t.pathway_type;if(!r){let{isBrownfield:c}=await Rn(this.projectPath);r=c?"brownfield-enhancement":"greenfield"}let o=$n.join(this.projectPath,".claude","CLAUDE.md"),s=ge.existsSync(o)?ge.readFileSync(o,"utf-8"):"",i=Oa(this.workflowId,r),a=Aa(s,i);ge.mkdirSync($n.join(this.projectPath,".claude"),{recursive:!0}),ge.writeFileSync(o,a,"utf-8"),console.log("[WorkflowEngine] Injected AI-DLC rules into .claude/CLAUDE.md")}catch(r){console.error("[WorkflowEngine] Failed to inject AI-DLC rules into CLAUDE.md:",r)}this.setupInterruptHandler();let n=t.current_stage;try{await this.executeStage(n)}catch(r){let o=r;console.error(`[WorkflowEngine] Failed to execute ${n} stage: ${o.message}`);try{let s=await I(this.projectPath,this.workflowId);s&&(s.status="paused",s.resume_context={...s.resume_context,error_message:o.message,failed_stage:n},await O(this.projectPath,s),console.log("[WorkflowEngine] Workflow saved as paused. Fix the issue and resume with `/continue`"))}catch(s){console.warn("[WorkflowEngine] Failed to save error checkpoint:",s.message)}throw new Error(`Failed to execute ${n} stage: ${o.message}`)}finally{this.cleanupInterruptHandler()}return`Resumed workflow from stage: ${n}`}async pause(){let t;try{t=await I(this.projectPath,this.workflowId)}catch(n){let r=n;throw console.error(`[WorkflowEngine] Failed to load checkpoint for pause: ${r.message}`),new Error(`Failed to pause workflow: Could not load checkpoint - ${r.message}`)}if(!t)throw console.error(`[WorkflowEngine] No checkpoint found for workflow: ${this.workflowId}`),new Error(`No checkpoint found for workflow: ${this.workflowId}`);t.status="paused";try{await O(this.projectPath,t)}catch(n){let r=n;throw console.error(`[WorkflowEngine] Failed to save paused checkpoint: ${r.message}`),new Error(`Failed to pause workflow: Could not save checkpoint - ${r.message}`)}return`aidlc-docs/${this.workflowId}/checkpoint.json`}async executeStage(t){if(t==="complete")throw new Error("No execution for complete stage");let n=await I(this.projectPath,this.workflowId);if(!n)throw new Error(`No checkpoint found for workflow: ${this.workflowId}`);switch(t){case"intent":await this.executeIntentStage(n);break;case"unit":await this.executeUnitStage(n);break;case"code-generation":await this.executeCodeGenerationStage(n);break}let r=oC(t);n.current_stage=r,r==="complete"?await this.completeWorkflow(n):await O(this.projectPath,n)}async getStatus(){let t;try{t=await I(this.projectPath,this.workflowId)}catch(r){let o=r;throw console.error(`[WorkflowEngine] Failed to load checkpoint for status: ${o.message}`),new Error(`Failed to get workflow status: Could not load checkpoint - ${o.message}`)}if(!t)throw console.error(`[WorkflowEngine] No checkpoint found for workflow: ${this.workflowId}`),new Error(`No checkpoint found for workflow: ${this.workflowId}`);let n=[];return{workflow_id:t.workflow_id,feature_name:t.feature_name,current_stage:t.current_stage,status:t.status,artifacts:n,updated_at:t.updated_at}}async executePhase(t){let n=Xr(this.projectPath,this.workflowId);if(n&&!os(n,t)){console.log(`[WorkflowEngine] Skipping ${t} phase (excluded by Workflow Routing: ${n.phases[t]?.rationale||"no rationale"})`);let r=await I(this.projectPath,this.workflowId);if(r){let s=r;s.phases&&s.phases[t]&&(s.phases[t].status="complete",s.phases[t].completed_at=new Date().toISOString(),s.phases[t].gate_bypassed=!0,s.phases[t].bypass_reason="Excluded by Workflow Routing"),await O(this.projectPath,r)}let o=`${this.projectPath}/aidlc-docs/${this.workflowId}/manifest.json`;try{Fe(o,{phase:t,action:"bypassed",actor:"config",reason:`Excluded by Workflow Routing (pathway: ${n.pathway})`})}catch{}return}switch(t){case"discovery":{let r=`${this.projectPath}/aidlc-docs/${this.workflowId}/manifest.json`,o=await Vf({projectPath:this.projectPath,workflowId:this.workflowId,featureName:this.featureName,manifestPath:r});o.gateRequired&&(console.log(`[WorkflowEngine] Discovery phase: ${o.artifactsGenerated.length} artifacts generated (${o.sourceFileCount} source files detected)`),console.log(`[WorkflowEngine] Discovery Gate: Review findings in aidlc-docs/${this.workflowId}/discovery/ before proceeding to Inception`));try{let s={type:"phase_complete",phase:"discovery",details:`${o.artifactsGenerated.length} artifacts generated, ${o.sourceFileCount} source files`},i={workflowId:this.workflowId,featureName:this.featureName,projectPath:this.projectPath,sessionId:"engine",phase:"discovery"},a=Ve(s,i);le(a)}catch(s){console.error("[WorkflowEngine] Failed to capture discovery phase discovery:",s)}break}case"inception":{let{InceptionOrchestrator:r}=await Promise.resolve().then(()=>(dg(),ug)),o=new r,s=await I(this.projectPath,this.workflowId);if(!s)throw new Error(`No checkpoint found for workflow: ${this.workflowId}`);if(s.current_stage!=="intent"){console.log(`[WorkflowEngine] Skipping inception orchestrator \u2014 checkpoint already at stage '${s.current_stage}'`);break}if(!s.inception_stages){let i=Xr(this.projectPath,this.workflowId),a=s;await o.initialize(this.projectPath,this.workflowId,a.pathway_type||"greenfield",i)}for(;!await o.isComplete(this.projectPath,this.workflowId);){let i=await o.executeNextStage(this.projectPath,this.workflowId);if(i.status==="awaiting_answers"||i.status==="review_required")break}try{let i={type:"phase_complete",phase:"inception",details:"Inception stages completed"},a={workflowId:this.workflowId,featureName:this.featureName,projectPath:this.projectPath,sessionId:"engine",phase:"inception"},c=Ve(i,a);le(c)}catch(i){console.error("[WorkflowEngine] Failed to capture inception phase discovery:",i)}break}case"construction":{let r=await I(this.projectPath,this.workflowId);if(r&&r.status==="awaiting_dev_review"){console.log("[WorkflowEngine] Waiting for developer review of technical specification (Risk Tier 3).");return}let o=lt(this.projectPath,this.workflowId,"intent"),s;try{s=ge.readFileSync(o,"utf-8")}catch{}let a=await new fs(this.projectPath,this.workflowId).execute(s);if(!a.passed)throw console.error("[WorkflowEngine] Construction phase validation failed:",a.blocking_issues),new Error(`Construction phase validation failed: ${a.blocking_issues.join(", ")}`);try{let c={type:"phase_complete",phase:"construction",details:"Construction phase completed"},l={workflowId:this.workflowId,featureName:this.featureName,projectPath:this.projectPath,sessionId:"engine",phase:"construction"},u=Ve(c,l);le(u)}catch(c){console.error("[WorkflowEngine] Failed to capture construction phase discovery:",c)}break}case"operations":{let{generateOperationsArtifacts:r}=await Promise.resolve().then(()=>(wg(),yg)),{loadManifest:o,registerArtifact:s,updatePhaseStatus:i}=await Promise.resolve().then(()=>(Z(),vn)),a=`${this.projectPath}/aidlc-docs/${this.workflowId}/manifest.json`,c=o(a),l=null;try{l=ge.readFileSync(lt(this.projectPath,this.workflowId,"intent"),"utf-8")}catch{}let u=await I(this.projectPath,this.workflowId),d="MEDIUM";if(c?.depth_assessment){let m=c.depth_assessment.total_score;m<=10?d="SHALLOW":m>=21&&(d="DEEP")}let p={workflowId:this.workflowId,featureName:this.featureName,manifest:c,specContent:l,buildLogContent:null,depthLevel:d},f=await r(p,this.projectPath);if(c){i(a,"operations","complete");for(let m of f.artifactsGenerated){let g=`aidlc-docs/${this.workflowId}/operations/${m}`,y=m.replace(/\.(md|json)$/,"").toUpperCase().replace(/-/g,"_");s(a,{id:`OPS-${y}`,type:y,phase:"operations",stage:"code-generation",path:g,validation_passed:!0,write_complete:!0,checksum:null})}}u&&(u.current_phase="operations",u.updated_at=new Date().toISOString(),await O(this.projectPath,u)),console.log(`[WorkflowEngine] Operations phase: Generated ${f.artifactsGenerated.length} artifacts (depth: ${d})`),console.log(`[WorkflowEngine] Operations artifacts: ${f.artifactsGenerated.join(", ")}`);try{let m={type:"phase_complete",phase:"operations",details:`${f.artifactsGenerated.length} artifacts generated (depth: ${d})`},g={workflowId:this.workflowId,featureName:this.featureName,projectPath:this.projectPath,sessionId:"engine",phase:"operations"},y=Ve(m,g);le(y)}catch(m){console.error("[WorkflowEngine] Failed to capture operations phase discovery:",m)}break}}}async completeWorkflow(t){t.status="complete";try{let n=$n.join(this.projectPath,".claude","CLAUDE.md");if(ge.existsSync(n)){let r=ge.readFileSync(n,"utf-8"),o=qm(r);ge.writeFileSync(n,o,"utf-8"),console.log("[WorkflowEngine] Removed AI-DLC rules from .claude/CLAUDE.md (workflow complete)")}}catch(n){console.error("[WorkflowEngine] Failed to remove AI-DLC rules from CLAUDE.md:",n)}await O(this.projectPath,t),await Li(this.projectPath,this.workflowId)}async approveWorkflowRouting(t){let n=Xr(this.projectPath,this.workflowId);if(!n)throw new Error(`No Workflow Routing found for workflow: ${this.workflowId}`);n.approved_at=new Date().toISOString(),n.approved_by="human",await rs(this.projectPath,this.workflowId,n);let r=await I(this.projectPath,this.workflowId);if(r){let s=r;if(s.inception_stages?.["workflow-planning"]){let i=s.inception_stages["workflow-planning"];i.status!=="completed"&&i.status!=="skipped"&&(i.status="completed",i.completed_at=new Date().toISOString(),await O(this.projectPath,r))}}let o=`${this.projectPath}/aidlc-docs/${this.workflowId}/manifest.json`;try{Fe(o,{phase:"inception",action:"approved",actor:"human",reason:t||"Workflow Routing approved"})}catch{}console.log("[WorkflowEngine] Workflow Routing approved")}setupInterruptHandler(){this.interruptHandler=async()=>{console.log(`
1142
- [WorkflowEngine] Workflow interrupted - saving checkpoint...`);try{let t=await I(this.projectPath,this.workflowId);t&&(t.status="paused",t.updated_at=new Date().toISOString(),t.resume_context={...t.resume_context,interrupted_at:new Date().toISOString(),current_stage:t.current_stage,message:`Workflow interrupted during ${t.current_stage} stage`},await O(this.projectPath,t),console.log("[WorkflowEngine] Checkpoint saved. Resume with `/continue`"))}catch(t){console.error("[WorkflowEngine] Failed to save checkpoint on interrupt:",t)}process.exit(0)},process.on("SIGINT",this.interruptHandler)}cleanupInterruptHandler(){this.interruptHandler&&(process.off("SIGINT",this.interruptHandler),this.interruptHandler=null)}async executeIntentStage(t){let n=t.resume_context?.initial_prompt||"No initial prompt provided";console.log(`[WorkflowEngine] Executing INTENT stage for feature: ${this.featureName}`),console.log(`[WorkflowEngine] Initial prompt: ${n}`),console.log("[WorkflowEngine] Generating merged INTENT artifact with full inception content");let r=`intent-${this.workflowId}`,o=new Date().toISOString(),s=`---
1141
+ workflow identity \u2014 do NOT search for a separate core-workflow.md file.`}var yC=["set up","build out","roll out","hook up","wire up","spin up","build","create","add","implement","design","make","develop","configure","integrate","fix","update","refactor","migrate","deploy","setup","establish","introduce","enable","write","construct","generate","define","prepare"];function Ya(e){let t=e.trim();t=t.replace(/\.[a-z]{1,4}$/i,"");let n=[...yC].sort((s,i)=>i.length-s.length);for(let s of n){let i=new RegExp(`^${s}\\s+`,"i");if(i.test(t)){t=t.replace(i,"");break}}t=t.replace(/^(?:a|an|the)\s+/i,"");let r=t.replace(/\s+(?:for|with|using|via|in|to|on|at|from|into|across|through|about|of)\s+.+$/i,"").trim();r.length>0&&(t=r);let o=t.toLowerCase().replace(/[_\s]+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"");if(o.length>40){let s=o.substring(0,40),i=s.lastIndexOf("-");o=i>0?s.substring(0,i):s,o=o.replace(/-$/,"")}if(!o)throw new Error("Feature name produced an empty workflow ID after sanitization");if(o==="completed")throw new Error("'completed' is a reserved directory name and cannot be used as a workflow ID");return o}var qa=["intent","unit","code-generation","complete"];function wC(e){let t=qa.indexOf(e);return t===-1||t>=qa.length-1?"complete":qa[t+1]}var Ss=class{projectPath;featureName;workflowId;interruptHandler=null;constructor(t,n){this.projectPath=t,this.featureName=n,this.workflowId=Ya(n)}async start(t){let n={schema_version:"3.0.0",workflow_id:this.workflowId,feature_name:this.featureName,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),current_phase:"inception",current_stage:"intent",status:"in_progress",origin:"hook-init",phases:{discovery:{status:"not_started",started_at:null,completed_at:null,gate_result:null,gate_bypassed:!1,bypass_reason:null},inception:{status:"in_progress",started_at:new Date().toISOString(),completed_at:null,gate_result:null,gate_bypassed:!1,bypass_reason:null},construction:{status:"not_started",started_at:null,completed_at:null,gate_result:null,gate_bypassed:!1,bypass_reason:null},operations:{status:"not_started",started_at:null,completed_at:null,gate_result:null,gate_bypassed:!1,bypass_reason:null}},manifest_path:`aidlc-docs/${this.workflowId}/manifest.json`,trust_state_path:".olympus/trust-state.json",resume_context:{initial_prompt:t}};try{await $p(this.projectPath,this.workflowId)}catch(o){let s=o;throw console.error(`[WorkflowEngine] Failed to initialize workflow directory: ${s.message}`),new Error(`Failed to start workflow: Could not create directory structure - ${s.message}`)}let r=$n.join(this.projectPath,"aidlc-docs",this.workflowId,"manifest.json");if(!ge.existsSync(r))try{Vi(this.workflowId,this.featureName,this.projectPath)}catch(o){console.warn(`[WorkflowEngine] Failed to create manifest: ${o.message}`)}try{await A(this.projectPath,n)}catch(o){let s=o;throw console.error(`[WorkflowEngine] Failed to save initial checkpoint: ${s.message}`),new Error(`Failed to start workflow: Could not save checkpoint - ${s.message}`)}try{let s=(await Rn(this.projectPath)).sourceFileCount??0,i=await xa(this.projectPath,t),a=ws(t),c=await Aa({projectPath:this.projectPath,workflowId:this.workflowId,intentText:t,depthAssessment:a,pathwayType:i,sourceFileCount:s}),l=await as(this.projectPath,this.workflowId,c),u=await I(this.projectPath,this.workflowId);if(u){u.workflow_routing_path=l,u.pathway_type=i;let d=["discovery","inception","construction","operations"];u.skipped_phases=d.filter(p=>!cs(c,p)),await A(this.projectPath,u)}if(console.log(`[WorkflowEngine] Generated Workflow Routing: pathway=${i}, depth=${c.estimated_depth}, bolts=${c.estimated_bolts}`),c.stages.some(d=>!d.included)){let d=c.stages.filter(p=>!p.included).map(p=>`${p.phase}/${p.stage}`);console.log(`[WorkflowEngine] Stages excluded by plan: ${d.join(", ")}`)}}catch(o){console.warn(`[WorkflowEngine] Failed to generate Workflow Routing: ${o.message}`),console.warn("[WorkflowEngine] Workflow will proceed without adaptive phase selection")}try{let s=(await I(this.projectPath,this.workflowId))?.pathway_type;if(!s){let{isBrownfield:u}=await Rn(this.projectPath);s=u?"brownfield-enhancement":"greenfield"}let i=$n.join(this.projectPath,".claude","CLAUDE.md"),a=ge.existsSync(i)?ge.readFileSync(i,"utf-8"):"",c=La(this.workflowId,s),l=Ma(a,c);ge.mkdirSync($n.join(this.projectPath,".claude"),{recursive:!0}),ge.writeFileSync(i,l,"utf-8"),console.log("[WorkflowEngine] Injected AI-DLC rules into .claude/CLAUDE.md")}catch(o){console.error("[WorkflowEngine] Failed to inject AI-DLC rules into CLAUDE.md:",o)}}async resume(){let t;try{t=await I(this.projectPath,this.workflowId)}catch(r){let o=r;throw console.error(`[WorkflowEngine] Failed to load checkpoint for resume: ${o.message}`),new Error(`Failed to resume workflow: Could not load checkpoint - ${o.message}`)}if(!t)throw console.error(`[WorkflowEngine] No checkpoint found for workflow: ${this.workflowId}`),console.error("[WorkflowEngine] Available workflows: Run 'olympus workflow list' to see workflows"),new Error(`No checkpoint found for workflow: ${this.workflowId}`);if(t.status==="complete")return"Workflow already complete";if(t.status==="paused"){t.status="in_progress";try{await A(this.projectPath,t)}catch(r){let o=r;throw console.error(`[WorkflowEngine] Failed to update checkpoint status: ${o.message}`),new Error(`Failed to resume workflow: Could not save checkpoint - ${o.message}`)}}try{let r=t.pathway_type;if(!r){let{isBrownfield:c}=await Rn(this.projectPath);r=c?"brownfield-enhancement":"greenfield"}let o=$n.join(this.projectPath,".claude","CLAUDE.md"),s=ge.existsSync(o)?ge.readFileSync(o,"utf-8"):"",i=La(this.workflowId,r),a=Ma(s,i);ge.mkdirSync($n.join(this.projectPath,".claude"),{recursive:!0}),ge.writeFileSync(o,a,"utf-8"),console.log("[WorkflowEngine] Injected AI-DLC rules into .claude/CLAUDE.md")}catch(r){console.error("[WorkflowEngine] Failed to inject AI-DLC rules into CLAUDE.md:",r)}this.setupInterruptHandler();let n=t.current_stage;try{await this.executeStage(n)}catch(r){let o=r;console.error(`[WorkflowEngine] Failed to execute ${n} stage: ${o.message}`);try{let s=await I(this.projectPath,this.workflowId);s&&(s.status="paused",s.resume_context={...s.resume_context,error_message:o.message,failed_stage:n},await A(this.projectPath,s),console.log("[WorkflowEngine] Workflow saved as paused. Fix the issue and resume with `/continue`"))}catch(s){console.warn("[WorkflowEngine] Failed to save error checkpoint:",s.message)}throw new Error(`Failed to execute ${n} stage: ${o.message}`)}finally{this.cleanupInterruptHandler()}return`Resumed workflow from stage: ${n}`}async pause(){let t;try{t=await I(this.projectPath,this.workflowId)}catch(n){let r=n;throw console.error(`[WorkflowEngine] Failed to load checkpoint for pause: ${r.message}`),new Error(`Failed to pause workflow: Could not load checkpoint - ${r.message}`)}if(!t)throw console.error(`[WorkflowEngine] No checkpoint found for workflow: ${this.workflowId}`),new Error(`No checkpoint found for workflow: ${this.workflowId}`);t.status="paused";try{await A(this.projectPath,t)}catch(n){let r=n;throw console.error(`[WorkflowEngine] Failed to save paused checkpoint: ${r.message}`),new Error(`Failed to pause workflow: Could not save checkpoint - ${r.message}`)}return`aidlc-docs/${this.workflowId}/checkpoint.json`}async executeStage(t){if(t==="complete")throw new Error("No execution for complete stage");let n=await I(this.projectPath,this.workflowId);if(!n)throw new Error(`No checkpoint found for workflow: ${this.workflowId}`);switch(t){case"intent":await this.executeIntentStage(n);break;case"unit":await this.executeUnitStage(n);break;case"code-generation":await this.executeCodeGenerationStage(n);break}let r=wC(t);n.current_stage=r,r==="complete"?await this.completeWorkflow(n):await A(this.projectPath,n)}async getStatus(){let t;try{t=await I(this.projectPath,this.workflowId)}catch(r){let o=r;throw console.error(`[WorkflowEngine] Failed to load checkpoint for status: ${o.message}`),new Error(`Failed to get workflow status: Could not load checkpoint - ${o.message}`)}if(!t)throw console.error(`[WorkflowEngine] No checkpoint found for workflow: ${this.workflowId}`),new Error(`No checkpoint found for workflow: ${this.workflowId}`);let n=[];return{workflow_id:t.workflow_id,feature_name:t.feature_name,current_stage:t.current_stage,status:t.status,artifacts:n,updated_at:t.updated_at}}async executePhase(t){let n=Xr(this.projectPath,this.workflowId);if(n&&!cs(n,t)){console.log(`[WorkflowEngine] Skipping ${t} phase (excluded by Workflow Routing: ${n.phases[t]?.rationale||"no rationale"})`);let r=await I(this.projectPath,this.workflowId);if(r){let s=r;s.phases&&s.phases[t]&&(s.phases[t].status="complete",s.phases[t].completed_at=new Date().toISOString(),s.phases[t].gate_bypassed=!0,s.phases[t].bypass_reason="Excluded by Workflow Routing"),await A(this.projectPath,r)}let o=`${this.projectPath}/aidlc-docs/${this.workflowId}/manifest.json`;try{Fe(o,{phase:t,action:"bypassed",actor:"config",reason:`Excluded by Workflow Routing (pathway: ${n.pathway})`})}catch{}return}switch(t){case"discovery":{let r=`${this.projectPath}/aidlc-docs/${this.workflowId}/manifest.json`,o=await um({projectPath:this.projectPath,workflowId:this.workflowId,featureName:this.featureName,manifestPath:r});o.gateRequired&&(console.log(`[WorkflowEngine] Discovery phase: ${o.artifactsGenerated.length} artifacts generated (${o.sourceFileCount} source files detected)`),console.log(`[WorkflowEngine] Discovery Gate: Review findings in aidlc-docs/${this.workflowId}/discovery/ before proceeding to Inception`));try{let s={type:"phase_complete",phase:"discovery",details:`${o.artifactsGenerated.length} artifacts generated, ${o.sourceFileCount} source files`},i={workflowId:this.workflowId,featureName:this.featureName,projectPath:this.projectPath,sessionId:"engine",phase:"discovery"},a=qe(s,i);ue(a)}catch(s){console.error("[WorkflowEngine] Failed to capture discovery phase discovery:",s)}break}case"inception":{let{InceptionOrchestrator:r}=await Promise.resolve().then(()=>(hg(),gg)),o=new r,s=await I(this.projectPath,this.workflowId);if(!s)throw new Error(`No checkpoint found for workflow: ${this.workflowId}`);if(s.current_stage!=="intent"){console.log(`[WorkflowEngine] Skipping inception orchestrator \u2014 checkpoint already at stage '${s.current_stage}'`);break}if(!s.inception_stages){let i=Xr(this.projectPath,this.workflowId),a=s;await o.initialize(this.projectPath,this.workflowId,a.pathway_type||"greenfield",i)}for(;!await o.isComplete(this.projectPath,this.workflowId);){let i=await o.executeNextStage(this.projectPath,this.workflowId);if(i.status==="awaiting_answers"||i.status==="review_required")break}try{let i={type:"phase_complete",phase:"inception",details:"Inception stages completed"},a={workflowId:this.workflowId,featureName:this.featureName,projectPath:this.projectPath,sessionId:"engine",phase:"inception"},c=qe(i,a);ue(c)}catch(i){console.error("[WorkflowEngine] Failed to capture inception phase discovery:",i)}break}case"construction":{let r=await I(this.projectPath,this.workflowId);if(r&&r.status==="awaiting_dev_review"){console.log("[WorkflowEngine] Waiting for developer review of technical specification (Risk Tier 3).");return}let o=lt(this.projectPath,this.workflowId,"intent"),s;try{s=ge.readFileSync(o,"utf-8")}catch{}let a=await new ys(this.projectPath,this.workflowId).execute(s);if(!a.passed)throw console.error("[WorkflowEngine] Construction phase validation failed:",a.blocking_issues),new Error(`Construction phase validation failed: ${a.blocking_issues.join(", ")}`);try{let c={type:"phase_complete",phase:"construction",details:"Construction phase completed"},l={workflowId:this.workflowId,featureName:this.featureName,projectPath:this.projectPath,sessionId:"engine",phase:"construction"},u=qe(c,l);ue(u)}catch(c){console.error("[WorkflowEngine] Failed to capture construction phase discovery:",c)}break}case"operations":{let{generateOperationsArtifacts:r}=await Promise.resolve().then(()=>(bg(),vg)),{loadManifest:o,registerArtifact:s,updatePhaseStatus:i}=await Promise.resolve().then(()=>(Z(),vn)),a=`${this.projectPath}/aidlc-docs/${this.workflowId}/manifest.json`,c=o(a),l=null;try{l=ge.readFileSync(lt(this.projectPath,this.workflowId,"intent"),"utf-8")}catch{}let u=await I(this.projectPath,this.workflowId),d="MEDIUM";if(c?.depth_assessment){let m=c.depth_assessment.total_score;m<=10?d="SHALLOW":m>=21&&(d="DEEP")}let p={workflowId:this.workflowId,featureName:this.featureName,manifest:c,specContent:l,buildLogContent:null,depthLevel:d},f=await r(p,this.projectPath);if(c){i(a,"operations","complete");for(let m of f.artifactsGenerated){let g=`aidlc-docs/${this.workflowId}/operations/${m}`,y=m.replace(/\.(md|json)$/,"").toUpperCase().replace(/-/g,"_");s(a,{id:`OPS-${y}`,type:y,phase:"operations",stage:"code-generation",path:g,validation_passed:!0,write_complete:!0,checksum:null})}}u&&(u.current_phase="operations",u.updated_at=new Date().toISOString(),await A(this.projectPath,u)),console.log(`[WorkflowEngine] Operations phase: Generated ${f.artifactsGenerated.length} artifacts (depth: ${d})`),console.log(`[WorkflowEngine] Operations artifacts: ${f.artifactsGenerated.join(", ")}`);try{let m={type:"phase_complete",phase:"operations",details:`${f.artifactsGenerated.length} artifacts generated (depth: ${d})`},g={workflowId:this.workflowId,featureName:this.featureName,projectPath:this.projectPath,sessionId:"engine",phase:"operations"},y=qe(m,g);ue(y)}catch(m){console.error("[WorkflowEngine] Failed to capture operations phase discovery:",m)}break}}}async completeWorkflow(t){t.status="complete";try{let n=$n.join(this.projectPath,".claude","CLAUDE.md");if(ge.existsSync(n)){let r=ge.readFileSync(n,"utf-8"),o=cg(r);ge.writeFileSync(n,o,"utf-8"),console.log("[WorkflowEngine] Removed AI-DLC rules from .claude/CLAUDE.md (workflow complete)")}}catch(n){console.error("[WorkflowEngine] Failed to remove AI-DLC rules from CLAUDE.md:",n)}await A(this.projectPath,t),await Wi(this.projectPath,this.workflowId)}async approveWorkflowRouting(t){let n=Xr(this.projectPath,this.workflowId);if(!n)throw new Error(`No Workflow Routing found for workflow: ${this.workflowId}`);n.approved_at=new Date().toISOString(),n.approved_by="human",await as(this.projectPath,this.workflowId,n);let r=await I(this.projectPath,this.workflowId);if(r){let s=r;if(s.inception_stages?.["workflow-planning"]){let i=s.inception_stages["workflow-planning"];i.status!=="completed"&&i.status!=="skipped"&&(i.status="completed",i.completed_at=new Date().toISOString(),await A(this.projectPath,r))}}let o=`${this.projectPath}/aidlc-docs/${this.workflowId}/manifest.json`;try{Fe(o,{phase:"inception",action:"approved",actor:"human",reason:t||"Workflow Routing approved"})}catch{}console.log("[WorkflowEngine] Workflow Routing approved")}setupInterruptHandler(){this.interruptHandler=async()=>{console.log(`
1142
+ [WorkflowEngine] Workflow interrupted - saving checkpoint...`);try{let t=await I(this.projectPath,this.workflowId);t&&(t.status="paused",t.updated_at=new Date().toISOString(),t.resume_context={...t.resume_context,interrupted_at:new Date().toISOString(),current_stage:t.current_stage,message:`Workflow interrupted during ${t.current_stage} stage`},await A(this.projectPath,t),console.log("[WorkflowEngine] Checkpoint saved. Resume with `/continue`"))}catch(t){console.error("[WorkflowEngine] Failed to save checkpoint on interrupt:",t)}process.exit(0)},process.on("SIGINT",this.interruptHandler)}cleanupInterruptHandler(){this.interruptHandler&&(process.off("SIGINT",this.interruptHandler),this.interruptHandler=null)}async executeIntentStage(t){let n=t.resume_context?.initial_prompt||"No initial prompt provided";console.log(`[WorkflowEngine] Executing INTENT stage for feature: ${this.featureName}`),console.log(`[WorkflowEngine] Initial prompt: ${n}`),console.log("[WorkflowEngine] Generating merged INTENT artifact with full inception content");let r=`intent-${this.workflowId}`,o=new Date().toISOString(),s=`---
1143
1143
  id: ${r}
1144
1144
  title: ${this.featureName}
1145
1145
  status: draft
@@ -1340,7 +1340,7 @@ created: ${o}
1340
1340
 
1341
1341
  ---
1342
1342
  *Generated by WorkflowEngine based on ${r}*
1343
- `;await Xn(this.projectPath,this.workflowId,"nfr",a),console.log("[WorkflowEngine] Generated NFR artifact at inception/requirements/nfr.md");let c=lt(this.projectPath,this.workflowId,"intent");console.log(`[WorkflowEngine] Validating INTENT artifact at: ${c}`);let l=await Go(c);l.passed?(console.log("[WorkflowEngine] INTENT validation passed"),console.log(`[WorkflowEngine] Coverage: ${l.coverage_percentage}%`)):(console.log("[WorkflowEngine] INTENT validation failed:",l.blocking_issues),console.log(`[WorkflowEngine] Coverage: ${l.coverage_percentage}%`));let u=await I(this.projectPath,this.workflowId);if(u){let d=u;d.interview_progress={stage:"intent",questions_asked:0,draft_artifact_path:c},u.updated_at=new Date().toISOString(),await O(this.projectPath,u)}}async executeUnitStage(t){throw console.log(`[WorkflowEngine] Executing UNIT stage for feature: ${this.featureName}`),new Error("UNIT stage execution not yet implemented")}async executeCodeGenerationStage(t){throw console.log(`[WorkflowEngine] Executing CODE-GENERATION stage for feature: ${this.featureName}`),new Error("Code generation stage execution not yet implemented")}};me();var kg={intent:null,unit:null,"code-generation":null,complete:null};function _g(e){switch(e){case"intent":return"capture the problem statement, personas, success metrics, constraints, and define business requirements, technical approach, and proposed UNITs";case"unit":return"decompose into module-scoped UNITs with interface contracts";case"code-generation":return"generate code from the approved code plan";case"complete":return"finalize and validate all workflow artifacts";default:return"proceed with the next stage"}}function Sg(e,t,n=!1){let r=t.current_stage,o=kg[r],s=_g(r),i=`You are beginning a structured workflow for feature: ${e}
1343
+ `;await Xn(this.projectPath,this.workflowId,"nfr",a),console.log("[WorkflowEngine] Generated NFR artifact at inception/requirements/nfr.md");let c=lt(this.projectPath,this.workflowId,"intent");console.log(`[WorkflowEngine] Validating INTENT artifact at: ${c}`);let l=await Bo(c);l.passed?(console.log("[WorkflowEngine] INTENT validation passed"),console.log(`[WorkflowEngine] Coverage: ${l.coverage_percentage}%`)):(console.log("[WorkflowEngine] INTENT validation failed:",l.blocking_issues),console.log(`[WorkflowEngine] Coverage: ${l.coverage_percentage}%`));let u=await I(this.projectPath,this.workflowId);if(u){let d=u;d.interview_progress={stage:"intent",questions_asked:0,draft_artifact_path:c},u.updated_at=new Date().toISOString(),await A(this.projectPath,u)}}async executeUnitStage(t){throw console.log(`[WorkflowEngine] Executing UNIT stage for feature: ${this.featureName}`),new Error("UNIT stage execution not yet implemented")}async executeCodeGenerationStage(t){throw console.log(`[WorkflowEngine] Executing CODE-GENERATION stage for feature: ${this.featureName}`),new Error("Code generation stage execution not yet implemented")}};le();var Tg={intent:null,unit:null,"code-generation":null,complete:null};function Eg(e){switch(e){case"intent":return"capture the problem statement, personas, success metrics, constraints, and define business requirements, technical approach, and proposed UNITs";case"unit":return"decompose into module-scoped UNITs with interface contracts";case"code-generation":return"generate code from the approved code plan";case"complete":return"finalize and validate all workflow artifacts";default:return"proceed with the next stage"}}function Cg(e,t,n=!1){let r=t.current_stage,o=Tg[r],s=Eg(r),i=`You are beginning a structured workflow for feature: ${e}
1344
1344
 
1345
1345
  `;return i+=`Current stage: ${r}
1346
1346
  `,i+=`Status: ${t.status}
@@ -1351,7 +1351,7 @@ created: ${o}
1351
1351
  `):i+=`Next step: ${s}
1352
1352
  `,n&&(i+=`
1353
1353
  IMPORTANT: This is a BRAND NEW workflow just initialized. `,i+="Do NOT treat this as a resumed or existing workflow. ",i+=`Proceed with workspace detection as the first step.
1354
- `),i}function vg(e,t){let n=t.current_stage,r=kg[n],o=_g(n),s=`Resuming workflow for feature: ${e}
1354
+ `),i}function Rg(e,t){let n=t.current_stage,r=Tg[n],o=Eg(n),s=`Resuming workflow for feature: ${e}
1355
1355
 
1356
1356
  `;return s+=`You were interrupted during: ${n}
1357
1357
  `,s+=`Last update: ${t.updated_at}
@@ -1364,17 +1364,17 @@ IMPORTANT: This is a BRAND NEW workflow just initialized. `,i+="Do NOT treat thi
1364
1364
 
1365
1365
  `,s+=`Use: Task(subagent_type="${r}", prompt="...")
1366
1366
  `):s+=`Continue from where you left off: ${o}
1367
- `,s}function Ha(e){return e.prompt?e.prompt:e.message?.content?e.message.content:e.parts?e.parts.filter(t=>t.type==="text"&&t.text).map(t=>t.text).join(" "):""}function Tg(){P({name:"structuredWorkflowDetector",event:"UserPromptSubmit",priority:8,handler:async e=>{let t=Ha(e);if(!t||!e.directory)return{continue:!0};let n=t.match(/^\/plan\s+(?!continue\b|--)([\s\S]+?)$/i),r=t.match(/^\/plan\s+continue$/i);if(n){let o=n[1].trim();o=o.replace(/\s+--structured\s*/i,"").trim();let s,i=o.match(/\s+--depth\s+(shallow|medium|deep)\s*$/i);i&&(s=i[1].toLowerCase(),o=o.replace(i[0],"").trim());let a,c=o.match(/\s+--(brownfield|greenfield)\s*$/i);if(c&&(a=c[1].toLowerCase(),o=o.replace(c[0],"").trim()),o.length>120)return console.error("[Structured Workflow] Feature name too long, likely not a real feature name:",o.substring(0,50)+"..."),{continue:!0};if(/\b(lets|let's|please|proceed|creating|we should|i want to|i need to|going to)\b/i.test(o))return console.error("[Structured Workflow] Feature name looks like conversational text, skipping:",o.substring(0,50)+"..."),{continue:!0};try{await new ks(e.directory,o).start(o);let d=Ba(o),p=await I(e.directory,d);if(!p)return{continue:!0};let f=Sg(o,p,!0),g=`${`[Workflow: ${d} | Phase: ${p.current_phase||"inception"} | Stage: ${p.current_stage||"intent"}]`}
1367
+ `,s}function Ka(e){return e.prompt?e.prompt:e.message?.content?e.message.content:e.parts?e.parts.filter(t=>t.type==="text"&&t.text).map(t=>t.text).join(" "):""}function xg(){P({name:"structuredWorkflowDetector",event:"UserPromptSubmit",priority:8,handler:async e=>{let t=Ka(e);if(!t||!e.directory)return{continue:!0};let n=t.match(/^\/plan\s+(?!continue\b|--)([\s\S]+?)$/i),r=t.match(/^\/plan\s+continue$/i);if(n){let o=n[1].trim();o=o.replace(/\s+--structured\s*/i,"").trim();let s,i=o.match(/\s+--depth\s+(shallow|medium|deep)\s*$/i);i&&(s=i[1].toLowerCase(),o=o.replace(i[0],"").trim());let a,c=o.match(/\s+--(brownfield|greenfield)\s*$/i);if(c&&(a=c[1].toLowerCase(),o=o.replace(c[0],"").trim()),o.length>120)return console.error("[Structured Workflow] Feature name too long, likely not a real feature name:",o.substring(0,50)+"..."),{continue:!0};if(/\b(lets|let's|please|proceed|creating|we should|i want to|i need to|going to)\b/i.test(o))return console.error("[Structured Workflow] Feature name looks like conversational text, skipping:",o.substring(0,50)+"..."),{continue:!0};try{await new Ss(e.directory,o).start(o);let d=Ya(o),p=await I(e.directory,d);if(!p)return{continue:!0};let f=Cg(o,p,!0),g=`${`[Workflow: ${d} | Phase: ${p.current_phase||"inception"} | Stage: ${p.current_stage||"intent"}]`}
1368
1368
 
1369
1369
  ${f}`;return s&&(g+=`
1370
1370
 
1371
1371
  Depth override: ${s}`),a&&(g+=`
1372
1372
 
1373
- Project type: ${a}`),{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:g}}}catch(u){return console.error("[Structured Workflow]",u),{continue:!0}}}if(r)try{let o=await oe(e.directory);if(o.length===0)return{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:"No active workflows found. Use `/plan {feature}` to start a new workflow."}};let s=o[0],i=await I(e.directory,s);if(!i)return{continue:!0};let a=vg(i.feature_name,i);return{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:`[TIP: For full AIDLC resume with behavioral rules, use /continue instead of /plan continue]
1373
+ Project type: ${a}`),{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:g}}}catch(u){return console.error("[Structured Workflow]",u),{continue:!0}}}if(r)try{let o=await oe(e.directory);if(o.length===0)return{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:"No active workflows found. Use `/plan {feature}` to start a new workflow."}};let s=o[0],i=await I(e.directory,s);if(!i)return{continue:!0};let a=Rg(i.feature_name,i);return{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:`[TIP: For full AIDLC resume with behavioral rules, use /continue instead of /plan continue]
1374
1374
 
1375
1375
  ${`[Workflow: ${s} | Phase: ${i.current_phase||"inception"} | Stage: ${i.current_stage||"intent"}]`}
1376
1376
 
1377
- ${a}`}}}catch(o){return console.error("[Workflow Resume]",o),{continue:!0}}return{continue:!0}}}),P({name:"keywordDetector",event:"UserPromptSubmit",priority:10,handler:e=>{let t=Ha(e);if(!t)return{continue:!0};let n=kl(t),r=_l(n);if(r.length===0)return{continue:!0};let o=r.some(c=>c.type==="ultrawork"),s=r.some(c=>c.type==="ultrathink"),i=r.some(c=>c.type==="search"),a=r.some(c=>c.type==="analyze");return o?(Wl(t,e.sessionId,e.directory||process.cwd()),{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:ql}}):s?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:Yl}}:i?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:Kl}}:a?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:Jl}}:{continue:!0}}}),P({name:"autoSlashCommand",event:"UserPromptSubmit",priority:20,handler:e=>{if(!e.parts)return{continue:!0};let n=Al().processMessage({sessionId:e.sessionId||""},e.parts);return n.detected&&n.injectedMessage?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:n.injectedMessage}}:{continue:!0}}}),P({name:"thinkMode",event:"UserPromptSubmit",priority:30,handler:e=>{if(!e.message||!e.parts)return{continue:!0};let t=Ll(),n=e.sessionId||"default",r={parts:e.parts,message:{model:e.message.model&&e.message.model.providerId&&e.message.model.modelId?{providerId:e.message.model.providerId,modelId:e.message.model.modelId}:void 0}},o=t.processChatParams(n,r);return o.requested&&o.modelSwitched?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:"[Think Mode Activated] Switched to high-reasoning model variant."}}:{continue:!0}}}),P({name:"learningFeedbackCapture",event:"UserPromptSubmit",priority:100,handler:async e=>{let t=Ha(e);return!t||!e.directory?{continue:!0}:(Promise.resolve().then(async()=>{try{await Su({prompt:t,directory:e.directory,sessionId:e.sessionId}),await Tu({prompt:t,directory:e.directory,sessionId:e.sessionId})}catch(n){console.error("[Olympus Learning]",n)}}),{continue:!0})}})}var Va=require("child_process");var sC="mcpProcessCleanup",iC=/mcp/i;function aC(e){return e?iC.test(e):!1}function cC(e,t){return e.filter(n=>aC(n.CommandLine)?!t.has(n.ParentProcessId):!1)}function lC(e){let t=0;for(let n of e)try{(0,Va.execSync)(`taskkill /T /F /PID ${n.ProcessId}`,{encoding:"utf8",timeout:5e3,stdio:"pipe"}),t++}catch{}return t}function uC(){if(process.platform!=="win32")return 0;try{let e=`
1377
+ ${a}`}}}catch(o){return console.error("[Workflow Resume]",o),{continue:!0}}return{continue:!0}}}),P({name:"keywordDetector",event:"UserPromptSubmit",priority:10,handler:e=>{let t=Ka(e);if(!t)return{continue:!0};let n=bl(t),r=Tl(n);if(r.length===0)return{continue:!0};let o=r.some(c=>c.type==="ultrawork"),s=r.some(c=>c.type==="ultrathink"),i=r.some(c=>c.type==="search"),a=r.some(c=>c.type==="analyze");return o?(Vl(t,e.sessionId,e.directory||process.cwd()),{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:zl}}):s?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:Ql}}:i?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:Xl}}:a?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:Zl}}:{continue:!0}}}),P({name:"autoSlashCommand",event:"UserPromptSubmit",priority:20,handler:e=>{if(!e.parts)return{continue:!0};let n=Nl().processMessage({sessionId:e.sessionId||""},e.parts);return n.detected&&n.injectedMessage?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:n.injectedMessage}}:{continue:!0}}}),P({name:"thinkMode",event:"UserPromptSubmit",priority:30,handler:e=>{if(!e.message||!e.parts)return{continue:!0};let t=Gl(),n=e.sessionId||"default",r={parts:e.parts,message:{model:e.message.model&&e.message.model.providerId&&e.message.model.modelId?{providerId:e.message.model.providerId,modelId:e.message.model.modelId}:void 0}},o=t.processChatParams(n,r);return o.requested&&o.modelSwitched?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:"[Think Mode Activated] Switched to high-reasoning model variant."}}:{continue:!0}}}),P({name:"learningFeedbackCapture",event:"UserPromptSubmit",priority:100,handler:async e=>{let t=Ka(e);return!t||!e.directory?{continue:!0}:(Promise.resolve().then(async()=>{try{await Eu({prompt:t,directory:e.directory,sessionId:e.sessionId}),await Ru({prompt:t,directory:e.directory,sessionId:e.sessionId})}catch(n){console.error("[Olympus Learning]",n)}}),{continue:!0})}})}var Ja=require("child_process");var _C="mcpProcessCleanup",kC=/mcp/i;function SC(e){return e?kC.test(e):!1}function vC(e,t){return e.filter(n=>SC(n.CommandLine)?!t.has(n.ParentProcessId):!1)}function bC(e){let t=0;for(let n of e)try{(0,Ja.execSync)(`taskkill /T /F /PID ${n.ProcessId}`,{encoding:"utf8",timeout:5e3,stdio:"pipe"}),t++}catch{}return t}function TC(){if(process.platform!=="win32")return 0;try{let e=`
1378
1378
  $nodeProcs = Get-CimInstance Win32_Process -Filter "Name='node.exe'" |
1379
1379
  Select-Object ProcessId, ParentProcessId, CommandLine;
1380
1380
  $allPids = (Get-Process -ErrorAction SilentlyContinue).Id;
@@ -1382,7 +1382,7 @@ ${a}`}}}catch(o){return console.error("[Workflow Resume]",o),{continue:!0}}retur
1382
1382
  nodeProcesses = @($nodeProcs | ForEach-Object { @{ ProcessId=$_.ProcessId; ParentProcessId=$_.ParentProcessId; CommandLine=$_.CommandLine } });
1383
1383
  allPids = @($allPids)
1384
1384
  } | ConvertTo-Json -Depth 3
1385
- `.replace(/\n/g," "),t=(0,Va.execSync)(`powershell -NoProfile -Command "${e}"`,{encoding:"utf8",timeout:15e3,stdio:["pipe","pipe","pipe"]}),n=JSON.parse(t),r=Array.isArray(n.nodeProcesses)?n.nodeProcesses:n.nodeProcesses?[n.nodeProcesses]:[],o=new Set(Array.isArray(n.allPids)?n.allPids:n.allPids?[n.allPids]:[]),s=cC(r,o);return s.length===0?0:lC(s)}catch(e){return console.error("[Olympus MCP Cleanup] Error:",e),0}}function Eg(){P({name:sC,event:"SessionStart",priority:1,handler:e=>{let t=uC();return t>0?{continue:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:`[MCP Cleanup] Removed ${t} orphaned MCP server process${t===1?"":"es"} from previous session(s).`}}:{continue:!0}}})}var Dn=require("fs"),un=require("path"),bg=require("os");function dC(e,t){let n=(0,un.join)((0,bg.homedir)(),".claude"),r=[];e&&(r.push((0,un.join)(n,"sessions",e,"todos.json")),r.push((0,un.join)(n,"todos",`${e}.json`))),t&&(r.push((0,un.join)(t,".olympus","todos.json")),r.push((0,un.join)(t,".claude","todos.json")));let o=(0,un.join)(n,"todos");if((0,Dn.existsSync)(o))try{let s=(0,Dn.readdirSync)(o);for(let i of s)i.endsWith(".json")&&r.push((0,un.join)(o,i))}catch{}return r}function pC(e){try{let t=(0,Dn.readFileSync)(e,"utf-8"),n=JSON.parse(t);return Array.isArray(n)?n.filter(r=>r&&typeof r.content=="string"&&typeof r.status=="string"):n.todos&&Array.isArray(n.todos)?n.todos.filter(r=>{let o=r;return o&&typeof o.content=="string"&&typeof o.status=="string"}):[]}catch{return[]}}function fC(e){return e.status!=="completed"&&e.status!=="cancelled"}async function to(e,t){let n=dC(e,t),r=new Set,o=[],s=[];for(let i of n){if(!(0,Dn.existsSync)(i))continue;let a=pC(i);for(let c of a){let l=`${c.content}:${c.status}`;r.has(l)||(r.add(l),o.push(c),fC(c)&&s.push(c))}}return{count:s.length,todos:s,total:o.length}}function Cg(e){let t=e.todos.find(n=>n.status==="in_progress");return t||(e.todos.find(n=>n.status==="pending")??null)}var qa=require("path");we();Yo();we();function Rg(e,t=5){return(e.token_efficiency?.invocation_count??0)>=t}vi();var xg=500;function Pg(e){let t=ke((0,qa.join)(de(),"user-preferences.json"),null),n=ke((0,qa.join)(kt(e),"patterns.json"),null),r=Vn(),o=Vn(e),s={...r,...o},i=[];if(t&&mC(t)){let u=t.explicit_rules.filter(p=>!p.project_path||p.project_path===e),d={...t,explicit_rules:u};i.push(gC(d))}n&&(n.conventions.length>0||n.tech_stack.length>0||n.learned_rules&&n.learned_rules.length>0||n.common_mistakes&&n.common_mistakes.length>0)&&i.push(hC(n)),t?.recurring_corrections&&t.recurring_corrections.length>0&&i.push(yC(t.recurring_corrections.slice(0,5)));let a=Object.values(s).filter(u=>u.weak_areas.length>0);a.length>0&&i.push(wC(a));let c=kC(s);if(c&&i.push(c),i.length===0)return"";let l=`<learned-context>
1385
+ `.replace(/\n/g," "),t=(0,Ja.execSync)(`powershell -NoProfile -Command "${e}"`,{encoding:"utf8",timeout:15e3,stdio:["pipe","pipe","pipe"]}),n=JSON.parse(t),r=Array.isArray(n.nodeProcesses)?n.nodeProcesses:n.nodeProcesses?[n.nodeProcesses]:[],o=new Set(Array.isArray(n.allPids)?n.allPids:n.allPids?[n.allPids]:[]),s=vC(r,o);return s.length===0?0:bC(s)}catch(e){return console.error("[Olympus MCP Cleanup] Error:",e),0}}function Pg(){P({name:_C,event:"SessionStart",priority:1,handler:e=>{let t=TC();return t>0?{continue:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:`[MCP Cleanup] Removed ${t} orphaned MCP server process${t===1?"":"es"} from previous session(s).`}}:{continue:!0}}})}var Dn=require("fs"),un=require("path"),Ag=require("os");function EC(e,t){let n=(0,un.join)((0,Ag.homedir)(),".claude"),r=[];e&&(r.push((0,un.join)(n,"sessions",e,"todos.json")),r.push((0,un.join)(n,"todos",`${e}.json`))),t&&(r.push((0,un.join)(t,".olympus","todos.json")),r.push((0,un.join)(t,".claude","todos.json")));let o=(0,un.join)(n,"todos");if((0,Dn.existsSync)(o))try{let s=(0,Dn.readdirSync)(o);for(let i of s)i.endsWith(".json")&&r.push((0,un.join)(o,i))}catch{}return r}function CC(e){try{let t=(0,Dn.readFileSync)(e,"utf-8"),n=JSON.parse(t);return Array.isArray(n)?n.filter(r=>r&&typeof r.content=="string"&&typeof r.status=="string"):n.todos&&Array.isArray(n.todos)?n.todos.filter(r=>{let o=r;return o&&typeof o.content=="string"&&typeof o.status=="string"}):[]}catch{return[]}}function RC(e){return e.status!=="completed"&&e.status!=="cancelled"}async function to(e,t){let n=EC(e,t),r=new Set,o=[],s=[];for(let i of n){if(!(0,Dn.existsSync)(i))continue;let a=CC(i);for(let c of a){let l=`${c.content}:${c.status}`;r.has(l)||(r.add(l),o.push(c),RC(c)&&s.push(c))}}return{count:s.length,todos:s,total:o.length}}function Ig(e){let t=e.todos.find(n=>n.status==="in_progress");return t||(e.todos.find(n=>n.status==="pending")??null)}var za=require("path");we();Qo();we();function Og(e,t=5){return(e.token_efficiency?.invocation_count??0)>=t}Ti();var $g=500;function Dg(e){let t=_e((0,za.join)(pe(),"user-preferences.json"),null),n=_e((0,za.join)(_t(e),"patterns.json"),null),r=Vn(),o=Vn(e),s={...r,...o},i=[];if(t&&xC(t)){let u=t.explicit_rules.filter(p=>!p.project_path||p.project_path===e),d={...t,explicit_rules:u};i.push(PC(d))}n&&(n.conventions.length>0||n.tech_stack.length>0||n.learned_rules&&n.learned_rules.length>0||n.common_mistakes&&n.common_mistakes.length>0)&&i.push(AC(n)),t?.recurring_corrections&&t.recurring_corrections.length>0&&i.push(IC(t.recurring_corrections.slice(0,5)));let a=Object.values(s).filter(u=>u.weak_areas.length>0);a.length>0&&i.push(OC(a));let c=$C(s);if(c&&i.push(c),i.length===0)return"";let l=`<learned-context>
1386
1386
 
1387
1387
  ${i.join(`
1388
1388
 
@@ -1392,21 +1392,21 @@ ${i.join(`
1392
1392
 
1393
1393
  ---
1394
1394
 
1395
- `;return l.length>xg*4?l.substring(0,xg*4)+`
1395
+ `;return l.length>$g*4?l.substring(0,$g*4)+`
1396
1396
  ...</learned-context>
1397
1397
 
1398
1398
  ---
1399
1399
 
1400
- `:l}function mC(e){return e.verbosity!=="unknown"||e.autonomy!=="unknown"||e.explicit_rules.length>0||e.inferred_preferences.length>0}function gC(e){let t=["## User Preferences"];e.verbosity!=="unknown"&&t.push(`- Verbosity: ${e.verbosity}`),e.autonomy!=="unknown"&&t.push(`- Autonomy: ${e.autonomy}`);for(let n of e.explicit_rules.slice(0,5)){let r=typeof n=="string"?n:n.rule;t.push(`- ${r}`)}return t.join(`
1401
- `)}function hC(e){let t=["## Project Conventions"];for(let n of e.conventions.slice(0,5))t.push(`- ${n}`);if(e.tech_stack.length>0&&t.push(`- Tech: ${e.tech_stack.join(", ")}`),e.learned_rules&&e.learned_rules.length>0)for(let n of e.learned_rules.slice(0,3))t.push(`- Rule: ${n}`);if(e.common_mistakes&&e.common_mistakes.length>0)for(let n of e.common_mistakes.slice(0,3))t.push(`- Watch out: ${n}`);return t.join(`
1402
- `)}function yC(e){let t=["## Avoid These Mistakes"];for(let n of e)t.push(`- ${n.pattern} (${n.count}x)`);return t.join(`
1403
- `)}function wC(e){let t=["## Agent Notes"];for(let n of e.slice(0,3))t.push(`- ${n.agent_name}: struggles with ${n.weak_areas.join(", ")}`);return t.join(`
1404
- `)}function kC(e){let t=Object.values(e).filter(a=>a.token_efficiency&&Rg(a)).sort((a,c)=>{let l=a.token_efficiency?.efficiency_score??0;return(c.token_efficiency?.efficiency_score??0)-l});if(t.length===0)return"";let n=[];n.push("<olympus-efficiency>"),n.push("AGENT EFFICIENCY (success%/avg tokens):");for(let a of t.slice(0,3)){let c=Math.round(a.success_rate*100),l=a.token_efficiency.avg_tokens_per_success,u=l>=1e3?`${(l/1e3).toFixed(1)}k`:`${Math.round(l)}`,p=a.success_rate>=.9&&a.token_efficiency.efficiency_score>.8?" [PREFERRED]":"";n.push(`- ${a.agent_name}: ${c}%/${u}${p}`)}let r=wn(),o=r>=1e3?`${(r/1e3).toFixed(0)}k`:r.toString(),s=Math.round(r*1.5),i=s>=1e3?`${(s/1e3).toFixed(0)}k`:s.toString();return n.push(""),n.push(`SESSION BUDGET: ~${o} baseline | warn at ${i}`),n.push("PATTERNS: Parallel reads save 40%"),n.push(""),n.push("Quality remains priority. Use efficiency as tiebreaker."),n.push("</olympus-efficiency>"),n.join(`
1405
- `)}function Ig(e){if(e.length===0)return"";let t=["## Agent Discoveries"];t.push(""),t.push("These insights were discovered during previous work:"),t.push("");for(let n of e.slice(0,5))t.push(`- **${n.category}**: ${n.summary}`),t.push(` ${n.details.substring(0,200)}`);return t.join(`
1406
- `)}Gt();Ge();var $g=T(require("path"),1);me();Z();var pt=T(require("path"),1),Ss=T(X(),1);Z();me();cn();async function vs(e){try{let t=await oe(e);if(t.length===0)return null;let n=t[0],r=pt.join(e,"aidlc-docs",n,"manifest.json"),o=W(r);if(!o)return null;let s=await I(e,n);if(!s)return null;let i=be(e),a=_C(o),l=Vi(o,"fulfilled").map(p=>p.id),d=Sn(o).filter(p=>p.contract_status!=="fulfilled").map(p=>p.id);return{workflowId:s.workflow_id,featureName:s.feature_name,currentPhase:s.current_phase,currentStage:s.current_stage,manifest:o,checkpoint:s,trustLevel:i.current_level,riskTier:s.risk_tier??0,depthScore:s.depth_score??0,pendingBolts:a,completedBolts:l,pendingUnits:d,executionMode:s.execution_mode??"manual"}}catch(t){return console.error("[WorkflowBridge] Failed to detect active workflow:",t),null}}function _C(e){return Et(e).filter(n=>n.contract_status!=="fulfilled").map(n=>n.id)}function SC(e){let t=Sn(e),n=Et(e),r=[...t].sort((a,c)=>a.id.localeCompare(c.id)),o=[],s=new Set;for(let a of r){let l=[...Et(e,a.id)].sort((u,d)=>u.id.localeCompare(d.id));for(let u of l)o.push(u.id),s.add(u.id)}let i=n.filter(a=>!s.has(a.id)).sort((a,c)=>a.id.localeCompare(c.id));for(let a of i)o.push(a.id);return o}function ro(e){let t=Et(e),n=t.length;if(n===0)return{completed:0,total:0,percentage:0};let r=t.filter(s=>s.contract_status==="fulfilled").length,o=Math.round(r/n*100);return{completed:r,total:n,percentage:o}}function no(e,t){try{if(!Ss.existsSync(e))return t;let r=Ss.readFileSync(e,"utf-8").split(`
1407
- `);for(let o of r){let s=o.trim();if(s.startsWith("# "))return s.slice(2).trim()}return t}catch{return t}}function _s(e,t){return e.links.find(r=>r.target_id===t&&(r.link_type==="derives"||r.link_type==="implements"))?.source_id??null}function vC(e){let t=e.toLowerCase(),n=["ui","component","frontend","style","css","layout","page","view"];for(let r of n)if(t.includes(r))return"frontend-engineer";return"olympian"}async function Ag(e){try{let t=await vs(e);if(!t)return"";let n=ro(t.manifest),r=Et(t.manifest),o=[];for(let a of t.pendingBolts){if(!r.find(f=>f.id===a))continue;let l=_s(t.manifest,a),u=l?pt.join(e,"aidlc-docs",t.workflowId,"construction",l,`${a}.md`):pt.join(e,"aidlc-docs",t.workflowId,"construction",`${a}.md`),d=no(u,a),p=l?` (${l})`:"";o.push(`- ${a} "${d}"${p}`)}let s=[];for(let a of t.completedBolts){if(!r.find(p=>p.id===a))continue;let l=_s(t.manifest,a),u=l?pt.join(e,"aidlc-docs",t.workflowId,"construction",l,`${a}.md`):pt.join(e,"aidlc-docs",t.workflowId,"construction",`${a}.md`),d=no(u,a);s.push(`- ${a} "${d}" done`)}let i=["## Active Workflow",`Workflow: ${t.featureName} (${t.workflowId})`,`Phase: ${t.currentPhase} | Stage: ${t.currentStage}`,`Trust: Level ${t.trustLevel} | Risk: Tier ${t.riskTier} | Depth: ${t.depthScore}`,`Mode: ${t.executionMode}`,"","### Progress",`BOLTs: ${n.completed}/${n.total} (${n.percentage}%)`];return o.length>0&&(i.push("","### Pending BOLTs:"),i.push(...o)),s.length>0&&(i.push("","### Completed BOLTs:"),i.push(...s)),i.join(`
1408
- `)}catch(t){return console.error("[WorkflowBridge] Failed to generate workflow summary:",t),""}}async function Og(e){try{let t=await vs(e);if(!t)return"";let n=Et(t.manifest),r=SC(t.manifest),o=new Set(t.pendingBolts),s=Sn(t.manifest),i=[],a=1;for(let u of r){if(!o.has(u))continue;let d=n.find(w=>w.id===u);if(!d)continue;let p=_s(t.manifest,u),f=p?pt.join(e,"aidlc-docs",t.workflowId,"construction",p,`${u}.md`):pt.join(e,"aidlc-docs",t.workflowId,"construction",`${u}.md`),m=no(f,u),g=vC(d.path),y="";if(p){let w=s.find(v=>v.id===p),k=pt.join(e,"aidlc-docs",t.workflowId,"construction",p,"spec.md"),h=no(k,p);y=` (${p}: ${h})`}i.push(`${a}. ${u} "${m}"${y}`),i.push(` Agent: ${g} | Files: ${d.path}`),a++}let c=[];for(let u of t.completedBolts){if(!n.find(g=>g.id===u))continue;let p=_s(t.manifest,u),f=p?pt.join(e,"aidlc-docs",t.workflowId,"construction",p,`${u}.md`):pt.join(e,"aidlc-docs",t.workflowId,"construction",`${u}.md`),m=no(f,u);c.push(`- ${u} "${m}" done (fulfilled)`)}let l=["## Workflow Execution Plan",`Workflow: ${t.featureName} (${t.workflowId})`,`Phase: ${t.currentPhase} | Trust: Level ${t.trustLevel} | Risk: Tier ${t.riskTier}`];return i.length>0&&(l.push("","### Pending BOLTs (execute in this order):"),l.push(...i)),c.length>0&&(l.push("","### Completed BOLTs:"),l.push(...c)),l.push("","### Instructions:"),l.push("For each pending BOLT: read its spec file, dispatch to the listed agent, then present Gate 4 review."),l.join(`
1409
- `)}catch(t){return console.error("[WorkflowBridge] Failed to generate bolt execution plan:",t),""}}async function Dg(e){let t=[];try{let n=await oe(e);for(let r of n){let o=await I(e,r);if(!o||o.status==="complete"||o.status==="archived")continue;let s=$g.join(e,"aidlc-docs",r,"manifest.json"),i=W(s),a={completed:0,total:0};i&&(a=ro(i)),t.push({workflowId:o.workflow_id,featureName:o.feature_name,currentPhase:o.current_phase,currentStage:o.current_stage,progress:a,lastActivity:o.updated_at,status:o.status,interviewProgress:o.interview_progress})}}catch(n){console.error("[ResumeDetector] Error checking aidlc-docs:",n)}return t}cn();function Ng(){Eg(),P({name:"learnedContextInjection",event:"SessionStart",priority:5,handler:e=>{if(!e.directory)return{continue:!0};try{let t=Pg(e.directory),n=ms(e.directory,5),r=Ig(n),o=new Date,s=new Date(o.getTime()-1440*60*1e3);for(let c of n)try{new Date(c.last_useful)<s&&Gm(c.id,e.directory)}catch(l){console.error("[Olympus Learning] Failed to mark discovery as useful:",l)}return{continue:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:`<olympus-mode>
1400
+ `:l}function xC(e){return e.verbosity!=="unknown"||e.autonomy!=="unknown"||e.explicit_rules.length>0||e.inferred_preferences.length>0}function PC(e){let t=["## User Preferences"];e.verbosity!=="unknown"&&t.push(`- Verbosity: ${e.verbosity}`),e.autonomy!=="unknown"&&t.push(`- Autonomy: ${e.autonomy}`);for(let n of e.explicit_rules.slice(0,5)){let r=typeof n=="string"?n:n.rule;t.push(`- ${r}`)}return t.join(`
1401
+ `)}function AC(e){let t=["## Project Conventions"];for(let n of e.conventions.slice(0,5))t.push(`- ${n}`);if(e.tech_stack.length>0&&t.push(`- Tech: ${e.tech_stack.join(", ")}`),e.learned_rules&&e.learned_rules.length>0)for(let n of e.learned_rules.slice(0,3))t.push(`- Rule: ${n}`);if(e.common_mistakes&&e.common_mistakes.length>0)for(let n of e.common_mistakes.slice(0,3))t.push(`- Watch out: ${n}`);return t.join(`
1402
+ `)}function IC(e){let t=["## Avoid These Mistakes"];for(let n of e)t.push(`- ${n.pattern} (${n.count}x)`);return t.join(`
1403
+ `)}function OC(e){let t=["## Agent Notes"];for(let n of e.slice(0,3))t.push(`- ${n.agent_name}: struggles with ${n.weak_areas.join(", ")}`);return t.join(`
1404
+ `)}function $C(e){let t=Object.values(e).filter(a=>a.token_efficiency&&Og(a)).sort((a,c)=>{let l=a.token_efficiency?.efficiency_score??0;return(c.token_efficiency?.efficiency_score??0)-l});if(t.length===0)return"";let n=[];n.push("<olympus-efficiency>"),n.push("AGENT EFFICIENCY (success%/avg tokens):");for(let a of t.slice(0,3)){let c=Math.round(a.success_rate*100),l=a.token_efficiency.avg_tokens_per_success,u=l>=1e3?`${(l/1e3).toFixed(1)}k`:`${Math.round(l)}`,p=a.success_rate>=.9&&a.token_efficiency.efficiency_score>.8?" [PREFERRED]":"";n.push(`- ${a.agent_name}: ${c}%/${u}${p}`)}let r=wn(),o=r>=1e3?`${(r/1e3).toFixed(0)}k`:r.toString(),s=Math.round(r*1.5),i=s>=1e3?`${(s/1e3).toFixed(0)}k`:s.toString();return n.push(""),n.push(`SESSION BUDGET: ~${o} baseline | warn at ${i}`),n.push("PATTERNS: Parallel reads save 40%"),n.push(""),n.push("Quality remains priority. Use efficiency as tiebreaker."),n.push("</olympus-efficiency>"),n.join(`
1405
+ `)}function Ng(e){if(e.length===0)return"";let t=["## Agent Discoveries"];t.push(""),t.push("These insights were discovered during previous work:"),t.push("");for(let n of e.slice(0,5))t.push(`- **${n.category}**: ${n.summary}`),t.push(` ${n.details.substring(0,200)}`);return t.join(`
1406
+ `)}Ut();Be();var Mg=b(require("path"),1);le();Z();var pt=b(require("path"),1),bs=b(X(),1);Z();le();sn();async function Ts(e){try{let t=await oe(e);if(t.length===0)return null;let n=t[0],r=pt.join(e,"aidlc-docs",n,"manifest.json"),o=W(r);if(!o)return null;let s=await I(e,n);if(!s)return null;let i=Te(e),a=DC(o),l=Yi(o,"fulfilled").map(p=>p.id),d=Sn(o).filter(p=>p.contract_status!=="fulfilled").map(p=>p.id);return{workflowId:s.workflow_id,featureName:s.feature_name,currentPhase:s.current_phase,currentStage:s.current_stage,manifest:o,checkpoint:s,trustLevel:i.current_level,riskTier:s.risk_tier??0,depthScore:s.depth_score??0,pendingBolts:a,completedBolts:l,pendingUnits:d,executionMode:s.execution_mode??"manual"}}catch(t){return console.error("[WorkflowBridge] Failed to detect active workflow:",t),null}}function DC(e){return Tt(e).filter(n=>n.contract_status!=="fulfilled").map(n=>n.id)}function NC(e){let t=Sn(e),n=Tt(e),r=[...t].sort((a,c)=>a.id.localeCompare(c.id)),o=[],s=new Set;for(let a of r){let l=[...Tt(e,a.id)].sort((u,d)=>u.id.localeCompare(d.id));for(let u of l)o.push(u.id),s.add(u.id)}let i=n.filter(a=>!s.has(a.id)).sort((a,c)=>a.id.localeCompare(c.id));for(let a of i)o.push(a.id);return o}function ro(e){let t=Tt(e),n=t.length;if(n===0)return{completed:0,total:0,percentage:0};let r=t.filter(s=>s.contract_status==="fulfilled").length,o=Math.round(r/n*100);return{completed:r,total:n,percentage:o}}function no(e,t){try{if(!bs.existsSync(e))return t;let r=bs.readFileSync(e,"utf-8").split(`
1407
+ `);for(let o of r){let s=o.trim();if(s.startsWith("# "))return s.slice(2).trim()}return t}catch{return t}}function vs(e,t){return e.links.find(r=>r.target_id===t&&(r.link_type==="derives"||r.link_type==="implements"))?.source_id??null}function FC(e){let t=e.toLowerCase(),n=["ui","component","frontend","style","css","layout","page","view"];for(let r of n)if(t.includes(r))return"frontend-engineer";return"olympian"}async function Fg(e){try{let t=await Ts(e);if(!t)return"";let n=ro(t.manifest),r=Tt(t.manifest),o=[];for(let a of t.pendingBolts){if(!r.find(f=>f.id===a))continue;let l=vs(t.manifest,a),u=l?pt.join(e,"aidlc-docs",t.workflowId,"construction",l,`${a}.md`):pt.join(e,"aidlc-docs",t.workflowId,"construction",`${a}.md`),d=no(u,a),p=l?` (${l})`:"";o.push(`- ${a} "${d}"${p}`)}let s=[];for(let a of t.completedBolts){if(!r.find(p=>p.id===a))continue;let l=vs(t.manifest,a),u=l?pt.join(e,"aidlc-docs",t.workflowId,"construction",l,`${a}.md`):pt.join(e,"aidlc-docs",t.workflowId,"construction",`${a}.md`),d=no(u,a);s.push(`- ${a} "${d}" done`)}let i=["## Active Workflow",`Workflow: ${t.featureName} (${t.workflowId})`,`Phase: ${t.currentPhase} | Stage: ${t.currentStage}`,`Trust: Level ${t.trustLevel} | Risk: Tier ${t.riskTier} | Depth: ${t.depthScore}`,`Mode: ${t.executionMode}`,"","### Progress",`BOLTs: ${n.completed}/${n.total} (${n.percentage}%)`];return o.length>0&&(i.push("","### Pending BOLTs:"),i.push(...o)),s.length>0&&(i.push("","### Completed BOLTs:"),i.push(...s)),i.join(`
1408
+ `)}catch(t){return console.error("[WorkflowBridge] Failed to generate workflow summary:",t),""}}async function jg(e){try{let t=await Ts(e);if(!t)return"";let n=Tt(t.manifest),r=NC(t.manifest),o=new Set(t.pendingBolts),s=Sn(t.manifest),i=[],a=1;for(let u of r){if(!o.has(u))continue;let d=n.find(w=>w.id===u);if(!d)continue;let p=vs(t.manifest,u),f=p?pt.join(e,"aidlc-docs",t.workflowId,"construction",p,`${u}.md`):pt.join(e,"aidlc-docs",t.workflowId,"construction",`${u}.md`),m=no(f,u),g=FC(d.path),y="";if(p){let w=s.find(v=>v.id===p),_=pt.join(e,"aidlc-docs",t.workflowId,"construction",p,"spec.md"),h=no(_,p);y=` (${p}: ${h})`}i.push(`${a}. ${u} "${m}"${y}`),i.push(` Agent: ${g} | Files: ${d.path}`),a++}let c=[];for(let u of t.completedBolts){if(!n.find(g=>g.id===u))continue;let p=vs(t.manifest,u),f=p?pt.join(e,"aidlc-docs",t.workflowId,"construction",p,`${u}.md`):pt.join(e,"aidlc-docs",t.workflowId,"construction",`${u}.md`),m=no(f,u);c.push(`- ${u} "${m}" done (fulfilled)`)}let l=["## Workflow Execution Plan",`Workflow: ${t.featureName} (${t.workflowId})`,`Phase: ${t.currentPhase} | Trust: Level ${t.trustLevel} | Risk: Tier ${t.riskTier}`];return i.length>0&&(l.push("","### Pending BOLTs (execute in this order):"),l.push(...i)),c.length>0&&(l.push("","### Completed BOLTs:"),l.push(...c)),l.push("","### Instructions:"),l.push("For each pending BOLT: read its spec file, dispatch to the listed agent, then present Gate 4 review."),l.join(`
1409
+ `)}catch(t){return console.error("[WorkflowBridge] Failed to generate bolt execution plan:",t),""}}async function Lg(e){let t=[];try{let n=await oe(e);for(let r of n){let o=await I(e,r);if(!o||o.status==="complete"||o.status==="archived")continue;let s=Mg.join(e,"aidlc-docs",r,"manifest.json"),i=W(s),a={completed:0,total:0};i&&(a=ro(i)),t.push({workflowId:o.workflow_id,featureName:o.feature_name,currentPhase:o.current_phase,currentStage:o.current_stage,progress:a,lastActivity:o.updated_at,status:o.status,interviewProgress:o.interview_progress})}}catch(n){console.error("[ResumeDetector] Error checking aidlc-docs:",n)}return t}sn();function Ug(){Pg(),P({name:"learnedContextInjection",event:"SessionStart",priority:5,handler:e=>{if(!e.directory)return{continue:!0};try{let t=Dg(e.directory),n=Jo(e.directory,5),r=Ng(n),o=new Date,s=new Date(o.getTime()-1440*60*1e3);for(let c of n)try{new Date(c.last_useful)<s&&yf(c.id,e.directory)}catch(l){console.error("[Olympus Learning] Failed to mark discovery as useful:",l)}return{continue:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:`<olympus-mode>
1410
1410
  [OLYMPUS MODE ACTIVE]
1411
1411
  You are operating as an Olympus orchestrator. MANDATORY behaviors:
1412
1412
  - DELEGATE multi-file changes to subagents (olympian, oracle, frontend-engineer, etc.) via the Task tool
@@ -1418,11 +1418,11 @@ You are operating as an Olympus orchestrator. MANDATORY behaviors:
1418
1418
 
1419
1419
  `+t+(r?`
1420
1420
 
1421
- `+r:"")}}}catch(t){console.error("[Olympus Learning]",t)}return{continue:!0}}}),P({name:"workflowResumeDetection",event:"SessionStart",priority:8,handler:async e=>{try{let t=e.directory||process.cwd(),n=await Dg(t);if(n.length===0)return{continue:!0};let r=[];for(let a of n)if(a.status==="awaiting_mode_selection")r.push(`[Active workflow: '${a.featureName}' \u2014 awaiting execution mode selection.
1421
+ `+r:"")}}}catch(t){console.error("[Olympus Learning]",t)}return{continue:!0}}}),P({name:"workflowResumeDetection",event:"SessionStart",priority:8,handler:async e=>{try{let t=e.directory||process.cwd(),n=await Lg(t);if(n.length===0)return{continue:!0};let r=[];for(let a of n)if(a.status==="awaiting_mode_selection")r.push(`[Active workflow: '${a.featureName}' \u2014 awaiting execution mode selection.
1422
1422
  Choose: /ascent, /olympus, or /ultrawork to begin Construction]`);else if(a.status==="awaiting_dev_review")r.push(`[Active workflow: '${a.featureName}' \u2014 awaiting developer review (Risk Tier 3).
1423
1423
  Review the INTENT technical specification before proceeding to Construction.]`);else{let c=a.progress.total>0?`, ${a.progress.completed}/${a.progress.total} BOLTs complete`:"";r.push(`[Active workflow: '${a.featureName}' \u2014 ${a.currentPhase} phase${c}.
1424
- Resume with /continue or check status with /workflow-status]`)}let o=be(t);r.push(`[Trust Level: ${o.current_level}]`);let s=await Ag(t);s&&r.push(s);let i=await Og(t);i&&r.push(i);for(let a of n)a.interviewProgress&&r.push(`[Interview in progress: ${a.interviewProgress.stage} stage, ${a.interviewProgress.questions_asked} questions asked${a.interviewProgress.draft_artifact_path?". Draft artifact exists.":""}]`);if(r.length>0)return{continue:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:r.join(`
1425
- `)}}}catch(t){console.error("[Olympus Resume Detection] Error:",t)}return{continue:!0}}}),P({name:"sessionStart",event:"SessionStart",priority:10,handler:async e=>{let t=e.sessionId,n=e.directory||process.cwd(),r=[];try{let i=Q(n,t);i.token_budget||(mu(i,n),ee(n,i))}catch(i){console.error("[Olympus Learning] Failed to initialize token budget:",i)}let o=Qt(n);o?.active&&r.push(`<session-restore>
1424
+ Resume with /continue or check status with /workflow-status]`)}let o=Te(t);r.push(`[Trust Level: ${o.current_level}]`);let s=await Fg(t);s&&r.push(s);let i=await jg(t);i&&r.push(i);for(let a of n)a.interviewProgress&&r.push(`[Interview in progress: ${a.interviewProgress.stage} stage, ${a.interviewProgress.questions_asked} questions asked${a.interviewProgress.draft_artifact_path?". Draft artifact exists.":""}]`);if(r.length>0)return{continue:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:r.join(`
1425
+ `)}}}catch(t){console.error("[Olympus Resume Detection] Error:",t)}return{continue:!0}}}),P({name:"sessionStart",event:"SessionStart",priority:10,handler:async e=>{let t=e.sessionId,n=e.directory||process.cwd(),r=[];try{let i=Q(n,t);i.token_budget||(wu(i,n),ee(n,i))}catch(i){console.error("[Olympus Learning] Failed to initialize token budget:",i)}let o=Qt(n);o?.active&&r.push(`<session-restore>
1426
1426
 
1427
1427
  [ULTRAWORK MODE RESTORED]
1428
1428
 
@@ -1447,7 +1447,7 @@ Please continue working on these tasks.
1447
1447
  ---
1448
1448
 
1449
1449
  `),r.length>0?{continue:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:r.join(`
1450
- `)}}:{continue:!0}}})}var mr=require("fs"),qt=require("path"),tc=require("os");var Ue=require("fs"),dn=require("path"),Fg=require("os");function Ya(e){let t=(0,dn.join)(e,".olympus");return(0,dn.join)(t,"ascent-state.json")}function TC(e){let t=(0,dn.join)(e,".olympus");(0,Ue.existsSync)(t)||(0,Ue.mkdirSync)(t,{recursive:!0})}function pr(e){let t=Ya(e);if(!(0,Ue.existsSync)(t))return null;try{let n=(0,Ue.readFileSync)(t,"utf-8");return JSON.parse(n)}catch{return null}}function EC(e,t){try{TC(e);let n=Ya(e);return(0,Ue.writeFileSync)(n,JSON.stringify(t,null,2)),!0}catch{return!1}}function Ts(e){let t=Ya(e);if(!(0,Ue.existsSync)(t))return!0;try{return(0,Ue.unlinkSync)(t),!0}catch{return!1}}function jg(e){let t=pr(e);return!t||!t.active?null:(t.iteration+=1,EC(e,t)?t:null)}function Mg(e,t){let n=(0,dn.join)((0,Fg.homedir)(),".claude"),r=[(0,dn.join)(n,"sessions",e,"transcript.md"),(0,dn.join)(n,"sessions",e,"messages.json"),(0,dn.join)(n,"transcripts",`${e}.md`)];for(let o of r)if((0,Ue.existsSync)(o))try{let s=(0,Ue.readFileSync)(o,"utf-8");if(new RegExp(`<promise>\\s*${bC(t)}\\s*</promise>`,"is").test(s))return!0}catch{continue}return!1}function bC(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var tt=require("fs"),Ka=require("path"),CC=3;function Ja(e){return(0,Ka.join)(e,".olympus","ascent-verification.json")}function so(e){let t=Ja(e);if(!(0,tt.existsSync)(t))return null;try{return JSON.parse((0,tt.readFileSync)(t,"utf-8"))}catch{return null}}function Lg(e,t){let n=Ja(e),r=(0,Ka.join)(e,".olympus");if(!(0,tt.existsSync)(r))try{(0,tt.mkdirSync)(r,{recursive:!0})}catch{return!1}try{return(0,tt.writeFileSync)(n,JSON.stringify(t,null,2)),!0}catch{return!1}}function oo(e){let t=Ja(e);if((0,tt.existsSync)(t))try{return(0,tt.unlinkSync)(t),!0}catch{return!1}return!0}function Ug(e,t,n){let r={pending:!0,completion_claim:t,verification_attempts:0,max_verification_attempts:CC,requested_at:new Date().toISOString(),original_task:n};return Lg(e,r),r}function Wg(e,t,n){let r=so(e);return r?(r.verification_attempts+=1,r.oracle_approved=t,r.oracle_feedback=n,t?(oo(e),{...r,pending:!1}):r.verification_attempts>=r.max_verification_attempts?(oo(e),{...r,pending:!1}):(Lg(e,r),r)):null}function za(e){return`<ascent-verification>
1450
+ `)}}:{continue:!0}}})}var mr=require("fs"),qt=require("path"),sc=require("os");var Ue=require("fs"),dn=require("path"),Wg=require("os");function Qa(e){let t=(0,dn.join)(e,".olympus");return(0,dn.join)(t,"ascent-state.json")}function jC(e){let t=(0,dn.join)(e,".olympus");(0,Ue.existsSync)(t)||(0,Ue.mkdirSync)(t,{recursive:!0})}function pr(e){let t=Qa(e);if(!(0,Ue.existsSync)(t))return null;try{let n=(0,Ue.readFileSync)(t,"utf-8");return JSON.parse(n)}catch{return null}}function MC(e,t){try{jC(e);let n=Qa(e);return(0,Ue.writeFileSync)(n,JSON.stringify(t,null,2)),!0}catch{return!1}}function Es(e){let t=Qa(e);if(!(0,Ue.existsSync)(t))return!0;try{return(0,Ue.unlinkSync)(t),!0}catch{return!1}}function Bg(e){let t=pr(e);return!t||!t.active?null:(t.iteration+=1,MC(e,t)?t:null)}function Gg(e,t){let n=(0,dn.join)((0,Wg.homedir)(),".claude"),r=[(0,dn.join)(n,"sessions",e,"transcript.md"),(0,dn.join)(n,"sessions",e,"messages.json"),(0,dn.join)(n,"transcripts",`${e}.md`)];for(let o of r)if((0,Ue.existsSync)(o))try{let s=(0,Ue.readFileSync)(o,"utf-8");if(new RegExp(`<promise>\\s*${LC(t)}\\s*</promise>`,"is").test(s))return!0}catch{continue}return!1}function LC(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var tt=require("fs"),Xa=require("path"),UC=3;function Za(e){return(0,Xa.join)(e,".olympus","ascent-verification.json")}function so(e){let t=Za(e);if(!(0,tt.existsSync)(t))return null;try{return JSON.parse((0,tt.readFileSync)(t,"utf-8"))}catch{return null}}function Hg(e,t){let n=Za(e),r=(0,Xa.join)(e,".olympus");if(!(0,tt.existsSync)(r))try{(0,tt.mkdirSync)(r,{recursive:!0})}catch{return!1}try{return(0,tt.writeFileSync)(n,JSON.stringify(t,null,2)),!0}catch{return!1}}function oo(e){let t=Za(e);if((0,tt.existsSync)(t))try{return(0,tt.unlinkSync)(t),!0}catch{return!1}return!0}function Vg(e,t,n){let r={pending:!0,completion_claim:t,verification_attempts:0,max_verification_attempts:UC,requested_at:new Date().toISOString(),original_task:n};return Hg(e,r),r}function qg(e,t,n){let r=so(e);return r?(r.verification_attempts+=1,r.oracle_approved=t,r.oracle_feedback=n,t?(oo(e),{...r,pending:!1}):r.verification_attempts>=r.max_verification_attempts?(oo(e),{...r,pending:!1}):(Hg(e,r),r)):null}function ec(e){return`<ascent-verification>
1451
1451
 
1452
1452
  [ORACLE VERIFICATION REQUIRED - Attempt ${e.verification_attempts+1}/${e.max_verification_attempts}]
1453
1453
 
@@ -1487,7 +1487,7 @@ DO NOT output the completion promise again until Oracle approves.
1487
1487
 
1488
1488
  ---
1489
1489
 
1490
- `}function Gg(e){return`<ascent-continuation-after-rejection>
1490
+ `}function Yg(e){return`<ascent-continuation-after-rejection>
1491
1491
 
1492
1492
  [ORACLE REJECTED - Continue Working]
1493
1493
 
@@ -1512,7 +1512,7 @@ Continue working now.
1512
1512
 
1513
1513
  ---
1514
1514
 
1515
- `}function Bg(e){return/<oracle-approved>.*?VERIFIED_COMPLETE.*?<\/oracle-approved>/is.test(e)}function Hg(e){let t=[/oracle.*?(rejected|found issues|not complete|incomplete)/i,/issues? (found|identified|detected)/i,/not yet complete/i,/missing.*?(implementation|feature|test)/i,/bug.*?(found|detected|identified)/i,/error.*?(found|detected|identified)/i];for(let n of t)if(n.test(e)){let r=e.match(/(?:oracle|feedback|issue|problem|error|bug)[:\s]+([^.]+\.)/i);return{rejected:!0,feedback:r?r[1]:"Oracle found issues with the implementation."}}return{rejected:!1,feedback:""}}var ue=require("fs"),fr=require("path"),Qa=require("os");function Xa(e){let t=e||process.cwd(),n=(0,fr.join)(t,".olympus");return(0,fr.join)(n,"olympus-state.json")}function Za(){return(0,fr.join)((0,Qa.homedir)(),".claude","olympus-state.json")}function RC(e){let t=e||process.cwd(),n=(0,fr.join)(t,".olympus");(0,ue.existsSync)(n)||(0,ue.mkdirSync)(n,{recursive:!0})}function xC(){let e=(0,fr.join)((0,Qa.homedir)(),".claude");(0,ue.existsSync)(e)||(0,ue.mkdirSync)(e,{recursive:!0})}function Nn(e){let t=Xa(e);if((0,ue.existsSync)(t))try{let r=(0,ue.readFileSync)(t,"utf-8");return JSON.parse(r)}catch{}let n=Za();if((0,ue.existsSync)(n))try{let r=(0,ue.readFileSync)(n,"utf-8");return JSON.parse(r)}catch{return null}return null}function Vg(e,t){try{RC(t);let n=Xa(t);(0,ue.writeFileSync)(n,JSON.stringify(e,null,2)),xC();let r=Za();return(0,ue.writeFileSync)(r,JSON.stringify(e,null,2)),!0}catch{return!1}}function ec(e){let t=Xa(e);if((0,ue.existsSync)(t))try{(0,ue.unlinkSync)(t)}catch{}let n=Za();if((0,ue.existsSync)(n))try{return(0,ue.unlinkSync)(n),!0}catch{return!1}return!0}function qg(e){let t=Nn(e);return!t||!t.active?null:(t.reinforcement_count+=1,t.last_checked_at=new Date().toISOString(),Vg(t,e)?t:null)}function Yg(e){let t=Nn(e);return!t||!t.active?!1:(t.oracle_approved=!0,t.last_checked_at=new Date().toISOString(),Vg(t,e))}function Kg(e){let t=e.requires_oracle_verification&&!e.oracle_approved?`
1515
+ `}function Kg(e){return/<oracle-approved>.*?VERIFIED_COMPLETE.*?<\/oracle-approved>/is.test(e)}function Jg(e){let t=[/oracle.*?(rejected|found issues|not complete|incomplete)/i,/issues? (found|identified|detected)/i,/not yet complete/i,/missing.*?(implementation|feature|test)/i,/bug.*?(found|detected|identified)/i,/error.*?(found|detected|identified)/i];for(let n of t)if(n.test(e)){let r=e.match(/(?:oracle|feedback|issue|problem|error|bug)[:\s]+([^.]+\.)/i);return{rejected:!0,feedback:r?r[1]:"Oracle found issues with the implementation."}}return{rejected:!1,feedback:""}}var de=require("fs"),fr=require("path"),tc=require("os");function nc(e){let t=e||process.cwd(),n=(0,fr.join)(t,".olympus");return(0,fr.join)(n,"olympus-state.json")}function rc(){return(0,fr.join)((0,tc.homedir)(),".claude","olympus-state.json")}function WC(e){let t=e||process.cwd(),n=(0,fr.join)(t,".olympus");(0,de.existsSync)(n)||(0,de.mkdirSync)(n,{recursive:!0})}function BC(){let e=(0,fr.join)((0,tc.homedir)(),".claude");(0,de.existsSync)(e)||(0,de.mkdirSync)(e,{recursive:!0})}function Nn(e){let t=nc(e);if((0,de.existsSync)(t))try{let r=(0,de.readFileSync)(t,"utf-8");return JSON.parse(r)}catch{}let n=rc();if((0,de.existsSync)(n))try{let r=(0,de.readFileSync)(n,"utf-8");return JSON.parse(r)}catch{return null}return null}function zg(e,t){try{WC(t);let n=nc(t);(0,de.writeFileSync)(n,JSON.stringify(e,null,2)),BC();let r=rc();return(0,de.writeFileSync)(r,JSON.stringify(e,null,2)),!0}catch{return!1}}function oc(e){let t=nc(e);if((0,de.existsSync)(t))try{(0,de.unlinkSync)(t)}catch{}let n=rc();if((0,de.existsSync)(n))try{return(0,de.unlinkSync)(n),!0}catch{return!1}return!0}function Qg(e){let t=Nn(e);return!t||!t.active?null:(t.reinforcement_count+=1,t.last_checked_at=new Date().toISOString(),zg(t,e)?t:null)}function Xg(e){let t=Nn(e);return!t||!t.active?!1:(t.oracle_approved=!0,t.last_checked_at=new Date().toISOString(),zg(t,e))}function Zg(e){let t=e.requires_oracle_verification&&!e.oracle_approved?`
1516
1516
 
1517
1517
  **ORACLE VERIFICATION REQUIRED**: Before declaring complete, you MUST get Oracle approval.`:"";return`<olympus-persistence>
1518
1518
 
@@ -1534,7 +1534,7 @@ Original task: ${e.original_prompt}
1534
1534
 
1535
1535
  ---
1536
1536
 
1537
- `}me();function Jg(e){let t=(0,qt.join)((0,tc.homedir)(),".claude"),n=[(0,qt.join)(t,"sessions",e,"transcript.md"),(0,qt.join)(t,"sessions",e,"messages.json"),(0,qt.join)(t,"transcripts",`${e}.md`)];for(let r of n)if((0,mr.existsSync)(r))try{let o=(0,mr.readFileSync)(r,"utf-8");if(Bg(o))return!0}catch{continue}return!1}function PC(e){let t=(0,qt.join)((0,tc.homedir)(),".claude"),n=[(0,qt.join)(t,"sessions",e,"transcript.md"),(0,qt.join)(t,"sessions",e,"messages.json"),(0,qt.join)(t,"transcripts",`${e}.md`)];for(let r of n)if((0,mr.existsSync)(r))try{let o=(0,mr.readFileSync)(r,"utf-8"),s=Hg(o);if(s.rejected)return s}catch{continue}return{rejected:!1,feedback:""}}async function IC(e,t){let n=t||process.cwd(),r=pr(n);if(!r||!r.active||r.session_id&&e&&r.session_id!==e)return null;let o=so(n);if(o?.pending){if(e){if(Jg(e))return oo(n),Ts(n),{shouldBlock:!1,message:`[ASCENT LOOP VERIFIED COMPLETE] Oracle verified task completion after ${r.iteration} iteration(s). Excellent work!`,mode:"none"};let l=PC(e);if(l.rejected){Wg(n,!1,l.feedback);let u=so(n);if(u)return{shouldBlock:!0,message:Gg(u),mode:"ascent",metadata:{iteration:r.iteration,maxIterations:r.max_iterations}}}}return{shouldBlock:!0,message:za(o),mode:"ascent",metadata:{iteration:r.iteration,maxIterations:r.max_iterations}}}if(Mg(e||"",r.completion_promise)){Ug(n,r.completion_promise,r.prompt);let c=so(n);return c?{shouldBlock:!0,message:za(c),mode:"ascent",metadata:{iteration:r.iteration,maxIterations:r.max_iterations}}:(Ts(n),{shouldBlock:!1,message:`[ASCENT LOOP COMPLETE] Task completed after ${r.iteration} iteration(s). Great work!`,mode:"none"})}if(r.iteration>=r.max_iterations)return Ts(n),oo(n),{shouldBlock:!1,message:`[ASCENT LOOP STOPPED] Max iterations (${r.max_iterations}) reached without completion promise. Consider reviewing the task requirements.`,mode:"none"};let i=jg(n);return i?{shouldBlock:!0,message:`<ascent-continuation>
1537
+ `}le();function eh(e){let t=(0,qt.join)((0,sc.homedir)(),".claude"),n=[(0,qt.join)(t,"sessions",e,"transcript.md"),(0,qt.join)(t,"sessions",e,"messages.json"),(0,qt.join)(t,"transcripts",`${e}.md`)];for(let r of n)if((0,mr.existsSync)(r))try{let o=(0,mr.readFileSync)(r,"utf-8");if(Kg(o))return!0}catch{continue}return!1}function GC(e){let t=(0,qt.join)((0,sc.homedir)(),".claude"),n=[(0,qt.join)(t,"sessions",e,"transcript.md"),(0,qt.join)(t,"sessions",e,"messages.json"),(0,qt.join)(t,"transcripts",`${e}.md`)];for(let r of n)if((0,mr.existsSync)(r))try{let o=(0,mr.readFileSync)(r,"utf-8"),s=Jg(o);if(s.rejected)return s}catch{continue}return{rejected:!1,feedback:""}}async function HC(e,t){let n=t||process.cwd(),r=pr(n);if(!r||!r.active||r.session_id&&e&&r.session_id!==e)return null;let o=so(n);if(o?.pending){if(e){if(eh(e))return oo(n),Es(n),{shouldBlock:!1,message:`[ASCENT LOOP VERIFIED COMPLETE] Oracle verified task completion after ${r.iteration} iteration(s). Excellent work!`,mode:"none"};let l=GC(e);if(l.rejected){qg(n,!1,l.feedback);let u=so(n);if(u)return{shouldBlock:!0,message:Yg(u),mode:"ascent",metadata:{iteration:r.iteration,maxIterations:r.max_iterations}}}}return{shouldBlock:!0,message:ec(o),mode:"ascent",metadata:{iteration:r.iteration,maxIterations:r.max_iterations}}}if(Gg(e||"",r.completion_promise)){Vg(n,r.completion_promise,r.prompt);let c=so(n);return c?{shouldBlock:!0,message:ec(c),mode:"ascent",metadata:{iteration:r.iteration,maxIterations:r.max_iterations}}:(Es(n),{shouldBlock:!1,message:`[ASCENT LOOP COMPLETE] Task completed after ${r.iteration} iteration(s). Great work!`,mode:"none"})}if(r.iteration>=r.max_iterations)return Es(n),oo(n),{shouldBlock:!1,message:`[ASCENT LOOP STOPPED] Max iterations (${r.max_iterations}) reached without completion promise. Consider reviewing the task requirements.`,mode:"none"};let i=Bg(n);return i?{shouldBlock:!0,message:`<ascent-continuation>
1538
1538
 
1539
1539
  [ASCENT LOOP - ITERATION ${i.iteration}/${i.max_iterations}]
1540
1540
 
@@ -1553,7 +1553,7 @@ ${i.prompt?`Original task: ${i.prompt}`:""}
1553
1553
 
1554
1554
  ---
1555
1555
 
1556
- `,mode:"ascent",metadata:{iteration:i.iteration,maxIterations:i.max_iterations}}:null}async function AC(e,t,n){let r=Qt(t);if(!r||!r.active||r.session_id&&e&&r.session_id!==e)return null;if(!n)return Gl(t),{shouldBlock:!1,message:"[ULTRAWORK COMPLETE] All tasks finished. Ultrawork mode deactivated. Well done!",mode:"none"};let o=Bl(t);return o?{shouldBlock:!0,message:Hl(o),mode:"ultrawork",metadata:{reinforcementCount:o.reinforcement_count}}:null}async function OC(e,t,n){let r=Nn(t);if(!r||!r.active||r.session_id&&e&&r.session_id!==e)return null;if(!n&&r.oracle_approved)return ec(t),{shouldBlock:!1,message:"[OLYMPUS COMPLETE] All tasks finished and Oracle verified. Orchestration mode deactivated. Excellent work!",mode:"none"};if(!n&&!r.oracle_approved&&r.requires_oracle_verification)return e&&Jg(e)?(Yg(t),ec(t),{shouldBlock:!1,message:"[OLYMPUS VERIFIED COMPLETE] Oracle approved. Orchestration mode deactivated. Excellent work!",mode:"none"}):{shouldBlock:!0,message:`<olympus-verification-required>
1556
+ `,mode:"ascent",metadata:{iteration:i.iteration,maxIterations:i.max_iterations}}:null}async function VC(e,t,n){let r=Qt(t);if(!r||!r.active||r.session_id&&e&&r.session_id!==e)return null;if(!n)return ql(t),{shouldBlock:!1,message:"[ULTRAWORK COMPLETE] All tasks finished. Ultrawork mode deactivated. Well done!",mode:"none"};let o=Yl(t);return o?{shouldBlock:!0,message:Kl(o),mode:"ultrawork",metadata:{reinforcementCount:o.reinforcement_count}}:null}async function qC(e,t,n){let r=Nn(t);if(!r||!r.active||r.session_id&&e&&r.session_id!==e)return null;if(!n&&r.oracle_approved)return oc(t),{shouldBlock:!1,message:"[OLYMPUS COMPLETE] All tasks finished and Oracle verified. Orchestration mode deactivated. Excellent work!",mode:"none"};if(!n&&!r.oracle_approved&&r.requires_oracle_verification)return e&&eh(e)?(Xg(t),oc(t),{shouldBlock:!1,message:"[OLYMPUS VERIFIED COMPLETE] Oracle approved. Orchestration mode deactivated. Excellent work!",mode:"none"}):{shouldBlock:!0,message:`<olympus-verification-required>
1557
1557
 
1558
1558
  [OLYMPUS MODE - ORACLE VERIFICATION REQUIRED]
1559
1559
 
@@ -1576,11 +1576,11 @@ DO NOT stop until Oracle has approved.
1576
1576
 
1577
1577
  ---
1578
1578
 
1579
- `,mode:"olympus",metadata:{reinforcementCount:r.reinforcement_count}};let o=qg(t);return o?{shouldBlock:!0,message:Kg(o),mode:"olympus",metadata:{reinforcementCount:o.reinforcement_count}}:null}async function $C(e,t){let n=await to(e,t);if(n.count===0)return null;let r=Cg(n),o=r?`
1579
+ `,mode:"olympus",metadata:{reinforcementCount:r.reinforcement_count}};let o=Qg(t);return o?{shouldBlock:!0,message:Zg(o),mode:"olympus",metadata:{reinforcementCount:o.reinforcement_count}}:null}async function YC(e,t){let n=await to(e,t);if(n.count===0)return null;let r=Ig(n),o=r?`
1580
1580
 
1581
1581
  Next task: "${r.content}" (${r.status})`:"";return{shouldBlock:!0,message:`<todo-continuation>
1582
1582
 
1583
- ${zl}
1583
+ ${eu}
1584
1584
 
1585
1585
  [Status: ${n.count} of ${n.total} tasks remaining]${o}
1586
1586
 
@@ -1588,11 +1588,11 @@ ${zl}
1588
1588
 
1589
1589
  ---
1590
1590
 
1591
- `,mode:"todo-continuation",metadata:{todoCount:n.count}}}async function DC(e,t,n){let r=t||process.cwd();try{let o=await vs(r);if(!o)return null;let s=ro(o.manifest),i=o.pendingBolts.length>0,a=`
1591
+ `,mode:"todo-continuation",metadata:{todoCount:n.count}}}async function KC(e,t,n){let r=t||process.cwd();try{let o=await Ts(r);if(!o)return null;let s=ro(o.manifest),i=o.pendingBolts.length>0,a=`
1592
1592
  Workflow '${o.featureName}': ${s.completed}/${s.total} BOLTs complete (${s.percentage}%)`;if(o.pendingBolts.length>0){let l=o.pendingBolts[0];a+=`
1593
- Next: ${l}`}try{await O(r,o.checkpoint)}catch{}return{progressMessage:a,shouldBlock:i&&(n==="ascent"||n==="ultrawork"||n==="olympus")}}catch{return null}}async function zg(e,t){let n=t||process.cwd(),o=(await to(e,n)).count>0,s=pr(n),i=Qt(n),a=Nn(n),c=null;s?.active?c="ascent":i?.active?c="ultrawork":a?.active&&(c="olympus");let l=await DC(e,n,c),u=await IC(e,n);if(u?.shouldBlock)return l&&(u.message=u.message+`
1594
- ${l.progressMessage}`),u;let d=await AC(e,n,o);if(d?.shouldBlock)return l&&(d.message=d.message+`
1595
- ${l.progressMessage}`),d;let p=await OC(e,n,o);if(p?.shouldBlock)return l&&(p.message=p.message+`
1593
+ Next: ${l}`}try{await A(r,o.checkpoint)}catch{}return{progressMessage:a,shouldBlock:i&&(n==="ascent"||n==="ultrawork"||n==="olympus")}}catch{return null}}async function th(e,t){let n=t||process.cwd(),o=(await to(e,n)).count>0,s=pr(n),i=Qt(n),a=Nn(n),c=null;s?.active?c="ascent":i?.active?c="ultrawork":a?.active&&(c="olympus");let l=await KC(e,n,c),u=await HC(e,n);if(u?.shouldBlock)return l&&(u.message=u.message+`
1594
+ ${l.progressMessage}`),u;let d=await VC(e,n,o);if(d?.shouldBlock)return l&&(d.message=d.message+`
1595
+ ${l.progressMessage}`),d;let p=await qC(e,n,o);if(p?.shouldBlock)return l&&(p.message=p.message+`
1596
1596
  ${l.progressMessage}`),p;if(l?.shouldBlock)return{shouldBlock:!0,message:`<workflow-continuation>
1597
1597
 
1598
1598
  [WORKFLOW IN PROGRESS - DO NOT STOP]
@@ -1605,21 +1605,21 @@ You are in ${c} mode with pending BOLTs. Continue executing the remaining BOLTs.
1605
1605
 
1606
1606
  ---
1607
1607
 
1608
- `,mode:c||"none",metadata:{}};if(o){let f=await $C(e,n);if(f?.shouldBlock)return l&&(f.message=f.message+`
1609
- ${l.progressMessage}`),f}return l?{shouldBlock:!1,message:l.progressMessage,mode:"none"}:{shouldBlock:!1,message:"",mode:"none"}}function Qg(e){return e.shouldBlock?{continue:!1,stopReason:e.message}:{continue:!0,message:e.message||void 0}}var gr=require("fs"),nc=require("path"),Xg=require("os");Ge();we();var Zg=require("crypto");function NC(){let e=(0,nc.join)((0,Xg.homedir)(),".claude","todos");if(!(0,gr.existsSync)(e))return 0;let t=0;try{let n=(0,gr.readdirSync)(e).filter(r=>r.endsWith(".json"));for(let r of n)try{let o=(0,gr.readFileSync)((0,nc.join)(e,r),"utf-8"),s=JSON.parse(o);Array.isArray(s)&&(t+=s.filter(i=>i.status!=="completed"&&i.status!=="cancelled").length)}catch{}}catch{}return t}async function eh(e){let{directory:t,sessionId:n}=e;if(!t)return;let r=Q(t,n),o=NC();if(o>0&&r.pending_completion){let s={id:(0,Zg.randomUUID)(),timestamp:new Date().toISOString(),session_id:r.session_id,project_path:t,event_type:"cancellation",original_task:r.pending_completion.task_description,agent_used:r.pending_completion.agent_used,user_message:`[Stopped with ${o} incomplete todos]`,feedback_category:"rejection",confidence:.7};Xt(s)}r.pending_completion=null,r.todo_snapshot={total:0,completed:0,pending:o},ee(t,r)}function th(){P({name:"persistentMode",event:"Stop",priority:10,handler:async e=>{let t=e.sessionId,n=e.directory||process.cwd(),r=await zg(t,n),o=Qg(r);return{continue:o.continue,message:o.message,stopReason:o.stopReason}}}),P({name:"learningCancellationCapture",event:"Stop",priority:100,handler:async e=>e.directory?(Promise.resolve().then(async()=>{try{await eh({directory:e.directory,sessionId:e.sessionId})}catch(t){console.error("[Olympus Learning]",t)}}),{continue:!0}):{continue:!0}})}var pc=require("fs"),fc=require("os"),ao=require("path");var ft=require("fs"),Ye=require("path");var rc=require("path"),nh=require("os"),FC=(0,rc.join)((0,nh.homedir)(),".olympus"),Es=(0,rc.join)(FC,"rules-injector"),rh=[".git","pyproject.toml","package.json","Cargo.toml","go.mod",".venv"],oh=[[".github","instructions"],[".cursor","rules"],[".claude","rules"]],sh=[".github/copilot-instructions.md"],ih=/\.instructions\.md$/,ah=".claude/rules",ch=[".md",".mdc"],oc=["read","write","edit","multiedit"];function jC(e){return e.includes(".github/instructions")||e.endsWith(".github/instructions")}function MC(e,t){return jC(t)?ih.test(e):ch.some(n=>e.endsWith(n))}function ac(e){let t;try{t=(0,ft.statSync)(e).isDirectory()?e:(0,Ye.dirname)(e)}catch{t=(0,Ye.dirname)(e)}for(;;){for(let r of rh){let o=(0,Ye.join)(t,r);if((0,ft.existsSync)(o))return t}let n=(0,Ye.dirname)(t);if(n===t)return null;t=n}}function ic(e,t){if((0,ft.existsSync)(e))try{let n=(0,ft.readdirSync)(e,{withFileTypes:!0});for(let r of n){let o=(0,Ye.join)(e,r.name);r.isDirectory()?ic(o,t):r.isFile()&&MC(r.name,e)&&t.push(o)}}catch{}}function sc(e){try{return(0,ft.realpathSync)(e)}catch{return e}}function cc(e,t,n){let r=[],o=new Set,s=(0,Ye.dirname)(n),i=0;for(;;){for(let[u,d]of oh){let p=(0,Ye.join)(s,u,d),f=[];ic(p,f);for(let m of f){let g=sc(m);o.has(g)||(o.add(g),r.push({path:m,realPath:g,isGlobal:!1,distance:i}))}}if(e&&s===e)break;let l=(0,Ye.dirname)(s);if(l===s)break;s=l,i++}if(e)for(let l of sh){let u=(0,Ye.join)(e,l);if((0,ft.existsSync)(u))try{if((0,ft.statSync)(u).isFile()){let p=sc(u);o.has(p)||(o.add(p),r.push({path:u,realPath:p,isGlobal:!1,distance:0,isSingleFile:!0}))}}catch{}}let a=(0,Ye.join)(t,ah),c=[];ic(a,c);for(let l of c){let u=sc(l);o.has(u)||(o.add(u),r.push({path:l,realPath:u,isGlobal:!0,distance:9999}))}return r.sort((l,u)=>l.isGlobal!==u.isGlobal?l.isGlobal?1:-1:l.distance-u.distance),r}var lh=require("crypto"),uh=require("path");function LC(e,t){let n=e.replace(/\./g,"\\.").replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/<<<GLOBSTAR>>>/g,".*").replace(/\?/g,".");return new RegExp(`^${n}$`).test(t)}function lc(e,t,n){if(e.alwaysApply===!0)return{applies:!0,reason:"alwaysApply"};let r=e.globs;if(!r)return{applies:!1};let o=Array.isArray(r)?r:[r];if(o.length===0)return{applies:!1};let i=(n?(0,uh.relative)(n,t):t).replace(/\\/g,"/");for(let a of o)if(LC(a,i))return{applies:!0,reason:`glob: ${a}`};return{applies:!1}}function dh(e,t){return t.has(e)}function ph(e){return(0,lh.createHash)("sha256").update(e).digest("hex").slice(0,16)}function fh(e,t){return t.has(e)}function uc(e){let t=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,n=e.match(t);if(!n)return{metadata:{},body:e};let r=n[1],o=n[2];try{return{metadata:UC(r),body:o}}catch{return{metadata:{},body:e}}}function UC(e){let t=e.split(`
1610
- `),n={},r=0;for(;r<t.length;){let o=t[r],s=o.indexOf(":");if(s===-1){r++;continue}let i=o.slice(0,s).trim(),a=o.slice(s+1).trim();if(i==="description")n.description=io(a);else if(i==="alwaysApply")n.alwaysApply=a==="true";else if(i==="globs"||i==="paths"||i==="applyTo"){let{value:c,consumed:l}=WC(a,t,r);n.globs=BC(n.globs,c),r+=l;continue}r++}return n}function io(e){return e?e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e:""}function WC(e,t,n){if(e.startsWith("["))return{value:GC(e),consumed:1};if(!e||e===""){let o=[],s=1;for(let i=n+1;i<t.length;i++){let a=t[i],c=a.match(/^\s+-\s*(.*)$/);if(c){let l=io(c[1].trim());l&&o.push(l),s++}else if(a.trim()==="")s++;else break}if(o.length>0)return{value:o,consumed:s}}let r=io(e);return r.includes(",")?{value:r.split(",").map(s=>s.trim()).filter(s=>s.length>0),consumed:1}:{value:r,consumed:1}}function GC(e){let t=e.slice(1,e.lastIndexOf("]")).trim();if(!t)return[];let n=[],r="",o=!1,s="";for(let a=0;a<t.length;a++){let c=t[a];if(!o&&(c==='"'||c==="'"))o=!0,s=c;else if(o&&c===s)o=!1,s="";else if(!o&&c===","){let l=r.trim();l&&n.push(io(l)),r=""}else r+=c}let i=r.trim();return i&&n.push(io(i)),n}function BC(e,t){if(!e)return t;let n=Array.isArray(e)?e:[e],r=Array.isArray(t)?t:[t];return[...n,...r]}var nt=require("fs"),mh=require("path");function dc(e){return(0,mh.join)(Es,`${e}.json`)}function gh(e){let t=dc(e);if(!(0,nt.existsSync)(t))return{contentHashes:new Set,realPaths:new Set};try{let n=(0,nt.readFileSync)(t,"utf-8"),r=JSON.parse(n);return{contentHashes:new Set(r.injectedHashes),realPaths:new Set(r.injectedRealPaths??[])}}catch{return{contentHashes:new Set,realPaths:new Set}}}function hh(e,t){(0,nt.existsSync)(Es)||(0,nt.mkdirSync)(Es,{recursive:!0});let n={sessionId:e,injectedHashes:[...t.contentHashes],injectedRealPaths:[...t.realPaths],updatedAt:Date.now()};(0,nt.writeFileSync)(dc(e),JSON.stringify(n,null,2))}function yh(e){let t=dc(e);(0,nt.existsSync)(t)&&(0,nt.unlinkSync)(t)}function wh(e){let t=new Map;function n(i){return t.has(i)||t.set(i,gh(i)),t.get(i)}function r(i){return i?i.startsWith("/")?i:(0,ao.resolve)(e,i):null}function o(i,a){let c=r(i);if(!c)return[];let l=ac(c),u=n(a),d=(0,fc.homedir)(),p=cc(l,d,c),f=[];for(let m of p)if(!dh(m.realPath,u.realPaths))try{let g=(0,pc.readFileSync)(m.path,"utf-8"),{metadata:y,body:w}=uc(g),k;if(m.isSingleFile)k="copilot-instructions (always apply)";else{let S=lc(y,c,l);if(!S.applies)continue;k=S.reason??"matched"}let h=ph(w);if(fh(h,u.contentHashes))continue;let v=l?(0,ao.relative)(l,m.path):m.path;f.push({relativePath:v,matchReason:k,content:w,distance:m.distance}),u.realPaths.add(m.realPath),u.contentHashes.add(h)}catch{}return f.length>0&&(f.sort((m,g)=>m.distance-g.distance),hh(a,u)),f}function s(i){if(i.length===0)return"";let a="";for(let c of i)a+=`
1608
+ `,mode:c||"none",metadata:{}};if(o){let f=await YC(e,n);if(f?.shouldBlock)return l&&(f.message=f.message+`
1609
+ ${l.progressMessage}`),f}return l?{shouldBlock:!1,message:l.progressMessage,mode:"none"}:{shouldBlock:!1,message:"",mode:"none"}}function nh(e){return e.shouldBlock?{continue:!1,stopReason:e.message}:{continue:!0,message:e.message||void 0}}var gr=require("fs"),ic=require("path"),rh=require("os");Be();we();var oh=require("crypto");function JC(){let e=(0,ic.join)((0,rh.homedir)(),".claude","todos");if(!(0,gr.existsSync)(e))return 0;let t=0;try{let n=(0,gr.readdirSync)(e).filter(r=>r.endsWith(".json"));for(let r of n)try{let o=(0,gr.readFileSync)((0,ic.join)(e,r),"utf-8"),s=JSON.parse(o);Array.isArray(s)&&(t+=s.filter(i=>i.status!=="completed"&&i.status!=="cancelled").length)}catch{}}catch{}return t}async function sh(e){let{directory:t,sessionId:n}=e;if(!t)return;let r=Q(t,n),o=JC();if(o>0&&r.pending_completion){let s={id:(0,oh.randomUUID)(),timestamp:new Date().toISOString(),session_id:r.session_id,project_path:t,event_type:"cancellation",original_task:r.pending_completion.task_description,agent_used:r.pending_completion.agent_used,user_message:`[Stopped with ${o} incomplete todos]`,feedback_category:"rejection",confidence:.7};Xt(s)}r.pending_completion=null,r.todo_snapshot={total:0,completed:0,pending:o},ee(t,r)}function ih(){P({name:"persistentMode",event:"Stop",priority:10,handler:async e=>{let t=e.sessionId,n=e.directory||process.cwd(),r=await th(t,n),o=nh(r);return{continue:o.continue,message:o.message,stopReason:o.stopReason}}}),P({name:"learningCancellationCapture",event:"Stop",priority:100,handler:async e=>e.directory?(Promise.resolve().then(async()=>{try{await sh({directory:e.directory,sessionId:e.sessionId})}catch(t){console.error("[Olympus Learning]",t)}}),{continue:!0}):{continue:!0}})}var hc=require("fs"),yc=require("os"),ao=require("path");var ft=require("fs"),Ye=require("path");var ac=require("path"),ah=require("os"),zC=(0,ac.join)((0,ah.homedir)(),".olympus"),Cs=(0,ac.join)(zC,"rules-injector"),ch=[".git","pyproject.toml","package.json","Cargo.toml","go.mod",".venv"],lh=[[".github","instructions"],[".cursor","rules"],[".claude","rules"]],uh=[".github/copilot-instructions.md"],dh=/\.instructions\.md$/,ph=".claude/rules",fh=[".md",".mdc"],cc=["read","write","edit","multiedit"];function QC(e){return e.includes(".github/instructions")||e.endsWith(".github/instructions")}function XC(e,t){return QC(t)?dh.test(e):fh.some(n=>e.endsWith(n))}function dc(e){let t;try{t=(0,ft.statSync)(e).isDirectory()?e:(0,Ye.dirname)(e)}catch{t=(0,Ye.dirname)(e)}for(;;){for(let r of ch){let o=(0,Ye.join)(t,r);if((0,ft.existsSync)(o))return t}let n=(0,Ye.dirname)(t);if(n===t)return null;t=n}}function uc(e,t){if((0,ft.existsSync)(e))try{let n=(0,ft.readdirSync)(e,{withFileTypes:!0});for(let r of n){let o=(0,Ye.join)(e,r.name);r.isDirectory()?uc(o,t):r.isFile()&&XC(r.name,e)&&t.push(o)}}catch{}}function lc(e){try{return(0,ft.realpathSync)(e)}catch{return e}}function pc(e,t,n){let r=[],o=new Set,s=(0,Ye.dirname)(n),i=0;for(;;){for(let[u,d]of lh){let p=(0,Ye.join)(s,u,d),f=[];uc(p,f);for(let m of f){let g=lc(m);o.has(g)||(o.add(g),r.push({path:m,realPath:g,isGlobal:!1,distance:i}))}}if(e&&s===e)break;let l=(0,Ye.dirname)(s);if(l===s)break;s=l,i++}if(e)for(let l of uh){let u=(0,Ye.join)(e,l);if((0,ft.existsSync)(u))try{if((0,ft.statSync)(u).isFile()){let p=lc(u);o.has(p)||(o.add(p),r.push({path:u,realPath:p,isGlobal:!1,distance:0,isSingleFile:!0}))}}catch{}}let a=(0,Ye.join)(t,ph),c=[];uc(a,c);for(let l of c){let u=lc(l);o.has(u)||(o.add(u),r.push({path:l,realPath:u,isGlobal:!0,distance:9999}))}return r.sort((l,u)=>l.isGlobal!==u.isGlobal?l.isGlobal?1:-1:l.distance-u.distance),r}var mh=require("crypto"),gh=require("path");function ZC(e,t){let n=e.replace(/\./g,"\\.").replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/<<<GLOBSTAR>>>/g,".*").replace(/\?/g,".");return new RegExp(`^${n}$`).test(t)}function fc(e,t,n){if(e.alwaysApply===!0)return{applies:!0,reason:"alwaysApply"};let r=e.globs;if(!r)return{applies:!1};let o=Array.isArray(r)?r:[r];if(o.length===0)return{applies:!1};let i=(n?(0,gh.relative)(n,t):t).replace(/\\/g,"/");for(let a of o)if(ZC(a,i))return{applies:!0,reason:`glob: ${a}`};return{applies:!1}}function hh(e,t){return t.has(e)}function yh(e){return(0,mh.createHash)("sha256").update(e).digest("hex").slice(0,16)}function wh(e,t){return t.has(e)}function mc(e){let t=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,n=e.match(t);if(!n)return{metadata:{},body:e};let r=n[1],o=n[2];try{return{metadata:eR(r),body:o}}catch{return{metadata:{},body:e}}}function eR(e){let t=e.split(`
1610
+ `),n={},r=0;for(;r<t.length;){let o=t[r],s=o.indexOf(":");if(s===-1){r++;continue}let i=o.slice(0,s).trim(),a=o.slice(s+1).trim();if(i==="description")n.description=io(a);else if(i==="alwaysApply")n.alwaysApply=a==="true";else if(i==="globs"||i==="paths"||i==="applyTo"){let{value:c,consumed:l}=tR(a,t,r);n.globs=rR(n.globs,c),r+=l;continue}r++}return n}function io(e){return e?e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e:""}function tR(e,t,n){if(e.startsWith("["))return{value:nR(e),consumed:1};if(!e||e===""){let o=[],s=1;for(let i=n+1;i<t.length;i++){let a=t[i],c=a.match(/^\s+-\s*(.*)$/);if(c){let l=io(c[1].trim());l&&o.push(l),s++}else if(a.trim()==="")s++;else break}if(o.length>0)return{value:o,consumed:s}}let r=io(e);return r.includes(",")?{value:r.split(",").map(s=>s.trim()).filter(s=>s.length>0),consumed:1}:{value:r,consumed:1}}function nR(e){let t=e.slice(1,e.lastIndexOf("]")).trim();if(!t)return[];let n=[],r="",o=!1,s="";for(let a=0;a<t.length;a++){let c=t[a];if(!o&&(c==='"'||c==="'"))o=!0,s=c;else if(o&&c===s)o=!1,s="";else if(!o&&c===","){let l=r.trim();l&&n.push(io(l)),r=""}else r+=c}let i=r.trim();return i&&n.push(io(i)),n}function rR(e,t){if(!e)return t;let n=Array.isArray(e)?e:[e],r=Array.isArray(t)?t:[t];return[...n,...r]}var nt=require("fs"),_h=require("path");function gc(e){return(0,_h.join)(Cs,`${e}.json`)}function kh(e){let t=gc(e);if(!(0,nt.existsSync)(t))return{contentHashes:new Set,realPaths:new Set};try{let n=(0,nt.readFileSync)(t,"utf-8"),r=JSON.parse(n);return{contentHashes:new Set(r.injectedHashes),realPaths:new Set(r.injectedRealPaths??[])}}catch{return{contentHashes:new Set,realPaths:new Set}}}function Sh(e,t){(0,nt.existsSync)(Cs)||(0,nt.mkdirSync)(Cs,{recursive:!0});let n={sessionId:e,injectedHashes:[...t.contentHashes],injectedRealPaths:[...t.realPaths],updatedAt:Date.now()};(0,nt.writeFileSync)(gc(e),JSON.stringify(n,null,2))}function vh(e){let t=gc(e);(0,nt.existsSync)(t)&&(0,nt.unlinkSync)(t)}function bh(e){let t=new Map;function n(i){return t.has(i)||t.set(i,kh(i)),t.get(i)}function r(i){return i?i.startsWith("/")?i:(0,ao.resolve)(e,i):null}function o(i,a){let c=r(i);if(!c)return[];let l=dc(c),u=n(a),d=(0,yc.homedir)(),p=pc(l,d,c),f=[];for(let m of p)if(!hh(m.realPath,u.realPaths))try{let g=(0,hc.readFileSync)(m.path,"utf-8"),{metadata:y,body:w}=mc(g),_;if(m.isSingleFile)_="copilot-instructions (always apply)";else{let S=fc(y,c,l);if(!S.applies)continue;_=S.reason??"matched"}let h=yh(w);if(wh(h,u.contentHashes))continue;let v=l?(0,ao.relative)(l,m.path):m.path;f.push({relativePath:v,matchReason:_,content:w,distance:m.distance}),u.realPaths.add(m.realPath),u.contentHashes.add(h)}catch{}return f.length>0&&(f.sort((m,g)=>m.distance-g.distance),Sh(a,u)),f}function s(i){if(i.length===0)return"";let a="";for(let c of i)a+=`
1611
1611
 
1612
1612
  [Rule: ${c.relativePath}]
1613
1613
  [Match: ${c.matchReason}]
1614
- ${c.content}`;return a}return{processToolExecution:(i,a,c)=>{if(!oc.includes(i.toLowerCase()))return"";let l=o(a,c);return s(l)},getRulesForFile:i=>{let a=r(i);if(!a)return[];let c=ac(a),l=(0,fc.homedir)(),u=cc(c,l,a),d=[];for(let p of u)try{let f=(0,pc.readFileSync)(p.path,"utf-8"),{metadata:m,body:g}=uc(f),y;if(p.isSingleFile)y="copilot-instructions (always apply)";else{let k=lc(m,a,c);if(!k.applies)continue;y=k.reason??"matched"}let w=c?(0,ao.relative)(c,p.path):p.path;d.push({relativePath:w,matchReason:y,content:g,distance:p.distance})}catch{}return d.sort((p,f)=>p.distance-f.distance)},clearSession:i=>{t.delete(i),yh(i)},isTrackedTool:i=>oc.includes(i.toLowerCase())}}var Cs=require("node:fs"),Yt=require("node:path");var rt=require("node:fs"),Sh=require("node:path");var mc=require("node:path"),kh=require("node:os"),HC=(0,mc.join)((0,kh.homedir)(),".olympus"),bs=(0,mc.join)(HC,"directory-readme"),_h="README.md",gc=["read","write","edit","multiedit"];function hc(e){return(0,Sh.join)(bs,`${e}.json`)}function vh(e){let t=hc(e);if(!(0,rt.existsSync)(t))return new Set;try{let n=(0,rt.readFileSync)(t,"utf-8"),r=JSON.parse(n);return new Set(r.injectedPaths)}catch{return new Set}}function Th(e,t){(0,rt.existsSync)(bs)||(0,rt.mkdirSync)(bs,{recursive:!0});let n={sessionID:e,injectedPaths:Array.from(t),updatedAt:Date.now()};(0,rt.writeFileSync)(hc(e),JSON.stringify(n,null,2))}function Eh(e){let t=hc(e);(0,rt.existsSync)(t)&&(0,rt.unlinkSync)(t)}var bh=4,VC=5e3;function qC(e,t=VC){if(Math.ceil(e.length/bh)<=t)return{result:e,truncated:!1};let r=t*bh;return{result:e.slice(0,r),truncated:!0}}function Ch(e){let t=new Map;function n(i){return t.has(i)||t.set(i,vh(i)),t.get(i)}function r(i){return i?i.startsWith("/")?i:(0,Yt.resolve)(e,i):null}function o(i){let a=[],c=i;for(;;){let l=(0,Yt.join)(c,_h);if((0,Cs.existsSync)(l)&&a.push(l),c===e)break;let u=(0,Yt.dirname)(c);if(u===c||!u.startsWith(e))break;c=u}return a.reverse()}function s(i,a){let c=r(i);if(!c)return"";let l=(0,Yt.dirname)(c),u=n(a),d=o(l),p="";for(let f of d){let m=(0,Yt.dirname)(f);if(!u.has(m))try{let g=(0,Cs.readFileSync)(f,"utf-8"),{result:y,truncated:w}=qC(g),k=w?`
1614
+ ${c.content}`;return a}return{processToolExecution:(i,a,c)=>{if(!cc.includes(i.toLowerCase()))return"";let l=o(a,c);return s(l)},getRulesForFile:i=>{let a=r(i);if(!a)return[];let c=dc(a),l=(0,yc.homedir)(),u=pc(c,l,a),d=[];for(let p of u)try{let f=(0,hc.readFileSync)(p.path,"utf-8"),{metadata:m,body:g}=mc(f),y;if(p.isSingleFile)y="copilot-instructions (always apply)";else{let _=fc(m,a,c);if(!_.applies)continue;y=_.reason??"matched"}let w=c?(0,ao.relative)(c,p.path):p.path;d.push({relativePath:w,matchReason:y,content:g,distance:p.distance})}catch{}return d.sort((p,f)=>p.distance-f.distance)},clearSession:i=>{t.delete(i),vh(i)},isTrackedTool:i=>cc.includes(i.toLowerCase())}}var xs=require("node:fs"),Yt=require("node:path");var rt=require("node:fs"),Ch=require("node:path");var wc=require("node:path"),Th=require("node:os"),oR=(0,wc.join)((0,Th.homedir)(),".olympus"),Rs=(0,wc.join)(oR,"directory-readme"),Eh="README.md",_c=["read","write","edit","multiedit"];function kc(e){return(0,Ch.join)(Rs,`${e}.json`)}function Rh(e){let t=kc(e);if(!(0,rt.existsSync)(t))return new Set;try{let n=(0,rt.readFileSync)(t,"utf-8"),r=JSON.parse(n);return new Set(r.injectedPaths)}catch{return new Set}}function xh(e,t){(0,rt.existsSync)(Rs)||(0,rt.mkdirSync)(Rs,{recursive:!0});let n={sessionID:e,injectedPaths:Array.from(t),updatedAt:Date.now()};(0,rt.writeFileSync)(kc(e),JSON.stringify(n,null,2))}function Ph(e){let t=kc(e);(0,rt.existsSync)(t)&&(0,rt.unlinkSync)(t)}var Ah=4,sR=5e3;function iR(e,t=sR){if(Math.ceil(e.length/Ah)<=t)return{result:e,truncated:!1};let r=t*Ah;return{result:e.slice(0,r),truncated:!0}}function Ih(e){let t=new Map;function n(i){return t.has(i)||t.set(i,Rh(i)),t.get(i)}function r(i){return i?i.startsWith("/")?i:(0,Yt.resolve)(e,i):null}function o(i){let a=[],c=i;for(;;){let l=(0,Yt.join)(c,Eh);if((0,xs.existsSync)(l)&&a.push(l),c===e)break;let u=(0,Yt.dirname)(c);if(u===c||!u.startsWith(e))break;c=u}return a.reverse()}function s(i,a){let c=r(i);if(!c)return"";let l=(0,Yt.dirname)(c),u=n(a),d=o(l),p="";for(let f of d){let m=(0,Yt.dirname)(f);if(!u.has(m))try{let g=(0,xs.readFileSync)(f,"utf-8"),{result:y,truncated:w}=iR(g),_=w?`
1615
1615
 
1616
1616
  [Note: Content was truncated to save context window space. For full context, please read the file directly: ${f}]`:"";p+=`
1617
1617
 
1618
1618
  [Project README: ${f}]
1619
- ${y}${k}`,u.add(m)}catch{}}return p&&Th(a,u),p}return{processToolExecution:(i,a,c)=>gc.includes(i.toLowerCase())?s(a,c):"",getReadmesForFile:i=>{let a=r(i);if(!a)return[];let c=(0,Yt.dirname)(a);return o(c)},clearSession:i=>{t.delete(i),Eh(i)},isTrackedTool:i=>gc.includes(i.toLowerCase())}}var Rh="non-interactive-env",xh={CI:"true",DEBIAN_FRONTEND:"noninteractive",GIT_TERMINAL_PROMPT:"0",GCM_INTERACTIVE:"never",HOMEBREW_NO_AUTO_UPDATE:"1",GIT_EDITOR:":",EDITOR:":",VISUAL:"",GIT_SEQUENCE_EDITOR:":",GIT_MERGE_AUTOEDIT:"no",GIT_PAGER:"cat",PAGER:"cat",npm_config_yes:"true",PIP_NO_INPUT:"1",YARN_ENABLE_IMMUTABLE_INSTALLS:"false"},yc={npm:{bad:["npm init","npm install (prompts)"],good:["npm init -y","npm install --yes"]},apt:{bad:["apt-get install pkg"],good:["apt-get install -y pkg","DEBIAN_FRONTEND=noninteractive apt-get install pkg"]},pip:{bad:["pip install pkg (with prompts)"],good:["pip install --no-input pkg","PIP_NO_INPUT=1 pip install pkg"]},git:{bad:["git commit","git merge branch","git add -p","git rebase -i"],good:["git commit -m 'msg'","git merge --no-edit branch","git add .","git rebase --no-edit"]},system:{bad:["rm file (prompts)","cp a b (prompts)","ssh host"],good:["rm -f file","cp -f a b","ssh -o BatchMode=yes host","unzip -o file.zip"]},banned:["vim","nano","vi","emacs","less","more","man","python (REPL)","node (REPL)","git add -p","git rebase -i"],workarounds:{yesPipe:"yes | ./script.sh",heredoc:`./script.sh <<EOF
1619
+ ${y}${_}`,u.add(m)}catch{}}return p&&xh(a,u),p}return{processToolExecution:(i,a,c)=>_c.includes(i.toLowerCase())?s(a,c):"",getReadmesForFile:i=>{let a=r(i);if(!a)return[];let c=(0,Yt.dirname)(a);return o(c)},clearSession:i=>{t.delete(i),Ph(i)},isTrackedTool:i=>_c.includes(i.toLowerCase())}}var Oh="non-interactive-env",$h={CI:"true",DEBIAN_FRONTEND:"noninteractive",GIT_TERMINAL_PROMPT:"0",GCM_INTERACTIVE:"never",HOMEBREW_NO_AUTO_UPDATE:"1",GIT_EDITOR:":",EDITOR:":",VISUAL:"",GIT_SEQUENCE_EDITOR:":",GIT_MERGE_AUTOEDIT:"no",GIT_PAGER:"cat",PAGER:"cat",npm_config_yes:"true",PIP_NO_INPUT:"1",YARN_ENABLE_IMMUTABLE_INSTALLS:"false"},Sc={npm:{bad:["npm init","npm install (prompts)"],good:["npm init -y","npm install --yes"]},apt:{bad:["apt-get install pkg"],good:["apt-get install -y pkg","DEBIAN_FRONTEND=noninteractive apt-get install pkg"]},pip:{bad:["pip install pkg (with prompts)"],good:["pip install --no-input pkg","PIP_NO_INPUT=1 pip install pkg"]},git:{bad:["git commit","git merge branch","git add -p","git rebase -i"],good:["git commit -m 'msg'","git merge --no-edit branch","git add .","git rebase --no-edit"]},system:{bad:["rm file (prompts)","cp a b (prompts)","ssh host"],good:["rm -f file","cp -f a b","ssh -o BatchMode=yes host","unzip -o file.zip"]},banned:["vim","nano","vi","emacs","less","more","man","python (REPL)","node (REPL)","git add -p","git rebase -i"],workarounds:{yesPipe:"yes | ./script.sh",heredoc:`./script.sh <<EOF
1620
1620
  option1
1621
1621
  option2
1622
- EOF`,expectAlternative:"Use environment variables or config files instead of expect"}};var Ph=yc.banned.filter(e=>!e.includes("(")).map(e=>new RegExp(`\\b${e}\\b`));function YC(e){for(let t=0;t<Ph.length;t++)if(Ph[t].test(e))return yc.banned[t]}function KC(e){return e===""?"''":/[^a-zA-Z0-9_\-.:\/]/.test(e)?`'${e.replace(/'/g,"'\\''")}'`:e}function JC(e){return`export ${Object.entries(e).map(([n,r])=>`${n}=${KC(r)}`).join(" ")};`}var wc={name:Rh,async beforeCommand(e){let t=YC(e),n=t?`Warning: '${t}' is an interactive command that may hang in non-interactive environments.`:void 0;return/\bgit\b/.test(e)?{command:`${JC(xh)} ${e}`,warning:n}:{command:e,warning:n}}};var _c=require("child_process");var Ih="olympus-orchestrator",Ah=".olympus/",Oh=["Write","Edit","write","edit"],$h=`
1622
+ EOF`,expectAlternative:"Use environment variables or config files instead of expect"}};var Dh=Sc.banned.filter(e=>!e.includes("(")).map(e=>new RegExp(`\\b${e}\\b`));function aR(e){for(let t=0;t<Dh.length;t++)if(Dh[t].test(e))return Sc.banned[t]}function cR(e){return e===""?"''":/[^a-zA-Z0-9_\-.:\/]/.test(e)?`'${e.replace(/'/g,"'\\''")}'`:e}function lR(e){return`export ${Object.entries(e).map(([n,r])=>`${n}=${cR(r)}`).join(" ")};`}var vc={name:Oh,async beforeCommand(e){let t=aR(e),n=t?`Warning: '${t}' is an interactive command that may hang in non-interactive environments.`:void 0;return/\bgit\b/.test(e)?{command:`${lR($h)} ${e}`,warning:n}:{command:e,warning:n}}};var Tc=require("child_process");var Nh="olympus-orchestrator",Fh=".olympus/",jh=["Write","Edit","write","edit"],Mh=`
1623
1623
 
1624
1624
  ---
1625
1625
 
@@ -1645,7 +1645,7 @@ You should NOT:
1645
1645
  3. Verify the subagent's work after completion
1646
1646
 
1647
1647
  ---
1648
- `;var Dh=`[SYSTEM REMINDER - QUEST CONTINUATION]
1648
+ `;var Lh=`[SYSTEM REMINDER - QUEST CONTINUATION]
1649
1649
 
1650
1650
  You have an active work plan with incomplete tasks. Continue working.
1651
1651
 
@@ -1654,7 +1654,7 @@ RULES:
1654
1654
  - Mark each checkbox [x] in the plan file when done
1655
1655
  - Learnings are automatically captured in .olympus/learning/discoveries.jsonl
1656
1656
  - Do not stop until all tasks are complete
1657
- - If blocked, document the blocker and move to the next task`,Nh=`**MANDATORY VERIFICATION - SUBAGENTS LIE**
1657
+ - If blocked, document the blocker and move to the next task`,Uh=`**MANDATORY VERIFICATION - SUBAGENTS LIE**
1658
1658
 
1659
1659
  Subagents FREQUENTLY claim completion when:
1660
1660
  - Tests are actually FAILING
@@ -1669,7 +1669,7 @@ Subagents FREQUENTLY claim completion when:
1669
1669
  3. Check build/typecheck - Must succeed
1670
1670
 
1671
1671
  DO NOT TRUST THE AGENT'S SELF-REPORT.
1672
- VERIFY EACH CLAIM WITH YOUR OWN TOOL CALLS.`,Fh=`
1672
+ VERIFY EACH CLAIM WITH YOUR OWN TOOL CALLS.`,Wh=`
1673
1673
 
1674
1674
  [SYSTEM DIRECTIVE - SINGLE TASK ONLY]
1675
1675
 
@@ -1692,7 +1692,7 @@ If you were NOT given **exactly ONE atomic task**, you MUST:
1692
1692
  - Batch delegation = sloppy work = rework = wasted tokens
1693
1693
 
1694
1694
  **REFUSE multi-task requests. DEMAND single-task clarity.**
1695
- `,jh=`
1695
+ `,Bh=`
1696
1696
 
1697
1697
  ================================================================================
1698
1698
  HARD BLOCK: DELEGATION REQUIRED
@@ -1731,41 +1731,41 @@ This is a HARD BLOCK. The operation will NOT be executed.
1731
1731
  Delegate to a subagent to proceed.
1732
1732
 
1733
1733
  ================================================================================
1734
- `;var co=".olympus",Rs="quest.json",zC=`${co}/${Rs}`,Mh="notepads",QC=`${co}/${Mh}`;var mt=require("fs"),xs=require("path");function Lh(e){return(0,xs.join)(e,co,Rs)}function Ps(e){let t=Lh(e);if(!(0,mt.existsSync)(t))return null;try{let n=(0,mt.readFileSync)(t,"utf-8");return JSON.parse(n)}catch{return null}}function Is(e){if(!(0,mt.existsSync)(e))return{total:0,completed:0,isComplete:!0};try{let t=(0,mt.readFileSync)(e,"utf-8"),n=t.match(/^[-*]\s*\[\s*\]/gm)||[],r=t.match(/^[-*]\s*\[[xX]\]/gm)||[],o=n.length+r.length,s=r.length;return{total:o,completed:s,isComplete:o===0||s===o}}catch{return{total:0,completed:0,isComplete:!0}}}var lo=class{recentTasks=[];maxTracked=3;recordTaskCompletion(t){this.recentTasks.unshift(t),this.recentTasks.length>this.maxTracked&&this.recentTasks.pop()}isVerificationEdit(t,n){return this.recentTasks.some(o=>o.filesModified.includes(t))&&n<10}getRecentTaskFiles(){let t=this.recentTasks.flatMap(n=>n.filesModified);return Array.from(new Set(t))}getRecentTasks(){return[...this.recentTasks]}clear(){this.recentTasks=[]}get trackedCount(){return this.recentTasks.length}},XD=new lo;var Fn=require("fs"),kc=require("path");function uo(e,t){let n=t||process.cwd(),r=(0,kc.join)(n,".olympus","logs"),o=(0,kc.join)(r,"hook-violations.jsonl");try{(0,Fn.existsSync)(r)||(0,Fn.mkdirSync)(r,{recursive:!0});let s=JSON.stringify(e)+`
1735
- `;(0,Fn.appendFileSync)(o,s,"utf-8")}catch(s){console.error("[Hook Logging] Failed to log violation:",s)}}var Uh=new lo;function Wh(e){return e?e.replace(/\\/g,"/").includes(Ah):!0}function eR(e){if(!e)return!1;let t=e.replace(/\\/g,"/");return t.includes("__tests__/")||t.endsWith(".test.ts")||t.endsWith(".test.js")||t.endsWith(".spec.ts")||t.endsWith(".spec.js")}function tR(e,t){if(!t)return 0;if(e==="Edit"||e==="edit"){let n=t.old_string??"",r=t.new_string??"";if(!n&&!r)return 0;let o=n.split(`
1734
+ `;var co=".olympus",Ps="quest.json",uR=`${co}/${Ps}`,Gh="notepads",dR=`${co}/${Gh}`;var mt=require("fs"),As=require("path");function Hh(e){return(0,As.join)(e,co,Ps)}function Is(e){let t=Hh(e);if(!(0,mt.existsSync)(t))return null;try{let n=(0,mt.readFileSync)(t,"utf-8");return JSON.parse(n)}catch{return null}}function Os(e){if(!(0,mt.existsSync)(e))return{total:0,completed:0,isComplete:!0};try{let t=(0,mt.readFileSync)(e,"utf-8"),n=t.match(/^[-*]\s*\[\s*\]/gm)||[],r=t.match(/^[-*]\s*\[[xX]\]/gm)||[],o=n.length+r.length,s=r.length;return{total:o,completed:s,isComplete:o===0||s===o}}catch{return{total:0,completed:0,isComplete:!0}}}var lo=class{recentTasks=[];maxTracked=3;recordTaskCompletion(t){this.recentTasks.unshift(t),this.recentTasks.length>this.maxTracked&&this.recentTasks.pop()}isVerificationEdit(t,n){return this.recentTasks.some(o=>o.filesModified.includes(t))&&n<10}getRecentTaskFiles(){let t=this.recentTasks.flatMap(n=>n.filesModified);return Array.from(new Set(t))}getRecentTasks(){return[...this.recentTasks]}clear(){this.recentTasks=[]}get trackedCount(){return this.recentTasks.length}},xN=new lo;var Fn=require("fs"),bc=require("path");function uo(e,t){let n=t||process.cwd(),r=(0,bc.join)(n,".olympus","logs"),o=(0,bc.join)(r,"hook-violations.jsonl");try{(0,Fn.existsSync)(r)||(0,Fn.mkdirSync)(r,{recursive:!0});let s=JSON.stringify(e)+`
1735
+ `;(0,Fn.appendFileSync)(o,s,"utf-8")}catch(s){console.error("[Hook Logging] Failed to log violation:",s)}}var Vh=new lo;function qh(e){return e?e.replace(/\\/g,"/").includes(Fh):!0}function mR(e){if(!e)return!1;let t=e.replace(/\\/g,"/");return t.includes("__tests__/")||t.endsWith(".test.ts")||t.endsWith(".test.js")||t.endsWith(".spec.ts")||t.endsWith(".spec.js")}function gR(e,t){if(!t)return 0;if(e==="Edit"||e==="edit"){let n=t.old_string??"",r=t.new_string??"";if(!n&&!r)return 0;let o=n.split(`
1736
1736
  `).length,s=r.split(`
1737
1737
  `).length;return Math.abs(s-o)}if(e==="Write"||e==="write"){let n=t.content??"";return n?n.split(`
1738
- `).length:0}return 0}function Gh(e){return Oh.includes(e)}function nR(e){try{let t=(0,_c.execSync)("git diff --numstat HEAD",{cwd:e,encoding:"utf-8",timeout:5e3}).trim();if(!t)return[];let n=(0,_c.execSync)("git status --porcelain",{cwd:e,encoding:"utf-8",timeout:5e3}).trim(),r=new Map;for(let s of n.split(`
1738
+ `).length:0}return 0}function Yh(e){return jh.includes(e)}function hR(e){try{let t=(0,Tc.execSync)("git diff --numstat HEAD",{cwd:e,encoding:"utf-8",timeout:5e3}).trim();if(!t)return[];let n=(0,Tc.execSync)("git status --porcelain",{cwd:e,encoding:"utf-8",timeout:5e3}).trim(),r=new Map;for(let s of n.split(`
1739
1739
  `)){if(!s)continue;let i=s.substring(0,2).trim(),a=s.substring(3);i==="A"||i==="??"?r.set(a,"added"):i==="D"?r.set(a,"deleted"):r.set(a,"modified")}let o=[];for(let s of t.split(`
1740
- `)){let i=s.split(" ");if(i.length<3)continue;let[a,c,l]=i,u=a==="-"?0:parseInt(a,10),d=c==="-"?0:parseInt(c,10);o.push({path:l,added:u,removed:d,status:r.get(l)??"modified"})}return o}catch{return[]}}function rR(e){if(e.length===0)return`[FILE CHANGES SUMMARY]
1740
+ `)){let i=s.split(" ");if(i.length<3)continue;let[a,c,l]=i,u=a==="-"?0:parseInt(a,10),d=c==="-"?0:parseInt(c,10);o.push({path:l,added:u,removed:d,status:r.get(l)??"modified"})}return o}catch{return[]}}function yR(e){if(e.length===0)return`[FILE CHANGES SUMMARY]
1741
1741
  No file changes detected.
1742
1742
  `;let t=e.filter(s=>s.status==="modified"),n=e.filter(s=>s.status==="added"),r=e.filter(s=>s.status==="deleted"),o=["[FILE CHANGES SUMMARY]"];if(t.length>0){o.push("Modified files:");for(let s of t)o.push(` ${s.path} (+${s.added}, -${s.removed})`);o.push("")}if(n.length>0){o.push("Created files:");for(let s of n)o.push(` ${s.path} (+${s.added})`);o.push("")}if(r.length>0){o.push("Deleted files:");for(let s of r)o.push(` ${s.path} (-${s.removed})`);o.push("")}return o.join(`
1743
- `)}function Bh(e){let t=Nh;return e&&(t+=`
1743
+ `)}function Kh(e){let t=Uh;return e&&(t+=`
1744
1744
 
1745
1745
  ---
1746
1746
 
1747
1747
  **If ANY verification fails, resume the subagent with the fix:**
1748
- Task tool with resume="${e}", prompt="fix: [describe the specific failure]"`),t}function oR(e,t,n){let r=t.total-t.completed;return`
1748
+ Task tool with resume="${e}", prompt="fix: [describe the specific failure]"`),t}function wR(e,t,n){let r=t.total-t.completed;return`
1749
1749
  ---
1750
1750
 
1751
1751
  **State:** Plan: ${e} | ${t.completed}/${t.total} done, ${r} left
1752
1752
 
1753
1753
  ---
1754
1754
 
1755
- ${Bh(n)}
1755
+ ${Kh(n)}
1756
1756
 
1757
- ALL pass? \u2192 commit atomic unit, mark \`[x]\`, next task.`}function sR(e,t,n){return Dh.replace(/{PLAN_NAME}/g,e)+`
1757
+ ALL pass? \u2192 commit atomic unit, mark \`[x]\`, next task.`}function _R(e,t,n){return Lh.replace(/{PLAN_NAME}/g,e)+`
1758
1758
 
1759
- [Status: ${n-t}/${n} completed, ${t} remaining]`}function iR(e){let{toolName:t,toolInput:n,directory:r}=e,o=r||process.cwd();if(!Gh(t))return{continue:!0};let s=n?.filePath??n?.path??n?.file;if(!s)return{continue:!0};let i=s.replace(/\\/g,"/");if(Wh(i))return uo({timestamp:new Date().toISOString(),filePath:i,toolName:t,wasBlocked:!1,reason:"Allowed: .olympus/ path"},o),{continue:!0};if(eR(i))return uo({timestamp:new Date().toISOString(),filePath:i,toolName:t,wasBlocked:!1,reason:"Allowed: Test file"},o),{continue:!0};let a=tR(t,n);return Uh.isVerificationEdit(i,a)?(uo({timestamp:new Date().toISOString(),filePath:i,toolName:t,linesChanged:a,wasBlocked:!1,reason:`Allowed: Verification edit (${a} lines on recent task file)`},o),{continue:!0}):(uo({timestamp:new Date().toISOString(),filePath:i,toolName:t,linesChanged:a,wasBlocked:!0,reason:"Blocked: Direct source file modification (delegation required)"},o),{continue:!1,message:jh})}function aR(e,t){let{toolName:n,toolInput:r,directory:o,sessionId:s}=e,i=o||process.cwd();if(Gh(n)){let a=r?.filePath??r?.path??r?.file;if(a&&!Wh(a))return{continue:!0,modifiedOutput:t+$h}}if(n==="Task"||n==="task"){if(t.includes("Background task launched")||t.includes("Background task resumed"))return{continue:!0};let c=nR(i),l=c.map(p=>p.path);Uh.recordTaskCompletion({timestamp:Date.now(),filesModified:l,taskId:s||`task-${Date.now()}`});let u=rR(c),d=Ps(i);if(d){let p=Is(d.active_plan);return{continue:!0,modifiedOutput:`
1759
+ [Status: ${n-t}/${n} completed, ${t} remaining]`}function kR(e){let{toolName:t,toolInput:n,directory:r}=e,o=r||process.cwd();if(!Yh(t))return{continue:!0};let s=n?.filePath??n?.path??n?.file;if(!s)return{continue:!0};let i=s.replace(/\\/g,"/");if(qh(i))return uo({timestamp:new Date().toISOString(),filePath:i,toolName:t,wasBlocked:!1,reason:"Allowed: .olympus/ path"},o),{continue:!0};if(mR(i))return uo({timestamp:new Date().toISOString(),filePath:i,toolName:t,wasBlocked:!1,reason:"Allowed: Test file"},o),{continue:!0};let a=gR(t,n);return Vh.isVerificationEdit(i,a)?(uo({timestamp:new Date().toISOString(),filePath:i,toolName:t,linesChanged:a,wasBlocked:!1,reason:`Allowed: Verification edit (${a} lines on recent task file)`},o),{continue:!0}):(uo({timestamp:new Date().toISOString(),filePath:i,toolName:t,linesChanged:a,wasBlocked:!0,reason:"Blocked: Direct source file modification (delegation required)"},o),{continue:!1,message:Bh})}function SR(e,t){let{toolName:n,toolInput:r,directory:o,sessionId:s}=e,i=o||process.cwd();if(Yh(n)){let a=r?.filePath??r?.path??r?.file;if(a&&!qh(a))return{continue:!0,modifiedOutput:t+Mh}}if(n==="Task"||n==="task"){if(t.includes("Background task launched")||t.includes("Background task resumed"))return{continue:!0};let c=hR(i),l=c.map(p=>p.path);Vh.recordTaskCompletion({timestamp:Date.now(),filesModified:l,taskId:s||`task-${Date.now()}`});let u=yR(c),d=Is(i);if(d){let p=Os(d.active_plan);return{continue:!0,modifiedOutput:`
1760
1760
  ## SUBAGENT WORK COMPLETED
1761
1761
 
1762
1762
  ${u}
1763
1763
  <system-reminder>
1764
- ${oR(d.plan_name,p,s)}
1764
+ ${wR(d.plan_name,p,s)}
1765
1765
  </system-reminder>`}}return{continue:!0,modifiedOutput:t+`
1766
1766
  <system-reminder>
1767
- ${Bh(s)}
1768
- </system-reminder>`}}return{continue:!0}}function cR(e){let t=Ps(e);if(!t)return{shouldContinue:!1};let n=Is(t.active_plan);if(n.isComplete)return{shouldContinue:!1};let r=n.total-n.completed;return{shouldContinue:!0,message:sR(t.plan_name,r,n.total)}}function As(e){return{name:Ih,preTool:(t,n)=>iR({toolName:t,toolInput:n,directory:e}),postTool:(t,n,r)=>aR({toolName:t,toolInput:n,directory:e},r),checkContinuation:()=>cR(e),getSingleTaskDirective:()=>Fh}}function Hh(e){if(!e||typeof e!="object")return null;let t=e;return t.file_path||t.filePath||t.path||t.file}function Vh(){P({name:"rulesInjector",event:"PreToolUse",priority:10,matcher:/^(read|edit|write|glob|grep)$/i,handler:e=>{let t=wh(e.directory||process.cwd()),n=Hh(e.toolInput);if(!n)return{continue:!0};let r=t.processToolExecution(e.toolName,n,e.sessionId||"default");return{continue:!0,hookSpecificOutput:r?{hookEventName:"PreToolUse",additionalContext:r}:void 0}}}),P({name:"directoryReadmeInjector",event:"PreToolUse",priority:20,matcher:/^(read|edit|write|glob|grep|bash)$/i,handler:e=>{let t=Ch(e.directory||process.cwd()),n=Hh(e.toolInput);if(!n)return{continue:!0};let r=t.processToolExecution(e.toolName,n,e.sessionId||"default");return{continue:!0,hookSpecificOutput:r?{hookEventName:"PreToolUse",additionalContext:r}:void 0}}}),P({name:"nonInteractiveEnv",event:"PreToolUse",priority:30,matcher:/^bash$/i,handler:async e=>{let t=e.toolInput;if(!t?.command)return{continue:!0};try{if(!wc.beforeCommand)return{continue:!0};let n=await wc.beforeCommand(t.command);return{continue:!0,hookSpecificOutput:n.warning?{hookEventName:"PreToolUse",additionalContext:n.warning}:void 0,modifiedInput:n.command!==t.command?{...t,command:n.command}:void 0}}catch(n){return console.error("[nonInteractiveEnv] Error:",n),{continue:!0}}}}),P({name:"olympusOrchestratorPre",event:"PreToolUse",priority:40,matcher:/^(write|edit|bash|task)$/i,handler:e=>As(e.directory||process.cwd()).preTool(e.toolName,e.toolInput)})}var lR=["oldString and newString must be different","oldString not found","oldString found multiple times","old_string not found","old_string and new_string must be different"],uR=`
1767
+ ${Kh(s)}
1768
+ </system-reminder>`}}return{continue:!0}}function vR(e){let t=Is(e);if(!t)return{shouldContinue:!1};let n=Os(t.active_plan);if(n.isComplete)return{shouldContinue:!1};let r=n.total-n.completed;return{shouldContinue:!0,message:_R(t.plan_name,r,n.total)}}function $s(e){return{name:Nh,preTool:(t,n)=>kR({toolName:t,toolInput:n,directory:e}),postTool:(t,n,r)=>SR({toolName:t,toolInput:n,directory:e},r),checkContinuation:()=>vR(e),getSingleTaskDirective:()=>Wh}}function Jh(e){if(!e||typeof e!="object")return null;let t=e;return t.file_path||t.filePath||t.path||t.file}function zh(){P({name:"rulesInjector",event:"PreToolUse",priority:10,matcher:/^(read|edit|write|glob|grep)$/i,handler:e=>{let t=bh(e.directory||process.cwd()),n=Jh(e.toolInput);if(!n)return{continue:!0};let r=t.processToolExecution(e.toolName,n,e.sessionId||"default");return{continue:!0,hookSpecificOutput:r?{hookEventName:"PreToolUse",additionalContext:r}:void 0}}}),P({name:"directoryReadmeInjector",event:"PreToolUse",priority:20,matcher:/^(read|edit|write|glob|grep|bash)$/i,handler:e=>{let t=Ih(e.directory||process.cwd()),n=Jh(e.toolInput);if(!n)return{continue:!0};let r=t.processToolExecution(e.toolName,n,e.sessionId||"default");return{continue:!0,hookSpecificOutput:r?{hookEventName:"PreToolUse",additionalContext:r}:void 0}}}),P({name:"nonInteractiveEnv",event:"PreToolUse",priority:30,matcher:/^bash$/i,handler:async e=>{let t=e.toolInput;if(!t?.command)return{continue:!0};try{if(!vc.beforeCommand)return{continue:!0};let n=await vc.beforeCommand(t.command);return{continue:!0,hookSpecificOutput:n.warning?{hookEventName:"PreToolUse",additionalContext:n.warning}:void 0,modifiedInput:n.command!==t.command?{...t,command:n.command}:void 0}}catch(n){return console.error("[nonInteractiveEnv] Error:",n),{continue:!0}}}}),P({name:"olympusOrchestratorPre",event:"PreToolUse",priority:40,matcher:/^(write|edit|bash|task)$/i,handler:e=>$s(e.directory||process.cwd()).preTool(e.toolName,e.toolInput)})}var bR=["oldString and newString must be different","oldString not found","oldString found multiple times","old_string not found","old_string and new_string must be different"],TR=`
1769
1769
  [EDIT ERROR - IMMEDIATE ACTION REQUIRED]
1770
1770
 
1771
1771
  You made an Edit mistake. STOP and do this NOW:
@@ -1776,7 +1776,7 @@ You made an Edit mistake. STOP and do this NOW:
1776
1776
  4. CONTINUE with corrected action based on the real file content
1777
1777
 
1778
1778
  DO NOT attempt another edit until you've read and verified the file state.
1779
- `;function dR(e){let t=e.toLowerCase();return lR.some(n=>t.includes(n.toLowerCase()))}function qh(){return{afterToolExecute:(e,t)=>e.tool.toLowerCase()!=="edit"?t:dR(t.output)?{...t,output:t.output+uR}:t}}var Jh=T(require("fs"),1),$s=T(require("path"),1),zh=require("os");var Os=new Set(["given","when","then","arrange","act","assert","when & then","when&then"]),Sc=["type:","noqa","pyright:","ruff:","mypy:","pylint:","flake8:","pyre:","pytype:","eslint-disable","eslint-enable","eslint-ignore","prettier-ignore","ts-ignore","ts-expect-error","ts-nocheck","@ts-ignore","@ts-expect-error","@ts-nocheck","clippy::","allow(","deny(","warn(","forbid(","nolint","go:generate","go:build","go:embed","coverage:","c8 ignore","istanbul ignore","biome-ignore","region","endregion","#region","#endregion"],vc=`COMMENT/DOCSTRING DETECTED - IMMEDIATE ACTION REQUIRED
1779
+ `;function ER(e){let t=e.toLowerCase();return bR.some(n=>t.includes(n.toLowerCase()))}function Qh(){return{afterToolExecute:(e,t)=>e.tool.toLowerCase()!=="edit"?t:ER(t.output)?{...t,output:t.output+TR}:t}}var ey=b(require("fs"),1),Ns=b(require("path"),1),ty=require("os");var Ds=new Set(["given","when","then","arrange","act","assert","when & then","when&then"]),Ec=["type:","noqa","pyright:","ruff:","mypy:","pylint:","flake8:","pyre:","pytype:","eslint-disable","eslint-enable","eslint-ignore","prettier-ignore","ts-ignore","ts-expect-error","ts-nocheck","@ts-ignore","@ts-expect-error","@ts-nocheck","clippy::","allow(","deny(","warn(","forbid(","nolint","go:generate","go:build","go:embed","coverage:","c8 ignore","istanbul ignore","biome-ignore","region","endregion","#region","#endregion"],Cc=`COMMENT/DOCSTRING DETECTED - IMMEDIATE ACTION REQUIRED
1780
1780
 
1781
1781
  Your recent changes contain comments or docstrings, which triggered this hook.
1782
1782
  You need to take immediate action. You must follow the conditions below.
@@ -1814,13 +1814,13 @@ MANDATORY REQUIREMENT: You must acknowledge this hook message and take one of th
1814
1814
  Review in the above priority order and take the corresponding action EVERY TIME this appears.
1815
1815
 
1816
1816
  Detected comments/docstrings:
1817
- `,Tc={js:/\/\/.*$|\/\*[\s\S]*?\*\//gm,ts:/\/\/.*$|\/\*[\s\S]*?\*\//gm,jsx:/\/\/.*$|\/\*[\s\S]*?\*\//gm,tsx:/\/\/.*$|\/\*[\s\S]*?\*\//gm,java:/\/\/.*$|\/\*[\s\S]*?\*\//gm,c:/\/\/.*$|\/\*[\s\S]*?\*\//gm,cpp:/\/\/.*$|\/\*[\s\S]*?\*\//gm,cs:/\/\/.*$|\/\*[\s\S]*?\*\//gm,go:/\/\/.*$/gm,rust:/\/\/.*$|\/\*[\s\S]*?\*\//gm,swift:/\/\/.*$|\/\*[\s\S]*?\*\//gm,kotlin:/\/\/.*$|\/\*[\s\S]*?\*\//gm,py:/#.*$|'''[\s\S]*?'''|"""[\s\S]*?"""/gm,rb:/#.*$|=begin[\s\S]*?=end/gm,sh:/#.*$/gm,bash:/#.*$/gm,zsh:/#.*$/gm,yaml:/#.*$/gm,yml:/#.*$/gm,toml:/#.*$/gm,html:/<!--[\s\S]*?-->/gm,xml:/<!--[\s\S]*?-->/gm,vue:/<!--[\s\S]*?-->|\/\/.*$|\/\*[\s\S]*?\*\//gm,svelte:/<!--[\s\S]*?-->|\/\/.*$|\/\*[\s\S]*?\*\//gm,sql:/--.*$/gm,lua:/--.*$|--\[\[[\s\S]*?\]\]/gm},Ec={".js":"js",".mjs":"js",".cjs":"js",".ts":"ts",".mts":"ts",".cts":"ts",".jsx":"jsx",".tsx":"tsx",".java":"java",".c":"c",".h":"c",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".hpp":"cpp",".cs":"cs",".go":"go",".rs":"rust",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".py":"py",".pyi":"py",".rb":"rb",".sh":"sh",".bash":"bash",".zsh":"zsh",".yaml":"yaml",".yml":"yml",".toml":"toml",".html":"html",".htm":"html",".xml":"xml",".vue":"vue",".svelte":"svelte",".sql":"sql",".lua":"lua"};function pR(e){return e.text.trim().startsWith("#!")&&e.lineNumber===1?{shouldSkip:!0,reason:"shebang"}:{shouldSkip:!1}}function fR(e){if(e.isDocstring)return{shouldSkip:!1};let t=e.text.toLowerCase().trim();for(let n of Os){if(t.startsWith(`#${n}`)||t.startsWith(`// ${n}`))return{shouldSkip:!0,reason:`BDD keyword: ${n}`};if(t.includes(n)&&t.split(/\s+/).some(o=>Os.has(o.replace(/[^a-z&]/g,""))))return{shouldSkip:!0,reason:"BDD keyword detected"}}return{shouldSkip:!1}}function mR(e){let t=e.text.toLowerCase().trim();for(let n of Sc)if(t.includes(n.toLowerCase()))return{shouldSkip:!0,reason:`directive: ${n}`};return{shouldSkip:!1}}function gR(e){return{shouldSkip:!1}}function hR(e){let t=e.text.toLowerCase(),n=["copyright","license","licensed under","spdx-license-identifier","all rights reserved","mit license","apache license","gnu general public","bsd license"];for(let r of n)if(t.includes(r))return{shouldSkip:!0,reason:"copyright/license"};return{shouldSkip:!1}}function yR(e){let t=e.text.toUpperCase(),n=["TODO","FIXME","HACK","XXX","NOTE","REVIEW"];for(let r of n)if(t.includes(r))return{shouldSkip:!0,reason:`todo marker: ${r}`};return{shouldSkip:!1}}var wR=[pR,fR,mR,hR,yR,gR];function bc(e){return e.filter(t=>{for(let n of wR)if(n(t).shouldSkip)return!1;return!0})}var kR=process.env.COMMENT_CHECKER_DEBUG==="1",_R=$s.join((0,zh.tmpdir)(),"comment-checker-debug.log");function jn(...e){if(kR){let t=`[${new Date().toISOString()}] [comment-checker] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
1818
- `;Jh.appendFileSync(_R,t)}}function SR(e){let t=$s.extname(e).toLowerCase();return Ec[t]}function Cc(e,t){let n=SR(t);if(!n)return jn("unsupported language for:",t),[];let r=Tc[n];if(!r)return jn("no pattern for language:",n),[];let o=[],s=e.split(`
1817
+ `,Rc={js:/\/\/.*$|\/\*[\s\S]*?\*\//gm,ts:/\/\/.*$|\/\*[\s\S]*?\*\//gm,jsx:/\/\/.*$|\/\*[\s\S]*?\*\//gm,tsx:/\/\/.*$|\/\*[\s\S]*?\*\//gm,java:/\/\/.*$|\/\*[\s\S]*?\*\//gm,c:/\/\/.*$|\/\*[\s\S]*?\*\//gm,cpp:/\/\/.*$|\/\*[\s\S]*?\*\//gm,cs:/\/\/.*$|\/\*[\s\S]*?\*\//gm,go:/\/\/.*$/gm,rust:/\/\/.*$|\/\*[\s\S]*?\*\//gm,swift:/\/\/.*$|\/\*[\s\S]*?\*\//gm,kotlin:/\/\/.*$|\/\*[\s\S]*?\*\//gm,py:/#.*$|'''[\s\S]*?'''|"""[\s\S]*?"""/gm,rb:/#.*$|=begin[\s\S]*?=end/gm,sh:/#.*$/gm,bash:/#.*$/gm,zsh:/#.*$/gm,yaml:/#.*$/gm,yml:/#.*$/gm,toml:/#.*$/gm,html:/<!--[\s\S]*?-->/gm,xml:/<!--[\s\S]*?-->/gm,vue:/<!--[\s\S]*?-->|\/\/.*$|\/\*[\s\S]*?\*\//gm,svelte:/<!--[\s\S]*?-->|\/\/.*$|\/\*[\s\S]*?\*\//gm,sql:/--.*$/gm,lua:/--.*$|--\[\[[\s\S]*?\]\]/gm},xc={".js":"js",".mjs":"js",".cjs":"js",".ts":"ts",".mts":"ts",".cts":"ts",".jsx":"jsx",".tsx":"tsx",".java":"java",".c":"c",".h":"c",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".hpp":"cpp",".cs":"cs",".go":"go",".rs":"rust",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".py":"py",".pyi":"py",".rb":"rb",".sh":"sh",".bash":"bash",".zsh":"zsh",".yaml":"yaml",".yml":"yml",".toml":"toml",".html":"html",".htm":"html",".xml":"xml",".vue":"vue",".svelte":"svelte",".sql":"sql",".lua":"lua"};function CR(e){return e.text.trim().startsWith("#!")&&e.lineNumber===1?{shouldSkip:!0,reason:"shebang"}:{shouldSkip:!1}}function RR(e){if(e.isDocstring)return{shouldSkip:!1};let t=e.text.toLowerCase().trim();for(let n of Ds){if(t.startsWith(`#${n}`)||t.startsWith(`// ${n}`))return{shouldSkip:!0,reason:`BDD keyword: ${n}`};if(t.includes(n)&&t.split(/\s+/).some(o=>Ds.has(o.replace(/[^a-z&]/g,""))))return{shouldSkip:!0,reason:"BDD keyword detected"}}return{shouldSkip:!1}}function xR(e){let t=e.text.toLowerCase().trim();for(let n of Ec)if(t.includes(n.toLowerCase()))return{shouldSkip:!0,reason:`directive: ${n}`};return{shouldSkip:!1}}function PR(e){return{shouldSkip:!1}}function AR(e){let t=e.text.toLowerCase(),n=["copyright","license","licensed under","spdx-license-identifier","all rights reserved","mit license","apache license","gnu general public","bsd license"];for(let r of n)if(t.includes(r))return{shouldSkip:!0,reason:"copyright/license"};return{shouldSkip:!1}}function IR(e){let t=e.text.toUpperCase(),n=["TODO","FIXME","HACK","XXX","NOTE","REVIEW"];for(let r of n)if(t.includes(r))return{shouldSkip:!0,reason:`todo marker: ${r}`};return{shouldSkip:!1}}var OR=[CR,RR,xR,AR,IR,PR];function Pc(e){return e.filter(t=>{for(let n of OR)if(n(t).shouldSkip)return!1;return!0})}var $R=process.env.COMMENT_CHECKER_DEBUG==="1",DR=Ns.join((0,ty.tmpdir)(),"comment-checker-debug.log");function jn(...e){if($R){let t=`[${new Date().toISOString()}] [comment-checker] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
1818
+ `;ey.appendFileSync(DR,t)}}function NR(e){let t=Ns.extname(e).toLowerCase();return xc[t]}function Ac(e,t){let n=NR(t);if(!n)return jn("unsupported language for:",t),[];let r=Rc[n];if(!r)return jn("no pattern for language:",n),[];let o=[],s=e.split(`
1819
1819
  `);r.lastIndex=0;let i;for(;(i=r.exec(e))!==null;){let a=i.index,c=i[0],u=e.substring(0,a).split(`
1820
- `).length,d="line",p=!1;c.startsWith("/*")||c.startsWith("<!--")?d="block":(c.startsWith("'''")||c.startsWith('"""')||c.startsWith("=begin"))&&(d="docstring",p=!0),o.push({text:c.trim(),lineNumber:u,filePath:t,commentType:d,isDocstring:p})}return o}function vR(e,t){return Cc(e,t)}function Yh(e,t,n){let r=Cc(e,t);if(n){let o=Cc(n,t),s=new Set(o.map(i=>i.text));return r.filter(i=>!s.has(i.text))}return r}function TR(e){if(e.length===0)return"";let t=new Map;for(let r of e){let o=t.get(r.filePath)||[];o.push(r),t.set(r.filePath,o)}let n=vc;for(let[r,o]of t){n+=`
1820
+ `).length,d="line",p=!1;c.startsWith("/*")||c.startsWith("<!--")?d="block":(c.startsWith("'''")||c.startsWith('"""')||c.startsWith("=begin"))&&(d="docstring",p=!0),o.push({text:c.trim(),lineNumber:u,filePath:t,commentType:d,isDocstring:p})}return o}function FR(e,t){return Ac(e,t)}function Xh(e,t,n){let r=Ac(e,t);if(n){let o=Ac(n,t),s=new Set(o.map(i=>i.text));return r.filter(i=>!s.has(i.text))}return r}function jR(e){if(e.length===0)return"";let t=new Map;for(let r of e){let o=t.get(r.filePath)||[];o.push(r),t.set(r.filePath,o)}let n=Cc;for(let[r,o]of t){n+=`
1821
1821
  File: ${r}
1822
1822
  `;for(let s of o){let i=s.isDocstring?"docstring":s.commentType;n+=` Line ${s.lineNumber} (${i}): ${s.text.substring(0,100)}${s.text.length>100?"...":""}
1823
- `}}return n}function ER(e,t,n,r,o){let s=[];if(t)s=vR(t,e);else if(r)s=Yh(r,e,n);else if(o&&o.length>0)for(let a of o){let c=Yh(a.new_string,e,a.old_string);s.push(...c)}let i=bc(s);return jn(`found ${s.length} comments, ${i.length} flagged after filtering`),i.length===0?{hasComments:!1,count:0,comments:[]}:{hasComments:!0,count:i.length,message:TR(i),comments:i}}var po=new Map,bR=6e4;function CR(){let e=Date.now();for(let[t,n]of po)e-n.timestamp>bR&&po.delete(t)}var Kh=!1;function Qh(e){return jn("createCommentCheckerHook called",{config:e}),Kh||(Kh=!0,setInterval(CR,1e4)),{preToolUse:t=>{let n=t.tool_name.toLowerCase();if(n!=="write"&&n!=="edit"&&n!=="multiedit")return null;let r=t.tool_input.file_path??t.tool_input.filePath??t.tool_input.path,o=t.tool_input.content,s=t.tool_input.old_string??t.tool_input.oldString,i=t.tool_input.new_string??t.tool_input.newString,a=t.tool_input.edits;if(!r)return null;let c=`${t.session_id}-${Date.now()}-${Math.random().toString(36).slice(2)}`;return jn("registering pendingCall:",{callId:c,filePath:r,tool:n}),po.set(c,{filePath:r,content:o,oldString:s,newString:i,edits:a,tool:n,sessionId:t.session_id,timestamp:Date.now()}),null},postToolUse:t=>{let n=t.tool_name.toLowerCase();if(n!=="write"&&n!=="edit"&&n!=="multiedit")return null;let r,o;for(let[i,a]of po)if(a.sessionId===t.session_id&&a.tool===n){r=a,o=i;break}if(!r){let i=t.tool_input.file_path??t.tool_input.filePath??t.tool_input.path;if(!i)return null;r={filePath:i,content:t.tool_input.content,oldString:t.tool_input.old_string??t.tool_input.oldString,newString:t.tool_input.new_string??t.tool_input.newString,edits:t.tool_input.edits,tool:n,sessionId:t.session_id,timestamp:Date.now()}}if(o&&po.delete(o),t.tool_response){let i=t.tool_response.toLowerCase();if(i.includes("error:")||i.includes("failed to")||i.includes("could not")||i.startsWith("error"))return jn("skipping due to tool failure in response"),null}let s=ER(r.filePath,r.content,r.oldString,r.newString,r.edits);return s.hasComments&&s.message?(jn("detected comments, returning message"),e?.customPrompt||s.message):null}}}var oy=T(require("fs"),1),sy=T(require("path"),1),iy=require("os");var Zh=[/(\d+)\s*tokens?\s*>\s*(\d+)\s*maximum/i,/prompt.*?(\d+).*?tokens.*?exceeds.*?(\d+)/i,/(\d+).*?tokens.*?limit.*?(\d+)/i,/context.*?length.*?(\d+).*?maximum.*?(\d+)/i,/max.*?context.*?(\d+).*?but.*?(\d+)/i],ey=["prompt is too long","is too long","context_length_exceeded","max_tokens","token limit","context length","too many tokens","non-empty content"],RR=[/thinking.*first block/i,/first block.*thinking/i,/must.*start.*thinking/i,/thinking.*redacted_thinking/i,/expected.*thinking.*found/i,/thinking.*disabled.*cannot.*contain/i],xR=/messages\.(\d+)/;function PR(e){return RR.some(t=>t.test(e))}function Rc(e){for(let t of Zh){let n=e.match(t);if(n){let r=parseInt(n[1],10),o=parseInt(n[2],10);return r>o?{current:r,max:o}:{current:o,max:r}}}return null}function Xh(e){let t=e.match(xR);if(t)return parseInt(t[1],10)}function hr(e){if(PR(e))return!1;let t=e.toLowerCase();return ey.some(n=>t.includes(n.toLowerCase()))}function Ds(e){if(typeof e=="string"){if(e.toLowerCase().includes("non-empty content"))return{currentTokens:0,maxTokens:0,errorType:"non-empty content",messageIndex:Xh(e)};if(hr(e)){let l=Rc(e);return{currentTokens:l?.current??0,maxTokens:l?.max??0,errorType:"token_limit_exceeded_string"}}return null}if(!e||typeof e!="object")return null;let t=e,n=[],r=t.data,o=r?.responseBody,s=t.message,i=t.error,a=i?.error;if(typeof o=="string"&&n.push(o),typeof s=="string"&&n.push(s),typeof i?.message=="string"&&n.push(i.message),typeof t.body=="string"&&n.push(t.body),typeof t.details=="string"&&n.push(t.details),typeof t.reason=="string"&&n.push(t.reason),typeof t.description=="string"&&n.push(t.description),typeof a?.message=="string"&&n.push(a.message),typeof r?.message=="string"&&n.push(r.message),typeof r?.error=="string"&&n.push(r.error),n.length===0)try{let l=JSON.stringify(t);hr(l)&&n.push(l)}catch{}let c=n.join(" ");if(!hr(c))return null;if(typeof o=="string")try{let l=[/data:\s*(\{[\s\S]*\})\s*$/m,/(\{"type"\s*:\s*"error"[\s\S]*\})/,/(\{[\s\S]*"error"[\s\S]*\})/];for(let d of l){let p=o.match(d);if(p)try{let f=JSON.parse(p[1]),m=f.error?.message||"",g=Rc(m);if(g)return{currentTokens:g.current,maxTokens:g.max,requestId:f.request_id,errorType:f.error?.type||"token_limit_exceeded"}}catch{}}let u=JSON.parse(o);if(typeof u.message=="string"&&hr(u.message))return{currentTokens:0,maxTokens:0,errorType:"bedrock_input_too_long"}}catch{}for(let l of n){let u=Rc(l);if(u)return{currentTokens:u.current,maxTokens:u.max,errorType:"token_limit_exceeded"}}return c.toLowerCase().includes("non-empty content")?{currentTokens:0,maxTokens:0,errorType:"non-empty content",messageIndex:Xh(c)}:hr(c)?{currentTokens:0,maxTokens:0,errorType:"token_limit_exceeded_unknown"}:null}function xc(e){return hr(e)}var Pc=`CONTEXT WINDOW LIMIT REACHED - IMMEDIATE ACTION REQUIRED
1823
+ `}}return n}function MR(e,t,n,r,o){let s=[];if(t)s=FR(t,e);else if(r)s=Xh(r,e,n);else if(o&&o.length>0)for(let a of o){let c=Xh(a.new_string,e,a.old_string);s.push(...c)}let i=Pc(s);return jn(`found ${s.length} comments, ${i.length} flagged after filtering`),i.length===0?{hasComments:!1,count:0,comments:[]}:{hasComments:!0,count:i.length,message:jR(i),comments:i}}var po=new Map,LR=6e4;function UR(){let e=Date.now();for(let[t,n]of po)e-n.timestamp>LR&&po.delete(t)}var Zh=!1;function ny(e){return jn("createCommentCheckerHook called",{config:e}),Zh||(Zh=!0,setInterval(UR,1e4)),{preToolUse:t=>{let n=t.tool_name.toLowerCase();if(n!=="write"&&n!=="edit"&&n!=="multiedit")return null;let r=t.tool_input.file_path??t.tool_input.filePath??t.tool_input.path,o=t.tool_input.content,s=t.tool_input.old_string??t.tool_input.oldString,i=t.tool_input.new_string??t.tool_input.newString,a=t.tool_input.edits;if(!r)return null;let c=`${t.session_id}-${Date.now()}-${Math.random().toString(36).slice(2)}`;return jn("registering pendingCall:",{callId:c,filePath:r,tool:n}),po.set(c,{filePath:r,content:o,oldString:s,newString:i,edits:a,tool:n,sessionId:t.session_id,timestamp:Date.now()}),null},postToolUse:t=>{let n=t.tool_name.toLowerCase();if(n!=="write"&&n!=="edit"&&n!=="multiedit")return null;let r,o;for(let[i,a]of po)if(a.sessionId===t.session_id&&a.tool===n){r=a,o=i;break}if(!r){let i=t.tool_input.file_path??t.tool_input.filePath??t.tool_input.path;if(!i)return null;r={filePath:i,content:t.tool_input.content,oldString:t.tool_input.old_string??t.tool_input.oldString,newString:t.tool_input.new_string??t.tool_input.newString,edits:t.tool_input.edits,tool:n,sessionId:t.session_id,timestamp:Date.now()}}if(o&&po.delete(o),t.tool_response){let i=t.tool_response.toLowerCase();if(i.includes("error:")||i.includes("failed to")||i.includes("could not")||i.startsWith("error"))return jn("skipping due to tool failure in response"),null}let s=MR(r.filePath,r.content,r.oldString,r.newString,r.edits);return s.hasComments&&s.message?(jn("detected comments, returning message"),e?.customPrompt||s.message):null}}}var ly=b(require("fs"),1),uy=b(require("path"),1),dy=require("os");var oy=[/(\d+)\s*tokens?\s*>\s*(\d+)\s*maximum/i,/prompt.*?(\d+).*?tokens.*?exceeds.*?(\d+)/i,/(\d+).*?tokens.*?limit.*?(\d+)/i,/context.*?length.*?(\d+).*?maximum.*?(\d+)/i,/max.*?context.*?(\d+).*?but.*?(\d+)/i],sy=["prompt is too long","is too long","context_length_exceeded","max_tokens","token limit","context length","too many tokens","non-empty content"],WR=[/thinking.*first block/i,/first block.*thinking/i,/must.*start.*thinking/i,/thinking.*redacted_thinking/i,/expected.*thinking.*found/i,/thinking.*disabled.*cannot.*contain/i],BR=/messages\.(\d+)/;function GR(e){return WR.some(t=>t.test(e))}function Ic(e){for(let t of oy){let n=e.match(t);if(n){let r=parseInt(n[1],10),o=parseInt(n[2],10);return r>o?{current:r,max:o}:{current:o,max:r}}}return null}function ry(e){let t=e.match(BR);if(t)return parseInt(t[1],10)}function hr(e){if(GR(e))return!1;let t=e.toLowerCase();return sy.some(n=>t.includes(n.toLowerCase()))}function Fs(e){if(typeof e=="string"){if(e.toLowerCase().includes("non-empty content"))return{currentTokens:0,maxTokens:0,errorType:"non-empty content",messageIndex:ry(e)};if(hr(e)){let l=Ic(e);return{currentTokens:l?.current??0,maxTokens:l?.max??0,errorType:"token_limit_exceeded_string"}}return null}if(!e||typeof e!="object")return null;let t=e,n=[],r=t.data,o=r?.responseBody,s=t.message,i=t.error,a=i?.error;if(typeof o=="string"&&n.push(o),typeof s=="string"&&n.push(s),typeof i?.message=="string"&&n.push(i.message),typeof t.body=="string"&&n.push(t.body),typeof t.details=="string"&&n.push(t.details),typeof t.reason=="string"&&n.push(t.reason),typeof t.description=="string"&&n.push(t.description),typeof a?.message=="string"&&n.push(a.message),typeof r?.message=="string"&&n.push(r.message),typeof r?.error=="string"&&n.push(r.error),n.length===0)try{let l=JSON.stringify(t);hr(l)&&n.push(l)}catch{}let c=n.join(" ");if(!hr(c))return null;if(typeof o=="string")try{let l=[/data:\s*(\{[\s\S]*\})\s*$/m,/(\{"type"\s*:\s*"error"[\s\S]*\})/,/(\{[\s\S]*"error"[\s\S]*\})/];for(let d of l){let p=o.match(d);if(p)try{let f=JSON.parse(p[1]),m=f.error?.message||"",g=Ic(m);if(g)return{currentTokens:g.current,maxTokens:g.max,requestId:f.request_id,errorType:f.error?.type||"token_limit_exceeded"}}catch{}}let u=JSON.parse(o);if(typeof u.message=="string"&&hr(u.message))return{currentTokens:0,maxTokens:0,errorType:"bedrock_input_too_long"}}catch{}for(let l of n){let u=Ic(l);if(u)return{currentTokens:u.current,maxTokens:u.max,errorType:"token_limit_exceeded"}}return c.toLowerCase().includes("non-empty content")?{currentTokens:0,maxTokens:0,errorType:"non-empty content",messageIndex:ry(c)}:hr(c)?{currentTokens:0,maxTokens:0,errorType:"token_limit_exceeded_unknown"}:null}function Oc(e){return hr(e)}var $c=`CONTEXT WINDOW LIMIT REACHED - IMMEDIATE ACTION REQUIRED
1824
1824
 
1825
1825
  The conversation has exceeded the model's context window limit. To continue working effectively, you must take one of these actions:
1826
1826
 
@@ -1845,7 +1845,7 @@ Current Status:
1845
1845
  - Context limit exceeded
1846
1846
  - Further API calls will fail until context is reduced
1847
1847
  - Action required before continuing
1848
- `,Ic="Context window limit reached. Please use /compact to summarize the conversation or start a new session.",Ac=`API ERROR: Non-empty content validation failed.
1848
+ `,Dc="Context window limit reached. Please use /compact to summarize the conversation or start a new session.",Nc=`API ERROR: Non-empty content validation failed.
1849
1849
 
1850
1850
  This error typically occurs when:
1851
1851
  - A message has empty text content
@@ -1856,7 +1856,7 @@ Suggested actions:
1856
1856
  2. If the error persists, start a new session
1857
1857
 
1858
1858
  The system will attempt automatic recovery.
1859
- `;var Oc=`CONTEXT RECOVERY FAILED
1859
+ `;var Fc=`CONTEXT RECOVERY FAILED
1860
1860
 
1861
1861
  All automatic recovery attempts have been exhausted.
1862
1862
  Please start a new session to continue.
@@ -1867,13 +1867,13 @@ Before starting a new session:
1867
1867
  3. Document the current state of the task
1868
1868
 
1869
1869
  You can copy this conversation summary to continue in a new session.
1870
- `;var $c={maxAttempts:2,initialDelayMs:2e3,backoffFactor:2,maxDelayMs:3e4};var IR=process.env.CONTEXT_LIMIT_RECOVERY_DEBUG==="1",AR=sy.join((0,iy.tmpdir)(),"context-limit-recovery-debug.log");function Ns(...e){if(IR){let t=`[${new Date().toISOString()}] [context-limit-recovery] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
1871
- `;oy.appendFileSync(AR,t)}}var Fs=new Map,ay=3e5;function ty(e){let t=Fs.get(e),n=Date.now();return t&&n-t.lastErrorTime>ay&&(t=void 0),t||(t={retryState:{attempt:0,lastAttemptTime:0},truncateState:{truncateAttempt:0},lastErrorTime:n,errorCount:0},Fs.set(e,t)),t}function OR(){let e=Date.now();for(let[t,n]of Fs)e-n.lastErrorTime>ay&&Fs.delete(t)}var ny=!1;function cy(e){return Ns("createContextLimitRecoveryHook called",{config:e}),ny||(ny=!0,setInterval(OR,6e4)),{postToolUse:t=>{if(!t.tool_response)return null;let n=Ds(t.tool_response);if(!n&&!xc(t.tool_response))return null;Ns("detected token limit error",{tool:t.tool_name,sessionId:t.session_id,parsed:n});let r=ty(t.session_id);r.lastErrorTime=Date.now(),r.errorCount++;let o=ry(n,r,e);return o.message?(Ns("injecting recovery message",{errorType:o.errorType,attempt:r.retryState.attempt}),o.message):null},onError:t=>{let n=Ds(t.error);if(!n)return{attempted:!1,success:!1};Ns("error notification contains token limit error",{sessionId:t.session_id,parsed:n});let r=ty(t.session_id);r.lastErrorTime=Date.now(),r.errorCount++;let o=ry(n,r,e);return{attempted:!0,success:!!o.message,message:o.message,errorType:o.errorType}}}}function ry(e,t,n){if(n?.customMessage)return{message:n.customMessage,errorType:e?.errorType};if(e?.errorType?.includes("non-empty content"))return{message:Ac,errorType:"non-empty content"};if(t.retryState.attempt++,t.retryState.lastAttemptTime=Date.now(),t.retryState.attempt>$c.maxAttempts)return{message:Oc,errorType:"recovery_exhausted"};if(n?.detailed!==!1){let r=Pc;return e?.currentTokens&&e?.maxTokens&&(r+=`
1870
+ `;var jc={maxAttempts:2,initialDelayMs:2e3,backoffFactor:2,maxDelayMs:3e4};var HR=process.env.CONTEXT_LIMIT_RECOVERY_DEBUG==="1",VR=uy.join((0,dy.tmpdir)(),"context-limit-recovery-debug.log");function js(...e){if(HR){let t=`[${new Date().toISOString()}] [context-limit-recovery] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
1871
+ `;ly.appendFileSync(VR,t)}}var Ms=new Map,py=3e5;function iy(e){let t=Ms.get(e),n=Date.now();return t&&n-t.lastErrorTime>py&&(t=void 0),t||(t={retryState:{attempt:0,lastAttemptTime:0},truncateState:{truncateAttempt:0},lastErrorTime:n,errorCount:0},Ms.set(e,t)),t}function qR(){let e=Date.now();for(let[t,n]of Ms)e-n.lastErrorTime>py&&Ms.delete(t)}var ay=!1;function fy(e){return js("createContextLimitRecoveryHook called",{config:e}),ay||(ay=!0,setInterval(qR,6e4)),{postToolUse:t=>{if(!t.tool_response)return null;let n=Fs(t.tool_response);if(!n&&!Oc(t.tool_response))return null;js("detected token limit error",{tool:t.tool_name,sessionId:t.session_id,parsed:n});let r=iy(t.session_id);r.lastErrorTime=Date.now(),r.errorCount++;let o=cy(n,r,e);return o.message?(js("injecting recovery message",{errorType:o.errorType,attempt:r.retryState.attempt}),o.message):null},onError:t=>{let n=Fs(t.error);if(!n)return{attempted:!1,success:!1};js("error notification contains token limit error",{sessionId:t.session_id,parsed:n});let r=iy(t.session_id);r.lastErrorTime=Date.now(),r.errorCount++;let o=cy(n,r,e);return{attempted:!0,success:!!o.message,message:o.message,errorType:o.errorType}}}}function cy(e,t,n){if(n?.customMessage)return{message:n.customMessage,errorType:e?.errorType};if(e?.errorType?.includes("non-empty content"))return{message:Nc,errorType:"non-empty content"};if(t.retryState.attempt++,t.retryState.lastAttemptTime=Date.now(),t.retryState.attempt>jc.maxAttempts)return{message:Fc,errorType:"recovery_exhausted"};if(n?.detailed!==!1){let r=$c;return e?.currentTokens&&e?.maxTokens&&(r+=`
1872
1872
  Token Details:
1873
1873
  - Current: ${e.currentTokens.toLocaleString()} tokens
1874
1874
  - Maximum: ${e.maxTokens.toLocaleString()} tokens
1875
1875
  - Over limit by: ${(e.currentTokens-e.maxTokens).toLocaleString()} tokens
1876
- `),{message:r,errorType:e?.errorType||"token_limit_exceeded"}}return{message:Ic,errorType:e?.errorType||"token_limit_exceeded"}}var ly=/File content \((\d+) tokens\) exceeds maximum allowed tokens \((\d+)\)/i,$R=/exceeds maximum allowed tokens/i;function DR(e){let t=e.match(ly);return t?{current:parseInt(t[1],10),max:parseInt(t[2],10)}:null}function NR(e,t){return e.toLowerCase()==="read"&&(ly.test(t)||$R.test(t))}function FR(e,t){return`[SYSTEM RECOVERY - READ TOOL FILE SIZE LIMIT]
1876
+ `),{message:r,errorType:e?.errorType||"token_limit_exceeded"}}return{message:Dc,errorType:e?.errorType||"token_limit_exceeded"}}var my=/File content \((\d+) tokens\) exceeds maximum allowed tokens \((\d+)\)/i,YR=/exceeds maximum allowed tokens/i;function KR(e){let t=e.match(my);return t?{current:parseInt(t[1],10),max:parseInt(t[2],10)}:null}function JR(e,t){return e.toLowerCase()==="read"&&(my.test(t)||YR.test(t))}function zR(e,t){return`[SYSTEM RECOVERY - READ TOOL FILE SIZE LIMIT]
1877
1877
 
1878
1878
  ${t?`The file contains ${t.current} tokens, exceeding the ${t.max} token limit.`:"The file is too large to read in one operation."}
1879
1879
 
@@ -1903,7 +1903,7 @@ ${t?`The file contains ${t.current} tokens, exceeding the ${t.max} token limit.`
1903
1903
  - Need overview/summary? \u2192 Use multimodal-looker agent
1904
1904
  - Need specific section? \u2192 Grep to find it, then Read that portion
1905
1905
 
1906
- Proceed with one of these strategies.`.trim()}function uy(){return{postToolUse:e=>{if(!e.tool_response||!NR(e.tool_name,e.tool_response))return null;let t=e.tool_input?.file_path||"<unknown file>",n=DR(e.tool_response);return FR(t,n||void 0)}}}var hy=T(require("fs"),1),yy=T(require("path"),1),wy=require("os");var Dc=process.env.ANTHROPIC_1M_CONTEXT==="true"||process.env.VERTEX_ANTHROPIC_1M_CONTEXT==="true"?1e6:2e5,js=4,Nc=`CONTEXT WINDOW WARNING - APPROACHING LIMIT
1906
+ Proceed with one of these strategies.`.trim()}function gy(){return{postToolUse:e=>{if(!e.tool_response||!JR(e.tool_name,e.tool_response))return null;let t=e.tool_input?.file_path||"<unknown file>",n=KR(e.tool_response);return zR(t,n||void 0)}}}var Sy=b(require("fs"),1),vy=b(require("path"),1),by=require("os");var Mc=process.env.ANTHROPIC_1M_CONTEXT==="true"||process.env.VERTEX_ANTHROPIC_1M_CONTEXT==="true"?1e6:2e5,Ls=4,Lc=`CONTEXT WINDOW WARNING - APPROACHING LIMIT
1907
1907
 
1908
1908
  Your context usage is getting high. Consider these actions to prevent hitting the limit:
1909
1909
 
@@ -1923,7 +1923,7 @@ Your context usage is getting high. Consider these actions to prevent hitting th
1923
1923
 
1924
1924
  Current Status: Context usage is high but recoverable.
1925
1925
  Action recommended: Use /compact when convenient.
1926
- `,Fc=`CRITICAL: CONTEXT WINDOW ALMOST FULL
1926
+ `,Uc=`CRITICAL: CONTEXT WINDOW ALMOST FULL
1927
1927
 
1928
1928
  Your context usage is critically high. Immediate action required:
1929
1929
 
@@ -1942,8 +1942,8 @@ Your context usage is critically high. Immediate action required:
1942
1942
 
1943
1943
  WARNING: Further messages may fail if context is not reduced.
1944
1944
  Action required: Run /compact now.
1945
- `;var jR=process.env.PREEMPTIVE_COMPACTION_DEBUG==="1",MR=yy.join((0,wy.tmpdir)(),"preemptive-compaction-debug.log");function yr(...e){if(jR){let t=`[${new Date().toISOString()}] [preemptive-compaction] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
1946
- `;hy.appendFileSync(MR,t)}}var Ms=new Map;function LR(){let e=Date.now(),t=1800*1e3;for(let[n,r]of Ms)e-r.lastWarningTime>t&&Ms.delete(n)}var dy=!1;function ky(e){return Math.ceil(e.length/js)}function UR(e,t){let n=t?.warningThreshold??.85,r=t?.criticalThreshold??.95,o=Dc,s=ky(e),i=s/o,a=i>=n,c=i>=r,l="none";return c?l="compact":a&&(l="warn"),{totalTokens:s,usageRatio:i,isWarning:a,isCritical:c,action:l}}function Ls(e){let t=Ms.get(e);return t||(t={lastWarningTime:0,warningCount:0,estimatedTokens:0},Ms.set(e,t)),t}function WR(e,t){let n=Ls(e),r=t?.cooldownMs??6e4,o=t?.maxWarnings??3,s=Date.now();return s-n.lastWarningTime<r?(yr("skipping warning - cooldown active",{sessionId:e,elapsed:s-n.lastWarningTime,cooldown:r}),!1):n.warningCount>=o?(yr("skipping warning - max reached",{sessionId:e,warningCount:n.warningCount,maxWarnings:o}),!1):!0}function GR(e){let t=Ls(e);t.lastWarningTime=Date.now(),t.warningCount++}function _y(e){return yr("createPreemptiveCompactionHook called",{config:e}),e?.enabled===!1?{postToolUse:()=>null,stop:()=>null}:(dy||(dy=!0,setInterval(LR,300*1e3)),{postToolUse:t=>{if(!t.tool_response)return null;let n=t.tool_name.toLowerCase();if(!["read","grep","glob","bash","webfetch"].includes(n))return null;let o=ky(t.tool_response),s=Ls(t.session_id);s.estimatedTokens+=o,yr("tracking tool output",{tool:n,responseTokens:o,cumulativeTokens:s.estimatedTokens});let i=UR("x".repeat(s.estimatedTokens*js),e);return!i.isWarning||!WR(t.session_id,e)?null:(GR(t.session_id),yr("injecting context warning",{sessionId:t.session_id,usageRatio:i.usageRatio,isCritical:i.isCritical}),e?.customMessage?e.customMessage:i.isCritical?Fc:Nc)},stop:t=>{let n=Ls(t.session_id);return n.warningCount>0&&(yr("resetting warning count on stop",{sessionId:t.session_id,previousCount:n.warningCount}),n.warningCount=0),null}})}var ot=require("fs"),vy=require("path");var jc=require("path"),Sy=require("os"),BR=(0,jc.join)((0,Sy.homedir)(),".olympus"),Us=(0,jc.join)(BR,"agent-usage-reminder"),Mc=new Set(["grep","safe_grep","glob","safe_glob","webfetch","context7_resolve-library-id","context7_query-docs","websearch_web_search_exa","context7_get-library-docs","grep_app_searchgithub"]),Lc=new Set(["task","call_omo_agent","olympus_task"]),Uc=`
1945
+ `;var QR=process.env.PREEMPTIVE_COMPACTION_DEBUG==="1",XR=vy.join((0,by.tmpdir)(),"preemptive-compaction-debug.log");function yr(...e){if(QR){let t=`[${new Date().toISOString()}] [preemptive-compaction] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
1946
+ `;Sy.appendFileSync(XR,t)}}var Us=new Map;function ZR(){let e=Date.now(),t=1800*1e3;for(let[n,r]of Us)e-r.lastWarningTime>t&&Us.delete(n)}var hy=!1;function Ty(e){return Math.ceil(e.length/Ls)}function ex(e,t){let n=t?.warningThreshold??.85,r=t?.criticalThreshold??.95,o=Mc,s=Ty(e),i=s/o,a=i>=n,c=i>=r,l="none";return c?l="compact":a&&(l="warn"),{totalTokens:s,usageRatio:i,isWarning:a,isCritical:c,action:l}}function Ws(e){let t=Us.get(e);return t||(t={lastWarningTime:0,warningCount:0,estimatedTokens:0},Us.set(e,t)),t}function tx(e,t){let n=Ws(e),r=t?.cooldownMs??6e4,o=t?.maxWarnings??3,s=Date.now();return s-n.lastWarningTime<r?(yr("skipping warning - cooldown active",{sessionId:e,elapsed:s-n.lastWarningTime,cooldown:r}),!1):n.warningCount>=o?(yr("skipping warning - max reached",{sessionId:e,warningCount:n.warningCount,maxWarnings:o}),!1):!0}function nx(e){let t=Ws(e);t.lastWarningTime=Date.now(),t.warningCount++}function Ey(e){return yr("createPreemptiveCompactionHook called",{config:e}),e?.enabled===!1?{postToolUse:()=>null,stop:()=>null}:(hy||(hy=!0,setInterval(ZR,300*1e3)),{postToolUse:t=>{if(!t.tool_response)return null;let n=t.tool_name.toLowerCase();if(!["read","grep","glob","bash","webfetch"].includes(n))return null;let o=Ty(t.tool_response),s=Ws(t.session_id);s.estimatedTokens+=o,yr("tracking tool output",{tool:n,responseTokens:o,cumulativeTokens:s.estimatedTokens});let i=ex("x".repeat(s.estimatedTokens*Ls),e);return!i.isWarning||!tx(t.session_id,e)?null:(nx(t.session_id),yr("injecting context warning",{sessionId:t.session_id,usageRatio:i.usageRatio,isCritical:i.isCritical}),e?.customMessage?e.customMessage:i.isCritical?Uc:Lc)},stop:t=>{let n=Ws(t.session_id);return n.warningCount>0&&(yr("resetting warning count on stop",{sessionId:t.session_id,previousCount:n.warningCount}),n.warningCount=0),null}})}var ot=require("fs"),Ry=require("path");var Wc=require("path"),Cy=require("os"),rx=(0,Wc.join)((0,Cy.homedir)(),".olympus"),Bs=(0,Wc.join)(rx,"agent-usage-reminder"),Bc=new Set(["grep","safe_grep","glob","safe_glob","webfetch","context7_resolve-library-id","context7_query-docs","websearch_web_search_exa","context7_get-library-docs","grep_app_searchgithub"]),Gc=new Set(["task","call_omo_agent","olympus_task"]),Hc=`
1947
1947
  [Agent Usage Reminder]
1948
1948
 
1949
1949
  You called a search/fetch tool directly without leveraging specialized agents.
@@ -1967,7 +1967,7 @@ WHY:
1967
1967
  - Reduces context window usage in main session
1968
1968
 
1969
1969
  ALWAYS prefer: Multiple parallel Task calls > Direct tool calls
1970
- `;function Wc(e){return(0,vy.join)(Us,`${e}.json`)}function Gc(e){let t=Wc(e);if(!(0,ot.existsSync)(t))return null;try{let n=(0,ot.readFileSync)(t,"utf-8");return JSON.parse(n)}catch{return null}}function Ws(e){(0,ot.existsSync)(Us)||(0,ot.mkdirSync)(Us,{recursive:!0});let t=Wc(e.sessionID);(0,ot.writeFileSync)(t,JSON.stringify(e,null,2))}function Bc(e){let t=Wc(e);(0,ot.existsSync)(t)&&(0,ot.unlinkSync)(t)}function HR(e){let t=e||process.cwd();return pr(t)?.active?{active:!0,mode:"ascent"}:Nn(t)?.active?{active:!0,mode:"olympus"}:Qt(t)?.active?{active:!0,mode:"ultrawork"}:{active:!1,mode:"none"}}function VR(e){if(!e||typeof e!="object")return null;let t=e;return t.file_path||t.filePath||t.path}function qR(e,t){if(e<3)return null;let n=e>=5?"CRITICAL":"WARNING";return`<conductor-violation severity="${n}">
1970
+ `;function Vc(e){return(0,Ry.join)(Bs,`${e}.json`)}function qc(e){let t=Vc(e);if(!(0,ot.existsSync)(t))return null;try{let n=(0,ot.readFileSync)(t,"utf-8");return JSON.parse(n)}catch{return null}}function Gs(e){(0,ot.existsSync)(Bs)||(0,ot.mkdirSync)(Bs,{recursive:!0});let t=Vc(e.sessionID);(0,ot.writeFileSync)(t,JSON.stringify(e,null,2))}function Yc(e){let t=Vc(e);(0,ot.existsSync)(t)&&(0,ot.unlinkSync)(t)}function ox(e){let t=e||process.cwd();return pr(t)?.active?{active:!0,mode:"ascent"}:Nn(t)?.active?{active:!0,mode:"olympus"}:Qt(t)?.active?{active:!0,mode:"ultrawork"}:{active:!1,mode:"none"}}function sx(e){if(!e||typeof e!="object")return null;let t=e;return t.file_path||t.filePath||t.path}function ix(e,t){if(e<3)return null;let n=e>=5?"CRITICAL":"WARNING";return`<conductor-violation severity="${n}">
1971
1971
 
1972
1972
  [${n}: CONDUCTOR MODE VIOLATION - ${t.toUpperCase()} ACTIVE]
1973
1973
 
@@ -1993,36 +1993,36 @@ ${e>=5?"**CRITICAL**: Too many direct operations. Your next action MUST be deleg
1993
1993
 
1994
1994
  ---
1995
1995
 
1996
- `}function Ty(){let e=new Map,t=new Map;function n(c){if(!e.has(c)){let u=Gc(c)??{sessionID:c,agentUsed:!1,reminderCount:0,updatedAt:Date.now()};e.set(c,u)}return e.get(c)}function r(c){let l=n(c);l.agentUsed=!0,l.updatedAt=Date.now(),Ws(l)}function o(c){e.delete(c),Bc(c),t.delete(c)}function s(c,l,u){let d=t.get(c)||{consecutiveCount:0,lastToolName:"",lastFilePath:"",sessionId:c};return l.toLowerCase()==="task"?(d.consecutiveCount=0,t.set(c,d),0):(["edit","write","multiedit"].includes(l.toLowerCase())&&(d.consecutiveCount++,d.lastToolName=l,d.lastFilePath=u,t.set(c,d)),d.consecutiveCount)}return{"tool.execute.after":async(c,l)=>{let{tool:u,sessionID:d}=c,p=u.toLowerCase();if(Lc.has(p)){r(d),s(d,p,"");return}let f=c.properties||{},m=VR(f),g=s(d,p,m||""),y=HR();if(y.active){let k=qR(g,y.mode);if(k){l.output=k+l.output;return}}if(!Mc.has(p))return;let w=n(d);w.agentUsed||(l.output+=Uc,w.reminderCount++,w.updatedAt=Date.now(),Ws(w))},event:async({event:c})=>{let l=c.properties;if(c.type==="session.deleted"){let u=l?.info;u?.id&&o(u.id)}if(c.type==="session.compacted"){let u=l?.sessionID??l?.info?.id;u&&o(u)}}}}function Ey(){let e=process.cwd(),t=qh();P({name:"editErrorRecovery",event:"PostToolUse",matcher:/^edit$/i,priority:10,handler:async c=>{if(!c.toolName||!c.toolOutput)return{continue:!0};let l=t.afterToolExecute({tool:c.toolName,sessionId:c.sessionId||"",callId:""},{title:"",output:String(c.toolOutput),metadata:void 0});return l.output!==String(c.toolOutput)?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:l.output.substring(String(c.toolOutput).length)}}:{continue:!0}}});let n=Qh();P({name:"commentChecker",event:"PostToolUse",matcher:/^(write|edit|multiedit)$/i,priority:20,handler:async c=>{if(!c.toolName)return{continue:!0};let l=n.postToolUse({tool_name:c.toolName,session_id:c.sessionId||"",tool_input:c.toolInput||{},tool_response:c.toolOutput?String(c.toolOutput):void 0});return l?{continue:!0,message:l}:{continue:!0}}});let r=cy();P({name:"contextWindowLimitRecovery",event:"PostToolUse",priority:30,handler:async c=>{if(!c.toolName)return{continue:!0};let l=r.postToolUse({tool_name:c.toolName,session_id:c.sessionId||"",tool_input:c.toolInput||{},tool_response:c.toolOutput?String(c.toolOutput):void 0});return l?{continue:!0,message:l}:{continue:!0}}});let o=uy();P({name:"readToolLimitRecovery",event:"PostToolUse",matcher:/^read$/i,priority:35,handler:async c=>{if(!c.toolName||c.toolName.toLowerCase()!=="read")return{continue:!0};let l=o.postToolUse({tool_name:c.toolName,session_id:c.sessionId||"",tool_input:c.toolInput||{},tool_response:c.toolOutput?String(c.toolOutput):void 0});return l?{continue:!0,message:l}:{continue:!0}}});let s=_y();P({name:"preemptiveCompaction",event:"PostToolUse",matcher:/^(read|grep|glob|bash|webfetch)$/i,priority:40,handler:async c=>{if(!c.toolName)return{continue:!0};let l=s.postToolUse({tool_name:c.toolName,session_id:c.sessionId||"",tool_input:c.toolInput||{},tool_response:c.toolOutput?String(c.toolOutput):void 0});return l?{continue:!0,message:l}:{continue:!0}}});let i=Ty();P({name:"agentUsageReminder",event:"PostToolUse",matcher:/^(read|grep|glob|edit|write)$/i,priority:50,handler:async c=>{if(!c.toolName)return{continue:!0};let l={title:"",output:c.toolOutput?String(c.toolOutput):"",metadata:void 0};await i["tool.execute.after"]({tool:c.toolName,sessionID:c.sessionId||"",callID:""},l);let u=c.toolOutput?String(c.toolOutput):"";return l.output!==u?{continue:!0,message:l.output.substring(u.length)}:{continue:!0}}});let a=As(e);P({name:"olympusOrchestratorPost",event:"PostToolUse",matcher:/^(write|edit|bash|task)$/i,priority:60,handler:async c=>{if(!c.toolName)return{continue:!0};let l=a.postTool(c.toolName,c.toolInput||{},c.toolOutput?String(c.toolOutput):"");return l.continue?l.modifiedOutput?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:l.modifiedOutput}}:l.message?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:l.message}}:{continue:!0}:{continue:!1,stopReason:l.message}}})}var Fy=require("node:fs");var J=require("node:fs"),We=require("node:path");var wr=require("node:path"),Gs=require("node:os");function YR(){return process.env.XDG_DATA_HOME??(0,wr.join)((0,Gs.homedir)(),".local","share")}function KR(){return(0,wr.join)(YR(),"claude-code","storage")}var by=KR(),fo=(0,wr.join)(by,"message"),kr=(0,wr.join)(by,"part"),pn=new Set(["thinking","redacted_thinking","reasoning"]),Cy=new Set(["step-start","step-finish"]);var st="[user interrupted]",Bs={tool_result_missing:{title:"Tool Crash Recovery",message:"Injecting cancelled tool results..."},thinking_block_order:{title:"Thinking Block Recovery",message:"Fixing message structure..."},thinking_disabled_violation:{title:"Thinking Strip Recovery",message:"Stripping thinking blocks..."},empty_content:{title:"Empty Content Recovery",message:"Adding placeholder content..."}};var Ry=process.env.SESSION_RECOVERY_DEBUG==="1",xy=(0,wr.join)((0,Gs.tmpdir)(),"session-recovery-debug.log");function JR(){let e=Date.now().toString(16),t=Math.random().toString(36).substring(2,10);return`prt_${e}${t}`}function zR(e){if(!(0,J.existsSync)(fo))return"";let t=(0,We.join)(fo,e);if((0,J.existsSync)(t))return t;for(let n of(0,J.readdirSync)(fo)){let r=(0,We.join)(fo,n,e);if((0,J.existsSync)(r))return r}return""}function Kt(e){let t=zR(e);if(!t||!(0,J.existsSync)(t))return[];let n=[];for(let r of(0,J.readdirSync)(t))if(r.endsWith(".json"))try{let o=(0,J.readFileSync)((0,We.join)(t,r),"utf-8");n.push(JSON.parse(o))}catch{continue}return n.sort((r,o)=>{let s=r.time?.created??0,i=o.time?.created??0;return s!==i?s-i:r.id.localeCompare(o.id)})}function At(e){let t=(0,We.join)(kr,e);if(!(0,J.existsSync)(t))return[];let n=[];for(let r of(0,J.readdirSync)(t))if(r.endsWith(".json"))try{let o=(0,J.readFileSync)((0,We.join)(t,r),"utf-8");n.push(JSON.parse(o))}catch{continue}return n}function Py(e){return pn.has(e.type)||Cy.has(e.type)?!1:e.type==="text"?!!e.text?.trim():e.type==="tool"||e.type==="tool_use"||e.type==="tool_result"}function Iy(e){return At(e).some(Py)}function mo(e,t,n){let r=(0,We.join)(kr,t);(0,J.existsSync)(r)||(0,J.mkdirSync)(r,{recursive:!0});let o=JR(),s={id:o,sessionID:e,messageID:t,type:"text",text:n,synthetic:!0};try{return(0,J.writeFileSync)((0,We.join)(r,`${o}.json`),JSON.stringify(s,null,2)),!0}catch{return!1}}function Hc(e){let t=Kt(e),n=[];for(let r of t)Iy(r.id)||n.push(r.id);return n}function Ay(e,t){let n=Kt(e),r=[t,t-1,t+1,t-2,t+2,t-3,t-4,t-5];for(let o of r){if(o<0||o>=n.length)continue;let s=n[o];if(!Iy(s.id))return s.id}return null}function Vc(e){let t=Kt(e),n=[];for(let r of t){if(r.role!=="assistant")continue;At(r.id).some(i=>pn.has(i.type))&&n.push(r.id)}return n}function Oy(e){let t=Kt(e),n=[];for(let r of t){if(r.role!=="assistant")continue;let o=At(r.id);if(o.length===0)continue;let s=o.some(a=>pn.has(a.type)),i=o.some(Py);s&&!i&&n.push(r.id)}return n}function qc(e){let t=Kt(e),n=[];for(let r of t){if(r.role!=="assistant")continue;let o=At(r.id);if(o.length===0)continue;let i=[...o].sort((c,l)=>c.id.localeCompare(l.id))[0];pn.has(i.type)||n.push(r.id)}return n}function QR(e,t){let n=Kt(e),r=n.findIndex(o=>o.id===t);if(r===-1)return"";for(let o=r-1;o>=0;o--){let s=n[o];if(s.role!=="assistant")continue;let i=At(s.id);for(let a of i)if(pn.has(a.type)){let c=a.thinking,l=a.text,u=c||l;if(u&&u.trim().length>0)return u}}return""}function Yc(e,t){let n=(0,We.join)(kr,t);(0,J.existsSync)(n)||(0,J.mkdirSync)(n,{recursive:!0});let r=QR(e,t),o="prt_0000000000_thinking",s={id:o,sessionID:e,messageID:t,type:"thinking",thinking:r||"[Continuing from previous reasoning]",synthetic:!0};try{return(0,J.writeFileSync)((0,We.join)(n,`${o}.json`),JSON.stringify(s,null,2)),!0}catch{return!1}}function $y(e){let t=(0,We.join)(kr,e);if(!(0,J.existsSync)(t))return!1;let n=!1;for(let r of(0,J.readdirSync)(t))if(r.endsWith(".json"))try{let o=(0,We.join)(t,r),s=(0,J.readFileSync)(o,"utf-8"),i=JSON.parse(s);pn.has(i.type)&&((0,J.unlinkSync)(o),n=!0)}catch{continue}return n}function go(e,t=st){let n=(0,We.join)(kr,e);if(!(0,J.existsSync)(n))return!1;let r=!1;for(let o of(0,J.readdirSync)(n))if(o.endsWith(".json"))try{let s=(0,We.join)(n,o),i=(0,J.readFileSync)(s,"utf-8"),a=JSON.parse(i);if(a.type==="text"){let c=a;c.text?.trim()||(c.text=t,c.synthetic=!0,(0,J.writeFileSync)(s,JSON.stringify(c,null,2)),r=!0)}}catch{continue}return r}function Dy(e){let t=Kt(e),n=[];for(let r of t)At(r.id).some(i=>i.type!=="text"?!1:!i.text?.trim())&&n.push(r.id);return n}function Ny(e,t){let n=Kt(e);if(t<0||t>=n.length)return null;let r=n[t];if(r.role!=="assistant")return null;let o=At(r.id);if(o.length===0)return null;let i=[...o].sort((c,l)=>c.id.localeCompare(l.id))[0];return pn.has(i.type)?null:r.id}function Se(...e){if(Ry){let t=`[${new Date().toISOString()}] [session-recovery] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
1997
- `;(0,Fy.appendFileSync)(xy,t)}}function jy(e){if(!e)return"";if(typeof e=="string")return e.toLowerCase();let t=e,n=[t.data,t.error,t,t.data?.error];for(let r of n)if(r&&typeof r=="object"){let o=r.message;if(typeof o=="string"&&o.length>0)return o.toLowerCase()}try{return JSON.stringify(e).toLowerCase()}catch{return""}}function My(e){let n=jy(e).match(/messages\.(\d+)/);return n?parseInt(n[1],10):null}function Ly(e){let t=jy(e);return t.includes("tool_use")&&t.includes("tool_result")?"tool_result_missing":t.includes("thinking")&&(t.includes("first block")||t.includes("must start with")||t.includes("preceeding")||t.includes("final block")||t.includes("cannot be thinking")||t.includes("expected")&&t.includes("found"))?"thinking_block_order":t.includes("thinking is disabled")&&t.includes("cannot contain")?"thinking_disabled_violation":t.includes("empty")&&(t.includes("content")||t.includes("message"))?"empty_content":null}function XR(e){return Ly(e)!==null}function ZR(e){return e.filter(t=>t.type==="tool_use"&&!!t.id).map(t=>t.id)}async function ex(e,t){Se("recoverToolResultMissing",{sessionID:e,msgId:t.info?.id});let n=t.parts||[];n.length===0&&t.info?.id&&(n=At(t.info.id).map(s=>({type:s.type==="tool"?"tool_use":s.type,id:"callID"in s?s.callID:s.id,name:"tool"in s?s.tool:void 0,input:"state"in s?s.state?.input:void 0})));let r=ZR(n);return r.length===0?(Se("No tool_use IDs found"),!1):(Se("Found tool_use IDs to inject results for",r),!0)}async function tx(e,t,n){Se("recoverThinkingBlockOrder",{sessionID:e});let r=My(n);if(r!==null){let i=Ny(e,r);if(i)return Se("Found target message by index",{targetIndex:r,targetMessageID:i}),Yc(e,i)}let o=qc(e);if(o.length===0)return Se("No orphan thinking messages found"),!1;Se("Found orphan thinking messages",o);let s=!1;for(let i of o)Yc(e,i)&&(s=!0);return s}async function nx(e,t){Se("recoverThinkingDisabledViolation",{sessionID:e});let n=Vc(e);if(n.length===0)return Se("No messages with thinking blocks found"),!1;Se("Found messages with thinking blocks",n);let r=!1;for(let o of n)$y(o)&&(r=!0);return r}async function rx(e,t,n){Se("recoverEmptyContentMessage",{sessionID:e});let r=My(n),o=t.info?.id,s=!1,i=Dy(e);for(let l of i)go(l,st)&&(s=!0);let a=Oy(e);for(let l of a)mo(e,l,st)&&(s=!0);if(r!==null){let l=Ay(e,r);if(l&&(go(l,st)||mo(e,l,st)))return!0}if(o&&(go(o,st)||mo(e,o,st)))return!0;let c=Hc(e);for(let l of c)go(l,st)&&(s=!0),mo(e,l,st)&&(s=!0);return s}async function ox(e,t,n,r){Se("handleSessionRecovery",{sessionID:e,error:t});let o=Ly(t);if(!o)return Se("Not a recoverable error"),{attempted:!1,success:!1};Se("Detected recoverable error type",o);try{let s=!1,i=n||{info:{},parts:[]};switch(o){case"tool_result_missing":s=await ex(e,i);break;case"thinking_block_order":s=await tx(e,i,t);break;case"thinking_disabled_violation":s=await nx(e,i);break;case"empty_content":s=await rx(e,i,t);break}Se("Recovery result",{errorType:o,success:s});let a=r?.customMessages?.[o]||Bs[o]?.message||`Session recovery attempted for ${o}`;return{attempted:!0,success:s,message:s?a:void 0,errorType:o}}catch(s){return Se("Recovery failed with error",s),{attempted:!0,success:!1,errorType:o}}}function Uy(e){return Se("createSessionRecoveryHook",{config:e}),{onError:async t=>ox(t.session_id,t.error,t.message,e),isRecoverable:t=>XR(t),getRecoveryMessage:t=>{if(t)return e?.customMessages?.[t]||Bs[t]?.message}}}function Wy(){let e=Uy();P({name:"sessionRecovery",event:"PostToolUseFailure",priority:10,handler:async t=>{let n=t.error||t.toolOutput;if(!n)return{continue:!0};if(!e.isRecoverable(n))return{continue:!0};let r=await e.onError({session_id:t.sessionId||"default",error:n,message:void 0});return r.attempted&&r.success?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:r.message||`[session-recovery] Recovered from ${r.errorType} error. Please retry.`}}:r.attempted&&!r.success?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:`[session-recovery] Attempted recovery for ${r.errorType} but could not fix automatically. You may need to restart the session.`}}:{continue:!0}}})}var it=require("fs"),Hs=require("path"),Gy=require("os");var ho=class{config;counts=new Map;queues=new Map;constructor(t){this.config=t}getConcurrencyLimit(t){let n=this.config?.modelConcurrency?.[t];if(n!==void 0)return n===0?1/0:n;let r=t.split("/")[0],o=this.config?.providerConcurrency?.[r];if(o!==void 0)return o===0?1/0:o;let s=this.config?.defaultConcurrency;return s!==void 0?s===0?1/0:s:5}async acquire(t){let n=this.getConcurrencyLimit(t);if(n===1/0)return;let r=this.counts.get(t)??0;if(r<n){this.counts.set(t,r+1);return}return new Promise(o=>{let s=this.queues.get(t)??[];s.push(o),this.queues.set(t,s)})}release(t){if(this.getConcurrencyLimit(t)===1/0)return;let r=this.queues.get(t);if(r&&r.length>0)r.shift()();else{let o=this.counts.get(t)??0;o>0&&this.counts.set(t,o-1)}}getCount(t){return this.counts.get(t)??0}getQueueLength(t){return this.queues.get(t)?.length??0}isAtCapacity(t){let n=this.getConcurrencyLimit(t);return n===1/0?!1:(this.counts.get(t)??0)>=n}getActiveCounts(){return new Map(this.counts)}clear(){this.counts.clear(),this.queues.clear()}};var sx=1800*1e3,_r=(0,Hs.join)((0,Gy.homedir)(),".claude",".olympus","background-tasks"),Vs=class{tasks=new Map;notifications=new Map;concurrencyManager;config;pruneInterval;constructor(t){this.config=t??{},this.concurrencyManager=new ho(t),this.ensureStorageDir(),this.loadPersistedTasks(),this.startPruning()}ensureStorageDir(){(0,it.existsSync)(_r)||(0,it.mkdirSync)(_r,{recursive:!0})}generateTaskId(){let t=Date.now().toString(36),n=Math.random().toString(36).substring(2,8);return`bg_${t}${n}`}getTaskPath(t){return(0,Hs.join)(_r,`${t}.json`)}persistTask(t){let n=this.getTaskPath(t.id);(0,it.writeFileSync)(n,JSON.stringify(t,null,2))}unpersistTask(t){let n=this.getTaskPath(t);(0,it.existsSync)(n)&&(0,it.unlinkSync)(n)}loadPersistedTasks(){if((0,it.existsSync)(_r))try{let{readdirSync:t}=require("fs"),n=t(_r);for(let r of n)if(r.endsWith(".json"))try{let o=(0,Hs.join)(_r,r),s=(0,it.readFileSync)(o,"utf-8"),i=JSON.parse(s);i.startedAt=new Date(i.startedAt),i.completedAt&&(i.completedAt=new Date(i.completedAt)),i.progress?.lastUpdate&&(i.progress.lastUpdate=new Date(i.progress.lastUpdate)),i.progress?.lastMessageAt&&(i.progress.lastMessageAt=new Date(i.progress.lastMessageAt)),this.tasks.set(i.id,i)}catch{}}catch{}}startPruning(){this.pruneInterval||(this.pruneInterval=setInterval(()=>{this.pruneStaleTasksAndNotifications()},6e4),this.pruneInterval.unref&&this.pruneInterval.unref())}stopPruning(){this.pruneInterval&&(clearInterval(this.pruneInterval),this.pruneInterval=void 0)}pruneStaleTasksAndNotifications(){let t=Date.now(),n=this.config.taskTimeoutMs??sx;for(let[r,o]of this.tasks.entries())t-o.startedAt.getTime()>n&&o.status==="running"&&(o.status="error",o.error=`Task timed out after ${Math.round(n/6e4)} minutes`,o.completedAt=new Date,o.concurrencyKey&&this.concurrencyManager.release(o.concurrencyKey),this.clearNotificationsForTask(r),this.unpersistTask(r),this.tasks.delete(r));for(let[r,o]of this.notifications.entries()){let s=o.filter(i=>t-i.startedAt.getTime()<=n);s.length===0?this.notifications.delete(r):s.length!==o.length&&this.notifications.set(r,s)}}async launch(t){let n=t.agent,r=this.config.maxTotalTasks??10;if(Array.from(this.tasks.values()).filter(c=>c.status==="running").length>=r)throw new Error(`Maximum concurrent background tasks (${r}) reached. Wait for some tasks to complete.`);await this.concurrencyManager.acquire(n);let s=this.generateTaskId(),i=`ses_${this.generateTaskId()}`,a={id:s,sessionId:i,parentSessionId:t.parentSessionId,description:t.description,prompt:t.prompt,agent:t.agent,status:"running",startedAt:new Date,progress:{toolCalls:0,lastUpdate:new Date},concurrencyKey:n};return this.tasks.set(s,a),this.persistTask(a),a}async resume(t){let n=this.findBySession(t.sessionId);if(!n)throw new Error(`Task not found for session: ${t.sessionId}`);return n.status="running",n.completedAt=void 0,n.error=void 0,n.parentSessionId=t.parentSessionId,n.progress||(n.progress={toolCalls:0,lastUpdate:new Date}),n.progress.lastUpdate=new Date,this.persistTask(n),n}getTask(t){return this.tasks.get(t)}findBySession(t){for(let n of this.tasks.values())if(n.sessionId===t)return n}getTasksByParentSession(t){let n=[];for(let r of this.tasks.values())r.parentSessionId===t&&n.push(r);return n}getAllTasks(){return Array.from(this.tasks.values())}getRunningTasks(){return Array.from(this.tasks.values()).filter(t=>t.status==="running")}updateTaskStatus(t,n,r,o){let s=this.tasks.get(t);s&&(s.status=n,r&&(s.result=r),o&&(s.error=o),(n==="completed"||n==="error"||n==="cancelled")&&(s.completedAt=new Date,s.concurrencyKey&&this.concurrencyManager.release(s.concurrencyKey),this.markForNotification(s)),this.persistTask(s))}updateTaskProgress(t,n){let r=this.tasks.get(t);r&&(r.progress||(r.progress={toolCalls:0,lastUpdate:new Date}),Object.assign(r.progress,n,{lastUpdate:new Date}),this.persistTask(r))}markForNotification(t){let n=this.notifications.get(t.parentSessionId)??[];n.push(t),this.notifications.set(t.parentSessionId,n)}getPendingNotifications(t){return this.notifications.get(t)??[]}clearNotifications(t){this.notifications.delete(t)}clearNotificationsForTask(t){for(let[n,r]of this.notifications.entries()){let o=r.filter(s=>s.id!==t);o.length===0?this.notifications.delete(n):this.notifications.set(n,o)}}removeTask(t){let n=this.tasks.get(t);n?.concurrencyKey&&this.concurrencyManager.release(n.concurrencyKey),this.clearNotificationsForTask(t),this.unpersistTask(t),this.tasks.delete(t)}formatDuration(t,n){let r=(n??new Date).getTime()-t.getTime(),o=Math.floor(r/1e3),s=Math.floor(o/60),i=Math.floor(s/60);return i>0?`${i}h ${s%60}m ${o%60}s`:s>0?`${s}m ${o%60}s`:`${o}s`}getStatusSummary(){let t=this.getRunningTasks(),n=this.getAllTasks();if(n.length===0)return"No background tasks.";let r=[`Background Tasks: ${t.length} running, ${n.length} total`,""];for(let o of n){let s=this.formatDuration(o.startedAt,o.completedAt),i=o.status.toUpperCase(),a=o.progress?` (${o.progress.toolCalls} tools)`:"";r.push(` [${i}] ${o.description} - ${s}${a}`),o.error&&r.push(` Error: ${o.error}`)}return r.join(`
1998
- `)}cleanup(){this.stopPruning(),this.tasks.clear(),this.notifications.clear()}},Kc;function Jc(e){return Kc||(Kc=new Vs(e)),Kc}function ix(e){let t=e.status.toUpperCase(),n=ax(e.startedAt,e.completedAt),o=[`${e.status==="completed"?"\u2713":e.status==="error"?"\u2717":"\u25CB"} [${t}] ${e.description}`,` Agent: ${e.agent}`,` Duration: ${n}`];if(e.progress?.toolCalls&&o.push(` Tool calls: ${e.progress.toolCalls}`),e.result){let s=e.result.substring(0,200),i=e.result.length>200?"...":"";o.push(` Result: ${s}${i}`)}return e.error&&o.push(` Error: ${e.error}`),o.join(`
1999
- `)}function ax(e,t){let n=(t??new Date).getTime()-e.getTime(),r=Math.floor(n/1e3),o=Math.floor(r/60),s=Math.floor(o/60);return s>0?`${s}h ${o%60}m ${r%60}s`:o>0?`${o}m ${r%60}s`:`${r}s`}function cx(e){if(e.length===0)return"";let t=e.length===1?`
1996
+ `}function xy(){let e=new Map,t=new Map;function n(c){if(!e.has(c)){let u=qc(c)??{sessionID:c,agentUsed:!1,reminderCount:0,updatedAt:Date.now()};e.set(c,u)}return e.get(c)}function r(c){let l=n(c);l.agentUsed=!0,l.updatedAt=Date.now(),Gs(l)}function o(c){e.delete(c),Yc(c),t.delete(c)}function s(c,l,u){let d=t.get(c)||{consecutiveCount:0,lastToolName:"",lastFilePath:"",sessionId:c};return l.toLowerCase()==="task"?(d.consecutiveCount=0,t.set(c,d),0):(["edit","write","multiedit"].includes(l.toLowerCase())&&(d.consecutiveCount++,d.lastToolName=l,d.lastFilePath=u,t.set(c,d)),d.consecutiveCount)}return{"tool.execute.after":async(c,l)=>{let{tool:u,sessionID:d}=c,p=u.toLowerCase();if(Gc.has(p)){r(d),s(d,p,"");return}let f=c.properties||{},m=sx(f),g=s(d,p,m||""),y=ox();if(y.active){let _=ix(g,y.mode);if(_){l.output=_+l.output;return}}if(!Bc.has(p))return;let w=n(d);w.agentUsed||(l.output+=Hc,w.reminderCount++,w.updatedAt=Date.now(),Gs(w))},event:async({event:c})=>{let l=c.properties;if(c.type==="session.deleted"){let u=l?.info;u?.id&&o(u.id)}if(c.type==="session.compacted"){let u=l?.sessionID??l?.info?.id;u&&o(u)}}}}function Py(){let e=process.cwd(),t=Qh();P({name:"editErrorRecovery",event:"PostToolUse",matcher:/^edit$/i,priority:10,handler:async c=>{if(!c.toolName||!c.toolOutput)return{continue:!0};let l=t.afterToolExecute({tool:c.toolName,sessionId:c.sessionId||"",callId:""},{title:"",output:String(c.toolOutput),metadata:void 0});return l.output!==String(c.toolOutput)?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:l.output.substring(String(c.toolOutput).length)}}:{continue:!0}}});let n=ny();P({name:"commentChecker",event:"PostToolUse",matcher:/^(write|edit|multiedit)$/i,priority:20,handler:async c=>{if(!c.toolName)return{continue:!0};let l=n.postToolUse({tool_name:c.toolName,session_id:c.sessionId||"",tool_input:c.toolInput||{},tool_response:c.toolOutput?String(c.toolOutput):void 0});return l?{continue:!0,message:l}:{continue:!0}}});let r=fy();P({name:"contextWindowLimitRecovery",event:"PostToolUse",priority:30,handler:async c=>{if(!c.toolName)return{continue:!0};let l=r.postToolUse({tool_name:c.toolName,session_id:c.sessionId||"",tool_input:c.toolInput||{},tool_response:c.toolOutput?String(c.toolOutput):void 0});return l?{continue:!0,message:l}:{continue:!0}}});let o=gy();P({name:"readToolLimitRecovery",event:"PostToolUse",matcher:/^read$/i,priority:35,handler:async c=>{if(!c.toolName||c.toolName.toLowerCase()!=="read")return{continue:!0};let l=o.postToolUse({tool_name:c.toolName,session_id:c.sessionId||"",tool_input:c.toolInput||{},tool_response:c.toolOutput?String(c.toolOutput):void 0});return l?{continue:!0,message:l}:{continue:!0}}});let s=Ey();P({name:"preemptiveCompaction",event:"PostToolUse",matcher:/^(read|grep|glob|bash|webfetch)$/i,priority:40,handler:async c=>{if(!c.toolName)return{continue:!0};let l=s.postToolUse({tool_name:c.toolName,session_id:c.sessionId||"",tool_input:c.toolInput||{},tool_response:c.toolOutput?String(c.toolOutput):void 0});return l?{continue:!0,message:l}:{continue:!0}}});let i=xy();P({name:"agentUsageReminder",event:"PostToolUse",matcher:/^(read|grep|glob|edit|write)$/i,priority:50,handler:async c=>{if(!c.toolName)return{continue:!0};let l={title:"",output:c.toolOutput?String(c.toolOutput):"",metadata:void 0};await i["tool.execute.after"]({tool:c.toolName,sessionID:c.sessionId||"",callID:""},l);let u=c.toolOutput?String(c.toolOutput):"";return l.output!==u?{continue:!0,message:l.output.substring(u.length)}:{continue:!0}}});let a=$s(e);P({name:"olympusOrchestratorPost",event:"PostToolUse",matcher:/^(write|edit|bash|task)$/i,priority:60,handler:async c=>{if(!c.toolName)return{continue:!0};let l=a.postTool(c.toolName,c.toolInput||{},c.toolOutput?String(c.toolOutput):"");return l.continue?l.modifiedOutput?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:l.modifiedOutput}}:l.message?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:l.message}}:{continue:!0}:{continue:!1,stopReason:l.message}}})}var Wy=require("node:fs");var J=require("node:fs"),We=require("node:path");var wr=require("node:path"),Hs=require("node:os");function ax(){return process.env.XDG_DATA_HOME??(0,wr.join)((0,Hs.homedir)(),".local","share")}function cx(){return(0,wr.join)(ax(),"claude-code","storage")}var Ay=cx(),fo=(0,wr.join)(Ay,"message"),_r=(0,wr.join)(Ay,"part"),pn=new Set(["thinking","redacted_thinking","reasoning"]),Iy=new Set(["step-start","step-finish"]);var st="[user interrupted]",Vs={tool_result_missing:{title:"Tool Crash Recovery",message:"Injecting cancelled tool results..."},thinking_block_order:{title:"Thinking Block Recovery",message:"Fixing message structure..."},thinking_disabled_violation:{title:"Thinking Strip Recovery",message:"Stripping thinking blocks..."},empty_content:{title:"Empty Content Recovery",message:"Adding placeholder content..."}};var Oy=process.env.SESSION_RECOVERY_DEBUG==="1",$y=(0,wr.join)((0,Hs.tmpdir)(),"session-recovery-debug.log");function lx(){let e=Date.now().toString(16),t=Math.random().toString(36).substring(2,10);return`prt_${e}${t}`}function ux(e){if(!(0,J.existsSync)(fo))return"";let t=(0,We.join)(fo,e);if((0,J.existsSync)(t))return t;for(let n of(0,J.readdirSync)(fo)){let r=(0,We.join)(fo,n,e);if((0,J.existsSync)(r))return r}return""}function Kt(e){let t=ux(e);if(!t||!(0,J.existsSync)(t))return[];let n=[];for(let r of(0,J.readdirSync)(t))if(r.endsWith(".json"))try{let o=(0,J.readFileSync)((0,We.join)(t,r),"utf-8");n.push(JSON.parse(o))}catch{continue}return n.sort((r,o)=>{let s=r.time?.created??0,i=o.time?.created??0;return s!==i?s-i:r.id.localeCompare(o.id)})}function It(e){let t=(0,We.join)(_r,e);if(!(0,J.existsSync)(t))return[];let n=[];for(let r of(0,J.readdirSync)(t))if(r.endsWith(".json"))try{let o=(0,J.readFileSync)((0,We.join)(t,r),"utf-8");n.push(JSON.parse(o))}catch{continue}return n}function Dy(e){return pn.has(e.type)||Iy.has(e.type)?!1:e.type==="text"?!!e.text?.trim():e.type==="tool"||e.type==="tool_use"||e.type==="tool_result"}function Ny(e){return It(e).some(Dy)}function mo(e,t,n){let r=(0,We.join)(_r,t);(0,J.existsSync)(r)||(0,J.mkdirSync)(r,{recursive:!0});let o=lx(),s={id:o,sessionID:e,messageID:t,type:"text",text:n,synthetic:!0};try{return(0,J.writeFileSync)((0,We.join)(r,`${o}.json`),JSON.stringify(s,null,2)),!0}catch{return!1}}function Kc(e){let t=Kt(e),n=[];for(let r of t)Ny(r.id)||n.push(r.id);return n}function Fy(e,t){let n=Kt(e),r=[t,t-1,t+1,t-2,t+2,t-3,t-4,t-5];for(let o of r){if(o<0||o>=n.length)continue;let s=n[o];if(!Ny(s.id))return s.id}return null}function Jc(e){let t=Kt(e),n=[];for(let r of t){if(r.role!=="assistant")continue;It(r.id).some(i=>pn.has(i.type))&&n.push(r.id)}return n}function jy(e){let t=Kt(e),n=[];for(let r of t){if(r.role!=="assistant")continue;let o=It(r.id);if(o.length===0)continue;let s=o.some(a=>pn.has(a.type)),i=o.some(Dy);s&&!i&&n.push(r.id)}return n}function zc(e){let t=Kt(e),n=[];for(let r of t){if(r.role!=="assistant")continue;let o=It(r.id);if(o.length===0)continue;let i=[...o].sort((c,l)=>c.id.localeCompare(l.id))[0];pn.has(i.type)||n.push(r.id)}return n}function dx(e,t){let n=Kt(e),r=n.findIndex(o=>o.id===t);if(r===-1)return"";for(let o=r-1;o>=0;o--){let s=n[o];if(s.role!=="assistant")continue;let i=It(s.id);for(let a of i)if(pn.has(a.type)){let c=a.thinking,l=a.text,u=c||l;if(u&&u.trim().length>0)return u}}return""}function Qc(e,t){let n=(0,We.join)(_r,t);(0,J.existsSync)(n)||(0,J.mkdirSync)(n,{recursive:!0});let r=dx(e,t),o="prt_0000000000_thinking",s={id:o,sessionID:e,messageID:t,type:"thinking",thinking:r||"[Continuing from previous reasoning]",synthetic:!0};try{return(0,J.writeFileSync)((0,We.join)(n,`${o}.json`),JSON.stringify(s,null,2)),!0}catch{return!1}}function My(e){let t=(0,We.join)(_r,e);if(!(0,J.existsSync)(t))return!1;let n=!1;for(let r of(0,J.readdirSync)(t))if(r.endsWith(".json"))try{let o=(0,We.join)(t,r),s=(0,J.readFileSync)(o,"utf-8"),i=JSON.parse(s);pn.has(i.type)&&((0,J.unlinkSync)(o),n=!0)}catch{continue}return n}function go(e,t=st){let n=(0,We.join)(_r,e);if(!(0,J.existsSync)(n))return!1;let r=!1;for(let o of(0,J.readdirSync)(n))if(o.endsWith(".json"))try{let s=(0,We.join)(n,o),i=(0,J.readFileSync)(s,"utf-8"),a=JSON.parse(i);if(a.type==="text"){let c=a;c.text?.trim()||(c.text=t,c.synthetic=!0,(0,J.writeFileSync)(s,JSON.stringify(c,null,2)),r=!0)}}catch{continue}return r}function Ly(e){let t=Kt(e),n=[];for(let r of t)It(r.id).some(i=>i.type!=="text"?!1:!i.text?.trim())&&n.push(r.id);return n}function Uy(e,t){let n=Kt(e);if(t<0||t>=n.length)return null;let r=n[t];if(r.role!=="assistant")return null;let o=It(r.id);if(o.length===0)return null;let i=[...o].sort((c,l)=>c.id.localeCompare(l.id))[0];return pn.has(i.type)?null:r.id}function Se(...e){if(Oy){let t=`[${new Date().toISOString()}] [session-recovery] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
1997
+ `;(0,Wy.appendFileSync)($y,t)}}function By(e){if(!e)return"";if(typeof e=="string")return e.toLowerCase();let t=e,n=[t.data,t.error,t,t.data?.error];for(let r of n)if(r&&typeof r=="object"){let o=r.message;if(typeof o=="string"&&o.length>0)return o.toLowerCase()}try{return JSON.stringify(e).toLowerCase()}catch{return""}}function Gy(e){let n=By(e).match(/messages\.(\d+)/);return n?parseInt(n[1],10):null}function Hy(e){let t=By(e);return t.includes("tool_use")&&t.includes("tool_result")?"tool_result_missing":t.includes("thinking")&&(t.includes("first block")||t.includes("must start with")||t.includes("preceeding")||t.includes("final block")||t.includes("cannot be thinking")||t.includes("expected")&&t.includes("found"))?"thinking_block_order":t.includes("thinking is disabled")&&t.includes("cannot contain")?"thinking_disabled_violation":t.includes("empty")&&(t.includes("content")||t.includes("message"))?"empty_content":null}function px(e){return Hy(e)!==null}function fx(e){return e.filter(t=>t.type==="tool_use"&&!!t.id).map(t=>t.id)}async function mx(e,t){Se("recoverToolResultMissing",{sessionID:e,msgId:t.info?.id});let n=t.parts||[];n.length===0&&t.info?.id&&(n=It(t.info.id).map(s=>({type:s.type==="tool"?"tool_use":s.type,id:"callID"in s?s.callID:s.id,name:"tool"in s?s.tool:void 0,input:"state"in s?s.state?.input:void 0})));let r=fx(n);return r.length===0?(Se("No tool_use IDs found"),!1):(Se("Found tool_use IDs to inject results for",r),!0)}async function gx(e,t,n){Se("recoverThinkingBlockOrder",{sessionID:e});let r=Gy(n);if(r!==null){let i=Uy(e,r);if(i)return Se("Found target message by index",{targetIndex:r,targetMessageID:i}),Qc(e,i)}let o=zc(e);if(o.length===0)return Se("No orphan thinking messages found"),!1;Se("Found orphan thinking messages",o);let s=!1;for(let i of o)Qc(e,i)&&(s=!0);return s}async function hx(e,t){Se("recoverThinkingDisabledViolation",{sessionID:e});let n=Jc(e);if(n.length===0)return Se("No messages with thinking blocks found"),!1;Se("Found messages with thinking blocks",n);let r=!1;for(let o of n)My(o)&&(r=!0);return r}async function yx(e,t,n){Se("recoverEmptyContentMessage",{sessionID:e});let r=Gy(n),o=t.info?.id,s=!1,i=Ly(e);for(let l of i)go(l,st)&&(s=!0);let a=jy(e);for(let l of a)mo(e,l,st)&&(s=!0);if(r!==null){let l=Fy(e,r);if(l&&(go(l,st)||mo(e,l,st)))return!0}if(o&&(go(o,st)||mo(e,o,st)))return!0;let c=Kc(e);for(let l of c)go(l,st)&&(s=!0),mo(e,l,st)&&(s=!0);return s}async function wx(e,t,n,r){Se("handleSessionRecovery",{sessionID:e,error:t});let o=Hy(t);if(!o)return Se("Not a recoverable error"),{attempted:!1,success:!1};Se("Detected recoverable error type",o);try{let s=!1,i=n||{info:{},parts:[]};switch(o){case"tool_result_missing":s=await mx(e,i);break;case"thinking_block_order":s=await gx(e,i,t);break;case"thinking_disabled_violation":s=await hx(e,i);break;case"empty_content":s=await yx(e,i,t);break}Se("Recovery result",{errorType:o,success:s});let a=r?.customMessages?.[o]||Vs[o]?.message||`Session recovery attempted for ${o}`;return{attempted:!0,success:s,message:s?a:void 0,errorType:o}}catch(s){return Se("Recovery failed with error",s),{attempted:!0,success:!1,errorType:o}}}function Vy(e){return Se("createSessionRecoveryHook",{config:e}),{onError:async t=>wx(t.session_id,t.error,t.message,e),isRecoverable:t=>px(t),getRecoveryMessage:t=>{if(t)return e?.customMessages?.[t]||Vs[t]?.message}}}function qy(){let e=Vy();P({name:"sessionRecovery",event:"PostToolUseFailure",priority:10,handler:async t=>{let n=t.error||t.toolOutput;if(!n)return{continue:!0};if(!e.isRecoverable(n))return{continue:!0};let r=await e.onError({session_id:t.sessionId||"default",error:n,message:void 0});return r.attempted&&r.success?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:r.message||`[session-recovery] Recovered from ${r.errorType} error. Please retry.`}}:r.attempted&&!r.success?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:`[session-recovery] Attempted recovery for ${r.errorType} but could not fix automatically. You may need to restart the session.`}}:{continue:!0}}})}var it=require("fs"),qs=require("path"),Yy=require("os");var ho=class{config;counts=new Map;queues=new Map;constructor(t){this.config=t}getConcurrencyLimit(t){let n=this.config?.modelConcurrency?.[t];if(n!==void 0)return n===0?1/0:n;let r=t.split("/")[0],o=this.config?.providerConcurrency?.[r];if(o!==void 0)return o===0?1/0:o;let s=this.config?.defaultConcurrency;return s!==void 0?s===0?1/0:s:5}async acquire(t){let n=this.getConcurrencyLimit(t);if(n===1/0)return;let r=this.counts.get(t)??0;if(r<n){this.counts.set(t,r+1);return}return new Promise(o=>{let s=this.queues.get(t)??[];s.push(o),this.queues.set(t,s)})}release(t){if(this.getConcurrencyLimit(t)===1/0)return;let r=this.queues.get(t);if(r&&r.length>0)r.shift()();else{let o=this.counts.get(t)??0;o>0&&this.counts.set(t,o-1)}}getCount(t){return this.counts.get(t)??0}getQueueLength(t){return this.queues.get(t)?.length??0}isAtCapacity(t){let n=this.getConcurrencyLimit(t);return n===1/0?!1:(this.counts.get(t)??0)>=n}getActiveCounts(){return new Map(this.counts)}clear(){this.counts.clear(),this.queues.clear()}};var _x=1800*1e3,kr=(0,qs.join)((0,Yy.homedir)(),".claude",".olympus","background-tasks"),Ys=class{tasks=new Map;notifications=new Map;concurrencyManager;config;pruneInterval;constructor(t){this.config=t??{},this.concurrencyManager=new ho(t),this.ensureStorageDir(),this.loadPersistedTasks(),this.startPruning()}ensureStorageDir(){(0,it.existsSync)(kr)||(0,it.mkdirSync)(kr,{recursive:!0})}generateTaskId(){let t=Date.now().toString(36),n=Math.random().toString(36).substring(2,8);return`bg_${t}${n}`}getTaskPath(t){return(0,qs.join)(kr,`${t}.json`)}persistTask(t){let n=this.getTaskPath(t.id);(0,it.writeFileSync)(n,JSON.stringify(t,null,2))}unpersistTask(t){let n=this.getTaskPath(t);(0,it.existsSync)(n)&&(0,it.unlinkSync)(n)}loadPersistedTasks(){if((0,it.existsSync)(kr))try{let{readdirSync:t}=require("fs"),n=t(kr);for(let r of n)if(r.endsWith(".json"))try{let o=(0,qs.join)(kr,r),s=(0,it.readFileSync)(o,"utf-8"),i=JSON.parse(s);i.startedAt=new Date(i.startedAt),i.completedAt&&(i.completedAt=new Date(i.completedAt)),i.progress?.lastUpdate&&(i.progress.lastUpdate=new Date(i.progress.lastUpdate)),i.progress?.lastMessageAt&&(i.progress.lastMessageAt=new Date(i.progress.lastMessageAt)),this.tasks.set(i.id,i)}catch{}}catch{}}startPruning(){this.pruneInterval||(this.pruneInterval=setInterval(()=>{this.pruneStaleTasksAndNotifications()},6e4),this.pruneInterval.unref&&this.pruneInterval.unref())}stopPruning(){this.pruneInterval&&(clearInterval(this.pruneInterval),this.pruneInterval=void 0)}pruneStaleTasksAndNotifications(){let t=Date.now(),n=this.config.taskTimeoutMs??_x;for(let[r,o]of this.tasks.entries())t-o.startedAt.getTime()>n&&o.status==="running"&&(o.status="error",o.error=`Task timed out after ${Math.round(n/6e4)} minutes`,o.completedAt=new Date,o.concurrencyKey&&this.concurrencyManager.release(o.concurrencyKey),this.clearNotificationsForTask(r),this.unpersistTask(r),this.tasks.delete(r));for(let[r,o]of this.notifications.entries()){let s=o.filter(i=>t-i.startedAt.getTime()<=n);s.length===0?this.notifications.delete(r):s.length!==o.length&&this.notifications.set(r,s)}}async launch(t){let n=t.agent,r=this.config.maxTotalTasks??10;if(Array.from(this.tasks.values()).filter(c=>c.status==="running").length>=r)throw new Error(`Maximum concurrent background tasks (${r}) reached. Wait for some tasks to complete.`);await this.concurrencyManager.acquire(n);let s=this.generateTaskId(),i=`ses_${this.generateTaskId()}`,a={id:s,sessionId:i,parentSessionId:t.parentSessionId,description:t.description,prompt:t.prompt,agent:t.agent,status:"running",startedAt:new Date,progress:{toolCalls:0,lastUpdate:new Date},concurrencyKey:n};return this.tasks.set(s,a),this.persistTask(a),a}async resume(t){let n=this.findBySession(t.sessionId);if(!n)throw new Error(`Task not found for session: ${t.sessionId}`);return n.status="running",n.completedAt=void 0,n.error=void 0,n.parentSessionId=t.parentSessionId,n.progress||(n.progress={toolCalls:0,lastUpdate:new Date}),n.progress.lastUpdate=new Date,this.persistTask(n),n}getTask(t){return this.tasks.get(t)}findBySession(t){for(let n of this.tasks.values())if(n.sessionId===t)return n}getTasksByParentSession(t){let n=[];for(let r of this.tasks.values())r.parentSessionId===t&&n.push(r);return n}getAllTasks(){return Array.from(this.tasks.values())}getRunningTasks(){return Array.from(this.tasks.values()).filter(t=>t.status==="running")}updateTaskStatus(t,n,r,o){let s=this.tasks.get(t);s&&(s.status=n,r&&(s.result=r),o&&(s.error=o),(n==="completed"||n==="error"||n==="cancelled")&&(s.completedAt=new Date,s.concurrencyKey&&this.concurrencyManager.release(s.concurrencyKey),this.markForNotification(s)),this.persistTask(s))}updateTaskProgress(t,n){let r=this.tasks.get(t);r&&(r.progress||(r.progress={toolCalls:0,lastUpdate:new Date}),Object.assign(r.progress,n,{lastUpdate:new Date}),this.persistTask(r))}markForNotification(t){let n=this.notifications.get(t.parentSessionId)??[];n.push(t),this.notifications.set(t.parentSessionId,n)}getPendingNotifications(t){return this.notifications.get(t)??[]}clearNotifications(t){this.notifications.delete(t)}clearNotificationsForTask(t){for(let[n,r]of this.notifications.entries()){let o=r.filter(s=>s.id!==t);o.length===0?this.notifications.delete(n):this.notifications.set(n,o)}}removeTask(t){let n=this.tasks.get(t);n?.concurrencyKey&&this.concurrencyManager.release(n.concurrencyKey),this.clearNotificationsForTask(t),this.unpersistTask(t),this.tasks.delete(t)}formatDuration(t,n){let r=(n??new Date).getTime()-t.getTime(),o=Math.floor(r/1e3),s=Math.floor(o/60),i=Math.floor(s/60);return i>0?`${i}h ${s%60}m ${o%60}s`:s>0?`${s}m ${o%60}s`:`${o}s`}getStatusSummary(){let t=this.getRunningTasks(),n=this.getAllTasks();if(n.length===0)return"No background tasks.";let r=[`Background Tasks: ${t.length} running, ${n.length} total`,""];for(let o of n){let s=this.formatDuration(o.startedAt,o.completedAt),i=o.status.toUpperCase(),a=o.progress?` (${o.progress.toolCalls} tools)`:"";r.push(` [${i}] ${o.description} - ${s}${a}`),o.error&&r.push(` Error: ${o.error}`)}return r.join(`
1998
+ `)}cleanup(){this.stopPruning(),this.tasks.clear(),this.notifications.clear()}},Xc;function Zc(e){return Xc||(Xc=new Ys(e)),Xc}function kx(e){let t=e.status.toUpperCase(),n=Sx(e.startedAt,e.completedAt),o=[`${e.status==="completed"?"\u2713":e.status==="error"?"\u2717":"\u25CB"} [${t}] ${e.description}`,` Agent: ${e.agent}`,` Duration: ${n}`];if(e.progress?.toolCalls&&o.push(` Tool calls: ${e.progress.toolCalls}`),e.result){let s=e.result.substring(0,200),i=e.result.length>200?"...":"";o.push(` Result: ${s}${i}`)}return e.error&&o.push(` Error: ${e.error}`),o.join(`
1999
+ `)}function Sx(e,t){let n=(t??new Date).getTime()-e.getTime(),r=Math.floor(n/1e3),o=Math.floor(r/60),s=Math.floor(o/60);return s>0?`${s}h ${o%60}m ${r%60}s`:o>0?`${o}m ${r%60}s`:`${r}s`}function vx(e){if(e.length===0)return"";let t=e.length===1?`
2000
2000
  [BACKGROUND TASK COMPLETED]
2001
2001
  `:`
2002
2002
  [${e.length} BACKGROUND TASKS COMPLETED]
2003
- `,n=e.map(r=>ix(r)).join(`
2003
+ `,n=e.map(r=>kx(r)).join(`
2004
2004
 
2005
2005
  `);return`${t}
2006
2006
  ${n}
2007
- `}function lx(e,t,n){let r=t.getPendingNotifications(e);if(r.length===0)return{hasNotifications:!1,tasks:[]};let s=(n?.formatNotification??cx)(r);return{hasNotifications:!0,tasks:r,message:s}}function By(e,t){let n=e.sessionId;if(!n)return{continue:!0};let r=Jc(),o=lx(n,r,t);return o.hasNotifications?((t?.autoClear??!0)&&r.clearNotifications(n),{continue:!0,message:o.message,notificationCount:o.tasks.length}):{continue:!0}}function Hy(){P({name:"backgroundNotification",event:"Notification",priority:10,handler:async e=>{let t={sessionId:e.sessionId,directory:e.directory,event:e.event?{type:e.event.type,properties:e.event.properties}:void 0},n=await By(t);return{continue:n.continue,hookSpecificOutput:n.message?{hookEventName:"Notification",additionalContext:n.message}:void 0}}})}var Qc=null,zc=!1;async function ux(){if(!zc)try{let{encode:e}=await import("gpt-tokenizer");Qc=e,zc=!0}catch{zc=!0}}function dx(e){return Math.ceil(e.length/4)}async function Mn(e){if(!e||e.length===0)return 0;await ux();try{if(Qc)return Qc(e).length}catch{}return dx(e)}async function Vy(e){if(!e)return 0;if(typeof e=="object"&&e!==null){let n=e;if("content"in n&&typeof n.content=="string")return Mn(n.content);if("output"in n&&typeof n.output=="string")return Mn(n.output);if("text"in n&&typeof n.text=="string")return Mn(n.text);if("result"in n&&typeof n.result=="string")return Mn(n.result)}let t=typeof e=="string"?e:JSON.stringify(e);return Mn(t)}var Xc=[{model_pattern:"claude-opus",input_per_million:15,output_per_million:75,effective_date:"2025-01-01"},{model_pattern:"claude-sonnet",input_per_million:3,output_per_million:15,effective_date:"2025-01-01"},{model_pattern:"claude-haiku",input_per_million:.25,output_per_million:1.25,effective_date:"2025-01-01"}];function qy(e,t,n,r=Xc){let o=r.find(a=>new RegExp(a.model_pattern,"i").test(n));if(!o){let a=r.find(u=>u.model_pattern==="claude-sonnet")||{input_per_million:3,output_per_million:15,effective_date:"2025-01-01"},c=e/1e6*a.input_per_million,l=t/1e6*a.output_per_million;return{inputCost:c,outputCost:l,totalCost:c+l,pricingVersion:a.effective_date}}let s=e/1e6*o.input_per_million,i=t/1e6*o.output_per_million;return{inputCost:s,outputCost:i,totalCost:s+i,pricingVersion:o.effective_date}}Ge();we();var Sr=T(require("fs"),1),qs=T(require("path"),1),Xy=T(require("os"),1),Zy=process.env.OLYMPUS_DEBUG_HOOKS==="1",Jy=qs.join(Xy.homedir(),".claude","olympus","learning","hooks-debug.log");function D(e,t,n){if(Zy)try{let o=`[${new Date().toISOString()}] [${e}] ${t}`;n!==void 0&&(typeof n=="object"?o+=`
2007
+ `}function bx(e,t,n){let r=t.getPendingNotifications(e);if(r.length===0)return{hasNotifications:!1,tasks:[]};let s=(n?.formatNotification??vx)(r);return{hasNotifications:!0,tasks:r,message:s}}function Ky(e,t){let n=e.sessionId;if(!n)return{continue:!0};let r=Zc(),o=bx(n,r,t);return o.hasNotifications?((t?.autoClear??!0)&&r.clearNotifications(n),{continue:!0,message:o.message,notificationCount:o.tasks.length}):{continue:!0}}function Jy(){P({name:"backgroundNotification",event:"Notification",priority:10,handler:async e=>{let t={sessionId:e.sessionId,directory:e.directory,event:e.event?{type:e.event.type,properties:e.event.properties}:void 0},n=await Ky(t);return{continue:n.continue,hookSpecificOutput:n.message?{hookEventName:"Notification",additionalContext:n.message}:void 0}}})}var tl=null,el=!1;async function Tx(){if(!el)try{let{encode:e}=await import("gpt-tokenizer");tl=e,el=!0}catch{el=!0}}function Ex(e){return Math.ceil(e.length/4)}async function Mn(e){if(!e||e.length===0)return 0;await Tx();try{if(tl)return tl(e).length}catch{}return Ex(e)}async function zy(e){if(!e)return 0;if(typeof e=="object"&&e!==null){let n=e;if("content"in n&&typeof n.content=="string")return Mn(n.content);if("output"in n&&typeof n.output=="string")return Mn(n.output);if("text"in n&&typeof n.text=="string")return Mn(n.text);if("result"in n&&typeof n.result=="string")return Mn(n.result)}let t=typeof e=="string"?e:JSON.stringify(e);return Mn(t)}var nl=[{model_pattern:"claude-opus",input_per_million:15,output_per_million:75,effective_date:"2025-01-01"},{model_pattern:"claude-sonnet",input_per_million:3,output_per_million:15,effective_date:"2025-01-01"},{model_pattern:"claude-haiku",input_per_million:.25,output_per_million:1.25,effective_date:"2025-01-01"}];function Qy(e,t,n,r=nl){let o=r.find(a=>new RegExp(a.model_pattern,"i").test(n));if(!o){let a=r.find(u=>u.model_pattern==="claude-sonnet")||{input_per_million:3,output_per_million:15,effective_date:"2025-01-01"},c=e/1e6*a.input_per_million,l=t/1e6*a.output_per_million;return{inputCost:c,outputCost:l,totalCost:c+l,pricingVersion:a.effective_date}}let s=e/1e6*o.input_per_million,i=t/1e6*o.output_per_million;return{inputCost:s,outputCost:i,totalCost:s+i,pricingVersion:o.effective_date}}Be();we();var Sr=b(require("fs"),1),Ks=b(require("path"),1),rw=b(require("os"),1),ow=process.env.OLYMPUS_DEBUG_HOOKS==="1",ew=Ks.join(rw.homedir(),".claude","olympus","learning","hooks-debug.log");function D(e,t,n){if(ow)try{let o=`[${new Date().toISOString()}] [${e}] ${t}`;n!==void 0&&(typeof n=="object"?o+=`
2008
2008
  ${JSON.stringify(n,null,2)}`:o+=` ${n}`),o+=`
2009
- `;let s=qs.dirname(Jy);Sr.existsSync(s)||Sr.mkdirSync(s,{recursive:!0}),Sr.appendFileSync(Jy,o,"utf8")}catch(r){console.error("[Olympus Debug] Failed to write debug log:",r)}}function Zc(e,t){Zy&&D(e,"Context received",{directory:t.directory,sessionId:t.sessionId,hasPrompt:!!t.prompt,promptLength:t.prompt?.length||0,hasMessage:!!t.message,messageModel:t.message?.model,toolName:t.toolName,hasToolOutput:!!t.toolOutput,toolOutputType:t.toolOutput?typeof t.toolOutput:void 0,hasParts:!!t.parts,partsLength:t.parts?.length||0})}function fx(e){return e.prompt?e.prompt:e.message?.content?e.message.content:e.parts?e.parts.filter(t=>t.type==="text"&&t.text).map(t=>t.text).join(" "):""}function zy(e){if(e.message?.model){let{providerId:t,modelId:n}=e.message.model;if(t&&n)return`${t}/${n}`;if(n)return n}}function Qy(e,t=1e4){return e.token_budget?(e.token_budget.input_tokens===void 0&&(e.token_budget.input_tokens=0),e.token_budget.output_tokens===void 0&&(e.token_budget.output_tokens=0)):e.token_budget={session_baseline:t,current_usage:0,input_tokens:0,output_tokens:0,warning_threshold:1.5,warning_issued:!1,started_at:new Date().toISOString()},e}function ew(){P({name:"learningCapturePrompt",event:"UserPromptSubmit",priority:110,handler:async e=>{D("learningCapturePrompt","Hook fired"),Zc("learningCapturePrompt",e);try{if(!e.directory)return D("learningCapturePrompt","No directory in context - skipping"),{continue:!0};D("learningCapturePrompt","Extracting prompt text");let t=fx(e);if(!t)return D("learningCapturePrompt","No prompt text extracted - skipping"),{continue:!0};D("learningCapturePrompt",`Prompt text extracted (${t.length} chars)`),D("learningCapturePrompt","Estimating input tokens");let n=await Mn(t);D("learningCapturePrompt",`Estimated tokens: ${n}`),D("learningCapturePrompt","Loading session state",{directory:e.directory,sessionId:e.sessionId});let r=Q(e.directory,e.sessionId);D("learningCapturePrompt","Session state loaded",{hasTokenBudget:!!r.token_budget,currentUsage:r.token_budget?.current_usage,inputTokens:r.token_budget?.input_tokens,outputTokens:r.token_budget?.output_tokens}),Qy(r),D("learningCapturePrompt","Token budget ensured");let o=zy(e);if(D("learningCapturePrompt",`Model identifier: ${o||"none"}`),o&&r.token_budget&&(r.token_budget.current_model=o,D("learningCapturePrompt",`Model set in token budget: ${o}`)),r.token_budget){let s=r.token_budget.input_tokens,i=r.token_budget.current_usage;r.token_budget.input_tokens+=n,r.token_budget.current_usage+=n,D("learningCapturePrompt","Tokens accumulated",{addedTokens:n,inputTokens:{before:s,after:r.token_budget.input_tokens},currentUsage:{before:i,after:r.token_budget.current_usage}}),D("learningCapturePrompt","Saving session state"),ee(e.directory,r),D("learningCapturePrompt","Session state saved successfully")}else D("learningCapturePrompt","WARNING: No token budget after ensure - this should not happen")}catch(t){D("learningCapturePrompt","ERROR in handler",{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0}),console.error("[Olympus Learning Capture] Error in prompt handler:",t)}return D("learningCapturePrompt","Hook completed"),{continue:!0}}}),P({name:"learningCaptureTool",event:"PostToolUse",priority:70,handler:async e=>{D("learningCaptureTool","Hook fired"),Zc("learningCaptureTool",e);try{if(!e.directory||!e.toolName)return D("learningCaptureTool","Missing directory or toolName - skipping",{hasDirectory:!!e.directory,hasToolName:!!e.toolName}),{continue:!0};D("learningCaptureTool",`Processing tool: ${e.toolName}`),D("learningCaptureTool","Estimating output tokens from tool result");let t=e.toolOutput?await Vy(e.toolOutput):0;D("learningCaptureTool",`Estimated output tokens: ${t}`),D("learningCaptureTool","Loading session state",{directory:e.directory,sessionId:e.sessionId});let n=Q(e.directory,e.sessionId);D("learningCaptureTool","Session state loaded",{hasTokenBudget:!!n.token_budget,currentUsage:n.token_budget?.current_usage,inputTokens:n.token_budget?.input_tokens,outputTokens:n.token_budget?.output_tokens}),Qy(n),D("learningCaptureTool","Token budget ensured");let r=zy(e);if(D("learningCaptureTool",`Model identifier: ${r||"none"}`),r&&n.token_budget&&(n.token_budget.current_model=r,D("learningCaptureTool",`Model set in token budget: ${r}`)),n.token_budget){let o=n.token_budget.output_tokens,s=n.token_budget.current_usage;n.token_budget.output_tokens+=t,n.token_budget.current_usage+=t,D("learningCaptureTool","Tokens accumulated",{addedTokens:t,outputTokens:{before:o,after:n.token_budget.output_tokens},currentUsage:{before:s,after:n.token_budget.current_usage}}),D("learningCaptureTool","Saving session state"),ee(e.directory,n),D("learningCaptureTool","Session state saved successfully")}else D("learningCaptureTool","WARNING: No token budget after ensure - this should not happen")}catch(t){D("learningCaptureTool","ERROR in handler",{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0}),console.error("[Olympus Learning Capture] Error in tool use handler:",t)}return D("learningCaptureTool","Hook completed"),{continue:!0}}}),P({name:"learningCaptureStop",event:"Stop",priority:90,handler:async e=>{D("learningCaptureStop","Hook fired"),Zc("learningCaptureStop",e);try{if(!e.directory)return D("learningCaptureStop","No directory in context - skipping"),{continue:!0};D("learningCaptureStop","Loading session state",{directory:e.directory,sessionId:e.sessionId});let t=Q(e.directory,e.sessionId);if(D("learningCaptureStop","Session state loaded",{hasTokenBudget:!!t.token_budget,currentUsage:t.token_budget?.current_usage,inputTokens:t.token_budget?.input_tokens,outputTokens:t.token_budget?.output_tokens,currentModel:t.token_budget?.current_model}),!t.token_budget)return D("learningCaptureStop","No token budget in session state - skipping (backward compatibility)"),{continue:!0};let n=t.token_budget.current_usage,r=t.token_budget.input_tokens||0,o=t.token_budget.output_tokens||0;if(D("learningCaptureStop","Token totals",{totalTokens:n,inputTokens:r,outputTokens:o}),n===0)return D("learningCaptureStop","No token usage recorded - skipping feedback entry creation"),{continue:!0};let s=t.token_budget.current_model||"unknown";D("learningCaptureStop",`Using model identifier: ${s}`),D("learningCaptureStop","Token usage object created",{input_tokens:r,output_tokens:o,total_tokens:n,estimated:!0,model:s}),D("learningCaptureStop","Calculating cost estimate");let a={input_cost:0,output_cost:0,total_cost:0,pricing_version:"2025-01-01"};try{let l=qy(r,o,s);a.input_cost=l.inputCost,a.output_cost=l.outputCost,a.total_cost=l.totalCost,a.pricing_version=l.pricingVersion,D("learningCaptureStop","Cost calculated successfully",{inputCost:l.inputCost,outputCost:l.outputCost,totalCost:l.totalCost})}catch(l){D("learningCaptureStop","Cost calculation failed (not critical)",{error:l instanceof Error?l.message:String(l)})}let c={session_id:t.session_id,project_path:e.directory,started_at:t.token_budget.started_at,ended_at:new Date().toISOString(),duration_seconds:Math.round((Date.now()-new Date(t.token_budget.started_at).getTime())/1e3),agents_used:t.token_budget.agents_used||[],total_input_tokens:r,total_output_tokens:o,total_tokens:n,estimated_cost:a.total_cost,model:s,outcome:"success"};D("learningCaptureStop","Session summary created",{sessionId:c.session_id,duration:c.duration_seconds,agentsUsed:c.agents_used,totalTokens:c.total_tokens,cost:c.estimated_cost});try{iu(c),D("learningCaptureStop","Session summary saved successfully")}catch(l){D("learningCaptureStop","Failed to save session summary (non-critical)",{error:l instanceof Error?l.message:String(l)})}try{let{formatSessionSummaryLine:l}=await Promise.resolve().then(()=>(Ky(),Yy)),u=l(c);console.error(u)}catch{}D("learningCaptureStop","Resetting token budget for next session"),t.token_budget.current_usage=0,t.token_budget.input_tokens=0,t.token_budget.output_tokens=0,t.token_budget.warning_issued=!1,t.token_budget.started_at=new Date().toISOString(),delete t.token_budget.current_model,delete t.token_budget.agents_used,D("learningCaptureStop","Saving reset session state"),ee(e.directory,t),D("learningCaptureStop","Session state saved successfully")}catch(t){D("learningCaptureStop","ERROR in handler",{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0}),console.error("[Olympus Learning Capture] Error in stop handler:",t)}return D("learningCaptureStop","Hook completed"),{continue:!0}}})}Ge();function tw(){P({name:"budgetWarning",event:"PostToolUse",priority:90,handler:e=>{if(!e.directory)return{continue:!0};try{let t=Q(e.directory,e.sessionId),n=0;if(e.toolOutput&&typeof e.toolOutput=="object"){let r=e.toolOutput;r.token_usage&&typeof r.token_usage=="object"&&(n=r.token_usage.total_tokens??0)}if(n>0&&gu(t,n),yu(t)){let r=t.token_budget,o=(r.current_usage/1e3).toFixed(1),s=(r.session_baseline/1e3).toFixed(0),i=(r.current_usage/r.session_baseline).toFixed(2);return hu(t),ee(e.directory,t),{continue:!0,message:`[TOKEN AWARENESS] Session at ${o}k tokens (${i}x baseline of ${s}k).
2009
+ `;let s=Ks.dirname(ew);Sr.existsSync(s)||Sr.mkdirSync(s,{recursive:!0}),Sr.appendFileSync(ew,o,"utf8")}catch(r){console.error("[Olympus Debug] Failed to write debug log:",r)}}function rl(e,t){ow&&D(e,"Context received",{directory:t.directory,sessionId:t.sessionId,hasPrompt:!!t.prompt,promptLength:t.prompt?.length||0,hasMessage:!!t.message,messageModel:t.message?.model,toolName:t.toolName,hasToolOutput:!!t.toolOutput,toolOutputType:t.toolOutput?typeof t.toolOutput:void 0,hasParts:!!t.parts,partsLength:t.parts?.length||0})}function Rx(e){return e.prompt?e.prompt:e.message?.content?e.message.content:e.parts?e.parts.filter(t=>t.type==="text"&&t.text).map(t=>t.text).join(" "):""}function tw(e){if(e.message?.model){let{providerId:t,modelId:n}=e.message.model;if(t&&n)return`${t}/${n}`;if(n)return n}}function nw(e,t=1e4){return e.token_budget?(e.token_budget.input_tokens===void 0&&(e.token_budget.input_tokens=0),e.token_budget.output_tokens===void 0&&(e.token_budget.output_tokens=0)):e.token_budget={session_baseline:t,current_usage:0,input_tokens:0,output_tokens:0,warning_threshold:1.5,warning_issued:!1,started_at:new Date().toISOString()},e}function sw(){P({name:"learningCapturePrompt",event:"UserPromptSubmit",priority:110,handler:async e=>{D("learningCapturePrompt","Hook fired"),rl("learningCapturePrompt",e);try{if(!e.directory)return D("learningCapturePrompt","No directory in context - skipping"),{continue:!0};D("learningCapturePrompt","Extracting prompt text");let t=Rx(e);if(!t)return D("learningCapturePrompt","No prompt text extracted - skipping"),{continue:!0};D("learningCapturePrompt",`Prompt text extracted (${t.length} chars)`),D("learningCapturePrompt","Estimating input tokens");let n=await Mn(t);D("learningCapturePrompt",`Estimated tokens: ${n}`),D("learningCapturePrompt","Loading session state",{directory:e.directory,sessionId:e.sessionId});let r=Q(e.directory,e.sessionId);D("learningCapturePrompt","Session state loaded",{hasTokenBudget:!!r.token_budget,currentUsage:r.token_budget?.current_usage,inputTokens:r.token_budget?.input_tokens,outputTokens:r.token_budget?.output_tokens}),nw(r),D("learningCapturePrompt","Token budget ensured");let o=tw(e);if(D("learningCapturePrompt",`Model identifier: ${o||"none"}`),o&&r.token_budget&&(r.token_budget.current_model=o,D("learningCapturePrompt",`Model set in token budget: ${o}`)),r.token_budget){let s=r.token_budget.input_tokens,i=r.token_budget.current_usage;r.token_budget.input_tokens+=n,r.token_budget.current_usage+=n,D("learningCapturePrompt","Tokens accumulated",{addedTokens:n,inputTokens:{before:s,after:r.token_budget.input_tokens},currentUsage:{before:i,after:r.token_budget.current_usage}}),D("learningCapturePrompt","Saving session state"),ee(e.directory,r),D("learningCapturePrompt","Session state saved successfully")}else D("learningCapturePrompt","WARNING: No token budget after ensure - this should not happen")}catch(t){D("learningCapturePrompt","ERROR in handler",{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0}),console.error("[Olympus Learning Capture] Error in prompt handler:",t)}return D("learningCapturePrompt","Hook completed"),{continue:!0}}}),P({name:"learningCaptureTool",event:"PostToolUse",priority:70,handler:async e=>{D("learningCaptureTool","Hook fired"),rl("learningCaptureTool",e);try{if(!e.directory||!e.toolName)return D("learningCaptureTool","Missing directory or toolName - skipping",{hasDirectory:!!e.directory,hasToolName:!!e.toolName}),{continue:!0};D("learningCaptureTool",`Processing tool: ${e.toolName}`),D("learningCaptureTool","Estimating output tokens from tool result");let t=e.toolOutput?await zy(e.toolOutput):0;D("learningCaptureTool",`Estimated output tokens: ${t}`),D("learningCaptureTool","Loading session state",{directory:e.directory,sessionId:e.sessionId});let n=Q(e.directory,e.sessionId);D("learningCaptureTool","Session state loaded",{hasTokenBudget:!!n.token_budget,currentUsage:n.token_budget?.current_usage,inputTokens:n.token_budget?.input_tokens,outputTokens:n.token_budget?.output_tokens}),nw(n),D("learningCaptureTool","Token budget ensured");let r=tw(e);if(D("learningCaptureTool",`Model identifier: ${r||"none"}`),r&&n.token_budget&&(n.token_budget.current_model=r,D("learningCaptureTool",`Model set in token budget: ${r}`)),n.token_budget){let o=n.token_budget.output_tokens,s=n.token_budget.current_usage;n.token_budget.output_tokens+=t,n.token_budget.current_usage+=t,D("learningCaptureTool","Tokens accumulated",{addedTokens:t,outputTokens:{before:o,after:n.token_budget.output_tokens},currentUsage:{before:s,after:n.token_budget.current_usage}}),D("learningCaptureTool","Saving session state"),ee(e.directory,n),D("learningCaptureTool","Session state saved successfully")}else D("learningCaptureTool","WARNING: No token budget after ensure - this should not happen")}catch(t){D("learningCaptureTool","ERROR in handler",{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0}),console.error("[Olympus Learning Capture] Error in tool use handler:",t)}return D("learningCaptureTool","Hook completed"),{continue:!0}}}),P({name:"learningCaptureStop",event:"Stop",priority:90,handler:async e=>{D("learningCaptureStop","Hook fired"),rl("learningCaptureStop",e);try{if(!e.directory)return D("learningCaptureStop","No directory in context - skipping"),{continue:!0};D("learningCaptureStop","Loading session state",{directory:e.directory,sessionId:e.sessionId});let t=Q(e.directory,e.sessionId);if(D("learningCaptureStop","Session state loaded",{hasTokenBudget:!!t.token_budget,currentUsage:t.token_budget?.current_usage,inputTokens:t.token_budget?.input_tokens,outputTokens:t.token_budget?.output_tokens,currentModel:t.token_budget?.current_model}),!t.token_budget)return D("learningCaptureStop","No token budget in session state - skipping (backward compatibility)"),{continue:!0};let n=t.token_budget.current_usage,r=t.token_budget.input_tokens||0,o=t.token_budget.output_tokens||0;if(D("learningCaptureStop","Token totals",{totalTokens:n,inputTokens:r,outputTokens:o}),n===0)return D("learningCaptureStop","No token usage recorded - skipping feedback entry creation"),{continue:!0};let s=t.token_budget.current_model||"unknown";D("learningCaptureStop",`Using model identifier: ${s}`),D("learningCaptureStop","Token usage object created",{input_tokens:r,output_tokens:o,total_tokens:n,estimated:!0,model:s}),D("learningCaptureStop","Calculating cost estimate");let a={input_cost:0,output_cost:0,total_cost:0,pricing_version:"2025-01-01"};try{let l=Qy(r,o,s);a.input_cost=l.inputCost,a.output_cost=l.outputCost,a.total_cost=l.totalCost,a.pricing_version=l.pricingVersion,D("learningCaptureStop","Cost calculated successfully",{inputCost:l.inputCost,outputCost:l.outputCost,totalCost:l.totalCost})}catch(l){D("learningCaptureStop","Cost calculation failed (not critical)",{error:l instanceof Error?l.message:String(l)})}let c={session_id:t.session_id,project_path:e.directory,started_at:t.token_budget.started_at,ended_at:new Date().toISOString(),duration_seconds:Math.round((Date.now()-new Date(t.token_budget.started_at).getTime())/1e3),agents_used:t.token_budget.agents_used||[],total_input_tokens:r,total_output_tokens:o,total_tokens:n,estimated_cost:a.total_cost,model:s,outcome:"success"};D("learningCaptureStop","Session summary created",{sessionId:c.session_id,duration:c.duration_seconds,agentsUsed:c.agents_used,totalTokens:c.total_tokens,cost:c.estimated_cost});try{uu(c),D("learningCaptureStop","Session summary saved successfully")}catch(l){D("learningCaptureStop","Failed to save session summary (non-critical)",{error:l instanceof Error?l.message:String(l)})}try{let{formatSessionSummaryLine:l}=await Promise.resolve().then(()=>(Zy(),Xy)),u=l(c);console.error(u)}catch{}D("learningCaptureStop","Resetting token budget for next session"),t.token_budget.current_usage=0,t.token_budget.input_tokens=0,t.token_budget.output_tokens=0,t.token_budget.warning_issued=!1,t.token_budget.started_at=new Date().toISOString(),delete t.token_budget.current_model,delete t.token_budget.agents_used,D("learningCaptureStop","Saving reset session state"),ee(e.directory,t),D("learningCaptureStop","Session state saved successfully")}catch(t){D("learningCaptureStop","ERROR in handler",{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0}),console.error("[Olympus Learning Capture] Error in stop handler:",t)}return D("learningCaptureStop","Hook completed"),{continue:!0}}})}Be();function iw(){P({name:"budgetWarning",event:"PostToolUse",priority:90,handler:e=>{if(!e.directory)return{continue:!0};try{let t=Q(e.directory,e.sessionId),n=0;if(e.toolOutput&&typeof e.toolOutput=="object"){let r=e.toolOutput;r.token_usage&&typeof r.token_usage=="object"&&(n=r.token_usage.total_tokens??0)}if(n>0&&_u(t,n),Su(t)){let r=t.token_budget,o=(r.current_usage/1e3).toFixed(1),s=(r.session_baseline/1e3).toFixed(0),i=(r.current_usage/r.session_baseline).toFixed(2);return ku(t),ee(e.directory,t),{continue:!0,message:`[TOKEN AWARENESS] Session at ${o}k tokens (${i}x baseline of ${s}k).
2010
2010
  This is informational - continue if task requires it.
2011
- Consider: delegate to subagent, break into smaller tasks.`}}return ee(e.directory,t),{continue:!0}}catch(t){return console.error("[Olympus Learning] Budget warning error:",t),{continue:!0}}}})}Ge();me();Z();Yo();Gt();var vr=T(require("fs"),1),yo=T(require("path"),1),lw=T(require("os"),1),kx=process.env.OLYMPUS_DEBUG_HOOKS==="1",cw=yo.join(lw.homedir(),".claude","olympus","learning","hooks-debug.log");function B(e,t,n){if(kx)try{let o=`[${new Date().toISOString()}] [${e}] ${t}`;n!==void 0&&(typeof n=="object"?o+=`
2011
+ Consider: delegate to subagent, break into smaller tasks.`}}return ee(e.directory,t),{continue:!0}}catch(t){return console.error("[Olympus Learning] Budget warning error:",t),{continue:!0}}}})}Be();le();Z();Qo();Ut();var vr=b(require("fs"),1),yo=b(require("path"),1),mw=b(require("os"),1),$x=process.env.OLYMPUS_DEBUG_HOOKS==="1",fw=yo.join(mw.homedir(),".claude","olympus","learning","hooks-debug.log");function B(e,t,n){if($x)try{let o=`[${new Date().toISOString()}] [${e}] ${t}`;n!==void 0&&(typeof n=="object"?o+=`
2012
2012
  ${JSON.stringify(n,null,2)}`:o+=` ${n}`),o+=`
2013
- `;let s=yo.dirname(cw);vr.existsSync(s)||vr.mkdirSync(s,{recursive:!0}),vr.appendFileSync(cw,o,"utf8")}catch(r){console.error("[Olympus Debug] Failed to write debug log:",r)}}async function _x(e,t){try{let n=e.includes("executing a coding task as part of a structured workflow"),r=e.match(/BOLT-(\d+)/i);if(!n&&!r)return null;let o=await oe(t);if(o.length===0)return null;let s=await I(t,o[0]);return s?s.active_code_plan_path?{boltId:s.active_code_plan_path,workflowId:s.workflow_id}:r&&n?{boltId:`BOLT-${r[1].padStart(3,"0")}`,workflowId:s.workflow_id}:null:null}catch(n){return B("agentTracking","Error detecting BOLT execution",{error:n instanceof Error?n.message:String(n)}),null}}function uw(){P({name:"agentTracking",event:"PreToolUse",priority:50,handler:async e=>{B("agentTracking","Hook fired"),B("agentTracking","Context received",{directory:e.directory,sessionId:e.sessionId,toolName:e.toolName,hasToolInput:!!e.toolInput});let t=null;try{if(e.toolName!=="Task")return B("agentTracking",`Skipping non-Task tool: ${e.toolName}`),{continue:!0};if(B("agentTracking","Task tool detected - processing"),!e.directory)return B("agentTracking","No directory in context - skipping"),{continue:!0};if(!e.sessionId)return B("agentTracking","No sessionId in context - skipping"),{continue:!0};if(!e.toolInput)return B("agentTracking","No toolInput in context - skipping"),{continue:!0};let n=e.toolInput,r=n.subagent_type,o=n.prompt;if(B("agentTracking","Tool input extracted",{subagentType:r,hasPrompt:!!o,promptLength:typeof o=="string"?o.length:0}),!r||typeof r!="string")return B("agentTracking","Missing or invalid subagent_type - skipping"),{continue:!0};if(!o||typeof o!="string")return B("agentTracking","Missing or invalid prompt - skipping"),{continue:!0};B("agentTracking","Loading session state",{directory:e.directory,sessionId:e.sessionId});let s=Q(e.directory,e.sessionId);B("agentTracking","Session state loaded",{sessionId:s.session_id,hasPendingCompletion:!!s.pending_completion});try{let{getRoutingRecommendation:a}=await Promise.resolve().then(()=>(aw(),iw));t=a(r,o),t&&B("agentTracking","Routing recommendation generated",{recommendation:t})}catch{}let i=await _x(o,e.directory);if(B("agentTracking","BOLT detection result",{isBoltExecution:!!i,boltId:i?.boltId,workflowId:i?.workflowId}),B("agentTracking","Marking completion claim",{agent:r,taskLength:o.length,hasBoltMetadata:!!i}),pu(s,o,r),i&&s.pending_completion){s.pending_completion.bolt_id=i.boltId,s.pending_completion.workflow_id=i.workflowId,B("agentTracking","BOLT metadata added to pending_completion",{bolt_id:i.boltId,workflow_id:i.workflowId});try{let a=await oe(e.directory),c=null;for(let l of a){let u=await I(e.directory,l);if(u&&u.status!=="complete"&&u.status!=="archived"&&u.status!=="deferred"){c=l;break}}if(!c)B("agentTracking","No active workflow found for manifest update");else{let l=yo.join(e.directory,"aidlc-docs",c,"manifest.json"),u=W(l);if(u){let d=u.artifacts.find(p=>p.id===i.boltId);d&&(d.executedBy=r,H(l,u),B("agentTracking","Set executedBy on BOLT artifact",{boltId:i.boltId,executedBy:r}))}}}catch(a){B("agentTracking","Error setting executedBy on manifest",{error:a instanceof Error?a.message:String(a)})}}B("agentTracking","Completion claim marked",{claimedAt:s.pending_completion?.claimed_at,agentUsed:s.pending_completion?.agent_used,bolt_id:s.pending_completion?.bolt_id,workflow_id:s.pending_completion?.workflow_id}),s.token_budget&&(s.token_budget.agents_used||(s.token_budget.agents_used=[]),s.token_budget.agents_used.includes(r)||s.token_budget.agents_used.push(r),B("agentTracking","Agents accumulated",{agents_used:s.token_budget.agents_used})),B("agentTracking","Saving session state"),ee(e.directory,s),B("agentTracking","Session state saved successfully")}catch(n){B("agentTracking","ERROR in handler",{error:n instanceof Error?n.message:String(n),stack:n instanceof Error?n.stack:void 0}),console.error("[Olympus Agent Tracking] Error in handler:",n)}return B("agentTracking","Hook completed"),t?{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:t}}:{continue:!0}}}),P({name:"agentTrackingBoltCompletion",event:"PostToolUse",priority:51,handler:async e=>{B("agentTrackingBoltCompletion","Hook fired");try{if(e.toolName!=="Task")return B("agentTrackingBoltCompletion",`Skipping non-Task tool: ${e.toolName}`),{continue:!0};if(!e.directory||!e.sessionId)return B("agentTrackingBoltCompletion","Missing directory or sessionId - skipping"),{continue:!0};let t=Q(e.directory,e.sessionId);if(B("agentTrackingBoltCompletion","Session state loaded",{hasPendingCompletion:!!t.pending_completion,bolt_id:t.pending_completion?.bolt_id}),!t.pending_completion||!t.pending_completion.bolt_id)return B("agentTrackingBoltCompletion","No BOLT execution detected - skipping"),{continue:!0};let{bolt_id:n,workflow_id:r,agent_used:o,task_description:s}=t.pending_completion;if(!o)return B("agentTrackingBoltCompletion","No agent_used in pending_completion - skipping"),{continue:!0};B("agentTrackingBoltCompletion","Recording BOLT execution",{boltId:n,agentName:o,workflowId:r}),cf({boltId:n,agentName:o,success:!0,sessionId:e.sessionId,projectPath:e.directory,taskDescription:s}),B("agentTrackingBoltCompletion","BOLT execution recorded successfully");try{let i={type:"bolt_execution_complete",phase:"construction",stage:"code-generation",details:`BOLT ${n} executed by ${o}`,artifactId:n,agentName:o},a={workflowId:r||"unknown",featureName:r||"unknown",projectPath:e.directory,sessionId:e.sessionId,phase:"construction"},c=Ve(i,a);le(c),B("agentTrackingBoltCompletion","BOLT completion discovery recorded",{boltId:n,discoveryId:c.id})}catch(i){console.error("[Olympus Agent Tracking] Failed to capture BOLT completion discovery:",i),B("agentTrackingBoltCompletion","Failed to capture BOLT completion discovery",{error:i instanceof Error?i.message:String(i)})}}catch(t){B("agentTrackingBoltCompletion","ERROR in handler",{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0}),console.error("[Olympus Agent Tracking BOLT Completion] Error in handler:",t)}return B("agentTrackingBoltCompletion","Hook completed"),{continue:!0}}})}Ge();var tl=require("path"),dw=require("os");we();var Sx={enabled:!0,minConfidence:.6,maxPerSession:5,maxPerDay:20,deduplicationWindowDays:7};function Tr(e){let t=(0,tl.join)((0,dw.homedir)(),".claude","olympus","config.json"),n=ke(t,{}),r={};if(e){let s=(0,tl.join)(e,".olympus","config.json");r=ke(s,{})}let o={...Sx,...n.autoDiscovery||{},...r.autoDiscovery||{}};return o.minConfidence=Math.max(0,Math.min(1,o.minConfidence)),o.maxPerSession=Math.max(1,Math.min(50,o.maxPerSession)),o.maxPerDay=Math.max(1,Math.min(200,o.maxPerDay)),o.deduplicationWindowDays=Math.max(1,Math.min(90,o.deduplicationWindowDays)),o}var Ys=require("fs"),pw=require("path");we();var vx={praise:.85,problem_solved:.7,topic_change:.6},Tx=[{pattern:/\bworkaround\b/i,category:"workaround"},{pattern:/\bgotcha\b/i,category:"gotcha"},{pattern:/\bperformance\b/i,category:"performance"},{pattern:/\bperformant\b/i,category:"performance"},{pattern:/\bslow\b/i,category:"performance"},{pattern:/\boptimiz/i,category:"performance"},{pattern:/\bdependenc/i,category:"dependency"},{pattern:/\bpackage\b/i,category:"dependency"},{pattern:/\bpeer\s+dep/i,category:"dependency"},{pattern:/\bconfig/i,category:"configuration"},{pattern:/\benvironment\s+variable/i,category:"configuration"},{pattern:/\benv\b/i,category:"configuration"},{pattern:/\bpattern\b/i,category:"pattern"},{pattern:/\bconvention\b/i,category:"pattern"}];function fw(e,t){if(!e.pending_completion?.task_description)return null;let n=e.pending_completion.task_description,r=e.pending_completion.agent_used||"unknown",o=xx(n),s=Px(n),i=Ex(n,r),a=vx[t]??.6;return{session_id:e.session_id,category:i,summary:o,details:s,agent_name:r,task_context:n.substring(0,200),confidence:a,scope:"project"}}function mw(e,t,n=7){let r=Ix(t,n);if(r.length===0)return!1;let o=e.summary||"",s=e.details||"";for(let i of r)if(i.details===s&&s.length>0||o.length>0&&i.summary&&bx(o,i.summary)>.7)return!0;return!1}function Ex(e,t){for(let{pattern:n,category:r}of Tx)if(n.test(e))return r;return"technical_insight"}function bx(e,t){let n=a=>new Set(a.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter(c=>c.length>3)),r=n(e),o=n(t);if(r.size===0&&o.size===0)return 1;if(r.size===0||o.size===0)return 0;let s=new Set([...r].filter(a=>o.has(a))),i=new Set([...r,...o]);return i.size>0?s.size/i.size:0}function Er(e,t){if(e.length<=t)return e;let n=e.substring(0,t),r=n.lastIndexOf(" ");return r>t*.5?n.substring(0,r)+"...":n+"..."}function Cx(e,t=100){if(!e||e.length===0)return"";let n=e.match(/^[^.]+\./),r=e.indexOf(`
2014
- `),o=e.length;n&&n[0].length<=t&&(o=Math.min(o,n[0].length)),r>0&&r<=t&&(o=Math.min(o,r)),o=Math.min(o,t);let s=e.substring(0,o).trim();return s.length<e.length&&!s.endsWith(".")?Er(s,t):s}function Rx(e){let t=e.replace(/`[^`]*[\\\/][^`]*`/g,"");return t=t.replace(/[A-Z]:[\\\/][\w\\\/.@-]+/gi,""),t=t.replace(/\/[\w-]+(?:\/[\w\/.@-]+)+/g,""),t=t.replace(/\s+/g," ").trim(),t}function xx(e){if(!e||e.length===0)return"Completed task";let t={Create:"Created",Fix:"Fixed",Update:"Updated",Add:"Added",Implement:"Implemented",Build:"Built",Write:"Wrote",Configure:"Configured","Set up":"Set up",Setup:"Set up",Install:"Installed",Remove:"Removed",Delete:"Deleted",Refactor:"Refactored",Test:"Tested",Debug:"Debugged",Deploy:"Deployed",Migrate:"Migrated",VERIFY:"Verified",Verify:"Verified",Analyze:"Analyzed",Review:"Reviewed",Explore:"Explored",Investigate:"Investigated"},n=Rx(e),r=Cx(n,150);for(let[s,i]of Object.entries(t)){let a=new RegExp(`^${s}\\b`,"i");if(a.test(r)){let c=r.replace(a,i);return Er(c.trim(),100)}}let o=n.match(/^In the .+? project,\s*(.+)/i);if(o){let s=o[1].trim();if(s.toLowerCase().startsWith("i need to")){let i=s.replace(/^i need to\s+/i,"");return Er(i.charAt(0).toUpperCase()+i.slice(1),100)}return Er(s,100)}return Er(r,100)}function Px(e){if(!e||e.length===0)return"";let t=e;t=t.replace(/```[\s\S]*?```/g,"[code block]"),t=t.replace(/`[^`]+`/g,"");let n=t.match(/^(.*?)(?=\n##|\n\n##|$)/s);n&&(t=n[1].trim());let r=t.match(/^\d+\.\s+(.+)/gm);return r&&r.length>0&&(t=r.slice(0,3).map(i=>i.replace(/^\d+\.\s+/,"").trim()).join("; ")),t=t.split(/\n\n/)[0]||t,t=t.replace(/\s+/g," ").trim(),t.length>500?Er(t,500):t}function Ix(e,t){let n=kt(e),r=(0,pw.join)(n,"discoveries.jsonl");if(!(0,Ys.existsSync)(r))return[];try{let o=(0,Ys.readFileSync)(r,"utf-8"),s=new Date(Date.now()-t*24*60*60*1e3);return o.split(`
2015
- `).filter(i=>i.trim()).map(i=>{try{return JSON.parse(i)}catch{return null}}).filter(i=>i?new Date(i.timestamp)>=s:!1)}catch{return[]}}Gt();function gw(){P({name:"discoveryCapture",event:"Stop",priority:92,handler:async e=>{try{if(!e.directory)return{continue:!0};let t=Tr(e.directory);if(!t.enabled)return{continue:!0};let n=Q(e.directory,e.sessionId);if(ku(n,t))return{continue:!0};if(!xo(n))return{continue:!0};let r=Ax(n);if(!r)return{continue:!0};let o=fw(n,r);if(!o)return{continue:!0};if((o.confidence||0)<t.minConfidence)return{continue:!0};if(mw(o,e.directory,t.deduplicationWindowDays))return{continue:!0};le({...o,project_path:e.directory,session_id:n.session_id,category:o.category||"technical_insight",summary:o.summary||"",details:o.details||"",agent_name:o.agent_name||"unknown",confidence:o.confidence||.6,scope:"project"}),wu(n),ee(e.directory,n)}catch(t){console.error("[Olympus Discovery Capture] Error:",t)}return{continue:!0}}})}function Ax(e){let t=e.recent_prompts||[];if(t.length===0)return null;let n=t[0];return n?.detected_feedback==="praise"?"praise":n?.prompt&&e.pending_completion?.task_description&&Ox(n.prompt,e.pending_completion.task_description)<.2?"topic_change":null}function Ox(e,t){let n=a=>new Set(a.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter(c=>c.length>3)),r=n(e),o=n(t);if(r.size===0&&o.size===0)return 1;if(r.size===0||o.size===0)return 0;let s=new Set([...r].filter(a=>o.has(a))),i=new Set([...r,...o]);return i.size>0?s.size/i.size:0}Ge();var br=require("fs"),ww=require("path"),hw=new Map;function kw(e,t,n){try{if(!(0,br.existsSync)(t))return null;let r=(0,ww.relative)(e,t),o=(0,br.readFileSync)(t,"utf-8"),i=(0,br.statSync)(t).mtimeMs,a=hw.get(t),c=a===void 0;if(hw.set(t,i),!c&&a===i)return null;let l=$x(o);if(c)return{event_type:"plan_created",plan_path:r,plan_summary:l,revision_count:0,session_id:n,timestamp:new Date().toISOString()};let u=Nx(t);return{event_type:"plan_revised",plan_path:r,plan_summary:l,revision_count:u,session_id:n,timestamp:new Date().toISOString()}}catch{return null}}function _w(e){let t=typeof e=="string"?e:String(e||"");if(!t)return{passed:!1,issues:["Empty review output"]};let n=t.toUpperCase(),o=["APPROVED","LOOKS GOOD","NO CRITICAL ISSUES","PLAN IS SOLID"].some(c=>n.includes(c)),i=["CRITICAL","REVISE","REJECT","MAJOR ISSUE","MISSING","INCOMPLETE"].some(c=>n.includes(c)),a=Dx(t);return o&&!i?{passed:!0,issues:a}:i?{passed:!1,issues:a.length>0?a:["Plan requires revision"]}:{passed:!0,issues:a}}function nl(e,t,n){let r=e.plan_path.split("/").pop()||e.plan_path,o=t.length,s=e.event_type==="plan_review_failed"?`Plan '${r}' failed review: ${o} issue${o!==1?"s":""}`:`Plan '${r}' failed: ${o} issue${o!==1?"s":""}`,i=t.map(c=>`- ${c}`).join(`
2013
+ `;let s=yo.dirname(fw);vr.existsSync(s)||vr.mkdirSync(s,{recursive:!0}),vr.appendFileSync(fw,o,"utf8")}catch(r){console.error("[Olympus Debug] Failed to write debug log:",r)}}async function Dx(e,t){try{let n=e.includes("executing a coding task as part of a structured workflow"),r=e.match(/BOLT-(\d+)/i);if(!n&&!r)return null;let o=await oe(t);if(o.length===0)return null;let s=await I(t,o[0]);return s?s.active_code_plan_path?{boltId:s.active_code_plan_path,workflowId:s.workflow_id}:r&&n?{boltId:`BOLT-${r[1].padStart(3,"0")}`,workflowId:s.workflow_id}:null:null}catch(n){return B("agentTracking","Error detecting BOLT execution",{error:n instanceof Error?n.message:String(n)}),null}}function gw(){P({name:"agentTracking",event:"PreToolUse",priority:50,handler:async e=>{B("agentTracking","Hook fired"),B("agentTracking","Context received",{directory:e.directory,sessionId:e.sessionId,toolName:e.toolName,hasToolInput:!!e.toolInput});let t=null;try{if(e.toolName!=="Task")return B("agentTracking",`Skipping non-Task tool: ${e.toolName}`),{continue:!0};if(B("agentTracking","Task tool detected - processing"),!e.directory)return B("agentTracking","No directory in context - skipping"),{continue:!0};if(!e.sessionId)return B("agentTracking","No sessionId in context - skipping"),{continue:!0};if(!e.toolInput)return B("agentTracking","No toolInput in context - skipping"),{continue:!0};let n=e.toolInput,r=n.subagent_type,o=n.prompt;if(B("agentTracking","Tool input extracted",{subagentType:r,hasPrompt:!!o,promptLength:typeof o=="string"?o.length:0}),!r||typeof r!="string")return B("agentTracking","Missing or invalid subagent_type - skipping"),{continue:!0};if(!o||typeof o!="string")return B("agentTracking","Missing or invalid prompt - skipping"),{continue:!0};B("agentTracking","Loading session state",{directory:e.directory,sessionId:e.sessionId});let s=Q(e.directory,e.sessionId);B("agentTracking","Session state loaded",{sessionId:s.session_id,hasPendingCompletion:!!s.pending_completion});try{let{getRoutingRecommendation:a}=await Promise.resolve().then(()=>(pw(),dw));t=a(r,o),t&&B("agentTracking","Routing recommendation generated",{recommendation:t})}catch{}let i=await Dx(o,e.directory);if(B("agentTracking","BOLT detection result",{isBoltExecution:!!i,boltId:i?.boltId,workflowId:i?.workflowId}),B("agentTracking","Marking completion claim",{agent:r,taskLength:o.length,hasBoltMetadata:!!i}),hu(s,o,r),i&&s.pending_completion){s.pending_completion.bolt_id=i.boltId,s.pending_completion.workflow_id=i.workflowId,B("agentTracking","BOLT metadata added to pending_completion",{bolt_id:i.boltId,workflow_id:i.workflowId});try{let a=await oe(e.directory),c=null;for(let l of a){let u=await I(e.directory,l);if(u&&u.status!=="complete"&&u.status!=="archived"&&u.status!=="deferred"){c=l;break}}if(!c)B("agentTracking","No active workflow found for manifest update");else{let l=yo.join(e.directory,"aidlc-docs",c,"manifest.json"),u=W(l);if(u){let d=u.artifacts.find(p=>p.id===i.boltId);d&&(d.executedBy=r,G(l,u),B("agentTracking","Set executedBy on BOLT artifact",{boltId:i.boltId,executedBy:r}))}}}catch(a){B("agentTracking","Error setting executedBy on manifest",{error:a instanceof Error?a.message:String(a)})}}B("agentTracking","Completion claim marked",{claimedAt:s.pending_completion?.claimed_at,agentUsed:s.pending_completion?.agent_used,bolt_id:s.pending_completion?.bolt_id,workflow_id:s.pending_completion?.workflow_id}),s.token_budget&&(s.token_budget.agents_used||(s.token_budget.agents_used=[]),s.token_budget.agents_used.includes(r)||s.token_budget.agents_used.push(r),B("agentTracking","Agents accumulated",{agents_used:s.token_budget.agents_used})),B("agentTracking","Saving session state"),ee(e.directory,s),B("agentTracking","Session state saved successfully")}catch(n){B("agentTracking","ERROR in handler",{error:n instanceof Error?n.message:String(n),stack:n instanceof Error?n.stack:void 0}),console.error("[Olympus Agent Tracking] Error in handler:",n)}return B("agentTracking","Hook completed"),t?{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:t}}:{continue:!0}}}),P({name:"agentTrackingBoltCompletion",event:"PostToolUse",priority:51,handler:async e=>{B("agentTrackingBoltCompletion","Hook fired");try{if(e.toolName!=="Task")return B("agentTrackingBoltCompletion",`Skipping non-Task tool: ${e.toolName}`),{continue:!0};if(!e.directory||!e.sessionId)return B("agentTrackingBoltCompletion","Missing directory or sessionId - skipping"),{continue:!0};let t=Q(e.directory,e.sessionId);if(B("agentTrackingBoltCompletion","Session state loaded",{hasPendingCompletion:!!t.pending_completion,bolt_id:t.pending_completion?.bolt_id}),!t.pending_completion||!t.pending_completion.bolt_id)return B("agentTrackingBoltCompletion","No BOLT execution detected - skipping"),{continue:!0};let{bolt_id:n,workflow_id:r,agent_used:o,task_description:s}=t.pending_completion;if(!o)return B("agentTrackingBoltCompletion","No agent_used in pending_completion - skipping"),{continue:!0};B("agentTrackingBoltCompletion","Recording BOLT execution",{boltId:n,agentName:o,workflowId:r}),Rf({boltId:n,agentName:o,success:!0,sessionId:e.sessionId,projectPath:e.directory,taskDescription:s}),B("agentTrackingBoltCompletion","BOLT execution recorded successfully");try{let i={type:"bolt_execution_complete",phase:"construction",stage:"code-generation",details:`BOLT ${n} executed by ${o}`,artifactId:n,agentName:o},a={workflowId:r||"unknown",featureName:r||"unknown",projectPath:e.directory,sessionId:e.sessionId,phase:"construction"},c=qe(i,a);ue(c),B("agentTrackingBoltCompletion","BOLT completion discovery recorded",{boltId:n,discoveryId:c.id})}catch(i){console.error("[Olympus Agent Tracking] Failed to capture BOLT completion discovery:",i),B("agentTrackingBoltCompletion","Failed to capture BOLT completion discovery",{error:i instanceof Error?i.message:String(i)})}}catch(t){B("agentTrackingBoltCompletion","ERROR in handler",{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0}),console.error("[Olympus Agent Tracking BOLT Completion] Error in handler:",t)}return B("agentTrackingBoltCompletion","Hook completed"),{continue:!0}}})}Be();var sl=require("path"),hw=require("os");we();var Nx={enabled:!0,minConfidence:.6,maxPerSession:5,maxPerDay:20,deduplicationWindowDays:7};function br(e){let t=(0,sl.join)((0,hw.homedir)(),".claude","olympus","config.json"),n=_e(t,{}),r={};if(e){let s=(0,sl.join)(e,".olympus","config.json");r=_e(s,{})}let o={...Nx,...n.autoDiscovery||{},...r.autoDiscovery||{}};return o.minConfidence=Math.max(0,Math.min(1,o.minConfidence)),o.maxPerSession=Math.max(1,Math.min(50,o.maxPerSession)),o.maxPerDay=Math.max(1,Math.min(200,o.maxPerDay)),o.deduplicationWindowDays=Math.max(1,Math.min(90,o.deduplicationWindowDays)),o}var Js=require("fs"),yw=require("path");we();var Fx={praise:.85,problem_solved:.7,topic_change:.6},jx=[{pattern:/\bworkaround\b/i,category:"workaround"},{pattern:/\bgotcha\b/i,category:"gotcha"},{pattern:/\bperformance\b/i,category:"performance"},{pattern:/\bperformant\b/i,category:"performance"},{pattern:/\bslow\b/i,category:"performance"},{pattern:/\boptimiz/i,category:"performance"},{pattern:/\bdependenc/i,category:"dependency"},{pattern:/\bpackage\b/i,category:"dependency"},{pattern:/\bpeer\s+dep/i,category:"dependency"},{pattern:/\bconfig/i,category:"configuration"},{pattern:/\benvironment\s+variable/i,category:"configuration"},{pattern:/\benv\b/i,category:"configuration"},{pattern:/\bpattern\b/i,category:"pattern"},{pattern:/\bconvention\b/i,category:"pattern"}];function ww(e,t){if(!e.pending_completion?.task_description)return null;let n=e.pending_completion.task_description,r=e.pending_completion.agent_used||"unknown",o=Bx(n),s=Gx(n),i=Mx(n,r),a=Fx[t]??.6;return{session_id:e.session_id,category:i,summary:o,details:s,agent_name:r,task_context:n.substring(0,200),confidence:a,scope:"project"}}function _w(e,t,n=7){let r=Hx(t,n);if(r.length===0)return!1;let o=e.summary||"",s=e.details||"";for(let i of r)if(i.details===s&&s.length>0||o.length>0&&i.summary&&Lx(o,i.summary)>.7)return!0;return!1}function Mx(e,t){for(let{pattern:n,category:r}of jx)if(n.test(e))return r;return"technical_insight"}function Lx(e,t){let n=a=>new Set(a.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter(c=>c.length>3)),r=n(e),o=n(t);if(r.size===0&&o.size===0)return 1;if(r.size===0||o.size===0)return 0;let s=new Set([...r].filter(a=>o.has(a))),i=new Set([...r,...o]);return i.size>0?s.size/i.size:0}function Tr(e,t){if(e.length<=t)return e;let n=e.substring(0,t),r=n.lastIndexOf(" ");return r>t*.5?n.substring(0,r)+"...":n+"..."}function Ux(e,t=100){if(!e||e.length===0)return"";let n=e.match(/^[^.]+\./),r=e.indexOf(`
2014
+ `),o=e.length;n&&n[0].length<=t&&(o=Math.min(o,n[0].length)),r>0&&r<=t&&(o=Math.min(o,r)),o=Math.min(o,t);let s=e.substring(0,o).trim();return s.length<e.length&&!s.endsWith(".")?Tr(s,t):s}function Wx(e){let t=e.replace(/`[^`]*[\\\/][^`]*`/g,"");return t=t.replace(/[A-Z]:[\\\/][\w\\\/.@-]+/gi,""),t=t.replace(/\/[\w-]+(?:\/[\w\/.@-]+)+/g,""),t=t.replace(/\s+/g," ").trim(),t}function Bx(e){if(!e||e.length===0)return"Completed task";let t={Create:"Created",Fix:"Fixed",Update:"Updated",Add:"Added",Implement:"Implemented",Build:"Built",Write:"Wrote",Configure:"Configured","Set up":"Set up",Setup:"Set up",Install:"Installed",Remove:"Removed",Delete:"Deleted",Refactor:"Refactored",Test:"Tested",Debug:"Debugged",Deploy:"Deployed",Migrate:"Migrated",VERIFY:"Verified",Verify:"Verified",Analyze:"Analyzed",Review:"Reviewed",Explore:"Explored",Investigate:"Investigated"},n=Wx(e),r=Ux(n,150);for(let[s,i]of Object.entries(t)){let a=new RegExp(`^${s}\\b`,"i");if(a.test(r)){let c=r.replace(a,i);return Tr(c.trim(),100)}}let o=n.match(/^In the .+? project,\s*(.+)/i);if(o){let s=o[1].trim();if(s.toLowerCase().startsWith("i need to")){let i=s.replace(/^i need to\s+/i,"");return Tr(i.charAt(0).toUpperCase()+i.slice(1),100)}return Tr(s,100)}return Tr(r,100)}function Gx(e){if(!e||e.length===0)return"";let t=e;t=t.replace(/```[\s\S]*?```/g,"[code block]"),t=t.replace(/`[^`]+`/g,"");let n=t.match(/^(.*?)(?=\n##|\n\n##|$)/s);n&&(t=n[1].trim());let r=t.match(/^\d+\.\s+(.+)/gm);return r&&r.length>0&&(t=r.slice(0,3).map(i=>i.replace(/^\d+\.\s+/,"").trim()).join("; ")),t=t.split(/\n\n/)[0]||t,t=t.replace(/\s+/g," ").trim(),t.length>500?Tr(t,500):t}function Hx(e,t){let n=_t(e),r=(0,yw.join)(n,"discoveries.jsonl");if(!(0,Js.existsSync)(r))return[];try{let o=(0,Js.readFileSync)(r,"utf-8"),s=new Date(Date.now()-t*24*60*60*1e3);return o.split(`
2015
+ `).filter(i=>i.trim()).map(i=>{try{return JSON.parse(i)}catch{return null}}).filter(i=>i?new Date(i.timestamp)>=s:!1)}catch{return[]}}Ut();function kw(){P({name:"discoveryCapture",event:"Stop",priority:92,handler:async e=>{try{if(!e.directory)return{continue:!0};let t=br(e.directory);if(!t.enabled)return{continue:!0};let n=Q(e.directory,e.sessionId);if(bu(n,t))return{continue:!0};if(!xo(n))return{continue:!0};let r=Vx(n);if(!r)return{continue:!0};let o=ww(n,r);if(!o)return{continue:!0};if((o.confidence||0)<t.minConfidence)return{continue:!0};if(_w(o,e.directory,t.deduplicationWindowDays))return{continue:!0};ue({...o,project_path:e.directory,session_id:n.session_id,category:o.category||"technical_insight",summary:o.summary||"",details:o.details||"",agent_name:o.agent_name||"unknown",confidence:o.confidence||.6,scope:"project"}),vu(n),ee(e.directory,n)}catch(t){console.error("[Olympus Discovery Capture] Error:",t)}return{continue:!0}}})}function Vx(e){let t=e.recent_prompts||[];if(t.length===0)return null;let n=t[0];return n?.detected_feedback==="praise"?"praise":n?.prompt&&e.pending_completion?.task_description&&qx(n.prompt,e.pending_completion.task_description)<.2?"topic_change":null}function qx(e,t){let n=a=>new Set(a.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter(c=>c.length>3)),r=n(e),o=n(t);if(r.size===0&&o.size===0)return 1;if(r.size===0||o.size===0)return 0;let s=new Set([...r].filter(a=>o.has(a))),i=new Set([...r,...o]);return i.size>0?s.size/i.size:0}Be();var Er=require("fs"),bw=require("path"),Sw=new Map;function Tw(e,t,n){try{if(!(0,Er.existsSync)(t))return null;let r=(0,bw.relative)(e,t),o=(0,Er.readFileSync)(t,"utf-8"),i=(0,Er.statSync)(t).mtimeMs,a=Sw.get(t),c=a===void 0;if(Sw.set(t,i),!c&&a===i)return null;let l=Yx(o);if(c)return{event_type:"plan_created",plan_path:r,plan_summary:l,revision_count:0,session_id:n,timestamp:new Date().toISOString()};let u=Jx(t);return{event_type:"plan_revised",plan_path:r,plan_summary:l,revision_count:u,session_id:n,timestamp:new Date().toISOString()}}catch{return null}}function Ew(e){let t=typeof e=="string"?e:String(e||"");if(!t)return{passed:!1,issues:["Empty review output"]};let n=t.toUpperCase(),o=["APPROVED","LOOKS GOOD","NO CRITICAL ISSUES","PLAN IS SOLID"].some(c=>n.includes(c)),i=["CRITICAL","REVISE","REJECT","MAJOR ISSUE","MISSING","INCOMPLETE"].some(c=>n.includes(c)),a=Kx(t);return o&&!i?{passed:!0,issues:a}:i?{passed:!1,issues:a.length>0?a:["Plan requires revision"]}:{passed:!0,issues:a}}function il(e,t,n){let r=e.plan_path.split("/").pop()||e.plan_path,o=t.length,s=e.event_type==="plan_review_failed"?`Plan '${r}' failed review: ${o} issue${o!==1?"s":""}`:`Plan '${r}' failed: ${o} issue${o!==1?"s":""}`,i=t.map(c=>`- ${c}`).join(`
2016
2016
  `).substring(0,500),a=[e.reviewer?`Issues found by ${e.reviewer}:`:"Issues:",i].join(`
2017
- `);return{session_id:e.session_id,project_path:n,category:"planning_insight",summary:s,details:a,agent_name:"prometheus",task_context:`Plan lifecycle: ${e.event_type}`,files_involved:[e.plan_path],confidence:.9,scope:"project"}}function Sw(e){if(e.length===0)return"";let t=["<plan-learnings>","## Planning Insights (from previous sessions)",""],n=[],r=[];for(let s of e.slice(0,5))s.summary.includes("failed")?n.push(`- ${s.summary}`):r.push(`- ${s.summary}`);n.length>0&&(t.push("**Common Planning Mistakes:**"),t.push(...n),t.push("")),r.length>0&&(t.push("**Required Considerations:**"),t.push(...r),t.push("")),t.push("</plan-learnings>");let o=t.join(`
2017
+ `);return{session_id:e.session_id,project_path:n,category:"planning_insight",summary:s,details:a,agent_name:"prometheus",task_context:`Plan lifecycle: ${e.event_type}`,files_involved:[e.plan_path],confidence:.9,scope:"project"}}function Cw(e){if(e.length===0)return"";let t=["<plan-learnings>","## Planning Insights (from previous sessions)",""],n=[],r=[];for(let s of e.slice(0,5))s.summary.includes("failed")?n.push(`- ${s.summary}`):r.push(`- ${s.summary}`);n.length>0&&(t.push("**Common Planning Mistakes:**"),t.push(...n),t.push("")),r.length>0&&(t.push("**Required Considerations:**"),t.push(...r),t.push("")),t.push("</plan-learnings>");let o=t.join(`
2018
2018
  `);return o.length>1200?o.substring(0,1200)+`
2019
- </plan-learnings>`:o}function $x(e){let t=e;if(t.startsWith("---")){let r=t.indexOf("---",3);r>0&&(t=t.substring(r+3).trim())}return t.replace(/^#+\s*/gm,"").replace(/\n+/g," ").trim().substring(0,200)}function Dx(e){let t=[],n=e.split(`
2020
- `);for(let r of n){let o=r.trim();/^[-*]\s+(CRITICAL|ISSUE|PROBLEM|MISSING|BUG|CONCERN):/i.test(o)&&t.push(o.replace(/^[-*]\s+/,"")),/\b(CRITICAL|MAJOR)\s+(ISSUE|PROBLEM|BUG|GAP)/i.test(o)&&o.length<200&&(t.includes(o)||t.push(o))}return t.slice(0,10)}var yw=new Map;function Nx(e){let n=(yw.get(e)||0)+1;return yw.set(e,n),n}Gt();Gt();Z();me();Da();var vw=T(require("path"),1);function Tw(){P({name:"planFileMonitor",event:"PostToolUse",priority:75,handler:async e=>{try{if(e.toolName!=="Write")return{continue:!0};if(!e.directory||!e.sessionId)return{continue:!0};if(!Tr(e.directory).enabled)return{continue:!0};let r=e.toolInput?.file_path;if(!r)return{continue:!0};let o=r.replace(/\\/g,"/");if(!o.includes(".olympus/plans/")||!o.endsWith(".md"))return{continue:!0};let s=kw(e.directory,r,e.sessionId);if(!s)return{continue:!0};if(s.event_type==="plan_revised"&&s.revision_count&&s.revision_count>=2){let i=nl(s,[`Plan revised ${s.revision_count} times - may indicate unclear requirements`],e.directory);i.summary&&i.details&&le({...i,project_path:e.directory,session_id:e.sessionId,category:i.category||"planning_insight",summary:i.summary,details:i.details,agent_name:i.agent_name||"prometheus",confidence:i.confidence||.7,scope:"project"})}}catch(t){console.error("[Olympus Plan Lifecycle] Error in plan file monitor:",t)}return{continue:!0}}}),P({name:"momusReviewTracker",event:"PostToolUse",priority:76,handler:async e=>{try{if(e.toolName!=="Task")return{continue:!0};if(!e.directory||!e.sessionId)return{continue:!0};if(!Tr(e.directory).enabled)return{continue:!0};let n=e.toolInput;if(n?.subagent_type!=="momus")return{continue:!0};let o=e.toolOutput,s=typeof o=="string"?o:JSON.stringify(o||""),i=_w(s);if(!i.passed&&i.issues.length>0){if(!i.issues.some(m=>m!=="Plan requires revision"&&m.length>10))return{continue:!0};let l=(n?.prompt||"").match(/\.olympus\/plans\/([\w-]+\.md)/),u=l?l[0]:"unknown-plan",d=l?l[1]:"unknown-plan",p={event_type:"plan_review_failed",plan_path:u,plan_summary:`Momus review failed with ${i.issues.length} issues`,failure_reasons:i.issues,reviewer:"momus",session_id:e.sessionId,timestamp:new Date().toISOString()},f=nl(p,i.issues,e.directory);f.summary&&f.details&&le({...f,project_path:e.directory,session_id:e.sessionId,category:"planning_insight",summary:f.summary,details:f.details,agent_name:"momus",confidence:.9,scope:"project"})}}catch(t){console.error("[Olympus Plan Lifecycle] Error in Momus review tracker:",t)}return{continue:!0}}}),P({name:"completePlanTracker",event:"UserPromptSubmit",priority:115,handler:async e=>{try{if(!e.directory||!e.sessionId)return{continue:!0};if(!Tr(e.directory).enabled)return{continue:!0};let n=e.prompt||"";if(!((e.parts||[]).map(a=>a.text||"").join(" ")||n).includes("[PLAN COMPLETION MODE - VERIFICATION REQUIRED]"))return{continue:!0};let i=Q(e.directory,e.sessionId);i.pending_completion||(i.pending_completion={claimed_at:new Date().toISOString(),task_description:"plan_completion_verification",agent_used:"complete-plan"},ee(e.directory,i))}catch(t){console.error("[Olympus Plan Lifecycle] Error in complete-plan tracker:",t)}return{continue:!0}}}),P({name:"prometheusLearningsInjection",event:"PreToolUse",priority:55,handler:async e=>{try{if(e.toolName!=="Task")return{continue:!0};if(!e.directory)return{continue:!0};if(e.toolInput?.subagent_type!=="prometheus")return{continue:!0};let o=ms(e.directory,20).filter(i=>i.category==="planning_insight");if(o.length===0)return{continue:!0};let s=Sw(o.slice(0,5));if(s)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:s}}}catch(t){console.error("[Olympus Plan Lifecycle] Error in Prometheus learnings injection:",t)}return{continue:!0}}}),P({name:"workflowPhaseTransitionTracker",event:"PostToolUse",priority:83,handler:async e=>{try{if(e.toolName!=="Write"&&e.toolName!=="Task")return{continue:!0};if(!e.directory||!e.sessionId)return{continue:!0};let t=e.directory,n=await oe(t),r=null,o=null;for(let u of n){let d=await I(t,u);if(d&&d.status!=="complete"&&d.status!=="archived"&&d.status!=="deferred"){r=u,o=d;break}}if(!r||!o)return{continue:!0};let s=vw.join(t,"aidlc-docs",r,"manifest.json"),i=W(s);if(!i)return{continue:!0};let a=Q(t,e.sessionId),c=o.current_phase,l=a.last_tracked_phase;if(l&&l!==c){let u=new Date().toISOString();i.gate_audit.push({phase:c,timestamp:u,action:"approved",actor:"trust",reason:`Phase transition: ${l} -> ${c}`});let d=l;i.phases[d]&&(i.phases[d].status="complete",i.phases[d].completed_at=u),i.phases[c]&&i.phases[c].status==="not_started"&&(i.phases[c].status="in_progress",i.phases[c].started_at=u),H(s,i),$a(t,r,o),(o.status==="complete"||o.current_stage==="complete")&&(i.phases.operations.status="complete",i.phases.operations.completed_at=u,H(s,i)),a.last_tracked_phase=c,ee(t,a);let p={discovery:"Discovery",inception:"Inception",construction:"Construction",operations:"Operations"},f=p[l]||l,m=p[c]||c,g=`Phase transition: ${f} \u2192 ${m}`;return c==="operations"&&(g+=`
2019
+ </plan-learnings>`:o}function Yx(e){let t=e;if(t.startsWith("---")){let r=t.indexOf("---",3);r>0&&(t=t.substring(r+3).trim())}return t.replace(/^#+\s*/gm,"").replace(/\n+/g," ").trim().substring(0,200)}function Kx(e){let t=[],n=e.split(`
2020
+ `);for(let r of n){let o=r.trim();/^[-*]\s+(CRITICAL|ISSUE|PROBLEM|MISSING|BUG|CONCERN):/i.test(o)&&t.push(o.replace(/^[-*]\s+/,"")),/\b(CRITICAL|MAJOR)\s+(ISSUE|PROBLEM|BUG|GAP)/i.test(o)&&o.length<200&&(t.includes(o)||t.push(o))}return t.slice(0,10)}var vw=new Map;function Jx(e){let n=(vw.get(e)||0)+1;return vw.set(e,n),n}Ut();Ut();Z();le();Wa();var Rw=b(require("path"),1);function xw(){P({name:"planFileMonitor",event:"PostToolUse",priority:75,handler:async e=>{try{if(e.toolName!=="Write")return{continue:!0};if(!e.directory||!e.sessionId)return{continue:!0};if(!br(e.directory).enabled)return{continue:!0};let r=e.toolInput?.file_path;if(!r)return{continue:!0};let o=r.replace(/\\/g,"/");if(!o.includes(".olympus/plans/")||!o.endsWith(".md"))return{continue:!0};let s=Tw(e.directory,r,e.sessionId);if(!s)return{continue:!0};if(s.event_type==="plan_revised"&&s.revision_count&&s.revision_count>=2){let i=il(s,[`Plan revised ${s.revision_count} times - may indicate unclear requirements`],e.directory);i.summary&&i.details&&ue({...i,project_path:e.directory,session_id:e.sessionId,category:i.category||"planning_insight",summary:i.summary,details:i.details,agent_name:i.agent_name||"prometheus",confidence:i.confidence||.7,scope:"project"})}}catch(t){console.error("[Olympus Plan Lifecycle] Error in plan file monitor:",t)}return{continue:!0}}}),P({name:"momusReviewTracker",event:"PostToolUse",priority:76,handler:async e=>{try{if(e.toolName!=="Task")return{continue:!0};if(!e.directory||!e.sessionId)return{continue:!0};if(!br(e.directory).enabled)return{continue:!0};let n=e.toolInput;if(n?.subagent_type!=="momus")return{continue:!0};let o=e.toolOutput,s=typeof o=="string"?o:JSON.stringify(o||""),i=Ew(s);if(!i.passed&&i.issues.length>0){if(!i.issues.some(m=>m!=="Plan requires revision"&&m.length>10))return{continue:!0};let l=(n?.prompt||"").match(/\.olympus\/plans\/([\w-]+\.md)/),u=l?l[0]:"unknown-plan",d=l?l[1]:"unknown-plan",p={event_type:"plan_review_failed",plan_path:u,plan_summary:`Momus review failed with ${i.issues.length} issues`,failure_reasons:i.issues,reviewer:"momus",session_id:e.sessionId,timestamp:new Date().toISOString()},f=il(p,i.issues,e.directory);f.summary&&f.details&&ue({...f,project_path:e.directory,session_id:e.sessionId,category:"planning_insight",summary:f.summary,details:f.details,agent_name:"momus",confidence:.9,scope:"project"})}}catch(t){console.error("[Olympus Plan Lifecycle] Error in Momus review tracker:",t)}return{continue:!0}}}),P({name:"completePlanTracker",event:"UserPromptSubmit",priority:115,handler:async e=>{try{if(!e.directory||!e.sessionId)return{continue:!0};if(!br(e.directory).enabled)return{continue:!0};let n=e.prompt||"";if(!((e.parts||[]).map(a=>a.text||"").join(" ")||n).includes("[PLAN COMPLETION MODE - VERIFICATION REQUIRED]"))return{continue:!0};let i=Q(e.directory,e.sessionId);i.pending_completion||(i.pending_completion={claimed_at:new Date().toISOString(),task_description:"plan_completion_verification",agent_used:"complete-plan"},ee(e.directory,i))}catch(t){console.error("[Olympus Plan Lifecycle] Error in complete-plan tracker:",t)}return{continue:!0}}}),P({name:"prometheusLearningsInjection",event:"PreToolUse",priority:55,handler:async e=>{try{if(e.toolName!=="Task")return{continue:!0};if(!e.directory)return{continue:!0};if(e.toolInput?.subagent_type!=="prometheus")return{continue:!0};let o=Jo(e.directory,20).filter(i=>i.category==="planning_insight");if(o.length===0)return{continue:!0};let s=Cw(o.slice(0,5));if(s)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:s}}}catch(t){console.error("[Olympus Plan Lifecycle] Error in Prometheus learnings injection:",t)}return{continue:!0}}}),P({name:"workflowPhaseTransitionTracker",event:"PostToolUse",priority:83,handler:async e=>{try{if(e.toolName!=="Write"&&e.toolName!=="Task")return{continue:!0};if(!e.directory||!e.sessionId)return{continue:!0};let t=e.directory,n=await oe(t),r=null,o=null;for(let u of n){let d=await I(t,u);if(d&&d.status!=="complete"&&d.status!=="archived"&&d.status!=="deferred"){r=u,o=d;break}}if(!r||!o)return{continue:!0};let s=Rw.join(t,"aidlc-docs",r,"manifest.json"),i=W(s);if(!i)return{continue:!0};let a=Q(t,e.sessionId),c=o.current_phase,l=a.last_tracked_phase;if(l&&l!==c){let u=new Date().toISOString();i.gate_audit.push({phase:c,timestamp:u,action:"approved",actor:"trust",reason:`Phase transition: ${l} -> ${c}`});let d=l;i.phases[d]&&(i.phases[d].status="complete",i.phases[d].completed_at=u),i.phases[c]&&i.phases[c].status==="not_started"&&(i.phases[c].status="in_progress",i.phases[c].started_at=u),G(s,i),Ua(t,r,o),(o.status==="complete"||o.current_stage==="complete")&&(i.phases.operations.status="complete",i.phases.operations.completed_at=u,G(s,i)),a.last_tracked_phase=c,ee(t,a);let p={discovery:"Discovery",inception:"Inception",construction:"Construction",operations:"Operations"},f=p[l]||l,m=p[c]||c,g=`Phase transition: ${f} \u2192 ${m}`;return c==="operations"&&(g+=`
2021
2021
  \u2192 Generating deployment artifacts...`),{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`<phase-transition>
2022
2022
  ${g}
2023
- </phase-transition>`}}}if(l||(a.last_tracked_phase=c,ee(t,a)),o.status==="complete"&&i.phases.operations.status!=="complete"){let u=new Date().toISOString();return i.phases.operations.status="complete",i.phases.operations.completed_at=u,H(s,i),$a(t,r,o),{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`<phase-transition>
2023
+ </phase-transition>`}}}if(l||(a.last_tracked_phase=c,ee(t,a)),o.status==="complete"&&i.phases.operations.status!=="complete"){let u=new Date().toISOString();return i.phases.operations.status="complete",i.phases.operations.completed_at=u,G(s,i),Ua(t,r,o),{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`<phase-transition>
2024
2024
  \u2713 Workflow complete! All phases finished.
2025
- </phase-transition>`}}}}catch(t){console.error("[Olympus Plan Lifecycle] Error in phase transition tracker:",t)}return{continue:!0}}})}me();Z();cn();Uo();function rl(e,t){return t===3||e<=1?"blocking":"auto-advance"}function ol(e,t){return t===3||e<=1?"blocking":e===2?"summary-review":"notification-only"}function sl(e,t){let n=e.links.find(r=>r.target_id===t&&r.link_type==="derives");return n?n.source_id:null}function Ew(e,t){let n=e.artifacts.filter(o=>o.stage==="unit"),r=e.risk_tier?.tier??null;return n.map(o=>{let s=e.links.filter(c=>c.source_id===o.id&&c.link_type==="derives").map(c=>e.artifacts.find(l=>l.id===c.target_id)).filter(c=>c!==void 0),i=s.length>0?`
2025
+ </phase-transition>`}}}}catch(t){console.error("[Olympus Plan Lifecycle] Error in phase transition tracker:",t)}return{continue:!0}}})}le();Z();sn();Uo();function al(e,t){return t===3||e<=1?"blocking":"auto-advance"}function cl(e,t){return t===3||e<=1?"blocking":e===2?"summary-review":"notification-only"}function ll(e,t){let n=e.links.find(r=>r.target_id===t&&r.link_type==="derives");return n?n.source_id:null}function Pw(e,t){let n=e.artifacts.filter(o=>o.stage==="unit"),r=e.risk_tier?.tier??null;return n.map(o=>{let s=e.links.filter(c=>c.source_id===o.id&&c.link_type==="derives").map(c=>e.artifacts.find(l=>l.id===c.target_id)).filter(c=>c!==void 0),i=s.length>0?`
2026
2026
 
2027
2027
  Child BOLTs:
2028
2028
  ${s.map(c=>` - ${c.id} (${c.path})`).join(`
@@ -2031,7 +2031,7 @@ ${s.map(c=>` - ${c.id} (${c.path})`).join(`
2031
2031
  No child BOLTs found.`,a=`UNIT Artifact: ${o.path}
2032
2032
  Contract Status: ${o.contract_status}${i}`;return r===3&&(a+=`
2033
2033
 
2034
- NOTE: Risk Tier 3 - Momus review mandatory for architecture decisions.`),{gateNumber:3,gateType:"architecture-review",artifactId:o.id,summary:`Architecture review for ${o.id}`,reviewContent:a,trustLevel:t,trustBehavior:rl(t,r)}})}function bw(e,t,n,r){let o=e.artifacts.find(c=>c.id===t);if(!o)throw new Error(`BOLT artifact not found: ${t}`);let s=ol(n,r),i="";n<=1?i=`
2034
+ NOTE: Risk Tier 3 - Momus review mandatory for architecture decisions.`),{gateNumber:3,gateType:"architecture-review",artifactId:o.id,summary:`Architecture review for ${o.id}`,reviewContent:a,trustLevel:t,trustBehavior:al(t,r)}})}function Aw(e,t,n,r){let o=e.artifacts.find(c=>c.id===t);if(!o)throw new Error(`BOLT artifact not found: ${t}`);let s=cl(n,r),i="";n<=1?i=`
2035
2035
 
2036
2036
  Review Instructions: Full code review required.`:n===2?i=`
2037
2037
 
@@ -2040,7 +2040,7 @@ Review Instructions: Summary review - verify major changes only.`:i=`
2040
2040
  Review Instructions: Notification only - AI proceeds automatically.`;let a=`BOLT Spec: ${o.path}
2041
2041
  Contract Status: ${o.contract_status}${i}`;return r===3&&(a+=`
2042
2042
 
2043
- NOTE: Risk Tier 3 - Developer review mandatory for every BOLT.`),{gateNumber:4,gateType:"code-review",artifactId:t,summary:`Code review for ${t}`,reviewContent:a,trustLevel:n,trustBehavior:s}}function Cw(e,t){let n=e.artifacts.length,r=e.artifacts.filter(c=>c.stage==="code-generation"),o=e.gate_audit.filter(c=>c.action==="approved").length,s=e.gate_audit.filter(c=>c.action==="rejected").length,i=r.length>0?r.map(c=>` - ${c.id}: ${c.contract_status}`).join(`
2043
+ NOTE: Risk Tier 3 - Developer review mandatory for every BOLT.`),{gateNumber:4,gateType:"code-review",artifactId:t,summary:`Code review for ${t}`,reviewContent:a,trustLevel:n,trustBehavior:s}}function Iw(e,t){let n=e.artifacts.length,r=e.artifacts.filter(c=>c.stage==="code-generation"),o=e.gate_audit.filter(c=>c.action==="approved").length,s=e.gate_audit.filter(c=>c.action==="rejected").length,i=r.length>0?r.map(c=>` - ${c.id}: ${c.contract_status}`).join(`
2044
2044
  `):" No BOLTs found.",a=`Release Approval Review
2045
2045
 
2046
2046
  Feature: ${e.feature_name}
@@ -2053,7 +2053,7 @@ Gate Audit Summary:
2053
2053
  BOLT Artifacts:
2054
2054
  ${i}
2055
2055
 
2056
- NOTE: Gate 5 is always blocking - final release approval required.`;return{gateNumber:5,gateType:"release-review",artifactId:e.workflow_id,summary:`Release approval for ${e.feature_name}`,reviewContent:a,trustLevel:t,trustBehavior:"blocking"}}var fn=T(X(),1),Ks=require("path");function il(e,t,n){fn.ensureDirSync((0,Ks.dirname)(e));let r="";fn.existsSync(e)?r=fn.readFileSync(e,"utf-8"):r=`# Validation Report: ${t}
2056
+ NOTE: Gate 5 is always blocking - final release approval required.`;return{gateNumber:5,gateType:"release-review",artifactId:e.workflow_id,summary:`Release approval for ${e.feature_name}`,reviewContent:a,trustLevel:t,trustBehavior:"blocking"}}var fn=b(X(),1),zs=require("path");function ul(e,t,n){fn.ensureDirSync((0,zs.dirname)(e));let r="";fn.existsSync(e)?r=fn.readFileSync(e,"utf-8"):r=`# Validation Report: ${t}
2057
2057
 
2058
2058
  `;let o=n.commandsExecuted.length>0?n.commandsExecuted.map(d=>`- \`${d.command}\` -> exit ${d.exitCode} (${d.result})`).join(`
2059
2059
  `):"- No commands recorded",s=`| Suite | Pass | Fail | Skip |
@@ -2080,37 +2080,37 @@ ${a}
2080
2080
 
2081
2081
  ---
2082
2082
 
2083
- `,u=r+l;fn.writeFileSync(e,u,"utf-8")}function al(e,t,n){return(0,Ks.join)(e,"aidlc-docs",t,"construction",n,"validation-report.md")}function Fx(e){switch(e){case 1:return"prometheus";case 2:return"prometheus";case 3:return"construction-executor";case 4:return"olympian";case 5:return"olympian";default:return console.error(`Unknown gate number: ${e}, defaulting to olympian`),"olympian"}}async function Rw(e,t,n,r=5){try{let o=n.attemptNumber>=r,s=Fx(n.gateNumber),i;switch(n.gateNumber){case 1:i=`Revise the INTENT based on this feedback: ${n.rejectionReason}`;break;case 2:i=`Update the INTENT based on this feedback: ${n.rejectionReason}`;break;case 3:i=`Regenerate UNITs based on this feedback: ${n.rejectionReason}`;break;case 4:i=`Re-implement this BOLT based on this feedback: ${n.rejectionReason}`;break;case 5:i=`Revise operations artifacts based on this feedback: ${n.rejectionReason}`;break;default:i=`Address this feedback: ${n.rejectionReason}`}let a=o?`Maximum revision attempts reached for ${n.artifactId}. Consider manual intervention or scope change.`:`${i}
2083
+ `,u=r+l;fn.writeFileSync(e,u,"utf-8")}function dl(e,t,n){return(0,zs.join)(e,"aidlc-docs",t,"construction",n,"validation-report.md")}function zx(e){switch(e){case 1:return"prometheus";case 2:return"prometheus";case 3:return"construction-executor";case 4:return"olympian";case 5:return"olympian";default:return console.error(`Unknown gate number: ${e}, defaulting to olympian`),"olympian"}}async function Ow(e,t,n,r=5){try{let o=n.attemptNumber>=r,s=zx(n.gateNumber),i;switch(n.gateNumber){case 1:i=`Revise the INTENT based on this feedback: ${n.rejectionReason}`;break;case 2:i=`Update the INTENT based on this feedback: ${n.rejectionReason}`;break;case 3:i=`Regenerate UNITs based on this feedback: ${n.rejectionReason}`;break;case 4:i=`Re-implement this BOLT based on this feedback: ${n.rejectionReason}`;break;case 5:i=`Revise operations artifacts based on this feedback: ${n.rejectionReason}`;break;default:i=`Address this feedback: ${n.rejectionReason}`}let a=o?`Maximum revision attempts reached for ${n.artifactId}. Consider manual intervention or scope change.`:`${i}
2084
2084
 
2085
2085
  Artifact ID: ${n.artifactId}
2086
2086
  Workflow ID: ${t}
2087
2087
  Attempt Number: ${n.attemptNumber}
2088
2088
  Rejected By: ${n.rejectedBy}
2089
2089
 
2090
- Please revise the artifact to address the feedback above and re-submit for approval.`;return{agentType:s,prompt:a,maxRetriesReached:o,contractStatusUpdate:{from:"violated",to:"draft"}}}catch(o){throw console.error("Error in dispatchRejection:",o),o}}var wo=T(require("fs"),1),ht=T(require("path"),1);function gt(e,t){try{return t()}catch(n){return{name:e,passed:!0,severity:"info",remediation:`Check error: ${n instanceof Error?n.message:String(n)}`}}}function cl(e){for(let t of e)if(wo.existsSync(t))return wo.readFileSync(t,"utf-8");return null}function jx(e){let t="user-stories-criteria",n=cl([ht.join(e,"inception","user-stories","stories.md"),ht.join(e,"inception","stories.md")]);return n===null?{name:t,passed:!0,severity:"info",remediation:"User stories stage was skipped \u2014 no stories.md artifact found."}:/acceptance\s+criteria/i.test(n)||/given\s+.+when\s+.+then/is.test(n)||/\bGiven\b.+\bWhen\b/s.test(n)?{name:t,passed:!0,severity:"info"}:{name:t,passed:!1,severity:"warning",remediation:'User stories are missing acceptance criteria. Add "Acceptance Criteria" sections or Given/When/Then scenarios to each story.'}}function Mx(e){let t="app-design-concrete",n=cl([ht.join(e,"inception","application-design","components.md"),ht.join(e,"inception","application-design.md"),ht.join(e,"inception","application-design","design.md")]);return n===null?{name:t,passed:!0,severity:"info",remediation:"Application design stage was skipped \u2014 no design artifact found."}:/\b(TBD|TODO|placeholder|to be determined|to be decided|N\/A)\b/i.test(n)?{name:t,passed:!1,severity:"warning",remediation:"Application design contains placeholder text (TBD/TODO/placeholder). Replace with concrete technology choices before proceeding to construction."}:{name:t,passed:!0,severity:"info"}}function Lx(e){let t="units-have-descriptions",n=cl([ht.join(e,"inception","unit-of-work.md"),ht.join(e,"inception","units-generation","unit-of-work.md")]);return n===null?{name:t,passed:!0,severity:"info",remediation:"Units generation stage was skipped \u2014 no unit-of-work.md artifact found."}:/^Scope\s*:\s*$/im.test(n)||/^Scope\s*:\s*(TBD|TODO|placeholder|N\/A)\s*$/im.test(n)?{name:t,passed:!1,severity:"error",remediation:"One or more units have an empty or placeholder Scope field. All units must have a concrete scope description before construction begins."}:{name:t,passed:!0,severity:"info"}}function xw(e){return[gt("user-stories-criteria",()=>jx(e)),gt("app-design-concrete",()=>Mx(e)),gt("units-have-descriptions",()=>Lx(e))]}function Ux(e){let t="tests-pass",n=e.test_generation_status;if(!n||n==="skipped"||n==="not_started")return{name:t,passed:!0,severity:"info",remediation:"Test generation was skipped or not started \u2014 no test results to evaluate."};let r=e.tests_total??0,o=e.tests_failed??0;return r===0?{name:t,passed:!1,severity:"warning",remediation:"No tests found for this unit. Add tests before marking the unit complete."}:o>0?{name:t,passed:!1,severity:"error",remediation:`${o} test(s) are failing. All tests must pass before Gate 4 approval.`}:{name:t,passed:!0,severity:"info"}}function Wx(e){let t="security-clean";if(!e.security_scan_status||e.security_scan_status==="not_started")return{name:t,passed:!0,severity:"info",remediation:"Security scanner not configured or not started."};if(e.security_scan_status==="skipped")return{name:t,passed:!0,severity:"info",remediation:"Security scan was skipped."};let n=e.security_findings_critical??0,r=n>0;return{name:t,passed:!r,severity:r?"error":"info",remediation:r?`${n} critical security finding(s) must be resolved before Gate 4 approval.`:void 0}}function Gx(e){let t="feature-doc-exists",n=e.feature_doc_status;return!n||n==="not_started"?{name:t,passed:!1,severity:"error",remediation:"Feature documentation has not been generated. Feature docs are mandatory for unit completion (FR-DOC-003). Run the documentation generator before approving this unit."}:n==="skipped"||n==="in_progress"?{name:t,passed:!0,severity:"info",remediation:n==="in_progress"?"Feature documentation is still in progress.":"Feature documentation was skipped."}:e.feature_doc_path?{name:t,passed:!0,severity:"info"}:{name:t,passed:!1,severity:"error",remediation:"Feature documentation status is completed but no artifact path was recorded. Re-run the documentation generator."}}function Bx(e){let t="architecture-model-updated",n=e.architecture_model_status;return!n||n==="not_started"?{name:t,passed:!0,severity:"warning",remediation:"Architecture model has not been updated for this unit. Consider running the architecture model updater."}:n==="updated"||n==="completed"?{name:t,passed:!0,severity:"info"}:{name:t,passed:!0,severity:"warning",remediation:`Architecture model status is "${n}". Verify the model reflects this unit's changes.`}}function ll(e,t){return[gt("tests-pass",()=>Ux(e)),gt("security-clean",()=>Wx(e)),gt("feature-doc-exists",()=>Gx(e)),gt("architecture-model-updated",()=>Bx(e))]}function Hx(e){let t="all-units-complete",n=e.construction_units;if(!n||Object.keys(n).length===0)return{name:t,passed:!0,severity:"info",remediation:"No construction units tracked in checkpoint."};let r=Object.values(n).filter(o=>o.code_generation_status!=="completed");if(r.length>0){let o=r.map(s=>s.unitId).join(", ");return{name:t,passed:!1,severity:"error",remediation:`${r.length} unit(s) have not completed code generation: ${o}. All units must be completed before Gate 5.`}}return{name:t,passed:!0,severity:"info"}}function Vx(e){let t="smoke-test-passed",n=e.smoke_test;return!n||n.status==="not_run"?{name:t,passed:!0,severity:"warning",remediation:"No smoke test result recorded. Run the smoke test build before proceeding to operations."}:n.status==="failed"?{name:t,passed:!1,severity:"error",remediation:`Smoke test failed (${n.tests_failed} failure(s) of ${n.tests_total} total). Fix failing tests before Gate 5 approval.`}:{name:t,passed:!0,severity:"info"}}function qx(e){let t="security-report-clean",n=e.construction_units;if(!n||Object.keys(n).length===0)return{name:t,passed:!0,severity:"info",remediation:"No construction units with security data found."};let r=Object.values(n).filter(s=>s.security_scan_status==="completed");if(r.length===0)return{name:t,passed:!0,severity:"info",remediation:"No units have completed security scans."};let o=r.reduce((s,i)=>s+(i.security_findings_critical??0),0);if(o>0){let s=r.filter(i=>(i.security_findings_critical??0)>0).map(i=>i.unitId).join(", ");return{name:t,passed:!1,severity:"error",remediation:`${o} critical security finding(s) across units: ${s}. Resolve all critical findings before Gate 5 approval.`}}return{name:t,passed:!0,severity:"info"}}function Yx(e){let t="test-report-exists",n=[ht.join(e,"construction","build-and-test","test-report.md"),ht.join(e,"construction","build-and-test","report.md"),ht.join(e,"construction","build-and-test","validation-report.md")];for(let r of n)if(wo.existsSync(r))return{name:t,passed:!0,severity:"info"};return{name:t,passed:!1,severity:"warning",remediation:"No test report found in build-and-test directory. Generate a test report before Gate 5 approval."}}function Pw(e,t){return[gt("all-units-complete",()=>Hx(e)),gt("smoke-test-passed",()=>Vx(e)),gt("security-report-clean",()=>qx(e)),gt("test-report-exists",()=>Yx(t))]}Gt();var zs=T(X(),1),Oe=require("path"),Rr=require("fs");function ul(e){if(!e)return"";let t=e.filter(r=>!r.passed);return t.length===0?"":`
2090
+ Please revise the artifact to address the feedback above and re-submit for approval.`;return{agentType:s,prompt:a,maxRetriesReached:o,contractStatusUpdate:{from:"violated",to:"draft"}}}catch(o){throw console.error("Error in dispatchRejection:",o),o}}var wo=b(require("fs"),1),ht=b(require("path"),1);function gt(e,t){try{return t()}catch(n){return{name:e,passed:!0,severity:"info",remediation:`Check error: ${n instanceof Error?n.message:String(n)}`}}}function pl(e){for(let t of e)if(wo.existsSync(t))return wo.readFileSync(t,"utf-8");return null}function Qx(e){let t="user-stories-criteria",n=pl([ht.join(e,"inception","user-stories","stories.md"),ht.join(e,"inception","stories.md")]);return n===null?{name:t,passed:!0,severity:"info",remediation:"User stories stage was skipped \u2014 no stories.md artifact found."}:/acceptance\s+criteria/i.test(n)||/given\s+.+when\s+.+then/is.test(n)||/\bGiven\b.+\bWhen\b/s.test(n)?{name:t,passed:!0,severity:"info"}:{name:t,passed:!1,severity:"warning",remediation:'User stories are missing acceptance criteria. Add "Acceptance Criteria" sections or Given/When/Then scenarios to each story.'}}function Xx(e){let t="app-design-concrete",n=pl([ht.join(e,"inception","application-design","components.md"),ht.join(e,"inception","application-design.md"),ht.join(e,"inception","application-design","design.md")]);return n===null?{name:t,passed:!0,severity:"info",remediation:"Application design stage was skipped \u2014 no design artifact found."}:/\b(TBD|TODO|placeholder|to be determined|to be decided|N\/A)\b/i.test(n)?{name:t,passed:!1,severity:"warning",remediation:"Application design contains placeholder text (TBD/TODO/placeholder). Replace with concrete technology choices before proceeding to construction."}:{name:t,passed:!0,severity:"info"}}function Zx(e){let t="units-have-descriptions",n=pl([ht.join(e,"inception","unit-of-work.md"),ht.join(e,"inception","units-generation","unit-of-work.md")]);return n===null?{name:t,passed:!0,severity:"info",remediation:"Units generation stage was skipped \u2014 no unit-of-work.md artifact found."}:/^Scope\s*:\s*$/im.test(n)||/^Scope\s*:\s*(TBD|TODO|placeholder|N\/A)\s*$/im.test(n)?{name:t,passed:!1,severity:"error",remediation:"One or more units have an empty or placeholder Scope field. All units must have a concrete scope description before construction begins."}:{name:t,passed:!0,severity:"info"}}function $w(e){return[gt("user-stories-criteria",()=>Qx(e)),gt("app-design-concrete",()=>Xx(e)),gt("units-have-descriptions",()=>Zx(e))]}function eP(e){let t="tests-pass",n=e.test_generation_status;if(!n||n==="skipped"||n==="not_started")return{name:t,passed:!0,severity:"info",remediation:"Test generation was skipped or not started \u2014 no test results to evaluate."};let r=e.tests_total??0,o=e.tests_failed??0;return r===0?{name:t,passed:!1,severity:"warning",remediation:"No tests found for this unit. Add tests before marking the unit complete."}:o>0?{name:t,passed:!1,severity:"error",remediation:`${o} test(s) are failing. All tests must pass before Gate 4 approval.`}:{name:t,passed:!0,severity:"info"}}function tP(e){let t="security-clean";if(!e.security_scan_status||e.security_scan_status==="not_started")return{name:t,passed:!0,severity:"info",remediation:"Security scanner not configured or not started."};if(e.security_scan_status==="skipped")return{name:t,passed:!0,severity:"info",remediation:"Security scan was skipped."};let n=e.security_findings_critical??0,r=n>0;return{name:t,passed:!r,severity:r?"error":"info",remediation:r?`${n} critical security finding(s) must be resolved before Gate 4 approval.`:void 0}}function nP(e){let t="feature-doc-exists",n=e.feature_doc_status;return!n||n==="not_started"?{name:t,passed:!1,severity:"error",remediation:"Feature documentation has not been generated. Feature docs are mandatory for unit completion (FR-DOC-003). Run the documentation generator before approving this unit."}:n==="skipped"||n==="in_progress"?{name:t,passed:!0,severity:"info",remediation:n==="in_progress"?"Feature documentation is still in progress.":"Feature documentation was skipped."}:e.feature_doc_path?{name:t,passed:!0,severity:"info"}:{name:t,passed:!1,severity:"error",remediation:"Feature documentation status is completed but no artifact path was recorded. Re-run the documentation generator."}}function rP(e){let t="architecture-model-updated",n=e.architecture_model_status;return!n||n==="not_started"?{name:t,passed:!0,severity:"warning",remediation:"Architecture model has not been updated for this unit. Consider running the architecture model updater."}:n==="updated"||n==="completed"?{name:t,passed:!0,severity:"info"}:{name:t,passed:!0,severity:"warning",remediation:`Architecture model status is "${n}". Verify the model reflects this unit's changes.`}}function fl(e,t){return[gt("tests-pass",()=>eP(e)),gt("security-clean",()=>tP(e)),gt("feature-doc-exists",()=>nP(e)),gt("architecture-model-updated",()=>rP(e))]}function oP(e){let t="all-units-complete",n=e.construction_units;if(!n||Object.keys(n).length===0)return{name:t,passed:!0,severity:"info",remediation:"No construction units tracked in checkpoint."};let r=Object.values(n).filter(o=>o.code_generation_status!=="completed");if(r.length>0){let o=r.map(s=>s.unitId).join(", ");return{name:t,passed:!1,severity:"error",remediation:`${r.length} unit(s) have not completed code generation: ${o}. All units must be completed before Gate 5.`}}return{name:t,passed:!0,severity:"info"}}function sP(e){let t="smoke-test-passed",n=e.smoke_test;return!n||n.status==="not_run"?{name:t,passed:!0,severity:"warning",remediation:"No smoke test result recorded. Run the smoke test build before proceeding to operations."}:n.status==="failed"?{name:t,passed:!1,severity:"error",remediation:`Smoke test failed (${n.tests_failed} failure(s) of ${n.tests_total} total). Fix failing tests before Gate 5 approval.`}:{name:t,passed:!0,severity:"info"}}function iP(e){let t="security-report-clean",n=e.construction_units;if(!n||Object.keys(n).length===0)return{name:t,passed:!0,severity:"info",remediation:"No construction units with security data found."};let r=Object.values(n).filter(s=>s.security_scan_status==="completed");if(r.length===0)return{name:t,passed:!0,severity:"info",remediation:"No units have completed security scans."};let o=r.reduce((s,i)=>s+(i.security_findings_critical??0),0);if(o>0){let s=r.filter(i=>(i.security_findings_critical??0)>0).map(i=>i.unitId).join(", ");return{name:t,passed:!1,severity:"error",remediation:`${o} critical security finding(s) across units: ${s}. Resolve all critical findings before Gate 5 approval.`}}return{name:t,passed:!0,severity:"info"}}function aP(e){let t="test-report-exists",n=[ht.join(e,"construction","build-and-test","test-report.md"),ht.join(e,"construction","build-and-test","report.md"),ht.join(e,"construction","build-and-test","validation-report.md")];for(let r of n)if(wo.existsSync(r))return{name:t,passed:!0,severity:"info"};return{name:t,passed:!1,severity:"warning",remediation:"No test report found in build-and-test directory. Generate a test report before Gate 5 approval."}}function Dw(e,t){return[gt("all-units-complete",()=>oP(e)),gt("smoke-test-passed",()=>sP(e)),gt("security-report-clean",()=>iP(e)),gt("test-report-exists",()=>aP(t))]}Ut();var Xs=b(X(),1),Oe=require("path"),Rr=require("fs");function ml(e){if(!e)return"";let t=e.filter(r=>!r.passed);return t.length===0?"":`
2091
2091
 
2092
2092
  **Content Check Failures:**
2093
2093
  ${t.map(r=>`- ${r.name}: ${r.remediation??"No remediation provided."}`).join(`
2094
- `)}`}var Cr={inception:[{question:"Does the INTENT address all stated constraints?",answer:null,answered_by:null,passed:null},{question:"Does the INTENT solve the actual business problem?",answer:null,answered_by:null,passed:null},{question:"Are NFRs properly derived from INTENT constraints?",answer:null,answered_by:null,passed:null}],construction:[{question:"Do UNITS cover all INTENT acceptance criteria?",answer:null,answered_by:null,passed:null},{question:"Does DESIGN address all UNIT requirements?",answer:null,answered_by:null,passed:null},{question:"Does BUILD satisfy DESIGN contracts?",answer:null,answered_by:null,passed:null}],operations:[{question:"Does the deployment guide cover all components?",answer:null,answered_by:null,passed:null},{question:"Does the monitoring config capture key metrics?",answer:null,answered_by:null,passed:null}],gate3:[{question:"Do UNITs cover all INTENT acceptance criteria?",answer:null,answered_by:null,passed:null},{question:"Is the decomposition granularity appropriate?",answer:null,answered_by:null,passed:null}],gate4:[{question:"Does the BOLT implementation satisfy its acceptance criteria?",answer:null,answered_by:null,passed:null},{question:"Are all tests passing?",answer:null,answered_by:null,passed:null}]};async function Js(e){try{let t=await oe(e);if(t.length===0)return null;let n=null;for(let r of t){let o=await I(e,r);if(!o||o.status==="complete")continue;let s=o.manifest_path||(0,Oe.join)(e,".olympus","workflow",r,"manifest.json");(!n||o.updated_at>n.updatedAt)&&(n={workflowId:r,checkpoint:o,manifestPath:s,updatedAt:o.updated_at})}return n?{workflowId:n.workflowId,checkpoint:n.checkpoint,manifestPath:n.manifestPath}:null}catch(t){return console.error("[Olympus Quality Gate] Failed to find active workflow:",t),null}}function Kx(e,t){let n=e.current_phase;if(!n)return e.current_stage==="intent"||e.current_stage==="complete"?"inception":null;if(t){let r=t.phases[n];if(r&&r.status==="in_progress"&&(!r.gate_result||r.gate_result&&!r.gate_result.passed&&r.gate_result.approved_by===null))return r.gate_result&&r.gate_result.approved_by===null?null:n}return n==="inception"&&(e.current_stage==="intent"||e.current_stage==="complete")?"inception":n==="construction"&&e.current_stage==="unit"||n==="construction"&&e.current_stage==="code-generation"&&e.active_code_plan_path?"construction":n==="operations"?"operations":null}function Jx(e){try{let t=(0,Oe.join)(e,".olympus","config.json");if(zs.existsSync(t)){let n=zs.readJsonSync(t);if(n?.workflow?.qualityGates?.enabled===!1||n?.hooks?.qualityGate?.enabled===!1)return!0}}catch{}return!1}function dl(e){for(let t of["discovery","inception","construction","operations"]){let n=e.phases[t];if(n.gate_result&&!n.gate_result.passed&&n.gate_result.approved_by===null)return t}return null}function zx(e,t){return e==="inception"?t==="intent"?2:1:e==="construction"?t==="code-generation"?4:3:e==="operations"?5:1}function Qx(e){return e.prompt?e.prompt:e.message?.content?e.message.content:e.parts?e.parts.filter(t=>t.type==="text"&&t.text).map(t=>t.text).join(" "):""}async function Xx(e){try{if(e.toolName!=="Task")return{continue:!0};if(!e.directory||!e.sessionId)return{continue:!0};let t=await Js(e.directory);if(!t)return{continue:!0};let{workflowId:n,checkpoint:r,manifestPath:o}=t,s=W(o);if(!s)return console.error("[Olympus Quality Gate] Manifest corrupted or missing - failing open"),{continue:!0};let i=Kx(r,s);if(!i)return{continue:!0};let a=be(e.directory),c=(typeof r.risk_tier=="number"?r.risk_tier:r.risk_tier?.tier)||s.risk_tier?.tier||2;if(c===3&&i==="inception"&&!s.artifacts.some(k=>k.type?.toLowerCase().includes("momus")||k.type?.toLowerCase()==="momus-review"))return s.phases[i].gate_result={passed:!1,approved_by:null,approved_at:null,feedback:"Momus review required for Risk Tier 3",verification:{conformance_score:0,coverage_percentage:0,missing_items:["Momus review artifact missing"],passed:!1},validation:{alignment_score:0,alignment_questions:[],passed:!1}},H(o,s),await O(e.directory,r),{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`[BLOCKING - Acknowledgment Required] BLOCKED: Risk Tier 3 requires Momus review before INTENT approval. Run /review to invoke Momus.
2094
+ `)}`}var Cr={inception:[{question:"Does the INTENT address all stated constraints?",answer:null,answered_by:null,passed:null},{question:"Does the INTENT solve the actual business problem?",answer:null,answered_by:null,passed:null},{question:"Are NFRs properly derived from INTENT constraints?",answer:null,answered_by:null,passed:null}],construction:[{question:"Do UNITS cover all INTENT acceptance criteria?",answer:null,answered_by:null,passed:null},{question:"Does DESIGN address all UNIT requirements?",answer:null,answered_by:null,passed:null},{question:"Does BUILD satisfy DESIGN contracts?",answer:null,answered_by:null,passed:null}],operations:[{question:"Does the deployment guide cover all components?",answer:null,answered_by:null,passed:null},{question:"Does the monitoring config capture key metrics?",answer:null,answered_by:null,passed:null}],gate3:[{question:"Do UNITs cover all INTENT acceptance criteria?",answer:null,answered_by:null,passed:null},{question:"Is the decomposition granularity appropriate?",answer:null,answered_by:null,passed:null}],gate4:[{question:"Does the BOLT implementation satisfy its acceptance criteria?",answer:null,answered_by:null,passed:null},{question:"Are all tests passing?",answer:null,answered_by:null,passed:null}]};async function Qs(e){try{let t=await oe(e);if(t.length===0)return null;let n=null;for(let r of t){let o=await I(e,r);if(!o||o.status==="complete")continue;let s=o.manifest_path||(0,Oe.join)(e,".olympus","workflow",r,"manifest.json");(!n||o.updated_at>n.updatedAt)&&(n={workflowId:r,checkpoint:o,manifestPath:s,updatedAt:o.updated_at})}return n?{workflowId:n.workflowId,checkpoint:n.checkpoint,manifestPath:n.manifestPath}:null}catch(t){return console.error("[Olympus Quality Gate] Failed to find active workflow:",t),null}}function cP(e,t){let n=e.current_phase;if(!n)return e.current_stage==="intent"||e.current_stage==="complete"?"inception":null;if(t){let r=t.phases[n];if(r&&r.status==="in_progress"&&(!r.gate_result||r.gate_result&&!r.gate_result.passed&&r.gate_result.approved_by===null))return r.gate_result&&r.gate_result.approved_by===null?null:n}return n==="inception"&&(e.current_stage==="intent"||e.current_stage==="complete")?"inception":n==="construction"&&e.current_stage==="unit"||n==="construction"&&e.current_stage==="code-generation"&&e.active_code_plan_path?"construction":n==="operations"?"operations":null}function lP(e){try{let t=(0,Oe.join)(e,".olympus","config.json");if(Xs.existsSync(t)){let n=Xs.readJsonSync(t);if(n?.workflow?.qualityGates?.enabled===!1||n?.hooks?.qualityGate?.enabled===!1)return!0}}catch{}return!1}function gl(e){for(let t of["discovery","inception","construction","operations"]){let n=e.phases[t];if(n.gate_result&&!n.gate_result.passed&&n.gate_result.approved_by===null)return t}return null}function uP(e,t){return e==="inception"?t==="intent"?2:1:e==="construction"?t==="code-generation"?4:3:e==="operations"?5:1}function dP(e){return e.prompt?e.prompt:e.message?.content?e.message.content:e.parts?e.parts.filter(t=>t.type==="text"&&t.text).map(t=>t.text).join(" "):""}async function pP(e){try{if(e.toolName!=="Task")return{continue:!0};if(!e.directory||!e.sessionId)return{continue:!0};let t=await Qs(e.directory);if(!t)return{continue:!0};let{workflowId:n,checkpoint:r,manifestPath:o}=t,s=W(o);if(!s)return console.error("[Olympus Quality Gate] Manifest corrupted or missing - failing open"),{continue:!0};let i=cP(r,s);if(!i)return{continue:!0};let a=Te(e.directory),c=(typeof r.risk_tier=="number"?r.risk_tier:r.risk_tier?.tier)||s.risk_tier?.tier||2;if(c===3&&i==="inception"&&!s.artifacts.some(_=>_.type?.toLowerCase().includes("momus")||_.type?.toLowerCase()==="momus-review"))return s.phases[i].gate_result={passed:!1,approved_by:null,approved_at:null,feedback:"Momus review required for Risk Tier 3",verification:{conformance_score:0,coverage_percentage:0,missing_items:["Momus review artifact missing"],passed:!1},validation:{alignment_score:0,alignment_questions:[],passed:!1}},G(o,s),await A(e.directory,r),{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`[BLOCKING - Acknowledgment Required] BLOCKED: Risk Tier 3 requires Momus review before INTENT approval. Run /review to invoke Momus.
2095
2095
 
2096
- [GATE_PENDING]`}};if(i==="construction"&&r.current_stage==="unit"){if(rl(a.current_level,c)==="auto-advance"&&c!==3){Fe(o,{phase:"construction",action:"approved",actor:"trust",reason:`Gate 3 auto-advanced by Trust Level ${a.current_level} for Tier ${c}`});let R=new Date().toISOString();s.phases.construction.gate_result={passed:!0,approved_by:"trust",approved_at:R,feedback:null,verification:{conformance_score:100,coverage_percentage:100,missing_items:[],passed:!0},validation:{alignment_score:100,alignment_questions:[],passed:!0}};for(let A of s.artifacts)A.stage==="unit"&&(A.reviewedBy="auto-approved");H(o,s),await O(e.directory,r);try{let A={type:"gate_approval",phase:"construction",stage:"unit",details:`Gate 3 auto-advanced by Trust Level ${a.current_level} for Tier ${c}`},C={workflowId:n,featureName:r.feature_name||n,projectPath:e.directory,sessionId:e.sessionId||"unknown",phase:"construction"},$=Ve(A,C);le($)}catch(A){console.error("[Olympus Quality Gate] Failed to capture Gate 3 auto-advance discovery:",A)}return{continue:!0}}let k;try{let R=(0,Oe.join)(e.directory,"aidlc-docs",n,"inception"),A=(0,Rr.readFileSync)((0,Oe.join)(R,"intent.md"),"utf-8"),C=s.artifacts.filter(x=>x.stage==="unit"),$=C.length>0?(0,Rr.readFileSync)((0,Oe.join)(e.directory,C[0].path),"utf-8"):"",N=Qn($,A,A,"intent-to-unit","unit-to-intent","intent",C[0]?.id||"unit","intent");k={conformance_score:N.parentCheck.verification.conformance_score,coverage_percentage:N.parentCheck.verification.coverage_percentage,missing_items:N.parentCheck.verification.missing_items,passed:N.passed}}catch{k={conformance_score:0,coverage_percentage:0,missing_items:["Could not read construction artifacts for alignment check"],passed:!1}}let h=Cr.gate3||[],v={alignment_score:0,alignment_questions:h,passed:!1},b=Ew(s,a.current_level).map(R=>R.reviewContent).join(`
2096
+ [GATE_PENDING]`}};if(i==="construction"&&r.current_stage==="unit"){if(al(a.current_level,c)==="auto-advance"&&c!==3){Fe(o,{phase:"construction",action:"approved",actor:"trust",reason:`Gate 3 auto-advanced by Trust Level ${a.current_level} for Tier ${c}`});let R=new Date().toISOString();s.phases.construction.gate_result={passed:!0,approved_by:"trust",approved_at:R,feedback:null,verification:{conformance_score:100,coverage_percentage:100,missing_items:[],passed:!0},validation:{alignment_score:100,alignment_questions:[],passed:!0}};for(let O of s.artifacts)O.stage==="unit"&&(O.reviewedBy="auto-approved");G(o,s),await A(e.directory,r);try{let O={type:"gate_approval",phase:"construction",stage:"unit",details:`Gate 3 auto-advanced by Trust Level ${a.current_level} for Tier ${c}`},C={workflowId:n,featureName:r.feature_name||n,projectPath:e.directory,sessionId:e.sessionId||"unknown",phase:"construction"},$=qe(O,C);ue($)}catch(O){console.error("[Olympus Quality Gate] Failed to capture Gate 3 auto-advance discovery:",O)}return{continue:!0}}let _;try{let R=(0,Oe.join)(e.directory,"aidlc-docs",n,"inception"),O=(0,Rr.readFileSync)((0,Oe.join)(R,"intent.md"),"utf-8"),C=s.artifacts.filter(x=>x.stage==="unit"),$=C.length>0?(0,Rr.readFileSync)((0,Oe.join)(e.directory,C[0].path),"utf-8"):"",N=Qn($,O,O,"intent-to-unit","unit-to-intent","intent",C[0]?.id||"unit","intent");_={conformance_score:N.parentCheck.verification.conformance_score,coverage_percentage:N.parentCheck.verification.coverage_percentage,missing_items:N.parentCheck.verification.missing_items,passed:N.passed}}catch{_={conformance_score:0,coverage_percentage:0,missing_items:["Could not read construction artifacts for alignment check"],passed:!1}}let h=Cr.gate3||[],v={alignment_score:0,alignment_questions:h,passed:!1},E=Pw(s,a.current_level).map(R=>R.reviewContent).join(`
2097
2097
 
2098
- `);return s.phases.construction.gate_result={passed:!1,approved_by:null,approved_at:null,feedback:null,verification:k,validation:v},Fe(o,{phase:"construction",action:"approved",actor:"trust",reason:"Gate 3 pending review"}),H(o,s),await O(e.directory,r),{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`${c===3?"[BLOCKING - Acknowledgment Required] ":""}STOP: Gate 3 (UNIT decomposition review) requires approval.
2098
+ `);return s.phases.construction.gate_result={passed:!1,approved_by:null,approved_at:null,feedback:null,verification:_,validation:v},Fe(o,{phase:"construction",action:"approved",actor:"trust",reason:"Gate 3 pending review"}),G(o,s),await A(e.directory,r),{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`${c===3?"[BLOCKING - Acknowledgment Required] ":""}STOP: Gate 3 (UNIT decomposition review) requires approval.
2099
2099
 
2100
- ${b}
2100
+ ${E}
2101
2101
 
2102
- VERIFICATION: ${k.conformance_score}% conformance, ${k.coverage_percentage}% coverage.
2103
- Missing: ${k.missing_items.join(", ")}
2102
+ VERIFICATION: ${_.conformance_score}% conformance, ${_.coverage_percentage}% coverage.
2103
+ Missing: ${_.missing_items.join(", ")}
2104
2104
 
2105
2105
  VALIDATION: Review alignment questions:
2106
- ${h.map((R,A)=>`${A+1}. ${R.question}`).join(`
2106
+ ${h.map((R,O)=>`${O+1}. ${R.question}`).join(`
2107
2107
  `)}
2108
2108
 
2109
2109
  Type "approve" to proceed or "reject <reason>" to block.
2110
2110
 
2111
- [GATE_PENDING]`}}}if(i==="construction"&&r.current_stage==="code-generation"&&r.active_code_plan_path){let w=r.active_code_plan_path,k=ol(a.current_level,c),h;try{let C=(0,Oe.join)(e.directory,"aidlc-docs",n,"inception"),$=(0,Rr.readFileSync)((0,Oe.join)(C,"intent.md"),"utf-8"),N=s.artifacts.find(M=>M.id===w),x=N?(0,Rr.readFileSync)((0,Oe.join)(e.directory,N.path),"utf-8"):"",E=Qn(x,$,$,"unit-to-bolt","bolt-to-intent","intent",w,"intent");h={conformance_score:E.parentCheck.verification.conformance_score,coverage_percentage:E.parentCheck.verification.coverage_percentage,missing_items:E.parentCheck.verification.missing_items,passed:E.passed}}catch{h={conformance_score:0,coverage_percentage:0,missing_items:["Could not read BOLT artifacts for alignment check"],passed:!1}}let v=Cr.gate4||[],S={alignment_score:0,alignment_questions:v,passed:!1};if(k==="notification-only"&&c!==3){Fe(o,{phase:"construction",action:"approved",actor:"trust",reason:`Gate 4 notification-only for BOLT ${w} at Trust Level ${a.current_level}`});let $={passed:!0,approved_by:"trust",approved_at:new Date().toISOString(),feedback:null,verification:h,validation:S};try{let E=r.construction_units?.[w];if(E){let M=ll(E,(0,Oe.join)(e.directory,"aidlc-docs",n));$.content_checks=M,M.some(F=>!F.passed&&F.severity==="error")&&($.passed=!1)}}catch(E){console.error("[quality-gate] Gate 4 content check error:",E)}s.phases.construction.gate_result=$;let N=s.artifacts.find(E=>E.id===w);N&&(N.reviewedBy="auto-approved"),Tt(o,w,"fulfilled");try{let E=sl(s,w);if(E&&e.directory){let M=al(e.directory,n,E);il(M,E,{boltId:w,boltTitle:N?.type||"auto-approved",commandsExecuted:[],testResults:[],filesChanged:[],gateApprovedBy:"auto-approved",dualValidation:{parentConformance:h.conformance_score,rootConformance:0},riskTier:c})}}catch(E){console.error("[Olympus Quality Gate] Failed to generate validation report:",E)}H(o,s),await O(e.directory,r);try{let E={type:"gate_approval",phase:"construction",stage:"code-generation",details:`Gate 4 notification-only for BOLT ${w} at Trust Level ${a.current_level}`,artifactId:w},M={workflowId:n,featureName:r.feature_name||n,projectPath:e.directory,sessionId:e.sessionId||"unknown",phase:"construction"},F=Ve(E,M);le(F)}catch(E){console.error("[Olympus Quality Gate] Failed to capture Gate 4 auto-advance discovery:",E)}let x="";try{let{isWorkflowComplete:E}=await Promise.resolve().then(()=>(Z(),vn)),M=W(o);M&&E(M)&&(r.current_phase="operations",r.current_stage="code-generation",jt(o,"construction","complete"),jt(o,"operations","in_progress"),await O(e.directory,r),x=" All BOLTs fulfilled \u2014 auto-transitioning to Operations phase.",console.log("[Olympus Quality Gate] All BOLTs fulfilled \u2014 auto-transitioning to Operations phase"))}catch(E){console.error("[Olympus Quality Gate] Failed to check workflow completion:",E)}return{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`Gate 4 (BOLT ${w} review): Auto-approved at Trust Level ${a.current_level}. Notification only.${x}`}}}let b;try{b=bw(s,w,a.current_level,c)}catch{return{continue:!0}}let _={passed:!1,approved_by:null,approved_at:null,feedback:null,verification:h,validation:S};try{let C=r.construction_units?.[w];if(C){let $=ll(C,(0,Oe.join)(e.directory,"aidlc-docs",n));_.content_checks=$,$.some(N=>!N.passed&&N.severity==="error")&&(_.passed=!1)}}catch(C){console.error("[quality-gate] Gate 4 content check error:",C)}return s.phases.construction.gate_result=_,Fe(o,{phase:"construction",action:"approved",actor:"trust",reason:`Gate 4 pending review for BOLT ${w}`,content_checks:_.content_checks}),H(o,s),await O(e.directory,r),{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`${c===3?"[BLOCKING - Acknowledgment Required] ":""}STOP: Gate 4 (BOLT ${w} review)${k==="summary-review"?" (Summary Review)":""} requires approval.
2111
+ [GATE_PENDING]`}}}if(i==="construction"&&r.current_stage==="code-generation"&&r.active_code_plan_path){let w=r.active_code_plan_path,_=cl(a.current_level,c),h;try{let C=(0,Oe.join)(e.directory,"aidlc-docs",n,"inception"),$=(0,Rr.readFileSync)((0,Oe.join)(C,"intent.md"),"utf-8"),N=s.artifacts.find(M=>M.id===w),x=N?(0,Rr.readFileSync)((0,Oe.join)(e.directory,N.path),"utf-8"):"",T=Qn(x,$,$,"unit-to-bolt","bolt-to-intent","intent",w,"intent");h={conformance_score:T.parentCheck.verification.conformance_score,coverage_percentage:T.parentCheck.verification.coverage_percentage,missing_items:T.parentCheck.verification.missing_items,passed:T.passed}}catch{h={conformance_score:0,coverage_percentage:0,missing_items:["Could not read BOLT artifacts for alignment check"],passed:!1}}let v=Cr.gate4||[],S={alignment_score:0,alignment_questions:v,passed:!1};if(_==="notification-only"&&c!==3){Fe(o,{phase:"construction",action:"approved",actor:"trust",reason:`Gate 4 notification-only for BOLT ${w} at Trust Level ${a.current_level}`});let $={passed:!0,approved_by:"trust",approved_at:new Date().toISOString(),feedback:null,verification:h,validation:S};try{let T=r.construction_units?.[w];if(T){let M=fl(T,(0,Oe.join)(e.directory,"aidlc-docs",n));$.content_checks=M,M.some(F=>!F.passed&&F.severity==="error")&&($.passed=!1)}}catch(T){console.error("[quality-gate] Gate 4 content check error:",T)}s.phases.construction.gate_result=$;let N=s.artifacts.find(T=>T.id===w);N&&(N.reviewedBy="auto-approved"),bt(o,w,"fulfilled");try{let T=ll(s,w);if(T&&e.directory){let M=dl(e.directory,n,T);ul(M,T,{boltId:w,boltTitle:N?.type||"auto-approved",commandsExecuted:[],testResults:[],filesChanged:[],gateApprovedBy:"auto-approved",dualValidation:{parentConformance:h.conformance_score,rootConformance:0},riskTier:c})}}catch(T){console.error("[Olympus Quality Gate] Failed to generate validation report:",T)}G(o,s),await A(e.directory,r);try{let T={type:"gate_approval",phase:"construction",stage:"code-generation",details:`Gate 4 notification-only for BOLT ${w} at Trust Level ${a.current_level}`,artifactId:w},M={workflowId:n,featureName:r.feature_name||n,projectPath:e.directory,sessionId:e.sessionId||"unknown",phase:"construction"},F=qe(T,M);ue(F)}catch(T){console.error("[Olympus Quality Gate] Failed to capture Gate 4 auto-advance discovery:",T)}let x="";try{let{isWorkflowComplete:T}=await Promise.resolve().then(()=>(Z(),vn)),M=W(o);M&&T(M)&&(r.current_phase="operations",r.current_stage="code-generation",jt(o,"construction","complete"),jt(o,"operations","in_progress"),await A(e.directory,r),x=" All BOLTs fulfilled \u2014 auto-transitioning to Operations phase.",console.log("[Olympus Quality Gate] All BOLTs fulfilled \u2014 auto-transitioning to Operations phase"))}catch(T){console.error("[Olympus Quality Gate] Failed to check workflow completion:",T)}return{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`Gate 4 (BOLT ${w} review): Auto-approved at Trust Level ${a.current_level}. Notification only.${x}`}}}let E;try{E=Aw(s,w,a.current_level,c)}catch{return{continue:!0}}let k={passed:!1,approved_by:null,approved_at:null,feedback:null,verification:h,validation:S};try{let C=r.construction_units?.[w];if(C){let $=fl(C,(0,Oe.join)(e.directory,"aidlc-docs",n));k.content_checks=$,$.some(N=>!N.passed&&N.severity==="error")&&(k.passed=!1)}}catch(C){console.error("[quality-gate] Gate 4 content check error:",C)}return s.phases.construction.gate_result=k,Fe(o,{phase:"construction",action:"approved",actor:"trust",reason:`Gate 4 pending review for BOLT ${w}`,content_checks:k.content_checks}),G(o,s),await A(e.directory,r),{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`${c===3?"[BLOCKING - Acknowledgment Required] ":""}STOP: Gate 4 (BOLT ${w} review)${_==="summary-review"?" (Summary Review)":""} requires approval.
2112
2112
 
2113
- ${b.reviewContent}
2113
+ ${E.reviewContent}
2114
2114
 
2115
2115
  VERIFICATION: ${h.conformance_score}% conformance, ${h.coverage_percentage}% coverage.
2116
2116
  Missing: ${h.missing_items.join(", ")}
@@ -2119,35 +2119,35 @@ VALIDATION: Review alignment questions:
2119
2119
  ${v.map((C,$)=>`${$+1}. ${C.question}`).join(`
2120
2120
  `)}
2121
2121
 
2122
- Type "approve" to proceed or "reject <reason>" to block.${ul(_.content_checks)}
2122
+ Type "approve" to proceed or "reject <reason>" to block.${ml(k.content_checks)}
2123
2123
 
2124
- [GATE_PENDING]`}}}if(i==="operations"){let w;try{w=Cw(s,a.current_level)}catch{return{continue:!0}}let k=Cr.operations||[],S={passed:!1,approved_by:null,approved_at:null,feedback:null,verification:{conformance_score:0,coverage_percentage:0,missing_items:["Release review pending"],passed:!1},validation:{alignment_score:0,alignment_questions:k,passed:!1}};try{let _=Pw(r,(0,Oe.join)(e.directory,"aidlc-docs",n));S.content_checks=_,_.some(j=>!j.passed&&j.severity==="error")&&(S.passed=!1)}catch(_){console.error("[quality-gate] Gate 5 content check error:",_)}return s.phases.operations.gate_result=S,H(o,s),await O(e.directory,r),{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`[BLOCKING - Acknowledgment Required] STOP: Gate 5 (Release review) requires approval.
2124
+ [GATE_PENDING]`}}}if(i==="operations"){let w;try{w=Iw(s,a.current_level)}catch{return{continue:!0}}let _=Cr.operations||[],S={passed:!1,approved_by:null,approved_at:null,feedback:null,verification:{conformance_score:0,coverage_percentage:0,missing_items:["Release review pending"],passed:!1},validation:{alignment_score:0,alignment_questions:_,passed:!1}};try{let k=Dw(r,(0,Oe.join)(e.directory,"aidlc-docs",n));S.content_checks=k,k.some(j=>!j.passed&&j.severity==="error")&&(S.passed=!1)}catch(k){console.error("[quality-gate] Gate 5 content check error:",k)}return s.phases.operations.gate_result=S,G(o,s),await A(e.directory,r),{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`[BLOCKING - Acknowledgment Required] STOP: Gate 5 (Release review) requires approval.
2125
2125
 
2126
2126
  ${w.reviewContent}
2127
2127
 
2128
2128
  VALIDATION: Review alignment questions:
2129
- ${k.map((_,j)=>`${j+1}. ${_.question}`).join(`
2129
+ ${_.map((k,j)=>`${j+1}. ${k.question}`).join(`
2130
2130
  `)}
2131
2131
 
2132
- Type "approve" to proceed or "reject <reason>" to block.${ul(S.content_checks)}
2132
+ Type "approve" to proceed or "reject <reason>" to block.${ml(S.content_checks)}
2133
2133
 
2134
- [GATE_PENDING]`}}}if(zm(c,a.current_level)){Fe(o,{phase:i,action:"approved",actor:"trust",reason:`Auto-advanced by Trust Level ${a.current_level} for Tier ${c}`});let w=new Date().toISOString();s.phases[i].gate_result={passed:!0,approved_by:"trust",approved_at:w,feedback:null,verification:{conformance_score:100,coverage_percentage:100,missing_items:[],passed:!0},validation:{alignment_score:100,alignment_questions:[],passed:!0}},H(o,s),await O(e.directory,r);try{let k={type:"gate_approval",phase:i,stage:r.current_stage,details:`Auto-advanced by Trust Level ${a.current_level} for Tier ${c}`},h={workflowId:n,featureName:r.feature_name||n,projectPath:e.directory,sessionId:e.sessionId||"unknown",phase:i},v=Ve(k,h);le(v)}catch(k){console.error("[Olympus Quality Gate] Failed to capture auto-advance discovery:",k)}return{continue:!0}}let l,u;if(i==="inception")try{let w=(0,Oe.join)(e.directory,"aidlc-docs",n,"inception"),k=(0,Rr.readFileSync)((0,Oe.join)(w,"intent.md"),"utf-8");l=Lo(k,k,"intent-to-unit"),u=Cr[i]||[]}catch{l={conformance_score:0,coverage_percentage:0,missing_items:["Could not read inception artifacts for alignment check"],passed:!1},u=Cr[i]||[]}else l={conformance_score:0,coverage_percentage:0,missing_items:["Alignment check not yet implemented for this phase"],passed:!1},u=Cr[i]||[];let d={alignment_score:0,alignment_questions:u,passed:!1},p="";if(i==="inception"){let w=r.depth_score||s.depth_assessment?.total_score;w&&w>=21&&(s.artifacts.some(h=>h.type?.toLowerCase().includes("metis"))||(p=`
2134
+ [GATE_PENDING]`}}}if(mf(c,a.current_level)){Fe(o,{phase:i,action:"approved",actor:"trust",reason:`Auto-advanced by Trust Level ${a.current_level} for Tier ${c}`});let w=new Date().toISOString();s.phases[i].gate_result={passed:!0,approved_by:"trust",approved_at:w,feedback:null,verification:{conformance_score:100,coverage_percentage:100,missing_items:[],passed:!0},validation:{alignment_score:100,alignment_questions:[],passed:!0}},G(o,s),await A(e.directory,r);try{let _={type:"gate_approval",phase:i,stage:r.current_stage,details:`Auto-advanced by Trust Level ${a.current_level} for Tier ${c}`},h={workflowId:n,featureName:r.feature_name||n,projectPath:e.directory,sessionId:e.sessionId||"unknown",phase:i},v=qe(_,h);ue(v)}catch(_){console.error("[Olympus Quality Gate] Failed to capture auto-advance discovery:",_)}return{continue:!0}}let l,u;if(i==="inception")try{let w=(0,Oe.join)(e.directory,"aidlc-docs",n,"inception"),_=(0,Rr.readFileSync)((0,Oe.join)(w,"intent.md"),"utf-8");l=Lo(_,_,"intent-to-unit"),u=Cr[i]||[]}catch{l={conformance_score:0,coverage_percentage:0,missing_items:["Could not read inception artifacts for alignment check"],passed:!1},u=Cr[i]||[]}else l={conformance_score:0,coverage_percentage:0,missing_items:["Alignment check not yet implemented for this phase"],passed:!1},u=Cr[i]||[];let d={alignment_score:0,alignment_questions:u,passed:!1},p="";if(i==="inception"){let w=r.depth_score||s.depth_assessment?.total_score;w&&w>=21&&(s.artifacts.some(h=>h.type?.toLowerCase().includes("metis"))||(p=`
2135
2135
 
2136
- WARNING: DEEP workflow without Metis consultation detected. Metis blind-spot analysis is strongly recommended for complex workflows.`))}let f={passed:!1,approved_by:null,approved_at:null,feedback:null,verification:l,validation:d};try{let w=(0,Oe.join)(e.directory,"aidlc-docs",n),k=xw(w);f.content_checks=k,k.some(h=>!h.passed&&h.severity==="error")&&(f.passed=!1)}catch(w){console.error("[quality-gate] Gate 1 content check error:",w)}s.phases[i].gate_result=f,H(o,s),await O(e.directory,r);let m=c===3?"[BLOCKING - Acknowledgment Required] ":"",g=r.current_stage==="intent"?"Gate 1 (INTENT review)":r.current_stage==="complete"?"Gate 2 (INTENT review)":`${i} transition`;return{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`${m}STOP: ${g} requires approval.
2136
+ WARNING: DEEP workflow without Metis consultation detected. Metis blind-spot analysis is strongly recommended for complex workflows.`))}let f={passed:!1,approved_by:null,approved_at:null,feedback:null,verification:l,validation:d};try{let w=(0,Oe.join)(e.directory,"aidlc-docs",n),_=$w(w);f.content_checks=_,_.some(h=>!h.passed&&h.severity==="error")&&(f.passed=!1)}catch(w){console.error("[quality-gate] Gate 1 content check error:",w)}s.phases[i].gate_result=f,G(o,s),await A(e.directory,r);let m=c===3?"[BLOCKING - Acknowledgment Required] ":"",g=r.current_stage==="intent"?"Gate 1 (INTENT review)":r.current_stage==="complete"?"Gate 2 (INTENT review)":`${i} transition`;return{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`${m}STOP: ${g} requires approval.
2137
2137
 
2138
2138
  VERIFICATION: ${l.conformance_score}% conformance, ${l.coverage_percentage}% coverage.
2139
2139
  Missing: ${l.missing_items.join(", ")}
2140
2140
 
2141
2141
  VALIDATION: Review alignment questions:
2142
- ${u.map((w,k)=>`${k+1}. ${w.question}`).join(`
2142
+ ${u.map((w,_)=>`${_+1}. ${w.question}`).join(`
2143
2143
  `)}
2144
2144
 
2145
- Type "approve" to proceed or "reject <reason>" to block.${p}${ul(f.content_checks)}
2145
+ Type "approve" to proceed or "reject <reason>" to block.${p}${ml(f.content_checks)}
2146
2146
 
2147
- [GATE_PENDING]`}}}catch(t){return console.error("[Olympus Quality Gate] Error in qualityGateBlocker:",t),{continue:!0}}}async function Zx(e){try{let t=Qx(e);if(!e.directory)return{continue:!0};if(t.includes("--no-gates")||Jx(e.directory)){let n=await Js(e.directory);if(n){let{manifestPath:r}=n,o=W(r);if(o){let s=dl(o);if(s){let i=t.includes("--no-gates")?"flag":"config";Fe(r,{phase:s,action:"bypassed",actor:i,reason:i==="flag"?"--no-gates flag detected":"Quality gates disabled in config"}),o.phases[s].gate_result=null,o.phases[s].gate_bypassed=!0,o.phases[s].bypass_reason=i==="flag"?"--no-gates flag":"Config disabled",H(r,o),await O(e.directory,n.checkpoint)}}}return{continue:!0}}if(t.trim().toLowerCase().startsWith("approve")){let n=await Js(e.directory);if(!n)return{continue:!0};let{manifestPath:r}=n,o=W(r);if(!o)return{continue:!0};let s=dl(o);if(!s)return{continue:!0};let i=new Date().toISOString();o.phases[s].gate_result&&(o.phases[s].gate_result.passed=!0,o.phases[s].gate_result.approved_by="human",o.phases[s].gate_result.approved_at=i);let{checkpoint:a}=n;if(s==="construction"){if(a.current_stage==="code-generation"&&a.active_code_plan_path){let p=a.active_code_plan_path;Tt(r,p,"fulfilled");let f=o.artifacts.find(m=>m.id===p);f&&(f.reviewedBy="human");try{let m=sl(o,p);if(m){let g=al(e.directory,n.workflowId,m),y=(typeof a.risk_tier=="number"?a.risk_tier:a.risk_tier?.tier)||o.risk_tier?.tier||2;il(g,m,{boltId:p,boltTitle:f?.type||p,commandsExecuted:[],testResults:[],filesChanged:[],gateApprovedBy:"human",dualValidation:{parentConformance:o.phases.construction.gate_result?.verification?.conformance_score??0,rootConformance:0},riskTier:y})}}catch(m){console.error("[Olympus Quality Gate] Failed to generate validation report:",m)}try{let{isWorkflowComplete:m}=await Promise.resolve().then(()=>(Z(),vn)),g=W(r);g&&m(g)&&(a.current_phase="operations",a.current_stage="code-generation",jt(r,"construction","complete"),jt(r,"operations","in_progress"),await O(e.directory,a),console.log("[Olympus Quality Gate] All BOLTs fulfilled \u2014 auto-transitioning to Operations phase"))}catch(m){console.error("[Olympus Quality Gate] Failed to check workflow completion:",m)}}else if(a.current_stage==="unit"){let p=o.artifacts.filter(f=>f.stage==="unit");for(let f of p)Tt(r,f.id,"active"),f.reviewedBy="human"}}else{let p=o.artifacts.filter(f=>f.phase===s);for(let f of p)Tt(r,f.id,"active")}Fe(r,{phase:s,action:"approved",actor:"human",reason:null,content_checks:o.phases[s].gate_result?.content_checks});try{let p={type:"gate_approval",phase:s,stage:a.current_stage,details:`Gate approved for ${s} phase`},f={workflowId:n.workflowId,featureName:a.feature_name||n.workflowId,projectPath:e.directory,sessionId:e.sessionId||"unknown",phase:s},m=Ve(p,f);le(m)}catch(p){console.error("[Olympus Quality Gate] Failed to capture gate approval discovery:",p)}let c=be(e.directory),l=Fa(c,!0,!1);Na(l,e.directory),H(r,o),await O(e.directory,n.checkpoint),o.phases[s].gate_result?.passed&&(o.phases[s].gate_result=null,H(r,o));let u="",d=n.checkpoint.depth_score;return d&&d<=10?u=" SHALLOW depth: Skip UNIT decomposition, proceed directly to single BOLT generation.":d&&d>=21&&(u=" DEEP depth: Full UNIT + BOLT decomposition with design artifacts required."),{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:`Gate approved. Phase ${s} transition approved. Proceeding to next phase.${u}`}}}if(t.trim().toLowerCase().startsWith("reject")){let n=await Js(e.directory);if(!n)return{continue:!0};let{manifestPath:r}=n,o=W(r);if(!o)return{continue:!0};let s=dl(o);if(!s)return{continue:!0};let i=t.trim().substring(6).trim()||"No reason provided";o.phases[s].gate_result&&(o.phases[s].gate_result.passed=!1,o.phases[s].gate_result.feedback=i);let{checkpoint:a}=n,c="";if(s==="construction")if(a.current_stage==="code-generation"&&a.active_code_plan_path){let g=a.active_code_plan_path;Tt(r,g,"violated",i),c=`The reviewer rejected ${g}: ${i}. Revise and re-submit.`}else if(a.current_stage==="unit"){let g=o.artifacts.filter(y=>y.stage==="unit");for(let y of g)Tt(r,y.id,"violated",i);c=`The reviewer rejected UNIT decomposition: ${i}. Revise and re-submit.`}else{let g=o.artifacts.filter(y=>y.phase===s);for(let y of g)Tt(r,y.id,"violated",i)}else{let g=o.artifacts.filter(y=>y.phase===s);for(let y of g)Tt(r,y.id,"violated",i)}Fe(r,{phase:s,action:"rejected",actor:"human",reason:i,content_checks:o.phases[s].gate_result?.content_checks});try{let g={type:"gate_rejection",phase:s,stage:a.current_stage,details:i},y={workflowId:n.workflowId,featureName:a.feature_name||n.workflowId,projectPath:e.directory,sessionId:e.sessionId||"unknown",phase:s},w=Ve(g,y);le(w)}catch(g){console.error("[Olympus Quality Gate] Failed to capture gate rejection discovery:",g)}let l=be(e.directory),u=Fa(l,!1,!0);Na(u,e.directory),H(r,o),await O(e.directory,n.checkpoint);let d=zx(s,a.current_stage),p=s==="construction"&&a.current_stage==="code-generation"&&a.active_code_plan_path?a.active_code_plan_path:o.artifacts.find(g=>g.phase===s)?.id??`${s}-artifact`,f=o.gate_audit.filter(g=>g.phase===s&&g.action==="rejected").length,m;try{let g=await Rw(e.directory,o.workflow_id,{gateNumber:d,artifactId:p,rejectionReason:i,rejectedBy:"human",attemptNumber:f+1});m=`Gate ${d} rejected ${p}: ${i}.
2147
+ [GATE_PENDING]`}}}catch(t){return console.error("[Olympus Quality Gate] Error in qualityGateBlocker:",t),{continue:!0}}}async function fP(e){try{let t=dP(e);if(!e.directory)return{continue:!0};if(t.includes("--no-gates")||lP(e.directory)){let n=await Qs(e.directory);if(n){let{manifestPath:r}=n,o=W(r);if(o){let s=gl(o);if(s){let i=t.includes("--no-gates")?"flag":"config";Fe(r,{phase:s,action:"bypassed",actor:i,reason:i==="flag"?"--no-gates flag detected":"Quality gates disabled in config"}),o.phases[s].gate_result=null,o.phases[s].gate_bypassed=!0,o.phases[s].bypass_reason=i==="flag"?"--no-gates flag":"Config disabled",G(r,o),await A(e.directory,n.checkpoint)}}}return{continue:!0}}if(t.trim().toLowerCase().startsWith("approve")){let n=await Qs(e.directory);if(!n)return{continue:!0};let{manifestPath:r}=n,o=W(r);if(!o)return{continue:!0};let s=gl(o);if(!s)return{continue:!0};let i=new Date().toISOString();o.phases[s].gate_result&&(o.phases[s].gate_result.passed=!0,o.phases[s].gate_result.approved_by="human",o.phases[s].gate_result.approved_at=i);let{checkpoint:a}=n;if(s==="construction"){if(a.current_stage==="code-generation"&&a.active_code_plan_path){let p=a.active_code_plan_path;bt(r,p,"fulfilled");let f=o.artifacts.find(m=>m.id===p);f&&(f.reviewedBy="human");try{let m=ll(o,p);if(m){let g=dl(e.directory,n.workflowId,m),y=(typeof a.risk_tier=="number"?a.risk_tier:a.risk_tier?.tier)||o.risk_tier?.tier||2;ul(g,m,{boltId:p,boltTitle:f?.type||p,commandsExecuted:[],testResults:[],filesChanged:[],gateApprovedBy:"human",dualValidation:{parentConformance:o.phases.construction.gate_result?.verification?.conformance_score??0,rootConformance:0},riskTier:y})}}catch(m){console.error("[Olympus Quality Gate] Failed to generate validation report:",m)}try{let{isWorkflowComplete:m}=await Promise.resolve().then(()=>(Z(),vn)),g=W(r);g&&m(g)&&(a.current_phase="operations",a.current_stage="code-generation",jt(r,"construction","complete"),jt(r,"operations","in_progress"),await A(e.directory,a),console.log("[Olympus Quality Gate] All BOLTs fulfilled \u2014 auto-transitioning to Operations phase"))}catch(m){console.error("[Olympus Quality Gate] Failed to check workflow completion:",m)}}else if(a.current_stage==="unit"){let p=o.artifacts.filter(f=>f.stage==="unit");for(let f of p)bt(r,f.id,"active"),f.reviewedBy="human"}}else{let p=o.artifacts.filter(f=>f.phase===s);for(let f of p)bt(r,f.id,"active")}Fe(r,{phase:s,action:"approved",actor:"human",reason:null,content_checks:o.phases[s].gate_result?.content_checks});try{let p={type:"gate_approval",phase:s,stage:a.current_stage,details:`Gate approved for ${s} phase`},f={workflowId:n.workflowId,featureName:a.feature_name||n.workflowId,projectPath:e.directory,sessionId:e.sessionId||"unknown",phase:s},m=qe(p,f);ue(m)}catch(p){console.error("[Olympus Quality Gate] Failed to capture gate approval discovery:",p)}let c=Te(e.directory),l=fa(c,!0,!1);pa(l,e.directory),G(r,o),await A(e.directory,n.checkpoint),o.phases[s].gate_result?.passed&&(o.phases[s].gate_result=null,G(r,o));let u="",d=n.checkpoint.depth_score;return d&&d<=10?u=" SHALLOW depth: Skip UNIT decomposition, proceed directly to single BOLT generation.":d&&d>=21&&(u=" DEEP depth: Full UNIT + BOLT decomposition with design artifacts required."),{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:`Gate approved. Phase ${s} transition approved. Proceeding to next phase.${u}`}}}if(t.trim().toLowerCase().startsWith("reject")){let n=await Qs(e.directory);if(!n)return{continue:!0};let{manifestPath:r}=n,o=W(r);if(!o)return{continue:!0};let s=gl(o);if(!s)return{continue:!0};let i=t.trim().substring(6).trim()||"No reason provided";o.phases[s].gate_result&&(o.phases[s].gate_result.passed=!1,o.phases[s].gate_result.feedback=i);let{checkpoint:a}=n,c="";if(s==="construction")if(a.current_stage==="code-generation"&&a.active_code_plan_path){let g=a.active_code_plan_path;bt(r,g,"violated",i),c=`The reviewer rejected ${g}: ${i}. Revise and re-submit.`}else if(a.current_stage==="unit"){let g=o.artifacts.filter(y=>y.stage==="unit");for(let y of g)bt(r,y.id,"violated",i);c=`The reviewer rejected UNIT decomposition: ${i}. Revise and re-submit.`}else{let g=o.artifacts.filter(y=>y.phase===s);for(let y of g)bt(r,y.id,"violated",i)}else{let g=o.artifacts.filter(y=>y.phase===s);for(let y of g)bt(r,y.id,"violated",i)}Fe(r,{phase:s,action:"rejected",actor:"human",reason:i,content_checks:o.phases[s].gate_result?.content_checks});try{let g={type:"gate_rejection",phase:s,stage:a.current_stage,details:i},y={workflowId:n.workflowId,featureName:a.feature_name||n.workflowId,projectPath:e.directory,sessionId:e.sessionId||"unknown",phase:s},w=qe(g,y);ue(w)}catch(g){console.error("[Olympus Quality Gate] Failed to capture gate rejection discovery:",g)}let l=Te(e.directory),u=fa(l,!1,!0);pa(u,e.directory),G(r,o),await A(e.directory,n.checkpoint);let d=uP(s,a.current_stage),p=s==="construction"&&a.current_stage==="code-generation"&&a.active_code_plan_path?a.active_code_plan_path:o.artifacts.find(g=>g.phase===s)?.id??`${s}-artifact`,f=o.gate_audit.filter(g=>g.phase===s&&g.action==="rejected").length,m;try{let g=await Ow(e.directory,o.workflow_id,{gateNumber:d,artifactId:p,rejectionReason:i,rejectedBy:"human",attemptNumber:f+1});m=`Gate ${d} rejected ${p}: ${i}.
2148
2148
 
2149
- ${g.prompt}`}catch{m=c||`Gate rejected. Reason: ${i}. Revise artifacts before retrying.`}return{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:m}}}return{continue:!0}}catch(t){return console.error("[Olympus Quality Gate] Error in qualityGateApprover:",t),{continue:!0}}}function Iw(){P({name:"qualityGateBlocker",event:"PostToolUse",priority:80,matcher:"task",handler:Xx}),P({name:"qualityGateApprover",event:"UserPromptSubmit",priority:12,handler:Zx})}var eP=["explore","explore-medium","librarian","librarian-low","oracle","oracle-low","oracle-medium","momus","metis","multimodal-looker"];function Aw(e){return eP.includes(e)}var Ow=/(?:^|\s|&&|\|\||;)(?:>|>>|rm\s|mv\s|cp\s|mkdir\s|rmdir\s|touch\s|npm\s+install|pip\s+install|cargo\s+add|tee\s|dd\s|install\s|sed\s+-i|awk\s+-i|chmod\s|chown\s)/,Qs={debounceMs:1e4,mode:"soft",enabled:!0};Ge();function $w(){P({name:"agentRoleGuard",event:"PreToolUse",priority:5,matcher:"write|edit|multiedit|bash",handler:async e=>{try{if(!e.directory||!e.sessionId)return{continue:!0};let n=Q(e.directory,e.sessionId).pending_completion?.agent_used;if(!n)return{continue:!0};if(!Aw(n))return{continue:!0};let r=e.toolName;if(r==="write"||r==="edit"||r==="multiedit")return{continue:!1,stopReason:`Agent "${n}" is read-only and cannot perform ${r} operations. Use an agent like "olympian" or "frontend-engineer" for file modifications.`};if(r==="bash"){let s=e.toolInput?.command;if(typeof s=="string"&&Ow.test(s))return{continue:!1,stopReason:`Agent "${n}" is read-only and cannot execute bash commands that modify files. Detected write operation in: ${s.substring(0,100)}${s.length>100?"...":""}`}}return{continue:!0}}catch(t){return console.error("[Olympus Agent Role Guard] Error in handler:",t),{continue:!0}}}})}var Xs=require("child_process"),Zs=require("path"),xr=require("fs"),Dw=0,mn=null,gn=null;function Nw(e){let t=(0,Zs.join)(e,".olympus","config.json"),n={enabled:Qs.enabled,mode:Qs.mode,debounceMs:Qs.debounceMs};try{if((0,xr.existsSync)(t)){let r=(0,xr.readFileSync)(t,"utf8"),o=JSON.parse(r);if(o.hooks?.buildCheck){let s=o.hooks.buildCheck;typeof s.enabled=="boolean"&&(n.enabled=s.enabled),(s.mode==="soft"||s.mode==="strict")&&(n.mode=s.mode),typeof s.debounceMs=="number"&&s.debounceMs>0&&(n.debounceMs=s.debounceMs)}}}catch(r){console.error("[Olympus Build Check] Failed to load config:",r)}return n}function tP(e){let t=(0,Zs.join)(e,"node_modules",".bin","tsc"),n=process.platform==="win32"?`${t}.cmd`:t;if((0,xr.existsSync)(n))return n;try{let r=process.platform==="win32"?"where":"which",s=require("child_process").execSync(`${r} tsc`,{encoding:"utf8"}).trim().split(`
2150
- `)[0];if(s)return s}catch{}return null}function nP(){if(!gn||!gn.pid)return;let e=gn.pid;try{gn.kill("SIGTERM")}catch{if(process.platform==="win32")try{(0,Xs.exec)(`taskkill /PID ${e} /F`,n=>{n&&console.error("[Olympus Build Check] Failed to kill process with taskkill:",n)})}catch{}}gn=null}function Fw(){P({name:"buildCheckTrigger",event:"PostToolUse",priority:65,matcher:/write|edit|multiedit/i,handler:async e=>{try{if(!e.directory)return{continue:!0};let t=Nw(e.directory);if(!t.enabled)return{continue:!0};let n=Date.now();if(n-Dw<t.debounceMs)return{continue:!0};let r=(0,Zs.join)(e.directory,"tsconfig.json");if(!(0,xr.existsSync)(r))return{continue:!0};let o=tP(e.directory);if(!o)return{continue:!0};nP();try{let s=(0,Xs.spawn)(o,["--noEmit"],{cwd:e.directory,detached:!0,stdio:"pipe"});gn=s,Dw=n;let i="",a="";s.stdout&&s.stdout.on("data",c=>{i+=c.toString()}),s.stderr&&s.stderr.on("data",c=>{a+=c.toString()}),s.on("exit",c=>{let l=(i+a).trim();mn={passed:c===0,output:l,timestamp:Date.now()},gn=null}),s.on("error",c=>{console.error("[Olympus Build Check] tsc spawn error:",c),gn=null})}catch(s){console.error("[Olympus Build Check] Failed to spawn tsc:",s)}}catch(t){console.error("[Olympus Build Check] Error in buildCheckTrigger:",t)}return{continue:!0}}}),P({name:"buildCheckInjector",event:"PostToolUse",priority:66,handler:async e=>{try{if(!mn)return{continue:!0};let t=e.directory?Nw(e.directory):{mode:"soft"};if(mn.passed)return mn=null,{continue:!0};let n=mn.output.length>500?mn.output.substring(0,500)+`
2149
+ ${g.prompt}`}catch{m=c||`Gate rejected. Reason: ${i}. Revise artifacts before retrying.`}return{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:m}}}return{continue:!0}}catch(t){return console.error("[Olympus Quality Gate] Error in qualityGateApprover:",t),{continue:!0}}}function Nw(){P({name:"qualityGateBlocker",event:"PostToolUse",priority:80,matcher:"task",handler:pP}),P({name:"qualityGateApprover",event:"UserPromptSubmit",priority:12,handler:fP})}var mP=["explore","explore-medium","librarian","librarian-low","oracle","oracle-low","oracle-medium","momus","metis","multimodal-looker"];function Fw(e){return mP.includes(e)}var jw=/(?:^|\s|&&|\|\||;)(?:>|>>|rm\s|mv\s|cp\s|mkdir\s|rmdir\s|touch\s|npm\s+install|pip\s+install|cargo\s+add|tee\s|dd\s|install\s|sed\s+-i|awk\s+-i|chmod\s|chown\s)/,Zs={debounceMs:1e4,mode:"soft",enabled:!0};Be();function Mw(){P({name:"agentRoleGuard",event:"PreToolUse",priority:5,matcher:"write|edit|multiedit|bash",handler:async e=>{try{if(!e.directory||!e.sessionId)return{continue:!0};let n=Q(e.directory,e.sessionId).pending_completion?.agent_used;if(!n)return{continue:!0};if(!Fw(n))return{continue:!0};let r=e.toolName;if(r==="write"||r==="edit"||r==="multiedit")return{continue:!1,stopReason:`Agent "${n}" is read-only and cannot perform ${r} operations. Use an agent like "olympian" or "frontend-engineer" for file modifications.`};if(r==="bash"){let s=e.toolInput?.command;if(typeof s=="string"&&jw.test(s))return{continue:!1,stopReason:`Agent "${n}" is read-only and cannot execute bash commands that modify files. Detected write operation in: ${s.substring(0,100)}${s.length>100?"...":""}`}}return{continue:!0}}catch(t){return console.error("[Olympus Agent Role Guard] Error in handler:",t),{continue:!0}}}})}var ei=require("child_process"),ti=require("path"),xr=require("fs"),Lw=0,mn=null,gn=null;function Uw(e){let t=(0,ti.join)(e,".olympus","config.json"),n={enabled:Zs.enabled,mode:Zs.mode,debounceMs:Zs.debounceMs};try{if((0,xr.existsSync)(t)){let r=(0,xr.readFileSync)(t,"utf8"),o=JSON.parse(r);if(o.hooks?.buildCheck){let s=o.hooks.buildCheck;typeof s.enabled=="boolean"&&(n.enabled=s.enabled),(s.mode==="soft"||s.mode==="strict")&&(n.mode=s.mode),typeof s.debounceMs=="number"&&s.debounceMs>0&&(n.debounceMs=s.debounceMs)}}}catch(r){console.error("[Olympus Build Check] Failed to load config:",r)}return n}function gP(e){let t=(0,ti.join)(e,"node_modules",".bin","tsc"),n=process.platform==="win32"?`${t}.cmd`:t;if((0,xr.existsSync)(n))return n;try{let r=process.platform==="win32"?"where":"which",s=require("child_process").execSync(`${r} tsc`,{encoding:"utf8"}).trim().split(`
2150
+ `)[0];if(s)return s}catch{}return null}function hP(){if(!gn||!gn.pid)return;let e=gn.pid;try{gn.kill("SIGTERM")}catch{if(process.platform==="win32")try{(0,ei.exec)(`taskkill /PID ${e} /F`,n=>{n&&console.error("[Olympus Build Check] Failed to kill process with taskkill:",n)})}catch{}}gn=null}function Ww(){P({name:"buildCheckTrigger",event:"PostToolUse",priority:65,matcher:/write|edit|multiedit/i,handler:async e=>{try{if(!e.directory)return{continue:!0};let t=Uw(e.directory);if(!t.enabled)return{continue:!0};let n=Date.now();if(n-Lw<t.debounceMs)return{continue:!0};let r=(0,ti.join)(e.directory,"tsconfig.json");if(!(0,xr.existsSync)(r))return{continue:!0};let o=gP(e.directory);if(!o)return{continue:!0};hP();try{let s=(0,ei.spawn)(o,["--noEmit"],{cwd:e.directory,detached:!0,stdio:"pipe"});gn=s,Lw=n;let i="",a="";s.stdout&&s.stdout.on("data",c=>{i+=c.toString()}),s.stderr&&s.stderr.on("data",c=>{a+=c.toString()}),s.on("exit",c=>{let l=(i+a).trim();mn={passed:c===0,output:l,timestamp:Date.now()},gn=null}),s.on("error",c=>{console.error("[Olympus Build Check] tsc spawn error:",c),gn=null})}catch(s){console.error("[Olympus Build Check] Failed to spawn tsc:",s)}}catch(t){console.error("[Olympus Build Check] Error in buildCheckTrigger:",t)}return{continue:!0}}}),P({name:"buildCheckInjector",event:"PostToolUse",priority:66,handler:async e=>{try{if(!mn)return{continue:!0};let t=e.directory?Uw(e.directory):{mode:"soft"};if(mn.passed)return mn=null,{continue:!0};let n=mn.output.length>500?mn.output.substring(0,500)+`
2151
2151
  ... (truncated)`:mn.output,r=t.mode==="strict"?`[BUILD CHECK FAILED - BLOCKING]
2152
2152
 
2153
2153
  TypeScript compilation failed:
@@ -2160,16 +2160,16 @@ TypeScript compilation failed:
2160
2160
 
2161
2161
  ${n}
2162
2162
 
2163
- Consider fixing these errors.`;return mn=null,t.mode==="strict"?{continue:!1,stopReason:"Build check failed (strict mode)",hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:r}}:{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:r}}}catch(t){console.error("[Olympus Build Check] Error in buildCheckInjector:",t)}return{continue:!0}}})}Ge();me();Z();var Pr=require("path"),Ir=require("fs"),rP={prometheus:"inception"};async function oP(e){try{let t=await oe(e);if(t.length===0)return null;let n=null;for(let r of t){let o=await I(e,r);!o||o.status==="complete"||(!n||o.updated_at>n.updatedAt)&&(n={workflowId:r,checkpoint:o,updatedAt:o.updated_at})}return n?{workflowId:n.workflowId,checkpoint:n.checkpoint}:null}catch(t){return console.error("[Olympus Artifact Gate] Failed to find active workflow:",t),null}}function sP(e,t){let n=(0,Pr.join)(e,"inception"),r=e;switch(t){case"intent":{let o=(0,Pr.join)(n,"intent.md"),s=(0,Pr.join)(r,"intent.md"),i=(0,Ir.existsSync)(o)?o:s;return(0,Ir.existsSync)(i)?{artifactPath:i,referencePaths:[]}:null}default:return null}}async function iP(e,t,n){try{switch(e){case"intent":return await Go(t);default:return null}}catch(r){return console.error(`[Olympus Artifact Gate] Validation error for ${e}:`,r),null}}function aP(e,t){let n=e.toUpperCase();if(t.passed)return`[Artifact Validation] ${n} validation PASSED (${t.coverage_percentage}% coverage). Good work!`;let r=t.blocking_issues.map((o,s)=>` ${s+1}. ${o}`).join(`
2163
+ Consider fixing these errors.`;return mn=null,t.mode==="strict"?{continue:!1,stopReason:"Build check failed (strict mode)",hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:r}}:{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:r}}}catch(t){console.error("[Olympus Build Check] Error in buildCheckInjector:",t)}return{continue:!0}}})}Be();le();Z();var Pr=require("path"),Ar=require("fs"),yP={prometheus:"inception"};async function wP(e){try{let t=await oe(e);if(t.length===0)return null;let n=null;for(let r of t){let o=await I(e,r);!o||o.status==="complete"||(!n||o.updated_at>n.updatedAt)&&(n={workflowId:r,checkpoint:o,updatedAt:o.updated_at})}return n?{workflowId:n.workflowId,checkpoint:n.checkpoint}:null}catch(t){return console.error("[Olympus Artifact Gate] Failed to find active workflow:",t),null}}function _P(e,t){let n=(0,Pr.join)(e,"inception"),r=e;switch(t){case"intent":{let o=(0,Pr.join)(n,"intent.md"),s=(0,Pr.join)(r,"intent.md"),i=(0,Ar.existsSync)(o)?o:s;return(0,Ar.existsSync)(i)?{artifactPath:i,referencePaths:[]}:null}default:return null}}async function kP(e,t,n){try{switch(e){case"intent":return await Bo(t);default:return null}}catch(r){return console.error(`[Olympus Artifact Gate] Validation error for ${e}:`,r),null}}function SP(e,t){let n=e.toUpperCase();if(t.passed)return`[Artifact Validation] ${n} validation PASSED (${t.coverage_percentage}% coverage). Good work!`;let r=t.blocking_issues.map((o,s)=>` ${s+1}. ${o}`).join(`
2164
2164
  `);return`[Artifact Validation] WARNING: ${n} validation FAILED (${t.coverage_percentage}% coverage)
2165
2165
 
2166
2166
  Blocking issues:
2167
2167
  ${r}
2168
2168
 
2169
2169
  ${t.reviewer?`Reviewer: ${t.reviewer}
2170
- `:""}Please review and address these issues before proceeding to the next stage.`}async function cP(e){try{if(e.toolName!=="Task")return{continue:!0};if(!e.directory||!e.sessionId)return{continue:!0};let n=Q(e.directory,e.sessionId).pending_completion?.agent_used;if(!n)return{continue:!0};if(!rP[n])return{continue:!0};let o=await oP(e.directory);if(!o)return{continue:!0};let{workflowId:s,checkpoint:i}=o,a="intent",c=(0,Pr.join)(e.directory,"aidlc-docs",s);if(!(0,Ir.existsSync)(c))return console.error("[Olympus Artifact Gate] Workflow directory not found:",c),{continue:!0};let l=sP(c,a);if(!l)return console.error(`[Olympus Artifact Gate] Could not find artifact paths for ${a} in ${c}`),{continue:!0};let u=await iP(a,l.artifactPath,l.referencePaths);if(!u)return console.error(`[Olympus Artifact Gate] Validation failed to run for ${a}`),{continue:!0};let d=aP(a,u);if(a==="intent"&&u.passed)try{let p=(0,Ir.readFileSync)(l.artifactPath,"utf-8"),f=gs(p),m=i.manifest_path||(0,Pr.join)(e.directory,"aidlc-docs",s,"manifest.json"),g=W(m);g&&(g.depth_assessment=f,g.risk_tier=f.risk_tier,H(m,g)),i.depth_score=f.total_score,i.risk_tier=f.risk_tier.tier,await O(e.directory,i);let y=f.recommended_depth==="minimal"?"SHALLOW":f.recommended_depth==="standard"?"MEDIUM":"DEEP";d+=`
2170
+ `:""}Please review and address these issues before proceeding to the next stage.`}async function vP(e){try{if(e.toolName!=="Task")return{continue:!0};if(!e.directory||!e.sessionId)return{continue:!0};let n=Q(e.directory,e.sessionId).pending_completion?.agent_used;if(!n)return{continue:!0};if(!yP[n])return{continue:!0};let o=await wP(e.directory);if(!o)return{continue:!0};let{workflowId:s,checkpoint:i}=o,a="intent",c=(0,Pr.join)(e.directory,"aidlc-docs",s);if(!(0,Ar.existsSync)(c))return console.error("[Olympus Artifact Gate] Workflow directory not found:",c),{continue:!0};let l=_P(c,a);if(!l)return console.error(`[Olympus Artifact Gate] Could not find artifact paths for ${a} in ${c}`),{continue:!0};let u=await kP(a,l.artifactPath,l.referencePaths);if(!u)return console.error(`[Olympus Artifact Gate] Validation failed to run for ${a}`),{continue:!0};let d=SP(a,u);if(a==="intent"&&u.passed)try{let p=(0,Ar.readFileSync)(l.artifactPath,"utf-8"),f=ws(p),m=i.manifest_path||(0,Pr.join)(e.directory,"aidlc-docs",s,"manifest.json"),g=W(m);g&&(g.depth_assessment=f,g.risk_tier=f.risk_tier,G(m,g)),i.depth_score=f.total_score,i.risk_tier=f.risk_tier.tier,await A(e.directory,i);let y=f.recommended_depth==="minimal"?"SHALLOW":f.recommended_depth==="standard"?"MEDIUM":"DEEP";d+=`
2171
2171
 
2172
- [Depth Assessment] Score: ${f.total_score}/30 \u2192 ${y} | Risk Tier: ${f.risk_tier.tier}`}catch(p){console.error("[Olympus Artifact Gate] Failed to assess depth after INTENT validation:",p)}return{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:d}}}catch(t){return console.error("[Olympus Artifact Gate] Error in workflowArtifactGateHandler:",t),{continue:!0}}}function jw(){P({name:"workflowArtifactGate",event:"PostToolUse",priority:78,matcher:"task",handler:cP})}me();Z();var Ln=T(X(),1),ei=require("path"),Mw=require("child_process");function Lw(e){let t=(0,ei.join)(e,".olympus","config.json");try{if(Ln.existsSync(t)){let n=Ln.readJsonSync(t);if(n?.ciChecks)return{staticQuality:{enabled:n.ciChecks.staticQuality?.enabled!==!1,commands:n.ciChecks.staticQuality?.commands},security:{enabled:n.ciChecks.security?.enabled!==!1,auditLevel:n.ciChecks.security?.auditLevel||"moderate"},complexity:{enabled:n.ciChecks.complexity?.enabled!==!1,agent:n.ciChecks.complexity?.agent||"oracle-low"},customChecks:n.ciChecks.customChecks||[]}}}catch{}return lP()}function lP(){return{staticQuality:{enabled:!0},security:{enabled:!0,auditLevel:"moderate"},complexity:{enabled:!0,agent:"oracle-low"},customChecks:[]}}function uP(e){let t=[];try{let n=(0,ei.join)(e,"package.json");if(Ln.existsSync(n)){let o=Ln.readJsonSync(n)?.scripts||{};o.lint&&t.push("npm run lint"),o.typecheck&&t.push("npm run typecheck"),o.test&&t.push("npm test"),!o.typecheck&&Ln.existsSync((0,ei.join)(e,"tsconfig.json"))&&t.push("npx tsc --noEmit")}}catch{}return t}function pl(e,t,n,r){let o=Date.now();try{let s=(0,Mw.execSync)(e,{cwd:t,timeout:12e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return{name:n,layer:r,passed:!0,command:e,exitCode:0,stdout:(s||"").substring(0,2e3),stderr:"",duration_ms:Date.now()-o}}catch(s){return{name:n,layer:r,passed:!1,command:e,exitCode:s.status||1,stdout:(s.stdout||"").substring(0,2e3),stderr:(s.stderr||"").substring(0,2e3),duration_ms:Date.now()-o}}}function Uw(e,t){let n=[],r=Date.now();if(t.staticQuality.enabled){let s=t.staticQuality.commands||uP(e);for(let i of s)n.push(pl(i,e,`Static: ${i}`,"static-quality"))}if(t.security.enabled){let s=t.security.auditLevel||"moderate";n.push(pl(`npm audit --audit-level=${s}`,e,"Security: npm audit","security"))}if(t.complexity.enabled&&n.push({name:"Complexity: AI review",layer:"complexity",passed:!0,command:`dispatch ${t.complexity.agent||"oracle-low"}`,exitCode:0,stdout:"AI complexity review dispatched",stderr:"",duration_ms:0}),t.customChecks)for(let s of t.customChecks)n.push(pl(s.command,e,`Custom: ${s.name}`,"custom"));let o=n.filter(s=>!s.passed).map(s=>s.name);return{allPassed:o.length===0,results:n,totalDuration_ms:Date.now()-r,failedChecks:o}}function Ww(e){let t=e.allPassed?"CI Review Pipeline: ALL CHECKS PASSED":`CI Review Pipeline: ${e.failedChecks.length} CHECK(S) FAILED`,n=e.results.map(r=>{let s=`[${r.passed?"PASS":"FAIL"}] ${r.name}`;return r.passed||(s+=`
2172
+ [Depth Assessment] Score: ${f.total_score}/30 \u2192 ${y} | Risk Tier: ${f.risk_tier.tier}`}catch(p){console.error("[Olympus Artifact Gate] Failed to assess depth after INTENT validation:",p)}return{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:d}}}catch(t){return console.error("[Olympus Artifact Gate] Error in workflowArtifactGateHandler:",t),{continue:!0}}}function Bw(){P({name:"workflowArtifactGate",event:"PostToolUse",priority:78,matcher:"task",handler:vP})}le();Z();var Ln=b(X(),1),ni=require("path"),Gw=require("child_process");function Hw(e){let t=(0,ni.join)(e,".olympus","config.json");try{if(Ln.existsSync(t)){let n=Ln.readJsonSync(t);if(n?.ciChecks)return{staticQuality:{enabled:n.ciChecks.staticQuality?.enabled!==!1,commands:n.ciChecks.staticQuality?.commands},security:{enabled:n.ciChecks.security?.enabled!==!1,auditLevel:n.ciChecks.security?.auditLevel||"moderate"},complexity:{enabled:n.ciChecks.complexity?.enabled!==!1,agent:n.ciChecks.complexity?.agent||"oracle-low"},customChecks:n.ciChecks.customChecks||[]}}}catch{}return bP()}function bP(){return{staticQuality:{enabled:!0},security:{enabled:!0,auditLevel:"moderate"},complexity:{enabled:!0,agent:"oracle-low"},customChecks:[]}}function TP(e){let t=[];try{let n=(0,ni.join)(e,"package.json");if(Ln.existsSync(n)){let o=Ln.readJsonSync(n)?.scripts||{};o.lint&&t.push("npm run lint"),o.typecheck&&t.push("npm run typecheck"),o.test&&t.push("npm test"),!o.typecheck&&Ln.existsSync((0,ni.join)(e,"tsconfig.json"))&&t.push("npx tsc --noEmit")}}catch{}return t}function hl(e,t,n,r){let o=Date.now();try{let s=(0,Gw.execSync)(e,{cwd:t,timeout:12e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return{name:n,layer:r,passed:!0,command:e,exitCode:0,stdout:(s||"").substring(0,2e3),stderr:"",duration_ms:Date.now()-o}}catch(s){return{name:n,layer:r,passed:!1,command:e,exitCode:s.status||1,stdout:(s.stdout||"").substring(0,2e3),stderr:(s.stderr||"").substring(0,2e3),duration_ms:Date.now()-o}}}function Vw(e,t){let n=[],r=Date.now();if(t.staticQuality.enabled){let s=t.staticQuality.commands||TP(e);for(let i of s)n.push(hl(i,e,`Static: ${i}`,"static-quality"))}if(t.security.enabled){let s=t.security.auditLevel||"moderate";n.push(hl(`npm audit --audit-level=${s}`,e,"Security: npm audit","security"))}if(t.complexity.enabled&&n.push({name:"Complexity: AI review",layer:"complexity",passed:!0,command:`dispatch ${t.complexity.agent||"oracle-low"}`,exitCode:0,stdout:"AI complexity review dispatched",stderr:"",duration_ms:0}),t.customChecks)for(let s of t.customChecks)n.push(hl(s.command,e,`Custom: ${s.name}`,"custom"));let o=n.filter(s=>!s.passed).map(s=>s.name);return{allPassed:o.length===0,results:n,totalDuration_ms:Date.now()-r,failedChecks:o}}function qw(e){let t=e.allPassed?"CI Review Pipeline: ALL CHECKS PASSED":`CI Review Pipeline: ${e.failedChecks.length} CHECK(S) FAILED`,n=e.results.map(r=>{let s=`[${r.passed?"PASS":"FAIL"}] ${r.name}`;return r.passed||(s+=`
2173
2173
  Command: ${r.command}`,s+=`
2174
2174
  Exit code: ${r.exitCode}`,r.stderr&&(s+=`
2175
2175
  Error: ${r.stderr.substring(0,500)}`)),s}).join(`
@@ -2177,7 +2177,7 @@ ${t.reviewer?`Reviewer: ${t.reviewer}
2177
2177
 
2178
2178
  ${n}
2179
2179
 
2180
- Total duration: ${e.totalDuration_ms}ms`}var Gw=require("fs");async function dP(e){try{if(e.toolName!=="Task")return{continue:!0};if(!e.directory||!e.sessionId)return{continue:!0};let t=await oe(e.directory);if(t.length===0)return{continue:!0};let n=null,r="";for(let f of t){let m=await I(e.directory,f);if(m&&m.status!=="complete"){n=m,r=m.manifest_path||"";break}}if(!n)return{continue:!0};if(n.current_phase!=="construction"||n.current_stage!=="code-generation"||!n.active_code_plan_path)return{continue:!0};let o=n.active_code_plan_path,s=W(r);if(!s)return{continue:!0};let i=Lw(e.directory),a=Uw(e.directory,i),c=s.artifacts.find(f=>f.id===o),l=[],u=[];if(c)try{let f=(0,Gw.readFileSync)(c.path,"utf-8");l=ea(f,c.path).map(m=>m.message),u=ta(f,c.path).map(m=>m.message)}catch{}let d=Ww(a),p="";return l.length>0&&(p=`
2180
+ Total duration: ${e.totalDuration_ms}ms`}var Yw=require("fs");async function EP(e){try{if(e.toolName!=="Task")return{continue:!0};if(!e.directory||!e.sessionId)return{continue:!0};let t=await oe(e.directory);if(t.length===0)return{continue:!0};let n=null,r="";for(let f of t){let m=await I(e.directory,f);if(m&&m.status!=="complete"){n=m,r=m.manifest_path||"";break}}if(!n)return{continue:!0};if(n.current_phase!=="construction"||n.current_stage!=="code-generation"||!n.active_code_plan_path)return{continue:!0};let o=n.active_code_plan_path,s=W(r);if(!s)return{continue:!0};let i=Hw(e.directory),a=Vw(e.directory,i),c=s.artifacts.find(f=>f.id===o),l=[],u=[];if(c)try{let f=(0,Yw.readFileSync)(c.path,"utf-8");l=na(f,c.path).map(m=>m.message),u=ra(f,c.path).map(m=>m.message)}catch{}let d=qw(a),p="";return l.length>0&&(p=`
2181
2181
 
2182
2182
  SECURITY FINDINGS:
2183
2183
  ${l.map(f=>` - ${f}`).join(`
@@ -2189,41 +2189,41 @@ ${u.map(f=>` - ${f}`).join(`
2189
2189
 
2190
2190
  ${d}${p}
2191
2191
 
2192
- Fix the failing checks and re-run the BOLT execution.`}}}catch(t){return console.error("[Olympus CI Review] Error in ciReviewPipeline:",t),{continue:!0}}}function Bw(){P({name:"ciReviewPipeline",event:"PostToolUse",priority:79,matcher:"task",handler:dP})}we();function Hw(e,t=2){let r=e.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter(s=>s.length>0);if(r.length<t)return new Set(r);let o=new Set;for(let s=0;s<=r.length-t;s++)o.add(r.slice(s,s+t).join(" "));return o}function fl(e,t){let n=Hw(e),r=Hw(t),o=new Set([...n].filter(i=>r.has(i))),s=new Set([...n,...r]);return s.size>0?o.size/s.size:0}function pP(e,t=.4){let n=[],r=new Set;for(let o of e){if(r.has(o.id))continue;let s=[o];r.add(o.id);for(let i of e){if(r.has(i.id))continue;fl(o.user_message,i.user_message)>=t&&(s.push(i),r.add(i.id))}n.push(s)}return n}function Vw(e,t=3,n=1e3,r){let i=(r?e.filter(c=>c.project_path===r):e).slice(-n).filter(c=>c.feedback_category==="correction"||c.feedback_category==="clarification"||c.feedback_category==="explicit_preference");return pP(i).filter(c=>c.length>=t).map(c=>{let l=c.sort((m,g)=>new Date(g.timestamp).getTime()-new Date(m.timestamp).getTime())[0],u=c.reduce((m,g)=>m+g.confidence,0)/c.length,p=new Set(c.map(m=>m.project_path)).size===1?"project":"global",f=mP(c);return{pattern:fP(c),confidence:u,evidence_count:c.length,evidence_examples:c.slice(0,3).map(m=>m.user_message.substring(0,150)),scope:p,category:f}})}function fP(e){let t=new Map;for(let o of e){let s=o.user_message.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter(i=>i.length>3);for(let i of s)t.set(i,(t.get(i)||0)+1)}let n=[...t.entries()].sort((o,s)=>s[1]-o[1]).slice(0,3).map(([o])=>o);return e[0].user_message.substring(0,100)+(n.length>0?` [themes: ${n.join(", ")}]`:"")}function mP(e){let t=e.map(n=>n.user_message).join(" ").toLowerCase();return/typescript|eslint|prettier|format|indent|naming/i.test(t)?"style":/test|build|npm|yarn|run|command|install/i.test(t)?"tooling":/verbose|brief|explain|detail|ask|confirm/i.test(t)?"communication":"behavior"}var gP={verbosity:"unknown",autonomy:"unknown",explanation_depth:"unknown",explicit_rules:[],inferred_preferences:[],recurring_corrections:[],last_updated:new Date().toISOString()},hP=30;function yP(e){let t=e.filter(r=>r.feedback_category==="explicit_preference"),n=[];for(let r of t){let o=r.user_message.match(/always\s+(.+?)(?:\.|$)/i),s=r.user_message.match(/never\s+(.+?)(?:\.|$)/i);o&&n.push(`Always: ${o[1].trim()}`),s&&n.push(`Never: ${s[1].trim()}`)}return[...new Set(n)]}function wP(e){let t=e.filter(r=>/too (long|verbose|much|wordy)/i.test(r.user_message)).length,n=e.filter(r=>/more (detail|info|explanation)|too (brief|short)/i.test(r.user_message)).length;return t>=3&&t>n?"concise":n>=3&&n>t?"detailed":"unknown"}function kP(e){let t=e.filter(r=>/ask (me )?(first|before)|don't assume|confirm/i.test(r.user_message)).length,n=e.filter(r=>/just (do|make|fix)|don't ask|stop asking/i.test(r.user_message)).length;return t>=3&&t>n?"ask_first":n>=3&&n>t?"just_do_it":t>=2&&n>=2?"balanced":"unknown"}function qw(e,t,n,r){let o={...e},s=r??t.find(f=>f.project_path)?.project_path,i=yP(t),a=new Set(o.explicit_rules.map(f=>f.rule)),c=i.filter(f=>!a.has(f)).map(f=>({rule:f,created_at:new Date().toISOString(),...s?{project_path:s}:{}}));o.explicit_rules=[...o.explicit_rules,...c];let l=wP(t);l!=="unknown"&&(o.verbosity=l);let u=kP(t);u!=="unknown"&&(o.autonomy=u);let d=n.filter(f=>f.confidence>.7&&f.scope==="global").map(f=>f.pattern);o.inferred_preferences=[...new Set([...o.inferred_preferences,...d])];for(let f of n){let m=o.recurring_corrections.find(g=>fl(g.pattern,f.pattern)>.5);m?(m.count=f.evidence_count,m.last_seen=new Date().toISOString(),m.examples=f.evidence_examples):o.recurring_corrections.push({pattern:f.pattern,count:f.evidence_count,last_seen:new Date().toISOString(),examples:f.evidence_examples})}let p=Date.now();if(o.recurring_corrections=o.recurring_corrections.filter(f=>{if(!f.last_seen)return!0;let m=Date.parse(f.last_seen);return isNaN(m)?!0:p-m<=hP*864e5}),n.length>0){let f=new Set(n.map(m=>m.pattern));o.inferred_preferences=o.inferred_preferences.filter(m=>f.has(m))}return o.last_updated=new Date().toISOString(),o}function Yw(){return{...gP,last_updated:new Date().toISOString()}}var ko=require("path"),Ar=require("fs"),_P=3,SP=10;function vP(e){let t=(0,ko.join)(e,"feedback-log.jsonl"),n=(0,ko.join)(e,"agent-performance.json");if(!(0,Ar.existsSync)(t))return!1;if(!(0,Ar.existsSync)(n))return!0;try{let r=(0,Ar.statSync)(t),o=(0,Ar.statSync)(n);return r.mtime>o.mtime}catch(r){return console.error("[Olympus Learning Aggregation] Failed to check file times:",r),!0}}function Kw(){P({name:"learningAggregation",event:"Stop",priority:95,handler:async e=>{try{if(!e.directory)return{continue:!0};let t=de();if(!vP(t))return{continue:!0};let n=Co();if(n.length<_P)return{continue:!0};let r=new Set;for(let d of n)d.agent_used&&r.add(d.agent_used);let o=Array.from(r);if(o.length===0)return{continue:!0};let s={};for(let d of o){let p=Ro(d,n);p&&(s[d]=p)}let i=(0,ko.join)(t,"agent-performance.json");at(i,s);let a=(0,ko.join)(t,"user-preferences.json"),c=ke(a,Yw()),l=[];if(n.length>=SP)try{l=Vw(n)}catch(d){console.error("[Olympus Learning Aggregation] Pattern extraction failed:",d)}let u=qw(c,n,l);at(a,u)}catch(t){console.error("[Olympus Learning Aggregation] Error in aggregation handler:",t)}return{continue:!0}}})}var gl=["discovery","inception","construction","operations"],TP={draft:"o",active:"+",fulfilled:"++",violated:"X",stale:"!"},EP={0:"Baseline",1:"Earned",2:"Extended",3:"Trusted"};function Jw(e,t=null,n=null){let r=bP(e),o=RP(e),s=xP(e.risks),i=PP(e.gate_audit),a=IP(t),c=AP(e.alignment_checks),l=OP(e.depth_assessment),u=$P(e.risk_tier),d=NP(e,r),p=DP(e),f=n?.inception_stages?jP(n.inception_stages,n.current_inception_stage):null,m=[`# Workflow Status: ${e.feature_name}`,`ID: ${e.workflow_id}`,"",d,"","## Phase Progress",...r.map(g=>CP(g)),"",...f?[f,""]:[],p,l,u,a,"","## Artifacts",o,"","## Alignment",c,"","## Risk Summary",s,"","## Gate Audit",i].filter(g=>g!==null).join(`
2193
- `);return{summary:d,phaseProgress:r,artifactTree:o,riskSummary:s,gateSummary:i,trustDisplay:a,alignmentSummary:c,fullReport:m}}function bP(e){return gl.map(t=>{let n=e.phases[t],r=e.artifacts.filter(a=>a.phase===t),o=r.length;if(o===0)return{phase:t,percentage:n.status==="complete"?100:0,status:n.status,artifactCount:0};let s=r.filter(a=>a.contract_status==="active"||a.contract_status==="fulfilled").length,i=Math.round(s/o*100);return{phase:t,percentage:i,status:n.status,artifactCount:o}})}function CP(e){let n=Math.round(e.percentage/100*20),r=20-n,o="=".repeat(n)+"-".repeat(r);return`${(e.phase.charAt(0).toUpperCase()+e.phase.slice(1)).padEnd(8)} [${o}] ${String(e.percentage).padStart(3)}% (${e.status}) ${e.artifactCount} artifacts`}function RP(e){let t=[];for(let n of gl){let r=e.artifacts.filter(i=>i.phase===n);if(r.length===0)continue;let o=n.charAt(0).toUpperCase()+n.slice(1);t.push(`[${o}]`);let s=new Map;for(let i of r){let a=i.stage;s.has(a)||s.set(a,[]),s.get(a).push(i)}for(let[i,a]of s){t.push(` ${i}/`);for(let c of a){let l=TP[c.contract_status]??"?",u=c.validation_passed===!0?"v":c.validation_passed===!1?"x":"-";t.push(` [${l}] ${c.id} (${c.type}) [${u}]`)}}}return t.join(`
2194
- `)}function xP(e){if(e.length===0)return"No risks registered";let t=e.filter(a=>a.status==="open").length,n=e.filter(a=>a.status==="mitigated").length,r=e.filter(a=>a.status==="accepted").length,o=e.filter(a=>a.status==="closed").length,s=[`Total: ${e.length} | Open: ${t} | Mitigated: ${n} | Accepted: ${r} | Closed: ${o}`],i=e.filter(a=>a.status==="open");for(let a of i)s.push(` [OPEN] ${a.id}: ${a.description} (${a.likelihood}/${a.impact})`);return s.join(`
2195
- `)}function PP(e){if(e.length===0)return"No gate transitions recorded";let t=e.filter(s=>s.action==="approved").length,n=e.filter(s=>s.action==="rejected").length,r=e.filter(s=>s.action==="bypassed").length,o=[`Total: ${e.length} | Approved: ${t} | Rejected: ${n} | Bypassed: ${r}`];for(let s of e){let i=s.phase.charAt(0).toUpperCase()+s.phase.slice(1);o.push(` [${s.action.toUpperCase()}] ${i} by ${s.actor}${s.reason?": "+s.reason:""}`)}return o.join(`
2196
- `)}function IP(e){if(!e)return"Trust: Not initialized";let t=EP[e.current_level]??"Unknown";return[`Trust Level ${e.current_level}: ${t}`,` Transitions: ${e.total_transitions} | Rejections: ${e.rejection_count} (${(e.rejection_rate*100).toFixed(1)}%) | Incidents: ${e.incident_count}`].join(`
2197
- `)}function AP(e){if(e.length===0)return"No alignment checks recorded";let t=e.filter(o=>o.alignment_passed).length,n=e.filter(o=>!o.alignment_passed).length,r=[`Total: ${e.length} | Passed: ${t} | Failed: ${n}`];for(let o of e){let s=o.alignment_passed?"PASS":"FAIL",i=o.verification.conformance_score,a=o.verification.passed?"v":"x",c=o.validation.passed?"v":"x";r.push(` [${s}] ${o.source_artifact_id} -> ${o.target_artifact_id}: verification=${i}% [${a}] validation [${c}]`)}return r.join(`
2198
- `)}function OP(e){return e?`Depth: ${e.recommended_depth} (score: ${e.total_score}/30)${e.skip_units?" [skip-units]":""}`:"Depth: Not assessed"}function $P(e){return e?`Risk Tier: ${e.tier} (${e.rationale})`:"Risk Tier: Not classified"}function DP(e){let t=e.artifacts.filter(o=>o.stage==="code-generation"),n=t.length;return n===0?"Bolts: 0/0":`Bolts: ${t.filter(o=>o.contract_status==="active"||o.contract_status==="fulfilled").length}/${n} complete`}function NP(e,t){let n=e.artifacts.length,r=t.filter(s=>s.status!=="not_started");return`${t.filter(s=>s.percentage===100&&s.status==="complete").length}/${gl.length} phases complete | ${n} artifacts total`}var ml=["workspace-detection","reverse-engineering","requirements-analysis","user-stories","workflow-planning","application-design","units-generation"],FP={"workspace-detection":"Workspace Detection","reverse-engineering":"Reverse Engineering","requirements-analysis":"Requirements Analysis","user-stories":"User Stories","workflow-planning":"Workflow Planning","application-design":"Application Design","units-generation":"Units Generation"};function jP(e,t){let n=ml.length,r=ml.filter(l=>e[l]?.status==="completed").length,o=Math.round(r/n*100),s=10,i=Math.round(o/100*s),c=[`Inception [${i>=s?"=".repeat(s):"=".repeat(i)+">"+"-".repeat(s-i-1)}] ${o}% (${r}/${n} stages)`];for(let l of ml){let u=e[l],d=FP[l];if(!u){c.push(` [ ] ${d}`);continue}if(u.status==="completed")c.push(` [x] ${d}`);else if(u.status==="skipped"){let p=u.skip_reason?` (${u.skip_reason})`:" (skipped)";c.push(` [-] ${d}${p}`)}else u.status==="in_progress"||l===t?c.push(` [ ] ${d} <- current`):c.push(` [ ] ${d}`)}return c.join(`
2199
- `)}Z();cn();me();var zw=T(require("path"),1);function Qw(){P({name:"workflowStatusReporter",event:"UserPromptSubmit",priority:6,handler:async e=>{try{let t=e.directory||process.cwd(),n=e.prompt||"",o=(e.parts||[]).map(f=>f.text||"").join(" ")||n;if(!(o.includes("Show status of all active structured workflows")||o.includes("workflow-status")))return{continue:!0};let i=await oe(t),a=null;for(let f of i){let m=await I(t,f);if(m&&m.status!=="complete"&&m.status!=="archived"&&m.status!=="deferred"){a=f;break}}if(!a)return{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:"<workflow-status>\nNo active workflows found. Start one with `/plan <description>`\n</workflow-status>"}};let c=zw.join(t,"aidlc-docs",a,"manifest.json"),l=W(c);if(!l){let f=await I(t,a),m=f?.current_phase||"unknown",g=f?.current_stage||"unknown";return{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:`<workflow-status>
2192
+ Fix the failing checks and re-run the BOLT execution.`}}}catch(t){return console.error("[Olympus CI Review] Error in ciReviewPipeline:",t),{continue:!0}}}function Kw(){P({name:"ciReviewPipeline",event:"PostToolUse",priority:79,matcher:"task",handler:EP})}we();function Jw(e,t=2){let r=e.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter(s=>s.length>0);if(r.length<t)return new Set(r);let o=new Set;for(let s=0;s<=r.length-t;s++)o.add(r.slice(s,s+t).join(" "));return o}function yl(e,t){let n=Jw(e),r=Jw(t),o=new Set([...n].filter(i=>r.has(i))),s=new Set([...n,...r]);return s.size>0?o.size/s.size:0}function CP(e,t=.4){let n=[],r=new Set;for(let o of e){if(r.has(o.id))continue;let s=[o];r.add(o.id);for(let i of e){if(r.has(i.id))continue;yl(o.user_message,i.user_message)>=t&&(s.push(i),r.add(i.id))}n.push(s)}return n}function zw(e,t=3,n=1e3,r){let i=(r?e.filter(c=>c.project_path===r):e).slice(-n).filter(c=>c.feedback_category==="correction"||c.feedback_category==="clarification"||c.feedback_category==="explicit_preference");return CP(i).filter(c=>c.length>=t).map(c=>{let l=c.sort((m,g)=>new Date(g.timestamp).getTime()-new Date(m.timestamp).getTime())[0],u=c.reduce((m,g)=>m+g.confidence,0)/c.length,p=new Set(c.map(m=>m.project_path)).size===1?"project":"global",f=xP(c);return{pattern:RP(c),confidence:u,evidence_count:c.length,evidence_examples:c.slice(0,3).map(m=>m.user_message.substring(0,150)),scope:p,category:f}})}function RP(e){let t=new Map;for(let o of e){let s=o.user_message.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter(i=>i.length>3);for(let i of s)t.set(i,(t.get(i)||0)+1)}let n=[...t.entries()].sort((o,s)=>s[1]-o[1]).slice(0,3).map(([o])=>o);return e[0].user_message.substring(0,100)+(n.length>0?` [themes: ${n.join(", ")}]`:"")}function xP(e){let t=e.map(n=>n.user_message).join(" ").toLowerCase();return/typescript|eslint|prettier|format|indent|naming/i.test(t)?"style":/test|build|npm|yarn|run|command|install/i.test(t)?"tooling":/verbose|brief|explain|detail|ask|confirm/i.test(t)?"communication":"behavior"}var PP={verbosity:"unknown",autonomy:"unknown",explanation_depth:"unknown",explicit_rules:[],inferred_preferences:[],recurring_corrections:[],last_updated:new Date().toISOString()},AP=30;function IP(e){let t=e.filter(r=>r.feedback_category==="explicit_preference"),n=[];for(let r of t){let o=r.user_message.match(/always\s+(.+?)(?:\.|$)/i),s=r.user_message.match(/never\s+(.+?)(?:\.|$)/i);o&&n.push(`Always: ${o[1].trim()}`),s&&n.push(`Never: ${s[1].trim()}`)}return[...new Set(n)]}function OP(e){let t=e.filter(r=>/too (long|verbose|much|wordy)/i.test(r.user_message)).length,n=e.filter(r=>/more (detail|info|explanation)|too (brief|short)/i.test(r.user_message)).length;return t>=3&&t>n?"concise":n>=3&&n>t?"detailed":"unknown"}function $P(e){let t=e.filter(r=>/ask (me )?(first|before)|don't assume|confirm/i.test(r.user_message)).length,n=e.filter(r=>/just (do|make|fix)|don't ask|stop asking/i.test(r.user_message)).length;return t>=3&&t>n?"ask_first":n>=3&&n>t?"just_do_it":t>=2&&n>=2?"balanced":"unknown"}function Qw(e,t,n,r){let o={...e},s=r??t.find(f=>f.project_path)?.project_path,i=IP(t),a=new Set(o.explicit_rules.map(f=>f.rule)),c=i.filter(f=>!a.has(f)).map(f=>({rule:f,created_at:new Date().toISOString(),...s?{project_path:s}:{}}));o.explicit_rules=[...o.explicit_rules,...c];let l=OP(t);l!=="unknown"&&(o.verbosity=l);let u=$P(t);u!=="unknown"&&(o.autonomy=u);let d=n.filter(f=>f.confidence>.7&&f.scope==="global").map(f=>f.pattern);o.inferred_preferences=[...new Set([...o.inferred_preferences,...d])];for(let f of n){let m=o.recurring_corrections.find(g=>yl(g.pattern,f.pattern)>.5);m?(m.count=f.evidence_count,m.last_seen=new Date().toISOString(),m.examples=f.evidence_examples):o.recurring_corrections.push({pattern:f.pattern,count:f.evidence_count,last_seen:new Date().toISOString(),examples:f.evidence_examples})}let p=Date.now();if(o.recurring_corrections=o.recurring_corrections.filter(f=>{if(!f.last_seen)return!0;let m=Date.parse(f.last_seen);return isNaN(m)?!0:p-m<=AP*864e5}),n.length>0){let f=new Set(n.map(m=>m.pattern));o.inferred_preferences=o.inferred_preferences.filter(m=>f.has(m))}return o.last_updated=new Date().toISOString(),o}function Xw(){return{...PP,last_updated:new Date().toISOString()}}var _o=require("path"),Ir=require("fs"),DP=3,NP=10;function FP(e){let t=(0,_o.join)(e,"feedback-log.jsonl"),n=(0,_o.join)(e,"agent-performance.json");if(!(0,Ir.existsSync)(t))return!1;if(!(0,Ir.existsSync)(n))return!0;try{let r=(0,Ir.statSync)(t),o=(0,Ir.statSync)(n);return r.mtime>o.mtime}catch(r){return console.error("[Olympus Learning Aggregation] Failed to check file times:",r),!0}}function Zw(){P({name:"learningAggregation",event:"Stop",priority:95,handler:async e=>{try{if(!e.directory)return{continue:!0};let t=pe();if(!FP(t))return{continue:!0};let n=Co();if(n.length<DP)return{continue:!0};let r=new Set;for(let d of n)d.agent_used&&r.add(d.agent_used);let o=Array.from(r);if(o.length===0)return{continue:!0};let s={};for(let d of o){let p=Ro(d,n);p&&(s[d]=p)}let i=(0,_o.join)(t,"agent-performance.json");at(i,s);let a=(0,_o.join)(t,"user-preferences.json"),c=_e(a,Xw()),l=[];if(n.length>=NP)try{l=zw(n)}catch(d){console.error("[Olympus Learning Aggregation] Pattern extraction failed:",d)}let u=Qw(c,n,l);at(a,u)}catch(t){console.error("[Olympus Learning Aggregation] Error in aggregation handler:",t)}return{continue:!0}}})}var _l=["discovery","inception","construction","operations"],jP={draft:"o",active:"+",fulfilled:"++",violated:"X",stale:"!"},MP={0:"Baseline",1:"Earned",2:"Extended",3:"Trusted"};function e_(e,t=null,n=null){let r=LP(e),o=WP(e),s=BP(e.risks),i=GP(e.gate_audit),a=HP(t),c=VP(e.alignment_checks),l=qP(e.depth_assessment),u=YP(e.risk_tier),d=JP(e,r),p=KP(e),f=n?.inception_stages?QP(n.inception_stages,n.current_inception_stage):null,m=[`# Workflow Status: ${e.feature_name}`,`ID: ${e.workflow_id}`,"",d,"","## Phase Progress",...r.map(g=>UP(g)),"",...f?[f,""]:[],p,l,u,a,"","## Artifacts",o,"","## Alignment",c,"","## Risk Summary",s,"","## Gate Audit",i].filter(g=>g!==null).join(`
2193
+ `);return{summary:d,phaseProgress:r,artifactTree:o,riskSummary:s,gateSummary:i,trustDisplay:a,alignmentSummary:c,fullReport:m}}function LP(e){return _l.map(t=>{let n=e.phases[t],r=e.artifacts.filter(a=>a.phase===t),o=r.length;if(o===0)return{phase:t,percentage:n.status==="complete"?100:0,status:n.status,artifactCount:0};let s=r.filter(a=>a.contract_status==="active"||a.contract_status==="fulfilled").length,i=Math.round(s/o*100);return{phase:t,percentage:i,status:n.status,artifactCount:o}})}function UP(e){let n=Math.round(e.percentage/100*20),r=20-n,o="=".repeat(n)+"-".repeat(r);return`${(e.phase.charAt(0).toUpperCase()+e.phase.slice(1)).padEnd(8)} [${o}] ${String(e.percentage).padStart(3)}% (${e.status}) ${e.artifactCount} artifacts`}function WP(e){let t=[];for(let n of _l){let r=e.artifacts.filter(i=>i.phase===n);if(r.length===0)continue;let o=n.charAt(0).toUpperCase()+n.slice(1);t.push(`[${o}]`);let s=new Map;for(let i of r){let a=i.stage;s.has(a)||s.set(a,[]),s.get(a).push(i)}for(let[i,a]of s){t.push(` ${i}/`);for(let c of a){let l=jP[c.contract_status]??"?",u=c.validation_passed===!0?"v":c.validation_passed===!1?"x":"-";t.push(` [${l}] ${c.id} (${c.type}) [${u}]`)}}}return t.join(`
2194
+ `)}function BP(e){if(e.length===0)return"No risks registered";let t=e.filter(a=>a.status==="open").length,n=e.filter(a=>a.status==="mitigated").length,r=e.filter(a=>a.status==="accepted").length,o=e.filter(a=>a.status==="closed").length,s=[`Total: ${e.length} | Open: ${t} | Mitigated: ${n} | Accepted: ${r} | Closed: ${o}`],i=e.filter(a=>a.status==="open");for(let a of i)s.push(` [OPEN] ${a.id}: ${a.description} (${a.likelihood}/${a.impact})`);return s.join(`
2195
+ `)}function GP(e){if(e.length===0)return"No gate transitions recorded";let t=e.filter(s=>s.action==="approved").length,n=e.filter(s=>s.action==="rejected").length,r=e.filter(s=>s.action==="bypassed").length,o=[`Total: ${e.length} | Approved: ${t} | Rejected: ${n} | Bypassed: ${r}`];for(let s of e){let i=s.phase.charAt(0).toUpperCase()+s.phase.slice(1);o.push(` [${s.action.toUpperCase()}] ${i} by ${s.actor}${s.reason?": "+s.reason:""}`)}return o.join(`
2196
+ `)}function HP(e){if(!e)return"Trust: Not initialized";let t=MP[e.current_level]??"Unknown";return[`Trust Level ${e.current_level}: ${t}`,` Transitions: ${e.total_transitions} | Rejections: ${e.rejection_count} (${(e.rejection_rate*100).toFixed(1)}%) | Incidents: ${e.incident_count}`].join(`
2197
+ `)}function VP(e){if(e.length===0)return"No alignment checks recorded";let t=e.filter(o=>o.alignment_passed).length,n=e.filter(o=>!o.alignment_passed).length,r=[`Total: ${e.length} | Passed: ${t} | Failed: ${n}`];for(let o of e){let s=o.alignment_passed?"PASS":"FAIL",i=o.verification.conformance_score,a=o.verification.passed?"v":"x",c=o.validation.passed?"v":"x";r.push(` [${s}] ${o.source_artifact_id} -> ${o.target_artifact_id}: verification=${i}% [${a}] validation [${c}]`)}return r.join(`
2198
+ `)}function qP(e){return e?`Depth: ${e.recommended_depth} (score: ${e.total_score}/30)${e.skip_units?" [skip-units]":""}`:"Depth: Not assessed"}function YP(e){return e?`Risk Tier: ${e.tier} (${e.rationale})`:"Risk Tier: Not classified"}function KP(e){let t=e.artifacts.filter(o=>o.stage==="code-generation"),n=t.length;return n===0?"Bolts: 0/0":`Bolts: ${t.filter(o=>o.contract_status==="active"||o.contract_status==="fulfilled").length}/${n} complete`}function JP(e,t){let n=e.artifacts.length,r=t.filter(s=>s.status!=="not_started");return`${t.filter(s=>s.percentage===100&&s.status==="complete").length}/${_l.length} phases complete | ${n} artifacts total`}var wl=["workspace-detection","reverse-engineering","requirements-analysis","user-stories","workflow-planning","application-design","units-generation"],zP={"workspace-detection":"Workspace Detection","reverse-engineering":"Reverse Engineering","requirements-analysis":"Requirements Analysis","user-stories":"User Stories","workflow-planning":"Workflow Planning","application-design":"Application Design","units-generation":"Units Generation"};function QP(e,t){let n=wl.length,r=wl.filter(l=>e[l]?.status==="completed").length,o=Math.round(r/n*100),s=10,i=Math.round(o/100*s),c=[`Inception [${i>=s?"=".repeat(s):"=".repeat(i)+">"+"-".repeat(s-i-1)}] ${o}% (${r}/${n} stages)`];for(let l of wl){let u=e[l],d=zP[l];if(!u){c.push(` [ ] ${d}`);continue}if(u.status==="completed")c.push(` [x] ${d}`);else if(u.status==="skipped"){let p=u.skip_reason?` (${u.skip_reason})`:" (skipped)";c.push(` [-] ${d}${p}`)}else u.status==="in_progress"||l===t?c.push(` [ ] ${d} <- current`):c.push(` [ ] ${d}`)}return c.join(`
2199
+ `)}Z();sn();le();var t_=b(require("path"),1);function n_(){P({name:"workflowStatusReporter",event:"UserPromptSubmit",priority:6,handler:async e=>{try{let t=e.directory||process.cwd(),n=e.prompt||"",o=(e.parts||[]).map(f=>f.text||"").join(" ")||n;if(!(o.includes("Show status of all active structured workflows")||o.includes("workflow-status")))return{continue:!0};let i=await oe(t),a=null;for(let f of i){let m=await I(t,f);if(m&&m.status!=="complete"&&m.status!=="archived"&&m.status!=="deferred"){a=f;break}}if(!a)return{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:"<workflow-status>\nNo active workflows found. Start one with `/plan <description>`\n</workflow-status>"}};let c=t_.join(t,"aidlc-docs",a,"manifest.json"),l=W(c);if(!l){let f=await I(t,a),m=f?.current_phase||"unknown",g=f?.current_stage||"unknown";return{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:`<workflow-status>
2200
2200
  # Workflow Status: ${a}
2201
2201
 
2202
2202
  Phase: ${m} | Stage: ${g}
2203
2203
 
2204
2204
  Note: manifest.json not found. Detailed artifact tracking unavailable. The workflow is active and can proceed normally.
2205
- </workflow-status>`}}}let u=be(t),d=await I(t,a);return{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:`<workflow-status>
2206
- ${Jw(l,u,d).fullReport}
2207
- </workflow-status>`}}}catch(t){return console.error("[Olympus Workflow Status] Error generating report:",t),{continue:!0}}}})}Z();cn();me();var Xw=T(require("path"),1);function Zw(){P({name:"workflowTransitionMessages",event:"PostToolUse",priority:82,handler:async e=>{try{let t=e.directory||process.cwd();if(e.toolName!=="Write"&&e.toolName!=="Task")return{continue:!0};let n=await oe(t),r=null,o=null;for(let m of n){let g=await I(t,m);if(g&&g.status!=="complete"&&g.status!=="archived"&&g.status!=="deferred"){r=m,o=g;break}}if(!r||!o)return{continue:!0};let s=Xw.join(t,"aidlc-docs",r,"manifest.json"),i=W(s);if(!i)return{continue:!0};let a=be(t),c=i.gate_audit.length>0?i.gate_audit[i.gate_audit.length-1]:null,l=null,u=Et(i),d=u.filter(m=>m.contract_status==="fulfilled"),p=Sn(i),f=i.artifacts.filter(m=>m.stage==="intent");if(u.length>0&&d.length===u.length&&o.current_stage==="code-generation"&&i.phases.construction.status==="complete")l=`\u2713 All ${u.length} BOLTs executed and reviewed
2205
+ </workflow-status>`}}}let u=Te(t),d=await I(t,a);return{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:`<workflow-status>
2206
+ ${e_(l,u,d).fullReport}
2207
+ </workflow-status>`}}}catch(t){return console.error("[Olympus Workflow Status] Error generating report:",t),{continue:!0}}}})}Z();sn();le();var r_=b(require("path"),1);function o_(){P({name:"workflowTransitionMessages",event:"PostToolUse",priority:82,handler:async e=>{try{let t=e.directory||process.cwd();if(e.toolName!=="Write"&&e.toolName!=="Task")return{continue:!0};let n=await oe(t),r=null,o=null;for(let m of n){let g=await I(t,m);if(g&&g.status!=="complete"&&g.status!=="archived"&&g.status!=="deferred"){r=m,o=g;break}}if(!r||!o)return{continue:!0};let s=r_.join(t,"aidlc-docs",r,"manifest.json"),i=W(s);if(!i)return{continue:!0};let a=Te(t),c=i.gate_audit.length>0?i.gate_audit[i.gate_audit.length-1]:null,l=null,u=Tt(i),d=u.filter(m=>m.contract_status==="fulfilled"),p=Sn(i),f=i.artifacts.filter(m=>m.stage==="intent");if(u.length>0&&d.length===u.length&&o.current_stage==="code-generation"&&i.phases.construction.status==="complete")l=`\u2713 All ${u.length} BOLTs executed and reviewed
2208
2208
  \u2192 Next: Operations phase. Generating deployment guide and release notes...`;else if(d.length>0&&d.length<u.length&&c?.phase==="construction"&&c?.action==="approved"){let m=u.length-d.length,g=d[d.length-1];l=`\u2713 BOLT ${d.length}/${u.length} complete \u2014 '${g.id}'
2209
2209
  Gate 4: Dev review of ${g.id} code
2210
2210
  \u2192 Current: ${m} remaining`}else if(p.length>0&&i.phases.construction.status==="in_progress"&&o.current_stage==="unit"&&c?.phase==="inception"&&c?.action==="approved"){let m=p.map(g=>g.id).join(", ");l=`\u2713 ${p.length} UNITs created: ${m}
2211
2211
  Gate 3: Dev review required (Trust Level ${a.current_level})
2212
2212
  \u2192 Waiting: Developer reviews architectural decomposition`}else if(f.some(m=>m.contract_status==="active"||m.contract_status==="fulfilled")&&o.current_stage==="intent"&&c?.phase==="inception"){let m=i.risk_tier?.tier??0,g="";m===3&&(g=`
2213
- \u26A0 Risk Tier 3: Dev review REQUIRED before Construction`,o.status!=="awaiting_dev_review"&&(o.status="awaiting_dev_review",await O(t,o)));let y=f.length>0?f[0].path:`aidlc-docs/${r}/inception/intent.md`;l=`\u2713 INTENT locked \u2014 '${i.feature_name}'
2213
+ \u26A0 Risk Tier 3: Dev review REQUIRED before Construction`,o.status!=="awaiting_dev_review"&&(o.status="awaiting_dev_review",await A(t,o)));let y=f.length>0?f[0].path:`aidlc-docs/${r}/inception/intent.md`;l=`\u2713 INTENT locked \u2014 '${i.feature_name}'
2214
2214
  Tech spec: ${y} | Risk: Tier ${m}
2215
2215
  ${p.length} UNITs decomposed | ${u.length} BOLTs queued
2216
- \u2192 Ready: /ascent, /olympus, or /ultrawork to begin Construction${g}`}if(!l&&o.inception_stages&&o.current_inception_stage){let m=o.inception_stages,g=o.current_inception_stage;if(m[g]?.status==="completed"){let k=Object.values(m).filter(h=>h.status==="completed").length;l=`Inception stage '${g}' complete (${k}/7)
2216
+ \u2192 Ready: /ascent, /olympus, or /ultrawork to begin Construction${g}`}if(!l&&o.inception_stages&&o.current_inception_stage){let m=o.inception_stages,g=o.current_inception_stage;if(m[g]?.status==="completed"){let _=Object.values(m).filter(h=>h.status==="completed").length;l=`Inception stage '${g}' complete (${_}/7)
2217
2217
  \u2192 Next: continue inception pipeline`}}if(l)return{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`<workflow-transition>
2218
2218
  ${l}
2219
- </workflow-transition>`}}}catch(t){console.error("[Olympus Workflow Transition] Error:",t)}return{continue:!0}}})}var ek=!1;function tk(){ek||($w(),Qw(),Tg(),Ng(),th(),Vh(),Ey(),Wy(),Hy(),ew(),tw(),uw(),gw(),Tw(),Fw(),jw(),Bw(),Iw(),Zw(),Kw(),ek=!0)}var si=require("fs"),uk=require("os"),oi=require("path");function ti(e,t=!1){let n=e.length,r=0,o="",s=0,i=16,a=0,c=0,l=0,u=0,d=0;function p(h,v){let S=0,b=0;for(;S<h||!v;){let _=e.charCodeAt(r);if(_>=48&&_<=57)b=b*16+_-48;else if(_>=65&&_<=70)b=b*16+_-65+10;else if(_>=97&&_<=102)b=b*16+_-97+10;else break;r++,S++}return S<h&&(b=-1),b}function f(h){r=h,o="",s=0,i=16,d=0}function m(){let h=r;if(e.charCodeAt(r)===48)r++;else for(r++;r<e.length&&Or(e.charCodeAt(r));)r++;if(r<e.length&&e.charCodeAt(r)===46)if(r++,r<e.length&&Or(e.charCodeAt(r)))for(r++;r<e.length&&Or(e.charCodeAt(r));)r++;else return d=3,e.substring(h,r);let v=r;if(r<e.length&&(e.charCodeAt(r)===69||e.charCodeAt(r)===101))if(r++,(r<e.length&&e.charCodeAt(r)===43||e.charCodeAt(r)===45)&&r++,r<e.length&&Or(e.charCodeAt(r))){for(r++;r<e.length&&Or(e.charCodeAt(r));)r++;v=r}else d=3;return e.substring(h,v)}function g(){let h="",v=r;for(;;){if(r>=n){h+=e.substring(v,r),d=2;break}let S=e.charCodeAt(r);if(S===34){h+=e.substring(v,r),r++;break}if(S===92){if(h+=e.substring(v,r),r++,r>=n){d=2;break}switch(e.charCodeAt(r++)){case 34:h+='"';break;case 92:h+="\\";break;case 47:h+="/";break;case 98:h+="\b";break;case 102:h+="\f";break;case 110:h+=`
2220
- `;break;case 114:h+="\r";break;case 116:h+=" ";break;case 117:let _=p(4,!0);_>=0?h+=String.fromCharCode(_):d=4;break;default:d=5}v=r;continue}if(S>=0&&S<=31)if(_o(S)){h+=e.substring(v,r),d=2;break}else d=6;r++}return h}function y(){if(o="",d=0,s=r,c=a,u=l,r>=n)return s=n,i=17;let h=e.charCodeAt(r);if(hl(h)){do r++,o+=String.fromCharCode(h),h=e.charCodeAt(r);while(hl(h));return i=15}if(_o(h))return r++,o+=String.fromCharCode(h),h===13&&e.charCodeAt(r)===10&&(r++,o+=`
2221
- `),a++,l=r,i=14;switch(h){case 123:return r++,i=1;case 125:return r++,i=2;case 91:return r++,i=3;case 93:return r++,i=4;case 58:return r++,i=6;case 44:return r++,i=5;case 34:return r++,o=g(),i=10;case 47:let v=r-1;if(e.charCodeAt(r+1)===47){for(r+=2;r<n&&!_o(e.charCodeAt(r));)r++;return o=e.substring(v,r),i=12}if(e.charCodeAt(r+1)===42){r+=2;let S=n-1,b=!1;for(;r<S;){let _=e.charCodeAt(r);if(_===42&&e.charCodeAt(r+1)===47){r+=2,b=!0;break}r++,_o(_)&&(_===13&&e.charCodeAt(r)===10&&r++,a++,l=r)}return b||(r++,d=1),o=e.substring(v,r),i=13}return o+=String.fromCharCode(h),r++,i=16;case 45:if(o+=String.fromCharCode(h),r++,r===n||!Or(e.charCodeAt(r)))return i=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return o+=m(),i=11;default:for(;r<n&&w(h);)r++,h=e.charCodeAt(r);if(s!==r){switch(o=e.substring(s,r),o){case"true":return i=8;case"false":return i=9;case"null":return i=7}return i=16}return o+=String.fromCharCode(h),r++,i=16}}function w(h){if(hl(h)||_o(h))return!1;switch(h){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}function k(){let h;do h=y();while(h>=12&&h<=15);return h}return{setPosition:f,getPosition:()=>r,scan:t?k:y,getToken:()=>i,getTokenValue:()=>o,getTokenOffset:()=>s,getTokenLength:()=>r-s,getTokenStartLine:()=>c,getTokenStartCharacter:()=>s-u,getTokenError:()=>d}}function hl(e){return e===32||e===9}function _o(e){return e===10||e===13}function Or(e){return e>=48&&e<=57}var nk;(function(e){e[e.lineFeed=10]="lineFeed",e[e.carriageReturn=13]="carriageReturn",e[e.space=32]="space",e[e._0=48]="_0",e[e._1=49]="_1",e[e._2=50]="_2",e[e._3=51]="_3",e[e._4=52]="_4",e[e._5=53]="_5",e[e._6=54]="_6",e[e._7=55]="_7",e[e._8=56]="_8",e[e._9=57]="_9",e[e.a=97]="a",e[e.b=98]="b",e[e.c=99]="c",e[e.d=100]="d",e[e.e=101]="e",e[e.f=102]="f",e[e.g=103]="g",e[e.h=104]="h",e[e.i=105]="i",e[e.j=106]="j",e[e.k=107]="k",e[e.l=108]="l",e[e.m=109]="m",e[e.n=110]="n",e[e.o=111]="o",e[e.p=112]="p",e[e.q=113]="q",e[e.r=114]="r",e[e.s=115]="s",e[e.t=116]="t",e[e.u=117]="u",e[e.v=118]="v",e[e.w=119]="w",e[e.x=120]="x",e[e.y=121]="y",e[e.z=122]="z",e[e.A=65]="A",e[e.B=66]="B",e[e.C=67]="C",e[e.D=68]="D",e[e.E=69]="E",e[e.F=70]="F",e[e.G=71]="G",e[e.H=72]="H",e[e.I=73]="I",e[e.J=74]="J",e[e.K=75]="K",e[e.L=76]="L",e[e.M=77]="M",e[e.N=78]="N",e[e.O=79]="O",e[e.P=80]="P",e[e.Q=81]="Q",e[e.R=82]="R",e[e.S=83]="S",e[e.T=84]="T",e[e.U=85]="U",e[e.V=86]="V",e[e.W=87]="W",e[e.X=88]="X",e[e.Y=89]="Y",e[e.Z=90]="Z",e[e.asterisk=42]="asterisk",e[e.backslash=92]="backslash",e[e.closeBrace=125]="closeBrace",e[e.closeBracket=93]="closeBracket",e[e.colon=58]="colon",e[e.comma=44]="comma",e[e.dot=46]="dot",e[e.doubleQuote=34]="doubleQuote",e[e.minus=45]="minus",e[e.openBrace=123]="openBrace",e[e.openBracket=91]="openBracket",e[e.plus=43]="plus",e[e.slash=47]="slash",e[e.formFeed=12]="formFeed",e[e.tab=9]="tab"})(nk||(nk={}));var LP=new Array(20).fill(0).map((e,t)=>" ".repeat(t)),$r=200,UP={" ":{"\n":new Array($r).fill(0).map((e,t)=>`
2219
+ </workflow-transition>`}}}catch(t){console.error("[Olympus Workflow Transition] Error:",t)}return{continue:!0}}})}var s_=!1;function i_(){s_||(Mw(),n_(),xg(),Ug(),ih(),zh(),Py(),qy(),Jy(),sw(),iw(),gw(),kw(),xw(),Ww(),Bw(),Kw(),Nw(),o_(),Zw(),s_=!0)}var ai=require("fs"),g_=require("os"),ii=require("path");function ri(e,t=!1){let n=e.length,r=0,o="",s=0,i=16,a=0,c=0,l=0,u=0,d=0;function p(h,v){let S=0,E=0;for(;S<h||!v;){let k=e.charCodeAt(r);if(k>=48&&k<=57)E=E*16+k-48;else if(k>=65&&k<=70)E=E*16+k-65+10;else if(k>=97&&k<=102)E=E*16+k-97+10;else break;r++,S++}return S<h&&(E=-1),E}function f(h){r=h,o="",s=0,i=16,d=0}function m(){let h=r;if(e.charCodeAt(r)===48)r++;else for(r++;r<e.length&&Or(e.charCodeAt(r));)r++;if(r<e.length&&e.charCodeAt(r)===46)if(r++,r<e.length&&Or(e.charCodeAt(r)))for(r++;r<e.length&&Or(e.charCodeAt(r));)r++;else return d=3,e.substring(h,r);let v=r;if(r<e.length&&(e.charCodeAt(r)===69||e.charCodeAt(r)===101))if(r++,(r<e.length&&e.charCodeAt(r)===43||e.charCodeAt(r)===45)&&r++,r<e.length&&Or(e.charCodeAt(r))){for(r++;r<e.length&&Or(e.charCodeAt(r));)r++;v=r}else d=3;return e.substring(h,v)}function g(){let h="",v=r;for(;;){if(r>=n){h+=e.substring(v,r),d=2;break}let S=e.charCodeAt(r);if(S===34){h+=e.substring(v,r),r++;break}if(S===92){if(h+=e.substring(v,r),r++,r>=n){d=2;break}switch(e.charCodeAt(r++)){case 34:h+='"';break;case 92:h+="\\";break;case 47:h+="/";break;case 98:h+="\b";break;case 102:h+="\f";break;case 110:h+=`
2220
+ `;break;case 114:h+="\r";break;case 116:h+=" ";break;case 117:let k=p(4,!0);k>=0?h+=String.fromCharCode(k):d=4;break;default:d=5}v=r;continue}if(S>=0&&S<=31)if(ko(S)){h+=e.substring(v,r),d=2;break}else d=6;r++}return h}function y(){if(o="",d=0,s=r,c=a,u=l,r>=n)return s=n,i=17;let h=e.charCodeAt(r);if(kl(h)){do r++,o+=String.fromCharCode(h),h=e.charCodeAt(r);while(kl(h));return i=15}if(ko(h))return r++,o+=String.fromCharCode(h),h===13&&e.charCodeAt(r)===10&&(r++,o+=`
2221
+ `),a++,l=r,i=14;switch(h){case 123:return r++,i=1;case 125:return r++,i=2;case 91:return r++,i=3;case 93:return r++,i=4;case 58:return r++,i=6;case 44:return r++,i=5;case 34:return r++,o=g(),i=10;case 47:let v=r-1;if(e.charCodeAt(r+1)===47){for(r+=2;r<n&&!ko(e.charCodeAt(r));)r++;return o=e.substring(v,r),i=12}if(e.charCodeAt(r+1)===42){r+=2;let S=n-1,E=!1;for(;r<S;){let k=e.charCodeAt(r);if(k===42&&e.charCodeAt(r+1)===47){r+=2,E=!0;break}r++,ko(k)&&(k===13&&e.charCodeAt(r)===10&&r++,a++,l=r)}return E||(r++,d=1),o=e.substring(v,r),i=13}return o+=String.fromCharCode(h),r++,i=16;case 45:if(o+=String.fromCharCode(h),r++,r===n||!Or(e.charCodeAt(r)))return i=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return o+=m(),i=11;default:for(;r<n&&w(h);)r++,h=e.charCodeAt(r);if(s!==r){switch(o=e.substring(s,r),o){case"true":return i=8;case"false":return i=9;case"null":return i=7}return i=16}return o+=String.fromCharCode(h),r++,i=16}}function w(h){if(kl(h)||ko(h))return!1;switch(h){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}function _(){let h;do h=y();while(h>=12&&h<=15);return h}return{setPosition:f,getPosition:()=>r,scan:t?_:y,getToken:()=>i,getTokenValue:()=>o,getTokenOffset:()=>s,getTokenLength:()=>r-s,getTokenStartLine:()=>c,getTokenStartCharacter:()=>s-u,getTokenError:()=>d}}function kl(e){return e===32||e===9}function ko(e){return e===10||e===13}function Or(e){return e>=48&&e<=57}var a_;(function(e){e[e.lineFeed=10]="lineFeed",e[e.carriageReturn=13]="carriageReturn",e[e.space=32]="space",e[e._0=48]="_0",e[e._1=49]="_1",e[e._2=50]="_2",e[e._3=51]="_3",e[e._4=52]="_4",e[e._5=53]="_5",e[e._6=54]="_6",e[e._7=55]="_7",e[e._8=56]="_8",e[e._9=57]="_9",e[e.a=97]="a",e[e.b=98]="b",e[e.c=99]="c",e[e.d=100]="d",e[e.e=101]="e",e[e.f=102]="f",e[e.g=103]="g",e[e.h=104]="h",e[e.i=105]="i",e[e.j=106]="j",e[e.k=107]="k",e[e.l=108]="l",e[e.m=109]="m",e[e.n=110]="n",e[e.o=111]="o",e[e.p=112]="p",e[e.q=113]="q",e[e.r=114]="r",e[e.s=115]="s",e[e.t=116]="t",e[e.u=117]="u",e[e.v=118]="v",e[e.w=119]="w",e[e.x=120]="x",e[e.y=121]="y",e[e.z=122]="z",e[e.A=65]="A",e[e.B=66]="B",e[e.C=67]="C",e[e.D=68]="D",e[e.E=69]="E",e[e.F=70]="F",e[e.G=71]="G",e[e.H=72]="H",e[e.I=73]="I",e[e.J=74]="J",e[e.K=75]="K",e[e.L=76]="L",e[e.M=77]="M",e[e.N=78]="N",e[e.O=79]="O",e[e.P=80]="P",e[e.Q=81]="Q",e[e.R=82]="R",e[e.S=83]="S",e[e.T=84]="T",e[e.U=85]="U",e[e.V=86]="V",e[e.W=87]="W",e[e.X=88]="X",e[e.Y=89]="Y",e[e.Z=90]="Z",e[e.asterisk=42]="asterisk",e[e.backslash=92]="backslash",e[e.closeBrace=125]="closeBrace",e[e.closeBracket=93]="closeBracket",e[e.colon=58]="colon",e[e.comma=44]="comma",e[e.dot=46]="dot",e[e.doubleQuote=34]="doubleQuote",e[e.minus=45]="minus",e[e.openBrace=123]="openBrace",e[e.openBracket=91]="openBracket",e[e.plus=43]="plus",e[e.slash=47]="slash",e[e.formFeed=12]="formFeed",e[e.tab=9]="tab"})(a_||(a_={}));var ZP=new Array(20).fill(0).map((e,t)=>" ".repeat(t)),$r=200,eA={" ":{"\n":new Array($r).fill(0).map((e,t)=>`
2222
2222
  `+" ".repeat(t)),"\r":new Array($r).fill(0).map((e,t)=>"\r"+" ".repeat(t)),"\r\n":new Array($r).fill(0).map((e,t)=>`\r
2223
2223
  `+" ".repeat(t))}," ":{"\n":new Array($r).fill(0).map((e,t)=>`
2224
2224
  `+" ".repeat(t)),"\r":new Array($r).fill(0).map((e,t)=>"\r"+" ".repeat(t)),"\r\n":new Array($r).fill(0).map((e,t)=>`\r
2225
- `+" ".repeat(t))}};var ni;(function(e){e.DEFAULT={allowTrailingComma:!1}})(ni||(ni={}));function rk(e,t=[],n=ni.DEFAULT){let r=null,o=[],s=[];function i(c){Array.isArray(o)?o.push(c):r!==null&&(o[r]=c)}return ok(e,{onObjectBegin:()=>{let c={};i(c),s.push(o),o=c,r=null},onObjectProperty:c=>{r=c},onObjectEnd:()=>{o=s.pop()},onArrayBegin:()=>{let c=[];i(c),s.push(o),o=c,r=null},onArrayEnd:()=>{o=s.pop()},onLiteralValue:i,onError:(c,l,u)=>{t.push({error:c,offset:l,length:u})}},n),o[0]}function ok(e,t,n=ni.DEFAULT){let r=ti(e,!1),o=[],s=0;function i(x){return x?()=>s===0&&x(r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter()):()=>!0}function a(x){return x?E=>s===0&&x(E,r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter()):()=>!0}function c(x){return x?E=>s===0&&x(E,r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter(),()=>o.slice()):()=>!0}function l(x){return x?()=>{s>0?s++:x(r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter(),()=>o.slice())===!1&&(s=1)}:()=>!0}function u(x){return x?()=>{s>0&&s--,s===0&&x(r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter())}:()=>!0}let d=l(t.onObjectBegin),p=c(t.onObjectProperty),f=u(t.onObjectEnd),m=l(t.onArrayBegin),g=u(t.onArrayEnd),y=c(t.onLiteralValue),w=a(t.onSeparator),k=i(t.onComment),h=a(t.onError),v=n&&n.disallowComments,S=n&&n.allowTrailingComma;function b(){for(;;){let x=r.scan();switch(r.getTokenError()){case 4:_(14);break;case 5:_(15);break;case 3:_(13);break;case 1:v||_(11);break;case 2:_(12);break;case 6:_(16);break}switch(x){case 12:case 13:v?_(10):k();break;case 16:_(1);break;case 15:case 14:break;default:return x}}}function _(x,E=[],M=[]){if(h(x),E.length+M.length>0){let F=r.getToken();for(;F!==17;){if(E.indexOf(F)!==-1){b();break}else if(M.indexOf(F)!==-1)break;F=b()}}}function j(x){let E=r.getTokenValue();return x?y(E):(p(E),o.push(E)),b(),!0}function R(){switch(r.getToken()){case 11:let x=r.getTokenValue(),E=Number(x);isNaN(E)&&(_(2),E=0),y(E);break;case 7:y(null);break;case 8:y(!0);break;case 9:y(!1);break;default:return!1}return b(),!0}function A(){return r.getToken()!==10?(_(3,[],[2,5]),!1):(j(!1),r.getToken()===6?(w(":"),b(),N()||_(4,[],[2,5])):_(5,[],[2,5]),o.pop(),!0)}function C(){d(),b();let x=!1;for(;r.getToken()!==2&&r.getToken()!==17;){if(r.getToken()===5){if(x||_(4,[],[]),w(","),b(),r.getToken()===2&&S)break}else x&&_(6,[],[]);A()||_(4,[],[2,5]),x=!0}return f(),r.getToken()!==2?_(7,[2],[]):b(),!0}function $(){m(),b();let x=!0,E=!1;for(;r.getToken()!==4&&r.getToken()!==17;){if(r.getToken()===5){if(E||_(4,[],[]),w(","),b(),r.getToken()===4&&S)break}else E&&_(6,[],[]);x?(o.push(0),x=!1):o[o.length-1]++,N()||_(4,[],[4,5]),E=!0}return g(),x||o.pop(),r.getToken()!==4?_(8,[4],[]):b(),!0}function N(){switch(r.getToken()){case 3:return $();case 1:return C();case 10:return j(!0);default:return R()}}return b(),r.getToken()===17?n.allowEmptyContent?!0:(_(4,[],[]),!1):N()?(r.getToken()!==17&&_(9,[],[]),!0):(_(4,[],[]),!1)}var sk;(function(e){e[e.None=0]="None",e[e.UnexpectedEndOfComment=1]="UnexpectedEndOfComment",e[e.UnexpectedEndOfString=2]="UnexpectedEndOfString",e[e.UnexpectedEndOfNumber=3]="UnexpectedEndOfNumber",e[e.InvalidUnicode=4]="InvalidUnicode",e[e.InvalidEscapeCharacter=5]="InvalidEscapeCharacter",e[e.InvalidCharacter=6]="InvalidCharacter"})(sk||(sk={}));var ik;(function(e){e[e.OpenBraceToken=1]="OpenBraceToken",e[e.CloseBraceToken=2]="CloseBraceToken",e[e.OpenBracketToken=3]="OpenBracketToken",e[e.CloseBracketToken=4]="CloseBracketToken",e[e.CommaToken=5]="CommaToken",e[e.ColonToken=6]="ColonToken",e[e.NullKeyword=7]="NullKeyword",e[e.TrueKeyword=8]="TrueKeyword",e[e.FalseKeyword=9]="FalseKeyword",e[e.StringLiteral=10]="StringLiteral",e[e.NumericLiteral=11]="NumericLiteral",e[e.LineCommentTrivia=12]="LineCommentTrivia",e[e.BlockCommentTrivia=13]="BlockCommentTrivia",e[e.LineBreakTrivia=14]="LineBreakTrivia",e[e.Trivia=15]="Trivia",e[e.Unknown=16]="Unknown",e[e.EOF=17]="EOF"})(ik||(ik={}));var ck=rk;var ak;(function(e){e[e.InvalidSymbol=1]="InvalidSymbol",e[e.InvalidNumberFormat=2]="InvalidNumberFormat",e[e.PropertyNameExpected=3]="PropertyNameExpected",e[e.ValueExpected=4]="ValueExpected",e[e.ColonExpected=5]="ColonExpected",e[e.CommaExpected=6]="CommaExpected",e[e.CloseBraceExpected=7]="CloseBraceExpected",e[e.CloseBracketExpected=8]="CloseBracketExpected",e[e.EndOfFileExpected=9]="EndOfFileExpected",e[e.InvalidCommentToken=10]="InvalidCommentToken",e[e.UnexpectedEndOfComment=11]="UnexpectedEndOfComment",e[e.UnexpectedEndOfString=12]="UnexpectedEndOfString",e[e.UnexpectedEndOfNumber=13]="UnexpectedEndOfNumber",e[e.InvalidUnicode=14]="InvalidUnicode",e[e.InvalidEscapeCharacter=15]="InvalidEscapeCharacter",e[e.InvalidCharacter=16]="InvalidCharacter"})(ak||(ak={}));var KP={agents:{olympus:{model:"claude-opus-4-5-20251101"},oracle:{model:"claude-opus-4-5-20251101",enabled:!0},librarian:{model:"claude-sonnet-4-5-20250929"},explore:{model:"claude-haiku-4-5-20251001"},frontendEngineer:{model:"claude-sonnet-4-5-20250929",enabled:!0},documentWriter:{model:"claude-haiku-4-5-20251001",enabled:!0},multimodalLooker:{model:"claude-sonnet-4-5-20250929",enabled:!0},momus:{model:"claude-opus-4-5-20251101",enabled:!0},metis:{model:"claude-opus-4-5-20251101",enabled:!0},orchestratorOlympus:{model:"claude-sonnet-4-5-20250929",enabled:!0},olympusJunior:{model:"claude-sonnet-4-5-20250929",enabled:!0},prometheus:{model:"claude-opus-4-5-20251101",enabled:!0}},features:{parallelExecution:!0,lspTools:!0,astTools:!0,continuationEnforcement:!0,autoContextInjection:!0},mcpServers:{exa:{enabled:!0},context7:{enabled:!0},grepApp:{enabled:!0}},permissions:{allowBash:!0,allowEdit:!0,allowWrite:!0,maxBackgroundTasks:5},magicKeywords:{ultrawork:["ultrawork","ulw","uw"],search:["search","find","locate"],analyze:["analyze","investigate","examine"],ultrathink:["ultrathink","think","reason","ponder"]},routing:{enabled:!0,defaultTier:"MEDIUM",escalationEnabled:!0,maxEscalations:2,tierModels:{LOW:"claude-haiku-4-5-20251001",MEDIUM:"claude-sonnet-4-5-20250929",HIGH:"claude-opus-4-5-20251101"},agentOverrides:{oracle:{tier:"HIGH",reason:"Advisory agent requires deep reasoning"},prometheus:{tier:"HIGH",reason:"Strategic planning requires deep reasoning"},momus:{tier:"HIGH",reason:"Critical review requires deep reasoning"},metis:{tier:"HIGH",reason:"Pre-planning analysis requires deep reasoning"},explore:{tier:"LOW",reason:"Exploration is search-focused"},"document-writer":{tier:"LOW",reason:"Documentation is straightforward"}},escalationKeywords:["critical","production","urgent","security","breaking","architecture","refactor","redesign","root cause"],simplificationKeywords:["find","list","show","where","search","locate","grep"]},ascent:{maxIterations:100},learning:{tokenMetrics:{enabled:!0,warningThreshold:1.5,minimumSamples:5,injectionTokenBudget:150,sessionBaseline:1e4}},pricing:{models:Xc,customPricing:[]}};function JP(){return{user:(0,oi.join)((0,uk.homedir)(),".claude","olympus","config.jsonc"),project:(0,oi.join)(process.cwd(),".claude","olympus.jsonc")}}function lk(e){if(!(0,si.existsSync)(e))return null;try{let t=(0,si.readFileSync)(e,"utf-8"),n=[],r=ck(t,n,{allowTrailingComma:!0,allowEmptyContent:!0});return n.length>0&&console.warn(`Warning: Parse errors in ${e}:`,n),r}catch(t){return console.error(`Error loading config from ${e}:`,t),null}}function ri(e,t){let n={...e};for(let r of Object.keys(t)){let o=t[r],s=n[r];o!==void 0&&typeof o=="object"&&o!==null&&!Array.isArray(o)&&typeof s=="object"&&s!==null&&!Array.isArray(s)?n[r]=ri(s,o):o!==void 0&&(n[r]=o)}return n}function zP(){let e={};if(process.env.EXA_API_KEY&&(e.mcpServers={...e.mcpServers,exa:{enabled:!0,apiKey:process.env.EXA_API_KEY}}),process.env.OLYMPUS_PARALLEL_EXECUTION!==void 0&&(e.features={...e.features,parallelExecution:process.env.OLYMPUS_PARALLEL_EXECUTION==="true"}),process.env.OLYMPUS_LSP_TOOLS!==void 0&&(e.features={...e.features,lspTools:process.env.OLYMPUS_LSP_TOOLS==="true"}),process.env.OLYMPUS_MAX_BACKGROUND_TASKS){let t=parseInt(process.env.OLYMPUS_MAX_BACKGROUND_TASKS,10);isNaN(t)||(e.permissions={...e.permissions,maxBackgroundTasks:t})}if(process.env.OLYMPUS_ROUTING_ENABLED!==void 0&&(e.routing={...e.routing,enabled:process.env.OLYMPUS_ROUTING_ENABLED==="true"}),process.env.OLYMPUS_ROUTING_DEFAULT_TIER){let t=process.env.OLYMPUS_ROUTING_DEFAULT_TIER.toUpperCase();(t==="LOW"||t==="MEDIUM"||t==="HIGH")&&(e.routing={...e.routing,defaultTier:t})}if(process.env.OLYMPUS_ESCALATION_ENABLED!==void 0&&(e.routing={...e.routing,escalationEnabled:process.env.OLYMPUS_ESCALATION_ENABLED==="true"}),process.env.OLYMPUS_MAX_ASCENT_ITERATIONS){let t=parseInt(process.env.OLYMPUS_MAX_ASCENT_ITERATIONS,10);!isNaN(t)&&t>=10&&t<=1e3?e.ascent={...e.ascent,maxIterations:t}:isNaN(t)||console.warn(`Warning: OLYMPUS_MAX_ASCENT_ITERATIONS must be between 10 and 1000. Got: ${t}`)}return e}function dk(){let e=JP(),t={...KP},n=lk(e.user);n&&(t=ri(t,n));let r=lk(e.project);r&&(t=ri(t,r));let o=zP();return t=ri(t,o),t}function QP(e){let t=e.hooks;return t&&typeof t.timeoutMs=="number"?t.timeoutMs:5e3}function XP(e,t){let n=e.hooks;if(n&&typeof n.enabled=="boolean"&&!n.enabled)return!1;if(n&&t in n){let r=n[t];if(typeof r=="object"&&r!==null){let o=r.enabled;if(typeof o=="boolean")return o}}return!0}async function ZP(e,t){return Promise.race([Promise.resolve(e()),new Promise(n=>setTimeout(()=>n(null),t))])}function eI(e,t){return!e||!t?!0:(typeof e=="string"?new RegExp(e,"i"):e).test(t)}async function pk(e,t){let n=dk(),r=wl(e),o=QP(n),s=!0,i=[],a,c=t.toolInput,l=t.messages;for(let u of r)if(XP(n,u.name)&&eI(u.matcher,t.toolName))try{let d=await ZP(()=>u.handler({...t,toolInput:c,messages:l}),o);if(d===null){console.error(`[hook-router] ${u.name} timed out after ${o}ms`);continue}d.continue||(s=!1,a=d.stopReason),d.message&&i.push(d.message),d.hookSpecificOutput?.additionalContext&&i.push(d.hookSpecificOutput.additionalContext),d.modifiedInput!==void 0&&(c=d.modifiedInput),d.modifiedMessages!==void 0&&(l=d.modifiedMessages)}catch(d){console.error(`[hook-router] ${u.name} error:`,d)}return{continue:s,message:i.length>0?i.join(`
2225
+ `+" ".repeat(t))}};var oi;(function(e){e.DEFAULT={allowTrailingComma:!1}})(oi||(oi={}));function c_(e,t=[],n=oi.DEFAULT){let r=null,o=[],s=[];function i(c){Array.isArray(o)?o.push(c):r!==null&&(o[r]=c)}return l_(e,{onObjectBegin:()=>{let c={};i(c),s.push(o),o=c,r=null},onObjectProperty:c=>{r=c},onObjectEnd:()=>{o=s.pop()},onArrayBegin:()=>{let c=[];i(c),s.push(o),o=c,r=null},onArrayEnd:()=>{o=s.pop()},onLiteralValue:i,onError:(c,l,u)=>{t.push({error:c,offset:l,length:u})}},n),o[0]}function l_(e,t,n=oi.DEFAULT){let r=ri(e,!1),o=[],s=0;function i(x){return x?()=>s===0&&x(r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter()):()=>!0}function a(x){return x?T=>s===0&&x(T,r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter()):()=>!0}function c(x){return x?T=>s===0&&x(T,r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter(),()=>o.slice()):()=>!0}function l(x){return x?()=>{s>0?s++:x(r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter(),()=>o.slice())===!1&&(s=1)}:()=>!0}function u(x){return x?()=>{s>0&&s--,s===0&&x(r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter())}:()=>!0}let d=l(t.onObjectBegin),p=c(t.onObjectProperty),f=u(t.onObjectEnd),m=l(t.onArrayBegin),g=u(t.onArrayEnd),y=c(t.onLiteralValue),w=a(t.onSeparator),_=i(t.onComment),h=a(t.onError),v=n&&n.disallowComments,S=n&&n.allowTrailingComma;function E(){for(;;){let x=r.scan();switch(r.getTokenError()){case 4:k(14);break;case 5:k(15);break;case 3:k(13);break;case 1:v||k(11);break;case 2:k(12);break;case 6:k(16);break}switch(x){case 12:case 13:v?k(10):_();break;case 16:k(1);break;case 15:case 14:break;default:return x}}}function k(x,T=[],M=[]){if(h(x),T.length+M.length>0){let F=r.getToken();for(;F!==17;){if(T.indexOf(F)!==-1){E();break}else if(M.indexOf(F)!==-1)break;F=E()}}}function j(x){let T=r.getTokenValue();return x?y(T):(p(T),o.push(T)),E(),!0}function R(){switch(r.getToken()){case 11:let x=r.getTokenValue(),T=Number(x);isNaN(T)&&(k(2),T=0),y(T);break;case 7:y(null);break;case 8:y(!0);break;case 9:y(!1);break;default:return!1}return E(),!0}function O(){return r.getToken()!==10?(k(3,[],[2,5]),!1):(j(!1),r.getToken()===6?(w(":"),E(),N()||k(4,[],[2,5])):k(5,[],[2,5]),o.pop(),!0)}function C(){d(),E();let x=!1;for(;r.getToken()!==2&&r.getToken()!==17;){if(r.getToken()===5){if(x||k(4,[],[]),w(","),E(),r.getToken()===2&&S)break}else x&&k(6,[],[]);O()||k(4,[],[2,5]),x=!0}return f(),r.getToken()!==2?k(7,[2],[]):E(),!0}function $(){m(),E();let x=!0,T=!1;for(;r.getToken()!==4&&r.getToken()!==17;){if(r.getToken()===5){if(T||k(4,[],[]),w(","),E(),r.getToken()===4&&S)break}else T&&k(6,[],[]);x?(o.push(0),x=!1):o[o.length-1]++,N()||k(4,[],[4,5]),T=!0}return g(),x||o.pop(),r.getToken()!==4?k(8,[4],[]):E(),!0}function N(){switch(r.getToken()){case 3:return $();case 1:return C();case 10:return j(!0);default:return R()}}return E(),r.getToken()===17?n.allowEmptyContent?!0:(k(4,[],[]),!1):N()?(r.getToken()!==17&&k(9,[],[]),!0):(k(4,[],[]),!1)}var u_;(function(e){e[e.None=0]="None",e[e.UnexpectedEndOfComment=1]="UnexpectedEndOfComment",e[e.UnexpectedEndOfString=2]="UnexpectedEndOfString",e[e.UnexpectedEndOfNumber=3]="UnexpectedEndOfNumber",e[e.InvalidUnicode=4]="InvalidUnicode",e[e.InvalidEscapeCharacter=5]="InvalidEscapeCharacter",e[e.InvalidCharacter=6]="InvalidCharacter"})(u_||(u_={}));var d_;(function(e){e[e.OpenBraceToken=1]="OpenBraceToken",e[e.CloseBraceToken=2]="CloseBraceToken",e[e.OpenBracketToken=3]="OpenBracketToken",e[e.CloseBracketToken=4]="CloseBracketToken",e[e.CommaToken=5]="CommaToken",e[e.ColonToken=6]="ColonToken",e[e.NullKeyword=7]="NullKeyword",e[e.TrueKeyword=8]="TrueKeyword",e[e.FalseKeyword=9]="FalseKeyword",e[e.StringLiteral=10]="StringLiteral",e[e.NumericLiteral=11]="NumericLiteral",e[e.LineCommentTrivia=12]="LineCommentTrivia",e[e.BlockCommentTrivia=13]="BlockCommentTrivia",e[e.LineBreakTrivia=14]="LineBreakTrivia",e[e.Trivia=15]="Trivia",e[e.Unknown=16]="Unknown",e[e.EOF=17]="EOF"})(d_||(d_={}));var f_=c_;var p_;(function(e){e[e.InvalidSymbol=1]="InvalidSymbol",e[e.InvalidNumberFormat=2]="InvalidNumberFormat",e[e.PropertyNameExpected=3]="PropertyNameExpected",e[e.ValueExpected=4]="ValueExpected",e[e.ColonExpected=5]="ColonExpected",e[e.CommaExpected=6]="CommaExpected",e[e.CloseBraceExpected=7]="CloseBraceExpected",e[e.CloseBracketExpected=8]="CloseBracketExpected",e[e.EndOfFileExpected=9]="EndOfFileExpected",e[e.InvalidCommentToken=10]="InvalidCommentToken",e[e.UnexpectedEndOfComment=11]="UnexpectedEndOfComment",e[e.UnexpectedEndOfString=12]="UnexpectedEndOfString",e[e.UnexpectedEndOfNumber=13]="UnexpectedEndOfNumber",e[e.InvalidUnicode=14]="InvalidUnicode",e[e.InvalidEscapeCharacter=15]="InvalidEscapeCharacter",e[e.InvalidCharacter=16]="InvalidCharacter"})(p_||(p_={}));var cA={agents:{olympus:{model:"claude-opus-4-5-20251101"},oracle:{model:"claude-opus-4-5-20251101",enabled:!0},librarian:{model:"claude-sonnet-4-5-20250929"},explore:{model:"claude-haiku-4-5-20251001"},frontendEngineer:{model:"claude-sonnet-4-5-20250929",enabled:!0},documentWriter:{model:"claude-haiku-4-5-20251001",enabled:!0},multimodalLooker:{model:"claude-sonnet-4-5-20250929",enabled:!0},momus:{model:"claude-opus-4-5-20251101",enabled:!0},metis:{model:"claude-opus-4-5-20251101",enabled:!0},orchestratorOlympus:{model:"claude-sonnet-4-5-20250929",enabled:!0},olympusJunior:{model:"claude-sonnet-4-5-20250929",enabled:!0},prometheus:{model:"claude-opus-4-5-20251101",enabled:!0}},features:{parallelExecution:!0,lspTools:!0,astTools:!0,continuationEnforcement:!0,autoContextInjection:!0},mcpServers:{exa:{enabled:!0},context7:{enabled:!0},grepApp:{enabled:!0}},permissions:{allowBash:!0,allowEdit:!0,allowWrite:!0,maxBackgroundTasks:5},magicKeywords:{ultrawork:["ultrawork","ulw","uw"],search:["search","find","locate"],analyze:["analyze","investigate","examine"],ultrathink:["ultrathink","think","reason","ponder"]},routing:{enabled:!0,defaultTier:"MEDIUM",escalationEnabled:!0,maxEscalations:2,tierModels:{LOW:"claude-haiku-4-5-20251001",MEDIUM:"claude-sonnet-4-5-20250929",HIGH:"claude-opus-4-5-20251101"},agentOverrides:{oracle:{tier:"HIGH",reason:"Advisory agent requires deep reasoning"},prometheus:{tier:"HIGH",reason:"Strategic planning requires deep reasoning"},momus:{tier:"HIGH",reason:"Critical review requires deep reasoning"},metis:{tier:"HIGH",reason:"Pre-planning analysis requires deep reasoning"},explore:{tier:"LOW",reason:"Exploration is search-focused"},"document-writer":{tier:"LOW",reason:"Documentation is straightforward"}},escalationKeywords:["critical","production","urgent","security","breaking","architecture","refactor","redesign","root cause"],simplificationKeywords:["find","list","show","where","search","locate","grep"]},ascent:{maxIterations:100},learning:{tokenMetrics:{enabled:!0,warningThreshold:1.5,minimumSamples:5,injectionTokenBudget:150,sessionBaseline:1e4}},pricing:{models:nl,customPricing:[]}};function lA(){return{user:(0,ii.join)((0,g_.homedir)(),".claude","olympus","config.jsonc"),project:(0,ii.join)(process.cwd(),".claude","olympus.jsonc")}}function m_(e){if(!(0,ai.existsSync)(e))return null;try{let t=(0,ai.readFileSync)(e,"utf-8"),n=[],r=f_(t,n,{allowTrailingComma:!0,allowEmptyContent:!0});return n.length>0&&console.warn(`Warning: Parse errors in ${e}:`,n),r}catch(t){return console.error(`Error loading config from ${e}:`,t),null}}function si(e,t){let n={...e};for(let r of Object.keys(t)){let o=t[r],s=n[r];o!==void 0&&typeof o=="object"&&o!==null&&!Array.isArray(o)&&typeof s=="object"&&s!==null&&!Array.isArray(s)?n[r]=si(s,o):o!==void 0&&(n[r]=o)}return n}function uA(){let e={};if(process.env.EXA_API_KEY&&(e.mcpServers={...e.mcpServers,exa:{enabled:!0,apiKey:process.env.EXA_API_KEY}}),process.env.OLYMPUS_PARALLEL_EXECUTION!==void 0&&(e.features={...e.features,parallelExecution:process.env.OLYMPUS_PARALLEL_EXECUTION==="true"}),process.env.OLYMPUS_LSP_TOOLS!==void 0&&(e.features={...e.features,lspTools:process.env.OLYMPUS_LSP_TOOLS==="true"}),process.env.OLYMPUS_MAX_BACKGROUND_TASKS){let t=parseInt(process.env.OLYMPUS_MAX_BACKGROUND_TASKS,10);isNaN(t)||(e.permissions={...e.permissions,maxBackgroundTasks:t})}if(process.env.OLYMPUS_ROUTING_ENABLED!==void 0&&(e.routing={...e.routing,enabled:process.env.OLYMPUS_ROUTING_ENABLED==="true"}),process.env.OLYMPUS_ROUTING_DEFAULT_TIER){let t=process.env.OLYMPUS_ROUTING_DEFAULT_TIER.toUpperCase();(t==="LOW"||t==="MEDIUM"||t==="HIGH")&&(e.routing={...e.routing,defaultTier:t})}if(process.env.OLYMPUS_ESCALATION_ENABLED!==void 0&&(e.routing={...e.routing,escalationEnabled:process.env.OLYMPUS_ESCALATION_ENABLED==="true"}),process.env.OLYMPUS_MAX_ASCENT_ITERATIONS){let t=parseInt(process.env.OLYMPUS_MAX_ASCENT_ITERATIONS,10);!isNaN(t)&&t>=10&&t<=1e3?e.ascent={...e.ascent,maxIterations:t}:isNaN(t)||console.warn(`Warning: OLYMPUS_MAX_ASCENT_ITERATIONS must be between 10 and 1000. Got: ${t}`)}return e}function h_(){let e=lA(),t={...cA},n=m_(e.user);n&&(t=si(t,n));let r=m_(e.project);r&&(t=si(t,r));let o=uA();return t=si(t,o),t}function dA(e){let t=e.hooks;return t&&typeof t.timeoutMs=="number"?t.timeoutMs:5e3}function pA(e,t){let n=e.hooks;if(n&&typeof n.enabled=="boolean"&&!n.enabled)return!1;if(n&&t in n){let r=n[t];if(typeof r=="object"&&r!==null){let o=r.enabled;if(typeof o=="boolean")return o}}return!0}async function fA(e,t){return Promise.race([Promise.resolve(e()),new Promise(n=>setTimeout(()=>n(null),t))])}function mA(e,t){return!e||!t?!0:(typeof e=="string"?new RegExp(e,"i"):e).test(t)}async function y_(e,t){let n=h_(),r=vl(e),o=dA(n),s=!0,i=[],a,c=t.toolInput,l=t.messages;for(let u of r)if(pA(n,u.name)&&mA(u.matcher,t.toolName))try{let d=await fA(()=>u.handler({...t,toolInput:c,messages:l}),o);if(d===null){console.error(`[hook-router] ${u.name} timed out after ${o}ms`);continue}d.continue||(s=!1,a=d.stopReason),d.message&&i.push(d.message),d.hookSpecificOutput?.additionalContext&&i.push(d.hookSpecificOutput.additionalContext),d.modifiedInput!==void 0&&(c=d.modifiedInput),d.modifiedMessages!==void 0&&(l=d.modifiedMessages)}catch(d){console.error(`[hook-router] ${u.name} error:`,d)}return{continue:s,message:i.length>0?i.join(`
2226
2226
 
2227
2227
  ---
2228
2228
 
2229
- `):void 0,stopReason:a,modifiedInput:c!==t.toolInput?c:void 0,modifiedMessages:l!==t.messages?l:void 0}}tk();async function tI(){return process.stdin.isTTY?"{}":new Promise(e=>{let t=[],n=!1,r=setTimeout(()=>{process.stdin.pause(),process.stdin.destroy(),e(n?Buffer.concat(t).toString("utf-8"):"{}")},1e3);process.stdin.on("data",o=>{n=!0,t.push(o)}),process.stdin.on("end",()=>{clearTimeout(r),e(n?Buffer.concat(t).toString("utf-8"):"{}")}),process.stdin.on("error",()=>{clearTimeout(r),e("{}")}),process.stdin.resume()})}async function fk(){let t=process.argv.slice(2).find(a=>a.startsWith("--event="));t||(console.error("Usage: node olympus-hooks.mjs --event=<event-type>"),process.exit(1));let n=t.split("=")[1],r=await tI(),o;try{let a=JSON.parse(r);o={...a,directory:a.cwd||a.directory,sessionId:a.session_id||a.sessionId,toolName:a.tool_name||a.toolName,toolInput:a.tool_input||a.toolInput,toolOutput:a.tool_response||a.toolOutput}}catch{o={}}let s=await pk(n,o),i={continue:s.continue};s.stopReason&&(i.stopReason=s.stopReason),s.message&&(n==="PreToolUse"||n==="UserPromptSubmit"||n==="PostToolUse"?i.hookSpecificOutput={hookEventName:n,additionalContext:s.message}:i.reason=s.message),console.log(JSON.stringify(i)),process.exit(0)}var ii=process.argv[1]||"",nI=ii.endsWith("entry.ts")||ii.endsWith("entry.js")||ii.endsWith("olympus-hooks.mjs")||ii.includes("olympus-hooks");nI&&fk().catch(e=>{console.error("[olympus-hooks] Fatal error:",e),process.exit(1)});0&&(module.exports={main});
2229
+ `):void 0,stopReason:a,modifiedInput:c!==t.toolInput?c:void 0,modifiedMessages:l!==t.messages?l:void 0}}i_();async function gA(){return process.stdin.isTTY?"{}":new Promise(e=>{let t=[],n=!1,r=setTimeout(()=>{process.stdin.pause(),process.stdin.destroy(),e(n?Buffer.concat(t).toString("utf-8"):"{}")},1e3);process.stdin.on("data",o=>{n=!0,t.push(o)}),process.stdin.on("end",()=>{clearTimeout(r),e(n?Buffer.concat(t).toString("utf-8"):"{}")}),process.stdin.on("error",()=>{clearTimeout(r),e("{}")}),process.stdin.resume()})}async function w_(){let t=process.argv.slice(2).find(a=>a.startsWith("--event="));t||(console.error("Usage: node olympus-hooks.mjs --event=<event-type>"),process.exit(1));let n=t.split("=")[1],r=await gA(),o;try{let a=JSON.parse(r);o={...a,directory:a.cwd||a.directory,sessionId:a.session_id||a.sessionId,toolName:a.tool_name||a.toolName,toolInput:a.tool_input||a.toolInput,toolOutput:a.tool_response||a.toolOutput}}catch{o={}}let s=await y_(n,o),i={continue:s.continue};s.stopReason&&(i.stopReason=s.stopReason),s.message&&(n==="PreToolUse"||n==="UserPromptSubmit"||n==="PostToolUse"?i.hookSpecificOutput={hookEventName:n,additionalContext:s.message}:i.reason=s.message),console.log(JSON.stringify(i)),process.exit(0)}var ci=process.argv[1]||"",hA=ci.endsWith("entry.ts")||ci.endsWith("entry.js")||ci.endsWith("olympus-hooks.mjs")||ci.includes("olympus-hooks");hA&&w_().catch(e=>{console.error("[olympus-hooks] Fatal error:",e),process.exit(1)});0&&(module.exports={main});