olympus-ai 4.4.3 → 4.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,31 +1,31 @@
1
1
  #!/usr/bin/env node
2
2
  // Olympus Hooks Bundle - Generated by esbuild
3
- "use strict";var fh=Object.create;var Io=Object.defineProperty;var mh=Object.getOwnPropertyDescriptor;var gh=Object.getOwnPropertyNames;var hh=Object.getPrototypeOf,yh=Object.prototype.hasOwnProperty;var B=(e,t)=>()=>(e&&(t=e(e=0)),t);var U=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),st=(e,t)=>{for(var n in t)Io(e,n,{get:t[n],enumerable:!0})},ja=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of gh(t))!yh.call(e,r)&&r!==n&&Io(e,r,{get:()=>t[r],enumerable:!(o=mh(t,r))||o.enumerable});return e};var b=(e,t,n)=>(n=e!=null?fh(hh(e)):{},ja(t||!e||!e.__esModule?Io(n,"default",{value:e,enumerable:!0}):n,e)),kh=e=>ja(Io({},"__esModule",{value:!0}),e);var mi,hc=B(()=>{"use strict";mi={maxAgeInDays:30,maxArchiveCount:5}});function gi(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 rn(e){return gi(e)?.total_tokens||0}var yc=B(()=>{"use strict"});function Fh(e){let t=(0,sn.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 o=(0,wc.createHash)("sha256").update(e).digest("hex").substring(0,8);return`${n}-${o}`}function Wt(e){return(0,sn.join)(ae(),"projects",Fh(e))}function hi(e){try{(0,kc.mkdirSync)(Wt(e),{recursive:!0})}catch(t){t.code!=="EEXIST"&&console.error("Failed to create project directory:",t)}}var sn,Lh,kc,wc,_c=B(()=>{"use strict";sn=require("path"),Lh=require("child_process"),kc=require("fs"),wc=require("crypto");fe();Ae()});function ae(){return process.env.OLYMPUS_TEST_LEARNING_DIR?process.env.OLYMPUS_TEST_LEARNING_DIR:(0,ee.join)((0,vc.homedir)(),".claude","olympus","learning")}function Qe(e){return(0,ee.join)(e,".olympus","learning")}function Ec(e){let t=(0,ee.resolve)(e);return(0,Tc.createHash)("sha256").update(t).digest("hex").substring(0,16)}function cn(e){let t=ae();if((0,q.existsSync)(t)||(0,q.mkdirSync)(t,{recursive:!0}),e){let n=Qe(e);(0,q.existsSync)(n)||(0,q.mkdirSync)(n,{recursive:!0})}}function Wh(e,t=mi){try{let n=(0,ee.dirname)(e),o=(0,ee.basename)(e,".jsonl"),r=(0,q.readdirSync)(n),i=new RegExp(`^${o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\..*\\.old\\.jsonl$`),s=r.filter(d=>i.test(d)).map(d=>{let f=d.match(/\.(\d{4}-\d{2}-\d{2})T/),m=f?new Date(f[1]):null;return{filename:d,filepath:(0,ee.join)(n,d),timestamp:m}}).filter(d=>d.timestamp!==null&&!isNaN(d.timestamp.getTime())).sort((d,f)=>f.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<s.length;d++){let f=s[d],m=f.timestamp<l,p=d>=c;if(m||p)try{(0,q.unlinkSync)(f.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 an(e,t=Uh,n=mi){if((0,q.existsSync)(e))try{let r=(0,q.readFileSync)(e,"utf-8").split(`
4
- `).filter(i=>i.trim()).length;if(r>=t){let i=new Date().toISOString().replace(/[:.]/g,"-"),s=e.replace(".jsonl",`.${i}.old.jsonl`);(0,q.renameSync)(e,s),console.log(`[Olympus Learning] Archived ${r} entries to ${s}`),Wh(e,n)}}catch(o){console.error(`[Olympus Learning] Failed to rotate ${e}:`,o)}}function St(e){if(e.project_path&&typeof e.project_path=="string")try{hi(e.project_path);let n=(0,ee.join)(Wt(e.project_path),"feedback-log.jsonl");an(n),(0,q.appendFileSync)(n,JSON.stringify(e)+`
3
+ "use strict";var gh=Object.create;var Ro=Object.defineProperty;var hh=Object.getOwnPropertyDescriptor;var yh=Object.getOwnPropertyNames;var kh=Object.getPrototypeOf,wh=Object.prototype.hasOwnProperty;var B=(e,t)=>()=>(e&&(t=e(e=0)),t);var U=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),st=(e,t)=>{for(var n in t)Ro(e,n,{get:t[n],enumerable:!0})},La=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of yh(t))!wh.call(e,r)&&r!==n&&Ro(e,r,{get:()=>t[r],enumerable:!(o=hh(t,r))||o.enumerable});return e};var b=(e,t,n)=>(n=e!=null?gh(kh(e)):{},La(t||!e||!e.__esModule?Ro(n,"default",{value:e,enumerable:!0}):n,e)),Sh=e=>La(Ro({},"__esModule",{value:!0}),e);var mi,kc=B(()=>{"use strict";mi={maxAgeInDays:30,maxArchiveCount:5}});function gi(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 rn(e){return gi(e)?.total_tokens||0}var wc=B(()=>{"use strict"});function Wh(e){let t=(0,sn.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 o=(0,_c.createHash)("sha256").update(e).digest("hex").substring(0,8);return`${n}-${o}`}function Wt(e){return(0,sn.join)(ae(),"projects",Wh(e))}function hi(e){try{(0,Sc.mkdirSync)(Wt(e),{recursive:!0})}catch(t){t.code!=="EEXIST"&&console.error("Failed to create project directory:",t)}}var sn,Uh,Sc,_c,vc=B(()=>{"use strict";sn=require("path"),Uh=require("child_process"),Sc=require("fs"),_c=require("crypto");fe();Pe()});function ae(){return process.env.OLYMPUS_TEST_LEARNING_DIR?process.env.OLYMPUS_TEST_LEARNING_DIR:(0,ee.join)((0,Ec.homedir)(),".claude","olympus","learning")}function Qe(e){return(0,ee.join)(e,".olympus","learning")}function Cc(e){let t=(0,ee.resolve)(e);return(0,bc.createHash)("sha256").update(t).digest("hex").substring(0,16)}function cn(e){let t=ae();if((0,q.existsSync)(t)||(0,q.mkdirSync)(t,{recursive:!0}),e){let n=Qe(e);(0,q.existsSync)(n)||(0,q.mkdirSync)(n,{recursive:!0})}}function Gh(e,t=mi){try{let n=(0,ee.dirname)(e),o=(0,ee.basename)(e,".jsonl"),r=(0,q.readdirSync)(n),i=new RegExp(`^${o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\..*\\.old\\.jsonl$`),s=r.filter(d=>i.test(d)).map(d=>{let f=d.match(/\.(\d{4}-\d{2}-\d{2})T/),m=f?new Date(f[1]):null;return{filename:d,filepath:(0,ee.join)(n,d),timestamp:m}}).filter(d=>d.timestamp!==null&&!isNaN(d.timestamp.getTime())).sort((d,f)=>f.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<s.length;d++){let f=s[d],m=f.timestamp<l,p=d>=c;if(m||p)try{(0,q.unlinkSync)(f.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 an(e,t=Hh,n=mi){if((0,q.existsSync)(e))try{let r=(0,q.readFileSync)(e,"utf-8").split(`
4
+ `).filter(i=>i.trim()).length;if(r>=t){let i=new Date().toISOString().replace(/[:.]/g,"-"),s=e.replace(".jsonl",`.${i}.old.jsonl`);(0,q.renameSync)(e,s),console.log(`[Olympus Learning] Archived ${r} entries to ${s}`),Gh(e,n)}}catch(o){console.error(`[Olympus Learning] Failed to rotate ${e}:`,o)}}function _t(e){if(e.project_path&&typeof e.project_path=="string")try{hi(e.project_path);let n=(0,ee.join)(Wt(e.project_path),"feedback-log.jsonl");an(n),(0,q.appendFileSync)(n,JSON.stringify(e)+`
5
5
  `,"utf-8");return}catch(n){console.error("[Olympus Learning] Project write failed, using global fallback:",n)}cn();let t=(0,ee.join)(ae(),"feedback-log.jsonl");an(t),(0,q.appendFileSync)(t,JSON.stringify(e)+`
6
- `,"utf-8")}function xo(e){let t=e?(0,ee.join)(Wt(e),"feedback-log.jsonl"):(0,ee.join)(ae(),"feedback-log.jsonl");return(0,q.existsSync)(t)?(0,q.readFileSync)(t,"utf-8").split(`
7
- `).filter(o=>o.trim()).map(o=>JSON.parse(o)):[]}function Hh(e){let t=e.filter(r=>r.event_type==="revision"||r.event_type==="cancellation"),n=new Map;for(let r of t){let i=r.extracted_lesson||r.feedback_category||"unknown",s=n.get(i);s?(s.count++,s.examples.length<3&&s.examples.push(r.user_message.substring(0,100))):n.set(i,{count:1,examples:[r.user_message.substring(0,100)]})}let o=[];for(let[r,i]of n)i.count>=2&&o.push({pattern:r,count:i.count,examples:i.examples});return o}function Gh(e){let t=[];return e>=.85&&t.push("high success rate"),t}function Bh(e,t){let n=[];return e<.6&&n.push("low success rate"),t>2&&n.push("frequently cancelled"),n}function $o(e,t,n){let o=t.filter(p=>p.agent_used===e);if(o.length===0)return null;let r=o.length,i=o.filter(p=>p.event_type==="success").length,s=o.filter(p=>p.event_type==="revision").length,a=o.filter(p=>p.event_type==="cancellation").length,c=r>0?i/r:0,l,u=o.filter(p=>gi(p)!==null);if(u.length>0){let p=u.filter(v=>v.event_type==="success"),g=u.filter(v=>v.event_type==="revision"||v.event_type==="cancellation"),h=u.reduce((v,R)=>v+rn(R),0),y=p.reduce((v,R)=>v+rn(R),0),w=g.reduce((v,R)=>v+rn(R),0),k=p.length>0?y/p.length:0,A=g.length>0?w/g.length:0;if(l={avg_tokens_per_success:k,avg_tokens_per_failure:A,total_tokens:h,invocation_count:u.length,efficiency_score:k,trend:"insufficient_data"},u.length>=10){let v=Math.floor(u.length/2),R=u.slice(0,v),C=u.slice(v),Z=R.reduce((P,M)=>P+rn(M),0)/R.length,O=C.reduce((P,M)=>P+rn(M),0)/C.length-Z,x=Z*.1;Math.abs(O)<x?l.trend="stable":O<0?l.trend="improving":l.trend="declining"}}let d={agent_name:e,total_invocations:r,success_count:i,revision_count:s,cancellation_count:a,success_rate:c,failure_patterns:Hh(o),strong_areas:Gh(c),weak_areas:Bh(c,a),last_updated:new Date().toISOString(),token_efficiency:l};if(n)try{let p=(0,ee.join)(Wt(n),"agent-performance.json"),g=me(p,{});g[e]=d,Ge(p,g)}catch(p){console.error("[Olympus Learning] Failed to write project agent performance:",p)}let f=(0,ee.join)(ae(),"agent-performance.json"),m=me(f,{});return m[e]=d,Ge(f,m),d}function ln(e){let t=e?(0,ee.join)(Wt(e),"agent-performance.json"):(0,ee.join)(ae(),"agent-performance.json");return me(t,{})}function me(e,t){if(!(0,q.existsSync)(e))return t;try{return JSON.parse((0,q.readFileSync)(e,"utf-8"))}catch(n){return console.error(`[Olympus Learning] Failed to read ${e}:`,n),t}}function Ge(e,t){try{let n=(0,ee.dirname)(e);n&&!(0,q.existsSync)(n)&&(0,q.mkdirSync)(n,{recursive:!0}),(0,q.writeFileSync)(e,JSON.stringify(t,null,2),"utf-8")}catch(n){console.error(`[Olympus Learning] Failed to write ${e}:`,n)}}function bc(e,t){if(t)try{hi(t);let o=(0,ee.join)(Wt(t),"session-summaries.jsonl");an(o,Sc),(0,q.appendFileSync)(o,JSON.stringify(e)+`
8
- `,"utf-8");return}catch(o){console.error("[Olympus Learning] Project session summary write failed, using global fallback:",o)}cn();let n=(0,ee.join)(ae(),"session-summaries.jsonl");an(n,Sc),(0,q.appendFileSync)(n,JSON.stringify(e)+`
9
- `,"utf-8")}var vc,ee,q,Tc,Uh,Sc,fe=B(()=>{"use strict";vc=require("os"),ee=require("path"),q=require("fs"),Tc=require("crypto");hc();yc();_c();Uh=1e4,Sc=500});function Ht(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 yi=B(()=>{"use strict"});function Oc(e){return(0,Ic.join)(e,".olympus","session-state.json")}function Cc(e,t){let n=Ht();return{session_id:e||(0,Rc.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 V(e,t){let n=Oc(e),o=me(n,null);if(!o)return Cc(t,e);let r=new Date(o.last_updated).getTime();if(Date.now()-r>Vh)return Cc(t,e);if(t&&o.session_id!==t&&(o.session_id=t),o.token_budget)o.token_budget.input_tokens===void 0&&(o.token_budget.input_tokens=0),o.token_budget.output_tokens===void 0&&(o.token_budget.output_tokens=0);else{let s=Ht();o.token_budget={session_baseline:s,current_usage:0,input_tokens:0,output_tokens:0,warning_threshold:1.5,warning_issued:!1,started_at:o.started_at}}return o.discovery_volume||(o.discovery_volume={session_count:0,daily_count:0,daily_reset_at:new Date().toISOString()}),o.resolved_project_root===void 0&&(o.resolved_project_root=null),o}function Q(e,t){let n=Oc(e);t.last_updated=new Date().toISOString(),Ge(n,t)}function Ac(e,t,n){let o={prompt:t,timestamp:new Date().toISOString(),detected_feedback:n};return e.recent_prompts=[o,...e.recent_prompts].slice(0,qh),e.last_updated=new Date().toISOString(),e}function Pc(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 xc(e){return e.pending_completion=null,e.last_updated=new Date().toISOString(),e}function No(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 $c(e,t){let n=Ht();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 Nc(e,t){return e.token_budget||(e.token_budget={session_baseline:Ht(),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 Dc(e){return e.token_budget&&(e.token_budget.warning_issued=!0,e.last_updated=new Date().toISOString()),e}function jc(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 Mc(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 Lc(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 Ic,Rc,qh,Vh,Ae=B(()=>{"use strict";Ic=require("path");fe();Rc=require("crypto");yi();qh=10,Vh=1800*1e3});var ce=U(wi=>{"use strict";wi.fromCallback=function(e){return Object.defineProperty(function(...t){if(typeof t[t.length-1]=="function")e.apply(this,t);else return new Promise((n,o)=>{t.push((r,i)=>r!=null?o(r):n(i)),e.apply(this,t)})},"name",{value:e.name})};wi.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(o=>n(null,o),n)},"name",{value:e.name})}});var Bc=U(($b,Gc)=>{var vt=require("constants"),Kh=process.cwd,Do=null,Jh=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return Do||(Do=Kh.call(process)),Do};try{process.cwd()}catch{}typeof process.chdir=="function"&&(_i=process.chdir,process.chdir=function(e){Do=null,_i.call(process,e)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,_i));var _i;Gc.exports=zh;function zh(e){vt.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&t(e),e.lutimes||n(e),e.chown=i(e.chown),e.fchown=i(e.fchown),e.lchown=i(e.lchown),e.chmod=o(e.chmod),e.fchmod=o(e.fchmod),e.lchmod=o(e.lchmod),e.chownSync=s(e.chownSync),e.fchownSync=s(e.fchownSync),e.lchownSync=s(e.lchownSync),e.chmodSync=r(e.chmodSync),e.fchmodSync=r(e.fchmodSync),e.lchmodSync=r(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,f){f&&process.nextTick(f)},e.lchmodSync=function(){}),e.chown&&!e.lchown&&(e.lchown=function(u,d,f,m){m&&process.nextTick(m)},e.lchownSync=function(){}),Jh==="win32"&&(e.rename=typeof e.rename!="function"?e.rename:(function(u){function d(f,m,p){var g=Date.now(),h=0;u(f,m,function y(w){if(w&&(w.code==="EACCES"||w.code==="EPERM"||w.code==="EBUSY")&&Date.now()-g<6e4){setTimeout(function(){e.stat(m,function(k,A){k&&k.code==="ENOENT"?u(f,m,y):p(w)})},h),h<100&&(h+=10);return}p&&p(w)})}return Object.setPrototypeOf&&Object.setPrototypeOf(d,u),d})(e.rename)),e.read=typeof e.read!="function"?e.read:(function(u){function d(f,m,p,g,h,y){var w;if(y&&typeof y=="function"){var k=0;w=function(A,v,R){if(A&&A.code==="EAGAIN"&&k<10)return k++,u.call(e,f,m,p,g,h,w);y.apply(this,arguments)}}return u.call(e,f,m,p,g,h,w)}return Object.setPrototypeOf&&Object.setPrototypeOf(d,u),d})(e.read),e.readSync=typeof e.readSync!="function"?e.readSync:(function(u){return function(d,f,m,p,g){for(var h=0;;)try{return u.call(e,d,f,m,p,g)}catch(y){if(y.code==="EAGAIN"&&h<10){h++;continue}throw y}}})(e.readSync);function t(u){u.lchmod=function(d,f,m){u.open(d,vt.O_WRONLY|vt.O_SYMLINK,f,function(p,g){if(p){m&&m(p);return}u.fchmod(g,f,function(h){u.close(g,function(y){m&&m(h||y)})})})},u.lchmodSync=function(d,f){var m=u.openSync(d,vt.O_WRONLY|vt.O_SYMLINK,f),p=!0,g;try{g=u.fchmodSync(m,f),p=!1}finally{if(p)try{u.closeSync(m)}catch{}else u.closeSync(m)}return g}}function n(u){vt.hasOwnProperty("O_SYMLINK")&&u.futimes?(u.lutimes=function(d,f,m,p){u.open(d,vt.O_SYMLINK,function(g,h){if(g){p&&p(g);return}u.futimes(h,f,m,function(y){u.close(h,function(w){p&&p(y||w)})})})},u.lutimesSync=function(d,f,m){var p=u.openSync(d,vt.O_SYMLINK),g,h=!0;try{g=u.futimesSync(p,f,m),h=!1}finally{if(h)try{u.closeSync(p)}catch{}else u.closeSync(p)}return g}):u.futimes&&(u.lutimes=function(d,f,m,p){p&&process.nextTick(p)},u.lutimesSync=function(){})}function o(u){return u&&function(d,f,m){return u.call(e,d,f,function(p){l(p)&&(p=null),m&&m.apply(this,arguments)})}}function r(u){return u&&function(d,f){try{return u.call(e,d,f)}catch(m){if(!l(m))throw m}}}function i(u){return u&&function(d,f,m,p){return u.call(e,d,f,m,function(g){l(g)&&(g=null),p&&p.apply(this,arguments)})}}function s(u){return u&&function(d,f,m){try{return u.call(e,d,f,m)}catch(p){if(!l(p))throw p}}}function a(u){return u&&function(d,f,m){typeof f=="function"&&(m=f,f=null);function p(g,h){h&&(h.uid<0&&(h.uid+=4294967296),h.gid<0&&(h.gid+=4294967296)),m&&m.apply(this,arguments)}return f?u.call(e,d,f,p):u.call(e,d,p)}}function c(u){return u&&function(d,f){var m=f?u.call(e,d,f):u.call(e,d);return m&&(m.uid<0&&(m.uid+=4294967296),m.gid<0&&(m.gid+=4294967296)),m}}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 Yc=U((Nb,Vc)=>{var qc=require("stream").Stream;Vc.exports=Qh;function Qh(e){return{ReadStream:t,WriteStream:n};function t(o,r){if(!(this instanceof t))return new t(o,r);qc.call(this);var i=this;this.path=o,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=64*1024,r=r||{};for(var s=Object.keys(r),a=0,c=s.length;a<c;a++){var l=s[a];this[l]=r[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(){i._read()});return}e.open(this.path,this.flags,this.mode,function(u,d){if(u){i.emit("error",u),i.readable=!1;return}i.fd=d,i.emit("open",d),i._read()})}function n(o,r){if(!(this instanceof n))return new n(o,r);qc.call(this),this.path=o,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,r=r||{};for(var i=Object.keys(r),s=0,a=i.length;s<a;s++){var c=i[s];this[c]=r[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 Jc=U((Db,Kc)=>{"use strict";Kc.exports=Zh;var Xh=Object.getPrototypeOf||function(e){return e.__proto__};function Zh(e){if(e===null||typeof e!="object")return e;if(e instanceof Object)var t={__proto__:Xh(e)};else var t=Object.create(null);return Object.getOwnPropertyNames(e).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(e,n))}),t}});var dn=U((jb,Ti)=>{var X=require("fs"),ey=Bc(),ty=Yc(),ny=Jc(),jo=require("util"),ge,Lo;typeof Symbol=="function"&&typeof Symbol.for=="function"?(ge=Symbol.for("graceful-fs.queue"),Lo=Symbol.for("graceful-fs.previous")):(ge="___graceful-fs.queue",Lo="___graceful-fs.previous");function oy(){}function Xc(e,t){Object.defineProperty(e,ge,{get:function(){return t}})}var Gt=oy;jo.debuglog?Gt=jo.debuglog("gfs4"):/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&(Gt=function(){var e=jo.format.apply(jo,arguments);e="GFS4: "+e.split(/\n/).join(`
10
- GFS4: `),console.error(e)});X[ge]||(zc=global[ge]||[],Xc(X,zc),X.close=(function(e){function t(n,o){return e.call(X,n,function(r){r||Qc(),typeof o=="function"&&o.apply(this,arguments)})}return Object.defineProperty(t,Lo,{value:e}),t})(X.close),X.closeSync=(function(e){function t(n){e.apply(X,arguments),Qc()}return Object.defineProperty(t,Lo,{value:e}),t})(X.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&process.on("exit",function(){Gt(X[ge]),require("assert").equal(X[ge].length,0)}));var zc;global[ge]||Xc(global,X[ge]);Ti.exports=Si(ny(X));process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!X.__patched&&(Ti.exports=Si(X),X.__patched=!0);function Si(e){ey(e),e.gracefulify=Si,e.createReadStream=v,e.createWriteStream=R;var t=e.readFile;e.readFile=n;function n(S,O,x){return typeof O=="function"&&(x=O,O=null),P(S,O,x);function P(M,E,N,Y){return t(M,E,function(H){H&&(H.code==="EMFILE"||H.code==="ENFILE")?un([P,[M,E,N],H,Y||Date.now(),Date.now()]):typeof N=="function"&&N.apply(this,arguments)})}}var o=e.writeFile;e.writeFile=r;function r(S,O,x,P){return typeof x=="function"&&(P=x,x=null),M(S,O,x,P);function M(E,N,Y,H,de){return o(E,N,Y,function(z){z&&(z.code==="EMFILE"||z.code==="ENFILE")?un([M,[E,N,Y,H],z,de||Date.now(),Date.now()]):typeof H=="function"&&H.apply(this,arguments)})}}var i=e.appendFile;i&&(e.appendFile=s);function s(S,O,x,P){return typeof x=="function"&&(P=x,x=null),M(S,O,x,P);function M(E,N,Y,H,de){return i(E,N,Y,function(z){z&&(z.code==="EMFILE"||z.code==="ENFILE")?un([M,[E,N,Y,H],z,de||Date.now(),Date.now()]):typeof H=="function"&&H.apply(this,arguments)})}}var a=e.copyFile;a&&(e.copyFile=c);function c(S,O,x,P){return typeof x=="function"&&(P=x,x=0),M(S,O,x,P);function M(E,N,Y,H,de){return a(E,N,Y,function(z){z&&(z.code==="EMFILE"||z.code==="ENFILE")?un([M,[E,N,Y,H],z,de||Date.now(),Date.now()]):typeof H=="function"&&H.apply(this,arguments)})}}var l=e.readdir;e.readdir=d;var u=/^v[0-5]\./;function d(S,O,x){typeof O=="function"&&(x=O,O=null);var P=u.test(process.version)?function(N,Y,H,de){return l(N,M(N,Y,H,de))}:function(N,Y,H,de){return l(N,Y,M(N,Y,H,de))};return P(S,O,x);function M(E,N,Y,H){return function(de,z){de&&(de.code==="EMFILE"||de.code==="ENFILE")?un([P,[E,N,Y],de,H||Date.now(),Date.now()]):(z&&z.sort&&z.sort(),typeof Y=="function"&&Y.call(this,de,z))}}}if(process.version.substr(0,4)==="v0.8"){var f=ty(e);y=f.ReadStream,k=f.WriteStream}var m=e.ReadStream;m&&(y.prototype=Object.create(m.prototype),y.prototype.open=w);var p=e.WriteStream;p&&(k.prototype=Object.create(p.prototype),k.prototype.open=A),Object.defineProperty(e,"ReadStream",{get:function(){return y},set:function(S){y=S},enumerable:!0,configurable:!0}),Object.defineProperty(e,"WriteStream",{get:function(){return k},set:function(S){k=S},enumerable:!0,configurable:!0});var g=y;Object.defineProperty(e,"FileReadStream",{get:function(){return g},set:function(S){g=S},enumerable:!0,configurable:!0});var h=k;Object.defineProperty(e,"FileWriteStream",{get:function(){return h},set:function(S){h=S},enumerable:!0,configurable:!0});function y(S,O){return this instanceof y?(m.apply(this,arguments),this):y.apply(Object.create(y.prototype),arguments)}function w(){var S=this;Z(S.path,S.flags,S.mode,function(O,x){O?(S.autoClose&&S.destroy(),S.emit("error",O)):(S.fd=x,S.emit("open",x),S.read())})}function k(S,O){return this instanceof k?(p.apply(this,arguments),this):k.apply(Object.create(k.prototype),arguments)}function A(){var S=this;Z(S.path,S.flags,S.mode,function(O,x){O?(S.destroy(),S.emit("error",O)):(S.fd=x,S.emit("open",x))})}function v(S,O){return new e.ReadStream(S,O)}function R(S,O){return new e.WriteStream(S,O)}var C=e.open;e.open=Z;function Z(S,O,x,P){return typeof x=="function"&&(P=x,x=null),M(S,O,x,P);function M(E,N,Y,H,de){return C(E,N,Y,function(z,$E){z&&(z.code==="EMFILE"||z.code==="ENFILE")?un([M,[E,N,Y,H],z,de||Date.now(),Date.now()]):typeof H=="function"&&H.apply(this,arguments)})}}return e}function un(e){Gt("ENQUEUE",e[0].name,e[1]),X[ge].push(e),vi()}var Mo;function Qc(){for(var e=Date.now(),t=0;t<X[ge].length;++t)X[ge][t].length>2&&(X[ge][t][3]=e,X[ge][t][4]=e);vi()}function vi(){if(clearTimeout(Mo),Mo=void 0,X[ge].length!==0){var e=X[ge].shift(),t=e[0],n=e[1],o=e[2],r=e[3],i=e[4];if(r===void 0)Gt("RETRY",t.name,n),t.apply(null,n);else if(Date.now()-r>=6e4){Gt("TIMEOUT",t.name,n);var s=n.pop();typeof s=="function"&&s.call(null,o)}else{var a=Date.now()-i,c=Math.max(i-r,1),l=Math.min(c*1.2,100);a>=l?(Gt("RETRY",t.name,n),t.apply(null,n.concat([r]))):X[ge].push(e)}Mo===void 0&&(Mo=setTimeout(vi,0))}}});var Se=U(ct=>{"use strict";var Zc=ce().fromCallback,_e=dn(),ry=["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 _e[e]=="function");Object.assign(ct,_e);ry.forEach(e=>{ct[e]=Zc(_e[e])});ct.exists=function(e,t){return typeof t=="function"?_e.exists(e,t):new Promise(n=>_e.exists(e,n))};ct.read=function(e,t,n,o,r,i){return typeof i=="function"?_e.read(e,t,n,o,r,i):new Promise((s,a)=>{_e.read(e,t,n,o,r,(c,l,u)=>{if(c)return a(c);s({bytesRead:l,buffer:u})})})};ct.write=function(e,t,...n){return typeof n[n.length-1]=="function"?_e.write(e,t,...n):new Promise((o,r)=>{_e.write(e,t,...n,(i,s,a)=>{if(i)return r(i);o({bytesWritten:s,buffer:a})})})};ct.readv=function(e,t,...n){return typeof n[n.length-1]=="function"?_e.readv(e,t,...n):new Promise((o,r)=>{_e.readv(e,t,...n,(i,s,a)=>{if(i)return r(i);o({bytesRead:s,buffers:a})})})};ct.writev=function(e,t,...n){return typeof n[n.length-1]=="function"?_e.writev(e,t,...n):new Promise((o,r)=>{_e.writev(e,t,...n,(i,s,a)=>{if(i)return r(i);o({bytesWritten:s,buffers:a})})})};typeof _e.realpath.native=="function"?ct.realpath.native=Zc(_e.realpath.native):process.emitWarning("fs.realpath.native is not a function. Is fs being monkey-patched?","Warning","fs-extra-WARN0003")});var tl=U((Lb,el)=>{"use strict";var iy=require("path");el.exports.checkPath=function(t){if(process.platform==="win32"&&/[<>:"|?*]/.test(t.replace(iy.parse(t).root,""))){let o=new Error(`Path contains invalid characters: ${t}`);throw o.code="EINVAL",o}}});var il=U((Fb,Ei)=>{"use strict";var nl=Se(),{checkPath:ol}=tl(),rl=e=>{let t={mode:511};return typeof e=="number"?e:{...t,...e}.mode};Ei.exports.makeDir=async(e,t)=>(ol(e),nl.mkdir(e,{mode:rl(t),recursive:!0}));Ei.exports.makeDirSync=(e,t)=>(ol(e),nl.mkdirSync(e,{mode:rl(t),recursive:!0}))});var Be=U((Ub,sl)=>{"use strict";var sy=ce().fromPromise,{makeDir:ay,makeDirSync:bi}=il(),Ci=sy(ay);sl.exports={mkdirs:Ci,mkdirsSync:bi,mkdirp:Ci,mkdirpSync:bi,ensureDir:Ci,ensureDirSync:bi}});var Tt=U((Wb,cl)=>{"use strict";var cy=ce().fromPromise,al=Se();function ly(e){return al.access(e).then(()=>!0).catch(()=>!1)}cl.exports={pathExists:cy(ly),pathExistsSync:al.existsSync}});var Ii=U((Hb,ll)=>{"use strict";var pn=Se(),uy=ce().fromPromise;async function dy(e,t,n){let o=await pn.open(e,"r+"),r=null;try{await pn.futimes(o,t,n)}finally{try{await pn.close(o)}catch(i){r=i}}if(r)throw r}function py(e,t,n){let o=pn.openSync(e,"r+");return pn.futimesSync(o,t,n),pn.closeSync(o)}ll.exports={utimesMillis:uy(dy),utimesMillisSync:py}});var Bt=U((Gb,fl)=>{"use strict";var fn=Se(),le=require("path"),ul=ce().fromPromise;function fy(e,t,n){let o=n.dereference?r=>fn.stat(r,{bigint:!0}):r=>fn.lstat(r,{bigint:!0});return Promise.all([o(e),o(t).catch(r=>{if(r.code==="ENOENT")return null;throw r})]).then(([r,i])=>({srcStat:r,destStat:i}))}function my(e,t,n){let o,r=n.dereference?s=>fn.statSync(s,{bigint:!0}):s=>fn.lstatSync(s,{bigint:!0}),i=r(e);try{o=r(t)}catch(s){if(s.code==="ENOENT")return{srcStat:i,destStat:null};throw s}return{srcStat:i,destStat:o}}async function gy(e,t,n,o){let{srcStat:r,destStat:i}=await fy(e,t,o);if(i){if(zn(r,i)){let s=le.basename(e),a=le.basename(t);if(n==="move"&&s!==a&&s.toLowerCase()===a.toLowerCase())return{srcStat:r,destStat:i,isChangingCase:!0};throw new Error("Source and destination must not be the same.")}if(r.isDirectory()&&!i.isDirectory())throw new Error(`Cannot overwrite non-directory '${t}' with directory '${e}'.`);if(!r.isDirectory()&&i.isDirectory())throw new Error(`Cannot overwrite directory '${t}' with non-directory '${e}'.`)}if(r.isDirectory()&&Ri(e,t))throw new Error(Fo(e,t,n));return{srcStat:r,destStat:i}}function hy(e,t,n,o){let{srcStat:r,destStat:i}=my(e,t,o);if(i){if(zn(r,i)){let s=le.basename(e),a=le.basename(t);if(n==="move"&&s!==a&&s.toLowerCase()===a.toLowerCase())return{srcStat:r,destStat:i,isChangingCase:!0};throw new Error("Source and destination must not be the same.")}if(r.isDirectory()&&!i.isDirectory())throw new Error(`Cannot overwrite non-directory '${t}' with directory '${e}'.`);if(!r.isDirectory()&&i.isDirectory())throw new Error(`Cannot overwrite directory '${t}' with non-directory '${e}'.`)}if(r.isDirectory()&&Ri(e,t))throw new Error(Fo(e,t,n));return{srcStat:r,destStat:i}}async function dl(e,t,n,o){let r=le.resolve(le.dirname(e)),i=le.resolve(le.dirname(n));if(i===r||i===le.parse(i).root)return;let s;try{s=await fn.stat(i,{bigint:!0})}catch(a){if(a.code==="ENOENT")return;throw a}if(zn(t,s))throw new Error(Fo(e,n,o));return dl(e,t,i,o)}function pl(e,t,n,o){let r=le.resolve(le.dirname(e)),i=le.resolve(le.dirname(n));if(i===r||i===le.parse(i).root)return;let s;try{s=fn.statSync(i,{bigint:!0})}catch(a){if(a.code==="ENOENT")return;throw a}if(zn(t,s))throw new Error(Fo(e,n,o));return pl(e,t,i,o)}function zn(e,t){return t.ino!==void 0&&t.dev!==void 0&&t.ino===e.ino&&t.dev===e.dev}function Ri(e,t){let n=le.resolve(e).split(le.sep).filter(r=>r),o=le.resolve(t).split(le.sep).filter(r=>r);return n.every((r,i)=>o[i]===r)}function Fo(e,t,n){return`Cannot ${n} '${e}' to a subdirectory of itself, '${t}'.`}fl.exports={checkPaths:ul(gy),checkPathsSync:hy,checkParentPaths:ul(dl),checkParentPathsSync:pl,isSrcSubdir:Ri,areIdentical:zn}});var gl=U((Bb,ml)=>{"use strict";async function yy(e,t){let n=[];for await(let o of e)n.push(t(o).then(()=>null,r=>r??new Error("unknown error")));await Promise.all(n.map(o=>o.then(r=>{if(r!==null)throw r})))}ml.exports={asyncIteratorConcurrentProcess:yy}});var _l=U((qb,wl)=>{"use strict";var ke=Se(),Qn=require("path"),{mkdirs:ky}=Be(),{pathExists:wy}=Tt(),{utimesMillis:_y}=Ii(),Xn=Bt(),{asyncIteratorConcurrentProcess:Sy}=gl();async function vy(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;
6
+ `,"utf-8")}function $o(e){let t=e?(0,ee.join)(Wt(e),"feedback-log.jsonl"):(0,ee.join)(ae(),"feedback-log.jsonl");return(0,q.existsSync)(t)?(0,q.readFileSync)(t,"utf-8").split(`
7
+ `).filter(o=>o.trim()).map(o=>JSON.parse(o)):[]}function Bh(e){let t=e.filter(r=>r.event_type==="revision"||r.event_type==="cancellation"),n=new Map;for(let r of t){let i=r.extracted_lesson||r.feedback_category||"unknown",s=n.get(i);s?(s.count++,s.examples.length<3&&s.examples.push(r.user_message.substring(0,100))):n.set(i,{count:1,examples:[r.user_message.substring(0,100)]})}let o=[];for(let[r,i]of n)i.count>=2&&o.push({pattern:r,count:i.count,examples:i.examples});return o}function qh(e){let t=[];return e>=.85&&t.push("high success rate"),t}function Vh(e,t){let n=[];return e<.6&&n.push("low success rate"),t>2&&n.push("frequently cancelled"),n}function No(e,t,n){let o=t.filter(p=>p.agent_used===e);if(o.length===0)return null;let r=o.length,i=o.filter(p=>p.event_type==="success").length,s=o.filter(p=>p.event_type==="revision").length,a=o.filter(p=>p.event_type==="cancellation").length,c=r>0?i/r:0,l,u=o.filter(p=>gi(p)!==null);if(u.length>0){let p=u.filter(v=>v.event_type==="success"),g=u.filter(v=>v.event_type==="revision"||v.event_type==="cancellation"),h=u.reduce((v,R)=>v+rn(R),0),y=p.reduce((v,R)=>v+rn(R),0),w=g.reduce((v,R)=>v+rn(R),0),k=p.length>0?y/p.length:0,A=g.length>0?w/g.length:0;if(l={avg_tokens_per_success:k,avg_tokens_per_failure:A,total_tokens:h,invocation_count:u.length,efficiency_score:k,trend:"insufficient_data"},u.length>=10){let v=Math.floor(u.length/2),R=u.slice(0,v),I=u.slice(v),Z=R.reduce((P,M)=>P+rn(M),0)/R.length,O=I.reduce((P,M)=>P+rn(M),0)/I.length-Z,x=Z*.1;Math.abs(O)<x?l.trend="stable":O<0?l.trend="improving":l.trend="declining"}}let d={agent_name:e,total_invocations:r,success_count:i,revision_count:s,cancellation_count:a,success_rate:c,failure_patterns:Bh(o),strong_areas:qh(c),weak_areas:Vh(c,a),last_updated:new Date().toISOString(),token_efficiency:l};if(n)try{let p=(0,ee.join)(Wt(n),"agent-performance.json"),g=me(p,{});g[e]=d,Ge(p,g)}catch(p){console.error("[Olympus Learning] Failed to write project agent performance:",p)}let f=(0,ee.join)(ae(),"agent-performance.json"),m=me(f,{});return m[e]=d,Ge(f,m),d}function ln(e){let t=e?(0,ee.join)(Wt(e),"agent-performance.json"):(0,ee.join)(ae(),"agent-performance.json");return me(t,{})}function me(e,t){if(!(0,q.existsSync)(e))return t;try{return JSON.parse((0,q.readFileSync)(e,"utf-8"))}catch(n){return console.error(`[Olympus Learning] Failed to read ${e}:`,n),t}}function Ge(e,t){try{let n=(0,ee.dirname)(e);n&&!(0,q.existsSync)(n)&&(0,q.mkdirSync)(n,{recursive:!0}),(0,q.writeFileSync)(e,JSON.stringify(t,null,2),"utf-8")}catch(n){console.error(`[Olympus Learning] Failed to write ${e}:`,n)}}function Ic(e,t){if(t)try{hi(t);let o=(0,ee.join)(Wt(t),"session-summaries.jsonl");an(o,Tc),(0,q.appendFileSync)(o,JSON.stringify(e)+`
8
+ `,"utf-8");return}catch(o){console.error("[Olympus Learning] Project session summary write failed, using global fallback:",o)}cn();let n=(0,ee.join)(ae(),"session-summaries.jsonl");an(n,Tc),(0,q.appendFileSync)(n,JSON.stringify(e)+`
9
+ `,"utf-8")}var Ec,ee,q,bc,Hh,Tc,fe=B(()=>{"use strict";Ec=require("os"),ee=require("path"),q=require("fs"),bc=require("crypto");kc();wc();vc();Hh=1e4,Tc=500});function Ht(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 yi=B(()=>{"use strict"});function Pc(e){return(0,Oc.join)(e,".olympus","session-state.json")}function Rc(e,t){let n=Ht();return{session_id:e||(0,Ac.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 V(e,t){let n=Pc(e),o=me(n,null);if(!o)return Rc(t,e);let r=new Date(o.last_updated).getTime();if(Date.now()-r>Kh)return Rc(t,e);if(t&&o.session_id!==t&&(o.session_id=t),o.token_budget)o.token_budget.input_tokens===void 0&&(o.token_budget.input_tokens=0),o.token_budget.output_tokens===void 0&&(o.token_budget.output_tokens=0);else{let s=Ht();o.token_budget={session_baseline:s,current_usage:0,input_tokens:0,output_tokens:0,warning_threshold:1.5,warning_issued:!1,started_at:o.started_at}}return o.discovery_volume||(o.discovery_volume={session_count:0,daily_count:0,daily_reset_at:new Date().toISOString()}),o.resolved_project_root===void 0&&(o.resolved_project_root=null),o}function Q(e,t){let n=Pc(e);t.last_updated=new Date().toISOString(),Ge(n,t)}function xc(e,t,n){let o={prompt:t,timestamp:new Date().toISOString(),detected_feedback:n};return e.recent_prompts=[o,...e.recent_prompts].slice(0,Yh),e.last_updated=new Date().toISOString(),e}function $c(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 Nc(e){return e.pending_completion=null,e.last_updated=new Date().toISOString(),e}function Do(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 Dc(e,t){let n=Ht();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 jc(e,t){return e.token_budget||(e.token_budget={session_baseline:Ht(),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 Mc(e){return e.token_budget&&(e.token_budget.warning_issued=!0,e.last_updated=new Date().toISOString()),e}function Lc(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 Fc(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 Uc(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 Oc,Ac,Yh,Kh,Pe=B(()=>{"use strict";Oc=require("path");fe();Ac=require("crypto");yi();Yh=10,Kh=1800*1e3});var ce=U(wi=>{"use strict";wi.fromCallback=function(e){return Object.defineProperty(function(...t){if(typeof t[t.length-1]=="function")e.apply(this,t);else return new Promise((n,o)=>{t.push((r,i)=>r!=null?o(r):n(i)),e.apply(this,t)})},"name",{value:e.name})};wi.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(o=>n(null,o),n)},"name",{value:e.name})}});var Vc=U((Db,qc)=>{var vt=require("constants"),zh=process.cwd,jo=null,Qh=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return jo||(jo=zh.call(process)),jo};try{process.cwd()}catch{}typeof process.chdir=="function"&&(Si=process.chdir,process.chdir=function(e){jo=null,Si.call(process,e)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,Si));var Si;qc.exports=Xh;function Xh(e){vt.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&t(e),e.lutimes||n(e),e.chown=i(e.chown),e.fchown=i(e.fchown),e.lchown=i(e.lchown),e.chmod=o(e.chmod),e.fchmod=o(e.fchmod),e.lchmod=o(e.lchmod),e.chownSync=s(e.chownSync),e.fchownSync=s(e.fchownSync),e.lchownSync=s(e.lchownSync),e.chmodSync=r(e.chmodSync),e.fchmodSync=r(e.fchmodSync),e.lchmodSync=r(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,f){f&&process.nextTick(f)},e.lchmodSync=function(){}),e.chown&&!e.lchown&&(e.lchown=function(u,d,f,m){m&&process.nextTick(m)},e.lchownSync=function(){}),Qh==="win32"&&(e.rename=typeof e.rename!="function"?e.rename:(function(u){function d(f,m,p){var g=Date.now(),h=0;u(f,m,function y(w){if(w&&(w.code==="EACCES"||w.code==="EPERM"||w.code==="EBUSY")&&Date.now()-g<6e4){setTimeout(function(){e.stat(m,function(k,A){k&&k.code==="ENOENT"?u(f,m,y):p(w)})},h),h<100&&(h+=10);return}p&&p(w)})}return Object.setPrototypeOf&&Object.setPrototypeOf(d,u),d})(e.rename)),e.read=typeof e.read!="function"?e.read:(function(u){function d(f,m,p,g,h,y){var w;if(y&&typeof y=="function"){var k=0;w=function(A,v,R){if(A&&A.code==="EAGAIN"&&k<10)return k++,u.call(e,f,m,p,g,h,w);y.apply(this,arguments)}}return u.call(e,f,m,p,g,h,w)}return Object.setPrototypeOf&&Object.setPrototypeOf(d,u),d})(e.read),e.readSync=typeof e.readSync!="function"?e.readSync:(function(u){return function(d,f,m,p,g){for(var h=0;;)try{return u.call(e,d,f,m,p,g)}catch(y){if(y.code==="EAGAIN"&&h<10){h++;continue}throw y}}})(e.readSync);function t(u){u.lchmod=function(d,f,m){u.open(d,vt.O_WRONLY|vt.O_SYMLINK,f,function(p,g){if(p){m&&m(p);return}u.fchmod(g,f,function(h){u.close(g,function(y){m&&m(h||y)})})})},u.lchmodSync=function(d,f){var m=u.openSync(d,vt.O_WRONLY|vt.O_SYMLINK,f),p=!0,g;try{g=u.fchmodSync(m,f),p=!1}finally{if(p)try{u.closeSync(m)}catch{}else u.closeSync(m)}return g}}function n(u){vt.hasOwnProperty("O_SYMLINK")&&u.futimes?(u.lutimes=function(d,f,m,p){u.open(d,vt.O_SYMLINK,function(g,h){if(g){p&&p(g);return}u.futimes(h,f,m,function(y){u.close(h,function(w){p&&p(y||w)})})})},u.lutimesSync=function(d,f,m){var p=u.openSync(d,vt.O_SYMLINK),g,h=!0;try{g=u.futimesSync(p,f,m),h=!1}finally{if(h)try{u.closeSync(p)}catch{}else u.closeSync(p)}return g}):u.futimes&&(u.lutimes=function(d,f,m,p){p&&process.nextTick(p)},u.lutimesSync=function(){})}function o(u){return u&&function(d,f,m){return u.call(e,d,f,function(p){l(p)&&(p=null),m&&m.apply(this,arguments)})}}function r(u){return u&&function(d,f){try{return u.call(e,d,f)}catch(m){if(!l(m))throw m}}}function i(u){return u&&function(d,f,m,p){return u.call(e,d,f,m,function(g){l(g)&&(g=null),p&&p.apply(this,arguments)})}}function s(u){return u&&function(d,f,m){try{return u.call(e,d,f,m)}catch(p){if(!l(p))throw p}}}function a(u){return u&&function(d,f,m){typeof f=="function"&&(m=f,f=null);function p(g,h){h&&(h.uid<0&&(h.uid+=4294967296),h.gid<0&&(h.gid+=4294967296)),m&&m.apply(this,arguments)}return f?u.call(e,d,f,p):u.call(e,d,p)}}function c(u){return u&&function(d,f){var m=f?u.call(e,d,f):u.call(e,d);return m&&(m.uid<0&&(m.uid+=4294967296),m.gid<0&&(m.gid+=4294967296)),m}}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 Jc=U((jb,Kc)=>{var Yc=require("stream").Stream;Kc.exports=Zh;function Zh(e){return{ReadStream:t,WriteStream:n};function t(o,r){if(!(this instanceof t))return new t(o,r);Yc.call(this);var i=this;this.path=o,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=64*1024,r=r||{};for(var s=Object.keys(r),a=0,c=s.length;a<c;a++){var l=s[a];this[l]=r[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(){i._read()});return}e.open(this.path,this.flags,this.mode,function(u,d){if(u){i.emit("error",u),i.readable=!1;return}i.fd=d,i.emit("open",d),i._read()})}function n(o,r){if(!(this instanceof n))return new n(o,r);Yc.call(this),this.path=o,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,r=r||{};for(var i=Object.keys(r),s=0,a=i.length;s<a;s++){var c=i[s];this[c]=r[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 Qc=U((Mb,zc)=>{"use strict";zc.exports=ty;var ey=Object.getPrototypeOf||function(e){return e.__proto__};function ty(e){if(e===null||typeof e!="object")return e;if(e instanceof Object)var t={__proto__:ey(e)};else var t=Object.create(null);return Object.getOwnPropertyNames(e).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(e,n))}),t}});var dn=U((Lb,Ti)=>{var X=require("fs"),ny=Vc(),oy=Jc(),ry=Qc(),Mo=require("util"),ge,Fo;typeof Symbol=="function"&&typeof Symbol.for=="function"?(ge=Symbol.for("graceful-fs.queue"),Fo=Symbol.for("graceful-fs.previous")):(ge="___graceful-fs.queue",Fo="___graceful-fs.previous");function iy(){}function el(e,t){Object.defineProperty(e,ge,{get:function(){return t}})}var Gt=iy;Mo.debuglog?Gt=Mo.debuglog("gfs4"):/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&(Gt=function(){var e=Mo.format.apply(Mo,arguments);e="GFS4: "+e.split(/\n/).join(`
10
+ GFS4: `),console.error(e)});X[ge]||(Xc=global[ge]||[],el(X,Xc),X.close=(function(e){function t(n,o){return e.call(X,n,function(r){r||Zc(),typeof o=="function"&&o.apply(this,arguments)})}return Object.defineProperty(t,Fo,{value:e}),t})(X.close),X.closeSync=(function(e){function t(n){e.apply(X,arguments),Zc()}return Object.defineProperty(t,Fo,{value:e}),t})(X.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&process.on("exit",function(){Gt(X[ge]),require("assert").equal(X[ge].length,0)}));var Xc;global[ge]||el(global,X[ge]);Ti.exports=_i(ry(X));process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!X.__patched&&(Ti.exports=_i(X),X.__patched=!0);function _i(e){ny(e),e.gracefulify=_i,e.createReadStream=v,e.createWriteStream=R;var t=e.readFile;e.readFile=n;function n(_,O,x){return typeof O=="function"&&(x=O,O=null),P(_,O,x);function P(M,E,N,Y){return t(M,E,function(H){H&&(H.code==="EMFILE"||H.code==="ENFILE")?un([P,[M,E,N],H,Y||Date.now(),Date.now()]):typeof N=="function"&&N.apply(this,arguments)})}}var o=e.writeFile;e.writeFile=r;function r(_,O,x,P){return typeof x=="function"&&(P=x,x=null),M(_,O,x,P);function M(E,N,Y,H,de){return o(E,N,Y,function(z){z&&(z.code==="EMFILE"||z.code==="ENFILE")?un([M,[E,N,Y,H],z,de||Date.now(),Date.now()]):typeof H=="function"&&H.apply(this,arguments)})}}var i=e.appendFile;i&&(e.appendFile=s);function s(_,O,x,P){return typeof x=="function"&&(P=x,x=null),M(_,O,x,P);function M(E,N,Y,H,de){return i(E,N,Y,function(z){z&&(z.code==="EMFILE"||z.code==="ENFILE")?un([M,[E,N,Y,H],z,de||Date.now(),Date.now()]):typeof H=="function"&&H.apply(this,arguments)})}}var a=e.copyFile;a&&(e.copyFile=c);function c(_,O,x,P){return typeof x=="function"&&(P=x,x=0),M(_,O,x,P);function M(E,N,Y,H,de){return a(E,N,Y,function(z){z&&(z.code==="EMFILE"||z.code==="ENFILE")?un([M,[E,N,Y,H],z,de||Date.now(),Date.now()]):typeof H=="function"&&H.apply(this,arguments)})}}var l=e.readdir;e.readdir=d;var u=/^v[0-5]\./;function d(_,O,x){typeof O=="function"&&(x=O,O=null);var P=u.test(process.version)?function(N,Y,H,de){return l(N,M(N,Y,H,de))}:function(N,Y,H,de){return l(N,Y,M(N,Y,H,de))};return P(_,O,x);function M(E,N,Y,H){return function(de,z){de&&(de.code==="EMFILE"||de.code==="ENFILE")?un([P,[E,N,Y],de,H||Date.now(),Date.now()]):(z&&z.sort&&z.sort(),typeof Y=="function"&&Y.call(this,de,z))}}}if(process.version.substr(0,4)==="v0.8"){var f=oy(e);y=f.ReadStream,k=f.WriteStream}var m=e.ReadStream;m&&(y.prototype=Object.create(m.prototype),y.prototype.open=w);var p=e.WriteStream;p&&(k.prototype=Object.create(p.prototype),k.prototype.open=A),Object.defineProperty(e,"ReadStream",{get:function(){return y},set:function(_){y=_},enumerable:!0,configurable:!0}),Object.defineProperty(e,"WriteStream",{get:function(){return k},set:function(_){k=_},enumerable:!0,configurable:!0});var g=y;Object.defineProperty(e,"FileReadStream",{get:function(){return g},set:function(_){g=_},enumerable:!0,configurable:!0});var h=k;Object.defineProperty(e,"FileWriteStream",{get:function(){return h},set:function(_){h=_},enumerable:!0,configurable:!0});function y(_,O){return this instanceof y?(m.apply(this,arguments),this):y.apply(Object.create(y.prototype),arguments)}function w(){var _=this;Z(_.path,_.flags,_.mode,function(O,x){O?(_.autoClose&&_.destroy(),_.emit("error",O)):(_.fd=x,_.emit("open",x),_.read())})}function k(_,O){return this instanceof k?(p.apply(this,arguments),this):k.apply(Object.create(k.prototype),arguments)}function A(){var _=this;Z(_.path,_.flags,_.mode,function(O,x){O?(_.destroy(),_.emit("error",O)):(_.fd=x,_.emit("open",x))})}function v(_,O){return new e.ReadStream(_,O)}function R(_,O){return new e.WriteStream(_,O)}var I=e.open;e.open=Z;function Z(_,O,x,P){return typeof x=="function"&&(P=x,x=null),M(_,O,x,P);function M(E,N,Y,H,de){return I(E,N,Y,function(z,DE){z&&(z.code==="EMFILE"||z.code==="ENFILE")?un([M,[E,N,Y,H],z,de||Date.now(),Date.now()]):typeof H=="function"&&H.apply(this,arguments)})}}return e}function un(e){Gt("ENQUEUE",e[0].name,e[1]),X[ge].push(e),vi()}var Lo;function Zc(){for(var e=Date.now(),t=0;t<X[ge].length;++t)X[ge][t].length>2&&(X[ge][t][3]=e,X[ge][t][4]=e);vi()}function vi(){if(clearTimeout(Lo),Lo=void 0,X[ge].length!==0){var e=X[ge].shift(),t=e[0],n=e[1],o=e[2],r=e[3],i=e[4];if(r===void 0)Gt("RETRY",t.name,n),t.apply(null,n);else if(Date.now()-r>=6e4){Gt("TIMEOUT",t.name,n);var s=n.pop();typeof s=="function"&&s.call(null,o)}else{var a=Date.now()-i,c=Math.max(i-r,1),l=Math.min(c*1.2,100);a>=l?(Gt("RETRY",t.name,n),t.apply(null,n.concat([r]))):X[ge].push(e)}Lo===void 0&&(Lo=setTimeout(vi,0))}}});var _e=U(ct=>{"use strict";var tl=ce().fromCallback,Se=dn(),sy=["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 Se[e]=="function");Object.assign(ct,Se);sy.forEach(e=>{ct[e]=tl(Se[e])});ct.exists=function(e,t){return typeof t=="function"?Se.exists(e,t):new Promise(n=>Se.exists(e,n))};ct.read=function(e,t,n,o,r,i){return typeof i=="function"?Se.read(e,t,n,o,r,i):new Promise((s,a)=>{Se.read(e,t,n,o,r,(c,l,u)=>{if(c)return a(c);s({bytesRead:l,buffer:u})})})};ct.write=function(e,t,...n){return typeof n[n.length-1]=="function"?Se.write(e,t,...n):new Promise((o,r)=>{Se.write(e,t,...n,(i,s,a)=>{if(i)return r(i);o({bytesWritten:s,buffer:a})})})};ct.readv=function(e,t,...n){return typeof n[n.length-1]=="function"?Se.readv(e,t,...n):new Promise((o,r)=>{Se.readv(e,t,...n,(i,s,a)=>{if(i)return r(i);o({bytesRead:s,buffers:a})})})};ct.writev=function(e,t,...n){return typeof n[n.length-1]=="function"?Se.writev(e,t,...n):new Promise((o,r)=>{Se.writev(e,t,...n,(i,s,a)=>{if(i)return r(i);o({bytesWritten:s,buffers:a})})})};typeof Se.realpath.native=="function"?ct.realpath.native=tl(Se.realpath.native):process.emitWarning("fs.realpath.native is not a function. Is fs being monkey-patched?","Warning","fs-extra-WARN0003")});var ol=U((Ub,nl)=>{"use strict";var ay=require("path");nl.exports.checkPath=function(t){if(process.platform==="win32"&&/[<>:"|?*]/.test(t.replace(ay.parse(t).root,""))){let o=new Error(`Path contains invalid characters: ${t}`);throw o.code="EINVAL",o}}});var al=U((Wb,Ei)=>{"use strict";var rl=_e(),{checkPath:il}=ol(),sl=e=>{let t={mode:511};return typeof e=="number"?e:{...t,...e}.mode};Ei.exports.makeDir=async(e,t)=>(il(e),rl.mkdir(e,{mode:sl(t),recursive:!0}));Ei.exports.makeDirSync=(e,t)=>(il(e),rl.mkdirSync(e,{mode:sl(t),recursive:!0}))});var Be=U((Hb,cl)=>{"use strict";var cy=ce().fromPromise,{makeDir:ly,makeDirSync:bi}=al(),Ci=cy(ly);cl.exports={mkdirs:Ci,mkdirsSync:bi,mkdirp:Ci,mkdirpSync:bi,ensureDir:Ci,ensureDirSync:bi}});var Tt=U((Gb,ul)=>{"use strict";var uy=ce().fromPromise,ll=_e();function dy(e){return ll.access(e).then(()=>!0).catch(()=>!1)}ul.exports={pathExists:uy(dy),pathExistsSync:ll.existsSync}});var Ii=U((Bb,dl)=>{"use strict";var pn=_e(),py=ce().fromPromise;async function fy(e,t,n){let o=await pn.open(e,"r+"),r=null;try{await pn.futimes(o,t,n)}finally{try{await pn.close(o)}catch(i){r=i}}if(r)throw r}function my(e,t,n){let o=pn.openSync(e,"r+");return pn.futimesSync(o,t,n),pn.closeSync(o)}dl.exports={utimesMillis:py(fy),utimesMillisSync:my}});var Bt=U((qb,gl)=>{"use strict";var fn=_e(),le=require("path"),pl=ce().fromPromise;function gy(e,t,n){let o=n.dereference?r=>fn.stat(r,{bigint:!0}):r=>fn.lstat(r,{bigint:!0});return Promise.all([o(e),o(t).catch(r=>{if(r.code==="ENOENT")return null;throw r})]).then(([r,i])=>({srcStat:r,destStat:i}))}function hy(e,t,n){let o,r=n.dereference?s=>fn.statSync(s,{bigint:!0}):s=>fn.lstatSync(s,{bigint:!0}),i=r(e);try{o=r(t)}catch(s){if(s.code==="ENOENT")return{srcStat:i,destStat:null};throw s}return{srcStat:i,destStat:o}}async function yy(e,t,n,o){let{srcStat:r,destStat:i}=await gy(e,t,o);if(i){if(zn(r,i)){let s=le.basename(e),a=le.basename(t);if(n==="move"&&s!==a&&s.toLowerCase()===a.toLowerCase())return{srcStat:r,destStat:i,isChangingCase:!0};throw new Error("Source and destination must not be the same.")}if(r.isDirectory()&&!i.isDirectory())throw new Error(`Cannot overwrite non-directory '${t}' with directory '${e}'.`);if(!r.isDirectory()&&i.isDirectory())throw new Error(`Cannot overwrite directory '${t}' with non-directory '${e}'.`)}if(r.isDirectory()&&Ri(e,t))throw new Error(Uo(e,t,n));return{srcStat:r,destStat:i}}function ky(e,t,n,o){let{srcStat:r,destStat:i}=hy(e,t,o);if(i){if(zn(r,i)){let s=le.basename(e),a=le.basename(t);if(n==="move"&&s!==a&&s.toLowerCase()===a.toLowerCase())return{srcStat:r,destStat:i,isChangingCase:!0};throw new Error("Source and destination must not be the same.")}if(r.isDirectory()&&!i.isDirectory())throw new Error(`Cannot overwrite non-directory '${t}' with directory '${e}'.`);if(!r.isDirectory()&&i.isDirectory())throw new Error(`Cannot overwrite directory '${t}' with non-directory '${e}'.`)}if(r.isDirectory()&&Ri(e,t))throw new Error(Uo(e,t,n));return{srcStat:r,destStat:i}}async function fl(e,t,n,o){let r=le.resolve(le.dirname(e)),i=le.resolve(le.dirname(n));if(i===r||i===le.parse(i).root)return;let s;try{s=await fn.stat(i,{bigint:!0})}catch(a){if(a.code==="ENOENT")return;throw a}if(zn(t,s))throw new Error(Uo(e,n,o));return fl(e,t,i,o)}function ml(e,t,n,o){let r=le.resolve(le.dirname(e)),i=le.resolve(le.dirname(n));if(i===r||i===le.parse(i).root)return;let s;try{s=fn.statSync(i,{bigint:!0})}catch(a){if(a.code==="ENOENT")return;throw a}if(zn(t,s))throw new Error(Uo(e,n,o));return ml(e,t,i,o)}function zn(e,t){return t.ino!==void 0&&t.dev!==void 0&&t.ino===e.ino&&t.dev===e.dev}function Ri(e,t){let n=le.resolve(e).split(le.sep).filter(r=>r),o=le.resolve(t).split(le.sep).filter(r=>r);return n.every((r,i)=>o[i]===r)}function Uo(e,t,n){return`Cannot ${n} '${e}' to a subdirectory of itself, '${t}'.`}gl.exports={checkPaths:pl(yy),checkPathsSync:ky,checkParentPaths:pl(fl),checkParentPathsSync:ml,isSrcSubdir:Ri,areIdentical:zn}});var yl=U((Vb,hl)=>{"use strict";async function wy(e,t){let n=[];for await(let o of e)n.push(t(o).then(()=>null,r=>r??new Error("unknown error")));await Promise.all(n.map(o=>o.then(r=>{if(r!==null)throw r})))}hl.exports={asyncIteratorConcurrentProcess:wy}});var vl=U((Yb,_l)=>{"use strict";var ke=_e(),Qn=require("path"),{mkdirs:Sy}=Be(),{pathExists:_y}=Tt(),{utimesMillis:vy}=Ii(),Xn=Bt(),{asyncIteratorConcurrentProcess:Ty}=yl();async function Ey(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:o,destStat:r}=await Xn.checkPaths(e,t,"copy",n);if(await Xn.checkParentPaths(e,o,t,"copy"),!await yl(e,t,n))return;let s=Qn.dirname(t);await wy(s)||await ky(s),await kl(r,e,t,n)}async function yl(e,t,n){return n.filter?n.filter(e,t):!0}async function kl(e,t,n,o){let i=await(o.dereference?ke.stat:ke.lstat)(t);if(i.isDirectory())return Cy(i,e,t,n,o);if(i.isFile()||i.isCharacterDevice()||i.isBlockDevice())return Ty(i,e,t,n,o);if(i.isSymbolicLink())return Iy(e,t,n,o);throw i.isSocket()?new Error(`Cannot copy a socket file: ${t}`):i.isFIFO()?new Error(`Cannot copy a FIFO pipe: ${t}`):new Error(`Unknown file: ${t}`)}async function Ty(e,t,n,o,r){if(!t)return hl(e,n,o,r);if(r.overwrite)return await ke.unlink(o),hl(e,n,o,r);if(r.errorOnExist)throw new Error(`'${o}' already exists`)}async function hl(e,t,n,o){if(await ke.copyFile(t,n),o.preserveTimestamps){Ey(e.mode)&&await by(n,e.mode);let r=await ke.stat(t);await _y(n,r.atime,r.mtime)}return ke.chmod(n,e.mode)}function Ey(e){return(e&128)===0}function by(e,t){return ke.chmod(e,t|128)}async function Cy(e,t,n,o,r){t||await ke.mkdir(o),await Sy(await ke.opendir(n),async i=>{let s=Qn.join(n,i.name),a=Qn.join(o,i.name);if(await yl(s,a,r)){let{destStat:l}=await Xn.checkPaths(s,a,"copy",r);await kl(l,s,a,r)}}),t||await ke.chmod(o,e.mode)}async function Iy(e,t,n,o){let r=await ke.readlink(t);if(o.dereference&&(r=Qn.resolve(process.cwd(),r)),!e)return ke.symlink(r,n);let i=null;try{i=await ke.readlink(n)}catch(s){if(s.code==="EINVAL"||s.code==="UNKNOWN")return ke.symlink(r,n);throw s}if(o.dereference&&(i=Qn.resolve(process.cwd(),i)),r!==i){if(Xn.isSrcSubdir(r,i))throw new Error(`Cannot copy '${r}' to a subdirectory of itself, '${i}'.`);if(Xn.isSrcSubdir(i,r))throw new Error(`Cannot overwrite '${i}' with '${r}'.`)}return await ke.unlink(n),ke.symlink(r,n)}wl.exports=vy});var bl=U((Vb,El)=>{"use strict";var ve=dn(),Zn=require("path"),Ry=Be().mkdirsSync,Oy=Ii().utimesMillisSync,eo=Bt();function Ay(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:o,destStat:r}=await Xn.checkPaths(e,t,"copy",n);if(await Xn.checkParentPaths(e,o,t,"copy"),!await wl(e,t,n))return;let s=Qn.dirname(t);await _y(s)||await Sy(s),await Sl(r,e,t,n)}async function wl(e,t,n){return n.filter?n.filter(e,t):!0}async function Sl(e,t,n,o){let i=await(o.dereference?ke.stat:ke.lstat)(t);if(i.isDirectory())return Ry(i,e,t,n,o);if(i.isFile()||i.isCharacterDevice()||i.isBlockDevice())return by(i,e,t,n,o);if(i.isSymbolicLink())return Oy(e,t,n,o);throw i.isSocket()?new Error(`Cannot copy a socket file: ${t}`):i.isFIFO()?new Error(`Cannot copy a FIFO pipe: ${t}`):new Error(`Unknown file: ${t}`)}async function by(e,t,n,o,r){if(!t)return kl(e,n,o,r);if(r.overwrite)return await ke.unlink(o),kl(e,n,o,r);if(r.errorOnExist)throw new Error(`'${o}' already exists`)}async function kl(e,t,n,o){if(await ke.copyFile(t,n),o.preserveTimestamps){Cy(e.mode)&&await Iy(n,e.mode);let r=await ke.stat(t);await vy(n,r.atime,r.mtime)}return ke.chmod(n,e.mode)}function Cy(e){return(e&128)===0}function Iy(e,t){return ke.chmod(e,t|128)}async function Ry(e,t,n,o,r){t||await ke.mkdir(o),await Ty(await ke.opendir(n),async i=>{let s=Qn.join(n,i.name),a=Qn.join(o,i.name);if(await wl(s,a,r)){let{destStat:l}=await Xn.checkPaths(s,a,"copy",r);await Sl(l,s,a,r)}}),t||await ke.chmod(o,e.mode)}async function Oy(e,t,n,o){let r=await ke.readlink(t);if(o.dereference&&(r=Qn.resolve(process.cwd(),r)),!e)return ke.symlink(r,n);let i=null;try{i=await ke.readlink(n)}catch(s){if(s.code==="EINVAL"||s.code==="UNKNOWN")return ke.symlink(r,n);throw s}if(o.dereference&&(i=Qn.resolve(process.cwd(),i)),r!==i){if(Xn.isSrcSubdir(r,i))throw new Error(`Cannot copy '${r}' to a subdirectory of itself, '${i}'.`);if(Xn.isSrcSubdir(i,r))throw new Error(`Cannot overwrite '${i}' with '${r}'.`)}return await ke.unlink(n),ke.symlink(r,n)}_l.exports=Ey});var Il=U((Kb,Cl)=>{"use strict";var ve=dn(),Zn=require("path"),Ay=Be().mkdirsSync,Py=Ii().utimesMillisSync,eo=Bt();function xy(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:o,destStat:r}=eo.checkPathsSync(e,t,"copy",n);if(eo.checkParentPathsSync(e,o,t,"copy"),n.filter&&!n.filter(e,t))return;let i=Zn.dirname(t);return ve.existsSync(i)||Ry(i),Sl(r,e,t,n)}function Sl(e,t,n,o){let i=(o.dereference?ve.statSync:ve.lstatSync)(t);if(i.isDirectory())return My(i,e,t,n,o);if(i.isFile()||i.isCharacterDevice()||i.isBlockDevice())return Py(i,e,t,n,o);if(i.isSymbolicLink())return Uy(e,t,n,o);throw i.isSocket()?new Error(`Cannot copy a socket file: ${t}`):i.isFIFO()?new Error(`Cannot copy a FIFO pipe: ${t}`):new Error(`Unknown file: ${t}`)}function Py(e,t,n,o,r){return t?xy(e,n,o,r):vl(e,n,o,r)}function xy(e,t,n,o){if(o.overwrite)return ve.unlinkSync(n),vl(e,t,n,o);if(o.errorOnExist)throw new Error(`'${n}' already exists`)}function vl(e,t,n,o){return ve.copyFileSync(t,n),o.preserveTimestamps&&$y(e.mode,t,n),Oi(n,e.mode)}function $y(e,t,n){return Ny(e)&&Dy(n,e),jy(t,n)}function Ny(e){return(e&128)===0}function Dy(e,t){return Oi(e,t|128)}function Oi(e,t){return ve.chmodSync(e,t)}function jy(e,t){let n=ve.statSync(e);return Oy(t,n.atime,n.mtime)}function My(e,t,n,o,r){return t?Tl(n,o,r):Ly(e.mode,n,o,r)}function Ly(e,t,n,o){return ve.mkdirSync(n),Tl(t,n,o),Oi(n,e)}function Tl(e,t,n){let o=ve.opendirSync(e);try{let r;for(;(r=o.readSync())!==null;)Fy(r.name,e,t,n)}finally{o.closeSync()}}function Fy(e,t,n,o){let r=Zn.join(t,e),i=Zn.join(n,e);if(o.filter&&!o.filter(r,i))return;let{destStat:s}=eo.checkPathsSync(r,i,"copy",o);return Sl(s,r,i,o)}function Uy(e,t,n,o){let r=ve.readlinkSync(t);if(o.dereference&&(r=Zn.resolve(process.cwd(),r)),e){let i;try{i=ve.readlinkSync(n)}catch(s){if(s.code==="EINVAL"||s.code==="UNKNOWN")return ve.symlinkSync(r,n);throw s}if(o.dereference&&(i=Zn.resolve(process.cwd(),i)),r!==i){if(eo.isSrcSubdir(r,i))throw new Error(`Cannot copy '${r}' to a subdirectory of itself, '${i}'.`);if(eo.isSrcSubdir(i,r))throw new Error(`Cannot overwrite '${i}' with '${r}'.`)}return Wy(r,n)}else return ve.symlinkSync(r,n)}function Wy(e,t){return ve.unlinkSync(t),ve.symlinkSync(e,t)}El.exports=Ay});var Uo=U((Yb,Cl)=>{"use strict";var Hy=ce().fromPromise;Cl.exports={copy:Hy(_l()),copySync:bl()}});var to=U((Kb,Rl)=>{"use strict";var Il=dn(),Gy=ce().fromCallback;function By(e,t){Il.rm(e,{recursive:!0,force:!0},t)}function qy(e){Il.rmSync(e,{recursive:!0,force:!0})}Rl.exports={remove:Gy(By),removeSync:qy}});var jl=U((Jb,Dl)=>{"use strict";var Vy=ce().fromPromise,Pl=Se(),xl=require("path"),$l=Be(),Nl=to(),Ol=Vy(async function(t){let n;try{n=await Pl.readdir(t)}catch{return $l.mkdirs(t)}return Promise.all(n.map(o=>Nl.remove(xl.join(t,o))))});function Al(e){let t;try{t=Pl.readdirSync(e)}catch{return $l.mkdirsSync(e)}t.forEach(n=>{n=xl.join(e,n),Nl.removeSync(n)})}Dl.exports={emptyDirSync:Al,emptydirSync:Al,emptyDir:Ol,emptydir:Ol}});var Ul=U((zb,Fl)=>{"use strict";var Yy=ce().fromPromise,Ml=require("path"),lt=Se(),Ll=Be();async function Ky(e){let t;try{t=await lt.stat(e)}catch{}if(t&&t.isFile())return;let n=Ml.dirname(e),o=null;try{o=await lt.stat(n)}catch(r){if(r.code==="ENOENT"){await Ll.mkdirs(n),await lt.writeFile(e,"");return}else throw r}o.isDirectory()?await lt.writeFile(e,""):await lt.readdir(n)}function Jy(e){let t;try{t=lt.statSync(e)}catch{}if(t&&t.isFile())return;let n=Ml.dirname(e);try{lt.statSync(n).isDirectory()||lt.readdirSync(n)}catch(o){if(o&&o.code==="ENOENT")Ll.mkdirsSync(n);else throw o}lt.writeFileSync(e,"")}Fl.exports={createFile:Yy(Ky),createFileSync:Jy}});var ql=U((Qb,Bl)=>{"use strict";var zy=ce().fromPromise,Wl=require("path"),Et=Se(),Hl=Be(),{pathExists:Qy}=Tt(),{areIdentical:Gl}=Bt();async function Xy(e,t){let n;try{n=await Et.lstat(t)}catch{}let o;try{o=await Et.lstat(e)}catch(s){throw s.message=s.message.replace("lstat","ensureLink"),s}if(n&&Gl(o,n))return;let r=Wl.dirname(t);await Qy(r)||await Hl.mkdirs(r),await Et.link(e,t)}function Zy(e,t){let n;try{n=Et.lstatSync(t)}catch{}try{let i=Et.lstatSync(e);if(n&&Gl(i,n))return}catch(i){throw i.message=i.message.replace("lstat","ensureLink"),i}let o=Wl.dirname(t);return Et.existsSync(o)||Hl.mkdirsSync(o),Et.linkSync(e,t)}Bl.exports={createLink:zy(Xy),createLinkSync:Zy}});var Yl=U((Xb,Vl)=>{"use strict";var bt=require("path"),no=Se(),{pathExists:ek}=Tt(),tk=ce().fromPromise;async function nk(e,t){if(bt.isAbsolute(e)){try{await no.lstat(e)}catch(i){throw i.message=i.message.replace("lstat","ensureSymlink"),i}return{toCwd:e,toDst:e}}let n=bt.dirname(t),o=bt.join(n,e);if(await ek(o))return{toCwd:o,toDst:e};try{await no.lstat(e)}catch(i){throw i.message=i.message.replace("lstat","ensureSymlink"),i}return{toCwd:e,toDst:bt.relative(n,e)}}function ok(e,t){if(bt.isAbsolute(e)){if(!no.existsSync(e))throw new Error("absolute srcpath does not exist");return{toCwd:e,toDst:e}}let n=bt.dirname(t),o=bt.join(n,e);if(no.existsSync(o))return{toCwd:o,toDst:e};if(!no.existsSync(e))throw new Error("relative srcpath does not exist");return{toCwd:e,toDst:bt.relative(n,e)}}Vl.exports={symlinkPaths:tk(nk),symlinkPathsSync:ok}});var zl=U((Zb,Jl)=>{"use strict";var Kl=Se(),rk=ce().fromPromise;async function ik(e,t){if(t)return t;let n;try{n=await Kl.lstat(e)}catch{return"file"}return n&&n.isDirectory()?"dir":"file"}function sk(e,t){if(t)return t;let n;try{n=Kl.lstatSync(e)}catch{return"file"}return n&&n.isDirectory()?"dir":"file"}Jl.exports={symlinkType:rk(ik),symlinkTypeSync:sk}});var eu=U((eC,Zl)=>{"use strict";var ak=ce().fromPromise,Ql=require("path"),Xe=Se(),{mkdirs:ck,mkdirsSync:lk}=Be(),{symlinkPaths:uk,symlinkPathsSync:dk}=Yl(),{symlinkType:pk,symlinkTypeSync:fk}=zl(),{pathExists:mk}=Tt(),{areIdentical:Xl}=Bt();async function gk(e,t,n){let o;try{o=await Xe.lstat(t)}catch{}if(o&&o.isSymbolicLink()){let[a,c]=await Promise.all([Xe.stat(e),Xe.stat(t)]);if(Xl(a,c))return}let r=await uk(e,t);e=r.toDst;let i=await pk(r.toCwd,n),s=Ql.dirname(t);return await mk(s)||await ck(s),Xe.symlink(e,t,i)}function hk(e,t,n){let o;try{o=Xe.lstatSync(t)}catch{}if(o&&o.isSymbolicLink()){let a=Xe.statSync(e),c=Xe.statSync(t);if(Xl(a,c))return}let r=dk(e,t);e=r.toDst,n=fk(r.toCwd,n);let i=Ql.dirname(t);return Xe.existsSync(i)||lk(i),Xe.symlinkSync(e,t,n)}Zl.exports={createSymlink:ak(gk),createSymlinkSync:hk}});var cu=U((tC,au)=>{"use strict";var{createFile:tu,createFileSync:nu}=Ul(),{createLink:ou,createLinkSync:ru}=ql(),{createSymlink:iu,createSymlinkSync:su}=eu();au.exports={createFile:tu,createFileSync:nu,ensureFile:tu,ensureFileSync:nu,createLink:ou,createLinkSync:ru,ensureLink:ou,ensureLinkSync:ru,createSymlink:iu,createSymlinkSync:su,ensureSymlink:iu,ensureSymlinkSync:su}});var Wo=U((nC,lu)=>{function yk(e,{EOL:t=`
15
- `,finalEOL:n=!0,replacer:o=null,spaces:r}={}){let i=n?t:"";return JSON.stringify(e,o,r).replace(/\n/g,t)+i}function kk(e){return Buffer.isBuffer(e)&&(e=e.toString("utf8")),e.replace(/^\uFEFF/,"")}lu.exports={stringify:yk,stripBom:kk}});var fu=U((oC,pu)=>{var mn;try{mn=dn()}catch{mn=require("fs")}var Ho=ce(),{stringify:uu,stripBom:du}=Wo();async function wk(e,t={}){typeof t=="string"&&(t={encoding:t});let n=t.fs||mn,o="throws"in t?t.throws:!0,r=await Ho.fromCallback(n.readFile)(e,t);r=du(r);let i;try{i=JSON.parse(r,t?t.reviver:null)}catch(s){if(o)throw s.message=`${e}: ${s.message}`,s;return null}return i}var _k=Ho.fromPromise(wk);function Sk(e,t={}){typeof t=="string"&&(t={encoding:t});let n=t.fs||mn,o="throws"in t?t.throws:!0;try{let r=n.readFileSync(e,t);return r=du(r),JSON.parse(r,t.reviver)}catch(r){if(o)throw r.message=`${e}: ${r.message}`,r;return null}}async function vk(e,t,n={}){let o=n.fs||mn,r=uu(t,n);await Ho.fromCallback(o.writeFile)(e,r,n)}var Tk=Ho.fromPromise(vk);function Ek(e,t,n={}){let o=n.fs||mn,r=uu(t,n);return o.writeFileSync(e,r,n)}pu.exports={readFile:_k,readFileSync:Sk,writeFile:Tk,writeFileSync:Ek}});var gu=U((rC,mu)=>{"use strict";var Go=fu();mu.exports={readJson:Go.readFile,readJsonSync:Go.readFileSync,writeJson:Go.writeFile,writeJsonSync:Go.writeFileSync}});var Bo=U((iC,ku)=>{"use strict";var bk=ce().fromPromise,Ai=Se(),hu=require("path"),yu=Be(),Ck=Tt().pathExists;async function Ik(e,t,n="utf-8"){let o=hu.dirname(e);return await Ck(o)||await yu.mkdirs(o),Ai.writeFile(e,t,n)}function Rk(e,...t){let n=hu.dirname(e);Ai.existsSync(n)||yu.mkdirsSync(n),Ai.writeFileSync(e,...t)}ku.exports={outputFile:bk(Ik),outputFileSync:Rk}});var _u=U((sC,wu)=>{"use strict";var{stringify:Ok}=Wo(),{outputFile:Ak}=Bo();async function Pk(e,t,n={}){let o=Ok(t,n);await Ak(e,o,n)}wu.exports=Pk});var vu=U((aC,Su)=>{"use strict";var{stringify:xk}=Wo(),{outputFileSync:$k}=Bo();function Nk(e,t,n){let o=xk(t,n);$k(e,o,n)}Su.exports=Nk});var Eu=U((cC,Tu)=>{"use strict";var Dk=ce().fromPromise,Te=gu();Te.outputJson=Dk(_u());Te.outputJsonSync=vu();Te.outputJSON=Te.outputJson;Te.outputJSONSync=Te.outputJsonSync;Te.writeJSON=Te.writeJson;Te.writeJSONSync=Te.writeJsonSync;Te.readJSON=Te.readJson;Te.readJSONSync=Te.readJsonSync;Tu.exports=Te});var Ou=U((lC,Ru)=>{"use strict";var jk=Se(),bu=require("path"),{copy:Mk}=Uo(),{remove:Iu}=to(),{mkdirp:Lk}=Be(),{pathExists:Fk}=Tt(),Cu=Bt();async function Uk(e,t,n={}){let o=n.overwrite||n.clobber||!1,{srcStat:r,isChangingCase:i=!1}=await Cu.checkPaths(e,t,"move",n);await Cu.checkParentPaths(e,r,t,"move");let s=bu.dirname(t);return bu.parse(s).root!==s&&await Lk(s),Wk(e,t,o,i)}async function Wk(e,t,n,o){if(!o){if(n)await Iu(t);else if(await Fk(t))throw new Error("dest already exists.")}try{await jk.rename(e,t)}catch(r){if(r.code!=="EXDEV")throw r;await Hk(e,t,n)}}async function Hk(e,t,n){return await Mk(e,t,{overwrite:n,errorOnExist:!0,preserveTimestamps:!0}),Iu(e)}Ru.exports=Uk});var Nu=U((uC,$u)=>{"use strict";var Pu=dn(),xi=require("path"),Gk=Uo().copySync,xu=to().removeSync,Bk=Be().mkdirpSync,Au=Bt();function qk(e,t,n){n=n||{};let o=n.overwrite||n.clobber||!1,{srcStat:r,isChangingCase:i=!1}=Au.checkPathsSync(e,t,"move",n);return Au.checkParentPathsSync(e,r,t,"move"),Vk(t)||Bk(xi.dirname(t)),Yk(e,t,o,i)}function Vk(e){let t=xi.dirname(e);return xi.parse(t).root===t}function Yk(e,t,n,o){if(o)return Pi(e,t,n);if(n)return xu(t),Pi(e,t,n);if(Pu.existsSync(t))throw new Error("dest already exists.");return Pi(e,t,n)}function Pi(e,t,n){try{Pu.renameSync(e,t)}catch(o){if(o.code!=="EXDEV")throw o;return Kk(e,t,n)}}function Kk(e,t,n){return Gk(e,t,{overwrite:n,errorOnExist:!0,preserveTimestamps:!0}),xu(e)}$u.exports=qk});var ju=U((dC,Du)=>{"use strict";var Jk=ce().fromPromise;Du.exports={move:Jk(Ou()),moveSync:Nu()}});var ue=U((pC,Mu)=>{"use strict";Mu.exports={...Se(),...Uo(),...jl(),...cu(),...Eu(),...Be(),...ju(),...Bo(),...Tt(),...to()}});function $i(e,t){return`${e}:${t}`}function Qk(e){return Date.now()-e.timestamp<zk}function It(e,t){let n=$i(e,t);qo.delete(n)}async function $(e,t){let n=(0,Ze.join)(e,Ct,t.workflow_id),o=(0,Ze.join)(n,Vo);try{if(t.updated_at=new Date().toISOString(),t.schema_version="3.0.0",await K.ensureDir(n),JSON.stringify(t).length>1e4){let a=JSON.stringify(t);await K.writeFile(o,a,"utf-8")}else await K.writeJson(o,t,{spaces:2});let s=$i(e,t.workflow_id);qo.set(s,{checkpoint:structuredClone(t),timestamp:Date.now(),dirty:!1})}catch(r){let i=r;throw i.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: ${o}`),new Error("Failed to save checkpoint: Disk is full. Please free up space and retry.")):i.code==="EACCES"||i.code==="EPERM"?(console.error("[Checkpoint] Failed to save checkpoint: Permission denied"),console.error(`[Checkpoint] Path: ${o}`),new Error(`Failed to save checkpoint: Permission denied for ${o}`)):i.code==="EROFS"?(console.error("[Checkpoint] Failed to save checkpoint: Read-only filesystem"),console.error(`[Checkpoint] Path: ${o}`),new Error("Failed to save checkpoint: Filesystem is read-only")):(console.error("[Checkpoint] Failed to save checkpoint:",i.message),console.error(`[Checkpoint] Workflow ID: ${t.workflow_id}`),console.error(`[Checkpoint] Path: ${o}`),new Error(`Failed to save checkpoint for workflow ${t.workflow_id}: ${i.message}`))}}async function I(e,t){let n=$i(e,t),o=qo.get(n);if(o&&Qk(o))return structuredClone(o.checkpoint);let r=(0,Ze.join)(e,Ct,t,Vo);try{let i=await K.readFile(r,"utf-8"),s=JSON.parse(i);return s.schema_version?s.schema_version!=="3.0.0"?(console.warn(`[Checkpoint] Unknown checkpoint schema version ${s.schema_version} for workflow ${t}`),console.warn("[Checkpoint] Expected 3.0.0"),null):(s.current_stage==="idea"&&(console.warn(`[Checkpoint] Migrating legacy 'idea' stage to 'intent' for workflow ${t}`),s.current_stage="intent"),qo.set(n,{checkpoint:structuredClone(s),timestamp:Date.now(),dirty:!1}),s):(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: ${r}`),null)}catch(i){let s=i,a=s;return a.code==="ENOENT"?null:s.name==="SyntaxError"||s.message.includes("JSON")?(console.warn(`[Checkpoint] Corrupt checkpoint detected for workflow ${t}`),console.warn(`[Checkpoint] Path: ${r}`),console.warn(`[Checkpoint] Error: ${s.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: ${r}`),null):(console.warn(`[Checkpoint] Failed to load checkpoint ${t}: ${s.message}`),console.warn(`[Checkpoint] Path: ${r}`),null)}}async function te(e){let t=(0,Ze.join)(e,Ct);try{if(!await K.pathExists(t))return[];let o=await K.readdir(t,{withFileTypes:!0}),r=[];for(let i of o){if(!i.isDirectory()||i.name==="completed")continue;let s=(0,Ze.join)(t,i.name,Vo);if(await K.pathExists(s))try{let a=await K.readFile(s,"utf-8"),c=JSON.parse(a);c.workflow_id&&r.push(c.workflow_id)}catch{}}return r}catch(n){let o=n;return o.code==="EACCES"||o.code==="EPERM"?console.warn(`[Checkpoint] Permission denied reading ${t}`):console.warn(`[Checkpoint] Failed to list workflows: ${o.message}`),[]}}async function Lu(e,t){let n=await I(e,t);if(!n||n.status!=="complete")return;let o=(0,Ze.join)(e,Ct,t),r=(0,Ze.join)(e,Ct,"completed",t),i=(0,Ze.join)(r,Vo);if(await K.pathExists(i))try{let s=await K.readFile(i,"utf-8");if(JSON.parse(s).workflow_id===t){console.log(`[Checkpoint] Workflow ${t} already archived at ${r}`);return}}catch{await K.remove(r)}else await K.pathExists(r)&&await K.remove(r);n.archived_at=new Date().toISOString(),n.archived_path=`${Ct}/completed/${t}`,await $(e,n);try{await K.move(o,r,{overwrite:!1}),It(e,t),console.log(`[Checkpoint] Workflow archived to ${Ct}/completed/${t}/`)}catch(s){let a=s,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 s=(0,Ze.join)(e,".olympus","plans",`${t}-plan.md`);if(await K.pathExists(s)){let a=`
14
+ see https://github.com/jprichardson/node-fs-extra/issues/269`,"Warning","fs-extra-WARN0002");let{srcStat:o,destStat:r}=eo.checkPathsSync(e,t,"copy",n);if(eo.checkParentPathsSync(e,o,t,"copy"),n.filter&&!n.filter(e,t))return;let i=Zn.dirname(t);return ve.existsSync(i)||Ay(i),Tl(r,e,t,n)}function Tl(e,t,n,o){let i=(o.dereference?ve.statSync:ve.lstatSync)(t);if(i.isDirectory())return Fy(i,e,t,n,o);if(i.isFile()||i.isCharacterDevice()||i.isBlockDevice())return $y(i,e,t,n,o);if(i.isSymbolicLink())return Hy(e,t,n,o);throw i.isSocket()?new Error(`Cannot copy a socket file: ${t}`):i.isFIFO()?new Error(`Cannot copy a FIFO pipe: ${t}`):new Error(`Unknown file: ${t}`)}function $y(e,t,n,o,r){return t?Ny(e,n,o,r):El(e,n,o,r)}function Ny(e,t,n,o){if(o.overwrite)return ve.unlinkSync(n),El(e,t,n,o);if(o.errorOnExist)throw new Error(`'${n}' already exists`)}function El(e,t,n,o){return ve.copyFileSync(t,n),o.preserveTimestamps&&Dy(e.mode,t,n),Oi(n,e.mode)}function Dy(e,t,n){return jy(e)&&My(n,e),Ly(t,n)}function jy(e){return(e&128)===0}function My(e,t){return Oi(e,t|128)}function Oi(e,t){return ve.chmodSync(e,t)}function Ly(e,t){let n=ve.statSync(e);return Py(t,n.atime,n.mtime)}function Fy(e,t,n,o,r){return t?bl(n,o,r):Uy(e.mode,n,o,r)}function Uy(e,t,n,o){return ve.mkdirSync(n),bl(t,n,o),Oi(n,e)}function bl(e,t,n){let o=ve.opendirSync(e);try{let r;for(;(r=o.readSync())!==null;)Wy(r.name,e,t,n)}finally{o.closeSync()}}function Wy(e,t,n,o){let r=Zn.join(t,e),i=Zn.join(n,e);if(o.filter&&!o.filter(r,i))return;let{destStat:s}=eo.checkPathsSync(r,i,"copy",o);return Tl(s,r,i,o)}function Hy(e,t,n,o){let r=ve.readlinkSync(t);if(o.dereference&&(r=Zn.resolve(process.cwd(),r)),e){let i;try{i=ve.readlinkSync(n)}catch(s){if(s.code==="EINVAL"||s.code==="UNKNOWN")return ve.symlinkSync(r,n);throw s}if(o.dereference&&(i=Zn.resolve(process.cwd(),i)),r!==i){if(eo.isSrcSubdir(r,i))throw new Error(`Cannot copy '${r}' to a subdirectory of itself, '${i}'.`);if(eo.isSrcSubdir(i,r))throw new Error(`Cannot overwrite '${i}' with '${r}'.`)}return Gy(r,n)}else return ve.symlinkSync(r,n)}function Gy(e,t){return ve.unlinkSync(t),ve.symlinkSync(e,t)}Cl.exports=xy});var Wo=U((Jb,Rl)=>{"use strict";var By=ce().fromPromise;Rl.exports={copy:By(vl()),copySync:Il()}});var to=U((zb,Al)=>{"use strict";var Ol=dn(),qy=ce().fromCallback;function Vy(e,t){Ol.rm(e,{recursive:!0,force:!0},t)}function Yy(e){Ol.rmSync(e,{recursive:!0,force:!0})}Al.exports={remove:qy(Vy),removeSync:Yy}});var Ll=U((Qb,Ml)=>{"use strict";var Ky=ce().fromPromise,$l=_e(),Nl=require("path"),Dl=Be(),jl=to(),Pl=Ky(async function(t){let n;try{n=await $l.readdir(t)}catch{return Dl.mkdirs(t)}return Promise.all(n.map(o=>jl.remove(Nl.join(t,o))))});function xl(e){let t;try{t=$l.readdirSync(e)}catch{return Dl.mkdirsSync(e)}t.forEach(n=>{n=Nl.join(e,n),jl.removeSync(n)})}Ml.exports={emptyDirSync:xl,emptydirSync:xl,emptyDir:Pl,emptydir:Pl}});var Hl=U((Xb,Wl)=>{"use strict";var Jy=ce().fromPromise,Fl=require("path"),lt=_e(),Ul=Be();async function zy(e){let t;try{t=await lt.stat(e)}catch{}if(t&&t.isFile())return;let n=Fl.dirname(e),o=null;try{o=await lt.stat(n)}catch(r){if(r.code==="ENOENT"){await Ul.mkdirs(n),await lt.writeFile(e,"");return}else throw r}o.isDirectory()?await lt.writeFile(e,""):await lt.readdir(n)}function Qy(e){let t;try{t=lt.statSync(e)}catch{}if(t&&t.isFile())return;let n=Fl.dirname(e);try{lt.statSync(n).isDirectory()||lt.readdirSync(n)}catch(o){if(o&&o.code==="ENOENT")Ul.mkdirsSync(n);else throw o}lt.writeFileSync(e,"")}Wl.exports={createFile:Jy(zy),createFileSync:Qy}});var Yl=U((Zb,Vl)=>{"use strict";var Xy=ce().fromPromise,Gl=require("path"),Et=_e(),Bl=Be(),{pathExists:Zy}=Tt(),{areIdentical:ql}=Bt();async function ek(e,t){let n;try{n=await Et.lstat(t)}catch{}let o;try{o=await Et.lstat(e)}catch(s){throw s.message=s.message.replace("lstat","ensureLink"),s}if(n&&ql(o,n))return;let r=Gl.dirname(t);await Zy(r)||await Bl.mkdirs(r),await Et.link(e,t)}function tk(e,t){let n;try{n=Et.lstatSync(t)}catch{}try{let i=Et.lstatSync(e);if(n&&ql(i,n))return}catch(i){throw i.message=i.message.replace("lstat","ensureLink"),i}let o=Gl.dirname(t);return Et.existsSync(o)||Bl.mkdirsSync(o),Et.linkSync(e,t)}Vl.exports={createLink:Xy(ek),createLinkSync:tk}});var Jl=U((eC,Kl)=>{"use strict";var bt=require("path"),no=_e(),{pathExists:nk}=Tt(),ok=ce().fromPromise;async function rk(e,t){if(bt.isAbsolute(e)){try{await no.lstat(e)}catch(i){throw i.message=i.message.replace("lstat","ensureSymlink"),i}return{toCwd:e,toDst:e}}let n=bt.dirname(t),o=bt.join(n,e);if(await nk(o))return{toCwd:o,toDst:e};try{await no.lstat(e)}catch(i){throw i.message=i.message.replace("lstat","ensureSymlink"),i}return{toCwd:e,toDst:bt.relative(n,e)}}function ik(e,t){if(bt.isAbsolute(e)){if(!no.existsSync(e))throw new Error("absolute srcpath does not exist");return{toCwd:e,toDst:e}}let n=bt.dirname(t),o=bt.join(n,e);if(no.existsSync(o))return{toCwd:o,toDst:e};if(!no.existsSync(e))throw new Error("relative srcpath does not exist");return{toCwd:e,toDst:bt.relative(n,e)}}Kl.exports={symlinkPaths:ok(rk),symlinkPathsSync:ik}});var Xl=U((tC,Ql)=>{"use strict";var zl=_e(),sk=ce().fromPromise;async function ak(e,t){if(t)return t;let n;try{n=await zl.lstat(e)}catch{return"file"}return n&&n.isDirectory()?"dir":"file"}function ck(e,t){if(t)return t;let n;try{n=zl.lstatSync(e)}catch{return"file"}return n&&n.isDirectory()?"dir":"file"}Ql.exports={symlinkType:sk(ak),symlinkTypeSync:ck}});var nu=U((nC,tu)=>{"use strict";var lk=ce().fromPromise,Zl=require("path"),Xe=_e(),{mkdirs:uk,mkdirsSync:dk}=Be(),{symlinkPaths:pk,symlinkPathsSync:fk}=Jl(),{symlinkType:mk,symlinkTypeSync:gk}=Xl(),{pathExists:hk}=Tt(),{areIdentical:eu}=Bt();async function yk(e,t,n){let o;try{o=await Xe.lstat(t)}catch{}if(o&&o.isSymbolicLink()){let[a,c]=await Promise.all([Xe.stat(e),Xe.stat(t)]);if(eu(a,c))return}let r=await pk(e,t);e=r.toDst;let i=await mk(r.toCwd,n),s=Zl.dirname(t);return await hk(s)||await uk(s),Xe.symlink(e,t,i)}function kk(e,t,n){let o;try{o=Xe.lstatSync(t)}catch{}if(o&&o.isSymbolicLink()){let a=Xe.statSync(e),c=Xe.statSync(t);if(eu(a,c))return}let r=fk(e,t);e=r.toDst,n=gk(r.toCwd,n);let i=Zl.dirname(t);return Xe.existsSync(i)||dk(i),Xe.symlinkSync(e,t,n)}tu.exports={createSymlink:lk(yk),createSymlinkSync:kk}});var uu=U((oC,lu)=>{"use strict";var{createFile:ou,createFileSync:ru}=Hl(),{createLink:iu,createLinkSync:su}=Yl(),{createSymlink:au,createSymlinkSync:cu}=nu();lu.exports={createFile:ou,createFileSync:ru,ensureFile:ou,ensureFileSync:ru,createLink:iu,createLinkSync:su,ensureLink:iu,ensureLinkSync:su,createSymlink:au,createSymlinkSync:cu,ensureSymlink:au,ensureSymlinkSync:cu}});var Ho=U((rC,du)=>{function wk(e,{EOL:t=`
15
+ `,finalEOL:n=!0,replacer:o=null,spaces:r}={}){let i=n?t:"";return JSON.stringify(e,o,r).replace(/\n/g,t)+i}function Sk(e){return Buffer.isBuffer(e)&&(e=e.toString("utf8")),e.replace(/^\uFEFF/,"")}du.exports={stringify:wk,stripBom:Sk}});var gu=U((iC,mu)=>{var mn;try{mn=dn()}catch{mn=require("fs")}var Go=ce(),{stringify:pu,stripBom:fu}=Ho();async function _k(e,t={}){typeof t=="string"&&(t={encoding:t});let n=t.fs||mn,o="throws"in t?t.throws:!0,r=await Go.fromCallback(n.readFile)(e,t);r=fu(r);let i;try{i=JSON.parse(r,t?t.reviver:null)}catch(s){if(o)throw s.message=`${e}: ${s.message}`,s;return null}return i}var vk=Go.fromPromise(_k);function Tk(e,t={}){typeof t=="string"&&(t={encoding:t});let n=t.fs||mn,o="throws"in t?t.throws:!0;try{let r=n.readFileSync(e,t);return r=fu(r),JSON.parse(r,t.reviver)}catch(r){if(o)throw r.message=`${e}: ${r.message}`,r;return null}}async function Ek(e,t,n={}){let o=n.fs||mn,r=pu(t,n);await Go.fromCallback(o.writeFile)(e,r,n)}var bk=Go.fromPromise(Ek);function Ck(e,t,n={}){let o=n.fs||mn,r=pu(t,n);return o.writeFileSync(e,r,n)}mu.exports={readFile:vk,readFileSync:Tk,writeFile:bk,writeFileSync:Ck}});var yu=U((sC,hu)=>{"use strict";var Bo=gu();hu.exports={readJson:Bo.readFile,readJsonSync:Bo.readFileSync,writeJson:Bo.writeFile,writeJsonSync:Bo.writeFileSync}});var qo=U((aC,Su)=>{"use strict";var Ik=ce().fromPromise,Ai=_e(),ku=require("path"),wu=Be(),Rk=Tt().pathExists;async function Ok(e,t,n="utf-8"){let o=ku.dirname(e);return await Rk(o)||await wu.mkdirs(o),Ai.writeFile(e,t,n)}function Ak(e,...t){let n=ku.dirname(e);Ai.existsSync(n)||wu.mkdirsSync(n),Ai.writeFileSync(e,...t)}Su.exports={outputFile:Ik(Ok),outputFileSync:Ak}});var vu=U((cC,_u)=>{"use strict";var{stringify:Pk}=Ho(),{outputFile:xk}=qo();async function $k(e,t,n={}){let o=Pk(t,n);await xk(e,o,n)}_u.exports=$k});var Eu=U((lC,Tu)=>{"use strict";var{stringify:Nk}=Ho(),{outputFileSync:Dk}=qo();function jk(e,t,n){let o=Nk(t,n);Dk(e,o,n)}Tu.exports=jk});var Cu=U((uC,bu)=>{"use strict";var Mk=ce().fromPromise,Te=yu();Te.outputJson=Mk(vu());Te.outputJsonSync=Eu();Te.outputJSON=Te.outputJson;Te.outputJSONSync=Te.outputJsonSync;Te.writeJSON=Te.writeJson;Te.writeJSONSync=Te.writeJsonSync;Te.readJSON=Te.readJson;Te.readJSONSync=Te.readJsonSync;bu.exports=Te});var Pu=U((dC,Au)=>{"use strict";var Lk=_e(),Iu=require("path"),{copy:Fk}=Wo(),{remove:Ou}=to(),{mkdirp:Uk}=Be(),{pathExists:Wk}=Tt(),Ru=Bt();async function Hk(e,t,n={}){let o=n.overwrite||n.clobber||!1,{srcStat:r,isChangingCase:i=!1}=await Ru.checkPaths(e,t,"move",n);await Ru.checkParentPaths(e,r,t,"move");let s=Iu.dirname(t);return Iu.parse(s).root!==s&&await Uk(s),Gk(e,t,o,i)}async function Gk(e,t,n,o){if(!o){if(n)await Ou(t);else if(await Wk(t))throw new Error("dest already exists.")}try{await Lk.rename(e,t)}catch(r){if(r.code!=="EXDEV")throw r;await Bk(e,t,n)}}async function Bk(e,t,n){return await Fk(e,t,{overwrite:n,errorOnExist:!0,preserveTimestamps:!0}),Ou(e)}Au.exports=Hk});var ju=U((pC,Du)=>{"use strict";var $u=dn(),xi=require("path"),qk=Wo().copySync,Nu=to().removeSync,Vk=Be().mkdirpSync,xu=Bt();function Yk(e,t,n){n=n||{};let o=n.overwrite||n.clobber||!1,{srcStat:r,isChangingCase:i=!1}=xu.checkPathsSync(e,t,"move",n);return xu.checkParentPathsSync(e,r,t,"move"),Kk(t)||Vk(xi.dirname(t)),Jk(e,t,o,i)}function Kk(e){let t=xi.dirname(e);return xi.parse(t).root===t}function Jk(e,t,n,o){if(o)return Pi(e,t,n);if(n)return Nu(t),Pi(e,t,n);if($u.existsSync(t))throw new Error("dest already exists.");return Pi(e,t,n)}function Pi(e,t,n){try{$u.renameSync(e,t)}catch(o){if(o.code!=="EXDEV")throw o;return zk(e,t,n)}}function zk(e,t,n){return qk(e,t,{overwrite:n,errorOnExist:!0,preserveTimestamps:!0}),Nu(e)}Du.exports=Yk});var Lu=U((fC,Mu)=>{"use strict";var Qk=ce().fromPromise;Mu.exports={move:Qk(Pu()),moveSync:ju()}});var ue=U((mC,Fu)=>{"use strict";Fu.exports={..._e(),...Wo(),...Ll(),...uu(),...Cu(),...Be(),...Lu(),...qo(),...Tt(),...to()}});function $i(e,t){return`${e}:${t}`}function Zk(e){return Date.now()-e.timestamp<Xk}function It(e,t){let n=$i(e,t);Vo.delete(n)}async function $(e,t){let n=(0,Ze.join)(e,Ct,t.workflow_id),o=(0,Ze.join)(n,Yo);try{if(t.updated_at=new Date().toISOString(),t.schema_version="3.0.0",await K.ensureDir(n),JSON.stringify(t).length>1e4){let a=JSON.stringify(t);await K.writeFile(o,a,"utf-8")}else await K.writeJson(o,t,{spaces:2});let s=$i(e,t.workflow_id);Vo.set(s,{checkpoint:structuredClone(t),timestamp:Date.now(),dirty:!1})}catch(r){let i=r;throw i.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: ${o}`),new Error("Failed to save checkpoint: Disk is full. Please free up space and retry.")):i.code==="EACCES"||i.code==="EPERM"?(console.error("[Checkpoint] Failed to save checkpoint: Permission denied"),console.error(`[Checkpoint] Path: ${o}`),new Error(`Failed to save checkpoint: Permission denied for ${o}`)):i.code==="EROFS"?(console.error("[Checkpoint] Failed to save checkpoint: Read-only filesystem"),console.error(`[Checkpoint] Path: ${o}`),new Error("Failed to save checkpoint: Filesystem is read-only")):(console.error("[Checkpoint] Failed to save checkpoint:",i.message),console.error(`[Checkpoint] Workflow ID: ${t.workflow_id}`),console.error(`[Checkpoint] Path: ${o}`),new Error(`Failed to save checkpoint for workflow ${t.workflow_id}: ${i.message}`))}}async function C(e,t){let n=$i(e,t),o=Vo.get(n);if(o&&Zk(o))return structuredClone(o.checkpoint);let r=(0,Ze.join)(e,Ct,t,Yo);try{let i=await K.readFile(r,"utf-8"),s=JSON.parse(i);return s.schema_version?s.schema_version!=="3.0.0"?(console.warn(`[Checkpoint] Unknown checkpoint schema version ${s.schema_version} for workflow ${t}`),console.warn("[Checkpoint] Expected 3.0.0"),null):(s.current_stage==="idea"&&(console.warn(`[Checkpoint] Migrating legacy 'idea' stage to 'intent' for workflow ${t}`),s.current_stage="intent"),Vo.set(n,{checkpoint:structuredClone(s),timestamp:Date.now(),dirty:!1}),s):(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: ${r}`),null)}catch(i){let s=i,a=s;return a.code==="ENOENT"?null:s.name==="SyntaxError"||s.message.includes("JSON")?(console.warn(`[Checkpoint] Corrupt checkpoint detected for workflow ${t}`),console.warn(`[Checkpoint] Path: ${r}`),console.warn(`[Checkpoint] Error: ${s.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: ${r}`),null):(console.warn(`[Checkpoint] Failed to load checkpoint ${t}: ${s.message}`),console.warn(`[Checkpoint] Path: ${r}`),null)}}async function te(e){let t=(0,Ze.join)(e,Ct);try{if(!await K.pathExists(t))return[];let o=await K.readdir(t,{withFileTypes:!0}),r=[];for(let i of o){if(!i.isDirectory()||i.name==="completed")continue;let s=(0,Ze.join)(t,i.name,Yo);if(await K.pathExists(s))try{let a=await K.readFile(s,"utf-8"),c=JSON.parse(a);c.workflow_id&&r.push(c.workflow_id)}catch{}}return r}catch(n){let o=n;return o.code==="EACCES"||o.code==="EPERM"?console.warn(`[Checkpoint] Permission denied reading ${t}`):console.warn(`[Checkpoint] Failed to list workflows: ${o.message}`),[]}}async function Uu(e,t){let n=await C(e,t);if(!n||n.status!=="complete")return;let o=(0,Ze.join)(e,Ct,t),r=(0,Ze.join)(e,Ct,"completed",t),i=(0,Ze.join)(r,Yo);if(await K.pathExists(i))try{let s=await K.readFile(i,"utf-8");if(JSON.parse(s).workflow_id===t){console.log(`[Checkpoint] Workflow ${t} already archived at ${r}`);return}}catch{await K.remove(r)}else await K.pathExists(r)&&await K.remove(r);n.archived_at=new Date().toISOString(),n.archived_path=`${Ct}/completed/${t}`,await $(e,n);try{await K.move(o,r,{overwrite:!1}),It(e,t),console.log(`[Checkpoint] Workflow archived to ${Ct}/completed/${t}/`)}catch(s){let a=s,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 s=(0,Ze.join)(e,".olympus","plans",`${t}-plan.md`);if(await K.pathExists(s)){let a=`
16
16
 
17
17
  ---
18
18
  _This workflow was archived to \`${Ct}/completed/${t}/\` on ${n.archived_at}_
19
- `;await K.appendFile(s,a,"utf-8")}}catch{}}var K,Ze,Ct,Vo,qo,zk,Ee=B(()=>{"use strict";K=b(ue(),1),Ze=require("path"),Ct="aidlc-docs",Vo="checkpoint.json",qo=new Map,zk=5e3});var Wu={};st(Wu,{computeVerification:()=>Yo,generateValidationQuestions:()=>Uu,getAdaptiveThreshold:()=>nw,getConformanceThreshold:()=>rw,recordAlignmentResult:()=>ow,runAlignmentCheck:()=>Di,runDualValidation:()=>gn});function ew(e){return e.replace(/^---\n[\s\S]*?\n---\n/,"")}function Ni(e){let t=new Map,n=e.split(`
19
+ `;await K.appendFile(s,a,"utf-8")}}catch{}}var K,Ze,Ct,Yo,Vo,Xk,Ee=B(()=>{"use strict";K=b(ue(),1),Ze=require("path"),Ct="aidlc-docs",Yo="checkpoint.json",Vo=new Map,Xk=5e3});var Gu={};st(Gu,{computeVerification:()=>Ko,generateValidationQuestions:()=>Hu,getAdaptiveThreshold:()=>rw,getConformanceThreshold:()=>sw,recordAlignmentResult:()=>iw,runAlignmentCheck:()=>Di,runDualValidation:()=>gn});function nw(e){return e.replace(/^---\n[\s\S]*?\n---\n/,"")}function Ni(e){let t=new Map,n=e.split(`
20
20
  `),o=null,r=[];for(let i of n){let s=i.match(/^##\s+(.+)$/);s?(o&&t.set(o,r.join(`
21
21
  `)),o=s[1].trim(),r=[]):o&&r.push(i)}return o&&t.set(o,r.join(`
22
22
  `)),t}function oo(e){let t=[],n=e.split(`
23
- `);for(let o of n){let r=o.match(/^\s*[-*+]\s+(?:\[[ x]\]\s+)?(.+)$/);r&&t.push(r[1].trim())}return t}function tw(e,t){let n=ew(e);if(t==="intent-to-unit"){let s=Ni(n),a=[],c=s.get("Business Requirements");c&&a.push(...oo(c));let l=s.get("Implementation Plan");return l&&a.push(...oo(l)),a}if(t==="unit-to-bolt"){let s=Ni(n),a=[],c=s.get("Acceptance Criteria");c&&a.push(...oo(c));let l=s.get("Target Files");return l&&a.push(...oo(l)),a}let o=Ni(n),r=Zk[t],i=[];for(let s of r){let a=o.get(s);if(a){let c=oo(a);i.push(...c)}}return i}function Yo(e,t,n){try{let o=tw(e,n);if(o.length===0)return{conformance_score:100,coverage_percentage:100,missing_items:[],passed:!0};let r=t.toLowerCase(),i=[],s=0;for(let d of o){let f=d.toLowerCase();r.includes(f)?s++:i.push(d)}let a=Math.round(s/o.length*100),c=a,l=Fu[n],u=a>=l;return{conformance_score:a,coverage_percentage:c,missing_items:i,passed:u}}catch(o){return console.error("[Alignment] Verification computation failed:",o),{conformance_score:0,coverage_percentage:0,missing_items:["Verification computation error"],passed:!1}}}function Uu(e){let t=Xk[e];return[{question:t.verification,answer:null,answered_by:null,passed:null},{question:t.validation,answer:null,answered_by:null,passed:null}]}function Di(e,t,n,o,r){try{let i=Yo(e,t,r),s=Uu(r),a=s.every(m=>m.answer!==null),c=s.every(m=>m.passed===!0),u={alignment_score:a&&c?100:0,alignment_questions:s,passed:c},d=i.passed&&u.passed;return{source_artifact_id:n,target_artifact_id:o,verification:i,validation:u,alignment_passed:d,checked_at:new Date().toISOString()}}catch(i){return console.error("[Alignment] Alignment check failed:",i),{source_artifact_id:n,target_artifact_id:o,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 gn(e,t,n,o,r,i,s,a){let c=Di(t,e,i,s,o),l=Di(n,e,a,s,r),u=c.alignment_passed&&l.alignment_passed;return{parentCheck:c,rootCheck:l,passed:u}}function nw(e,t){let n=0;t>=2&&(n+=10),t>=3&&(n+=10);let o=e-n;return Math.max(0,o)}function ow(e,t){try{let n=D(e);if(!n){console.error(`[Alignment] Manifest not found at ${e}`);return}n.alignment_checks.push(t),F(e,n)}catch(n){console.error("[Alignment] Failed to record alignment result:",n)}}function rw(e){return Fu[e]}var Fu,Xk,Zk,Ko=B(()=>{"use strict";J();Fu={"intent-to-unit":95,"unit-to-bolt":100,"unit-to-intent":80,"bolt-to-intent":70},Xk={"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?"}},Zk={"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 Vt={};st(Vt,{addGateAuditEntry:()=>Ce,cascadeInvalidation:()=>aw,computeChecksum:()=>Jo,createManifest:()=>iw,detectStaleArtifacts:()=>sw,getArtifactById:()=>uw,getArtifactsByPhase:()=>dw,getBoltArtifacts:()=>nt,getBoltsByStatus:()=>Li,getUnitArtifacts:()=>qt,isWorkflowComplete:()=>Gu,linkArtifacts:()=>Mi,loadManifest:()=>D,normalizePath:()=>ji,recoverManifest:()=>lw,registerArtifact:()=>Pe,revalidateStaleArtifacts:()=>fw,runAlignmentCheck:()=>cw,saveManifest:()=>F,transitionToActive:()=>Fi,transitionToDraft:()=>Bu,transitionToFulfilled:()=>Ui,transitionToStale:()=>Vu,transitionToViolated:()=>qu,updateContractStatus:()=>tt,updatePhaseStatus:()=>ut});function ji(e){return e.replace(/\\/g,"/")}function Rt(){return{status:"not_started",started_at:null,completed_at:null,gate_result:null,gate_bypassed:!1,bypass_reason:null}}function iw(e,t,n){let o=et.join(n,"aidlc-docs",e),r=et.join(o,"manifest.json");try{oe.ensureDirSync(o);let i=new Date().toISOString(),s={schema_version:"2.0.0",workflow_id:e,feature_name:t,created_at:i,updated_at:i,phases:{discovery:Rt(),inception:Rt(),construction:Rt(),operations:Rt()},depth_assessment:null,artifacts:[],links:[],risks:[],gate_audit:[],metrics:null,alignment_checks:[],risk_tier:null};return oe.writeFileSync(r,JSON.stringify(s,null,2),"utf-8"),r}catch(i){throw console.error(`Failed to create manifest at ${r}:`,i),i}}function D(e){try{if(!oe.existsSync(e))return null;let t=oe.readFileSync(e,"utf-8");return JSON.parse(t)}catch(t){return console.error(`Failed to load manifest at ${e}:`,t),null}}function F(e,t){try{t.updated_at=new Date().toISOString(),oe.writeFileSync(e,JSON.stringify(t,null,2),"utf-8")}catch(n){throw console.error(`Failed to save manifest at ${e}:`,n),n}}function Jo(e){try{if(!oe.existsSync(e))return null;let t=oe.readFileSync(e),n=(0,Hu.createHash)("sha256");return n.update(t),n.digest("hex")}catch(t){return console.error(`Failed to compute checksum for ${e}:`,t),null}}function Pe(e,t){try{let n=D(e);if(!n)throw new Error(`Manifest not found at ${e}`);let o=new Date().toISOString(),r=ji(t.path),i=n.artifacts.findIndex(a=>a.id===t.id),s=Jo(t.path);if(i>=0){let a=n.artifacts[i];n.artifacts[i]={...a,...t,path:r,updated_at:o,contract_version:a.contract_version+1,checksum:s}}else{let a={...t,path:r,created_at:o,updated_at:o,contract_version:1,contract_status:"draft",stale_reason:null,checksum:s};n.artifacts.push(a)}F(e,n)}catch(n){throw console.error(`Failed to register artifact in ${e}:`,n),n}}function Mi(e,t){try{let n=D(e);if(!n)throw new Error(`Manifest not found at ${e}`);let o=n.artifacts.some(s=>s.id===t.source_id),r=n.artifacts.some(s=>s.id===t.target_id);if(!o)throw new Error(`Source artifact not found: ${t.source_id}`);if(!r)throw new Error(`Target artifact not found: ${t.target_id}`);n.links.some(s=>s.source_id===t.source_id&&s.target_id===t.target_id&&s.link_type===t.link_type)||(n.links.push(t),F(e,n))}catch(n){throw console.error(`Failed to link artifacts in ${e}:`,n),n}}function sw(e){try{let t=D(e);if(!t)return[];let n=[];for(let o of t.artifacts)if(o.checksum&&o.write_complete){let r=Jo(o.path);r&&r!==o.checksum&&n.push(o.id)}return n}catch(t){return console.error(`Failed to detect stale artifacts in ${e}:`,t),[]}}function aw(e,t){try{let n=D(e);if(!n)return;let o=new Set,r=[t];for(;r.length>0;){let i=r.shift();if(o.has(i))continue;o.add(i);let s=n.artifacts.find(c=>c.id===i);if(s){let c=i===t?"Artifact content was modified":`Parent artifact ${i} was modified`;pw(s,c)}let a=n.links.filter(c=>c.source_id===i);for(let c of a)o.has(c.target_id)||r.push(c.target_id)}F(e,n)}catch(n){console.error(`Failed to cascade invalidation in ${e}:`,n)}}function cw(e,t,n){try{let o=D(e);if(!o)return;let r=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:r};o.alignment_checks.push(a),F(e,o)}catch(o){console.error(`Failed to run alignment check in ${e}:`,o)}}function lw(e,t){try{let n=et.join(e,"aidlc-docs",t);if(!oe.existsSync(n))return null;let o=new Date().toISOString(),r={schema_version:"2.0.0",workflow_id:t,feature_name:"Recovered Workflow",created_at:o,updated_at:o,phases:{discovery:Rt(),inception:Rt(),construction:Rt(),operations:Rt()},depth_assessment:null,artifacts:[],links:[],risks:[],gate_audit:[],metrics:null,alignment_checks:[],risk_tier:null},i=oe.readdirSync(n,{recursive:!0,withFileTypes:!0});for(let s of i)if(s.isFile()&&s.name!=="manifest.json"){let a=et.join(s.path,s.name),c=et.relative(n,a),l=ji(a),u={id:`recovered-${Date.now()}-${r.artifacts.length}`,type:et.extname(s.name)||"unknown",phase:"inception",stage:"intent",path:l,created_at:o,updated_at:o,validation_passed:null,write_complete:!0,checksum:Jo(a),contract_status:"draft",contract_version:1,stale_reason:null};r.artifacts.push(u)}return r}catch(n){return console.error(`Failed to recover manifest for workflow ${t}:`,n),null}}function ut(e,t,n,o,r){try{let i=D(e);if(!i)return;i.phases[t].status=n,o!==void 0&&(i.phases[t].started_at=o),r!==void 0&&(i.phases[t].completed_at=r),F(e,i)}catch(i){console.error(`Failed to update phase status in ${e}:`,i)}}function Ce(e,t){try{let n=D(e);if(!n)return;let o={...t,timestamp:new Date().toISOString()};n.gate_audit.push(o),F(e,n)}catch(n){console.error(`Failed to add gate audit entry in ${e}:`,n)}}function uw(e,t){return e.artifacts.find(n=>n.id===t)}function dw(e,t){return e.artifacts.filter(n=>n.phase===t)}function tt(e,t,n,o){try{switch(n){case"draft":Bu(e,t);break;case"active":Fi(e,t);break;case"fulfilled":Ui(e,t);break;case"violated":qu(e,t);break;case"stale":if(!o)throw new Error('staleReason is required when setting status to "stale"');Vu(e,t,o);break}}catch(r){console.error(`Failed to update contract status in ${e}:`,r)}}function qt(e){return e.artifacts.filter(t=>t.stage==="unit")}function nt(e,t){let n=e.artifacts.filter(o=>o.stage==="code-generation");if(t){let o=new Set(e.links.filter(r=>r.source_id===t&&(r.link_type==="derives"||r.link_type==="implements")).map(r=>r.target_id));return n.filter(r=>o.has(r.id))}return n}function Li(e,t){return e.artifacts.filter(n=>n.stage==="code-generation"&&n.contract_status===t)}function Gu(e){let t=e.artifacts.filter(n=>n.stage==="code-generation");return t.length===0?!1:t.every(n=>n.contract_status==="fulfilled")}function pw(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 Bu(e,t){let n=D(e);if(!n)throw new Error(`Manifest not found at ${e}`);let o=n.artifacts.find(r=>r.id===t);if(!o)throw new Error(`Artifact ${t} not found in manifest`);if(o.contract_status!=="violated"&&o.contract_status!=="stale")throw new Error(`Cannot transition from '${o.contract_status}' to 'draft'`);o.contract_status="draft",o.stale_reason=null,o.statusHistory||(o.statusHistory=[]),o.statusHistory.push({status:"draft",timestamp:new Date().toISOString()}),F(e,n)}function Fi(e,t){let n=D(e);if(!n)throw new Error(`Manifest not found at ${e}`);let o=n.artifacts.find(r=>r.id===t);if(!o)throw new Error(`Artifact ${t} not found in manifest`);if(o.contract_status!=="draft"&&o.contract_status!=="stale")throw new Error(`Cannot transition from '${o.contract_status}' to 'active'`);o.contract_status="active",o.stale_reason=null,o.statusHistory||(o.statusHistory=[]),o.statusHistory.push({status:"active",timestamp:new Date().toISOString()}),F(e,n)}function Ui(e,t){let n=D(e);if(!n)throw new Error(`Manifest not found at ${e}`);let o=n.artifacts.find(r=>r.id===t);if(!o)throw new Error(`Artifact ${t} not found in manifest`);if(o.contract_status!=="active")throw new Error(`Cannot transition from '${o.contract_status}' to 'fulfilled'`);o.contract_status="fulfilled",o.stale_reason=null,o.statusHistory||(o.statusHistory=[]),o.statusHistory.push({status:"fulfilled",timestamp:new Date().toISOString()}),F(e,n)}function qu(e,t){let n=D(e);if(!n)throw new Error(`Manifest not found at ${e}`);let o=n.artifacts.find(r=>r.id===t);if(!o)throw new Error(`Artifact ${t} not found in manifest`);if(o.contract_status!=="active")throw new Error(`Cannot transition from '${o.contract_status}' to 'violated'`);o.contract_status="violated",o.stale_reason=null,o.statusHistory||(o.statusHistory=[]),o.statusHistory.push({status:"violated",timestamp:new Date().toISOString()}),F(e,n)}function Vu(e,t,n){let o=D(e);if(!o)throw new Error(`Manifest not found at ${e}`);let r=o.artifacts.find(i=>i.id===t);if(!r)throw new Error(`Artifact ${t} not found in manifest`);if(r.contract_status!=="active"&&r.contract_status!=="fulfilled")throw new Error(`Cannot transition from '${r.contract_status}' to 'stale'`);r.contract_status="stale",r.stale_reason=n,r.statusHistory||(r.statusHistory=[]),r.statusHistory.push({status:"stale",timestamp:new Date().toISOString()}),F(e,o)}async function fw(e,t){let n={restored:[],stillStale:[],errors:[]},o=et.join(e,"aidlc-docs",t,"manifest.json"),r=D(o);if(!r)return n.errors.push("Manifest not found"),n;let i=r.artifacts.filter(s=>s.contract_status==="stale");for(let s of i)try{let a=r.links.find(y=>y.target_id===s.id);if(!a){n.stillStale.push(s.id);continue}let c=r.artifacts.find(y=>y.id===a.source_id);if(!c){n.stillStale.push(s.id);continue}let l=r.artifacts.find(y=>y.stage==="intent");if(!l){n.stillStale.push(s.id);continue}let u=oe.existsSync(s.path)?oe.readFileSync(s.path,"utf-8"):null,d=oe.existsSync(c.path)?oe.readFileSync(c.path,"utf-8"):null,f=oe.existsSync(l.path)?oe.readFileSync(l.path,"utf-8"):null;if(!u||!d||!f){n.stillStale.push(s.id);continue}let{runDualValidation:m}=await Promise.resolve().then(()=>(Ko(),Wu)),p,g;if(s.stage==="unit")p="intent-to-unit",g="unit-to-intent";else if(s.stage==="code-generation")p="unit-to-bolt",g="bolt-to-intent";else{n.stillStale.push(s.id);continue}m(u,d,f,p,g,c.id,s.id,l.id).passed?(s.contract_status="active",s.stale_reason=null,s.statusHistory||(s.statusHistory=[]),s.statusHistory.push({status:"active",timestamp:new Date().toISOString()}),n.restored.push(s.id)):n.stillStale.push(s.id)}catch(a){n.errors.push(`Error revalidating ${s.id}: ${a}`),n.stillStale.push(s.id)}return F(o,r),n}var oe,et,Hu,J=B(()=>{"use strict";oe=b(ue(),1),et=b(require("path"),1),Hu=require("crypto")});async function Yu(e,t){let n=j.join(e,"aidlc-docs",t),o=j.join(n,"checkpoint.json");try{await he.ensureDir(n),await he.ensureDir(j.join(n,"inception")),await he.ensureDir(j.join(n,"construction")),await he.ensureDir(j.join(n,"construction","design")),await he.ensureDir(j.join(n,"operations")),await he.pathExists(o)||await he.writeJson(o,{workflow_id:t,current_stage:"intent",created_at:new Date().toISOString(),updated_at:new Date().toISOString()},{spaces:2})}catch(r){let i=r;throw i.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.")):i.code==="EACCES"||i.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}`)):i.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: ${i.message}`),console.error(`[Artifacts] Workflow ID: ${t}`),console.error(`[Artifacts] Path: ${n}`),new Error(`Failed to create workflow directory for ${t}: ${i.message}`))}}function Ot(e,t,n,o,r){let i=j.join(e,"aidlc-docs",t);switch(n){case"intent":return j.join(i,"inception","intent.md");case"nfr":return j.join(i,"inception","requirements","nfr.md");case"unit":if(!o)throw new Error("artifactId is required for unit artifacts");return j.join(i,"construction",o,"spec.md");case"code-generation":if(!o)throw new Error("artifactId is required for code-generation artifacts");if(!r)throw new Error("unitId is required for code-generation artifacts");return j.join(i,"construction",r,`${o}.md`);case"validation-report":if(!o)throw new Error("artifactId is required for validation-report artifacts");return j.join(i,"construction",o,"validation-report.md");case"interfaces":return j.join(i,"construction","design","interfaces.json");case"data-flow":return j.join(i,"construction","design","data-flow.json");case"components":return j.join(i,"construction","design","components.json");case"deploy-guide":return j.join(i,"operations","deploy-guide.md");case"runbook":return j.join(i,"operations","runbook.md");case"monitoring":return j.join(i,"operations","monitoring.json");case"release-notes":return j.join(i,"operations","release-notes.md");case"state":return j.join(i,"state.md");case"audit":return j.join(i,"audit.md");case"analysis-plan":return j.join(i,"discovery","analysis-plan.md");case"current-state-analysis":return j.join(i,"discovery","current-state-analysis.md");case"regression-baseline":return j.join(i,"discovery","regression-baseline.md");case"change-impact":return j.join(i,"discovery","change-impact.md");case"static-model":return j.join(i,"discovery","static-model.md");case"dynamic-model":return j.join(i,"discovery","dynamic-model.md");case"WORKFLOW_ROUTING":return j.join(i,"inception","plans","workflow-routing.md");case"requirements-qa":return j.join(i,"inception","requirements","requirements-analysis-questions.md");case"requirements":return j.join(i,"inception","requirements","requirements.md");case"personas":return j.join(i,"inception","user-stories","personas.md");case"user-stories":return j.join(i,"inception","user-stories","stories.md");case"execution-plan":return j.join(i,"inception","plans","execution-plan.md");case"units-generation":return j.join(i,"inception","application-design","unit-of-work.md");case"unit-dependency":return j.join(i,"inception","application-design","unit-of-work-dependency.md");case"unit-story-map":return j.join(i,"inception","application-design","unit-of-work-story-map.md");default:throw new Error(`Unknown artifact type: ${n}`)}}async function hn(e,t,n,o,r,i){let s=Ot(e,t,n,r,i),a=await he.pathExists(s);try{await he.ensureDir(j.dirname(s)),await he.writeFile(s,o,"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: ${s}`),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: ${s}`),new Error(`Failed to write ${n} artifact: Permission denied for ${s}`)):l.code==="EROFS"?(console.error(`[Artifacts] Failed to write ${n} artifact: Read-only filesystem`),console.error(`[Artifacts] Path: ${s}`),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: ${s}`),new Error(`Failed to write ${n} artifact: ${l.message}`))}if(a)try{let c=j.join(e,"aidlc-docs",t,"manifest.json"),{cascadeInvalidation:l,loadManifest:u,saveManifest:d,computeChecksum:f}=await Promise.resolve().then(()=>(J(),Vt)),m=u(c);if(m){let p=s.replace(/\\/g,"/"),g=m.artifacts.find(h=>h.path===p||h.path.endsWith(j.basename(s)));if(g){let h=f(s);h&&(g.checksum=h,g.updated_at=new Date().toISOString(),d(c,m)),l(c,g.id)}}}catch(c){console.error("[Artifacts] Cascade invalidation after write failed:",c)}}async function Wi(e,t){let n=j.join(e,"aidlc-docs",t,"discovery");await he.ensureDir(n)}var j,he,Hi=B(()=>{"use strict";j=b(require("path"),1),he=b(ue(),1)});function rd(e){let t={id:(0,od.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};St(t)}function id(e){let t=xo();return $o(e,t)}var od,Qo=B(()=>{"use strict";od=require("crypto");fe()});var Xo={};st(Xo,{CODE_PLAN_FORMAT_INSTRUCTIONS:()=>Mw,buildCodeGenerationPrompt:()=>ld,buildCodePlanPath:()=>Dw,dispatchCodeGeneration:()=>jw,extractSections:()=>zi,extractTargetFiles:()=>Qi,selectAgentForCodeGeneration:()=>cd});function Dw(e,t,n){return(0,_n.join)(e,"aidlc-docs",t,"construction",n,"code-plan.md")}function zi(e,t){if(!e)return"";let n=[],o=e.split(`
23
+ `);for(let o of n){let r=o.match(/^\s*[-*+]\s+(?:\[[ x]\]\s+)?(.+)$/);r&&t.push(r[1].trim())}return t}function ow(e,t){let n=nw(e);if(t==="intent-to-unit"){let s=Ni(n),a=[],c=s.get("Business Requirements");c&&a.push(...oo(c));let l=s.get("Implementation Plan");return l&&a.push(...oo(l)),a}if(t==="unit-to-bolt"){let s=Ni(n),a=[],c=s.get("Acceptance Criteria");c&&a.push(...oo(c));let l=s.get("Target Files");return l&&a.push(...oo(l)),a}let o=Ni(n),r=tw[t],i=[];for(let s of r){let a=o.get(s);if(a){let c=oo(a);i.push(...c)}}return i}function Ko(e,t,n){try{let o=ow(e,n);if(o.length===0)return{conformance_score:100,coverage_percentage:100,missing_items:[],passed:!0};let r=t.toLowerCase(),i=[],s=0;for(let d of o){let f=d.toLowerCase();r.includes(f)?s++:i.push(d)}let a=Math.round(s/o.length*100),c=a,l=Wu[n],u=a>=l;return{conformance_score:a,coverage_percentage:c,missing_items:i,passed:u}}catch(o){return console.error("[Alignment] Verification computation failed:",o),{conformance_score:0,coverage_percentage:0,missing_items:["Verification computation error"],passed:!1}}}function Hu(e){let t=ew[e];return[{question:t.verification,answer:null,answered_by:null,passed:null},{question:t.validation,answer:null,answered_by:null,passed:null}]}function Di(e,t,n,o,r){try{let i=Ko(e,t,r),s=Hu(r),a=s.every(m=>m.answer!==null),c=s.every(m=>m.passed===!0),u={alignment_score:a&&c?100:0,alignment_questions:s,passed:c},d=i.passed&&u.passed;return{source_artifact_id:n,target_artifact_id:o,verification:i,validation:u,alignment_passed:d,checked_at:new Date().toISOString()}}catch(i){return console.error("[Alignment] Alignment check failed:",i),{source_artifact_id:n,target_artifact_id:o,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 gn(e,t,n,o,r,i,s,a){let c=Di(t,e,i,s,o),l=Di(n,e,a,s,r),u=c.alignment_passed&&l.alignment_passed;return{parentCheck:c,rootCheck:l,passed:u}}function rw(e,t){let n=0;t>=2&&(n+=10),t>=3&&(n+=10);let o=e-n;return Math.max(0,o)}function iw(e,t){try{let n=D(e);if(!n){console.error(`[Alignment] Manifest not found at ${e}`);return}n.alignment_checks.push(t),F(e,n)}catch(n){console.error("[Alignment] Failed to record alignment result:",n)}}function sw(e){return Wu[e]}var Wu,ew,tw,Jo=B(()=>{"use strict";J();Wu={"intent-to-unit":95,"unit-to-bolt":100,"unit-to-intent":80,"bolt-to-intent":70},ew={"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?"}},tw={"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 Vt={};st(Vt,{addGateAuditEntry:()=>Ce,cascadeInvalidation:()=>cw,computeChecksum:()=>zo,createManifest:()=>Mi,detectStaleArtifacts:()=>aw,getArtifactById:()=>dw,getArtifactsByPhase:()=>pw,getBoltArtifacts:()=>nt,getBoltsByStatus:()=>Fi,getUnitArtifacts:()=>qt,isWorkflowComplete:()=>qu,linkArtifacts:()=>Li,loadManifest:()=>D,normalizePath:()=>ji,recoverManifest:()=>uw,registerArtifact:()=>xe,revalidateStaleArtifacts:()=>mw,runAlignmentCheck:()=>lw,saveManifest:()=>F,transitionToActive:()=>Ui,transitionToDraft:()=>Vu,transitionToFulfilled:()=>Wi,transitionToStale:()=>Ku,transitionToViolated:()=>Yu,updateContractStatus:()=>tt,updatePhaseStatus:()=>ut});function ji(e){return e.replace(/\\/g,"/")}function Rt(){return{status:"not_started",started_at:null,completed_at:null,gate_result:null,gate_bypassed:!1,bypass_reason:null}}function Mi(e,t,n){let o=et.join(n,"aidlc-docs",e),r=et.join(o,"manifest.json");try{oe.ensureDirSync(o);let i=new Date().toISOString(),s={schema_version:"2.0.0",workflow_id:e,feature_name:t,created_at:i,updated_at:i,phases:{discovery:Rt(),inception:Rt(),construction:Rt(),operations:Rt()},depth_assessment:null,artifacts:[],links:[],risks:[],gate_audit:[],metrics:null,alignment_checks:[],risk_tier:null};return oe.writeFileSync(r,JSON.stringify(s,null,2),"utf-8"),r}catch(i){throw console.error(`Failed to create manifest at ${r}:`,i),i}}function D(e){try{if(!oe.existsSync(e))return null;let t=oe.readFileSync(e,"utf-8");return JSON.parse(t)}catch(t){return console.error(`Failed to load manifest at ${e}:`,t),null}}function F(e,t){try{t.updated_at=new Date().toISOString(),oe.writeFileSync(e,JSON.stringify(t,null,2),"utf-8")}catch(n){throw console.error(`Failed to save manifest at ${e}:`,n),n}}function zo(e){try{if(!oe.existsSync(e))return null;let t=oe.readFileSync(e),n=(0,Bu.createHash)("sha256");return n.update(t),n.digest("hex")}catch(t){return console.error(`Failed to compute checksum for ${e}:`,t),null}}function xe(e,t){try{let n=D(e);if(!n)throw new Error(`Manifest not found at ${e}`);let o=new Date().toISOString(),r=ji(t.path),i=n.artifacts.findIndex(a=>a.id===t.id),s=zo(t.path);if(i>=0){let a=n.artifacts[i];n.artifacts[i]={...a,...t,path:r,updated_at:o,contract_version:a.contract_version+1,checksum:s}}else{let a={...t,path:r,created_at:o,updated_at:o,contract_version:1,contract_status:"draft",stale_reason:null,checksum:s};n.artifacts.push(a)}F(e,n)}catch(n){throw console.error(`Failed to register artifact in ${e}:`,n),n}}function Li(e,t){try{let n=D(e);if(!n)throw new Error(`Manifest not found at ${e}`);let o=n.artifacts.some(s=>s.id===t.source_id),r=n.artifacts.some(s=>s.id===t.target_id);if(!o)throw new Error(`Source artifact not found: ${t.source_id}`);if(!r)throw new Error(`Target artifact not found: ${t.target_id}`);n.links.some(s=>s.source_id===t.source_id&&s.target_id===t.target_id&&s.link_type===t.link_type)||(n.links.push(t),F(e,n))}catch(n){throw console.error(`Failed to link artifacts in ${e}:`,n),n}}function aw(e){try{let t=D(e);if(!t)return[];let n=[];for(let o of t.artifacts)if(o.checksum&&o.write_complete){let r=zo(o.path);r&&r!==o.checksum&&n.push(o.id)}return n}catch(t){return console.error(`Failed to detect stale artifacts in ${e}:`,t),[]}}function cw(e,t){try{let n=D(e);if(!n)return;let o=new Set,r=[t];for(;r.length>0;){let i=r.shift();if(o.has(i))continue;o.add(i);let s=n.artifacts.find(c=>c.id===i);if(s){let c=i===t?"Artifact content was modified":`Parent artifact ${i} was modified`;fw(s,c)}let a=n.links.filter(c=>c.source_id===i);for(let c of a)o.has(c.target_id)||r.push(c.target_id)}F(e,n)}catch(n){console.error(`Failed to cascade invalidation in ${e}:`,n)}}function lw(e,t,n){try{let o=D(e);if(!o)return;let r=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:r};o.alignment_checks.push(a),F(e,o)}catch(o){console.error(`Failed to run alignment check in ${e}:`,o)}}function uw(e,t){try{let n=et.join(e,"aidlc-docs",t);if(!oe.existsSync(n))return null;let o=new Date().toISOString(),r={schema_version:"2.0.0",workflow_id:t,feature_name:"Recovered Workflow",created_at:o,updated_at:o,phases:{discovery:Rt(),inception:Rt(),construction:Rt(),operations:Rt()},depth_assessment:null,artifacts:[],links:[],risks:[],gate_audit:[],metrics:null,alignment_checks:[],risk_tier:null},i=oe.readdirSync(n,{recursive:!0,withFileTypes:!0});for(let s of i)if(s.isFile()&&s.name!=="manifest.json"){let a=et.join(s.path,s.name),c=et.relative(n,a),l=ji(a),u={id:`recovered-${Date.now()}-${r.artifacts.length}`,type:et.extname(s.name)||"unknown",phase:"inception",stage:"intent",path:l,created_at:o,updated_at:o,validation_passed:null,write_complete:!0,checksum:zo(a),contract_status:"draft",contract_version:1,stale_reason:null};r.artifacts.push(u)}return r}catch(n){return console.error(`Failed to recover manifest for workflow ${t}:`,n),null}}function ut(e,t,n,o,r){try{let i=D(e);if(!i)return;i.phases[t].status=n,o!==void 0&&(i.phases[t].started_at=o),r!==void 0&&(i.phases[t].completed_at=r),F(e,i)}catch(i){console.error(`Failed to update phase status in ${e}:`,i)}}function Ce(e,t){try{let n=D(e);if(!n)return;let o={...t,timestamp:new Date().toISOString()};n.gate_audit.push(o),F(e,n)}catch(n){console.error(`Failed to add gate audit entry in ${e}:`,n)}}function dw(e,t){return e.artifacts.find(n=>n.id===t)}function pw(e,t){return e.artifacts.filter(n=>n.phase===t)}function tt(e,t,n,o){try{switch(n){case"draft":Vu(e,t);break;case"active":Ui(e,t);break;case"fulfilled":Wi(e,t);break;case"violated":Yu(e,t);break;case"stale":if(!o)throw new Error('staleReason is required when setting status to "stale"');Ku(e,t,o);break}}catch(r){console.error(`Failed to update contract status in ${e}:`,r)}}function qt(e){return e.artifacts.filter(t=>t.stage==="unit")}function nt(e,t){let n=e.artifacts.filter(o=>o.stage==="code-generation");if(t){let o=new Set(e.links.filter(r=>r.source_id===t&&(r.link_type==="derives"||r.link_type==="implements")).map(r=>r.target_id));return n.filter(r=>o.has(r.id))}return n}function Fi(e,t){return e.artifacts.filter(n=>n.stage==="code-generation"&&n.contract_status===t)}function qu(e){let t=e.artifacts.filter(n=>n.stage==="code-generation");return t.length===0?!1:t.every(n=>n.contract_status==="fulfilled")}function fw(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 Vu(e,t){let n=D(e);if(!n)throw new Error(`Manifest not found at ${e}`);let o=n.artifacts.find(r=>r.id===t);if(!o)throw new Error(`Artifact ${t} not found in manifest`);if(o.contract_status!=="violated"&&o.contract_status!=="stale")throw new Error(`Cannot transition from '${o.contract_status}' to 'draft'`);o.contract_status="draft",o.stale_reason=null,o.statusHistory||(o.statusHistory=[]),o.statusHistory.push({status:"draft",timestamp:new Date().toISOString()}),F(e,n)}function Ui(e,t){let n=D(e);if(!n)throw new Error(`Manifest not found at ${e}`);let o=n.artifacts.find(r=>r.id===t);if(!o)throw new Error(`Artifact ${t} not found in manifest`);if(o.contract_status!=="draft"&&o.contract_status!=="stale")throw new Error(`Cannot transition from '${o.contract_status}' to 'active'`);o.contract_status="active",o.stale_reason=null,o.statusHistory||(o.statusHistory=[]),o.statusHistory.push({status:"active",timestamp:new Date().toISOString()}),F(e,n)}function Wi(e,t){let n=D(e);if(!n)throw new Error(`Manifest not found at ${e}`);let o=n.artifacts.find(r=>r.id===t);if(!o)throw new Error(`Artifact ${t} not found in manifest`);if(o.contract_status!=="active")throw new Error(`Cannot transition from '${o.contract_status}' to 'fulfilled'`);o.contract_status="fulfilled",o.stale_reason=null,o.statusHistory||(o.statusHistory=[]),o.statusHistory.push({status:"fulfilled",timestamp:new Date().toISOString()}),F(e,n)}function Yu(e,t){let n=D(e);if(!n)throw new Error(`Manifest not found at ${e}`);let o=n.artifacts.find(r=>r.id===t);if(!o)throw new Error(`Artifact ${t} not found in manifest`);if(o.contract_status!=="active")throw new Error(`Cannot transition from '${o.contract_status}' to 'violated'`);o.contract_status="violated",o.stale_reason=null,o.statusHistory||(o.statusHistory=[]),o.statusHistory.push({status:"violated",timestamp:new Date().toISOString()}),F(e,n)}function Ku(e,t,n){let o=D(e);if(!o)throw new Error(`Manifest not found at ${e}`);let r=o.artifacts.find(i=>i.id===t);if(!r)throw new Error(`Artifact ${t} not found in manifest`);if(r.contract_status!=="active"&&r.contract_status!=="fulfilled")throw new Error(`Cannot transition from '${r.contract_status}' to 'stale'`);r.contract_status="stale",r.stale_reason=n,r.statusHistory||(r.statusHistory=[]),r.statusHistory.push({status:"stale",timestamp:new Date().toISOString()}),F(e,o)}async function mw(e,t){let n={restored:[],stillStale:[],errors:[]},o=et.join(e,"aidlc-docs",t,"manifest.json"),r=D(o);if(!r)return n.errors.push("Manifest not found"),n;let i=r.artifacts.filter(s=>s.contract_status==="stale");for(let s of i)try{let a=r.links.find(y=>y.target_id===s.id);if(!a){n.stillStale.push(s.id);continue}let c=r.artifacts.find(y=>y.id===a.source_id);if(!c){n.stillStale.push(s.id);continue}let l=r.artifacts.find(y=>y.stage==="intent");if(!l){n.stillStale.push(s.id);continue}let u=oe.existsSync(s.path)?oe.readFileSync(s.path,"utf-8"):null,d=oe.existsSync(c.path)?oe.readFileSync(c.path,"utf-8"):null,f=oe.existsSync(l.path)?oe.readFileSync(l.path,"utf-8"):null;if(!u||!d||!f){n.stillStale.push(s.id);continue}let{runDualValidation:m}=await Promise.resolve().then(()=>(Jo(),Gu)),p,g;if(s.stage==="unit")p="intent-to-unit",g="unit-to-intent";else if(s.stage==="code-generation")p="unit-to-bolt",g="bolt-to-intent";else{n.stillStale.push(s.id);continue}m(u,d,f,p,g,c.id,s.id,l.id).passed?(s.contract_status="active",s.stale_reason=null,s.statusHistory||(s.statusHistory=[]),s.statusHistory.push({status:"active",timestamp:new Date().toISOString()}),n.restored.push(s.id)):n.stillStale.push(s.id)}catch(a){n.errors.push(`Error revalidating ${s.id}: ${a}`),n.stillStale.push(s.id)}return F(o,r),n}var oe,et,Bu,J=B(()=>{"use strict";oe=b(ue(),1),et=b(require("path"),1),Bu=require("crypto")});async function Ju(e,t){let n=j.join(e,"aidlc-docs",t),o=j.join(n,"checkpoint.json");try{await he.ensureDir(n),await he.ensureDir(j.join(n,"inception")),await he.ensureDir(j.join(n,"construction")),await he.ensureDir(j.join(n,"construction","design")),await he.ensureDir(j.join(n,"operations")),await he.pathExists(o)||await he.writeJson(o,{workflow_id:t,current_stage:"intent",created_at:new Date().toISOString(),updated_at:new Date().toISOString()},{spaces:2})}catch(r){let i=r;throw i.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.")):i.code==="EACCES"||i.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}`)):i.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: ${i.message}`),console.error(`[Artifacts] Workflow ID: ${t}`),console.error(`[Artifacts] Path: ${n}`),new Error(`Failed to create workflow directory for ${t}: ${i.message}`))}}function Ot(e,t,n,o,r){let i=j.join(e,"aidlc-docs",t);switch(n){case"intent":return j.join(i,"inception","intent.md");case"nfr":return j.join(i,"inception","requirements","nfr.md");case"unit":if(!o)throw new Error("artifactId is required for unit artifacts");return j.join(i,"construction",o,"spec.md");case"code-generation":if(!o)throw new Error("artifactId is required for code-generation artifacts");if(!r)throw new Error("unitId is required for code-generation artifacts");return j.join(i,"construction",r,`${o}.md`);case"validation-report":if(!o)throw new Error("artifactId is required for validation-report artifacts");return j.join(i,"construction",o,"validation-report.md");case"interfaces":return j.join(i,"construction","design","interfaces.json");case"data-flow":return j.join(i,"construction","design","data-flow.json");case"components":return j.join(i,"construction","design","components.json");case"deploy-guide":return j.join(i,"operations","deploy-guide.md");case"runbook":return j.join(i,"operations","runbook.md");case"monitoring":return j.join(i,"operations","monitoring.json");case"release-notes":return j.join(i,"operations","release-notes.md");case"state":return j.join(i,"state.md");case"audit":return j.join(i,"audit.md");case"analysis-plan":return j.join(i,"discovery","analysis-plan.md");case"current-state-analysis":return j.join(i,"discovery","current-state-analysis.md");case"regression-baseline":return j.join(i,"discovery","regression-baseline.md");case"change-impact":return j.join(i,"discovery","change-impact.md");case"static-model":return j.join(i,"discovery","static-model.md");case"dynamic-model":return j.join(i,"discovery","dynamic-model.md");case"WORKFLOW_ROUTING":return j.join(i,"inception","plans","workflow-routing.md");case"requirements-qa":return j.join(i,"inception","requirements","requirements-analysis-questions.md");case"requirements":return j.join(i,"inception","requirements","requirements.md");case"personas":return j.join(i,"inception","user-stories","personas.md");case"user-stories":return j.join(i,"inception","user-stories","stories.md");case"execution-plan":return j.join(i,"inception","plans","execution-plan.md");case"units-generation":return j.join(i,"inception","application-design","unit-of-work.md");case"unit-dependency":return j.join(i,"inception","application-design","unit-of-work-dependency.md");case"unit-story-map":return j.join(i,"inception","application-design","unit-of-work-story-map.md");default:throw new Error(`Unknown artifact type: ${n}`)}}async function hn(e,t,n,o,r,i){let s=Ot(e,t,n,r,i),a=await he.pathExists(s);try{await he.ensureDir(j.dirname(s)),await he.writeFile(s,o,"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: ${s}`),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: ${s}`),new Error(`Failed to write ${n} artifact: Permission denied for ${s}`)):l.code==="EROFS"?(console.error(`[Artifacts] Failed to write ${n} artifact: Read-only filesystem`),console.error(`[Artifacts] Path: ${s}`),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: ${s}`),new Error(`Failed to write ${n} artifact: ${l.message}`))}if(a)try{let c=j.join(e,"aidlc-docs",t,"manifest.json"),{cascadeInvalidation:l,loadManifest:u,saveManifest:d,computeChecksum:f}=await Promise.resolve().then(()=>(J(),Vt)),m=u(c);if(m){let p=s.replace(/\\/g,"/"),g=m.artifacts.find(h=>h.path===p||h.path.endsWith(j.basename(s)));if(g){let h=f(s);h&&(g.checksum=h,g.updated_at=new Date().toISOString(),d(c,m)),l(c,g.id)}}}catch(c){console.error("[Artifacts] Cascade invalidation after write failed:",c)}}async function Hi(e,t){let n=j.join(e,"aidlc-docs",t,"discovery");await he.ensureDir(n)}var j,he,Gi=B(()=>{"use strict";j=b(require("path"),1),he=b(ue(),1)});function sd(e){let t={id:(0,id.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};_t(t)}function ad(e){let t=$o();return No(e,t)}var id,Xo=B(()=>{"use strict";id=require("crypto");fe()});var Zo={};st(Zo,{CODE_PLAN_FORMAT_INSTRUCTIONS:()=>Lw,buildCodeGenerationPrompt:()=>dd,buildCodePlanPath:()=>jw,dispatchCodeGeneration:()=>Mw,extractSections:()=>Qi,extractTargetFiles:()=>Xi,selectAgentForCodeGeneration:()=>ud});function jw(e,t,n){return(0,Sn.join)(e,"aidlc-docs",t,"construction",n,"code-plan.md")}function Qi(e,t){if(!e)return"";let n=[],o=e.split(`
24
24
  `);for(let r=0;r<o.length;r++){let i=o[r],s=i.match(/^##\s+(.+)$/)||i.match(/^###\s+(.+)$/);if(s){let a=s[1].trim();if(t.some(c=>a.includes(c))){let c=[i],l=i.match(/^(#+)/)?.[1].length||2;for(let u=r+1;u<o.length;u++){let d=o[u],f=d.match(/^(#+)\s/);if(f&&f[1].length<=l)break;c.push(d)}n.push(c.join(`
25
25
  `))}}}return n.length>0?n.join(`
26
26
 
27
- `):e}function Qi(e){let t=[],n=e.split(`
28
- `),o=!1;for(let r of n){if(r.match(/^##\s+Target Files/i)||r.match(/^###\s+Target Files/i)){o=!0;continue}if(o&&r.match(/^##\s+/))break;if(o){let i=r.match(/^-\s+(.+)$/);i&&t.push(i[1].trim())}}return t}function cd(e){let t=Qi(e),n=["olympian-low","frontend-engineer-low","oracle-low"];for(let o of n){let r=id(o);if(r&&r.success_rate>.8&&r.total_invocations>10)return sd(t,e)?o.startsWith("frontend")?o:"frontend-engineer-low":ad(e)?o.startsWith("oracle")?o:"oracle-low":o.startsWith("olympian")?o:"olympian-low"}return sd(t,e)?"frontend-engineer":ad(e)?"oracle":"olympian"}function sd(e,t){let n=[".tsx",".jsx",".css",".scss","/ui/","/component","/page","/layout"];for(let o of e){let r=o.toLowerCase();if(n.some(i=>r.includes(i)))return!0}return!1}function ad(e){let t=["debug","fix","investigate","diagnose"],n=e.toLowerCase();return t.some(o=>n.includes(o))}function ld(e,t,n,o){let r=o?`
27
+ `):e}function Xi(e){let t=[],n=e.split(`
28
+ `),o=!1;for(let r of n){if(r.match(/^##\s+Target Files/i)||r.match(/^###\s+Target Files/i)){o=!0;continue}if(o&&r.match(/^##\s+/))break;if(o){let i=r.match(/^-\s+(.+)$/);i&&t.push(i[1].trim())}}return t}function ud(e){let t=Xi(e),n=["olympian-low","frontend-engineer-low","oracle-low"];for(let o of n){let r=ad(o);if(r&&r.success_rate>.8&&r.total_invocations>10)return cd(t,e)?o.startsWith("frontend")?o:"frontend-engineer-low":ld(e)?o.startsWith("oracle")?o:"oracle-low":o.startsWith("olympian")?o:"olympian-low"}return cd(t,e)?"frontend-engineer":ld(e)?"oracle":"olympian"}function cd(e,t){let n=[".tsx",".jsx",".css",".scss","/ui/","/component","/page","/layout"];for(let o of e){let r=o.toLowerCase();if(n.some(i=>r.includes(i)))return!0}return!1}function ld(e){let t=["debug","fix","investigate","diagnose"],n=e.toLowerCase();return t.some(o=>n.includes(o))}function dd(e,t,n,o){let r=o?`
29
29
  ## Execution Protocol (Two-Part Code Generation)
30
30
  PART 1 - PLAN:
31
31
  1. Create an execution plan in a markdown file with checkboxes for each step
@@ -52,13 +52,13 @@ Generate code for this unit according to the spec above.
52
52
  - Create/modify files listed in "Target Files"
53
53
  - Write tests per "Test Requirements"
54
54
  - Meet all "Acceptance Criteria"
55
- - Do NOT modify files outside the target list without justification`}async function jw(e,t,n){let o=(0,_n.join)(e,"aidlc-docs",t),r=(0,_n.join)(o,"construction"),i=(0,_n.join)(r,n,"spec.md"),s=(0,Sn.existsSync)(i)?(0,Sn.readFileSync)(i,"utf-8"):"",a=(0,_n.join)(o,"inception","intent.md"),c=(0,Sn.existsSync)(a)?(0,Sn.readFileSync)(a,"utf-8"):"",l=zi(c,["Business Requirements","Technical Specification"]),u=zi(c,["Problem Statement","Success Metrics"]),d=Qi(s),f=cd(s),m=ld(u,l,s);return{unitName:n,agentType:f,prompt:m,context:{unitSpec:s,intentSummary:l,intentSummary2:u,targetFiles:d}}}var Sn,_n,Mw,Zo=B(()=>{"use strict";Sn=require("fs"),_n=require("path");Qo();Mw=`A code generation plan must contain:
55
+ - Do NOT modify files outside the target list without justification`}async function Mw(e,t,n){let o=(0,Sn.join)(e,"aidlc-docs",t),r=(0,Sn.join)(o,"construction"),i=(0,Sn.join)(r,n,"spec.md"),s=(0,_n.existsSync)(i)?(0,_n.readFileSync)(i,"utf-8"):"",a=(0,Sn.join)(o,"inception","intent.md"),c=(0,_n.existsSync)(a)?(0,_n.readFileSync)(a,"utf-8"):"",l=Qi(c,["Business Requirements","Technical Specification"]),u=Qi(c,["Problem Statement","Success Metrics"]),d=Xi(s),f=ud(s),m=dd(u,l,s);return{unitName:n,agentType:f,prompt:m,context:{unitSpec:s,intentSummary:l,intentSummary2:u,targetFiles:d}}}var _n,Sn,Lw,er=B(()=>{"use strict";_n=require("fs"),Sn=require("path");Xo();Lw=`A code generation plan must contain:
56
56
  1. A title line: "# Code Plan: {unitName}"
57
57
  2. A checklist of implementation steps using markdown checkboxes (- [ ] step)
58
58
  3. Each step should be specific and actionable
59
59
  4. Steps should be ordered by dependency (prerequisites first)
60
60
  5. Include a "## Verification" section with test/validation checkboxes
61
- The plan file is saved at: aidlc-docs/{workflowId}/construction/{unitName}/code-plan.md`});async function ud(e,t,n){let o=vn.default.join(e,"aidlc-docs",t,"inception","requirements","nfr.md"),r=vn.default.join(e,"aidlc-docs",t,"construction",n,"spec.md"),i=vn.default.join(e,"aidlc-docs",t,"construction",n,"nfr-requirements.md"),s="";try{await Kt.default.pathExists(o)&&(s=await Kt.default.readFile(o,"utf-8"))}catch{}let a="";try{await Kt.default.pathExists(r)&&(a=await Kt.default.readFile(r,"utf-8"))}catch{}let c=a.match(/^title:\s*(.+)$/m),l=c?c[1].trim().replace(/^["']|["']$/g,""):n,u=Lw(s,a,l),d=new Date().toISOString(),f=`---
61
+ The plan file is saved at: aidlc-docs/{workflowId}/construction/{unitName}/code-plan.md`});async function pd(e,t,n){let o=vn.default.join(e,"aidlc-docs",t,"inception","requirements","nfr.md"),r=vn.default.join(e,"aidlc-docs",t,"construction",n,"spec.md"),i=vn.default.join(e,"aidlc-docs",t,"construction",n,"nfr-requirements.md"),s="";try{await Kt.default.pathExists(o)&&(s=await Kt.default.readFile(o,"utf-8"))}catch{}let a="";try{await Kt.default.pathExists(r)&&(a=await Kt.default.readFile(r,"utf-8"))}catch{}let c=a.match(/^title:\s*(.+)$/m),l=c?c[1].trim().replace(/^["']|["']$/g,""):n,u=Fw(s,a,l),d=new Date().toISOString(),f=`---
62
62
  id: ${n}-nfr-requirements
63
63
  parent_unit: ${n}
64
64
  generated_at: ${d}
@@ -75,8 +75,8 @@ ${u||"_No specific NFRs identified for this unit. Inherit project-level defaults
75
75
 
76
76
  ## Unit Context
77
77
  ${l}
78
- `;await Kt.default.ensureDir(vn.default.dirname(i)),await Kt.default.writeFile(i,f,"utf-8");try{let m=vn.default.join(e,"aidlc-docs",t,"manifest.json");Pe(m,{id:`${n}-nfr-requirements`,type:"NFR_REQUIREMENTS",phase:"construction",stage:"unit",path:i,validation_passed:null,write_complete:!0,checksum:null})}catch(m){console.error(`[NFRRequirements] Failed to register artifact for ${n}:`,m)}return{artifactPath:i,nfrContent:u}}function Lw(e,t,n){if(!e.trim())return"";let o=e.split(/(?=^## )/m).filter(a=>a.trim());if(o.length===0)return e;let r=Fw(t+" "+n);if(r.length===0)return e;let s=o.map(a=>{let c=a.toLowerCase(),l=r.filter(u=>c.includes(u)).length;return{section:a,score:l}}).filter(a=>a.score>0);return s.length===0?e:s.map(a=>a.section).join(`
79
- `)}function Fw(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,o,r)=>r.indexOf(n)===o).slice(0,30)}var Kt,vn,dd=B(()=>{"use strict";Kt=b(ue(),1),vn=b(require("path"),1);J()});var pd={};st(pd,{UnitStageRunner:()=>Xi});var Ie,dt,Uw,Xi,fd=B(()=>{"use strict";Ie=b(ue(),1),dt=b(require("path"),1);dd();Uw={SHALLOW:[],MEDIUM:["functional-design","nfr-requirements"],DEEP:["functional-design","nfr-requirements","nfr-design","infrastructure-design"]},Xi=class{projectPath;workflowId;constructor(t,n){this.projectPath=t,this.workflowId=n}async executeForUnit(t,n,o,r){let i=Uw[n],s=dt.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:i.includes(u)?"not_started":"skipped",artifact_path:null,completed_at:null};if(i.length===0)return console.log(`[UnitStageRunner] SHALLOW depth: skipping all design stages for ${t}`),c;console.log(`[UnitStageRunner] Running ${i.length} design stages for ${t} (${n})`);let l="";try{let u=dt.default.join(s,"spec.md");await Ie.default.pathExists(u)&&(l=await Ie.default.readFile(u,"utf-8"))}catch{}for(let u of i){c.stages[u].status="in_progress";try{let d=await this.executeStage(u,t,s,l,o,r);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,i,c),c}async executeStage(t,n,o,r,i,s){switch(await Ie.default.ensureDir(o),t){case"functional-design":{let a=dt.default.join(o,"functional-design.md"),c=this.buildFunctionalDesignContent(n,r,i);return await Ie.default.writeFile(a,c,"utf-8"),a}case"nfr-requirements":return(await ud(this.projectPath,this.workflowId,n)).artifactPath;case"nfr-design":{let a=dt.default.join(o,"nfr-design.md"),c=dt.default.join(o,"nfr-requirements.md"),l=s||"";try{await Ie.default.pathExists(c)&&(l=await Ie.default.readFile(c,"utf-8"))}catch{}let u=this.buildNFRDesignContent(n,r,l);return await Ie.default.writeFile(a,u,"utf-8"),a}case"infrastructure-design":{let a=dt.default.join(o,"infrastructure-design.md"),c=dt.default.join(o,"nfr-design.md"),l="";try{await Ie.default.pathExists(c)&&(l=await Ie.default.readFile(c,"utf-8"))}catch{}let u=this.buildInfrastructureDesignContent(n,r,l);return await Ie.default.writeFile(a,u,"utf-8"),a}default:throw new Error(`Stage '${t}' not handled by UnitStageRunner`)}}buildFunctionalDesignContent(t,n,o){let r=n.match(/^title:\s*(.+)$/m),i=r?r[1].trim().replace(/^["']|["']$/g,""):t,s=new Date().toISOString();return`---
78
+ `;await Kt.default.ensureDir(vn.default.dirname(i)),await Kt.default.writeFile(i,f,"utf-8");try{let m=vn.default.join(e,"aidlc-docs",t,"manifest.json");xe(m,{id:`${n}-nfr-requirements`,type:"NFR_REQUIREMENTS",phase:"construction",stage:"unit",path:i,validation_passed:null,write_complete:!0,checksum:null})}catch(m){console.error(`[NFRRequirements] Failed to register artifact for ${n}:`,m)}return{artifactPath:i,nfrContent:u}}function Fw(e,t,n){if(!e.trim())return"";let o=e.split(/(?=^## )/m).filter(a=>a.trim());if(o.length===0)return e;let r=Uw(t+" "+n);if(r.length===0)return e;let s=o.map(a=>{let c=a.toLowerCase(),l=r.filter(u=>c.includes(u)).length;return{section:a,score:l}}).filter(a=>a.score>0);return s.length===0?e:s.map(a=>a.section).join(`
79
+ `)}function Uw(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,o,r)=>r.indexOf(n)===o).slice(0,30)}var Kt,vn,fd=B(()=>{"use strict";Kt=b(ue(),1),vn=b(require("path"),1);J()});var md={};st(md,{UnitStageRunner:()=>Zi});var Ie,dt,Ww,Zi,gd=B(()=>{"use strict";Ie=b(ue(),1),dt=b(require("path"),1);fd();Ww={SHALLOW:[],MEDIUM:["functional-design","nfr-requirements"],DEEP:["functional-design","nfr-requirements","nfr-design","infrastructure-design"]},Zi=class{projectPath;workflowId;constructor(t,n){this.projectPath=t,this.workflowId=n}async executeForUnit(t,n,o,r){let i=Ww[n],s=dt.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:i.includes(u)?"not_started":"skipped",artifact_path:null,completed_at:null};if(i.length===0)return console.log(`[UnitStageRunner] SHALLOW depth: skipping all design stages for ${t}`),c;console.log(`[UnitStageRunner] Running ${i.length} design stages for ${t} (${n})`);let l="";try{let u=dt.default.join(s,"spec.md");await Ie.default.pathExists(u)&&(l=await Ie.default.readFile(u,"utf-8"))}catch{}for(let u of i){c.stages[u].status="in_progress";try{let d=await this.executeStage(u,t,s,l,o,r);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,i,c),c}async executeStage(t,n,o,r,i,s){switch(await Ie.default.ensureDir(o),t){case"functional-design":{let a=dt.default.join(o,"functional-design.md"),c=this.buildFunctionalDesignContent(n,r,i);return await Ie.default.writeFile(a,c,"utf-8"),a}case"nfr-requirements":return(await pd(this.projectPath,this.workflowId,n)).artifactPath;case"nfr-design":{let a=dt.default.join(o,"nfr-design.md"),c=dt.default.join(o,"nfr-requirements.md"),l=s||"";try{await Ie.default.pathExists(c)&&(l=await Ie.default.readFile(c,"utf-8"))}catch{}let u=this.buildNFRDesignContent(n,r,l);return await Ie.default.writeFile(a,u,"utf-8"),a}case"infrastructure-design":{let a=dt.default.join(o,"infrastructure-design.md"),c=dt.default.join(o,"nfr-design.md"),l="";try{await Ie.default.pathExists(c)&&(l=await Ie.default.readFile(c,"utf-8"))}catch{}let u=this.buildInfrastructureDesignContent(n,r,l);return await Ie.default.writeFile(a,u,"utf-8"),a}default:throw new Error(`Stage '${t}' not handled by UnitStageRunner`)}}buildFunctionalDesignContent(t,n,o){let r=n.match(/^title:\s*(.+)$/m),i=r?r[1].trim().replace(/^["']|["']$/g,""):t,s=new Date().toISOString();return`---
80
80
  id: ${t}-functional-design
81
81
  parent_unit: ${t}
82
82
  stage: functional-design
@@ -139,15 +139,15 @@ Deployment topology and environment configuration.
139
139
  `+s.map(c=>`- [x] ${c}: ${o.stages[c].artifact_path}`).join(`
140
140
  `)+`
141
141
  `;await Ie.default.pathExists(r)?await Ie.default.appendFile(r,a,"utf-8"):await Ie.default.writeFile(r,`# Audit Trail
142
- ${a}`,"utf-8")}catch(r){console.error(`[UnitStageRunner] Failed to update audit for ${t}:`,r)}}}});function hd(e){try{return(0,tr.readFileSync)(e,"utf8").split(`
143
- `).length}catch{return 0}}function yd(e,t){let n=[],o;if(t===".ts"||t===".tsx"||t===".js"||t===".jsx"){let r=/import\s+(?:.*?\s+from\s+)?['"]([^'"]+)['"]/g;for(;(o=r.exec(e))!==null;)n.push(o[1]);let i=/export\s+(?:.*?\s+from\s+)?['"]([^'"]+)['"]/g;for(;(o=i.exec(e))!==null;)n.push(o[1])}else if(t===".py"){let r=/^import\s+([^\s;#]+)/gm;for(;(o=r.exec(e))!==null;)n.push(o[1]);let i=/^from\s+([^\s;#]+)\s+import/gm;for(;(o=i.exec(e))!==null;)n.push(o[1])}else if(t===".go"){let r=/import\s+"([^"]+)"/g;for(;(o=r.exec(e))!==null;)n.push(o[1]);let i=/^\s+"([^"]+)"/gm;for(;(o=i.exec(e))!==null;)n.push(o[1])}return n}async function kd(e){let t={value:0},n={value:0},o={},r=[],i=[],s={},a=[];async function c(f,m){let p={name:Pt.basename(f),path:f,fileCount:0,children:[]},g;try{g=await Zi.readdir(f,{withFileTypes:!0})}catch(h){return console.error(`[brownfield-scanner] Cannot read directory ${f}:`,h),p}for(let h of g){if(h.name.startsWith(".")||md.has(h.name))continue;let y=Pt.join(f,h.name);if(h.isDirectory()){let w=await c(y,m);p.fileCount+=w.fileCount,p.children.push(w)}else if(h.isFile()){t.value+=1,p.fileCount+=1;let w=Pt.extname(h.name);if(nr.includes(w)){n.value+=1,o[w]=(o[w]??0)+1,gd.has(h.name)&&i.push(y);let A=m??"(root)";s[A]||(s[A]=[]),s[A].push({file:y,lines:hd(y)});try{let v=(0,tr.readFileSync)(y,"utf8");for(let R of yd(v,w))r.push({sourceFile:y,importedModule:R})}catch(v){console.error(`[brownfield-scanner] Cannot read file ${y}:`,v)}}}}return p}let l=[];try{l=await Zi.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=Pt.join(e,f.name);if(f.isDirectory()){if(md.has(f.name))continue;let p=await c(m,f.name);u.push(p)}else if(f.isFile()){t.value+=1;let p=Pt.extname(f.name);if(nr.includes(p)){n.value+=1,o[p]=(o[p]??0)+1,gd.has(f.name)&&i.push(m),s["(root)"]||(s["(root)"]=[]),s["(root)"].push({file:m,lines:hd(m)});try{let h=(0,tr.readFileSync)(m,"utf8");for(let y of yd(h,p))r.push({sourceFile:m,importedModule:y})}catch(h){console.error(`[brownfield-scanner] Cannot read file ${m}:`,h)}}Ww.has(f.name)&&a.push(f.name)}}let d={};for(let[f,m]of Object.entries(s)){let p=m.slice().sort((g,h)=>h.lines-g.lines);d[f]=p.slice(0,3).map(g=>g.file)}return{totalFiles:t.value,sourceFiles:n.value,directoryTree:u,languageDistribution:o,importGraph:r,entryPoints:i,largestFilesByDirectory:d,configFiles:a}}function wd(e,t=20){let n=[],o=new Set;function r(s){o.has(s)||(o.add(s),n.push(s))}for(let s of e.entryPoints.slice(0,5))r(s);let i=Object.keys(e.largestFilesByDirectory).slice(0,10);for(let s of i){let a=e.largestFilesByDirectory[s];a&&a.length>0&&r(a[0])}for(let s of e.configFiles.slice(0,5))r(s);return n.slice(0,t)}function _d(e,t,n=15){let o=t.split(/\s+/).map(d=>d.toLowerCase().replace(/[^a-z0-9]/g,"")).filter(d=>d.length>=3&&!Hw.has(d));if(o.length===0)return[];let r=new Set(e.importGraph.map(d=>d.sourceFile));for(let d of e.entryPoints)r.add(d);for(let d of Object.values(e.largestFilesByDirectory))for(let f of d)r.add(f);let i=new Map;for(let d of e.importGraph){let f=i.get(d.sourceFile)??[];f.push(d.importedModule),i.set(d.sourceFile,f)}function s(d){let f=d.replace(/^\.+\//,"").replace(/\.js$/,"").toLowerCase();return f?Array.from(r).filter(m=>m.replace(/\\/g,"/").toLowerCase().includes(f)):[]}let a=new Set;for(let d of r){let f=d.replace(/\\/g,"/").toLowerCase();o.some(m=>f.includes(m))&&a.add(d)}let c=new Set(a);for(let d of a)for(let f of i.get(d)??[])for(let m of s(f))c.add(m);let l=[],u=new Set;for(let d of a)u.has(d)||(u.add(d),l.push(d));for(let d of c)u.has(d)||(u.add(d),l.push(d));return l.slice(0,n)}var Pt,Zi,tr,md,Ww,gd,Hw,Sd=B(()=>{"use strict";Pt=b(require("path"),1),Zi=b(require("fs/promises"),1),tr=require("fs");or();md=new Set(["node_modules",".git","dist","build",".olympus","aidlc-docs",".next","__pycache__",".venv","vendor","target"]),Ww=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"]),gd=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"]),Hw=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"])});function qw(e){let t=new Set;for(let n of Object.keys(e.languageDistribution)){let o=Gw[n];o&&t.add(o)}for(let n of e.configFiles){let o=Bw[n];o&&t.add(o)}return Array.from(t)}function Vw(e){let t=[];for(let o of e.directoryTree){let r=o.name;r==="src"?t.push("Uses src/ directory for source code"):r==="__tests__"||r==="tests"?t.push("Has dedicated test directory"):r==="packages"?t.push("Monorepo with packages/ directory"):r==="docs"?t.push("Has documentation directory"):r==="lib"&&t.push("Uses lib/ directory for library code")}return Object.entries(e.languageDistribution).filter(([,o])=>o>5).length>1&&t.push("Multi-language project"),t}function Td(e,t){try{cn(e);let n=(0,vd.join)(Qe(e),"patterns.json"),o=me(n,null),r=qw(t),i=Vw(t),s;o?s={...o,tech_stack:Array.from(new Set([...o.tech_stack,...r])),conventions:Array.from(new Set([...o.conventions,...i])),learned_rules:o.learned_rules||[],common_mistakes:o.common_mistakes||[],last_updated:new Date().toISOString()}:s={project_hash:Ec(e),project_path:e,tech_stack:r,conventions:i,learned_rules:[],common_mistakes:[],last_updated:new Date().toISOString()},Ge(n,s)}catch(n){console.error("[Olympus Learning] Failed to write project patterns:",n)}}var vd,Gw,Bw,Ed=B(()=>{"use strict";vd=require("path");fe();fe();Gw={".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"},Bw={"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 Kw(e,t){let n=e.split(`
142
+ ${a}`,"utf-8")}catch(r){console.error(`[UnitStageRunner] Failed to update audit for ${t}:`,r)}}}});function kd(e){try{return(0,nr.readFileSync)(e,"utf8").split(`
143
+ `).length}catch{return 0}}function wd(e,t){let n=[],o;if(t===".ts"||t===".tsx"||t===".js"||t===".jsx"){let r=/import\s+(?:.*?\s+from\s+)?['"]([^'"]+)['"]/g;for(;(o=r.exec(e))!==null;)n.push(o[1]);let i=/export\s+(?:.*?\s+from\s+)?['"]([^'"]+)['"]/g;for(;(o=i.exec(e))!==null;)n.push(o[1])}else if(t===".py"){let r=/^import\s+([^\s;#]+)/gm;for(;(o=r.exec(e))!==null;)n.push(o[1]);let i=/^from\s+([^\s;#]+)\s+import/gm;for(;(o=i.exec(e))!==null;)n.push(o[1])}else if(t===".go"){let r=/import\s+"([^"]+)"/g;for(;(o=r.exec(e))!==null;)n.push(o[1]);let i=/^\s+"([^"]+)"/gm;for(;(o=i.exec(e))!==null;)n.push(o[1])}return n}async function Sd(e){let t={value:0},n={value:0},o={},r=[],i=[],s={},a=[];async function c(f,m){let p={name:Pt.basename(f),path:f,fileCount:0,children:[]},g;try{g=await es.readdir(f,{withFileTypes:!0})}catch(h){return console.error(`[brownfield-scanner] Cannot read directory ${f}:`,h),p}for(let h of g){if(h.name.startsWith(".")||hd.has(h.name))continue;let y=Pt.join(f,h.name);if(h.isDirectory()){let w=await c(y,m);p.fileCount+=w.fileCount,p.children.push(w)}else if(h.isFile()){t.value+=1,p.fileCount+=1;let w=Pt.extname(h.name);if(or.includes(w)){n.value+=1,o[w]=(o[w]??0)+1,yd.has(h.name)&&i.push(y);let A=m??"(root)";s[A]||(s[A]=[]),s[A].push({file:y,lines:kd(y)});try{let v=(0,nr.readFileSync)(y,"utf8");for(let R of wd(v,w))r.push({sourceFile:y,importedModule:R})}catch(v){console.error(`[brownfield-scanner] Cannot read file ${y}:`,v)}}}}return p}let l=[];try{l=await es.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=Pt.join(e,f.name);if(f.isDirectory()){if(hd.has(f.name))continue;let p=await c(m,f.name);u.push(p)}else if(f.isFile()){t.value+=1;let p=Pt.extname(f.name);if(or.includes(p)){n.value+=1,o[p]=(o[p]??0)+1,yd.has(f.name)&&i.push(m),s["(root)"]||(s["(root)"]=[]),s["(root)"].push({file:m,lines:kd(m)});try{let h=(0,nr.readFileSync)(m,"utf8");for(let y of wd(h,p))r.push({sourceFile:m,importedModule:y})}catch(h){console.error(`[brownfield-scanner] Cannot read file ${m}:`,h)}}Hw.has(f.name)&&a.push(f.name)}}let d={};for(let[f,m]of Object.entries(s)){let p=m.slice().sort((g,h)=>h.lines-g.lines);d[f]=p.slice(0,3).map(g=>g.file)}return{totalFiles:t.value,sourceFiles:n.value,directoryTree:u,languageDistribution:o,importGraph:r,entryPoints:i,largestFilesByDirectory:d,configFiles:a}}function _d(e,t=20){let n=[],o=new Set;function r(s){o.has(s)||(o.add(s),n.push(s))}for(let s of e.entryPoints.slice(0,5))r(s);let i=Object.keys(e.largestFilesByDirectory).slice(0,10);for(let s of i){let a=e.largestFilesByDirectory[s];a&&a.length>0&&r(a[0])}for(let s of e.configFiles.slice(0,5))r(s);return n.slice(0,t)}function vd(e,t,n=15){let o=t.split(/\s+/).map(d=>d.toLowerCase().replace(/[^a-z0-9]/g,"")).filter(d=>d.length>=3&&!Gw.has(d));if(o.length===0)return[];let r=new Set(e.importGraph.map(d=>d.sourceFile));for(let d of e.entryPoints)r.add(d);for(let d of Object.values(e.largestFilesByDirectory))for(let f of d)r.add(f);let i=new Map;for(let d of e.importGraph){let f=i.get(d.sourceFile)??[];f.push(d.importedModule),i.set(d.sourceFile,f)}function s(d){let f=d.replace(/^\.+\//,"").replace(/\.js$/,"").toLowerCase();return f?Array.from(r).filter(m=>m.replace(/\\/g,"/").toLowerCase().includes(f)):[]}let a=new Set;for(let d of r){let f=d.replace(/\\/g,"/").toLowerCase();o.some(m=>f.includes(m))&&a.add(d)}let c=new Set(a);for(let d of a)for(let f of i.get(d)??[])for(let m of s(f))c.add(m);let l=[],u=new Set;for(let d of a)u.has(d)||(u.add(d),l.push(d));for(let d of c)u.has(d)||(u.add(d),l.push(d));return l.slice(0,n)}var Pt,es,nr,hd,Hw,yd,Gw,Td=B(()=>{"use strict";Pt=b(require("path"),1),es=b(require("fs/promises"),1),nr=require("fs");rr();hd=new Set(["node_modules",".git","dist","build",".olympus","aidlc-docs",".next","__pycache__",".venv","vendor","target"]),Hw=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"]),yd=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"]),Gw=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"])});function Vw(e){let t=new Set;for(let n of Object.keys(e.languageDistribution)){let o=Bw[n];o&&t.add(o)}for(let n of e.configFiles){let o=qw[n];o&&t.add(o)}return Array.from(t)}function Yw(e){let t=[];for(let o of e.directoryTree){let r=o.name;r==="src"?t.push("Uses src/ directory for source code"):r==="__tests__"||r==="tests"?t.push("Has dedicated test directory"):r==="packages"?t.push("Monorepo with packages/ directory"):r==="docs"?t.push("Has documentation directory"):r==="lib"&&t.push("Uses lib/ directory for library code")}return Object.entries(e.languageDistribution).filter(([,o])=>o>5).length>1&&t.push("Multi-language project"),t}function bd(e,t){try{cn(e);let n=(0,Ed.join)(Qe(e),"patterns.json"),o=me(n,null),r=Vw(t),i=Yw(t),s;o?s={...o,tech_stack:Array.from(new Set([...o.tech_stack,...r])),conventions:Array.from(new Set([...o.conventions,...i])),learned_rules:o.learned_rules||[],common_mistakes:o.common_mistakes||[],last_updated:new Date().toISOString()}:s={project_hash:Cc(e),project_path:e,tech_stack:r,conventions:i,learned_rules:[],common_mistakes:[],last_updated:new Date().toISOString()},Ge(n,s)}catch(n){console.error("[Olympus Learning] Failed to write project patterns:",n)}}var Ed,Bw,qw,Cd=B(()=>{"use strict";Ed=require("path");fe();fe();Bw={".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"},qw={"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 Jw(e,t){let n=e.split(`
144
144
  `);return n.length<=t?e:n.slice(0,t).join(`
145
145
  `)+`
146
- ... (truncated)`}function Id(e,t){let n=[],o=" ".repeat(t*2);for(let r of e)n.push(`${o}${r.name}/ (${r.fileCount} files)`),r.children.length>0&&n.push(Id(r.children,t+1));return n.join(`
147
- `)}function Jw(e){try{return(0,Cd.readFileSync)(e,"utf8")}catch{return"(unable to read)"}}function zw(e,t){return ro.isAbsolute(e)?e:ro.resolve(t,e)}function bd(e){return e.replace(/\\/g,"/")}function Rd(e){let{projectPath:t,featureName:n,scanResult:o,keyFiles:r}=e,i=Id(o.directoryTree,0),s=Object.entries(o.languageDistribution).sort((d,f)=>f[1]-d[1]).map(([d,f])=>` ${d}: ${f} files`).join(`
148
- `),a=o.importGraph.slice(0,50).map(d=>` ${bd(d.sourceFile)} -> ${d.importedModule}`).join(`
146
+ ... (truncated)`}function Od(e,t){let n=[],o=" ".repeat(t*2);for(let r of e)n.push(`${o}${r.name}/ (${r.fileCount} files)`),r.children.length>0&&n.push(Od(r.children,t+1));return n.join(`
147
+ `)}function zw(e){try{return(0,Rd.readFileSync)(e,"utf8")}catch{return"(unable to read)"}}function Qw(e,t){return ro.isAbsolute(e)?e:ro.resolve(t,e)}function Id(e){return e.replace(/\\/g,"/")}function Ad(e){let{projectPath:t,featureName:n,scanResult:o,keyFiles:r}=e,i=Od(o.directoryTree,0),s=Object.entries(o.languageDistribution).sort((d,f)=>f[1]-d[1]).map(([d,f])=>` ${d}: ${f} files`).join(`
148
+ `),a=o.importGraph.slice(0,50).map(d=>` ${Id(d.sourceFile)} -> ${d.importedModule}`).join(`
149
149
  `),c=o.importGraph.length>50?`
150
- ... (${o.importGraph.length-50} more edges omitted)`:"",l=r.map(d=>{let f=zw(d,t),m=Jw(f),p=Kw(m,200);return`### ${bd(d)}
150
+ ... (${o.importGraph.length-50} more edges omitted)`:"",l=r.map(d=>{let f=Qw(d,t),m=zw(f),p=Jw(m,200);return`### ${Id(d)}
151
151
  \`\`\`
152
152
  ${p}
153
153
  \`\`\``}).join(`
@@ -175,9 +175,9 @@ ${l||"(no key files provided)"}
175
175
 
176
176
  Based on the above project structure and source files, produce a Static Code Model.
177
177
 
178
- ${Yw}
178
+ ${Kw}
179
179
 
180
- 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 ro,Cd,Yw,Od=B(()=>{"use strict";ro=b(require("path"),1),Cd=require("fs");J();Yw=`A Static Code Model must contain these markdown sections:
180
+ 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 ro,Rd,Kw,Pd=B(()=>{"use strict";ro=b(require("path"),1),Rd=require("fs");J();Kw=`A Static Code Model must contain these markdown sections:
181
181
  ## Modules
182
182
  | Name | Path | Responsibility | Public Interface |
183
183
  |------|------|----------------|------------------|
@@ -193,7 +193,7 @@ Be precise and concise. Each module row should capture the real public exports o
193
193
  (one row per data model)
194
194
 
195
195
  ## Configuration Summary
196
- (paragraph describing configuration approach)`});async function Ad(e){let t=0;try{let n=await so.readdir(e,{withFileTypes:!0});for(let o of n){if(o.name.startsWith(".")||Qw.has(o.name))continue;let r=io.join(e,o.name);if(o.isDirectory())t+=await Ad(r);else if(o.isFile()){let i=io.extname(o.name);nr.includes(i)&&t++}}}catch(n){console.error(`Error reading directory ${e}:`,n)}return t}async function Tn(e){let t=await Ad(e);return{isBrownfield:t>=3,sourceFileCount:t}}function Zw(e,t){return{"analysis-plan":`# Analysis Plan
196
+ (paragraph describing configuration approach)`});async function xd(e){let t=0;try{let n=await so.readdir(e,{withFileTypes:!0});for(let o of n){if(o.name.startsWith(".")||Xw.has(o.name))continue;let r=io.join(e,o.name);if(o.isDirectory())t+=await xd(r);else if(o.isFile()){let i=io.extname(o.name);or.includes(i)&&t++}}}catch(n){console.error(`Error reading directory ${e}:`,n)}return t}async function Tn(e){let t=await xd(e);return{isBrownfield:t>=3,sourceFileCount:t}}function eS(e,t){return{"analysis-plan":`# Analysis Plan
197
197
 
198
198
  ## Feature: ${t}
199
199
 
@@ -305,12 +305,12 @@ Be precise and concise. Each module row should capture the real public exports o
305
305
 
306
306
  ## Error Handling Patterns
307
307
  <!-- How errors propagate and are handled -->
308
- `,"workspace-scan":""}[e]}async function Pd(e){let{projectPath:t,workflowId:n,featureName:o,manifestPath:r}=e;try{await Wi(t,n);let i=new Date().toISOString();ut(r,"discovery","in_progress",i);let s=[];for(let d of Xw){if(d==="workspace-scan")continue;let f=Zw(d,o),m=Ot(t,n,d);await hn(t,n,d,f),s.push(m),Pe(r,{id:`DISCOVERY-${d}`,type:d,phase:"discovery",stage:"intent",path:m,validation_passed:null,write_complete:!0,checksum:null})}let{sourceFileCount:a,isBrownfield:c}=await Tn(t),l;if(c)try{let d=await kd(t);Td(t,d);let f=wd(d);if(e.includeFiles&&e.includeFiles.length>0){let w=new Set(f);for(let k of e.includeFiles)w.has(k)||f.push(k)}let m=_d(d,o),p=Ot(t,n,"workspace-scan");await hn(t,n,"workspace-scan",JSON.stringify(d,null,2)),s.push(p),Pe(r,{id:"DISCOVERY-workspace-scan",type:"workspace-scan",phase:"discovery",stage:"intent",path:p,validation_passed:null,write_complete:!0,checksum:null});let h=Rd({projectPath:t,workflowId:n,featureName:o,scanResult:d,keyFiles:f,relevantFiles:m,intentText:o}),y=io.join(t,"aidlc-docs",n,"discovery","static-model-prompt.md");await Wi(t,n),await so.writeFile(y,h,"utf-8"),l={scanResult:d,keyFiles:f,relevantFiles:m,staticModelPrompt:h}}catch(d){console.error("[Discovery] Brownfield scanning failed (non-blocking):",d)}ut(r,"discovery","blocked");let u=await I(t,n);return u&&(u.current_phase="discovery",u.phases.discovery.status="blocked",await $(t,u)),{completed:!1,gateRequired:!0,artifactsGenerated:s,sourceFileCount:a,brownfieldData:l}}catch(i){throw console.error("[Discovery] Error executing discovery phase:",i),new Error(`Discovery phase failed: ${i instanceof Error?i.message:String(i)}`)}}var io,so,nr,Qw,Xw,or=B(()=>{"use strict";io=b(require("path"),1),so=b(ue(),1);Hi();J();Ee();Sd();Ed();Od();nr=[".ts",".tsx",".js",".jsx",".py",".go",".rs",".java",".c",".cpp",".cs",".rb",".swift",".kt",".css",".scss",".html",".vue",".svelte"],Qw=new Set(["node_modules",".git","dist","build",".olympus","aidlc-docs",".next","__pycache__",".venv","vendor","target"]),Xw=["analysis-plan","current-state-analysis","regression-baseline","change-impact","static-model","dynamic-model","workspace-scan"]});function ie(e){let t={...e,id:(0,Nd.randomUUID)(),timestamp:new Date().toISOString(),verified:!1,verification_count:0,last_useful:new Date().toISOString()},n=t.scope==="global"?ae():Qe(t.project_path);cn(t.project_path);let o=(0,xt.join)(n,"discoveries.jsonl");return an(o),(0,$e.appendFileSync)(o,JSON.stringify(t)+`
309
- `,"utf-8"),t}function r_(e){let t=(0,xt.join)(ae(),"discoveries.jsonl"),n=Qe(e),o=(0,xt.join)(n,"discoveries.jsonl"),r=$d(t),i=$d(o),s=[...r,...i],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 s)a[l.category]++;let c=[...s].sort((l,u)=>u.verification_count-l.verification_count);return{project_discoveries:i,global_discoveries:r,total_discoveries:s.length,categories:a,most_useful:c.slice(0,5)}}function Dd(e,t){let n=(0,xt.join)(ae(),"discoveries.jsonl"),o=(0,xt.join)(t,".olympus","learning","discoveries.jsonl"),r=i=>{if(!(0,$e.existsSync)(i))return!1;let a=(0,$e.readFileSync)(i,"utf-8").trim().split(`
310
- `).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,xt.dirname)(i);(0,$e.existsSync)(u)||(0,$e.mkdirSync)(u,{recursive:!0}),(0,$e.writeFileSync)(i,l.join(`
308
+ `,"workspace-scan":""}[e]}async function $d(e){let{projectPath:t,workflowId:n,featureName:o,manifestPath:r}=e;try{await Hi(t,n);let i=new Date().toISOString();ut(r,"discovery","in_progress",i);let s=[];for(let d of Zw){if(d==="workspace-scan")continue;let f=eS(d,o),m=Ot(t,n,d);await hn(t,n,d,f),s.push(m),xe(r,{id:`DISCOVERY-${d}`,type:d,phase:"discovery",stage:"intent",path:m,validation_passed:null,write_complete:!0,checksum:null})}let{sourceFileCount:a,isBrownfield:c}=await Tn(t),l;if(c)try{let d=await Sd(t);bd(t,d);let f=_d(d);if(e.includeFiles&&e.includeFiles.length>0){let w=new Set(f);for(let k of e.includeFiles)w.has(k)||f.push(k)}let m=vd(d,o),p=Ot(t,n,"workspace-scan");await hn(t,n,"workspace-scan",JSON.stringify(d,null,2)),s.push(p),xe(r,{id:"DISCOVERY-workspace-scan",type:"workspace-scan",phase:"discovery",stage:"intent",path:p,validation_passed:null,write_complete:!0,checksum:null});let h=Ad({projectPath:t,workflowId:n,featureName:o,scanResult:d,keyFiles:f,relevantFiles:m,intentText:o}),y=io.join(t,"aidlc-docs",n,"discovery","static-model-prompt.md");await Hi(t,n),await so.writeFile(y,h,"utf-8"),l={scanResult:d,keyFiles:f,relevantFiles:m,staticModelPrompt:h}}catch(d){console.error("[Discovery] Brownfield scanning failed (non-blocking):",d)}ut(r,"discovery","blocked");let u=await C(t,n);return u&&(u.current_phase="discovery",u.phases.discovery.status="blocked",await $(t,u)),{completed:!1,gateRequired:!0,artifactsGenerated:s,sourceFileCount:a,brownfieldData:l}}catch(i){throw console.error("[Discovery] Error executing discovery phase:",i),new Error(`Discovery phase failed: ${i instanceof Error?i.message:String(i)}`)}}var io,so,or,Xw,Zw,rr=B(()=>{"use strict";io=b(require("path"),1),so=b(ue(),1);Gi();J();Ee();Td();Cd();Pd();or=[".ts",".tsx",".js",".jsx",".py",".go",".rs",".java",".c",".cpp",".cs",".rb",".swift",".kt",".css",".scss",".html",".vue",".svelte"],Xw=new Set(["node_modules",".git","dist","build",".olympus","aidlc-docs",".next","__pycache__",".venv","vendor","target"]),Zw=["analysis-plan","current-state-analysis","regression-baseline","change-impact","static-model","dynamic-model","workspace-scan"]});function ie(e){let t={...e,id:(0,jd.randomUUID)(),timestamp:new Date().toISOString(),verified:!1,verification_count:0,last_useful:new Date().toISOString()},n=t.scope==="global"?ae():Qe(t.project_path);cn(t.project_path);let o=(0,xt.join)(n,"discoveries.jsonl");return an(o),(0,Ne.appendFileSync)(o,JSON.stringify(t)+`
309
+ `,"utf-8"),t}function iS(e){let t=(0,xt.join)(ae(),"discoveries.jsonl"),n=Qe(e),o=(0,xt.join)(n,"discoveries.jsonl"),r=Dd(t),i=Dd(o),s=[...r,...i],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 s)a[l.category]++;let c=[...s].sort((l,u)=>u.verification_count-l.verification_count);return{project_discoveries:i,global_discoveries:r,total_discoveries:s.length,categories:a,most_useful:c.slice(0,5)}}function Md(e,t){let n=(0,xt.join)(ae(),"discoveries.jsonl"),o=(0,xt.join)(t,".olympus","learning","discoveries.jsonl"),r=i=>{if(!(0,Ne.existsSync)(i))return!1;let a=(0,Ne.readFileSync)(i,"utf-8").trim().split(`
310
+ `).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,xt.dirname)(i);(0,Ne.existsSync)(u)||(0,Ne.mkdirSync)(u,{recursive:!0}),(0,Ne.writeFileSync)(i,l.join(`
311
311
  `)+`
312
- `,"utf-8")}return c};r(o)||r(n)}function rr(e,t=10){let n=r_(e),o=[...n.project_discoveries,...n.global_discoveries],r=new Date,s=o.filter(a=>a.expires_at?new Date(a.expires_at)>r:!0).map(a=>{let c=(r.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 s.sort((a,c)=>c.score-a.score),s.slice(0,t).map(a=>a.discovery)}function $d(e){if(!(0,$e.existsSync)(e))return[];try{return(0,$e.readFileSync)(e,"utf-8").split(`
313
- `).filter(n=>n.trim()).map(n=>JSON.parse(n))}catch(t){return console.error(`[Olympus Learning] Failed to read discoveries: ${t}`),[]}}var xt,$e,Nd,pt=B(()=>{"use strict";xt=require("path"),$e=require("fs"),Nd=require("crypto");fe()});async function jd(e,t){let{isBrownfield:n}=await Tn(e);if(!n)return"greenfield";let o=t.toLowerCase();for(let{pathway:r,keywords:i}of i_)for(let s of i)if(o.includes(s))return r;return"brownfield-enhancement"}function s_(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 ir(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 a_(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 c_(e,t,n,o){return e==="construction"&&t==="unit-decomposition"&&o==="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 Md(e){let{pathwayType:t,depthAssessment:n,sourceFileCount:o}=e,{recommended_depth:r,total_score:i,risk_tier:s}=n,a=s_(t),c={discovery:{included:a.discovery,rationale:ir("discovery",t,a.discovery)},inception:{included:a.inception,rationale:ir("inception",t,a.inception)},construction:{included:a.construction,rationale:ir("construction",t,a.construction)},operations:{included:a.operations,rationale:ir("operations",t,a.operations)}},l=["discovery","inception","construction","operations"],u=[];for(let m of l)if(a[m])for(let p of a_(m,t)){let g=m==="construction"&&p==="unit-decomposition",h=m==="inception"&&p==="reverse-engineering",y=m==="inception"&&p==="user-stories",w=m==="inception"&&p==="application-design",k=m==="inception"&&p==="units-generation",A=!0;g&&r==="minimal"&&(A=!1),h&&t==="greenfield"&&(A=!1),(y||w)&&(t==="bugfix"||t==="optimization")&&(A=!1),k&&r==="minimal"&&(A=!1),u.push({phase:m,stage:p,included:A,rationale:c_(m,p,t,r)})}let d;if(t==="bugfix")d=1;else switch(r){case"minimal":d=1;break;case"standard":d=Math.min(10,Math.max(1,Math.ceil(o/50)));break;case"comprehensive":d=Math.min(20,Math.max(2,Math.ceil(o/25)));break}let f=i<=10?"LOW":i<=20?"MEDIUM":"HIGH";return{pathway:t,risk_assessment:f,risk_tier:s.tier,phases:c,stages:u,estimated_code_generations:d,estimated_depth:r,generated_at:new Date().toISOString(),approved_at:null,approved_by:null}}function l_(e,t){let o=["discovery","inception","construction","operations"].map(i=>{let{included:s,rationale:a}=t.phases[i];return`| ${i} | ${s?"yes":"no"} | ${a} |`}).join(`
312
+ `,"utf-8")}return c};r(o)||r(n)}function ir(e,t=10){let n=iS(e),o=[...n.project_discoveries,...n.global_discoveries],r=new Date,s=o.filter(a=>a.expires_at?new Date(a.expires_at)>r:!0).map(a=>{let c=(r.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 s.sort((a,c)=>c.score-a.score),s.slice(0,t).map(a=>a.discovery)}function Dd(e){if(!(0,Ne.existsSync)(e))return[];try{return(0,Ne.readFileSync)(e,"utf-8").split(`
313
+ `).filter(n=>n.trim()).map(n=>JSON.parse(n))}catch(t){return console.error(`[Olympus Learning] Failed to read discoveries: ${t}`),[]}}var xt,Ne,jd,pt=B(()=>{"use strict";xt=require("path"),Ne=require("fs"),jd=require("crypto");fe()});async function Ld(e,t){let{isBrownfield:n}=await Tn(e);if(!n)return"greenfield";let o=t.toLowerCase();for(let{pathway:r,keywords:i}of sS)for(let s of i)if(o.includes(s))return r;return"brownfield-enhancement"}function aS(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 sr(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 cS(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 lS(e,t,n,o){return e==="construction"&&t==="unit-decomposition"&&o==="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 Fd(e){let{pathwayType:t,depthAssessment:n,sourceFileCount:o}=e,{recommended_depth:r,total_score:i,risk_tier:s}=n,a=aS(t),c={discovery:{included:a.discovery,rationale:sr("discovery",t,a.discovery)},inception:{included:a.inception,rationale:sr("inception",t,a.inception)},construction:{included:a.construction,rationale:sr("construction",t,a.construction)},operations:{included:a.operations,rationale:sr("operations",t,a.operations)}},l=["discovery","inception","construction","operations"],u=[];for(let m of l)if(a[m])for(let p of cS(m,t)){let g=m==="construction"&&p==="unit-decomposition",h=m==="inception"&&p==="reverse-engineering",y=m==="inception"&&p==="user-stories",w=m==="inception"&&p==="application-design",k=m==="inception"&&p==="units-generation",A=!0;g&&r==="minimal"&&(A=!1),h&&t==="greenfield"&&(A=!1),(y||w)&&(t==="bugfix"||t==="optimization")&&(A=!1),k&&r==="minimal"&&(A=!1),u.push({phase:m,stage:p,included:A,rationale:lS(m,p,t,r)})}let d;if(t==="bugfix")d=1;else switch(r){case"minimal":d=1;break;case"standard":d=Math.min(10,Math.max(1,Math.ceil(o/50)));break;case"comprehensive":d=Math.min(20,Math.max(2,Math.ceil(o/25)));break}let f=i<=10?"LOW":i<=20?"MEDIUM":"HIGH";return{pathway:t,risk_assessment:f,risk_tier:s.tier,phases:c,stages:u,estimated_code_generations:d,estimated_depth:r,generated_at:new Date().toISOString(),approved_at:null,approved_by:null}}function uS(e,t){let o=["discovery","inception","construction","operations"].map(i=>{let{included:s,rationale:a}=t.phases[i];return`| ${i} | ${s?"yes":"no"} | ${a} |`}).join(`
314
314
  `),r=t.stages.map((i,s)=>`| ${s+1} | ${i.phase} | ${i.stage} | ${i.included?"yes":"no"} | ${i.rationale} |`).join(`
315
315
  `);return`# Workflow Routing: ${e}
316
316
 
@@ -333,18 +333,18 @@ ${o}
333
333
  | # | Phase | Stage | Included | Rationale |
334
334
  |---|-------|-------|----------|-----------|
335
335
  ${r}
336
- `}async function es(e,t,n){let o=Jt.join(e,"aidlc-docs",t,"inception","plans"),r=Jt.join(o,"workflow-routing.md"),i=Jt.posix.join("aidlc-docs",t,"inception","plans","workflow-routing.md");try{await sr.mkdir(o,{recursive:!0});let a=l_(t,n),c=p_(n),l=a+`
336
+ `}async function ts(e,t,n){let o=Jt.join(e,"aidlc-docs",t,"inception","plans"),r=Jt.join(o,"workflow-routing.md"),i=Jt.posix.join("aidlc-docs",t,"inception","plans","workflow-routing.md");try{await ar.mkdir(o,{recursive:!0});let a=uS(t,n),c=fS(n),l=a+`
337
337
  ## Execution Plan Visualization
338
338
 
339
339
  `+c+`
340
- `;await sr.writeFile(r,l,"utf-8")}catch(a){throw console.error("[WorkflowRouting] Failed to write artifact:",a),a}let s=Jt.join(e,"aidlc-docs",t,"manifest.json");return Pe(s,{id:`WORKFLOW-ROUTING-${t}`,type:"WORKFLOW_ROUTING",phase:"inception",stage:"intent",path:i,validation_passed:!0,write_complete:!0,checksum:null}),i}function u_(e){let t={},n=e.match(/## Phase Overview[\s\S]*?\n\|[-| ]+\|\n([\s\S]*?)(?=\n## |\n# |$)/);if(!n)return t;for(let o of n[1].trim().split(`
341
- `)){let r=o.split("|").map(i=>i.trim()).filter(Boolean);if(r.length>=3){let[i,s,...a]=r;t[i]={included:s.toLowerCase()==="yes",rationale:a.join(" | ")}}}return t}function d_(e){let t=[],n=e.match(/## Stage Details[\s\S]*?\n\|[-| ]+\|\n([\s\S]*?)(?=\n## |\n# |$)/);if(!n)return t;for(let o of n[1].trim().split(`
342
- `)){let r=o.split("|").map(i=>i.trim()).filter(Boolean);if(r.length>=5){let[i,s,a,c,...l]=r;t.push({phase:s,stage:a,included:c.toLowerCase()==="yes",rationale:l.join(" | ")})}}return t}function cr(e,t){let n=Jt.join(e,"aidlc-docs",t,"inception","plans","workflow-routing.md");if(!(0,ar.existsSync)(n))return null;let o;try{o=(0,ar.readFileSync)(n,"utf-8")}catch(r){return console.error("[WorkflowRouting] Failed to read artifact:",r),null}try{let r=o.match(/\*\*Pathway:\*\*\s*(.+)/),i=o.match(/\*\*Risk Assessment:\*\*\s*(.+)/),s=o.match(/\*\*Risk Tier:\*\*\s*(.+)/),a=o.match(/\*\*Estimated Code Generations:\*\*\s*(\d+)/),c=o.match(/\*\*Estimated Depth:\*\*\s*(.+)/),l=o.match(/\*\*Generated:\*\*\s*(.+)/),u=o.match(/\*\*Approved:\*\*\s*(.+)/);if(!r||!i||!s||!a||!c||!l)return console.error("[WorkflowRouting] Missing required header fields"),null;let d=u?u[1].trim():"Pending",f=u_(o);return{pathway:r[1].trim(),risk_assessment:i[1].trim(),risk_tier:parseInt(s[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:f.discovery??{included:!0,rationale:""},inception:f.inception??{included:!0,rationale:""},construction:f.construction??{included:!0,rationale:""},operations:f.operations??{included:!0,rationale:""}},stages:d_(o)}}catch(r){return console.error("[WorkflowRouting] Failed to parse artifact:",r),null}}function ts(e,t){return e.phases[t]?.included??!0}function Ld(e,t,n){return e.stages.find(r=>r.phase===t&&r.stage===n)?.included??!0}function p_(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 o of n){let r=e.phases[o],i=o.charAt(0).toUpperCase()+o.slice(1);if(r.included){t.push(` subgraph ${i}["${i} Phase"]`);let s=e.stages.filter(c=>c.phase===o);for(let c of s){let l=`${o}_${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=s.map(c=>`${o}_${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 s=`${o}_skip`;t.push(` ${s}["${i} (SKIPPED)"]`),t.push(` class ${s} skip`)}t.push("")}for(let o=0;o<n.length-1;o++){let r=n[o],i=n[o+1],s=e.stages.filter(f=>f.phase===r),a=e.stages.filter(f=>f.phase===i),c=e.phases[r].included,l=e.phases[i].included,u,d;c&&s.length>0?u=`${r}_${s[s.length-1].stage.replace(/-/g,"_")}`:u=`${r}_skip`,l&&a.length>0?d=`${i}_${a[0].stage.replace(/-/g,"_")}`:d=`${i}_skip`,!c||!l?t.push(` ${u} -.-> ${d}`):t.push(` ${u} --> ${d}`)}return t.push("```"),t.join(`
343
- `)}var Jt,sr,ar,i_,ns=B(()=>{"use strict";Jt=b(require("path"),1),sr=b(require("fs/promises"),1),ar=require("fs");or();J();i_=[{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"]}]});function R_(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function O_(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 A_(e){let{inception_stages:t,current_inception_stage:n}=e;if(!t)return[];let o=[];for(let r of I_){let i=t[r];if(!i)continue;let s=R_(r),a=n===r,c,l;i.status==="completed"?(c="[x]",l=i.completed_at?`(completed ${i.completed_at})`:"(completed)"):i.status==="skipped"?(c="[ ]",l=i.skip_reason?`(skipped -- ${i.skip_reason})`:"(skipped)"):(c="[ ]",l="");let u=` - ${c} ${s} ${l}`.trimEnd();a&&(u+=" <- CURRENT"),o.push(u)}return o}function P_(e){let t=["## Progress"];for(let n of C_){let o=e.phases[n],r,i;o?.completed_at?(r="[x]",i=`(completed ${o.completed_at})`):e.current_phase===n?(r="[ ]",i="(in progress)"):(r="[ ]",i="");let s=n.charAt(0).toUpperCase()+n.slice(1);if(t.push(`- ${r} ${s} ${i}`.trimEnd()),n==="inception"&&e.inception_stages){let a=A_(e);t.push(...a)}}return t.join(`
344
- `)}function x_(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(`
340
+ `;await ar.writeFile(r,l,"utf-8")}catch(a){throw console.error("[WorkflowRouting] Failed to write artifact:",a),a}let s=Jt.join(e,"aidlc-docs",t,"manifest.json");return xe(s,{id:`WORKFLOW-ROUTING-${t}`,type:"WORKFLOW_ROUTING",phase:"inception",stage:"intent",path:i,validation_passed:!0,write_complete:!0,checksum:null}),i}function dS(e){let t={},n=e.match(/## Phase Overview[\s\S]*?\n\|[-| ]+\|\n([\s\S]*?)(?=\n## |\n# |$)/);if(!n)return t;for(let o of n[1].trim().split(`
341
+ `)){let r=o.split("|").map(i=>i.trim()).filter(Boolean);if(r.length>=3){let[i,s,...a]=r;t[i]={included:s.toLowerCase()==="yes",rationale:a.join(" | ")}}}return t}function pS(e){let t=[],n=e.match(/## Stage Details[\s\S]*?\n\|[-| ]+\|\n([\s\S]*?)(?=\n## |\n# |$)/);if(!n)return t;for(let o of n[1].trim().split(`
342
+ `)){let r=o.split("|").map(i=>i.trim()).filter(Boolean);if(r.length>=5){let[i,s,a,c,...l]=r;t.push({phase:s,stage:a,included:c.toLowerCase()==="yes",rationale:l.join(" | ")})}}return t}function lr(e,t){let n=Jt.join(e,"aidlc-docs",t,"inception","plans","workflow-routing.md");if(!(0,cr.existsSync)(n))return null;let o;try{o=(0,cr.readFileSync)(n,"utf-8")}catch(r){return console.error("[WorkflowRouting] Failed to read artifact:",r),null}try{let r=o.match(/\*\*Pathway:\*\*\s*(.+)/),i=o.match(/\*\*Risk Assessment:\*\*\s*(.+)/),s=o.match(/\*\*Risk Tier:\*\*\s*(.+)/),a=o.match(/\*\*Estimated Code Generations:\*\*\s*(\d+)/),c=o.match(/\*\*Estimated Depth:\*\*\s*(.+)/),l=o.match(/\*\*Generated:\*\*\s*(.+)/),u=o.match(/\*\*Approved:\*\*\s*(.+)/);if(!r||!i||!s||!a||!c||!l)return console.error("[WorkflowRouting] Missing required header fields"),null;let d=u?u[1].trim():"Pending",f=dS(o);return{pathway:r[1].trim(),risk_assessment:i[1].trim(),risk_tier:parseInt(s[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:f.discovery??{included:!0,rationale:""},inception:f.inception??{included:!0,rationale:""},construction:f.construction??{included:!0,rationale:""},operations:f.operations??{included:!0,rationale:""}},stages:pS(o)}}catch(r){return console.error("[WorkflowRouting] Failed to parse artifact:",r),null}}function ns(e,t){return e.phases[t]?.included??!0}function Ud(e,t,n){return e.stages.find(r=>r.phase===t&&r.stage===n)?.included??!0}function fS(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 o of n){let r=e.phases[o],i=o.charAt(0).toUpperCase()+o.slice(1);if(r.included){t.push(` subgraph ${i}["${i} Phase"]`);let s=e.stages.filter(c=>c.phase===o);for(let c of s){let l=`${o}_${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=s.map(c=>`${o}_${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 s=`${o}_skip`;t.push(` ${s}["${i} (SKIPPED)"]`),t.push(` class ${s} skip`)}t.push("")}for(let o=0;o<n.length-1;o++){let r=n[o],i=n[o+1],s=e.stages.filter(f=>f.phase===r),a=e.stages.filter(f=>f.phase===i),c=e.phases[r].included,l=e.phases[i].included,u,d;c&&s.length>0?u=`${r}_${s[s.length-1].stage.replace(/-/g,"_")}`:u=`${r}_skip`,l&&a.length>0?d=`${i}_${a[0].stage.replace(/-/g,"_")}`:d=`${i}_skip`,!c||!l?t.push(` ${u} -.-> ${d}`):t.push(` ${u} --> ${d}`)}return t.push("```"),t.join(`
343
+ `)}var Jt,ar,cr,sS,os=B(()=>{"use strict";Jt=b(require("path"),1),ar=b(require("fs/promises"),1),cr=require("fs");rr();J();sS=[{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"]}]});function OS(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function AS(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 PS(e){let{inception_stages:t,current_inception_stage:n}=e;if(!t)return[];let o=[];for(let r of RS){let i=t[r];if(!i)continue;let s=OS(r),a=n===r,c,l;i.status==="completed"?(c="[x]",l=i.completed_at?`(completed ${i.completed_at})`:"(completed)"):i.status==="skipped"?(c="[ ]",l=i.skip_reason?`(skipped -- ${i.skip_reason})`:"(skipped)"):(c="[ ]",l="");let u=` - ${c} ${s} ${l}`.trimEnd();a&&(u+=" <- CURRENT"),o.push(u)}return o}function xS(e){let t=["## Progress"];for(let n of IS){let o=e.phases[n],r,i;o?.completed_at?(r="[x]",i=`(completed ${o.completed_at})`):e.current_phase===n?(r="[ ]",i="(in progress)"):(r="[ ]",i="");let s=n.charAt(0).toUpperCase()+n.slice(1);if(t.push(`- ${r} ${s} ${i}`.trimEnd()),n==="inception"&&e.inception_stages){let a=PS(e);t.push(...a)}}return t.join(`
344
+ `)}function $S(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(`
345
345
  `);t.push(""),t.push("| Unit | Status |"),t.push("|------|--------|");for(let[n,o]of Object.entries(e.construction_units))t.push(`| ${n} | ${o.code_generation_status} |`);return t.join(`
346
- `)}function $_(e,t){let n=["## Key Artifacts",""];n.push("| Artifact | Path | Status |"),n.push("|----------|------|--------|");let o=Cn.join(e,ao,t),r=[{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 i of r){let s=ft.existsSync(Cn.join(o,i.path));n.push(`| ${i.name} | ${i.path} | ${s?"created":"pending"} |`)}return n.join(`
347
- `)}function os(e,t,n){let o=Cn.join(e,ao,t,qd);try{let r=O_(n.feature_name),i=P_(n),s=x_(n),a=$_(e,t),c=`# ${r}
346
+ `)}function NS(e,t){let n=["## Key Artifacts",""];n.push("| Artifact | Path | Status |"),n.push("|----------|------|--------|");let o=Cn.join(e,ao,t),r=[{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 i of r){let s=ft.existsSync(Cn.join(o,i.path));n.push(`| ${i.name} | ${i.path} | ${s?"created":"pending"} |`)}return n.join(`
347
+ `)}function rs(e,t,n){let o=Cn.join(e,ao,t,Yd);try{let r=AS(n.feature_name),i=xS(n),s=$S(n),a=NS(e,t),c=`# ${r}
348
348
 
349
349
  | Field | Value |
350
350
  |-------|-------|
@@ -372,11 +372,11 @@ ${a}
372
372
 
373
373
  Application Code: ${e} (NEVER in aidlc-docs/)
374
374
  Documentation: ${ao}/${t}/
375
- `;ft.ensureDirSync(Cn.join(e,ao,t)),ft.writeFileSync(o,c,"utf-8")}catch(r){console.error(`[StateFile] Failed to generate state file for workflow ${t}:`,r.message)}return o}function dr(e,t,n,o){let r=Cn.join(e,ao,t,qd);try{let i=ft.readFileSync(r,"utf-8"),s=new RegExp(`^(- \\[[ x\\-]\\] ${n}.*)$`,"im"),a=i;o==="completed"?a=a.replace(s,(u,d)=>`${d.replace(/\[[ x\-]\]/,"[x]").replace(/\s*\(.*?\)\s*$/,"").replace(/\s*← CURRENT\s*$/,"")} (completed ${new Date().toISOString()})`):o==="in_progress"?a=a.replace(s,(u,d)=>`${d.replace(/\[[ x\-]\]/,"[ ]").replace(/\s*\(.*?\)\s*$/,"").replace(/\s*← CURRENT\s*$/,"")} \u2190 CURRENT`):o==="skipped"&&(a=a.replace(s,(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()}`),ft.writeFileSync(r,a,"utf-8")}catch(i){console.error(`[StateFile] Failed to update state file for workflow ${t}:`,i.message)}}var Cn,ft,ao,qd,C_,I_,rs=B(()=>{"use strict";Cn=b(require("path"),1),ft=b(ue(),1),ao="aidlc-docs",qd="aidlc-state.md",C_=["discovery","inception","construction","operations"],I_=["workspace-detection","reverse-engineering","requirements-analysis","user-stories","workflow-planning","application-design","units-generation"]});function Vd(){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 we(e){try{let t=e||process.cwd(),n=(0,pr.join)(t,Yd);if(!(0,mt.existsSync)(n))return Vd();let o=(0,mt.readFileSync)(n,"utf-8"),r=JSON.parse(o);return r.consecutive_rejections===void 0&&(r.consecutive_rejections=0),Array.isArray(r.transition_history)||(r.transition_history=[]),r}catch(t){return console.error("Error loading trust state:",t),Vd()}}function is(e,t){try{let n=t||process.cwd(),o=(0,pr.join)(n,".olympus"),r=(0,pr.join)(n,Yd);(0,mt.existsSync)(o)||(0,mt.mkdirSync)(o,{recursive:!0}),(0,mt.writeFileSync)(r,JSON.stringify(e,null,2),"utf-8")}catch(n){console.error("Error saving trust state:",n)}}function Kd(e,t){return t>=e}var mt,pr,Yd,$t=B(()=>{"use strict";mt=require("fs"),pr=require("path"),Yd=".olympus/trust-state.json"});function Jd(e,t){let n=t||"",o=n?(0,In.join)(e,"aidlc-docs",n,"manifest.json"):(0,In.join)(e,"aidlc-docs","manifest.json"),r=D(o),i=we(e),s={workflowId:"",featureName:"",gateRejections:[],cascadeEvents:[],trustDecreases:[],ciFailureCount:0,totalGates:0,totalRejections:0};if(!r)return s;let a=(r.gate_audit||[]).filter(p=>p.action==="rejected").map(p=>({phase:p.phase,timestamp:p.timestamp,reason:p.reason||null,actor:p.actor})),c=[];for(let p of r.artifacts||[])if(p.statusHistory)for(let g of p.statusHistory)(g.status.toLowerCase().includes("stale")||g.status.toLowerCase().includes("violated"))&&c.push({artifactId:p.id,status:g.status,timestamp:g.timestamp});let l=(i?.level_history||[]).filter(p=>p.to<p.from).map(p=>({from:p.from,to:p.to,reason:p.reason,timestamp:p.timestamp})),u=0,d=n?(0,In.join)(e,"aidlc-docs",n,"construction"):(0,In.join)(e,"aidlc-docs","construction");if((0,gt.existsSync)(d)){let p=(0,gt.readdirSync)(d,{withFileTypes:!0}).filter(g=>g.isDirectory()&&g.name.startsWith("UNIT-")).map(g=>g.name);for(let g of p){let h=(0,In.join)(d,g,"validation-report.md");if((0,gt.existsSync)(h)){let w=(0,gt.readFileSync)(h,"utf-8").split(`
376
- `);u+=w.filter(k=>k.toLowerCase().includes("fail")).length}}}let f=(r.gate_audit||[]).length,m=a.length;return{workflowId:r.workflow_id||"",featureName:r.feature_name||"",gateRejections:a,cascadeEvents:c,trustDecreases:l,ciFailureCount:u,totalGates:f,totalRejections:m}}function zd(e){let t=[],n=new Map;for(let o of e.gateRejections){let r=(o.reason||"unspecified").toLowerCase().trim();n.has(r)||n.set(r,[]),n.get(r).push(o)}for(let[o,r]of n.entries()){let i=r.length,s=i>=3?"High":i===2?"Medium":"Low",c=`Gate rejections in ${r.map(u=>u.phase).join(", ")} with reason: "${o}"`,l=i>1?`Review and address recurring gate rejection pattern: "${o}". Consider improving upstream validation or documentation.`:`Address gate rejection: "${o}". Ensure requirements are clear before implementation.`;t.push({description:`Gate rejection pattern: ${o}`,evidence:c,suggestion:l,confidence:s,occurrences:i})}if(e.trustDecreases.length>0){let o=e.trustDecreases.length,r=o>=3?"High":o===2?"Medium":"Low",i=e.trustDecreases.map(s=>`${s.from} \u2192 ${s.to} (${s.reason})`).join("; ");t.push({description:"Trust level decreases detected",evidence:`Trust trajectory: ${i}`,suggestion:"Improve code quality and validation processes to rebuild trust. Consider more thorough review before gate submissions.",confidence:r,occurrences:o})}if(e.cascadeEvents.length>0){let o=e.cascadeEvents.length,r=o>=3?"High":o===2?"Medium":"Low",i=[...new Set(e.cascadeEvents.map(s=>s.artifactId))].join(", ");t.push({description:"Cascade invalidation events",evidence:`${o} invalidation event(s) affecting: ${i}`,suggestion:"Strengthen contract verification and dependency validation to prevent cascading failures. Consider improving artifact stability.",confidence:r,occurrences:o})}return t}var gt,In,Qd=B(()=>{"use strict";gt=require("fs"),In=require("path");J();$t();pt()});function N_(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 D_(e){let t=e.artifacts||[],n=e.links||[];return t.filter(r=>r.stage==="intent").map(r=>{let i=n.filter(c=>c.source_id===r.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")),s=[];for(let c of i){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"));s.push(...l)}let a=[...new Set(s.flatMap(c=>{let l=t.find(d=>d.id===c);if(!l)return[];let u=ot.extname(l.path).toLowerCase();return u&&u!==".md"&&u!==".json"?[l.path]:[]}))];return{intentId:r.id,unitIds:i,codeGenerationIds:[...new Set(s)],codeFiles:a}})}function j_(e){return(e.level_history||[]).map(t=>({from:t.from,to:t.to,reason:t.reason,timestamp:t.timestamp}))}function M_(e){let t=[];for(let n of e.artifacts||[]){if(!n.statusHistory||n.statusHistory.length<2)continue;let o=n.statusHistory;for(let r=1;r<o.length;r++){let i=o[r-1],s=o[r],a=s.status.toLowerCase();(a.includes("stale")||a.includes("violated"))&&t.push({artifactId:n.id,previousStatus:i.status,newStatus:s.status,reason:n.stale_reason??`Artifact transitioned to ${s.status}`,timestamp:s.timestamp})}}return t.sort((n,o)=>n.timestamp.localeCompare(o.timestamp))}function Xd(e){return{workflowId:e,featureName:"",generatedAt:new Date().toISOString(),timeline:[],traceabilityMatrix:[],trustHistory:[],cascadeEvents:[],retroInsights:[]}}function Zd(e,t){try{let n=ot.join(e,"aidlc-docs",t,"manifest.json"),o=D(n);if(!o)return Xd(t);let r=we(e),i=Jd(e,t),a=zd(i).filter(c=>c.confidence==="High"||c.confidence==="Medium").map(c=>c.description);return{workflowId:o.workflow_id,featureName:o.feature_name,generatedAt:new Date().toISOString(),timeline:N_(o),traceabilityMatrix:D_(o),trustHistory:j_(r),cascadeEvents:M_(o),retroInsights:a}}catch(n){return console.error(`Failed to generate audit document for workflow ${t}:`,n),Xd(t)}}function ss(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 o=n.unitIds.length>0?n.unitIds.join(", "):"\u2014",r=n.codeGenerationIds.length>0?n.codeGenerationIds.join(", "):"\u2014",i=n.codeFiles.length>0?n.codeFiles.join(", "):"\u2014";t.push(`| ${n.intentId} | ${o} | ${r} | ${i} |`)}}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(`
377
- `)}async function ep(e,t,n){let o=ot.join(e,"aidlc-docs",t),r=ot.join(o,"audit.md"),i=ot.join(o,"manifest.json");try{let s=ss(n);await je.ensureDir(o),await je.writeFile(r,s,"utf-8"),Pe(i,{id:`audit-${t}`,type:"AUDIT",phase:"operations",stage:"complete",path:r,validation_passed:null,write_complete:!0,checksum:null})}catch(s){console.error(`Failed to write audit artifact for workflow ${t}:`,s)}return r}function tp(e,t,n){try{let o=ot.join(e,"aidlc-docs",t,"audit.md");if(!je.existsSync(o)){let i=["# Audit Report","",`Generated: ${new Date().toISOString()}`,`Workflow ID: ${t}`,"","## Timeline","","| Timestamp | Phase | Action | Actor | Reason |","|-----------|-------|--------|-------|--------|",""].join(`
375
+ `;ft.ensureDirSync(Cn.join(e,ao,t)),ft.writeFileSync(o,c,"utf-8")}catch(r){console.error(`[StateFile] Failed to generate state file for workflow ${t}:`,r.message)}return o}function pr(e,t,n,o){let r=Cn.join(e,ao,t,Yd);try{let i=ft.readFileSync(r,"utf-8"),s=new RegExp(`^(- \\[[ x\\-]\\] ${n}.*)$`,"im"),a=i;o==="completed"?a=a.replace(s,(u,d)=>`${d.replace(/\[[ x\-]\]/,"[x]").replace(/\s*\(.*?\)\s*$/,"").replace(/\s*← CURRENT\s*$/,"")} (completed ${new Date().toISOString()})`):o==="in_progress"?a=a.replace(s,(u,d)=>`${d.replace(/\[[ x\-]\]/,"[ ]").replace(/\s*\(.*?\)\s*$/,"").replace(/\s*← CURRENT\s*$/,"")} \u2190 CURRENT`):o==="skipped"&&(a=a.replace(s,(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()}`),ft.writeFileSync(r,a,"utf-8")}catch(i){console.error(`[StateFile] Failed to update state file for workflow ${t}:`,i.message)}}var Cn,ft,ao,Yd,IS,RS,is=B(()=>{"use strict";Cn=b(require("path"),1),ft=b(ue(),1),ao="aidlc-docs",Yd="aidlc-state.md",IS=["discovery","inception","construction","operations"],RS=["workspace-detection","reverse-engineering","requirements-analysis","user-stories","workflow-planning","application-design","units-generation"]});function Kd(){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 we(e){try{let t=e||process.cwd(),n=(0,fr.join)(t,Jd);if(!(0,mt.existsSync)(n))return Kd();let o=(0,mt.readFileSync)(n,"utf-8"),r=JSON.parse(o);return r.consecutive_rejections===void 0&&(r.consecutive_rejections=0),Array.isArray(r.transition_history)||(r.transition_history=[]),r}catch(t){return console.error("Error loading trust state:",t),Kd()}}function ss(e,t){try{let n=t||process.cwd(),o=(0,fr.join)(n,".olympus"),r=(0,fr.join)(n,Jd);(0,mt.existsSync)(o)||(0,mt.mkdirSync)(o,{recursive:!0}),(0,mt.writeFileSync)(r,JSON.stringify(e,null,2),"utf-8")}catch(n){console.error("Error saving trust state:",n)}}function DS(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 as(e,t,n,o){let r=e.total_transitions+1,i=n?e.rejection_count+1:e.rejection_count,s=i/r,a=n?e.consecutive_rejections+1:0,c={success:t,rejected:n,metadata:o,timestamp:new Date().toISOString()},l=[...e.transition_history,c].slice(-100),u={...e,total_transitions:r,rejection_count:i,rejection_rate:s,consecutive_rejections:a,transition_history:l},d=DS(u);if(d!==e.current_level){let f={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:f.timestamp,level_history:[...e.level_history,f]}}return u}function zd(e,t){return t>=e}var mt,fr,Jd,$t=B(()=>{"use strict";mt=require("fs"),fr=require("path"),Jd=".olympus/trust-state.json"});function Qd(e,t){let n=t||"",o=n?(0,In.join)(e,"aidlc-docs",n,"manifest.json"):(0,In.join)(e,"aidlc-docs","manifest.json"),r=D(o),i=we(e),s={workflowId:"",featureName:"",gateRejections:[],cascadeEvents:[],trustDecreases:[],ciFailureCount:0,totalGates:0,totalRejections:0};if(!r)return s;let a=(r.gate_audit||[]).filter(p=>p.action==="rejected").map(p=>({phase:p.phase,timestamp:p.timestamp,reason:p.reason||null,actor:p.actor})),c=[];for(let p of r.artifacts||[])if(p.statusHistory)for(let g of p.statusHistory)(g.status.toLowerCase().includes("stale")||g.status.toLowerCase().includes("violated"))&&c.push({artifactId:p.id,status:g.status,timestamp:g.timestamp});let l=(i?.level_history||[]).filter(p=>p.to<p.from).map(p=>({from:p.from,to:p.to,reason:p.reason,timestamp:p.timestamp})),u=0,d=n?(0,In.join)(e,"aidlc-docs",n,"construction"):(0,In.join)(e,"aidlc-docs","construction");if((0,gt.existsSync)(d)){let p=(0,gt.readdirSync)(d,{withFileTypes:!0}).filter(g=>g.isDirectory()&&g.name.startsWith("UNIT-")).map(g=>g.name);for(let g of p){let h=(0,In.join)(d,g,"validation-report.md");if((0,gt.existsSync)(h)){let w=(0,gt.readFileSync)(h,"utf-8").split(`
376
+ `);u+=w.filter(k=>k.toLowerCase().includes("fail")).length}}}let f=(r.gate_audit||[]).length,m=a.length;return{workflowId:r.workflow_id||"",featureName:r.feature_name||"",gateRejections:a,cascadeEvents:c,trustDecreases:l,ciFailureCount:u,totalGates:f,totalRejections:m}}function Xd(e){let t=[],n=new Map;for(let o of e.gateRejections){let r=(o.reason||"unspecified").toLowerCase().trim();n.has(r)||n.set(r,[]),n.get(r).push(o)}for(let[o,r]of n.entries()){let i=r.length,s=i>=3?"High":i===2?"Medium":"Low",c=`Gate rejections in ${r.map(u=>u.phase).join(", ")} with reason: "${o}"`,l=i>1?`Review and address recurring gate rejection pattern: "${o}". Consider improving upstream validation or documentation.`:`Address gate rejection: "${o}". Ensure requirements are clear before implementation.`;t.push({description:`Gate rejection pattern: ${o}`,evidence:c,suggestion:l,confidence:s,occurrences:i})}if(e.trustDecreases.length>0){let o=e.trustDecreases.length,r=o>=3?"High":o===2?"Medium":"Low",i=e.trustDecreases.map(s=>`${s.from} \u2192 ${s.to} (${s.reason})`).join("; ");t.push({description:"Trust level decreases detected",evidence:`Trust trajectory: ${i}`,suggestion:"Improve code quality and validation processes to rebuild trust. Consider more thorough review before gate submissions.",confidence:r,occurrences:o})}if(e.cascadeEvents.length>0){let o=e.cascadeEvents.length,r=o>=3?"High":o===2?"Medium":"Low",i=[...new Set(e.cascadeEvents.map(s=>s.artifactId))].join(", ");t.push({description:"Cascade invalidation events",evidence:`${o} invalidation event(s) affecting: ${i}`,suggestion:"Strengthen contract verification and dependency validation to prevent cascading failures. Consider improving artifact stability.",confidence:r,occurrences:o})}return t}var gt,In,Zd=B(()=>{"use strict";gt=require("fs"),In=require("path");J();$t();pt()});function jS(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 MS(e){let t=e.artifacts||[],n=e.links||[];return t.filter(r=>r.stage==="intent").map(r=>{let i=n.filter(c=>c.source_id===r.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")),s=[];for(let c of i){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"));s.push(...l)}let a=[...new Set(s.flatMap(c=>{let l=t.find(d=>d.id===c);if(!l)return[];let u=ot.extname(l.path).toLowerCase();return u&&u!==".md"&&u!==".json"?[l.path]:[]}))];return{intentId:r.id,unitIds:i,codeGenerationIds:[...new Set(s)],codeFiles:a}})}function LS(e){return(e.level_history||[]).map(t=>({from:t.from,to:t.to,reason:t.reason,timestamp:t.timestamp}))}function FS(e){let t=[];for(let n of e.artifacts||[]){if(!n.statusHistory||n.statusHistory.length<2)continue;let o=n.statusHistory;for(let r=1;r<o.length;r++){let i=o[r-1],s=o[r],a=s.status.toLowerCase();(a.includes("stale")||a.includes("violated"))&&t.push({artifactId:n.id,previousStatus:i.status,newStatus:s.status,reason:n.stale_reason??`Artifact transitioned to ${s.status}`,timestamp:s.timestamp})}}return t.sort((n,o)=>n.timestamp.localeCompare(o.timestamp))}function ep(e){return{workflowId:e,featureName:"",generatedAt:new Date().toISOString(),timeline:[],traceabilityMatrix:[],trustHistory:[],cascadeEvents:[],retroInsights:[]}}function tp(e,t){try{let n=ot.join(e,"aidlc-docs",t,"manifest.json"),o=D(n);if(!o)return ep(t);let r=we(e),i=Qd(e,t),a=Xd(i).filter(c=>c.confidence==="High"||c.confidence==="Medium").map(c=>c.description);return{workflowId:o.workflow_id,featureName:o.feature_name,generatedAt:new Date().toISOString(),timeline:jS(o),traceabilityMatrix:MS(o),trustHistory:LS(r),cascadeEvents:FS(o),retroInsights:a}}catch(n){return console.error(`Failed to generate audit document for workflow ${t}:`,n),ep(t)}}function cs(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 o=n.unitIds.length>0?n.unitIds.join(", "):"\u2014",r=n.codeGenerationIds.length>0?n.codeGenerationIds.join(", "):"\u2014",i=n.codeFiles.length>0?n.codeFiles.join(", "):"\u2014";t.push(`| ${n.intentId} | ${o} | ${r} | ${i} |`)}}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(`
377
+ `)}async function np(e,t,n){let o=ot.join(e,"aidlc-docs",t),r=ot.join(o,"audit.md"),i=ot.join(o,"manifest.json");try{let s=cs(n);await je.ensureDir(o),await je.writeFile(r,s,"utf-8"),xe(i,{id:`audit-${t}`,type:"AUDIT",phase:"operations",stage:"complete",path:r,validation_passed:null,write_complete:!0,checksum:null})}catch(s){console.error(`Failed to write audit artifact for workflow ${t}:`,s)}return r}function op(e,t,n){try{let o=ot.join(e,"aidlc-docs",t,"audit.md");if(!je.existsSync(o)){let i=["# Audit Report","",`Generated: ${new Date().toISOString()}`,`Workflow ID: ${t}`,"","## Timeline","","| Timestamp | Phase | Action | Actor | Reason |","|-----------|-------|--------|-------|--------|",""].join(`
378
378
  `);je.ensureDirSync(ot.dirname(o)),je.writeFileSync(o,i,"utf-8")}let r=`| ${n.timestamp} | ${n.phase} | ${n.action} | ${n.actor} | ${n.reason??"\u2014"} |
379
- `;je.appendFileSync(o,r,"utf-8")}catch(o){console.error(`Failed to append to audit for workflow ${t}:`,o)}}var je,ot,np=B(()=>{"use strict";je=b(ue(),1),ot=b(require("path"),1);J();$t();Qd()});var cp={};st(cp,{InceptionOrchestrator:()=>us,registerStageHandler:()=>L_});function L_(e,t){ls[e]=t}function op(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 as(e,t,n){return n&&!Ld(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 rp(e){for(let t of rt){let n=e[t];if(n&&(n.status==="not_started"||n.status==="in_progress"))return t}return null}function F_(e,t){let n=rt.indexOf(e);for(let o=n+1;o<rt.length;o++){let r=rt[o],i=t[r];if(i&&(i.status==="not_started"||i.status==="in_progress"))return r}}async function U_(e,t,n){if(!n.trust_state_path)return 0;try{let o=(0,ap.join)(e,"aidlc-docs",t,n.trust_state_path),r=await sp.readFile(o,"utf-8");return JSON.parse(r).current_level??0}catch{return 0}}function W_(e,t,n){let o=e==="workspace-detection",r=t.status==="awaiting_answers";return!(n>=3||n>=2&&!r||n>=1&&o&&!r)}function ip(e){return rt.every(t=>{let n=e[t];return n&&(n.status==="completed"||n.status==="skipped")})}function H_(e){let t=e.phases?.discovery;if(!t)return!1;let n=t.status;return n==="complete"||n==="completed"}function cs(e,t=null){let n=t!==null,o=new Date().toISOString();return{stage:e,status:n?"skipped":"completed",started_at:n?null:o,completed_at:o,skip_reason:t,artifacts_generated:[],questions_file:null,answers_received:!1}}var sp,ap,ls,rt,us,lp=B(()=>{"use strict";sp=b(ue(),1),ap=require("path");Ee();rs();np();ns();ls={};rt=["workspace-detection","reverse-engineering","requirements-analysis","user-stories","workflow-planning","application-design","units-generation"];us=class{async migrateCheckpoint(t,n){let o=await I(t,n);if(!o)throw new Error(`[InceptionOrchestrator] Checkpoint not found for workflow ${n}`);if(o.inception_stages)return{migrated:!1,case:"no_migration_needed"};let r=o.pathway_type??"brownfield-enhancement";if(o.current_stage!=="intent"){let a={};for(let c of rt){let{skipReason:l}=as(c,r,null);a[c]=cs(c,l)}return o.inception_stages=a,o.current_inception_stage=void 0,await $(t,o),It(t,n),{migrated:!0,case:"already_past_inception"}}let i={};for(let a of rt){let{status:c,skipReason:l}=as(a,r,null);i[a]=op(a,c,l)}i["workspace-detection"].status!=="skipped"&&(i["workspace-detection"]=cs("workspace-detection")),i["reverse-engineering"].status!=="skipped"&&H_(o)&&(i["reverse-engineering"]=cs("reverse-engineering")),o.inception_stages=i;let s=rp(i);return o.current_inception_stage=s??void 0,await $(t,o),It(t,n),{migrated:!0,case:"paused_at_intent"}}async initialize(t,n,o,r){let i=await I(t,n);if(!i)throw new Error(`[InceptionOrchestrator] Checkpoint not found for workflow ${n}`);if(i.inception_stages)return;let s={},a;for(let c of rt){let{status:l,skipReason:u}=as(c,o,r);s[c]=op(c,l,u),!a&&l==="not_started"&&(a=c)}i.inception_stages=s,i.current_inception_stage=a??void 0,await $(t,i),It(t,n)}async executeNextStage(t,n){let o=await I(t,n);if(!o)throw new Error(`[InceptionOrchestrator] Checkpoint not found for workflow ${n}`);let r=o.inception_stages;if(!r)throw new Error(`[InceptionOrchestrator] inception_stages not initialized for workflow ${n}. Call initialize() first.`);let i=rp(r);if(!i)return{stage:"units-generation",status:"completed",requires_approval:!1,artifacts_generated:[],whats_next:"Inception is complete. Proceed to construction phase."};r[i].status="in_progress",r[i].started_at=new Date().toISOString(),o.current_inception_stage=i,await $(t,o),It(t,n);let s=ls[i],a;if(s)try{a=await s(t,n,o)}catch(c){let l=c;console.error(`[InceptionOrchestrator] Stage '${i}' handler threw:`,l.message);let u=await I(t,n);return u?.inception_stages&&(u.inception_stages[i].status="not_started",u.inception_stages[i].started_at=null,await $(t,u),It(t,n)),{stage:i,status:"review_required",requires_approval:!0,artifacts_generated:[],review_summary:`Stage '${i}' failed with error: ${l.message}`}}else a={stage:i,status:"completed",requires_approval:!0,artifacts_generated:[],review_summary:`Stage '${i}' has no handler registered yet.`,whats_next:"This stage will be implemented in a future TODO."};return await this._postStage(t,n,i,a),a}async processAnswers(t,n,o){let r=await I(t,n);if(!r)throw new Error(`[InceptionOrchestrator] Checkpoint not found for workflow ${n}`);let i=r.inception_stages;if(!i)throw new Error(`[InceptionOrchestrator] inception_stages not initialized for workflow ${n}`);let s=i[o];if(!s||s.status!=="in_progress")throw new Error(`[InceptionOrchestrator] Stage '${o}' is not in_progress (status: ${s?.status??"unknown"})`);let a=ls[o],c;if(a)try{c=await a(t,n,r)}catch(l){let u=l;return console.error(`[InceptionOrchestrator] processAnswers for '${o}' threw:`,u.message),{stage:o,status:"review_required",requires_approval:!0,artifacts_generated:[],review_summary:`Stage '${o}' answer processing failed: ${u.message}`}}else c={stage:o,status:"completed",requires_approval:!0,artifacts_generated:[],review_summary:`Stage '${o}' has no handler registered yet.`,whats_next:"This stage will be implemented in a future TODO."};return await this._postStage(t,n,o,c),c}async getProgress(t,n){let o=await I(t,n);if(!o)throw new Error(`[InceptionOrchestrator] Checkpoint not found for workflow ${n}`);let r=o.inception_stages??{},i=rt.length,s=0,a=0;for(let c of rt){let l=r[c];l&&(l.status==="completed"&&s++,l.status==="skipped"&&a++)}return{total_stages:i,completed_stages:s,skipped_stages:a,current_stage:o.current_inception_stage??null,stages:r}}async isComplete(t,n){let o=await I(t,n);return o?.inception_stages?ip(o.inception_stages):!1}async _postStage(t,n,o,r){let i=await I(t,n);if(!i?.inception_stages)return;let s=i.inception_stages,a=new Date().toISOString();r.status==="completed"?(s[o].status="completed",s[o].completed_at=a,s[o].artifacts_generated=r.artifacts_generated):r.status==="awaiting_answers"?(s[o].status="in_progress",s[o].questions_file=r.questions_file??null):r.status==="skipped"&&(s[o].status="skipped",s[o].completed_at=a),(r.status==="completed"||r.status==="skipped")&&(i.current_inception_stage=F_(o,s)),await $(t,i),It(t,n);try{r.status==="completed"?dr(t,n,o,"completed"):r.status==="awaiting_answers"?dr(t,n,o,"in_progress"):r.status==="skipped"&&dr(t,n,o,"skipped")}catch(u){console.error(`[InceptionOrchestrator] Failed to update state file for stage ${o}:`,u.message)}try{let u={timestamp:a,phase:"inception",action:`Stage '${o}' ${r.status}`,actor:"ai",reason:r.review_summary??null};tp(t,n,u)}catch(u){console.error(`[InceptionOrchestrator] Failed to append to audit for stage ${o}:`,u.message)}if(ip(s))try{let u=Zd(t,n);ss(u),await ep(t,n,u)}catch(u){console.error("[InceptionOrchestrator] Failed to generate final audit document:",u.message)}try{let u=await U_(t,n,i);r.requires_approval=W_(o,r,u)}catch(u){console.error("[InceptionOrchestrator] Failed to compute trust level:",u.message),r.requires_approval=!0}let l=await I(t,n);l?.current_inception_stage&&(r.next_stage=l.current_inception_stage)}}});var gp={};st(gp,{generateCostAnalysis:()=>mp,generateDeployGuide:()=>up,generateMonitoringConfig:()=>pp,generateOperationsArtifacts:()=>G_,generateReleaseNotes:()=>fp,generateRunbook:()=>dp});function up(e){let{featureName:t,workflowId:n,manifest:o}=e,r=new Date().toISOString(),i=o?.artifacts?.length??0,s=o?.artifacts?.filter(c=>c.phase==="inception").length??0,a=o?.artifacts?.filter(c=>c.phase==="construction").length??0;return`---
379
+ `;je.appendFileSync(o,r,"utf-8")}catch(o){console.error(`Failed to append to audit for workflow ${t}:`,o)}}var je,ot,rp=B(()=>{"use strict";je=b(ue(),1),ot=b(require("path"),1);J();$t();Zd()});var up={};st(up,{InceptionOrchestrator:()=>ps,registerStageHandler:()=>US});function US(e,t){ds[e]=t}function ip(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 ls(e,t,n){return n&&!Ud(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 sp(e){for(let t of rt){let n=e[t];if(n&&(n.status==="not_started"||n.status==="in_progress"))return t}return null}function WS(e,t){let n=rt.indexOf(e);for(let o=n+1;o<rt.length;o++){let r=rt[o],i=t[r];if(i&&(i.status==="not_started"||i.status==="in_progress"))return r}}async function HS(e,t,n){if(!n.trust_state_path)return 0;try{let o=(0,lp.join)(e,"aidlc-docs",t,n.trust_state_path),r=await cp.readFile(o,"utf-8");return JSON.parse(r).current_level??0}catch{return 0}}function GS(e,t,n){let o=e==="workspace-detection",r=t.status==="awaiting_answers";return!(n>=3||n>=2&&!r||n>=1&&o&&!r)}function ap(e){return rt.every(t=>{let n=e[t];return n&&(n.status==="completed"||n.status==="skipped")})}function BS(e){let t=e.phases?.discovery;if(!t)return!1;let n=t.status;return n==="complete"||n==="completed"}function us(e,t=null){let n=t!==null,o=new Date().toISOString();return{stage:e,status:n?"skipped":"completed",started_at:n?null:o,completed_at:o,skip_reason:t,artifacts_generated:[],questions_file:null,answers_received:!1}}var cp,lp,ds,rt,ps,dp=B(()=>{"use strict";cp=b(ue(),1),lp=require("path");Ee();is();rp();os();ds={};rt=["workspace-detection","reverse-engineering","requirements-analysis","user-stories","workflow-planning","application-design","units-generation"];ps=class{async migrateCheckpoint(t,n){let o=await C(t,n);if(!o)throw new Error(`[InceptionOrchestrator] Checkpoint not found for workflow ${n}`);if(o.inception_stages)return{migrated:!1,case:"no_migration_needed"};let r=o.pathway_type??"brownfield-enhancement";if(o.current_stage!=="intent"){let a={};for(let c of rt){let{skipReason:l}=ls(c,r,null);a[c]=us(c,l)}return o.inception_stages=a,o.current_inception_stage=void 0,await $(t,o),It(t,n),{migrated:!0,case:"already_past_inception"}}let i={};for(let a of rt){let{status:c,skipReason:l}=ls(a,r,null);i[a]=ip(a,c,l)}i["workspace-detection"].status!=="skipped"&&(i["workspace-detection"]=us("workspace-detection")),i["reverse-engineering"].status!=="skipped"&&BS(o)&&(i["reverse-engineering"]=us("reverse-engineering")),o.inception_stages=i;let s=sp(i);return o.current_inception_stage=s??void 0,await $(t,o),It(t,n),{migrated:!0,case:"paused_at_intent"}}async initialize(t,n,o,r){let i=await C(t,n);if(!i)throw new Error(`[InceptionOrchestrator] Checkpoint not found for workflow ${n}`);if(i.inception_stages)return;let s={},a;for(let c of rt){let{status:l,skipReason:u}=ls(c,o,r);s[c]=ip(c,l,u),!a&&l==="not_started"&&(a=c)}i.inception_stages=s,i.current_inception_stage=a??void 0,await $(t,i),It(t,n)}async executeNextStage(t,n){let o=await C(t,n);if(!o)throw new Error(`[InceptionOrchestrator] Checkpoint not found for workflow ${n}`);let r=o.inception_stages;if(!r)throw new Error(`[InceptionOrchestrator] inception_stages not initialized for workflow ${n}. Call initialize() first.`);let i=sp(r);if(!i)return{stage:"units-generation",status:"completed",requires_approval:!1,artifacts_generated:[],whats_next:"Inception is complete. Proceed to construction phase."};r[i].status="in_progress",r[i].started_at=new Date().toISOString(),o.current_inception_stage=i,await $(t,o),It(t,n);let s=ds[i],a;if(s)try{a=await s(t,n,o)}catch(c){let l=c;console.error(`[InceptionOrchestrator] Stage '${i}' handler threw:`,l.message);let u=await C(t,n);return u?.inception_stages&&(u.inception_stages[i].status="not_started",u.inception_stages[i].started_at=null,await $(t,u),It(t,n)),{stage:i,status:"review_required",requires_approval:!0,artifacts_generated:[],review_summary:`Stage '${i}' failed with error: ${l.message}`}}else a={stage:i,status:"completed",requires_approval:!0,artifacts_generated:[],review_summary:`Stage '${i}' has no handler registered yet.`,whats_next:"This stage will be implemented in a future TODO."};return await this._postStage(t,n,i,a),a}async processAnswers(t,n,o){let r=await C(t,n);if(!r)throw new Error(`[InceptionOrchestrator] Checkpoint not found for workflow ${n}`);let i=r.inception_stages;if(!i)throw new Error(`[InceptionOrchestrator] inception_stages not initialized for workflow ${n}`);let s=i[o];if(!s||s.status!=="in_progress")throw new Error(`[InceptionOrchestrator] Stage '${o}' is not in_progress (status: ${s?.status??"unknown"})`);let a=ds[o],c;if(a)try{c=await a(t,n,r)}catch(l){let u=l;return console.error(`[InceptionOrchestrator] processAnswers for '${o}' threw:`,u.message),{stage:o,status:"review_required",requires_approval:!0,artifacts_generated:[],review_summary:`Stage '${o}' answer processing failed: ${u.message}`}}else c={stage:o,status:"completed",requires_approval:!0,artifacts_generated:[],review_summary:`Stage '${o}' has no handler registered yet.`,whats_next:"This stage will be implemented in a future TODO."};return await this._postStage(t,n,o,c),c}async getProgress(t,n){let o=await C(t,n);if(!o)throw new Error(`[InceptionOrchestrator] Checkpoint not found for workflow ${n}`);let r=o.inception_stages??{},i=rt.length,s=0,a=0;for(let c of rt){let l=r[c];l&&(l.status==="completed"&&s++,l.status==="skipped"&&a++)}return{total_stages:i,completed_stages:s,skipped_stages:a,current_stage:o.current_inception_stage??null,stages:r}}async isComplete(t,n){let o=await C(t,n);return o?.inception_stages?ap(o.inception_stages):!1}async _postStage(t,n,o,r){let i=await C(t,n);if(!i?.inception_stages)return;let s=i.inception_stages,a=new Date().toISOString();r.status==="completed"?(s[o].status="completed",s[o].completed_at=a,s[o].artifacts_generated=r.artifacts_generated):r.status==="awaiting_answers"?(s[o].status="in_progress",s[o].questions_file=r.questions_file??null):r.status==="skipped"&&(s[o].status="skipped",s[o].completed_at=a),(r.status==="completed"||r.status==="skipped")&&(i.current_inception_stage=WS(o,s)),await $(t,i),It(t,n);try{r.status==="completed"?pr(t,n,o,"completed"):r.status==="awaiting_answers"?pr(t,n,o,"in_progress"):r.status==="skipped"&&pr(t,n,o,"skipped")}catch(u){console.error(`[InceptionOrchestrator] Failed to update state file for stage ${o}:`,u.message)}try{let u={timestamp:a,phase:"inception",action:`Stage '${o}' ${r.status}`,actor:"ai",reason:r.review_summary??null};op(t,n,u)}catch(u){console.error(`[InceptionOrchestrator] Failed to append to audit for stage ${o}:`,u.message)}if(ap(s))try{let u=tp(t,n);cs(u),await np(t,n,u)}catch(u){console.error("[InceptionOrchestrator] Failed to generate final audit document:",u.message)}try{let u=await HS(t,n,i);r.requires_approval=GS(o,r,u)}catch(u){console.error("[InceptionOrchestrator] Failed to compute trust level:",u.message),r.requires_approval=!0}let l=await C(t,n);l?.current_inception_stage&&(r.next_stage=l.current_inception_stage)}}});var yp={};st(yp,{generateCostAnalysis:()=>hp,generateDeployGuide:()=>pp,generateMonitoringConfig:()=>mp,generateOperationsArtifacts:()=>qS,generateReleaseNotes:()=>gp,generateRunbook:()=>fp});function pp(e){let{featureName:t,workflowId:n,manifest:o}=e,r=new Date().toISOString(),i=o?.artifacts?.length??0,s=o?.artifacts?.filter(c=>c.phase==="inception").length??0,a=o?.artifacts?.filter(c=>c.phase==="construction").length??0;return`---
380
380
  id: DEPLOY-GUIDE-001
381
381
  feature: ${n}
382
382
  created: ${r}
@@ -442,7 +442,7 @@ Generated from ${i} artifacts (${s} Inception, ${a} Construction).
442
442
 
443
443
  ---
444
444
  *Generated by Operations Phase Templates*
445
- `}function dp(e){let{featureName:t,workflowId:n}=e,o=new Date().toISOString();return`---
445
+ `}function fp(e){let{featureName:t,workflowId:n}=e,o=new Date().toISOString();return`---
446
446
  id: RUNBOOK-001
447
447
  feature: ${n}
448
448
  created: ${o}
@@ -526,7 +526,7 @@ grep -i error /var/log/service/${n}.log | tail -20
526
526
 
527
527
  ---
528
528
  *Generated by Operations Phase Templates*
529
- `}function pp(e){let{featureName:t,workflowId:n,manifest:o}=e,r=new Date().toISOString(),i=o?.risk_tier?.tier??2,s=i===3?.5:i===2?1:2,a=i===3?500:i===2?1e3:2e3,l={id:"MONITORING-001",feature:n,feature_name:t,created:r,phase:"operations",stage:"monitor",risk_tier:i,health_checks:{endpoint:"/health",interval_seconds:i===3?30:i===2?60:120,timeout_seconds:5,unhealthy_threshold:3},alerts:[{name:`${n}-error-rate`,metric:"error_rate_percent",threshold:s,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:i===3?"debug":"info",retention_days:i===3?90:i===2?60:30,structured:!0}};return JSON.stringify(l,null,2)}function fp(e){let{featureName:t,workflowId:n,manifest:o}=e,r=new Date().toISOString(),i=o?.artifacts??[],s=i.filter(p=>p.phase==="inception"),a=i.filter(p=>p.phase==="construction"),c=o?.risks??[],l=c.filter(p=>p.status==="open"),u=c.filter(p=>p.status==="mitigated"),f=(o?.gate_audit??[]).filter(p=>p.action==="approved"),m=i.map(p=>`- **${p.id}** (${p.phase}/${p.stage}): ${p.contract_status}`).join(`
529
+ `}function mp(e){let{featureName:t,workflowId:n,manifest:o}=e,r=new Date().toISOString(),i=o?.risk_tier?.tier??2,s=i===3?.5:i===2?1:2,a=i===3?500:i===2?1e3:2e3,l={id:"MONITORING-001",feature:n,feature_name:t,created:r,phase:"operations",stage:"monitor",risk_tier:i,health_checks:{endpoint:"/health",interval_seconds:i===3?30:i===2?60:120,timeout_seconds:5,unhealthy_threshold:3},alerts:[{name:`${n}-error-rate`,metric:"error_rate_percent",threshold:s,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:i===3?"debug":"info",retention_days:i===3?90:i===2?60:30,structured:!0}};return JSON.stringify(l,null,2)}function gp(e){let{featureName:t,workflowId:n,manifest:o}=e,r=new Date().toISOString(),i=o?.artifacts??[],s=i.filter(p=>p.phase==="inception"),a=i.filter(p=>p.phase==="construction"),c=o?.risks??[],l=c.filter(p=>p.status==="open"),u=c.filter(p=>p.status==="mitigated"),f=(o?.gate_audit??[]).filter(p=>p.action==="approved"),m=i.map(p=>`- **${p.id}** (${p.phase}/${p.stage}): ${p.contract_status}`).join(`
530
530
  `);return`---
531
531
  id: RELEASE-NOTES-001
532
532
  feature: ${n}
@@ -592,7 +592,7 @@ This is a new feature deployment. No migration from previous versions required.
592
592
 
593
593
  ---
594
594
  *Generated by Operations Phase Templates*
595
- `}function mp(e){let{featureName:t,workflowId:n,manifest:o}=e,r=new Date().toISOString(),i=o?.artifacts??[],s=i.filter(d=>d.stage==="code-generation"),a=i.filter(d=>d.stage==="unit"),l=(o?.gate_audit??[]).filter(d=>d.action==="rejected"),u=o?.metrics??null;return`---
595
+ `}function hp(e){let{featureName:t,workflowId:n,manifest:o}=e,r=new Date().toISOString(),i=o?.artifacts??[],s=i.filter(d=>d.stage==="code-generation"),a=i.filter(d=>d.stage==="unit"),l=(o?.gate_audit??[]).filter(d=>d.action==="rejected"),u=o?.metrics??null;return`---
596
596
  id: COST-001
597
597
  feature: ${n}
598
598
  created: ${r}
@@ -639,27 +639,27 @@ ${l.length>2?"- High rejection rate suggests specification clarity could be impr
639
639
 
640
640
  ---
641
641
  *Generated by Operations Phase Templates*
642
- `}async function G_(e,t){let n=zt.join(t,"aidlc-docs",e.workflowId,"operations");await Nt.ensureDir(n);let o=[],r=e.depthLevel||"MEDIUM";return await Nt.writeFile(zt.join(n,"release-notes.md"),fp(e),"utf-8"),o.push("release-notes.md"),r==="SHALLOW"?{artifactsGenerated:o,operationsDir:n}:(await Nt.writeFile(zt.join(n,"deploy-guide.md"),up(e),"utf-8"),o.push("deploy-guide.md"),await Nt.writeFile(zt.join(n,"runbook.md"),dp(e),"utf-8"),o.push("runbook.md"),await Nt.writeFile(zt.join(n,"monitoring.json"),pp(e),"utf-8"),o.push("monitoring.json"),await Nt.writeFile(zt.join(n,"cost.md"),mp(e),"utf-8"),o.push("cost.md"),{artifactsGenerated:o,operationsDir:n})}var Nt,zt,hp=B(()=>{"use strict";Nt=b(ue(),1),zt=b(require("path"),1)});var Vm={};st(Vm,{formatSessionSummaryLine:()=>Xv});function Xv(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,o=Math.floor(n/60),r=n%60,i;o>0?i=`${o}m ${r}s`:i=`${r}s`;let s=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}) | ${s} tokens | ${a} | ${i}`;return u.length>200&&(u=u.substring(0,197)+"..."),u}var Ym=B(()=>{"use strict"});function tg(e){if(!e)return[];let t=e.toLowerCase(),n=[];for(let[o,r]of Object.entries(eT))for(let i of r)if(t.includes(i)){n.push(o);break}return n}var eT,ng=B(()=>{"use strict";eT={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 ig={};st(ig,{COLD_START_FALLBACK_RATE:()=>va,getRoutingRecommendation:()=>rT});function tT(){let e=(0,rg.join)(ae(),"routing-config.json"),t=me(e,null);if(t)return t;try{Ge(e,og)}catch{}return og}function nT(e,t){for(let[n,o]of Object.entries(t)){let r=o.indexOf(e);if(r>=0)return{family:n,tierList:o,index:r}}return null}function oT(e,t){return!e||t===0?va:t*e.success_rate+(1-t)*va}function rT(e,t,n){try{let o=tT();if(!o.preferLowerTier)return null;let r=nT(e,o.agentTiers);if(!r||r.index===0)return null;let i=ln(n),s=r.tierList.slice(0,r.index);for(let a of s){let c=i[a],l=c?.total_invocations??0,u=Math.min(1,l/5),d=oT(c,u);if(d<o.minSuccessRate||u>=1&&l<o.minDataPoints)continue;let f="";if(c?.task_patterns&&c.task_patterns.length>0){let g=tg(t);for(let h of c.task_patterns)if(g.includes(h.pattern)&&h.successfulAgents.includes(a)&&h.confidence>=.7){f=` (especially for ${h.pattern.replace(/_/g," ")} tasks)`;break}}let m=(d*100).toFixed(0);return`Based on ${l} data points, ${a} handles this type of task with ${m}% success rate${f}. Consider using ${a} instead of ${e} to save tokens.`}return null}catch{return null}}var rg,va,og,sg=B(()=>{"use strict";rg=require("path");fe();ng();va=.5,og={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 xE={};st(xE,{main:()=>ph});module.exports=kh(xE);var ni=new Map;function _(e){let t=ni.get(e.event)||[];t.push(e),t.sort((n,o)=>(n.priority??100)-(o.priority??100)),ni.set(e.event,t)}function Ma(e){return ni.get(e)||[]}var wh={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},_h=["ultrawork","ultrathink","olympus","search","analyze"];function La(e){let t=e.replace(/```[\s\S]*?```/g,"");return t=t.replace(/~~~[\s\S]*?~~~/g,""),t=t.replace(/`[^`]+`/g,""),t}function Fa(e,t){let n=[];for(let o of _h){let r=wh[o],i=e.match(r);i&&i.index!==void 0&&n.push({type:o,keyword:i[0],position:i.index})}return n}var Ua="auto-slash-command",Ro="<auto-slash-command>",Oo="</auto-slash-command>",Wa=/^\/([a-zA-Z][\w-]*)\s*(.*)/,Ha=new Set(["ascent","cancel-ascent","help","clear","history","exit","quit"]);var Sh=/```[\s\S]*?```/g;function Ga(e){return e.replace(Sh,"")}function Ba(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.match(Wa);if(!n)return null;let[o,r,i]=n;return{command:r.toLowerCase(),args:i.trim(),raw:o}}function qa(e){return Ha.has(e.toLowerCase())}function oi(e){let n=Ga(e).trim();if(!n.startsWith("/"))return null;let o=Ba(n);return!o||qa(o.command)?null:o}function ri(e){return e.filter(t=>t.type==="text").map(t=>t.text||"").join(" ")}var Je=require("fs"),at=require("path"),Ka=require("os"),Va=(0,at.join)((0,Ka.homedir)(),".claude");function Ja(e){let t=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,n=e.match(t);if(!n)return{data:{},body:e};let[,o,r]=n,i={};for(let s of o.split(`
643
- `)){let a=s.indexOf(":");if(a===-1)continue;let c=s.slice(0,a).trim(),l=s.slice(a+1).trim();(l.startsWith('"')&&l.endsWith('"')||l.startsWith("'")&&l.endsWith("'"))&&(l=l.slice(1,-1)),i[c]=l}return{data:i,body:r}}function Ya(e,t){if(!(0,Je.existsSync)(e))return[];let n;try{n=(0,Je.readdirSync)(e,{withFileTypes:!0})}catch{return[]}let o=[];for(let r of n){if(!r.isFile()||!r.name.endsWith(".md"))continue;let i=(0,at.join)(e,r.name),s=(0,at.basename)(r.name,".md");try{let a=(0,Je.readFileSync)(i,"utf-8"),{data:c,body:l}=Ja(a),u={name:s,description:c.description||"",argumentHint:c["argument-hint"],model:c.model,agent:c.agent};o.push({name:s,path:i,metadata:u,content:l,scope:t})}catch{continue}}return o}function ii(){let e=(0,at.join)(Va,"commands"),t=(0,at.join)(process.cwd(),".claude","commands"),n=(0,at.join)(Va,"skills"),o=Ya(e,"user"),r=Ya(t,"project"),i=[];if((0,Je.existsSync)(n))try{let s=(0,Je.readdirSync)(n,{withFileTypes:!0});for(let a of s){if(!a.isDirectory())continue;let c=(0,at.join)(n,a.name,"SKILL.md");if((0,Je.existsSync)(c))try{let l=(0,Je.readFileSync)(c,"utf-8"),{data:u,body:d}=Ja(l),f={name:u.name||a.name,description:u.description||"",argumentHint:u["argument-hint"],model:u.model,agent:u.agent};i.push({name:u.name||a.name,path:c,metadata:f,content:d,scope:"skill"})}catch{continue}}}catch{}return[...r,...o,...i]}function Ao(e){return ii().find(n=>n.name.toLowerCase()===e.toLowerCase())??null}function vh(e,t){return e.replace(/\$ARGUMENTS/g,t||"(no arguments provided)")}function Th(e,t){let n=[];n.push(`<command-name>/${e.name}</command-name>
642
+ `}async function qS(e,t){let n=zt.join(t,"aidlc-docs",e.workflowId,"operations");await Nt.ensureDir(n);let o=[],r=e.depthLevel||"MEDIUM";return await Nt.writeFile(zt.join(n,"release-notes.md"),gp(e),"utf-8"),o.push("release-notes.md"),r==="SHALLOW"?{artifactsGenerated:o,operationsDir:n}:(await Nt.writeFile(zt.join(n,"deploy-guide.md"),pp(e),"utf-8"),o.push("deploy-guide.md"),await Nt.writeFile(zt.join(n,"runbook.md"),fp(e),"utf-8"),o.push("runbook.md"),await Nt.writeFile(zt.join(n,"monitoring.json"),mp(e),"utf-8"),o.push("monitoring.json"),await Nt.writeFile(zt.join(n,"cost.md"),hp(e),"utf-8"),o.push("cost.md"),{artifactsGenerated:o,operationsDir:n})}var Nt,zt,kp=B(()=>{"use strict";Nt=b(ue(),1),zt=b(require("path"),1)});var Km={};st(Km,{formatSessionSummaryLine:()=>eT});function eT(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,o=Math.floor(n/60),r=n%60,i;o>0?i=`${o}m ${r}s`:i=`${r}s`;let s=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}) | ${s} tokens | ${a} | ${i}`;return u.length>200&&(u=u.substring(0,197)+"..."),u}var Jm=B(()=>{"use strict"});function og(e){if(!e)return[];let t=e.toLowerCase(),n=[];for(let[o,r]of Object.entries(nT))for(let i of r)if(t.includes(i)){n.push(o);break}return n}var nT,rg=B(()=>{"use strict";nT={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 ag={};st(ag,{COLD_START_FALLBACK_RATE:()=>Ea,getRoutingRecommendation:()=>sT});function oT(){let e=(0,sg.join)(ae(),"routing-config.json"),t=me(e,null);if(t)return t;try{Ge(e,ig)}catch{}return ig}function rT(e,t){for(let[n,o]of Object.entries(t)){let r=o.indexOf(e);if(r>=0)return{family:n,tierList:o,index:r}}return null}function iT(e,t){return!e||t===0?Ea:t*e.success_rate+(1-t)*Ea}function sT(e,t,n){try{let o=oT();if(!o.preferLowerTier)return null;let r=rT(e,o.agentTiers);if(!r||r.index===0)return null;let i=ln(n),s=r.tierList.slice(0,r.index);for(let a of s){let c=i[a],l=c?.total_invocations??0,u=Math.min(1,l/5),d=iT(c,u);if(d<o.minSuccessRate||u>=1&&l<o.minDataPoints)continue;let f="";if(c?.task_patterns&&c.task_patterns.length>0){let g=og(t);for(let h of c.task_patterns)if(g.includes(h.pattern)&&h.successfulAgents.includes(a)&&h.confidence>=.7){f=` (especially for ${h.pattern.replace(/_/g," ")} tasks)`;break}}let m=(d*100).toFixed(0);return`Based on ${l} data points, ${a} handles this type of task with ${m}% success rate${f}. Consider using ${a} instead of ${e} to save tokens.`}return null}catch{return null}}var sg,Ea,ig,cg=B(()=>{"use strict";sg=require("path");fe();rg();Ea=.5,ig={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 NE={};st(NE,{main:()=>mh});module.exports=Sh(NE);var ni=new Map;function S(e){let t=ni.get(e.event)||[];t.push(e),t.sort((n,o)=>(n.priority??100)-(o.priority??100)),ni.set(e.event,t)}function Fa(e){return ni.get(e)||[]}var _h={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},vh=["ultrawork","ultrathink","olympus","search","analyze"];function Ua(e){let t=e.replace(/```[\s\S]*?```/g,"");return t=t.replace(/~~~[\s\S]*?~~~/g,""),t=t.replace(/`[^`]+`/g,""),t}function Wa(e,t){let n=[];for(let o of vh){let r=_h[o],i=e.match(r);i&&i.index!==void 0&&n.push({type:o,keyword:i[0],position:i.index})}return n}var Ha="auto-slash-command",Oo="<auto-slash-command>",Ao="</auto-slash-command>",Ga=/^\/([a-zA-Z][\w-]*)\s*(.*)/,Ba=new Set(["ascent","cancel-ascent","help","clear","history","exit","quit"]);var Th=/```[\s\S]*?```/g;function qa(e){return e.replace(Th,"")}function Va(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.match(Ga);if(!n)return null;let[o,r,i]=n;return{command:r.toLowerCase(),args:i.trim(),raw:o}}function Ya(e){return Ba.has(e.toLowerCase())}function oi(e){let n=qa(e).trim();if(!n.startsWith("/"))return null;let o=Va(n);return!o||Ya(o.command)?null:o}function ri(e){return e.filter(t=>t.type==="text").map(t=>t.text||"").join(" ")}var Je=require("fs"),at=require("path"),za=require("os"),Ka=(0,at.join)((0,za.homedir)(),".claude");function Qa(e){let t=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,n=e.match(t);if(!n)return{data:{},body:e};let[,o,r]=n,i={};for(let s of o.split(`
643
+ `)){let a=s.indexOf(":");if(a===-1)continue;let c=s.slice(0,a).trim(),l=s.slice(a+1).trim();(l.startsWith('"')&&l.endsWith('"')||l.startsWith("'")&&l.endsWith("'"))&&(l=l.slice(1,-1)),i[c]=l}return{data:i,body:r}}function Ja(e,t){if(!(0,Je.existsSync)(e))return[];let n;try{n=(0,Je.readdirSync)(e,{withFileTypes:!0})}catch{return[]}let o=[];for(let r of n){if(!r.isFile()||!r.name.endsWith(".md"))continue;let i=(0,at.join)(e,r.name),s=(0,at.basename)(r.name,".md");try{let a=(0,Je.readFileSync)(i,"utf-8"),{data:c,body:l}=Qa(a),u={name:s,description:c.description||"",argumentHint:c["argument-hint"],model:c.model,agent:c.agent};o.push({name:s,path:i,metadata:u,content:l,scope:t})}catch{continue}}return o}function ii(){let e=(0,at.join)(Ka,"commands"),t=(0,at.join)(process.cwd(),".claude","commands"),n=(0,at.join)(Ka,"skills"),o=Ja(e,"user"),r=Ja(t,"project"),i=[];if((0,Je.existsSync)(n))try{let s=(0,Je.readdirSync)(n,{withFileTypes:!0});for(let a of s){if(!a.isDirectory())continue;let c=(0,at.join)(n,a.name,"SKILL.md");if((0,Je.existsSync)(c))try{let l=(0,Je.readFileSync)(c,"utf-8"),{data:u,body:d}=Qa(l),f={name:u.name||a.name,description:u.description||"",argumentHint:u["argument-hint"],model:u.model,agent:u.agent};i.push({name:u.name||a.name,path:c,metadata:f,content:d,scope:"skill"})}catch{continue}}}catch{}return[...r,...o,...i]}function Po(e){return ii().find(n=>n.name.toLowerCase()===e.toLowerCase())??null}function Eh(e,t){return e.replace(/\$ARGUMENTS/g,t||"(no arguments provided)")}function bh(e,t){let n=[];n.push(`<command-name>/${e.name}</command-name>
644
644
  `),e.metadata.description&&n.push(`**Description**: ${e.metadata.description}
645
645
  `),t&&n.push(`**Arguments**: ${t}
646
646
  `),e.metadata.model&&n.push(`**Model**: ${e.metadata.model}
647
647
  `),e.metadata.agent&&n.push(`**Agent**: ${e.metadata.agent}
648
648
  `),n.push(`**Scope**: ${e.scope}
649
649
  `),n.push(`---
650
- `);let o=vh(e.content||"",t);return n.push(o.trim()),t&&!e.content?.includes("$ARGUMENTS")&&(n.push(`
650
+ `);let o=Eh(e.content||"",t);return n.push(o.trim()),t&&!e.content?.includes("$ARGUMENTS")&&(n.push(`
651
651
 
652
652
  ---
653
653
  `),n.push(`## User Request
654
654
  `),n.push(t)),n.join(`
655
- `)}function si(e){let t=Ao(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:Th(t,e.args)}}catch(n){return{success:!1,error:`Failed to load command "/${e.command}": ${n instanceof Error?n.message:String(n)}`}}}function ai(){return ii().map(t=>({name:t.name,description:t.metadata.description,scope:t.scope}))}var Po=new Set;function za(){return{name:Ua,processMessage:(e,t)=>{let n=ri(t);if(n.includes(Ro)||n.includes(Oo))return{detected:!1};let o=oi(n);if(!o)return{detected:!1};let r=`${e.sessionId}:${e.messageId}:${o.command}`;if(Po.has(r))return{detected:!1};Po.add(r);let i=si(o);if(i.success&&i.replacementText){let a=`${Ro}
655
+ `)}function si(e){let t=Po(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:bh(t,e.args)}}catch(n){return{success:!1,error:`Failed to load command "/${e.command}": ${n instanceof Error?n.message:String(n)}`}}}function ai(){return ii().map(t=>({name:t.name,description:t.metadata.description,scope:t.scope}))}var xo=new Set;function Xa(){return{name:Ha,processMessage:(e,t)=>{let n=ri(t);if(n.includes(Oo)||n.includes(Ao))return{detected:!1};let o=oi(n);if(!o)return{detected:!1};let r=`${e.sessionId}:${e.messageId}:${o.command}`;if(xo.has(r))return{detected:!1};xo.add(r);let i=si(o);if(i.success&&i.replacementText){let a=`${Oo}
656
656
  ${i.replacementText}
657
- ${Oo}`;return{detected:!0,parsedCommand:o,injectedMessage:a}}let s=`${Ro}
657
+ ${Ao}`;return{detected:!0,parsedCommand:o,injectedMessage:a}}let s=`${Oo}
658
658
  [AUTO-SLASH-COMMAND ERROR]
659
659
  ${i.error}
660
660
 
661
661
  Original input: ${o.raw}
662
- ${Oo}`;return{detected:!0,parsedCommand:o,injectedMessage:s}},listCommands:()=>ai(),findCommand:e=>Ao(e),clearSession:e=>{let t=[];for(let n of Po)n.startsWith(`${e}:`)&&t.push(n);for(let n of t)Po.delete(n)}}}var Eh=[/\bultrathink\b/i,/\bthink\b/i],bh=["\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"],Ch=bh.map(e=>new RegExp(e,"i")),Ih=[...Eh,...Ch],Rh=/```[\s\S]*?```/g,Oh=/`[^`]+`/g;function Ah(e){return e.replace(Rh,"").replace(Oh,"")}function Qa(e){let t=Ah(e);return Ih.some(n=>n.test(t))}function Xa(e){return e.filter(t=>t.type==="text").map(t=>t.text||"").join("")}function ci(e){let t=e.indexOf("/");return t===-1?{prefix:"",base:e}:{prefix:e.slice(0,t+1),base:e.slice(t+1)}}function li(e){return e.replace(/\.(\d+)/g,"-$1")}var Za={"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"},ec=new Set(Object.values(Za)),tc={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"}},Ph={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 nc(e){let t=li(e),{prefix:n,base:o}=ci(t);if(ec.has(o)||o.endsWith("-high"))return null;let r=Za[o];return r?n+r:null}function ui(e){let t=li(e),{base:n}=ci(t);return ec.has(n)||n.endsWith("-high")}function xh(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 $h(e){return e in tc}function oc(e,t){let n=li(t),{base:o}=ci(n);if(ui(n))return null;let r=xh(e,t);if(!$h(r))return null;let i=tc[r],s=Ph[r];if(!s)return null;let a=o.toLowerCase();return s.some(l=>a.includes(l.toLowerCase()))?i:null}var wt=new Map;function Nh(e){wt.delete(e)}function rc(){return{processChatParams:(e,t)=>{let n=Xa(t.parts),o={requested:!1,modelSwitched:!1,thinkingConfigInjected:!1};if(!Qa(n))return wt.set(e,o),o;o.requested=!0;let r=t.message.model;if(!r||(o.providerId=r.providerId,o.modelId=r.modelId,ui(r.modelId)))return wt.set(e,o),o;let i=nc(r.modelId),s=oc(r.providerId,r.modelId);return i&&(t.message.model={providerId:r.providerId,modelId:i},o.modelSwitched=!0),s&&(Object.assign(t.message,s),o.thinkingConfigInjected=!0),wt.set(e,o),o},onSessionDeleted:e=>{wt.delete(e)},isRequested:e=>wt.get(e)?.requested??!1,getState:e=>wt.get(e),clear:Nh}}var re=require("fs"),on=require("path"),di=require("os");function pi(e){let t=e||process.cwd(),n=(0,on.join)(t,".olympus");return(0,on.join)(n,"ultrawork-state.json")}function fi(){return(0,on.join)((0,di.homedir)(),".claude","ultrawork-state.json")}function Dh(e){let t=e||process.cwd(),n=(0,on.join)(t,".olympus");(0,re.existsSync)(n)||(0,re.mkdirSync)(n,{recursive:!0})}function jh(){let e=(0,on.join)((0,di.homedir)(),".claude");(0,re.existsSync)(e)||(0,re.mkdirSync)(e,{recursive:!0})}function _t(e){let t=pi(e);if((0,re.existsSync)(t))try{let o=(0,re.readFileSync)(t,"utf-8");return JSON.parse(o)}catch{}let n=fi();if((0,re.existsSync)(n))try{let o=(0,re.readFileSync)(n,"utf-8");return JSON.parse(o)}catch{return null}return null}function ic(e,t){try{Dh(t);let n=pi(t);(0,re.writeFileSync)(n,JSON.stringify(e,null,2)),jh();let o=fi();return(0,re.writeFileSync)(o,JSON.stringify(e,null,2)),!0}catch{return!1}}function sc(e,t,n){let o={active:!0,started_at:new Date().toISOString(),original_prompt:e,session_id:t,reinforcement_count:0,last_checked_at:new Date().toISOString()};return ic(o,n)}function ac(e){let t=pi(e);if((0,re.existsSync)(t))try{(0,re.unlinkSync)(t)}catch{}let n=fi();if((0,re.existsSync)(n))try{return(0,re.unlinkSync)(n),!0}catch{return!1}return!0}function cc(e){let t=_t(e);return!t||!t.active?null:(t.reinforcement_count+=1,t.last_checked_at=new Date().toISOString(),ic(t,e)?t:null)}function lc(e){return`<ultrawork-persistence>
662
+ ${Ao}`;return{detected:!0,parsedCommand:o,injectedMessage:s}},listCommands:()=>ai(),findCommand:e=>Po(e),clearSession:e=>{let t=[];for(let n of xo)n.startsWith(`${e}:`)&&t.push(n);for(let n of t)xo.delete(n)}}}var Ch=[/\bultrathink\b/i,/\bthink\b/i],Ih=["\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"],Rh=Ih.map(e=>new RegExp(e,"i")),Oh=[...Ch,...Rh],Ah=/```[\s\S]*?```/g,Ph=/`[^`]+`/g;function xh(e){return e.replace(Ah,"").replace(Ph,"")}function Za(e){let t=xh(e);return Oh.some(n=>n.test(t))}function ec(e){return e.filter(t=>t.type==="text").map(t=>t.text||"").join("")}function ci(e){let t=e.indexOf("/");return t===-1?{prefix:"",base:e}:{prefix:e.slice(0,t+1),base:e.slice(t+1)}}function li(e){return e.replace(/\.(\d+)/g,"-$1")}var tc={"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"},nc=new Set(Object.values(tc)),oc={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"}},$h={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 rc(e){let t=li(e),{prefix:n,base:o}=ci(t);if(nc.has(o)||o.endsWith("-high"))return null;let r=tc[o];return r?n+r:null}function ui(e){let t=li(e),{base:n}=ci(t);return nc.has(n)||n.endsWith("-high")}function Nh(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 Dh(e){return e in oc}function ic(e,t){let n=li(t),{base:o}=ci(n);if(ui(n))return null;let r=Nh(e,t);if(!Dh(r))return null;let i=oc[r],s=$h[r];if(!s)return null;let a=o.toLowerCase();return s.some(l=>a.includes(l.toLowerCase()))?i:null}var wt=new Map;function jh(e){wt.delete(e)}function sc(){return{processChatParams:(e,t)=>{let n=ec(t.parts),o={requested:!1,modelSwitched:!1,thinkingConfigInjected:!1};if(!Za(n))return wt.set(e,o),o;o.requested=!0;let r=t.message.model;if(!r||(o.providerId=r.providerId,o.modelId=r.modelId,ui(r.modelId)))return wt.set(e,o),o;let i=rc(r.modelId),s=ic(r.providerId,r.modelId);return i&&(t.message.model={providerId:r.providerId,modelId:i},o.modelSwitched=!0),s&&(Object.assign(t.message,s),o.thinkingConfigInjected=!0),wt.set(e,o),o},onSessionDeleted:e=>{wt.delete(e)},isRequested:e=>wt.get(e)?.requested??!1,getState:e=>wt.get(e),clear:jh}}var re=require("fs"),on=require("path"),di=require("os");function pi(e){let t=e||process.cwd(),n=(0,on.join)(t,".olympus");return(0,on.join)(n,"ultrawork-state.json")}function fi(){return(0,on.join)((0,di.homedir)(),".claude","ultrawork-state.json")}function Mh(e){let t=e||process.cwd(),n=(0,on.join)(t,".olympus");(0,re.existsSync)(n)||(0,re.mkdirSync)(n,{recursive:!0})}function Lh(){let e=(0,on.join)((0,di.homedir)(),".claude");(0,re.existsSync)(e)||(0,re.mkdirSync)(e,{recursive:!0})}function St(e){let t=pi(e);if((0,re.existsSync)(t))try{let o=(0,re.readFileSync)(t,"utf-8");return JSON.parse(o)}catch{}let n=fi();if((0,re.existsSync)(n))try{let o=(0,re.readFileSync)(n,"utf-8");return JSON.parse(o)}catch{return null}return null}function ac(e,t){try{Mh(t);let n=pi(t);(0,re.writeFileSync)(n,JSON.stringify(e,null,2)),Lh();let o=fi();return(0,re.writeFileSync)(o,JSON.stringify(e,null,2)),!0}catch{return!1}}function cc(e,t,n){let o={active:!0,started_at:new Date().toISOString(),original_prompt:e,session_id:t,reinforcement_count:0,last_checked_at:new Date().toISOString()};return ac(o,n)}function lc(e){let t=pi(e);if((0,re.existsSync)(t))try{(0,re.unlinkSync)(t)}catch{}let n=fi();if((0,re.existsSync)(n))try{return(0,re.unlinkSync)(n),!0}catch{return!1}return!0}function uc(e){let t=St(e);return!t||!t.active?null:(t.reinforcement_count+=1,t.last_checked_at=new Date().toISOString(),ac(t,e)?t:null)}function dc(e){return`<ultrawork-persistence>
663
663
 
664
664
  [ULTRAWORK MODE STILL ACTIVE - Reinforcement #${e.reinforcement_count+1}]
665
665
 
@@ -680,7 +680,7 @@ Original task: ${e.original_prompt}
680
680
 
681
681
  ---
682
682
 
683
- `}var uc=require("os"),pe=require("path");function ze(){return process.platform==="win32"}function Mh(){return(0,pe.join)((0,uc.homedir)(),".claude")}function be(){return(0,pe.join)(Mh(),"hooks")}var dc=`<ultrawork-mode>
683
+ `}var pc=require("os"),pe=require("path");function ze(){return process.platform==="win32"}function Fh(){return(0,pe.join)((0,pc.homedir)(),".claude")}function be(){return(0,pe.join)(Fh(),"hooks")}var fc=`<ultrawork-mode>
684
684
 
685
685
  **MANDATORY**: You MUST say "ULTRAWORK MODE ENABLED!" to the user as your first response when this mode activates. This is non-negotiable.
686
686
 
@@ -771,7 +771,7 @@ THE USER ASKED FOR X. DELIVER EXACTLY X. NOT A SUBSET. NOT A DEMO. NOT A STARTIN
771
771
 
772
772
  ---
773
773
 
774
- `,pc=`<think-mode>
774
+ `,mc=`<think-mode>
775
775
 
776
776
  **ULTRATHINK MODE ENABLED** - Extended reasoning activated.
777
777
 
@@ -787,7 +787,7 @@ Use your extended thinking capabilities to provide the most thorough and well-re
787
787
 
788
788
  ---
789
789
 
790
- `;var fc=`<search-mode>
790
+ `;var gc=`<search-mode>
791
791
  MAXIMIZE SEARCH EFFORT. Launch multiple background agents IN PARALLEL:
792
792
  - explore agents (codebase patterns, file structures)
793
793
  - librarian agents (remote repos, official docs, GitHub examples)
@@ -797,7 +797,7 @@ NEVER stop at first result - be exhaustive.
797
797
 
798
798
  ---
799
799
 
800
- `,mc=`<analyze-mode>
800
+ `,hc=`<analyze-mode>
801
801
  ANALYSIS MODE. Gather context before diving deep:
802
802
 
803
803
  CONTEXT GATHERING (parallel):
@@ -813,25 +813,25 @@ SYNTHESIZE findings before proceeding.
813
813
 
814
814
  ---
815
815
 
816
- `,gc=`[SYSTEM REMINDER - TODO CONTINUATION]
816
+ `,yc=`[SYSTEM REMINDER - TODO CONTINUATION]
817
817
 
818
818
  Incomplete tasks remain in your todo list. Continue working on the next pending task.
819
819
 
820
820
  - Proceed without asking for permission
821
821
  - Mark each task complete when finished
822
- - Do not stop until all tasks are done`;var sb={hooks:{UserPromptSubmit:[{hooks:[{type:"command",command:ze()?'node "%USERPROFILE%\\.claude\\hooks\\keyword-detector.mjs"':'node "$HOME/.claude/hooks/keyword-detector.mjs"'}]}],SessionStart:[{hooks:[{type:"command",command:ze()?'node "%USERPROFILE%\\.claude\\hooks\\session-start.mjs"':'node "$HOME/.claude/hooks/session-start.mjs"'}]}],Stop:[{hooks:[{type:"command",command:ze()?'node "%USERPROFILE%\\.claude\\hooks\\persistent-mode.mjs"':'node "$HOME/.claude/hooks/persistent-mode.mjs"'}]}]}},ab={hooks:{UserPromptSubmit:[{hooks:[{type:"command",command:ze()?`node "${(0,pe.join)(be(),"olympus-hooks.cjs")}" --event=UserPromptSubmit`:`node "${(0,pe.join)(be(),"olympus-hooks.cjs")}" --event=UserPromptSubmit`}]}],SessionStart:[{hooks:[{type:"command",command:ze()?`node "${(0,pe.join)(be(),"olympus-hooks.cjs")}" --event=SessionStart`:`node "${(0,pe.join)(be(),"olympus-hooks.cjs")}" --event=SessionStart`}]}],Stop:[{hooks:[{type:"command",command:ze()?`node "${(0,pe.join)(be(),"olympus-hooks.cjs")}" --event=Stop`:`node "${(0,pe.join)(be(),"olympus-hooks.cjs")}" --event=Stop`}]}],PreToolUse:[{hooks:[{type:"command",command:ze()?`node "${(0,pe.join)(be(),"olympus-hooks.cjs")}" --event=PreToolUse`:`node "${(0,pe.join)(be(),"olympus-hooks.cjs")}" --event=PreToolUse`}]}],PostToolUse:[{hooks:[{type:"command",command:ze()?`node "${(0,pe.join)(be(),"olympus-hooks.cjs")}" --event=PostToolUse`:`node "${(0,pe.join)(be(),"olympus-hooks.cjs")}" --event=PostToolUse`}]}],PostToolUseFailure:[{hooks:[{type:"command",command:ze()?`node "${(0,pe.join)(be(),"olympus-hooks.cjs")}" --event=PostToolUseFailure`:`node "${(0,pe.join)(be(),"olympus-hooks.cjs")}" --event=PostToolUseFailure`}]}],Notification:[{hooks:[{type:"command",command:ze()?`node "${(0,pe.join)(be(),"olympus-hooks.cjs")}" --event=Notification`:`node "${(0,pe.join)(be(),"olympus-hooks.cjs")}" --event=Notification`}]}]}};Ae();fe();var Fc=require("crypto"),Yh={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 ki(e){let t=e.replace(/```[\s\S]*?```/g,"").replace(/`[^`]+`/g,""),n=null;for(let[o,r]of Object.entries(Yh))for(let{regex:i,confidence:s}of r)i.test(t)&&(!n||s>n.confidence)&&(n={category:o,confidence:s});return n}async function Uc(e){let{prompt:t,directory:n,sessionId:o}=e;if(!t||!n)return;let r=V(n,o),i=ki(t),s=Ac(r,t,i?.category);if(i){let a={id:(0,Fc.randomUUID)(),timestamp:new Date().toISOString(),session_id:r.session_id,project_path:n,event_type:i.category==="explicit_preference"?"explicit_preference":"revision",original_task:r.pending_completion?.task_description,agent_used:r.pending_completion?.agent_used,user_message:t,feedback_category:i.category,confidence:i.confidence};St(a)}Q(n,s)}Ae();fe();var Wc=require("crypto");async function Hc(e){let{prompt:t,directory:n,sessionId:o}=e;if(!t||!n)return;let r=V(n,o),i=ki(t);if(i?.category==="praise"&&i.confidence>.7){let a={id:(0,Wc.randomUUID)(),timestamp:new Date().toISOString(),session_id:r.session_id,project_path:n,event_type:"success",original_task:r.pending_completion?.task_description,agent_used:r.pending_completion?.agent_used,user_message:t,feedback_category:"praise",confidence:i.confidence};if(St(a),No(r)){let c=xc(r);Q(n,c)}}}var Ne=b(require("fs"),1),fr=b(require("path"),1);Ee();Hi();var Ju=require("fs"),Ku=new Map,mw=1e4;function gw(e){let t=Ku.get(e);if(t&&Date.now()-t.timestamp<mw)return t.content;let n=(0,Ju.readFileSync)(e,"utf-8");return Ku.set(e,{content:n,timestamp:Date.now()}),n}function hw(e){let t=e.match(/^---\n([\s\S]*?)\n---/);if(!t)return null;let n=t[1];try{let o={},r=n.split(`
823
- `);for(let i of r){let s=i.match(/^(\w+):\s*(.+)$/);if(s){let[,a,c]=s;o[a]=c.trim()}}return o}catch{return null}}function yw(e){return e.replace(/^---\n[\s\S]*?\n---\n/,"")}function kw(e){let t=new Map,n=e.split(`
822
+ - Do not stop until all tasks are done`;var cb={hooks:{UserPromptSubmit:[{hooks:[{type:"command",command:ze()?'node "%USERPROFILE%\\.claude\\hooks\\keyword-detector.mjs"':'node "$HOME/.claude/hooks/keyword-detector.mjs"'}]}],SessionStart:[{hooks:[{type:"command",command:ze()?'node "%USERPROFILE%\\.claude\\hooks\\session-start.mjs"':'node "$HOME/.claude/hooks/session-start.mjs"'}]}],Stop:[{hooks:[{type:"command",command:ze()?'node "%USERPROFILE%\\.claude\\hooks\\persistent-mode.mjs"':'node "$HOME/.claude/hooks/persistent-mode.mjs"'}]}]}},lb={hooks:{UserPromptSubmit:[{hooks:[{type:"command",command:ze()?`node "${(0,pe.join)(be(),"olympus-hooks.cjs")}" --event=UserPromptSubmit`:`node "${(0,pe.join)(be(),"olympus-hooks.cjs")}" --event=UserPromptSubmit`}]}],SessionStart:[{hooks:[{type:"command",command:ze()?`node "${(0,pe.join)(be(),"olympus-hooks.cjs")}" --event=SessionStart`:`node "${(0,pe.join)(be(),"olympus-hooks.cjs")}" --event=SessionStart`}]}],Stop:[{hooks:[{type:"command",command:ze()?`node "${(0,pe.join)(be(),"olympus-hooks.cjs")}" --event=Stop`:`node "${(0,pe.join)(be(),"olympus-hooks.cjs")}" --event=Stop`}]}],PreToolUse:[{hooks:[{type:"command",command:ze()?`node "${(0,pe.join)(be(),"olympus-hooks.cjs")}" --event=PreToolUse`:`node "${(0,pe.join)(be(),"olympus-hooks.cjs")}" --event=PreToolUse`}]}],PostToolUse:[{hooks:[{type:"command",command:ze()?`node "${(0,pe.join)(be(),"olympus-hooks.cjs")}" --event=PostToolUse`:`node "${(0,pe.join)(be(),"olympus-hooks.cjs")}" --event=PostToolUse`}]}],PostToolUseFailure:[{hooks:[{type:"command",command:ze()?`node "${(0,pe.join)(be(),"olympus-hooks.cjs")}" --event=PostToolUseFailure`:`node "${(0,pe.join)(be(),"olympus-hooks.cjs")}" --event=PostToolUseFailure`}]}],Notification:[{hooks:[{type:"command",command:ze()?`node "${(0,pe.join)(be(),"olympus-hooks.cjs")}" --event=Notification`:`node "${(0,pe.join)(be(),"olympus-hooks.cjs")}" --event=Notification`}]}]}};Pe();fe();var Wc=require("crypto"),Jh={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 ki(e){let t=e.replace(/```[\s\S]*?```/g,"").replace(/`[^`]+`/g,""),n=null;for(let[o,r]of Object.entries(Jh))for(let{regex:i,confidence:s}of r)i.test(t)&&(!n||s>n.confidence)&&(n={category:o,confidence:s});return n}async function Hc(e){let{prompt:t,directory:n,sessionId:o}=e;if(!t||!n)return;let r=V(n,o),i=ki(t),s=xc(r,t,i?.category);if(i){let a={id:(0,Wc.randomUUID)(),timestamp:new Date().toISOString(),session_id:r.session_id,project_path:n,event_type:i.category==="explicit_preference"?"explicit_preference":"revision",original_task:r.pending_completion?.task_description,agent_used:r.pending_completion?.agent_used,user_message:t,feedback_category:i.category,confidence:i.confidence};_t(a)}Q(n,s)}Pe();fe();var Gc=require("crypto");async function Bc(e){let{prompt:t,directory:n,sessionId:o}=e;if(!t||!n)return;let r=V(n,o),i=ki(t);if(i?.category==="praise"&&i.confidence>.7){let a={id:(0,Gc.randomUUID)(),timestamp:new Date().toISOString(),session_id:r.session_id,project_path:n,event_type:"success",original_task:r.pending_completion?.task_description,agent_used:r.pending_completion?.agent_used,user_message:t,feedback_category:"praise",confidence:i.confidence};if(_t(a),Do(r)){let c=Nc(r);Q(n,c)}}}var Re=b(require("fs"),1),co=b(require("path"),1);Ee();Gi();var Qu=require("fs"),zu=new Map,gw=1e4;function hw(e){let t=zu.get(e);if(t&&Date.now()-t.timestamp<gw)return t.content;let n=(0,Qu.readFileSync)(e,"utf-8");return zu.set(e,{content:n,timestamp:Date.now()}),n}function yw(e){let t=e.match(/^---\n([\s\S]*?)\n---/);if(!t)return null;let n=t[1];try{let o={},r=n.split(`
823
+ `);for(let i of r){let s=i.match(/^(\w+):\s*(.+)$/);if(s){let[,a,c]=s;o[a]=c.trim()}}return o}catch{return null}}function kw(e){return e.replace(/^---\n[\s\S]*?\n---\n/,"")}function ww(e){let t=new Map,n=e.split(`
824
824
  `),o=null,r=[];for(let i of n){let s=i.match(/^##\s+(.+)$/);s?(o&&t.set(o,r.join(`
825
825
  `)),o=s[1].trim(),r=[]):o&&r.push(i)}return o&&t.set(o,r.join(`
826
- `)),t}async function zo(e){let t=new Date().toISOString(),n=[],o;try{o=gw(e)}catch(m){let p=m;return p.code==="ENOENT"?(console.error(`[Validation] INTENT artifact not found: ${e}`),{passed:!1,coverage_percentage:0,blocking_issues:["Artifact file not found"],timestamp:t}):p.code==="EACCES"||p.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: ${p.message}`),console.error(`[Validation] Path: ${e}`),{passed:!1,coverage_percentage:0,blocking_issues:[`Failed to read artifact: ${p.message}`],timestamp:t})}let r=hw(o),i=["id","title","parent","status","depth_score","risk_tier"],s=!0;for(let m of i)(!r||!r[m])&&(n.push(`Frontmatter missing required field: ${m}`),s=!1);let a=yw(o),c=kw(a),l=s?1:0,u=[()=>{let m=c.get("Business Requirements");if(!m)return"Missing Business Requirements section";let p=m.match(/US-\d{3}/g);return!p||p.length===0?"No User Stories found (expected US-NNN pattern)":null},()=>{let m=c.get("Business Requirements");if(m){let p=m.match(/US-\d{3}/g);if(p)for(let g of p){let h=m.indexOf(g),y=m.indexOf("US-",h+1);if(!(y>0?m.substring(h,y):m.substring(h)).match(/Acceptance:/i))return`User Story ${g} missing Acceptance criterion`}}return null},()=>{let m=c.get("Technical Specification");return!m||m.trim().length===0?"Technical Specification section missing or empty":null},()=>{let m=c.get("Implementation Plan");return!m||m.trim().length===0?"Implementation Plan section missing or empty":null},()=>{let m=c.get("Implementation Plan");if(!m||m.trim().length===0)return"";let p=m.match(/UNIT-\d{3}/g);return!p||p.length===0?"No Proposed UNITs found (expected UNIT-NNN pattern)":null}];for(let m of u){let p=m();p!==null?p.trim().length>0&&n.push(p):l++}let f=Math.round(l/6*100);return{passed:n.length===0,coverage_percentage:f,blocking_issues:n,timestamp:t}}var ne=b(ue(),1),W=b(require("path"),1);var yn=b(ue(),1),zu=b(require("path"),1),ww=10;function Qu(e,t){let n=`u-${String(t).padStart(3,"0")}`;if(!e||!e.trim())return`${n}-untitled`;let o=e.toLowerCase().replace(/[_\s]+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"");return o?o.length>60?`${n}-${o.substring(0,60).replace(/-$/,"")}`:`${n}-${o}`:`${n}-untitled`}async function Gi(e){try{if(!await yn.default.pathExists(e))return[];let o=(await yn.default.readdir(e)).filter(i=>i.startsWith("INTENT-")&&i.endsWith(".md")),r=[];for(let i of o)try{let s=zu.default.join(e,i),c=(await yn.default.readFile(s,"utf-8")).match(/^---\n([\s\S]*?)\n---/);if(!c){console.error(`No frontmatter found in ${i}`);continue}let u=c[1].split(`
827
- `),d={};for(let m of u){let p=m.match(/^(\w+):\s*(.+)$/);if(p){let[,g,h]=p;h.startsWith("[")?d[g]=JSON.parse(h.replace(/'/g,'"')):isNaN(Number(h))?d[g]=h.trim():d[g]=Number(h)}}let f={id:d.id||i.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};r.push(f)}catch(s){console.error(`Failed to parse ${i}:`,s)}return r}catch(t){return console.error(`Failed to read intents from ${e}:`,t),[]}}async function Bi(e){try{if(!await yn.default.pathExists(e))return null;let n=await yn.default.readFile(e,"utf-8"),o=[],r=n.match(/### Proposed UNITs\s*\n([\s\S]*?)(?=\n##[^#]|\n---|\Z|$)/);if(r){let i=r[1],s=/^-\s+\*\*([^*]+)\*\*:\s*(.+)$/gm,a,c=0;for(;(a=s.exec(i))!==null;){let l=a[1].trim(),u=a[2].trim(),d=Qu(l,c+1);o.push({id:d,title:l,description:u}),c++}}return{content:n,proposedUnits:o}}catch(t){return console.error(`Failed to parse intent from ${e}:`,t),null}}function qi(e,t,n=ww){let o=t;o.length>n&&(console.warn(`[decomposition] Unit specs (${o.length}) exceed maxUnits limit (${n}). Truncating to ${n}.`),o=o.slice(0,n));let r=[];for(let i=0;i<o.length;i++){let s=o[i],a=Qu(s.title,i+1),c={id:a,type:"unit",title:s.title,parent_id:e.id,children_ids:[],status:"pending",assigned_agent:null,estimated_effort:s.estimated_effort};r.push(c),e.children_ids.push(a)}return r}function Vi(e){let t=new Map;function n(o,r){t.set(o.id,o);for(let i of o.children_ids){let s=r.find(a=>a.id===i);s&&n(s,r)}}for(let o of e)t.set(o.id,o);return{roots:e,nodes:t}}var kn=b(ue(),1),wn=b(require("path"),1);function Zu(e,t){let n=[],o=1;for(let r of e){let i=At(r.title),s=_w(t,i),a=Xu(s,"input"),c=Xu(s,"output"),l=Sw(r,e);n.push({id:`IFACE-${String(o++).padStart(3,"0")}`,unit_id:r.id,name:vw(r.title),inputs:a,outputs:c,dependencies:l,description:`Interface contract for ${r.title}`})}return n}function ed(e,t){let n=[],o=1;for(let r of e){let i=t.filter(c=>c.unit_id===r.id),s=[],a=[];for(let c of i){s.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(Ew(c)){let l=`STORE-${c.id}`;s.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(o++).padStart(3,"0")}`,unit_id:r.id,components:s,flows:a,description:`Data flow diagram for ${r.title}`})}return n}function td(e,t,n){let o=[],r=1;for(let i of e){let s=t.filter(u=>u.unit_id===i.id),a=n.find(u=>u.unit_id===i.id),c=a?a.components.filter(u=>u.type==="store").map(u=>u.name):[],l=bw(i,s);o.push({id:`COMP-${String(r++).padStart(3,"0")}`,unit_id:i.id,name:Tw(i.title),responsibilities:l,interfaces_used:s.map(u=>u.id),data_stores:c,description:`Component design for ${i.title}`})}return o}function Yi(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 o=new Set(e.interfaces.map(a=>a.id));for(let a of e.components)for(let c of a.interfaces_used)o.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 r=Cw(t),i=Iw(e),s=Rw(r,i);return{passed:n.length===0,coverage_percentage:s,blocking_issues:n,reviewer:"design-validator",timestamp:new Date().toISOString()}}async function nd(e,t,n){let o=wn.default.join(e,"aidlc-docs",t,"construction","design");try{await kn.default.ensureDir(o),await kn.default.writeJson(wn.default.join(o,"interfaces.json"),n.interfaces,{spaces:2}),await kn.default.writeJson(wn.default.join(o,"data-flow.json"),n.dataFlows,{spaces:2}),await kn.default.writeJson(wn.default.join(o,"components.json"),n.components,{spaces:2});let r=Yi(n,"");await kn.default.writeJson(wn.default.join(o,"validation.json"),r,{spaces:2})}catch(r){throw console.error("Failed to write design artifacts:",r),r}}function At(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 _w(e,t){let n=e.split(`
826
+ `)),t}async function Qo(e){let t=new Date().toISOString(),n=[],o;try{o=hw(e)}catch(m){let p=m;return p.code==="ENOENT"?(console.error(`[Validation] INTENT artifact not found: ${e}`),{passed:!1,coverage_percentage:0,blocking_issues:["Artifact file not found"],timestamp:t}):p.code==="EACCES"||p.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: ${p.message}`),console.error(`[Validation] Path: ${e}`),{passed:!1,coverage_percentage:0,blocking_issues:[`Failed to read artifact: ${p.message}`],timestamp:t})}let r=yw(o),i=["id","title","parent","status","depth_score","risk_tier"],s=!0;for(let m of i)(!r||!r[m])&&(n.push(`Frontmatter missing required field: ${m}`),s=!1);let a=kw(o),c=ww(a),l=s?1:0,u=[()=>{let m=c.get("Business Requirements");if(!m)return"Missing Business Requirements section";let p=m.match(/US-\d{3}/g);return!p||p.length===0?"No User Stories found (expected US-NNN pattern)":null},()=>{let m=c.get("Business Requirements");if(m){let p=m.match(/US-\d{3}/g);if(p)for(let g of p){let h=m.indexOf(g),y=m.indexOf("US-",h+1);if(!(y>0?m.substring(h,y):m.substring(h)).match(/Acceptance:/i))return`User Story ${g} missing Acceptance criterion`}}return null},()=>{let m=c.get("Technical Specification");return!m||m.trim().length===0?"Technical Specification section missing or empty":null},()=>{let m=c.get("Implementation Plan");return!m||m.trim().length===0?"Implementation Plan section missing or empty":null},()=>{let m=c.get("Implementation Plan");if(!m||m.trim().length===0)return"";let p=m.match(/UNIT-\d{3}/g);return!p||p.length===0?"No Proposed UNITs found (expected UNIT-NNN pattern)":null}];for(let m of u){let p=m();p!==null?p.trim().length>0&&n.push(p):l++}let f=Math.round(l/6*100);return{passed:n.length===0,coverage_percentage:f,blocking_issues:n,timestamp:t}}var ne=b(ue(),1),W=b(require("path"),1);var yn=b(ue(),1),Xu=b(require("path"),1),Sw=10;function Zu(e,t){let n=`u-${String(t).padStart(3,"0")}`;if(!e||!e.trim())return`${n}-untitled`;let o=e.toLowerCase().replace(/[_\s]+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"");return o?o.length>60?`${n}-${o.substring(0,60).replace(/-$/,"")}`:`${n}-${o}`:`${n}-untitled`}async function Bi(e){try{if(!await yn.default.pathExists(e))return[];let o=(await yn.default.readdir(e)).filter(i=>i.startsWith("INTENT-")&&i.endsWith(".md")),r=[];for(let i of o)try{let s=Xu.default.join(e,i),c=(await yn.default.readFile(s,"utf-8")).match(/^---\n([\s\S]*?)\n---/);if(!c){console.error(`No frontmatter found in ${i}`);continue}let u=c[1].split(`
827
+ `),d={};for(let m of u){let p=m.match(/^(\w+):\s*(.+)$/);if(p){let[,g,h]=p;h.startsWith("[")?d[g]=JSON.parse(h.replace(/'/g,'"')):isNaN(Number(h))?d[g]=h.trim():d[g]=Number(h)}}let f={id:d.id||i.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};r.push(f)}catch(s){console.error(`Failed to parse ${i}:`,s)}return r}catch(t){return console.error(`Failed to read intents from ${e}:`,t),[]}}async function qi(e){try{if(!await yn.default.pathExists(e))return null;let n=await yn.default.readFile(e,"utf-8"),o=[],r=n.match(/### Proposed UNITs\s*\n([\s\S]*?)(?=\n##[^#]|\n---|\Z|$)/);if(r){let i=r[1],s=/^-\s+\*\*([^*]+)\*\*:\s*(.+)$/gm,a,c=0;for(;(a=s.exec(i))!==null;){let l=a[1].trim(),u=a[2].trim(),d=Zu(l,c+1);o.push({id:d,title:l,description:u}),c++}}return{content:n,proposedUnits:o}}catch(t){return console.error(`Failed to parse intent from ${e}:`,t),null}}function Vi(e,t,n=Sw){let o=t;o.length>n&&(console.warn(`[decomposition] Unit specs (${o.length}) exceed maxUnits limit (${n}). Truncating to ${n}.`),o=o.slice(0,n));let r=[];for(let i=0;i<o.length;i++){let s=o[i],a=Zu(s.title,i+1),c={id:a,type:"unit",title:s.title,parent_id:e.id,children_ids:[],status:"pending",assigned_agent:null,estimated_effort:s.estimated_effort};r.push(c),e.children_ids.push(a)}return r}function Yi(e){let t=new Map;function n(o,r){t.set(o.id,o);for(let i of o.children_ids){let s=r.find(a=>a.id===i);s&&n(s,r)}}for(let o of e)t.set(o.id,o);return{roots:e,nodes:t}}var kn=b(ue(),1),wn=b(require("path"),1);function td(e,t){let n=[],o=1;for(let r of e){let i=At(r.title),s=_w(t,i),a=ed(s,"input"),c=ed(s,"output"),l=vw(r,e);n.push({id:`IFACE-${String(o++).padStart(3,"0")}`,unit_id:r.id,name:Tw(r.title),inputs:a,outputs:c,dependencies:l,description:`Interface contract for ${r.title}`})}return n}function nd(e,t){let n=[],o=1;for(let r of e){let i=t.filter(c=>c.unit_id===r.id),s=[],a=[];for(let c of i){s.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(bw(c)){let l=`STORE-${c.id}`;s.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(o++).padStart(3,"0")}`,unit_id:r.id,components:s,flows:a,description:`Data flow diagram for ${r.title}`})}return n}function od(e,t,n){let o=[],r=1;for(let i of e){let s=t.filter(u=>u.unit_id===i.id),a=n.find(u=>u.unit_id===i.id),c=a?a.components.filter(u=>u.type==="store").map(u=>u.name):[],l=Cw(i,s);o.push({id:`COMP-${String(r++).padStart(3,"0")}`,unit_id:i.id,name:Ew(i.title),responsibilities:l,interfaces_used:s.map(u=>u.id),data_stores:c,description:`Component design for ${i.title}`})}return o}function Ki(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 o=new Set(e.interfaces.map(a=>a.id));for(let a of e.components)for(let c of a.interfaces_used)o.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 r=Iw(t),i=Rw(e),s=Ow(r,i);return{passed:n.length===0,coverage_percentage:s,blocking_issues:n,reviewer:"design-validator",timestamp:new Date().toISOString()}}async function rd(e,t,n){let o=wn.default.join(e,"aidlc-docs",t,"construction","design");try{await kn.default.ensureDir(o),await kn.default.writeJson(wn.default.join(o,"interfaces.json"),n.interfaces,{spaces:2}),await kn.default.writeJson(wn.default.join(o,"data-flow.json"),n.dataFlows,{spaces:2}),await kn.default.writeJson(wn.default.join(o,"components.json"),n.components,{spaces:2});let r=Ki(n,"");await kn.default.writeJson(wn.default.join(o,"validation.json"),r,{spaces:2})}catch(r){throw console.error("Failed to write design artifacts:",r),r}}function At(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 _w(e,t){let n=e.split(`
828
828
  `),o=[];for(let r of n){let i=r.toLowerCase();t.some(s=>i.includes(s))&&o.push(r)}return o.join(`
829
- `)}function Xu(e,t){let n=[],o=/(\w+):\s*(\w+)/g,r;for(;(r=o.exec(e))!==null;)n.push({name:r[1],type:r[2],required:!0,description:`${t} field ${r[1]}`});return n}function Sw(e,t){let n=new Set(At(e.title)),o=[];for(let r of t){if(r.id===e.id)continue;At(r.title).filter(a=>n.has(a)).length>0&&o.push(r.id)}return o}function vw(e){return e.split(/\s+/).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")+"Interface"}function Tw(e){return e.split(/\s+/).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")+"Component"}function Ew(e){let t=["store","save","persist","database","repository"],n=e.name.toLowerCase();return t.some(o=>n.includes(o))}function bw(e,t){let n=[];n.push(`Implement ${e.title}`);for(let o of t)o.inputs.length>0&&n.push(`Process inputs for ${o.name}`),o.outputs.length>0&&n.push(`Generate outputs for ${o.name}`);return n}function Cw(e){return new Set(At(e))}function Iw(e){let t=new Set;for(let n of e.interfaces)At(n.name).forEach(o=>t.add(o)),At(n.description).forEach(o=>t.add(o));for(let n of e.components)At(n.name).forEach(o=>t.add(o)),At(n.description).forEach(o=>t.add(o));return t}function Rw(e,t){if(e.size===0)return 100;let n=0;for(let o of e)t.has(o)&&n++;return Math.round(n/e.size*100)}var Yt=require("fs"),Ki=require("path"),Ow=[1,2,4,8,16];function Aw(e){let t=e.match(/^---\n([\s\S]*?)\n---/);if(!t)return null;let n=t[1];try{let o={},r=n.split(`
830
- `);for(let i of r){let s=i.match(/^(\w+):\s*(.+)$/);if(s){let[,a,c]=s;o[a]=c.trim()}}return o}catch{return null}}function Pw(e){return e.replace(/^---\n[\s\S]*?\n---\n/,"")}function xw(e){let t=new Map,n=e.split(`
829
+ `)}function ed(e,t){let n=[],o=/(\w+):\s*(\w+)/g,r;for(;(r=o.exec(e))!==null;)n.push({name:r[1],type:r[2],required:!0,description:`${t} field ${r[1]}`});return n}function vw(e,t){let n=new Set(At(e.title)),o=[];for(let r of t){if(r.id===e.id)continue;At(r.title).filter(a=>n.has(a)).length>0&&o.push(r.id)}return o}function Tw(e){return e.split(/\s+/).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")+"Interface"}function Ew(e){return e.split(/\s+/).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")+"Component"}function bw(e){let t=["store","save","persist","database","repository"],n=e.name.toLowerCase();return t.some(o=>n.includes(o))}function Cw(e,t){let n=[];n.push(`Implement ${e.title}`);for(let o of t)o.inputs.length>0&&n.push(`Process inputs for ${o.name}`),o.outputs.length>0&&n.push(`Generate outputs for ${o.name}`);return n}function Iw(e){return new Set(At(e))}function Rw(e){let t=new Set;for(let n of e.interfaces)At(n.name).forEach(o=>t.add(o)),At(n.description).forEach(o=>t.add(o));for(let n of e.components)At(n.name).forEach(o=>t.add(o)),At(n.description).forEach(o=>t.add(o));return t}function Ow(e,t){if(e.size===0)return 100;let n=0;for(let o of e)t.has(o)&&n++;return Math.round(n/e.size*100)}var Yt=require("fs"),Ji=require("path"),Aw=[1,2,4,8,16];function Pw(e){let t=e.match(/^---\n([\s\S]*?)\n---/);if(!t)return null;let n=t[1];try{let o={},r=n.split(`
830
+ `);for(let i of r){let s=i.match(/^(\w+):\s*(.+)$/);if(s){let[,a,c]=s;o[a]=c.trim()}}return o}catch{return null}}function xw(e){return e.replace(/^---\n[\s\S]*?\n---\n/,"")}function $w(e){let t=new Map,n=e.split(`
831
831
  `),o=null,r=[];for(let i of n){let s=i.match(/^##\s+(.+)$/);s?(o&&t.set(o,r.join(`
832
832
  `)),o=s[1].trim(),r=[]):o&&r.push(i)}return o&&t.set(o,r.join(`
833
- `)),t}function $w(e){let t=e.split(`
834
- `),n=0;for(let o of t)o.trim().match(/^[-*+]\s+/)&&n++;return n}function Nw(e,t,n){let o=[],r=null,i=Aw(e);if(!i)return o.push(`${t}: Missing frontmatter`),{isValid:!1,blockingIssues:o,parentIntent:r};let s=["id","title","parent_intent","status","estimated_effort"],a=[];for(let h of s)i[h]||a.push(h);if(a.length>0)return o.push(`${t}: Missing frontmatter fields: ${a.join(", ")}`),{isValid:!1,blockingIssues:o,parentIntent:r};if(r=i.parent_intent,!n.has(r)&&!r.startsWith("intent-"))return o.push(`${t}: References non-existent parent intent: ${r}`),{isValid:!1,blockingIssues:o,parentIntent:r};let c=parseInt(i.estimated_effort,10);if(isNaN(c)||!Ow.includes(c))return o.push(`${t}: Invalid effort estimate ${i.estimated_effort} (must be 1, 2, 4, 8, or 16)`),{isValid:!1,blockingIssues:o,parentIntent:r};let l=Pw(e),u=xw(l),d=["Scope & Responsibility","Interface Contracts","Dependencies","Acceptance Criteria"],f=["Goal","Acceptance Criteria","Implementation Notes"],m=d.every(h=>u.has(h)),p=f.every(h=>u.has(h));if(!m&&!p){let h=d.filter(y=>!u.has(y));return o.push(`${t}: Missing sections: ${h.join(", ")}`),{isValid:!1,blockingIssues:o,parentIntent:r}}let g=u.get("Acceptance Criteria");if(g){if($w(g)===0)return o.push(`${t}: No acceptance criteria found`),{isValid:!1,blockingIssues:o,parentIntent:r}}else return o.push(`${t}: Acceptance Criteria section is empty`),{isValid:!1,blockingIssues:o,parentIntent:r};return{isValid:!0,blockingIssues:o,parentIntent:r}}async function Ji(e,t){let n=new Date().toISOString(),o=[],r;try{r=(0,Yt.readdirSync)(e,{withFileTypes:!0})}catch(p){let g=p;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 i=r.filter(p=>p.isDirectory()&&p.name!=="design"),s=r.filter(p=>p.isFile()&&p.name.endsWith(".md")&&p.name!=="design.md"),a=new Set,c=[];for(let p of i){let g=p.name,h=(0,Ki.join)(e,p.name,"spec.md");(0,Yt.existsSync)(h)&&(a.add(g),c.push({unitId:g,filePath:h}))}for(let p of s){let g=p.name.replace(".md","");a.has(g)||(a.add(g),c.push({unitId:g,filePath:(0,Ki.join)(e,p.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 p=(0,Yt.readdirSync)(t).filter(g=>g.startsWith("INTENT-")&&g.endsWith(".md"));l=new Set(p.map(g=>g.replace(".md","")))}catch(p){let g=p;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,f=c.length;for(let{unitId:p,filePath:g}of c){let h;try{h=(0,Yt.readFileSync)(g,"utf-8")}catch(w){let k=w;console.error(`[Validation] Failed to read unit file: ${k.message}`),console.error(`[Validation] Path: ${g}`);let A=k.code==="ENOENT"?`Unit file not found: ${p}`:k.code==="EACCES"||k.code==="EPERM"?`Permission denied reading unit file: ${p}`:`Failed to read unit file ${p}: ${k.message}`;o.push(A);continue}let y=Nw(h,p,l);o.push(...y.blockingIssues),y.parentIntent&&l.has(y.parentIntent)&&u.add(y.parentIntent),y.isValid&&d++}for(let p of l)u.has(p)||o.push(`Intent ${p} has no unit children`);let m=Math.round(d/f*100);return{passed:o.length===0&&d===f,coverage_percentage:m,blocking_issues:o,timestamp:n}}Ko();J();var er=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:o="MEDIUM",max_units:r=10,max_code_gen_per_unit:i=8,max_total_code_gen:s=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: ${o})`),o==="SHALLOW")return this.executeShallow();this.currentStage="unit";let l=await this.executeDecompositionPhase(r,i,s,o);if(!l.passed)return console.error("[ConstructionExecutor] Decomposition phase failed"),l;if(console.log("[ConstructionExecutor] Decomposition phase complete"),c)try{await c()}catch(d){console.error("[ConstructionExecutor] Checkpoint save callback failed:",d)}this.currentStage="design";let u=await this.executeDesignStage(t);return u.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"),u)}getProgress(){let t=0,n=0;if(this.tree)for(let s of this.tree.nodes.values())s.type==="unit"&&(t++,s.status==="complete"&&n++);let o=this.totalCodeGenerations,r=0,i=0;return this.currentStage==="unit"?i=t>0?Math.round(n/t*50):0:this.currentStage==="code-generation"?i=50+(o>0?Math.round(r/o*25):0):this.currentStage==="design"&&(i=100),{current_stage:this.currentStage,units_total:t,units_complete:n,code_gen_total:o,code_gen_complete:r,design_complete:this.currentStage==="design",overall_percentage:i}}getDecompositionSummary(){return{units:this.totalUnits,codeGenerations:this.totalCodeGenerations,totalEffort:this.totalEffort}}async executeCodeGenerationWithPlanApproval(t,n={}){let o=n.projectPath||this.projectPath,r=n.workflowId||this.workflowId,{buildCodePlanPath:i,dispatchCodeGeneration:s,buildCodeGenerationPrompt:a}=await Promise.resolve().then(()=>(Zo(),Xo)),c=i(o,r,t),l=await s(o,r,t),u=a(l.context.intentSummary2,l.context.intentSummary,l.context.unitSpec,c);return{status:"awaiting_code_plan_approval",codePlanPath:c,prompt:u}}async approveCodePlan(t,n){let{buildCodePlanPath:o,dispatchCodeGeneration:r,buildCodeGenerationPrompt:i}=await Promise.resolve().then(()=>(Zo(),Xo)),{addGateAuditEntry:s}=await Promise.resolve().then(()=>(J(),Vt)),a=o(this.projectPath,this.workflowId,t);if(!await ne.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=W.default.join(this.projectPath,"aidlc-docs",this.workflowId,"manifest.json");try{s(l,{phase:"construction",action:"approved",actor:"human",reason:n||`Code plan for ${t} approved by developer`})}catch(f){console.error(`[ConstructionExecutor] Failed to record gate audit for ${t}:`,f)}let u=await r(this.projectPath,this.workflowId,t);return{status:"executing_code_plan",prompt:i(u.context.intentSummary2,u.context.intentSummary,u.context.unitSpec)}}async autoApproveCodePlan(t,n){let{addGateAuditEntry:o}=await Promise.resolve().then(()=>(J(),Vt)),r=W.default.join(this.projectPath,"aidlc-docs",this.workflowId,"manifest.json"),i=n>=3;try{o(r,{phase:"construction",action:"approved",actor:"trust",reason:i?`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)}i||console.log(`[ConstructionExecutor] Code plan for ${t} auto-approved (trust level ${n})`);let{dispatchCodeGeneration:s,buildCodeGenerationPrompt:a}=await Promise.resolve().then(()=>(Zo(),Xo)),c=await s(this.projectPath,this.workflowId,t);return{status:"executing_code_plan",prompt:a(c.context.intentSummary2,c.context.intentSummary,c.context.unitSpec)}}async executeShallow(){let t=W.default.join(this.projectPath,"aidlc-docs",this.workflowId,"inception","intent.md"),n=W.default.join(this.projectPath,"aidlc-docs",this.workflowId,"construction"),o="Shallow Implementation",r=2,i="",s=await Bi(t);if(s){i=s.content;let d=i.match(/^title:\s*(.+)$/m);d&&(o=d[1].trim().replace(/^["']|["']$/g,""));let f=i.match(/^estimated_effort:\s*(\d+)/m);f&&(r=Number(f[1]))}else{let d=W.default.join(this.projectPath,"aidlc-docs",this.workflowId,"inception"),f=await Gi(d);if(f.length===0)return{passed:!1,coverage_percentage:0,blocking_issues:["No intent found for SHALLOW construction"],reviewer:"construction-executor",timestamp:new Date().toISOString()};o=f[0].title,r=f[0].estimated_effort}await ne.default.ensureDir(n);let a="shallow-impl",c=W.default.join(n,a);await ne.default.ensureDir(c);let l=new Date().toISOString(),u=this.formatUnitMarkdown({id:a,type:"unit",title:o,parent_id:null,children_ids:[],status:"pending",assigned_agent:null,estimated_effort:r},"none",i);return await ne.default.writeFile(W.default.join(c,"spec.md"),u,"utf-8"),this.registerConstructionArtifact(a,"unit","unit",W.default.join(c,"spec.md")),this.totalCodeGenerations=1,this.totalEffort=r,console.log("[ConstructionExecutor] SHALLOW mode: created single unit for code generation from INTENT"),{passed:!0,coverage_percentage:100,blocking_issues:[],reviewer:"construction-executor",timestamp:l}}async executeDecompositionPhase(t,n,o,r="MEDIUM"){let i=W.default.join(this.projectPath,"aidlc-docs",this.workflowId,"inception"),s=W.default.join(this.projectPath,"aidlc-docs",this.workflowId,"construction");await ne.default.ensureDir(s);let a=W.default.join(i,"intent.md"),c=await Bi(a),l=W.default.join(i,"intent.md"),u="";try{await ne.default.pathExists(l)&&(u=await ne.default.readFile(l,"utf-8"))}catch{}return c?this.executeDecompositionFromIntent(c,i,s,t,n,o,u,r):this.executeDecompositionFromLegacyIntents(i,s,t,n,o,u)}async executeDecompositionFromIntent(t,n,o,r,i,s,a,c="MEDIUM"){let l=t.content,u=l.match(/^title:\s*(.+)$/m),d=l.match(/^estimated_effort:\s*(\d+)/m),f=u?u[1].trim().replace(/^["']|["']$/g,""):"Untitled Intent",m=d?Number(d[1]):0,p="INTENT-001",g={id:p,type:"intent",title:f,parent_id:null,children_ids:[],status:"pending",assigned_agent:null,estimated_effort:m},h=`---
833
+ `)),t}function Nw(e){let t=e.split(`
834
+ `),n=0;for(let o of t)o.trim().match(/^[-*+]\s+/)&&n++;return n}function Dw(e,t,n){let o=[],r=null,i=Pw(e);if(!i)return o.push(`${t}: Missing frontmatter`),{isValid:!1,blockingIssues:o,parentIntent:r};let s=["id","title","parent_intent","status","estimated_effort"],a=[];for(let h of s)i[h]||a.push(h);if(a.length>0)return o.push(`${t}: Missing frontmatter fields: ${a.join(", ")}`),{isValid:!1,blockingIssues:o,parentIntent:r};if(r=i.parent_intent,!n.has(r)&&!r.startsWith("intent-"))return o.push(`${t}: References non-existent parent intent: ${r}`),{isValid:!1,blockingIssues:o,parentIntent:r};let c=parseInt(i.estimated_effort,10);if(isNaN(c)||!Aw.includes(c))return o.push(`${t}: Invalid effort estimate ${i.estimated_effort} (must be 1, 2, 4, 8, or 16)`),{isValid:!1,blockingIssues:o,parentIntent:r};let l=xw(e),u=$w(l),d=["Scope & Responsibility","Interface Contracts","Dependencies","Acceptance Criteria"],f=["Goal","Acceptance Criteria","Implementation Notes"],m=d.every(h=>u.has(h)),p=f.every(h=>u.has(h));if(!m&&!p){let h=d.filter(y=>!u.has(y));return o.push(`${t}: Missing sections: ${h.join(", ")}`),{isValid:!1,blockingIssues:o,parentIntent:r}}let g=u.get("Acceptance Criteria");if(g){if(Nw(g)===0)return o.push(`${t}: No acceptance criteria found`),{isValid:!1,blockingIssues:o,parentIntent:r}}else return o.push(`${t}: Acceptance Criteria section is empty`),{isValid:!1,blockingIssues:o,parentIntent:r};return{isValid:!0,blockingIssues:o,parentIntent:r}}async function zi(e,t){let n=new Date().toISOString(),o=[],r;try{r=(0,Yt.readdirSync)(e,{withFileTypes:!0})}catch(p){let g=p;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 i=r.filter(p=>p.isDirectory()&&p.name!=="design"),s=r.filter(p=>p.isFile()&&p.name.endsWith(".md")&&p.name!=="design.md"),a=new Set,c=[];for(let p of i){let g=p.name,h=(0,Ji.join)(e,p.name,"spec.md");(0,Yt.existsSync)(h)&&(a.add(g),c.push({unitId:g,filePath:h}))}for(let p of s){let g=p.name.replace(".md","");a.has(g)||(a.add(g),c.push({unitId:g,filePath:(0,Ji.join)(e,p.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 p=(0,Yt.readdirSync)(t).filter(g=>g.startsWith("INTENT-")&&g.endsWith(".md"));l=new Set(p.map(g=>g.replace(".md","")))}catch(p){let g=p;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,f=c.length;for(let{unitId:p,filePath:g}of c){let h;try{h=(0,Yt.readFileSync)(g,"utf-8")}catch(w){let k=w;console.error(`[Validation] Failed to read unit file: ${k.message}`),console.error(`[Validation] Path: ${g}`);let A=k.code==="ENOENT"?`Unit file not found: ${p}`:k.code==="EACCES"||k.code==="EPERM"?`Permission denied reading unit file: ${p}`:`Failed to read unit file ${p}: ${k.message}`;o.push(A);continue}let y=Dw(h,p,l);o.push(...y.blockingIssues),y.parentIntent&&l.has(y.parentIntent)&&u.add(y.parentIntent),y.isValid&&d++}for(let p of l)u.has(p)||o.push(`Intent ${p} has no unit children`);let m=Math.round(d/f*100);return{passed:o.length===0&&d===f,coverage_percentage:m,blocking_issues:o,timestamp:n}}Jo();J();var tr=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:o="MEDIUM",max_units:r=10,max_code_gen_per_unit:i=8,max_total_code_gen:s=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: ${o})`),o==="SHALLOW")return this.executeShallow();this.currentStage="unit";let l=await this.executeDecompositionPhase(r,i,s,o);if(!l.passed)return console.error("[ConstructionExecutor] Decomposition phase failed"),l;if(console.log("[ConstructionExecutor] Decomposition phase complete"),c)try{await c()}catch(d){console.error("[ConstructionExecutor] Checkpoint save callback failed:",d)}this.currentStage="design";let u=await this.executeDesignStage(t);return u.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"),u)}getProgress(){let t=0,n=0;if(this.tree)for(let s of this.tree.nodes.values())s.type==="unit"&&(t++,s.status==="complete"&&n++);let o=this.totalCodeGenerations,r=0,i=0;return this.currentStage==="unit"?i=t>0?Math.round(n/t*50):0:this.currentStage==="code-generation"?i=50+(o>0?Math.round(r/o*25):0):this.currentStage==="design"&&(i=100),{current_stage:this.currentStage,units_total:t,units_complete:n,code_gen_total:o,code_gen_complete:r,design_complete:this.currentStage==="design",overall_percentage:i}}getDecompositionSummary(){return{units:this.totalUnits,codeGenerations:this.totalCodeGenerations,totalEffort:this.totalEffort}}async executeCodeGenerationWithPlanApproval(t,n={}){let o=n.projectPath||this.projectPath,r=n.workflowId||this.workflowId,{buildCodePlanPath:i,dispatchCodeGeneration:s,buildCodeGenerationPrompt:a}=await Promise.resolve().then(()=>(er(),Zo)),c=i(o,r,t),l=await s(o,r,t),u=a(l.context.intentSummary2,l.context.intentSummary,l.context.unitSpec,c);return{status:"awaiting_code_plan_approval",codePlanPath:c,prompt:u}}async approveCodePlan(t,n){let{buildCodePlanPath:o,dispatchCodeGeneration:r,buildCodeGenerationPrompt:i}=await Promise.resolve().then(()=>(er(),Zo)),{addGateAuditEntry:s}=await Promise.resolve().then(()=>(J(),Vt)),a=o(this.projectPath,this.workflowId,t);if(!await ne.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=W.default.join(this.projectPath,"aidlc-docs",this.workflowId,"manifest.json");try{s(l,{phase:"construction",action:"approved",actor:"human",reason:n||`Code plan for ${t} approved by developer`})}catch(f){console.error(`[ConstructionExecutor] Failed to record gate audit for ${t}:`,f)}let u=await r(this.projectPath,this.workflowId,t);return{status:"executing_code_plan",prompt:i(u.context.intentSummary2,u.context.intentSummary,u.context.unitSpec)}}async autoApproveCodePlan(t,n){let{addGateAuditEntry:o}=await Promise.resolve().then(()=>(J(),Vt)),r=W.default.join(this.projectPath,"aidlc-docs",this.workflowId,"manifest.json"),i=n>=3;try{o(r,{phase:"construction",action:"approved",actor:"trust",reason:i?`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)}i||console.log(`[ConstructionExecutor] Code plan for ${t} auto-approved (trust level ${n})`);let{dispatchCodeGeneration:s,buildCodeGenerationPrompt:a}=await Promise.resolve().then(()=>(er(),Zo)),c=await s(this.projectPath,this.workflowId,t);return{status:"executing_code_plan",prompt:a(c.context.intentSummary2,c.context.intentSummary,c.context.unitSpec)}}async executeShallow(){let t=W.default.join(this.projectPath,"aidlc-docs",this.workflowId,"inception","intent.md"),n=W.default.join(this.projectPath,"aidlc-docs",this.workflowId,"construction"),o="Shallow Implementation",r=2,i="",s=await qi(t);if(s){i=s.content;let d=i.match(/^title:\s*(.+)$/m);d&&(o=d[1].trim().replace(/^["']|["']$/g,""));let f=i.match(/^estimated_effort:\s*(\d+)/m);f&&(r=Number(f[1]))}else{let d=W.default.join(this.projectPath,"aidlc-docs",this.workflowId,"inception"),f=await Bi(d);if(f.length===0)return{passed:!1,coverage_percentage:0,blocking_issues:["No intent found for SHALLOW construction"],reviewer:"construction-executor",timestamp:new Date().toISOString()};o=f[0].title,r=f[0].estimated_effort}await ne.default.ensureDir(n);let a="shallow-impl",c=W.default.join(n,a);await ne.default.ensureDir(c);let l=new Date().toISOString(),u=this.formatUnitMarkdown({id:a,type:"unit",title:o,parent_id:null,children_ids:[],status:"pending",assigned_agent:null,estimated_effort:r},"none",i);return await ne.default.writeFile(W.default.join(c,"spec.md"),u,"utf-8"),this.registerConstructionArtifact(a,"unit","unit",W.default.join(c,"spec.md")),this.totalCodeGenerations=1,this.totalEffort=r,console.log("[ConstructionExecutor] SHALLOW mode: created single unit for code generation from INTENT"),{passed:!0,coverage_percentage:100,blocking_issues:[],reviewer:"construction-executor",timestamp:l}}async executeDecompositionPhase(t,n,o,r="MEDIUM"){let i=W.default.join(this.projectPath,"aidlc-docs",this.workflowId,"inception"),s=W.default.join(this.projectPath,"aidlc-docs",this.workflowId,"construction");await ne.default.ensureDir(s);let a=W.default.join(i,"intent.md"),c=await qi(a),l=W.default.join(i,"intent.md"),u="";try{await ne.default.pathExists(l)&&(u=await ne.default.readFile(l,"utf-8"))}catch{}return c?this.executeDecompositionFromIntent(c,i,s,t,n,o,u,r):this.executeDecompositionFromLegacyIntents(i,s,t,n,o,u)}async executeDecompositionFromIntent(t,n,o,r,i,s,a,c="MEDIUM"){let l=t.content,u=l.match(/^title:\s*(.+)$/m),d=l.match(/^estimated_effort:\s*(\d+)/m),f=u?u[1].trim().replace(/^["']|["']$/g,""):"Untitled Intent",m=d?Number(d[1]):0,p="INTENT-001",g={id:p,type:"intent",title:f,parent_id:null,children_ids:[],status:"pending",assigned_agent:null,estimated_effort:m},h=`---
835
835
  id: ${p}
836
836
  title: ${f}
837
837
  status: pending
@@ -855,7 +855,7 @@ Auto-generated
855
855
 
856
856
  ## Technical Notes
857
857
  Generated from inception/intent.md
858
- `;await ne.default.writeFile(W.default.join(n,`${p}.md`),h,"utf-8");let y=t.proposedUnits.map(v=>({title:v.title,estimated_effort:Math.ceil(m/Math.max(t.proposedUnits.length,1)),description:v.description}));y.length===0&&y.push({title:f,estimated_effort:m,description:`Implementation unit for ${f}`});let w=qi(g,y,r),k=[];for(let v of w){let R=W.default.join(o,v.id);await ne.default.ensureDir(R);let C=this.formatUnitMarkdown(v,g.id,l);await ne.default.writeFile(W.default.join(R,"spec.md"),C,"utf-8"),await ne.default.writeFile(W.default.join(o,`${v.id}.md`),C,"utf-8"),this.registerConstructionArtifact(v.id,"unit","unit",W.default.join(R,"spec.md")),this.linkConstructionArtifacts(p,v.id,"derives"),this.runUnitValidation(C,l,a,g.id,v.id);try{let{UnitStageRunner:Z}=await Promise.resolve().then(()=>(fd(),pd));await new Z(this.projectPath,this.workflowId).executeForUnit(v.id,c,a)}catch(Z){console.error(`[ConstructionExecutor] Unit stage runner failed for ${v.id}:`,Z)}}this.tree=Vi([g]);for(let v of w)this.tree.nodes.set(v.id,v);this.totalUnits=w.length,this.totalCodeGenerations=w.length,this.totalEffort=w.reduce((v,R)=>v+R.estimated_effort,0),console.log(`[ConstructionExecutor] Created ${w.length} units for code generation`);let A=await Ji(o,n);return A.passed?k.length>0?{passed:!1,coverage_percentage:0,blocking_issues:k,reviewer:"construction-executor",timestamp:new Date().toISOString()}:{passed:!0,coverage_percentage:100,blocking_issues:[],reviewer:"construction-executor",timestamp:new Date().toISOString()}:A}async executeDecompositionFromLegacyIntents(t,n,o,r,i,s){let a=await Gi(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 m=(await ne.default.readdir(t)).find(p=>p.startsWith("INTENT-")&&p.endsWith(".md"));m&&(c=await ne.default.readFile(W.default.join(t,m),"utf-8"))}catch{}let l=[],u=[];for(let f of a){let m=[{title:f.title,estimated_effort:f.estimated_effort,description:`Implementation unit for ${f.title}`}],p=qi(f,m,o);l.push(...p);for(let g of p){let h=W.default.join(n,`${g.id}.md`),y=this.formatUnitMarkdown(g,f.id);await ne.default.writeFile(h,y,"utf-8");let w=W.default.join(n,g.id);await ne.default.ensureDir(w),await ne.default.writeFile(W.default.join(w,"spec.md"),y,"utf-8"),this.registerConstructionArtifact(g.id,"unit","unit",W.default.join(w,"spec.md")),this.linkConstructionArtifacts(f.id,g.id,"derives"),this.runUnitValidation(y,c,s,f.id,g.id)}}console.log(`[ConstructionExecutor] Created ${l.length} units for code generation`),this.tree=Vi(a);for(let f of l)this.tree.nodes.set(f.id,f);this.totalUnits=l.length,this.totalCodeGenerations=l.length,this.totalEffort=l.reduce((f,m)=>f+m.estimated_effort,0);let d=await Ji(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=W.default.join(this.projectPath,"aidlc-docs",this.workflowId,"construction"),o=await ne.default.readdir(n,{withFileTypes:!0}),r=[];for(let l of o)if(l.isDirectory()&&l.name!=="design"){let u=W.default.join(n,l.name,"spec.md");if(await ne.default.pathExists(u)){let d=await ne.default.readFile(u,"utf-8"),f=this.parseUnitFromMarkdown(d,l.name);f&&r.push(f)}}else if(l.isFile()&&l.name.endsWith(".md")&&l.name!=="design"){let u=W.default.join(n,l.name),d=await ne.default.readFile(u,"utf-8"),f=this.parseUnitFromMarkdown(d,l.name.replace(".md",""));f&&r.push(f)}if(r.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 ${r.length} units`);let i=Zu(r,t||""),s=ed(r,i),a=td(r,i,s);await nd(this.projectPath,this.workflowId,{interfaces:i,dataFlows:s,components:a});let c=W.default.join(this.projectPath,"aidlc-docs",this.workflowId,"construction","design");return this.registerConstructionArtifact("design-interfaces","interface-contracts","unit",W.default.join(c,"interfaces.json")),this.registerConstructionArtifact("design-data-flow","data-flow-diagram","unit",W.default.join(c,"data-flow.json")),this.registerConstructionArtifact("design-components","component-design","unit",W.default.join(c,"components.json")),t?Yi({interfaces:i,dataFlows:s,components:a},t):{passed:!0,coverage_percentage:100,blocking_issues:[],reviewer:"construction-executor",timestamp:new Date().toISOString()}}runUnitValidation(t,n,o,r,i){if(!(!n||!o))try{let s=gn(t,n,o,"intent-to-unit","unit-to-intent",r,i,`intent-${this.workflowId}`);s.passed||console.warn(`[ConstructionExecutor] Dual validation warning for ${i}: parent=${s.parentCheck.alignment_passed}, root=${s.rootCheck.alignment_passed}`)}catch(s){console.error(`[ConstructionExecutor] Dual validation error for ${i}:`,s)}}registerConstructionArtifact(t,n,o,r){try{let i=W.default.join(this.projectPath,"aidlc-docs",this.workflowId,"manifest.json");Pe(i,{id:t,type:n,phase:"construction",stage:o,path:r,validation_passed:null,write_complete:!0,checksum:null})}catch(i){console.error(`[ConstructionExecutor] Failed to register artifact ${t}:`,i)}}linkConstructionArtifacts(t,n,o){try{let r=W.default.join(this.projectPath,"aidlc-docs",this.workflowId,"manifest.json");Mi(r,{source_id:t,target_id:n,link_type:o})}catch(r){console.error(`[ConstructionExecutor] Failed to link ${t} -> ${n}:`,r)}}formatUnitMarkdown(t,n,o){let r=new Date().toISOString();return`---
858
+ `;await ne.default.writeFile(W.default.join(n,`${p}.md`),h,"utf-8");let y=t.proposedUnits.map(v=>({title:v.title,estimated_effort:Math.ceil(m/Math.max(t.proposedUnits.length,1)),description:v.description}));y.length===0&&y.push({title:f,estimated_effort:m,description:`Implementation unit for ${f}`});let w=Vi(g,y,r),k=[];for(let v of w){let R=W.default.join(o,v.id);await ne.default.ensureDir(R);let I=this.formatUnitMarkdown(v,g.id,l);await ne.default.writeFile(W.default.join(R,"spec.md"),I,"utf-8"),await ne.default.writeFile(W.default.join(o,`${v.id}.md`),I,"utf-8"),this.registerConstructionArtifact(v.id,"unit","unit",W.default.join(R,"spec.md")),this.linkConstructionArtifacts(p,v.id,"derives"),this.runUnitValidation(I,l,a,g.id,v.id);try{let{UnitStageRunner:Z}=await Promise.resolve().then(()=>(gd(),md));await new Z(this.projectPath,this.workflowId).executeForUnit(v.id,c,a)}catch(Z){console.error(`[ConstructionExecutor] Unit stage runner failed for ${v.id}:`,Z)}}this.tree=Yi([g]);for(let v of w)this.tree.nodes.set(v.id,v);this.totalUnits=w.length,this.totalCodeGenerations=w.length,this.totalEffort=w.reduce((v,R)=>v+R.estimated_effort,0),console.log(`[ConstructionExecutor] Created ${w.length} units for code generation`);let A=await zi(o,n);return A.passed?k.length>0?{passed:!1,coverage_percentage:0,blocking_issues:k,reviewer:"construction-executor",timestamp:new Date().toISOString()}:{passed:!0,coverage_percentage:100,blocking_issues:[],reviewer:"construction-executor",timestamp:new Date().toISOString()}:A}async executeDecompositionFromLegacyIntents(t,n,o,r,i,s){let a=await Bi(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 m=(await ne.default.readdir(t)).find(p=>p.startsWith("INTENT-")&&p.endsWith(".md"));m&&(c=await ne.default.readFile(W.default.join(t,m),"utf-8"))}catch{}let l=[],u=[];for(let f of a){let m=[{title:f.title,estimated_effort:f.estimated_effort,description:`Implementation unit for ${f.title}`}],p=Vi(f,m,o);l.push(...p);for(let g of p){let h=W.default.join(n,`${g.id}.md`),y=this.formatUnitMarkdown(g,f.id);await ne.default.writeFile(h,y,"utf-8");let w=W.default.join(n,g.id);await ne.default.ensureDir(w),await ne.default.writeFile(W.default.join(w,"spec.md"),y,"utf-8"),this.registerConstructionArtifact(g.id,"unit","unit",W.default.join(w,"spec.md")),this.linkConstructionArtifacts(f.id,g.id,"derives"),this.runUnitValidation(y,c,s,f.id,g.id)}}console.log(`[ConstructionExecutor] Created ${l.length} units for code generation`),this.tree=Yi(a);for(let f of l)this.tree.nodes.set(f.id,f);this.totalUnits=l.length,this.totalCodeGenerations=l.length,this.totalEffort=l.reduce((f,m)=>f+m.estimated_effort,0);let d=await zi(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=W.default.join(this.projectPath,"aidlc-docs",this.workflowId,"construction"),o=await ne.default.readdir(n,{withFileTypes:!0}),r=[];for(let l of o)if(l.isDirectory()&&l.name!=="design"){let u=W.default.join(n,l.name,"spec.md");if(await ne.default.pathExists(u)){let d=await ne.default.readFile(u,"utf-8"),f=this.parseUnitFromMarkdown(d,l.name);f&&r.push(f)}}else if(l.isFile()&&l.name.endsWith(".md")&&l.name!=="design"){let u=W.default.join(n,l.name),d=await ne.default.readFile(u,"utf-8"),f=this.parseUnitFromMarkdown(d,l.name.replace(".md",""));f&&r.push(f)}if(r.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 ${r.length} units`);let i=td(r,t||""),s=nd(r,i),a=od(r,i,s);await rd(this.projectPath,this.workflowId,{interfaces:i,dataFlows:s,components:a});let c=W.default.join(this.projectPath,"aidlc-docs",this.workflowId,"construction","design");return this.registerConstructionArtifact("design-interfaces","interface-contracts","unit",W.default.join(c,"interfaces.json")),this.registerConstructionArtifact("design-data-flow","data-flow-diagram","unit",W.default.join(c,"data-flow.json")),this.registerConstructionArtifact("design-components","component-design","unit",W.default.join(c,"components.json")),t?Ki({interfaces:i,dataFlows:s,components:a},t):{passed:!0,coverage_percentage:100,blocking_issues:[],reviewer:"construction-executor",timestamp:new Date().toISOString()}}runUnitValidation(t,n,o,r,i){if(!(!n||!o))try{let s=gn(t,n,o,"intent-to-unit","unit-to-intent",r,i,`intent-${this.workflowId}`);s.passed||console.warn(`[ConstructionExecutor] Dual validation warning for ${i}: parent=${s.parentCheck.alignment_passed}, root=${s.rootCheck.alignment_passed}`)}catch(s){console.error(`[ConstructionExecutor] Dual validation error for ${i}:`,s)}}registerConstructionArtifact(t,n,o,r){try{let i=W.default.join(this.projectPath,"aidlc-docs",this.workflowId,"manifest.json");xe(i,{id:t,type:n,phase:"construction",stage:o,path:r,validation_passed:null,write_complete:!0,checksum:null})}catch(i){console.error(`[ConstructionExecutor] Failed to register artifact ${t}:`,i)}}linkConstructionArtifacts(t,n,o){try{let r=W.default.join(this.projectPath,"aidlc-docs",this.workflowId,"manifest.json");Li(r,{source_id:t,target_id:n,link_type:o})}catch(r){console.error(`[ConstructionExecutor] Failed to link ${t} -> ${n}:`,r)}}formatUnitMarkdown(t,n,o){let r=new Date().toISOString();return`---
859
859
  id: ${t.id}
860
860
  title: ${t.title}
861
861
  parent_intent: ${n}
@@ -906,16 +906,16 @@ Implementation details for ${t.title}.
906
906
  - Parent INTENT: ${n} (inception/intent.md)
907
907
  - Root INTENT: intent-${this.workflowId} (inception/intent.md)
908
908
  `}parseUnitFromMarkdown(t,n){try{let o=t.match(/^---\n([\s\S]*?)\n---/);if(!o)return null;let i=o[1].split(`
909
- `),s={};for(let a of i){let c=a.match(/^(\w+):\s*(.+)$/);if(c){let[,l,u]=c,d=u.trim().replace(/^["']|["']$/g,"");isNaN(Number(d))?s[l]=d:s[l]=Number(d)}}return{id:n,type:"unit",title:s.title||"Untitled Unit",parent_id:s.parent_intent||null,children_ids:[],status:s.status||"pending",assigned_agent:s.assigned_agent||null,estimated_effort:s.estimated_effort||0}}catch(o){return console.error("Failed to parse unit from markdown:",o),null}}};or();var xd=require("crypto"),e_={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 xe(e,t){let n=e_[e.type],o=e.timestamp??new Date().toISOString(),r=t_(e.type),i=n_(e).slice(0,100),s=o_(e,t);return{id:(0,xd.randomUUID)(),timestamp:o,session_id:t.sessionId,project_path:t.projectPath,category:n,summary:i,details:s,agent_name:e.agentName??"workflow-engine",task_context:`${t.featureName} (${e.phase}${e.stage?"/"+e.stage:""})`,files_involved:e.artifactId?[`${e.artifactId}`]:[],confidence:r,verified:e.type==="gate_approval"||e.type==="phase_complete"||e.type==="bolt_execution_complete",verification_count:0,scope:"project",last_useful:o}}function t_(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 n_(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 o_(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(`
910
- `)}pt();ns();function En(e){return Math.max(1,Math.min(5,Math.round(e)))}function f_(e){let t=En(e.clarity),n=En(e.complexity),o=En(e.scope),r=En(e.risk),i=En(e.context),s=En(e.preferences),a=t+n+o+r+i+s,c;a<=10?c="minimal":a<=20?c="standard":c="comprehensive";let l=a<=10,u=m_(r,n,o),d=Fd(u);return{clarity:t,complexity:n,scope:o,risk:r,context:i,preferences:s,total_score:a,recommended_depth:c,skip_units:l,risk_tier:d}}function m_(e,t,n){let o;e>=4?o="difficult":e>=3?o="moderate":o="easy";let r;n>=4?r="system-wide":n>=3?r="cross-cutting":r="isolated";let i;e>=4&&t>=3?i="user-facing":e>=3?i="internal":i="none";let s;return e>=5?s="major":e>=4?s="minor":s="none",{reversibility:o,blast_radius:r,data_sensitivity:i,compliance_impact:s}}function Fd(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,o=e.data_sensitivity==="none"?1:e.data_sensitivity==="internal"?2:3,r=e.compliance_impact==="none"?1:e.compliance_impact==="minor"?2:3,i=t+n+o+r,s;i<=6?s=1:i<=9?s=2:s=3;let a=g_(s,e);return{tier:s,rationale:a,factors:e,override_reason:null}}function g_(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 lr(e){let t=h_(e),n=y_(t),o=k_(t),r=w_(t),i=__(t),s=S_(t),a=v_(t),c=T_(e,t),u=f_({clarity:n,complexity:o,scope:r,risk:i,context:s,preferences:a}),d=Fd(c);return u.risk_tier=d,u}function h_(e){let t={problemStatement:"",userPersonas:"",businessConstraints:"",successMetrics:"",outOfScope:""},n=/^## (.+)$/gm,o=[],r=0,i;for(;(i=n.exec(e))!==null;)o.length>0&&(o[o.length-1].content=e.substring(r,i.index).trim()),o.push({title:i[1].trim(),content:""}),r=i.index+i[0].length;o.length>0&&(o[o.length-1].content=e.substring(r).trim());for(let s of o){let a=s.title.toLowerCase();a.includes("problem")||a.includes("statement")?t.problemStatement=s.content:a.includes("persona")||a.includes("user persona")?t.userPersonas=s.content:a.includes("business constraint")||a.includes("constraint")?t.businessConstraints=s.content:a.includes("success")||a.includes("metric")?t.successMetrics=s.content:(a.includes("out of scope")||a.includes("scope"))&&(t.outOfScope=s.content)}return t}function y_(e){let t=e.problemStatement.length+e.userPersonas.length;return t>1e3?1:t>500?2:t>250?3:t>100?4:5}function k_(e){let t=(e.userPersonas.match(/^[-*+]\s/gm)||[]).length,o=["component","service","module","layer","system","integration","api"].filter(i=>e.userPersonas.toLowerCase().includes(i)).length,r=t+o;return r>=10?5:r>=7?4:r>=4?3:r>=2?2:1}function w_(e){let t=(e.businessConstraints.match(/^[-*+]\s/gm)||[]).length,n=(e.successMetrics.match(/^[-*+]\s/gm)||[]).length,o=t+n;return o>=10?5:o>=7?4:o>=4?3:o>=2?2:1}function __(e){let t=["security","compliance","data","migration","breaking","irreversible","pii","gdpr","authentication","payment","infrastructure","system-wide","critical"],o=(e.businessConstraints+e.userPersonas).toLowerCase(),r=t.filter(i=>o.includes(i)).length;return r>=5?5:r>=3?4:r>=2?3:r>=1?2:1}function S_(e){let t=e.outOfScope.length;return t>500?1:t>300?2:t>150?3:t>50?4:5}function v_(e){let t=["must","should","could","prefer","optional","required","nice to have"],o=(e.businessConstraints+e.userPersonas).toLowerCase(),r=t.filter(i=>o.includes(i)).length;return r>=8?5:r>=5?4:r>=3?3:r>=2?2:1}function T_(e,t){let n=e.toLowerCase(),o="moderate";n.includes("irreversible")||n.includes("migration")||n.includes("data loss")||n.includes("breaking change")?o="difficult":(n.includes("refactor")||n.includes("new feature")||n.includes("additive"))&&(o="easy");let r="isolated";n.includes("system-wide")||n.includes("all users")||n.includes("infrastructure")||n.includes("platform")?r="system-wide":(n.includes("cross-cutting")||n.includes("multiple")||n.includes("shared"))&&(r="cross-cutting");let i="none";n.includes("pii")||n.includes("personal")||n.includes("authentication")||n.includes("payment")||n.includes("user data")||n.includes("sensitive")?i="user-facing":(n.includes("internal")||n.includes("logging")||n.includes("metrics")||n.includes("telemetry"))&&(i="internal");let s="none";return n.includes("gdpr")||n.includes("soc")||n.includes("hipaa")||n.includes("compliance")||n.includes("regulatory")?s="major":(n.includes("audit")||n.includes("policy"))&&(s="minor"),{reversibility:o,blast_radius:r,data_sensitivity:i,compliance_impact:s}}J();var Ud=require("fs"),E_=require("path"),b_=require("os"),ur="<!-- AIDLC-RULES-START -->",bn="<!-- AIDLC-RULES-END -->";function Wd(e){return e.includes(ur)&&e.includes(bn)}function Hd(e,t){let n=`${ur}
909
+ `),s={};for(let a of i){let c=a.match(/^(\w+):\s*(.+)$/);if(c){let[,l,u]=c,d=u.trim().replace(/^["']|["']$/g,"");isNaN(Number(d))?s[l]=d:s[l]=Number(d)}}return{id:n,type:"unit",title:s.title||"Untitled Unit",parent_id:s.parent_intent||null,children_ids:[],status:s.status||"pending",assigned_agent:s.assigned_agent||null,estimated_effort:s.estimated_effort||0}}catch(o){return console.error("Failed to parse unit from markdown:",o),null}}};rr();var Nd=require("crypto"),tS={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 $e(e,t){let n=tS[e.type],o=e.timestamp??new Date().toISOString(),r=nS(e.type),i=oS(e).slice(0,100),s=rS(e,t);return{id:(0,Nd.randomUUID)(),timestamp:o,session_id:t.sessionId,project_path:t.projectPath,category:n,summary:i,details:s,agent_name:e.agentName??"workflow-engine",task_context:`${t.featureName} (${e.phase}${e.stage?"/"+e.stage:""})`,files_involved:e.artifactId?[`${e.artifactId}`]:[],confidence:r,verified:e.type==="gate_approval"||e.type==="phase_complete"||e.type==="bolt_execution_complete",verification_count:0,scope:"project",last_useful:o}}function nS(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 oS(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 rS(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(`
910
+ `)}pt();os();function En(e){return Math.max(1,Math.min(5,Math.round(e)))}function mS(e){let t=En(e.clarity),n=En(e.complexity),o=En(e.scope),r=En(e.risk),i=En(e.context),s=En(e.preferences),a=t+n+o+r+i+s,c;a<=10?c="minimal":a<=20?c="standard":c="comprehensive";let l=a<=10,u=gS(r,n,o),d=Wd(u);return{clarity:t,complexity:n,scope:o,risk:r,context:i,preferences:s,total_score:a,recommended_depth:c,skip_units:l,risk_tier:d}}function gS(e,t,n){let o;e>=4?o="difficult":e>=3?o="moderate":o="easy";let r;n>=4?r="system-wide":n>=3?r="cross-cutting":r="isolated";let i;e>=4&&t>=3?i="user-facing":e>=3?i="internal":i="none";let s;return e>=5?s="major":e>=4?s="minor":s="none",{reversibility:o,blast_radius:r,data_sensitivity:i,compliance_impact:s}}function Wd(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,o=e.data_sensitivity==="none"?1:e.data_sensitivity==="internal"?2:3,r=e.compliance_impact==="none"?1:e.compliance_impact==="minor"?2:3,i=t+n+o+r,s;i<=6?s=1:i<=9?s=2:s=3;let a=hS(s,e);return{tier:s,rationale:a,factors:e,override_reason:null}}function hS(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 ur(e){let t=yS(e),n=kS(t),o=wS(t),r=SS(t),i=_S(t),s=vS(t),a=TS(t),c=ES(e,t),u=mS({clarity:n,complexity:o,scope:r,risk:i,context:s,preferences:a}),d=Wd(c);return u.risk_tier=d,u}function yS(e){let t={problemStatement:"",userPersonas:"",businessConstraints:"",successMetrics:"",outOfScope:""},n=/^## (.+)$/gm,o=[],r=0,i;for(;(i=n.exec(e))!==null;)o.length>0&&(o[o.length-1].content=e.substring(r,i.index).trim()),o.push({title:i[1].trim(),content:""}),r=i.index+i[0].length;o.length>0&&(o[o.length-1].content=e.substring(r).trim());for(let s of o){let a=s.title.toLowerCase();a.includes("problem")||a.includes("statement")?t.problemStatement=s.content:a.includes("persona")||a.includes("user persona")?t.userPersonas=s.content:a.includes("business constraint")||a.includes("constraint")?t.businessConstraints=s.content:a.includes("success")||a.includes("metric")?t.successMetrics=s.content:(a.includes("out of scope")||a.includes("scope"))&&(t.outOfScope=s.content)}return t}function kS(e){let t=e.problemStatement.length+e.userPersonas.length;return t>1e3?1:t>500?2:t>250?3:t>100?4:5}function wS(e){let t=(e.userPersonas.match(/^[-*+]\s/gm)||[]).length,o=["component","service","module","layer","system","integration","api"].filter(i=>e.userPersonas.toLowerCase().includes(i)).length,r=t+o;return r>=10?5:r>=7?4:r>=4?3:r>=2?2:1}function SS(e){let t=(e.businessConstraints.match(/^[-*+]\s/gm)||[]).length,n=(e.successMetrics.match(/^[-*+]\s/gm)||[]).length,o=t+n;return o>=10?5:o>=7?4:o>=4?3:o>=2?2:1}function _S(e){let t=["security","compliance","data","migration","breaking","irreversible","pii","gdpr","authentication","payment","infrastructure","system-wide","critical"],o=(e.businessConstraints+e.userPersonas).toLowerCase(),r=t.filter(i=>o.includes(i)).length;return r>=5?5:r>=3?4:r>=2?3:r>=1?2:1}function vS(e){let t=e.outOfScope.length;return t>500?1:t>300?2:t>150?3:t>50?4:5}function TS(e){let t=["must","should","could","prefer","optional","required","nice to have"],o=(e.businessConstraints+e.userPersonas).toLowerCase(),r=t.filter(i=>o.includes(i)).length;return r>=8?5:r>=5?4:r>=3?3:r>=2?2:1}function ES(e,t){let n=e.toLowerCase(),o="moderate";n.includes("irreversible")||n.includes("migration")||n.includes("data loss")||n.includes("breaking change")?o="difficult":(n.includes("refactor")||n.includes("new feature")||n.includes("additive"))&&(o="easy");let r="isolated";n.includes("system-wide")||n.includes("all users")||n.includes("infrastructure")||n.includes("platform")?r="system-wide":(n.includes("cross-cutting")||n.includes("multiple")||n.includes("shared"))&&(r="cross-cutting");let i="none";n.includes("pii")||n.includes("personal")||n.includes("authentication")||n.includes("payment")||n.includes("user data")||n.includes("sensitive")?i="user-facing":(n.includes("internal")||n.includes("logging")||n.includes("metrics")||n.includes("telemetry"))&&(i="internal");let s="none";return n.includes("gdpr")||n.includes("soc")||n.includes("hipaa")||n.includes("compliance")||n.includes("regulatory")?s="major":(n.includes("audit")||n.includes("policy"))&&(s="minor"),{reversibility:o,blast_radius:r,data_sensitivity:i,compliance_impact:s}}J();var Hd=require("fs"),bS=require("path"),CS=require("os"),dr="<!-- AIDLC-RULES-START -->",bn="<!-- AIDLC-RULES-END -->";function Gd(e){return e.includes(dr)&&e.includes(bn)}function Bd(e,t){let n=`${dr}
911
911
  ${t}
912
- ${bn}`;if(Wd(e)){let r=e.indexOf(ur),i=e.indexOf(bn)+bn.length,s=e.slice(0,r).replace(/\s+$/,""),a=e.slice(i).replace(/^\s+/,"");return a?`${n}
912
+ ${bn}`;if(Gd(e)){let r=e.indexOf(dr),i=e.indexOf(bn)+bn.length,s=e.slice(0,r).replace(/\s+$/,""),a=e.slice(i).replace(/^\s+/,"");return a?`${n}
913
913
 
914
914
  ${a}`:n}let o=e.replace(/^\s+/,"");return o?`${n}
915
915
 
916
- ${o}`:n}function Gd(e){if(!Wd(e))return e;let t=e.indexOf(ur),n=e.indexOf(bn)+bn.length,o=e.slice(0,t).replace(/\s+$/,""),r=e.slice(n).replace(/^\s+/,"");return o&&r?`${o}
916
+ ${o}`:n}function qd(e){if(!Gd(e))return e;let t=e.indexOf(dr),n=e.indexOf(bn)+bn.length,o=e.slice(0,t).replace(/\s+$/,""),r=e.slice(n).replace(/^\s+/,"");return o&&r?`${o}
917
917
 
918
- ${r}`:o||r||""}function Bd(e,t){return`# AI-DLC Workflow Rules (Olympus-Native)
918
+ ${r}`:o||r||""}function Vd(e,t){return`# AI-DLC Workflow Rules (Olympus-Native)
919
919
 
920
920
  ## Active Workflow
921
921
  - **Workflow ID**: \`${e}\`
@@ -926,8 +926,8 @@ ${r}`:o||r||""}function Bd(e,t){return`# AI-DLC Workflow Rules (Olympus-Native)
926
926
 
927
927
  All workflow stages, agent delegation, directory layout, and rules are defined in the
928
928
  AI-DLC Core Workflow reference (loaded from core-workflow.md). This block only tracks
929
- the active workflow identity above.`}var ds=["intent","unit","code-generation","complete"];function B_(e){let t=ds.indexOf(e);return t===-1||t>=ds.length-1?"complete":ds[t+1]}var mr=class{projectPath;featureName;workflowId;interruptHandler=null;constructor(t,n){this.projectPath=t,this.featureName=n;let o=n.toLowerCase().replace(/\.[a-z]{1,4}$/,"").replace(/[_\s]+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"");if(o.length>80&&(o=o.substring(0,80).replace(/-$/,"")),!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");this.workflowId=o}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 Yu(this.projectPath,this.workflowId)}catch(o){let r=o;throw console.error(`[WorkflowEngine] Failed to initialize workflow directory: ${r.message}`),new Error(`Failed to start workflow: Could not create directory structure - ${r.message}`)}try{await $(this.projectPath,n)}catch(o){let r=o;throw console.error(`[WorkflowEngine] Failed to save initial checkpoint: ${r.message}`),new Error(`Failed to start workflow: Could not save checkpoint - ${r.message}`)}try{let r=(await Tn(this.projectPath)).sourceFileCount??0,i=await jd(this.projectPath,t),s=lr(t),a=await Md({projectPath:this.projectPath,workflowId:this.workflowId,intentText:t,depthAssessment:s,pathwayType:i,sourceFileCount:r}),c=await es(this.projectPath,this.workflowId,a),l=await I(this.projectPath,this.workflowId);if(l){l.workflow_routing_path=c,l.pathway_type=i;let u=["discovery","inception","construction","operations"];l.skipped_phases=u.filter(d=>!ts(a,d)),await $(this.projectPath,l)}if(console.log(`[WorkflowEngine] Generated Workflow Routing: pathway=${i}, depth=${a.estimated_depth}, code-generations=${a.estimated_code_generations}`),a.stages.some(u=>!u.included)){let u=a.stages.filter(d=>!d.included).map(d=>`${d.phase}/${d.stage}`);console.log(`[WorkflowEngine] Stages excluded by plan: ${u.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 r=(await I(this.projectPath,this.workflowId))?.pathway_type;if(!r){let{isBrownfield:l}=await Tn(this.projectPath);r=l?"brownfield-enhancement":"greenfield"}let i=fr.join(this.projectPath,".claude","CLAUDE.md"),s=Ne.existsSync(i)?Ne.readFileSync(i,"utf-8"):"",a=Bd(this.workflowId,r),c=Hd(s,a);Ne.mkdirSync(fr.join(this.projectPath,".claude"),{recursive:!0}),Ne.writeFileSync(i,c,"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(o){let r=o;throw console.error(`[WorkflowEngine] Failed to load checkpoint for resume: ${r.message}`),new Error(`Failed to resume workflow: Could not load checkpoint - ${r.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 $(this.projectPath,t)}catch(o){let r=o;throw console.error(`[WorkflowEngine] Failed to update checkpoint status: ${r.message}`),new Error(`Failed to resume workflow: Could not save checkpoint - ${r.message}`)}}this.setupInterruptHandler();let n=t.current_stage;try{await this.executeStage(n)}catch(o){let r=o;console.error(`[WorkflowEngine] Failed to execute ${n} stage: ${r.message}`);try{let i=await I(this.projectPath,this.workflowId);i&&(i.status="paused",i.resume_context={...i.resume_context,error_message:r.message,failed_stage:n},await $(this.projectPath,i),console.log("[WorkflowEngine] Workflow saved as paused. Fix the issue and resume with `/continue`"))}catch(i){console.warn("[WorkflowEngine] Failed to save error checkpoint:",i.message)}throw new Error(`Failed to execute ${n} stage: ${r.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 o=n;throw console.error(`[WorkflowEngine] Failed to load checkpoint for pause: ${o.message}`),new Error(`Failed to pause workflow: 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}`);t.status="paused";try{await $(this.projectPath,t)}catch(n){let o=n;throw console.error(`[WorkflowEngine] Failed to save paused checkpoint: ${o.message}`),new Error(`Failed to pause workflow: Could not save checkpoint - ${o.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 o=B_(t);n.current_stage=o,o==="complete"?await this.completeWorkflow(n):await $(this.projectPath,n)}async getStatus(){let t;try{t=await I(this.projectPath,this.workflowId)}catch(o){let r=o;throw console.error(`[WorkflowEngine] Failed to load checkpoint for status: ${r.message}`),new Error(`Failed to get workflow status: 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}`);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=cr(this.projectPath,this.workflowId);if(n&&!ts(n,t)){console.log(`[WorkflowEngine] Skipping ${t} phase (excluded by Workflow Routing: ${n.phases[t]?.rationale||"no rationale"})`);let o=await I(this.projectPath,this.workflowId);if(o){let i=o;i.phases&&i.phases[t]&&(i.phases[t].status="complete",i.phases[t].completed_at=new Date().toISOString(),i.phases[t].gate_bypassed=!0,i.phases[t].bypass_reason="Excluded by Workflow Routing"),await $(this.projectPath,o)}let r=`${this.projectPath}/aidlc-docs/${this.workflowId}/manifest.json`;try{Ce(r,{phase:t,action:"bypassed",actor:"config",reason:`Excluded by Workflow Routing (pathway: ${n.pathway})`})}catch{}return}switch(t){case"discovery":{let o=`${this.projectPath}/aidlc-docs/${this.workflowId}/manifest.json`,r=await Pd({projectPath:this.projectPath,workflowId:this.workflowId,featureName:this.featureName,manifestPath:o});r.gateRequired&&(console.log(`[WorkflowEngine] Discovery phase: ${r.artifactsGenerated.length} artifacts generated (${r.sourceFileCount} source files detected)`),console.log(`[WorkflowEngine] Discovery Gate: Review findings in aidlc-docs/${this.workflowId}/discovery/ before proceeding to Inception`));try{let i={type:"phase_complete",phase:"discovery",details:`${r.artifactsGenerated.length} artifacts generated, ${r.sourceFileCount} source files`},s={workflowId:this.workflowId,featureName:this.featureName,projectPath:this.projectPath,sessionId:"engine",phase:"discovery"},a=xe(i,s);ie(a)}catch(i){console.error("[WorkflowEngine] Failed to capture discovery phase discovery:",i)}break}case"inception":{let{InceptionOrchestrator:o}=await Promise.resolve().then(()=>(lp(),cp)),r=new o,i=await I(this.projectPath,this.workflowId);if(!i)throw new Error(`No checkpoint found for workflow: ${this.workflowId}`);if(i.current_stage!=="intent"){console.log(`[WorkflowEngine] Skipping inception orchestrator \u2014 checkpoint already at stage '${i.current_stage}'`);break}if(!i.inception_stages){let s=cr(this.projectPath,this.workflowId),a=i;await r.initialize(this.projectPath,this.workflowId,a.pathway_type||"greenfield",s)}for(;!await r.isComplete(this.projectPath,this.workflowId);){let s=await r.executeNextStage(this.projectPath,this.workflowId);if(s.status==="awaiting_answers"||s.status==="review_required")break}try{let s={type:"phase_complete",phase:"inception",details:"Inception stages completed"},a={workflowId:this.workflowId,featureName:this.featureName,projectPath:this.projectPath,sessionId:"engine",phase:"inception"},c=xe(s,a);ie(c)}catch(s){console.error("[WorkflowEngine] Failed to capture inception phase discovery:",s)}break}case"construction":{let o=await I(this.projectPath,this.workflowId);if(o&&o.status==="awaiting_dev_review"){console.log("[WorkflowEngine] Waiting for developer review of technical specification (Risk Tier 3).");return}let r=Ot(this.projectPath,this.workflowId,"intent"),i;try{i=Ne.readFileSync(r,"utf-8")}catch{}let a=await new er(this.projectPath,this.workflowId).execute(i);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=xe(c,l);ie(u)}catch(c){console.error("[WorkflowEngine] Failed to capture construction phase discovery:",c)}break}case"operations":{let{generateOperationsArtifacts:o}=await Promise.resolve().then(()=>(hp(),gp)),{loadManifest:r,registerArtifact:i,updatePhaseStatus:s}=await Promise.resolve().then(()=>(J(),Vt)),a=`${this.projectPath}/aidlc-docs/${this.workflowId}/manifest.json`,c=r(a),l=null;try{l=Ne.readFileSync(Ot(this.projectPath,this.workflowId,"intent"),"utf-8")}catch{}let u=await I(this.projectPath,this.workflowId),d="MEDIUM";if(c?.depth_assessment){let p=c.depth_assessment.total_score;p<=10?d="SHALLOW":p>=21&&(d="DEEP")}let f={workflowId:this.workflowId,featureName:this.featureName,manifest:c,specContent:l,buildLogContent:null,depthLevel:d},m=await o(f,this.projectPath);if(c){s(a,"operations","complete");for(let p of m.artifactsGenerated){let g=`aidlc-docs/${this.workflowId}/operations/${p}`,h=p.replace(/\.(md|json)$/,"").toUpperCase().replace(/-/g,"_");i(a,{id:`OPS-${h}`,type:h,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 $(this.projectPath,u)),console.log(`[WorkflowEngine] Operations phase: Generated ${m.artifactsGenerated.length} artifacts (depth: ${d})`),console.log(`[WorkflowEngine] Operations artifacts: ${m.artifactsGenerated.join(", ")}`);try{let p={type:"phase_complete",phase:"operations",details:`${m.artifactsGenerated.length} artifacts generated (depth: ${d})`},g={workflowId:this.workflowId,featureName:this.featureName,projectPath:this.projectPath,sessionId:"engine",phase:"operations"},h=xe(p,g);ie(h)}catch(p){console.error("[WorkflowEngine] Failed to capture operations phase discovery:",p)}break}}}async completeWorkflow(t){t.status="complete";try{let n=fr.join(this.projectPath,".claude","CLAUDE.md");if(Ne.existsSync(n)){let o=Ne.readFileSync(n,"utf-8"),r=Gd(o);Ne.writeFileSync(n,r,"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 $(this.projectPath,t),await Lu(this.projectPath,this.workflowId)}async approveWorkflowRouting(t){let n=cr(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 es(this.projectPath,this.workflowId,n);let o=await I(this.projectPath,this.workflowId);if(o){let i=o;if(i.inception_stages?.["workflow-planning"]){let s=i.inception_stages["workflow-planning"];s.status!=="completed"&&s.status!=="skipped"&&(s.status="completed",s.completed_at=new Date().toISOString(),await $(this.projectPath,o))}}let r=`${this.projectPath}/aidlc-docs/${this.workflowId}/manifest.json`;try{Ce(r,{phase:"inception",action:"approved",actor:"human",reason:t||"Workflow Routing approved"})}catch{}console.log("[WorkflowEngine] Workflow Routing approved")}setupInterruptHandler(){this.interruptHandler=async()=>{console.log(`
930
- [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 $(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 o=`intent-${this.workflowId}`,r=new Date().toISOString(),i=`---
929
+ the active workflow identity above.`}var fs=["intent","unit","code-generation","complete"];function VS(e){let t=fs.indexOf(e);return t===-1||t>=fs.length-1?"complete":fs[t+1]}var mr=class{projectPath;featureName;workflowId;interruptHandler=null;constructor(t,n){this.projectPath=t,this.featureName=n;let o=n.toLowerCase().replace(/\.[a-z]{1,4}$/,"").replace(/[_\s]+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"");if(o.length>80&&(o=o.substring(0,80).replace(/-$/,"")),!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");this.workflowId=o}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 Ju(this.projectPath,this.workflowId)}catch(r){let i=r;throw console.error(`[WorkflowEngine] Failed to initialize workflow directory: ${i.message}`),new Error(`Failed to start workflow: Could not create directory structure - ${i.message}`)}let o=co.join(this.projectPath,"aidlc-docs",this.workflowId,"manifest.json");if(!Re.existsSync(o))try{Mi(this.workflowId,this.featureName,this.projectPath)}catch(r){console.warn(`[WorkflowEngine] Failed to create manifest: ${r.message}`)}try{await $(this.projectPath,n)}catch(r){let i=r;throw console.error(`[WorkflowEngine] Failed to save initial checkpoint: ${i.message}`),new Error(`Failed to start workflow: Could not save checkpoint - ${i.message}`)}try{let i=(await Tn(this.projectPath)).sourceFileCount??0,s=await Ld(this.projectPath,t),a=ur(t),c=await Fd({projectPath:this.projectPath,workflowId:this.workflowId,intentText:t,depthAssessment:a,pathwayType:s,sourceFileCount:i}),l=await ts(this.projectPath,this.workflowId,c),u=await C(this.projectPath,this.workflowId);if(u){u.workflow_routing_path=l,u.pathway_type=s;let d=["discovery","inception","construction","operations"];u.skipped_phases=d.filter(f=>!ns(c,f)),await $(this.projectPath,u)}if(console.log(`[WorkflowEngine] Generated Workflow Routing: pathway=${s}, depth=${c.estimated_depth}, code-generations=${c.estimated_code_generations}`),c.stages.some(d=>!d.included)){let d=c.stages.filter(f=>!f.included).map(f=>`${f.phase}/${f.stage}`);console.log(`[WorkflowEngine] Stages excluded by plan: ${d.join(", ")}`)}}catch(r){console.warn(`[WorkflowEngine] Failed to generate Workflow Routing: ${r.message}`),console.warn("[WorkflowEngine] Workflow will proceed without adaptive phase selection")}try{let i=(await C(this.projectPath,this.workflowId))?.pathway_type;if(!i){let{isBrownfield:u}=await Tn(this.projectPath);i=u?"brownfield-enhancement":"greenfield"}let s=co.join(this.projectPath,".claude","CLAUDE.md"),a=Re.existsSync(s)?Re.readFileSync(s,"utf-8"):"",c=Vd(this.workflowId,i),l=Bd(a,c);Re.mkdirSync(co.join(this.projectPath,".claude"),{recursive:!0}),Re.writeFileSync(s,l,"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)}}async resume(){let t;try{t=await C(this.projectPath,this.workflowId)}catch(o){let r=o;throw console.error(`[WorkflowEngine] Failed to load checkpoint for resume: ${r.message}`),new Error(`Failed to resume workflow: Could not load checkpoint - ${r.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 $(this.projectPath,t)}catch(o){let r=o;throw console.error(`[WorkflowEngine] Failed to update checkpoint status: ${r.message}`),new Error(`Failed to resume workflow: Could not save checkpoint - ${r.message}`)}}this.setupInterruptHandler();let n=t.current_stage;try{await this.executeStage(n)}catch(o){let r=o;console.error(`[WorkflowEngine] Failed to execute ${n} stage: ${r.message}`);try{let i=await C(this.projectPath,this.workflowId);i&&(i.status="paused",i.resume_context={...i.resume_context,error_message:r.message,failed_stage:n},await $(this.projectPath,i),console.log("[WorkflowEngine] Workflow saved as paused. Fix the issue and resume with `/continue`"))}catch(i){console.warn("[WorkflowEngine] Failed to save error checkpoint:",i.message)}throw new Error(`Failed to execute ${n} stage: ${r.message}`)}finally{this.cleanupInterruptHandler()}return`Resumed workflow from stage: ${n}`}async pause(){let t;try{t=await C(this.projectPath,this.workflowId)}catch(n){let o=n;throw console.error(`[WorkflowEngine] Failed to load checkpoint for pause: ${o.message}`),new Error(`Failed to pause workflow: 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}`);t.status="paused";try{await $(this.projectPath,t)}catch(n){let o=n;throw console.error(`[WorkflowEngine] Failed to save paused checkpoint: ${o.message}`),new Error(`Failed to pause workflow: Could not save checkpoint - ${o.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 C(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 o=VS(t);n.current_stage=o,o==="complete"?await this.completeWorkflow(n):await $(this.projectPath,n)}async getStatus(){let t;try{t=await C(this.projectPath,this.workflowId)}catch(o){let r=o;throw console.error(`[WorkflowEngine] Failed to load checkpoint for status: ${r.message}`),new Error(`Failed to get workflow status: 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}`);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=lr(this.projectPath,this.workflowId);if(n&&!ns(n,t)){console.log(`[WorkflowEngine] Skipping ${t} phase (excluded by Workflow Routing: ${n.phases[t]?.rationale||"no rationale"})`);let o=await C(this.projectPath,this.workflowId);if(o){let i=o;i.phases&&i.phases[t]&&(i.phases[t].status="complete",i.phases[t].completed_at=new Date().toISOString(),i.phases[t].gate_bypassed=!0,i.phases[t].bypass_reason="Excluded by Workflow Routing"),await $(this.projectPath,o)}let r=`${this.projectPath}/aidlc-docs/${this.workflowId}/manifest.json`;try{Ce(r,{phase:t,action:"bypassed",actor:"config",reason:`Excluded by Workflow Routing (pathway: ${n.pathway})`})}catch{}return}switch(t){case"discovery":{let o=`${this.projectPath}/aidlc-docs/${this.workflowId}/manifest.json`,r=await $d({projectPath:this.projectPath,workflowId:this.workflowId,featureName:this.featureName,manifestPath:o});r.gateRequired&&(console.log(`[WorkflowEngine] Discovery phase: ${r.artifactsGenerated.length} artifacts generated (${r.sourceFileCount} source files detected)`),console.log(`[WorkflowEngine] Discovery Gate: Review findings in aidlc-docs/${this.workflowId}/discovery/ before proceeding to Inception`));try{let i={type:"phase_complete",phase:"discovery",details:`${r.artifactsGenerated.length} artifacts generated, ${r.sourceFileCount} source files`},s={workflowId:this.workflowId,featureName:this.featureName,projectPath:this.projectPath,sessionId:"engine",phase:"discovery"},a=$e(i,s);ie(a)}catch(i){console.error("[WorkflowEngine] Failed to capture discovery phase discovery:",i)}break}case"inception":{let{InceptionOrchestrator:o}=await Promise.resolve().then(()=>(dp(),up)),r=new o,i=await C(this.projectPath,this.workflowId);if(!i)throw new Error(`No checkpoint found for workflow: ${this.workflowId}`);if(i.current_stage!=="intent"){console.log(`[WorkflowEngine] Skipping inception orchestrator \u2014 checkpoint already at stage '${i.current_stage}'`);break}if(!i.inception_stages){let s=lr(this.projectPath,this.workflowId),a=i;await r.initialize(this.projectPath,this.workflowId,a.pathway_type||"greenfield",s)}for(;!await r.isComplete(this.projectPath,this.workflowId);){let s=await r.executeNextStage(this.projectPath,this.workflowId);if(s.status==="awaiting_answers"||s.status==="review_required")break}try{let s={type:"phase_complete",phase:"inception",details:"Inception stages completed"},a={workflowId:this.workflowId,featureName:this.featureName,projectPath:this.projectPath,sessionId:"engine",phase:"inception"},c=$e(s,a);ie(c)}catch(s){console.error("[WorkflowEngine] Failed to capture inception phase discovery:",s)}break}case"construction":{let o=await C(this.projectPath,this.workflowId);if(o&&o.status==="awaiting_dev_review"){console.log("[WorkflowEngine] Waiting for developer review of technical specification (Risk Tier 3).");return}let r=Ot(this.projectPath,this.workflowId,"intent"),i;try{i=Re.readFileSync(r,"utf-8")}catch{}let a=await new tr(this.projectPath,this.workflowId).execute(i);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=$e(c,l);ie(u)}catch(c){console.error("[WorkflowEngine] Failed to capture construction phase discovery:",c)}break}case"operations":{let{generateOperationsArtifacts:o}=await Promise.resolve().then(()=>(kp(),yp)),{loadManifest:r,registerArtifact:i,updatePhaseStatus:s}=await Promise.resolve().then(()=>(J(),Vt)),a=`${this.projectPath}/aidlc-docs/${this.workflowId}/manifest.json`,c=r(a),l=null;try{l=Re.readFileSync(Ot(this.projectPath,this.workflowId,"intent"),"utf-8")}catch{}let u=await C(this.projectPath,this.workflowId),d="MEDIUM";if(c?.depth_assessment){let p=c.depth_assessment.total_score;p<=10?d="SHALLOW":p>=21&&(d="DEEP")}let f={workflowId:this.workflowId,featureName:this.featureName,manifest:c,specContent:l,buildLogContent:null,depthLevel:d},m=await o(f,this.projectPath);if(c){s(a,"operations","complete");for(let p of m.artifactsGenerated){let g=`aidlc-docs/${this.workflowId}/operations/${p}`,h=p.replace(/\.(md|json)$/,"").toUpperCase().replace(/-/g,"_");i(a,{id:`OPS-${h}`,type:h,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 $(this.projectPath,u)),console.log(`[WorkflowEngine] Operations phase: Generated ${m.artifactsGenerated.length} artifacts (depth: ${d})`),console.log(`[WorkflowEngine] Operations artifacts: ${m.artifactsGenerated.join(", ")}`);try{let p={type:"phase_complete",phase:"operations",details:`${m.artifactsGenerated.length} artifacts generated (depth: ${d})`},g={workflowId:this.workflowId,featureName:this.featureName,projectPath:this.projectPath,sessionId:"engine",phase:"operations"},h=$e(p,g);ie(h)}catch(p){console.error("[WorkflowEngine] Failed to capture operations phase discovery:",p)}break}}}async completeWorkflow(t){t.status="complete";try{let n=co.join(this.projectPath,".claude","CLAUDE.md");if(Re.existsSync(n)){let o=Re.readFileSync(n,"utf-8"),r=qd(o);Re.writeFileSync(n,r,"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 $(this.projectPath,t),await Uu(this.projectPath,this.workflowId)}async approveWorkflowRouting(t){let n=lr(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 ts(this.projectPath,this.workflowId,n);let o=await C(this.projectPath,this.workflowId);if(o){let i=o;if(i.inception_stages?.["workflow-planning"]){let s=i.inception_stages["workflow-planning"];s.status!=="completed"&&s.status!=="skipped"&&(s.status="completed",s.completed_at=new Date().toISOString(),await $(this.projectPath,o))}}let r=`${this.projectPath}/aidlc-docs/${this.workflowId}/manifest.json`;try{Ce(r,{phase:"inception",action:"approved",actor:"human",reason:t||"Workflow Routing approved"})}catch{}console.log("[WorkflowEngine] Workflow Routing approved")}setupInterruptHandler(){this.interruptHandler=async()=>{console.log(`
930
+ [WorkflowEngine] Workflow interrupted - saving checkpoint...`);try{let t=await C(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 $(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 o=`intent-${this.workflowId}`,r=new Date().toISOString(),i=`---
931
931
  id: ${o}
932
932
  title: ${this.featureName}
933
933
  status: draft
@@ -1128,7 +1128,7 @@ created: ${r}
1128
1128
 
1129
1129
  ---
1130
1130
  *Generated by WorkflowEngine based on ${o}*
1131
- `;await hn(this.projectPath,this.workflowId,"nfr",a),console.log("[WorkflowEngine] Generated NFR artifact at inception/requirements/nfr.md");let c=Ot(this.projectPath,this.workflowId,"intent");console.log(`[WorkflowEngine] Validating INTENT artifact at: ${c}`);let l=await zo(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 $(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")}};Ee();var yp={intent:null,unit:null,"code-generation":null,complete:null};function kp(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 wp(e,t,n=!1){let o=t.current_stage,r=yp[o],i=kp(o),s=`You are beginning a structured workflow for feature: ${e}
1131
+ `;await hn(this.projectPath,this.workflowId,"nfr",a),console.log("[WorkflowEngine] Generated NFR artifact at inception/requirements/nfr.md");let c=Ot(this.projectPath,this.workflowId,"intent");console.log(`[WorkflowEngine] Validating INTENT artifact at: ${c}`);let l=await Qo(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 C(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 $(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")}};Ee();var wp={intent:null,unit:null,"code-generation":null,complete:null};function Sp(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 _p(e,t,n=!1){let o=t.current_stage,r=wp[o],i=Sp(o),s=`You are beginning a structured workflow for feature: ${e}
1132
1132
 
1133
1133
  `;return s+=`Current stage: ${o}
1134
1134
  `,s+=`Status: ${t.status}
@@ -1139,7 +1139,7 @@ created: ${r}
1139
1139
  `):s+=`Next step: ${i}
1140
1140
  `,n&&(s+=`
1141
1141
  IMPORTANT: This is a BRAND NEW workflow just initialized. `,s+="Do NOT treat this as a resumed or existing workflow. ",s+=`Proceed with workspace detection as the first step.
1142
- `),s}function _p(e,t){let n=t.current_stage,o=yp[n],r=kp(n),i=`Resuming workflow for feature: ${e}
1142
+ `),s}function vp(e,t){let n=t.current_stage,o=wp[n],r=Sp(n),i=`Resuming workflow for feature: ${e}
1143
1143
 
1144
1144
  `;return i+=`You were interrupted during: ${n}
1145
1145
  `,i+=`Last update: ${t.updated_at}
@@ -1152,17 +1152,17 @@ IMPORTANT: This is a BRAND NEW workflow just initialized. `,s+="Do NOT treat thi
1152
1152
 
1153
1153
  `,i+=`Use: Task(subagent_type="${o}", prompt="...")
1154
1154
  `):i+=`Continue from where you left off: ${r}
1155
- `,i}function ps(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 Sp(){_({name:"structuredWorkflowDetector",event:"UserPromptSubmit",priority:8,handler:async e=>{let t=ps(e);if(!t||!e.directory)return{continue:!0};let n=t.match(/^\/plan\s+(?!continue\b|--)([\s\S]+?)$/i),o=t.match(/^\/plan\s+continue$/i);if(n){let r=n[1].trim();r=r.replace(/\s+--structured\s*/i,"").trim();let i,s=r.match(/\s+--depth\s+(shallow|medium|deep)\s*$/i);s&&(i=s[1].toLowerCase(),r=r.replace(s[0],"").trim());let a,c=r.match(/\s+--(brownfield|greenfield)\s*$/i);if(c&&(a=c[1].toLowerCase(),r=r.replace(c[0],"").trim()),r.length>120)return console.error("[Structured Workflow] Feature name too long, likely not a real feature name:",r.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(r))return console.error("[Structured Workflow] Feature name looks like conversational text, skipping:",r.substring(0,50)+"..."),{continue:!0};try{await new mr(e.directory,r).start(r);let d=r.toLowerCase().replace(/\.[a-z]{1,4}$/,"").replace(/[_\s]+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"");if(d==="completed")return console.warn('[user-prompt-submit] "completed" is a reserved workflow directory name'),{continue:!0};let f=await I(e.directory,d);if(!f)return{continue:!0};let m=wp(r,f,!0),g=`${`[Workflow: ${d} | Phase: ${f.current_phase||"inception"} | Stage: ${f.current_stage||"intent"}]`}
1155
+ `,i}function ms(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 Tp(){S({name:"structuredWorkflowDetector",event:"UserPromptSubmit",priority:8,handler:async e=>{let t=ms(e);if(!t||!e.directory)return{continue:!0};let n=t.match(/^\/plan\s+(?!continue\b|--)([\s\S]+?)$/i),o=t.match(/^\/plan\s+continue$/i);if(n){let r=n[1].trim();r=r.replace(/\s+--structured\s*/i,"").trim();let i,s=r.match(/\s+--depth\s+(shallow|medium|deep)\s*$/i);s&&(i=s[1].toLowerCase(),r=r.replace(s[0],"").trim());let a,c=r.match(/\s+--(brownfield|greenfield)\s*$/i);if(c&&(a=c[1].toLowerCase(),r=r.replace(c[0],"").trim()),r.length>120)return console.error("[Structured Workflow] Feature name too long, likely not a real feature name:",r.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(r))return console.error("[Structured Workflow] Feature name looks like conversational text, skipping:",r.substring(0,50)+"..."),{continue:!0};try{await new mr(e.directory,r).start(r);let d=r.toLowerCase().replace(/\.[a-z]{1,4}$/,"").replace(/[_\s]+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"");if(d==="completed")return console.warn('[user-prompt-submit] "completed" is a reserved workflow directory name'),{continue:!0};let f=await C(e.directory,d);if(!f)return{continue:!0};let m=_p(r,f,!0),g=`${`[Workflow: ${d} | Phase: ${f.current_phase||"inception"} | Stage: ${f.current_stage||"intent"}]`}
1156
1156
 
1157
1157
  ${m}`;return i&&(g+=`
1158
1158
 
1159
1159
  Depth override: ${i}`),a&&(g+=`
1160
1160
 
1161
- Project type: ${a}`),{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:g}}}catch(u){return console.error("[Structured Workflow]",u),{continue:!0}}}if(o)try{let r=await te(e.directory);if(r.length===0)return{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:"No active workflows found. Use `/plan {feature}` to start a new workflow."}};let i=r[0],s=await I(e.directory,i);if(!s)return{continue:!0};let a=_p(s.feature_name,s);return{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:`[TIP: For full AIDLC resume with behavioral rules, use /continue instead of /plan continue]
1161
+ Project type: ${a}`),{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:g}}}catch(u){return console.error("[Structured Workflow]",u),{continue:!0}}}if(o)try{let r=await te(e.directory);if(r.length===0)return{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:"No active workflows found. Use `/plan {feature}` to start a new workflow."}};let i=r[0],s=await C(e.directory,i);if(!s)return{continue:!0};let a=vp(s.feature_name,s);return{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:`[TIP: For full AIDLC resume with behavioral rules, use /continue instead of /plan continue]
1162
1162
 
1163
1163
  ${`[Workflow: ${i} | Phase: ${s.current_phase||"inception"} | Stage: ${s.current_stage||"intent"}]`}
1164
1164
 
1165
- ${a}`}}}catch(r){return console.error("[Workflow Resume]",r),{continue:!0}}return{continue:!0}}}),_({name:"keywordDetector",event:"UserPromptSubmit",priority:10,handler:e=>{let t=ps(e);if(!t)return{continue:!0};let n=La(t),o=Fa(n);if(o.length===0)return{continue:!0};let r=o.some(c=>c.type==="ultrawork"),i=o.some(c=>c.type==="ultrathink"),s=o.some(c=>c.type==="search"),a=o.some(c=>c.type==="analyze");return r?(sc(t,e.sessionId,e.directory||process.cwd()),{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:dc}}):i?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:pc}}:s?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:fc}}:a?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:mc}}:{continue:!0}}}),_({name:"autoSlashCommand",event:"UserPromptSubmit",priority:20,handler:e=>{if(!e.parts)return{continue:!0};let n=za().processMessage({sessionId:e.sessionId||""},e.parts);return n.detected&&n.injectedMessage?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:n.injectedMessage}}:{continue:!0}}}),_({name:"thinkMode",event:"UserPromptSubmit",priority:30,handler:e=>{if(!e.message||!e.parts)return{continue:!0};let t=rc(),n=e.sessionId||"default",o={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}},r=t.processChatParams(n,o);return r.requested&&r.modelSwitched?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:"[Think Mode Activated] Switched to high-reasoning model variant."}}:{continue:!0}}}),_({name:"learningFeedbackCapture",event:"UserPromptSubmit",priority:100,handler:async e=>{let t=ps(e);return!t||!e.directory?{continue:!0}:(Promise.resolve().then(async()=>{try{await Uc({prompt:t,directory:e.directory,sessionId:e.sessionId}),await Hc({prompt:t,directory:e.directory,sessionId:e.sessionId})}catch(n){console.error("[Olympus Learning]",n)}}),{continue:!0})}})}var fs=require("child_process");var q_="mcpProcessCleanup",V_=/mcp/i;function Y_(e){return e?V_.test(e):!1}function K_(e,t){return e.filter(n=>Y_(n.CommandLine)?!t.has(n.ParentProcessId):!1)}function J_(e){let t=0;for(let n of e)try{(0,fs.execSync)(`taskkill /T /F /PID ${n.ProcessId}`,{encoding:"utf8",timeout:5e3,stdio:"pipe"}),t++}catch{}return t}function z_(){if(process.platform!=="win32")return 0;try{let e=`
1165
+ ${a}`}}}catch(r){return console.error("[Workflow Resume]",r),{continue:!0}}return{continue:!0}}}),S({name:"keywordDetector",event:"UserPromptSubmit",priority:10,handler:e=>{let t=ms(e);if(!t)return{continue:!0};let n=Ua(t),o=Wa(n);if(o.length===0)return{continue:!0};let r=o.some(c=>c.type==="ultrawork"),i=o.some(c=>c.type==="ultrathink"),s=o.some(c=>c.type==="search"),a=o.some(c=>c.type==="analyze");return r?(cc(t,e.sessionId,e.directory||process.cwd()),{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:fc}}):i?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:mc}}:s?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:gc}}:a?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:hc}}:{continue:!0}}}),S({name:"autoSlashCommand",event:"UserPromptSubmit",priority:20,handler:e=>{if(!e.parts)return{continue:!0};let n=Xa().processMessage({sessionId:e.sessionId||""},e.parts);return n.detected&&n.injectedMessage?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:n.injectedMessage}}:{continue:!0}}}),S({name:"thinkMode",event:"UserPromptSubmit",priority:30,handler:e=>{if(!e.message||!e.parts)return{continue:!0};let t=sc(),n=e.sessionId||"default",o={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}},r=t.processChatParams(n,o);return r.requested&&r.modelSwitched?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:"[Think Mode Activated] Switched to high-reasoning model variant."}}:{continue:!0}}}),S({name:"learningFeedbackCapture",event:"UserPromptSubmit",priority:100,handler:async e=>{let t=ms(e);return!t||!e.directory?{continue:!0}:(Promise.resolve().then(async()=>{try{await Hc({prompt:t,directory:e.directory,sessionId:e.sessionId}),await Bc({prompt:t,directory:e.directory,sessionId:e.sessionId})}catch(n){console.error("[Olympus Learning]",n)}}),{continue:!0})}})}var gs=require("child_process");var YS="mcpProcessCleanup",KS=/mcp/i;function JS(e){return e?KS.test(e):!1}function zS(e,t){return e.filter(n=>JS(n.CommandLine)?!t.has(n.ParentProcessId):!1)}function QS(e){let t=0;for(let n of e)try{(0,gs.execSync)(`taskkill /T /F /PID ${n.ProcessId}`,{encoding:"utf8",timeout:5e3,stdio:"pipe"}),t++}catch{}return t}function XS(){if(process.platform!=="win32")return 0;try{let e=`
1166
1166
  $nodeProcs = Get-CimInstance Win32_Process -Filter "Name='node.exe'" |
1167
1167
  Select-Object ProcessId, ParentProcessId, CommandLine;
1168
1168
  $allPids = (Get-Process -ErrorAction SilentlyContinue).Id;
@@ -1170,7 +1170,7 @@ ${a}`}}}catch(r){return console.error("[Workflow Resume]",r),{continue:!0}}retur
1170
1170
  nodeProcesses = @($nodeProcs | ForEach-Object { @{ ProcessId=$_.ProcessId; ParentProcessId=$_.ParentProcessId; CommandLine=$_.CommandLine } });
1171
1171
  allPids = @($allPids)
1172
1172
  } | ConvertTo-Json -Depth 3
1173
- `.replace(/\n/g," "),t=(0,fs.execSync)(`powershell -NoProfile -Command "${e}"`,{encoding:"utf8",timeout:15e3,stdio:["pipe","pipe","pipe"]}),n=JSON.parse(t),o=Array.isArray(n.nodeProcesses)?n.nodeProcesses:n.nodeProcesses?[n.nodeProcesses]:[],r=new Set(Array.isArray(n.allPids)?n.allPids:n.allPids?[n.allPids]:[]),i=K_(o,r);return i.length===0?0:J_(i)}catch(e){return console.error("[Olympus MCP Cleanup] Error:",e),0}}function vp(){_({name:q_,event:"SessionStart",priority:1,handler:e=>{let t=z_();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 Qt=require("fs"),Dt=require("path"),Tp=require("os");function Q_(e,t){let n=(0,Dt.join)((0,Tp.homedir)(),".claude"),o=[];e&&(o.push((0,Dt.join)(n,"sessions",e,"todos.json")),o.push((0,Dt.join)(n,"todos",`${e}.json`))),t&&(o.push((0,Dt.join)(t,".olympus","todos.json")),o.push((0,Dt.join)(t,".claude","todos.json")));let r=(0,Dt.join)(n,"todos");if((0,Qt.existsSync)(r))try{let i=(0,Qt.readdirSync)(r);for(let s of i)s.endsWith(".json")&&o.push((0,Dt.join)(r,s))}catch{}return o}function X_(e){try{let t=(0,Qt.readFileSync)(e,"utf-8"),n=JSON.parse(t);return Array.isArray(n)?n.filter(o=>o&&typeof o.content=="string"&&typeof o.status=="string"):n.todos&&Array.isArray(n.todos)?n.todos.filter(o=>{let r=o;return r&&typeof r.content=="string"&&typeof r.status=="string"}):[]}catch{return[]}}function Z_(e){return e.status!=="completed"&&e.status!=="cancelled"}async function co(e,t){let n=Q_(e,t),o=new Set,r=[],i=[];for(let s of n){if(!(0,Qt.existsSync)(s))continue;let a=X_(s);for(let c of a){let l=`${c.content}:${c.status}`;o.has(l)||(o.add(l),r.push(c),Z_(c)&&i.push(c))}}return{count:i.length,todos:i,total:r.length}}function Ep(e){let t=e.todos.find(n=>n.status==="in_progress");return t||(e.todos.find(n=>n.status==="pending")??null)}var ms=require("path");fe();Qo();fe();function bp(e,t=5){return(e.token_efficiency?.invocation_count??0)>=t}yi();var Cp=500;function Ip(e){let t=me((0,ms.join)(ae(),"user-preferences.json"),null),n=me((0,ms.join)(Qe(e),"patterns.json"),null),o=ln(),r=ln(e),i={...o,...r},s=[];if(t&&eS(t)){let u=t.explicit_rules.filter(f=>!f.project_path||f.project_path===e),d={...t,explicit_rules:u};s.push(tS(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)&&s.push(nS(n)),t?.recurring_corrections&&t.recurring_corrections.length>0&&s.push(oS(t.recurring_corrections.slice(0,5)));let a=Object.values(i).filter(u=>u.weak_areas.length>0);a.length>0&&s.push(rS(a));let c=iS(i);if(c&&s.push(c),s.length===0)return"";let l=`<learned-context>
1173
+ `.replace(/\n/g," "),t=(0,gs.execSync)(`powershell -NoProfile -Command "${e}"`,{encoding:"utf8",timeout:15e3,stdio:["pipe","pipe","pipe"]}),n=JSON.parse(t),o=Array.isArray(n.nodeProcesses)?n.nodeProcesses:n.nodeProcesses?[n.nodeProcesses]:[],r=new Set(Array.isArray(n.allPids)?n.allPids:n.allPids?[n.allPids]:[]),i=zS(o,r);return i.length===0?0:QS(i)}catch(e){return console.error("[Olympus MCP Cleanup] Error:",e),0}}function Ep(){S({name:YS,event:"SessionStart",priority:1,handler:e=>{let t=XS();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 Qt=require("fs"),Dt=require("path"),bp=require("os");function ZS(e,t){let n=(0,Dt.join)((0,bp.homedir)(),".claude"),o=[];e&&(o.push((0,Dt.join)(n,"sessions",e,"todos.json")),o.push((0,Dt.join)(n,"todos",`${e}.json`))),t&&(o.push((0,Dt.join)(t,".olympus","todos.json")),o.push((0,Dt.join)(t,".claude","todos.json")));let r=(0,Dt.join)(n,"todos");if((0,Qt.existsSync)(r))try{let i=(0,Qt.readdirSync)(r);for(let s of i)s.endsWith(".json")&&o.push((0,Dt.join)(r,s))}catch{}return o}function e_(e){try{let t=(0,Qt.readFileSync)(e,"utf-8"),n=JSON.parse(t);return Array.isArray(n)?n.filter(o=>o&&typeof o.content=="string"&&typeof o.status=="string"):n.todos&&Array.isArray(n.todos)?n.todos.filter(o=>{let r=o;return r&&typeof r.content=="string"&&typeof r.status=="string"}):[]}catch{return[]}}function t_(e){return e.status!=="completed"&&e.status!=="cancelled"}async function lo(e,t){let n=ZS(e,t),o=new Set,r=[],i=[];for(let s of n){if(!(0,Qt.existsSync)(s))continue;let a=e_(s);for(let c of a){let l=`${c.content}:${c.status}`;o.has(l)||(o.add(l),r.push(c),t_(c)&&i.push(c))}}return{count:i.length,todos:i,total:r.length}}function Cp(e){let t=e.todos.find(n=>n.status==="in_progress");return t||(e.todos.find(n=>n.status==="pending")??null)}var hs=require("path");fe();Xo();fe();function Ip(e,t=5){return(e.token_efficiency?.invocation_count??0)>=t}yi();var Rp=500;function Op(e){let t=me((0,hs.join)(ae(),"user-preferences.json"),null),n=me((0,hs.join)(Qe(e),"patterns.json"),null),o=ln(),r=ln(e),i={...o,...r},s=[];if(t&&n_(t)){let u=t.explicit_rules.filter(f=>!f.project_path||f.project_path===e),d={...t,explicit_rules:u};s.push(o_(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)&&s.push(r_(n)),t?.recurring_corrections&&t.recurring_corrections.length>0&&s.push(i_(t.recurring_corrections.slice(0,5)));let a=Object.values(i).filter(u=>u.weak_areas.length>0);a.length>0&&s.push(s_(a));let c=a_(i);if(c&&s.push(c),s.length===0)return"";let l=`<learned-context>
1174
1174
 
1175
1175
  ${s.join(`
1176
1176
 
@@ -1180,21 +1180,21 @@ ${s.join(`
1180
1180
 
1181
1181
  ---
1182
1182
 
1183
- `;return l.length>Cp*4?l.substring(0,Cp*4)+`
1183
+ `;return l.length>Rp*4?l.substring(0,Rp*4)+`
1184
1184
  ...</learned-context>
1185
1185
 
1186
1186
  ---
1187
1187
 
1188
- `:l}function eS(e){return e.verbosity!=="unknown"||e.autonomy!=="unknown"||e.explicit_rules.length>0||e.inferred_preferences.length>0}function tS(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 o=typeof n=="string"?n:n.rule;t.push(`- ${o}`)}return t.join(`
1189
- `)}function nS(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(`
1190
- `)}function oS(e){let t=["## Avoid These Mistakes"];for(let n of e)t.push(`- ${n.pattern} (${n.count}x)`);return t.join(`
1191
- `)}function rS(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(`
1192
- `)}function iS(e){let t=Object.values(e).filter(a=>a.token_efficiency&&bp(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)}`,f=a.success_rate>=.9&&a.token_efficiency.efficiency_score>.8?" [PREFERRED]":"";n.push(`- ${a.agent_name}: ${c}%/${u}${f}`)}let o=Ht(),r=o>=1e3?`${(o/1e3).toFixed(0)}k`:o.toString(),i=Math.round(o*1.5),s=i>=1e3?`${(i/1e3).toFixed(0)}k`:i.toString();return n.push(""),n.push(`SESSION BUDGET: ~${r} baseline | warn at ${s}`),n.push("PATTERNS: Parallel reads save 40%"),n.push(""),n.push("Quality remains priority. Use efficiency as tiebreaker."),n.push("</olympus-efficiency>"),n.join(`
1193
- `)}function Rp(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(`
1194
- `)}pt();Ae();var Pp=b(require("path"),1);Ee();J();var qe=b(require("path"),1),hr=b(ue(),1);J();Ee();$t();async function yr(e){try{let t=await te(e);if(t.length===0)return null;let n=t[0],o=qe.join(e,"aidlc-docs",n,"manifest.json"),r=D(o);if(!r)return null;let i=await I(e,n);if(!i)return null;let s=we(e),a=sS(r),l=Li(r,"fulfilled").map(f=>f.id),d=qt(r).filter(f=>f.contract_status!=="fulfilled").map(f=>f.id);return{workflowId:i.workflow_id,featureName:i.feature_name,currentPhase:i.current_phase,currentStage:i.current_stage,manifest:r,checkpoint:i,trustLevel:s.current_level,riskTier:i.risk_tier??0,depthScore:i.depth_score??0,pendingBolts:a,completedBolts:l,pendingUnits:d,executionMode:i.execution_mode??"manual"}}catch(t){return console.error("[WorkflowBridge] Failed to detect active workflow:",t),null}}function sS(e){return nt(e).filter(n=>n.contract_status!=="fulfilled").map(n=>n.id)}function aS(e){let t=qt(e),n=nt(e),o=[...t].sort((a,c)=>a.id.localeCompare(c.id)),r=[],i=new Set;for(let a of o){let l=[...nt(e,a.id)].sort((u,d)=>u.id.localeCompare(d.id));for(let u of l)r.push(u.id),i.add(u.id)}let s=n.filter(a=>!i.has(a.id)).sort((a,c)=>a.id.localeCompare(c.id));for(let a of s)r.push(a.id);return r}function uo(e){let t=nt(e),n=t.length;if(n===0)return{completed:0,total:0,percentage:0};let o=t.filter(i=>i.contract_status==="fulfilled").length,r=Math.round(o/n*100);return{completed:o,total:n,percentage:r}}function lo(e,t){try{if(!hr.existsSync(e))return t;let o=hr.readFileSync(e,"utf-8").split(`
1195
- `);for(let r of o){let i=r.trim();if(i.startsWith("# "))return i.slice(2).trim()}return t}catch{return t}}function gr(e,t){return e.links.find(o=>o.target_id===t&&(o.link_type==="derives"||o.link_type==="implements"))?.source_id??null}function cS(e){let t=e.toLowerCase(),n=["ui","component","frontend","style","css","layout","page","view"];for(let o of n)if(t.includes(o))return"frontend-engineer";return"olympian"}async function Op(e){try{let t=await yr(e);if(!t)return"";let n=uo(t.manifest),o=nt(t.manifest),r=[];for(let a of t.pendingBolts){if(!o.find(m=>m.id===a))continue;let l=gr(t.manifest,a),u=l?qe.join(e,"aidlc-docs",t.workflowId,"construction",l,`${a}.md`):qe.join(e,"aidlc-docs",t.workflowId,"construction",`${a}.md`),d=lo(u,a),f=l?` (${l})`:"";r.push(`- ${a} "${d}"${f}`)}let i=[];for(let a of t.completedBolts){if(!o.find(f=>f.id===a))continue;let l=gr(t.manifest,a),u=l?qe.join(e,"aidlc-docs",t.workflowId,"construction",l,`${a}.md`):qe.join(e,"aidlc-docs",t.workflowId,"construction",`${a}.md`),d=lo(u,a);i.push(`- ${a} "${d}" done`)}let s=["## 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 r.length>0&&(s.push("","### Pending BOLTs:"),s.push(...r)),i.length>0&&(s.push("","### Completed BOLTs:"),s.push(...i)),s.join(`
1196
- `)}catch(t){return console.error("[WorkflowBridge] Failed to generate workflow summary:",t),""}}async function Ap(e){try{let t=await yr(e);if(!t)return"";let n=nt(t.manifest),o=aS(t.manifest),r=new Set(t.pendingBolts),i=qt(t.manifest),s=[],a=1;for(let u of o){if(!r.has(u))continue;let d=n.find(y=>y.id===u);if(!d)continue;let f=gr(t.manifest,u),m=f?qe.join(e,"aidlc-docs",t.workflowId,"construction",f,`${u}.md`):qe.join(e,"aidlc-docs",t.workflowId,"construction",`${u}.md`),p=lo(m,u),g=cS(d.path),h="";if(f){let y=i.find(A=>A.id===f),w=qe.join(e,"aidlc-docs",t.workflowId,"construction",f,"spec.md"),k=lo(w,f);h=` (${f}: ${k})`}s.push(`${a}. ${u} "${p}"${h}`),s.push(` Agent: ${g} | Files: ${d.path}`),a++}let c=[];for(let u of t.completedBolts){if(!n.find(g=>g.id===u))continue;let f=gr(t.manifest,u),m=f?qe.join(e,"aidlc-docs",t.workflowId,"construction",f,`${u}.md`):qe.join(e,"aidlc-docs",t.workflowId,"construction",`${u}.md`),p=lo(m,u);c.push(`- ${u} "${p}" done (fulfilled)`)}let l=["## Workflow Execution Plan",`Workflow: ${t.featureName} (${t.workflowId})`,`Phase: ${t.currentPhase} | Trust: Level ${t.trustLevel} | Risk: Tier ${t.riskTier}`];return s.length>0&&(l.push("","### Pending BOLTs (execute in this order):"),l.push(...s)),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(`
1197
- `)}catch(t){return console.error("[WorkflowBridge] Failed to generate bolt execution plan:",t),""}}async function xp(e){let t=[];try{let n=await te(e);for(let o of n){let r=await I(e,o);if(!r||r.status==="complete"||r.status==="archived")continue;let i=Pp.join(e,"aidlc-docs",o,"manifest.json"),s=D(i),a={completed:0,total:0};s&&(a=uo(s)),t.push({workflowId:r.workflow_id,featureName:r.feature_name,currentPhase:r.current_phase,currentStage:r.current_stage,progress:a,lastActivity:r.updated_at,status:r.status,interviewProgress:r.interview_progress})}}catch(n){console.error("[ResumeDetector] Error checking aidlc-docs:",n)}return t}$t();function $p(){vp(),_({name:"learnedContextInjection",event:"SessionStart",priority:5,handler:e=>{if(!e.directory)return{continue:!0};try{let t=Ip(e.directory),n=rr(e.directory,5),o=Rp(n),r=new Date,i=new Date(r.getTime()-1440*60*1e3);for(let c of n)try{new Date(c.last_useful)<i&&Dd(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>
1188
+ `:l}function n_(e){return e.verbosity!=="unknown"||e.autonomy!=="unknown"||e.explicit_rules.length>0||e.inferred_preferences.length>0}function o_(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 o=typeof n=="string"?n:n.rule;t.push(`- ${o}`)}return t.join(`
1189
+ `)}function r_(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(`
1190
+ `)}function i_(e){let t=["## Avoid These Mistakes"];for(let n of e)t.push(`- ${n.pattern} (${n.count}x)`);return t.join(`
1191
+ `)}function s_(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(`
1192
+ `)}function a_(e){let t=Object.values(e).filter(a=>a.token_efficiency&&Ip(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)}`,f=a.success_rate>=.9&&a.token_efficiency.efficiency_score>.8?" [PREFERRED]":"";n.push(`- ${a.agent_name}: ${c}%/${u}${f}`)}let o=Ht(),r=o>=1e3?`${(o/1e3).toFixed(0)}k`:o.toString(),i=Math.round(o*1.5),s=i>=1e3?`${(i/1e3).toFixed(0)}k`:i.toString();return n.push(""),n.push(`SESSION BUDGET: ~${r} baseline | warn at ${s}`),n.push("PATTERNS: Parallel reads save 40%"),n.push(""),n.push("Quality remains priority. Use efficiency as tiebreaker."),n.push("</olympus-efficiency>"),n.join(`
1193
+ `)}function Ap(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(`
1194
+ `)}pt();Pe();var $p=b(require("path"),1);Ee();J();var qe=b(require("path"),1),hr=b(ue(),1);J();Ee();$t();async function yr(e){try{let t=await te(e);if(t.length===0)return null;let n=t[0],o=qe.join(e,"aidlc-docs",n,"manifest.json"),r=D(o);if(!r)return null;let i=await C(e,n);if(!i)return null;let s=we(e),a=c_(r),l=Fi(r,"fulfilled").map(f=>f.id),d=qt(r).filter(f=>f.contract_status!=="fulfilled").map(f=>f.id);return{workflowId:i.workflow_id,featureName:i.feature_name,currentPhase:i.current_phase,currentStage:i.current_stage,manifest:r,checkpoint:i,trustLevel:s.current_level,riskTier:i.risk_tier??0,depthScore:i.depth_score??0,pendingBolts:a,completedBolts:l,pendingUnits:d,executionMode:i.execution_mode??"manual"}}catch(t){return console.error("[WorkflowBridge] Failed to detect active workflow:",t),null}}function c_(e){return nt(e).filter(n=>n.contract_status!=="fulfilled").map(n=>n.id)}function l_(e){let t=qt(e),n=nt(e),o=[...t].sort((a,c)=>a.id.localeCompare(c.id)),r=[],i=new Set;for(let a of o){let l=[...nt(e,a.id)].sort((u,d)=>u.id.localeCompare(d.id));for(let u of l)r.push(u.id),i.add(u.id)}let s=n.filter(a=>!i.has(a.id)).sort((a,c)=>a.id.localeCompare(c.id));for(let a of s)r.push(a.id);return r}function po(e){let t=nt(e),n=t.length;if(n===0)return{completed:0,total:0,percentage:0};let o=t.filter(i=>i.contract_status==="fulfilled").length,r=Math.round(o/n*100);return{completed:o,total:n,percentage:r}}function uo(e,t){try{if(!hr.existsSync(e))return t;let o=hr.readFileSync(e,"utf-8").split(`
1195
+ `);for(let r of o){let i=r.trim();if(i.startsWith("# "))return i.slice(2).trim()}return t}catch{return t}}function gr(e,t){return e.links.find(o=>o.target_id===t&&(o.link_type==="derives"||o.link_type==="implements"))?.source_id??null}function u_(e){let t=e.toLowerCase(),n=["ui","component","frontend","style","css","layout","page","view"];for(let o of n)if(t.includes(o))return"frontend-engineer";return"olympian"}async function Pp(e){try{let t=await yr(e);if(!t)return"";let n=po(t.manifest),o=nt(t.manifest),r=[];for(let a of t.pendingBolts){if(!o.find(m=>m.id===a))continue;let l=gr(t.manifest,a),u=l?qe.join(e,"aidlc-docs",t.workflowId,"construction",l,`${a}.md`):qe.join(e,"aidlc-docs",t.workflowId,"construction",`${a}.md`),d=uo(u,a),f=l?` (${l})`:"";r.push(`- ${a} "${d}"${f}`)}let i=[];for(let a of t.completedBolts){if(!o.find(f=>f.id===a))continue;let l=gr(t.manifest,a),u=l?qe.join(e,"aidlc-docs",t.workflowId,"construction",l,`${a}.md`):qe.join(e,"aidlc-docs",t.workflowId,"construction",`${a}.md`),d=uo(u,a);i.push(`- ${a} "${d}" done`)}let s=["## 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 r.length>0&&(s.push("","### Pending BOLTs:"),s.push(...r)),i.length>0&&(s.push("","### Completed BOLTs:"),s.push(...i)),s.join(`
1196
+ `)}catch(t){return console.error("[WorkflowBridge] Failed to generate workflow summary:",t),""}}async function xp(e){try{let t=await yr(e);if(!t)return"";let n=nt(t.manifest),o=l_(t.manifest),r=new Set(t.pendingBolts),i=qt(t.manifest),s=[],a=1;for(let u of o){if(!r.has(u))continue;let d=n.find(y=>y.id===u);if(!d)continue;let f=gr(t.manifest,u),m=f?qe.join(e,"aidlc-docs",t.workflowId,"construction",f,`${u}.md`):qe.join(e,"aidlc-docs",t.workflowId,"construction",`${u}.md`),p=uo(m,u),g=u_(d.path),h="";if(f){let y=i.find(A=>A.id===f),w=qe.join(e,"aidlc-docs",t.workflowId,"construction",f,"spec.md"),k=uo(w,f);h=` (${f}: ${k})`}s.push(`${a}. ${u} "${p}"${h}`),s.push(` Agent: ${g} | Files: ${d.path}`),a++}let c=[];for(let u of t.completedBolts){if(!n.find(g=>g.id===u))continue;let f=gr(t.manifest,u),m=f?qe.join(e,"aidlc-docs",t.workflowId,"construction",f,`${u}.md`):qe.join(e,"aidlc-docs",t.workflowId,"construction",`${u}.md`),p=uo(m,u);c.push(`- ${u} "${p}" done (fulfilled)`)}let l=["## Workflow Execution Plan",`Workflow: ${t.featureName} (${t.workflowId})`,`Phase: ${t.currentPhase} | Trust: Level ${t.trustLevel} | Risk: Tier ${t.riskTier}`];return s.length>0&&(l.push("","### Pending BOLTs (execute in this order):"),l.push(...s)),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(`
1197
+ `)}catch(t){return console.error("[WorkflowBridge] Failed to generate bolt execution plan:",t),""}}async function Np(e){let t=[];try{let n=await te(e);for(let o of n){let r=await C(e,o);if(!r||r.status==="complete"||r.status==="archived")continue;let i=$p.join(e,"aidlc-docs",o,"manifest.json"),s=D(i),a={completed:0,total:0};s&&(a=po(s)),t.push({workflowId:r.workflow_id,featureName:r.feature_name,currentPhase:r.current_phase,currentStage:r.current_stage,progress:a,lastActivity:r.updated_at,status:r.status,interviewProgress:r.interview_progress})}}catch(n){console.error("[ResumeDetector] Error checking aidlc-docs:",n)}return t}$t();function Dp(){Ep(),S({name:"learnedContextInjection",event:"SessionStart",priority:5,handler:e=>{if(!e.directory)return{continue:!0};try{let t=Op(e.directory),n=ir(e.directory,5),o=Ap(n),r=new Date,i=new Date(r.getTime()-1440*60*1e3);for(let c of n)try{new Date(c.last_useful)<i&&Md(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>
1198
1198
  [OLYMPUS MODE ACTIVE]
1199
1199
  You are operating as an Olympus orchestrator. MANDATORY behaviors:
1200
1200
  - DELEGATE multi-file changes to subagents (olympian, oracle, frontend-engineer, etc.) via the Task tool
@@ -1206,11 +1206,11 @@ You are operating as an Olympus orchestrator. MANDATORY behaviors:
1206
1206
 
1207
1207
  `+t+(o?`
1208
1208
 
1209
- `+o:"")}}}catch(t){console.error("[Olympus Learning]",t)}return{continue:!0}}}),_({name:"workflowResumeDetection",event:"SessionStart",priority:8,handler:async e=>{try{let t=e.directory||process.cwd(),n=await xp(t);if(n.length===0)return{continue:!0};let o=[];for(let a of n)if(a.status==="awaiting_mode_selection")o.push(`[Active workflow: '${a.featureName}' \u2014 awaiting execution mode selection.
1209
+ `+o:"")}}}catch(t){console.error("[Olympus Learning]",t)}return{continue:!0}}}),S({name:"workflowResumeDetection",event:"SessionStart",priority:8,handler:async e=>{try{let t=e.directory||process.cwd(),n=await Np(t);if(n.length===0)return{continue:!0};let o=[];for(let a of n)if(a.status==="awaiting_mode_selection")o.push(`[Active workflow: '${a.featureName}' \u2014 awaiting execution mode selection.
1210
1210
  Choose: /ascent, /olympus, or /ultrawork to begin Construction]`);else if(a.status==="awaiting_dev_review")o.push(`[Active workflow: '${a.featureName}' \u2014 awaiting developer review (Risk Tier 3).
1211
1211
  Review the INTENT technical specification before proceeding to Construction.]`);else{let c=a.progress.total>0?`, ${a.progress.completed}/${a.progress.total} BOLTs complete`:"";o.push(`[Active workflow: '${a.featureName}' \u2014 ${a.currentPhase} phase${c}.
1212
- Resume with /continue or check status with /workflow-status]`)}let r=we(t);o.push(`[Trust Level: ${r.current_level}]`);let i=await Op(t);i&&o.push(i);let s=await Ap(t);s&&o.push(s);for(let a of n)a.interviewProgress&&o.push(`[Interview in progress: ${a.interviewProgress.stage} stage, ${a.interviewProgress.questions_asked} questions asked${a.interviewProgress.draft_artifact_path?". Draft artifact exists.":""}]`);if(o.length>0)return{continue:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:o.join(`
1213
- `)}}}catch(t){console.error("[Olympus Resume Detection] Error:",t)}return{continue:!0}}}),_({name:"sessionStart",event:"SessionStart",priority:10,handler:async e=>{let t=e.sessionId,n=e.directory||process.cwd(),o=[];try{let s=V(n,t);s.token_budget||($c(s,n),Q(n,s))}catch(s){console.error("[Olympus Learning] Failed to initialize token budget:",s)}let r=_t(n);r?.active&&o.push(`<session-restore>
1212
+ Resume with /continue or check status with /workflow-status]`)}let r=we(t);o.push(`[Trust Level: ${r.current_level}]`);let i=await Pp(t);i&&o.push(i);let s=await xp(t);s&&o.push(s);for(let a of n)a.interviewProgress&&o.push(`[Interview in progress: ${a.interviewProgress.stage} stage, ${a.interviewProgress.questions_asked} questions asked${a.interviewProgress.draft_artifact_path?". Draft artifact exists.":""}]`);if(o.length>0)return{continue:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:o.join(`
1213
+ `)}}}catch(t){console.error("[Olympus Resume Detection] Error:",t)}return{continue:!0}}}),S({name:"sessionStart",event:"SessionStart",priority:10,handler:async e=>{let t=e.sessionId,n=e.directory||process.cwd(),o=[];try{let s=V(n,t);s.token_budget||(Dc(s,n),Q(n,s))}catch(s){console.error("[Olympus Learning] Failed to initialize token budget:",s)}let r=St(n);r?.active&&o.push(`<session-restore>
1214
1214
 
1215
1215
  [ULTRAWORK MODE RESTORED]
1216
1216
 
@@ -1223,7 +1223,7 @@ Continue working in ultrawork mode until all tasks are complete.
1223
1223
 
1224
1224
  ---
1225
1225
 
1226
- `);let i=await co(t,n);return i.count>0&&o.push(`<session-restore>
1226
+ `);let i=await lo(t,n);return i.count>0&&o.push(`<session-restore>
1227
1227
 
1228
1228
  [PENDING TASKS DETECTED]
1229
1229
 
@@ -1235,7 +1235,7 @@ Please continue working on these tasks.
1235
1235
  ---
1236
1236
 
1237
1237
  `),o.length>0?{continue:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:o.join(`
1238
- `)}}:{continue:!0}}})}var An=require("fs"),ht=require("path"),Ts=require("os");var Re=require("fs"),jt=require("path"),Np=require("os");function gs(e){let t=(0,jt.join)(e,".olympus");return(0,jt.join)(t,"ascent-state.json")}function lS(e){let t=(0,jt.join)(e,".olympus");(0,Re.existsSync)(t)||(0,Re.mkdirSync)(t,{recursive:!0})}function Rn(e){let t=gs(e);if(!(0,Re.existsSync)(t))return null;try{let n=(0,Re.readFileSync)(t,"utf-8");return JSON.parse(n)}catch{return null}}function uS(e,t){try{lS(e);let n=gs(e);return(0,Re.writeFileSync)(n,JSON.stringify(t,null,2)),!0}catch{return!1}}function kr(e){let t=gs(e);if(!(0,Re.existsSync)(t))return!0;try{return(0,Re.unlinkSync)(t),!0}catch{return!1}}function Dp(e){let t=Rn(e);return!t||!t.active?null:(t.iteration+=1,uS(e,t)?t:null)}function jp(e,t){let n=(0,jt.join)((0,Np.homedir)(),".claude"),o=[(0,jt.join)(n,"sessions",e,"transcript.md"),(0,jt.join)(n,"sessions",e,"messages.json"),(0,jt.join)(n,"transcripts",`${e}.md`)];for(let r of o)if((0,Re.existsSync)(r))try{let i=(0,Re.readFileSync)(r,"utf-8");if(new RegExp(`<promise>\\s*${dS(t)}\\s*</promise>`,"is").test(i))return!0}catch{continue}return!1}function dS(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Me=require("fs"),hs=require("path"),pS=3;function ys(e){return(0,hs.join)(e,".olympus","ascent-verification.json")}function fo(e){let t=ys(e);if(!(0,Me.existsSync)(t))return null;try{return JSON.parse((0,Me.readFileSync)(t,"utf-8"))}catch{return null}}function Mp(e,t){let n=ys(e),o=(0,hs.join)(e,".olympus");if(!(0,Me.existsSync)(o))try{(0,Me.mkdirSync)(o,{recursive:!0})}catch{return!1}try{return(0,Me.writeFileSync)(n,JSON.stringify(t,null,2)),!0}catch{return!1}}function po(e){let t=ys(e);if((0,Me.existsSync)(t))try{return(0,Me.unlinkSync)(t),!0}catch{return!1}return!0}function Lp(e,t,n){let o={pending:!0,completion_claim:t,verification_attempts:0,max_verification_attempts:pS,requested_at:new Date().toISOString(),original_task:n};return Mp(e,o),o}function Fp(e,t,n){let o=fo(e);return o?(o.verification_attempts+=1,o.oracle_approved=t,o.oracle_feedback=n,t?(po(e),{...o,pending:!1}):o.verification_attempts>=o.max_verification_attempts?(po(e),{...o,pending:!1}):(Mp(e,o),o)):null}function ks(e){return`<ascent-verification>
1238
+ `)}}:{continue:!0}}})}var An=require("fs"),ht=require("path"),bs=require("os");var Oe=require("fs"),jt=require("path"),jp=require("os");function ys(e){let t=(0,jt.join)(e,".olympus");return(0,jt.join)(t,"ascent-state.json")}function d_(e){let t=(0,jt.join)(e,".olympus");(0,Oe.existsSync)(t)||(0,Oe.mkdirSync)(t,{recursive:!0})}function Rn(e){let t=ys(e);if(!(0,Oe.existsSync)(t))return null;try{let n=(0,Oe.readFileSync)(t,"utf-8");return JSON.parse(n)}catch{return null}}function p_(e,t){try{d_(e);let n=ys(e);return(0,Oe.writeFileSync)(n,JSON.stringify(t,null,2)),!0}catch{return!1}}function kr(e){let t=ys(e);if(!(0,Oe.existsSync)(t))return!0;try{return(0,Oe.unlinkSync)(t),!0}catch{return!1}}function Mp(e){let t=Rn(e);return!t||!t.active?null:(t.iteration+=1,p_(e,t)?t:null)}function Lp(e,t){let n=(0,jt.join)((0,jp.homedir)(),".claude"),o=[(0,jt.join)(n,"sessions",e,"transcript.md"),(0,jt.join)(n,"sessions",e,"messages.json"),(0,jt.join)(n,"transcripts",`${e}.md`)];for(let r of o)if((0,Oe.existsSync)(r))try{let i=(0,Oe.readFileSync)(r,"utf-8");if(new RegExp(`<promise>\\s*${f_(t)}\\s*</promise>`,"is").test(i))return!0}catch{continue}return!1}function f_(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Me=require("fs"),ks=require("path"),m_=3;function ws(e){return(0,ks.join)(e,".olympus","ascent-verification.json")}function mo(e){let t=ws(e);if(!(0,Me.existsSync)(t))return null;try{return JSON.parse((0,Me.readFileSync)(t,"utf-8"))}catch{return null}}function Fp(e,t){let n=ws(e),o=(0,ks.join)(e,".olympus");if(!(0,Me.existsSync)(o))try{(0,Me.mkdirSync)(o,{recursive:!0})}catch{return!1}try{return(0,Me.writeFileSync)(n,JSON.stringify(t,null,2)),!0}catch{return!1}}function fo(e){let t=ws(e);if((0,Me.existsSync)(t))try{return(0,Me.unlinkSync)(t),!0}catch{return!1}return!0}function Up(e,t,n){let o={pending:!0,completion_claim:t,verification_attempts:0,max_verification_attempts:m_,requested_at:new Date().toISOString(),original_task:n};return Fp(e,o),o}function Wp(e,t,n){let o=mo(e);return o?(o.verification_attempts+=1,o.oracle_approved=t,o.oracle_feedback=n,t?(fo(e),{...o,pending:!1}):o.verification_attempts>=o.max_verification_attempts?(fo(e),{...o,pending:!1}):(Fp(e,o),o)):null}function Ss(e){return`<ascent-verification>
1239
1239
 
1240
1240
  [ORACLE VERIFICATION REQUIRED - Attempt ${e.verification_attempts+1}/${e.max_verification_attempts}]
1241
1241
 
@@ -1275,7 +1275,7 @@ DO NOT output the completion promise again until Oracle approves.
1275
1275
 
1276
1276
  ---
1277
1277
 
1278
- `}function Up(e){return`<ascent-continuation-after-rejection>
1278
+ `}function Hp(e){return`<ascent-continuation-after-rejection>
1279
1279
 
1280
1280
  [ORACLE REJECTED - Continue Working]
1281
1281
 
@@ -1300,7 +1300,7 @@ Continue working now.
1300
1300
 
1301
1301
  ---
1302
1302
 
1303
- `}function Wp(e){return/<oracle-approved>.*?VERIFIED_COMPLETE.*?<\/oracle-approved>/is.test(e)}function Hp(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 o=e.match(/(?:oracle|feedback|issue|problem|error|bug)[:\s]+([^.]+\.)/i);return{rejected:!0,feedback:o?o[1]:"Oracle found issues with the implementation."}}return{rejected:!1,feedback:""}}var se=require("fs"),On=require("path"),ws=require("os");function _s(e){let t=e||process.cwd(),n=(0,On.join)(t,".olympus");return(0,On.join)(n,"olympus-state.json")}function Ss(){return(0,On.join)((0,ws.homedir)(),".claude","olympus-state.json")}function fS(e){let t=e||process.cwd(),n=(0,On.join)(t,".olympus");(0,se.existsSync)(n)||(0,se.mkdirSync)(n,{recursive:!0})}function mS(){let e=(0,On.join)((0,ws.homedir)(),".claude");(0,se.existsSync)(e)||(0,se.mkdirSync)(e,{recursive:!0})}function Xt(e){let t=_s(e);if((0,se.existsSync)(t))try{let o=(0,se.readFileSync)(t,"utf-8");return JSON.parse(o)}catch{}let n=Ss();if((0,se.existsSync)(n))try{let o=(0,se.readFileSync)(n,"utf-8");return JSON.parse(o)}catch{return null}return null}function Gp(e,t){try{fS(t);let n=_s(t);(0,se.writeFileSync)(n,JSON.stringify(e,null,2)),mS();let o=Ss();return(0,se.writeFileSync)(o,JSON.stringify(e,null,2)),!0}catch{return!1}}function vs(e){let t=_s(e);if((0,se.existsSync)(t))try{(0,se.unlinkSync)(t)}catch{}let n=Ss();if((0,se.existsSync)(n))try{return(0,se.unlinkSync)(n),!0}catch{return!1}return!0}function Bp(e){let t=Xt(e);return!t||!t.active?null:(t.reinforcement_count+=1,t.last_checked_at=new Date().toISOString(),Gp(t,e)?t:null)}function qp(e){let t=Xt(e);return!t||!t.active?!1:(t.oracle_approved=!0,t.last_checked_at=new Date().toISOString(),Gp(t,e))}function Vp(e){let t=e.requires_oracle_verification&&!e.oracle_approved?`
1303
+ `}function Gp(e){return/<oracle-approved>.*?VERIFIED_COMPLETE.*?<\/oracle-approved>/is.test(e)}function Bp(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 o=e.match(/(?:oracle|feedback|issue|problem|error|bug)[:\s]+([^.]+\.)/i);return{rejected:!0,feedback:o?o[1]:"Oracle found issues with the implementation."}}return{rejected:!1,feedback:""}}var se=require("fs"),On=require("path"),_s=require("os");function vs(e){let t=e||process.cwd(),n=(0,On.join)(t,".olympus");return(0,On.join)(n,"olympus-state.json")}function Ts(){return(0,On.join)((0,_s.homedir)(),".claude","olympus-state.json")}function g_(e){let t=e||process.cwd(),n=(0,On.join)(t,".olympus");(0,se.existsSync)(n)||(0,se.mkdirSync)(n,{recursive:!0})}function h_(){let e=(0,On.join)((0,_s.homedir)(),".claude");(0,se.existsSync)(e)||(0,se.mkdirSync)(e,{recursive:!0})}function Xt(e){let t=vs(e);if((0,se.existsSync)(t))try{let o=(0,se.readFileSync)(t,"utf-8");return JSON.parse(o)}catch{}let n=Ts();if((0,se.existsSync)(n))try{let o=(0,se.readFileSync)(n,"utf-8");return JSON.parse(o)}catch{return null}return null}function qp(e,t){try{g_(t);let n=vs(t);(0,se.writeFileSync)(n,JSON.stringify(e,null,2)),h_();let o=Ts();return(0,se.writeFileSync)(o,JSON.stringify(e,null,2)),!0}catch{return!1}}function Es(e){let t=vs(e);if((0,se.existsSync)(t))try{(0,se.unlinkSync)(t)}catch{}let n=Ts();if((0,se.existsSync)(n))try{return(0,se.unlinkSync)(n),!0}catch{return!1}return!0}function Vp(e){let t=Xt(e);return!t||!t.active?null:(t.reinforcement_count+=1,t.last_checked_at=new Date().toISOString(),qp(t,e)?t:null)}function Yp(e){let t=Xt(e);return!t||!t.active?!1:(t.oracle_approved=!0,t.last_checked_at=new Date().toISOString(),qp(t,e))}function Kp(e){let t=e.requires_oracle_verification&&!e.oracle_approved?`
1304
1304
 
1305
1305
  **ORACLE VERIFICATION REQUIRED**: Before declaring complete, you MUST get Oracle approval.`:"";return`<olympus-persistence>
1306
1306
 
@@ -1322,7 +1322,7 @@ Original task: ${e.original_prompt}
1322
1322
 
1323
1323
  ---
1324
1324
 
1325
- `}Ee();function Yp(e){let t=(0,ht.join)((0,Ts.homedir)(),".claude"),n=[(0,ht.join)(t,"sessions",e,"transcript.md"),(0,ht.join)(t,"sessions",e,"messages.json"),(0,ht.join)(t,"transcripts",`${e}.md`)];for(let o of n)if((0,An.existsSync)(o))try{let r=(0,An.readFileSync)(o,"utf-8");if(Wp(r))return!0}catch{continue}return!1}function gS(e){let t=(0,ht.join)((0,Ts.homedir)(),".claude"),n=[(0,ht.join)(t,"sessions",e,"transcript.md"),(0,ht.join)(t,"sessions",e,"messages.json"),(0,ht.join)(t,"transcripts",`${e}.md`)];for(let o of n)if((0,An.existsSync)(o))try{let r=(0,An.readFileSync)(o,"utf-8"),i=Hp(r);if(i.rejected)return i}catch{continue}return{rejected:!1,feedback:""}}async function hS(e,t){let n=t||process.cwd(),o=Rn(n);if(!o||!o.active||o.session_id&&e&&o.session_id!==e)return null;let r=fo(n);if(r?.pending){if(e){if(Yp(e))return po(n),kr(n),{shouldBlock:!1,message:`[ASCENT LOOP VERIFIED COMPLETE] Oracle verified task completion after ${o.iteration} iteration(s). Excellent work!`,mode:"none"};let l=gS(e);if(l.rejected){Fp(n,!1,l.feedback);let u=fo(n);if(u)return{shouldBlock:!0,message:Up(u),mode:"ascent",metadata:{iteration:o.iteration,maxIterations:o.max_iterations}}}}return{shouldBlock:!0,message:ks(r),mode:"ascent",metadata:{iteration:o.iteration,maxIterations:o.max_iterations}}}if(jp(e||"",o.completion_promise)){Lp(n,o.completion_promise,o.prompt);let c=fo(n);return c?{shouldBlock:!0,message:ks(c),mode:"ascent",metadata:{iteration:o.iteration,maxIterations:o.max_iterations}}:(kr(n),{shouldBlock:!1,message:`[ASCENT LOOP COMPLETE] Task completed after ${o.iteration} iteration(s). Great work!`,mode:"none"})}if(o.iteration>=o.max_iterations)return kr(n),po(n),{shouldBlock:!1,message:`[ASCENT LOOP STOPPED] Max iterations (${o.max_iterations}) reached without completion promise. Consider reviewing the task requirements.`,mode:"none"};let s=Dp(n);return s?{shouldBlock:!0,message:`<ascent-continuation>
1325
+ `}Ee();function Jp(e){let t=(0,ht.join)((0,bs.homedir)(),".claude"),n=[(0,ht.join)(t,"sessions",e,"transcript.md"),(0,ht.join)(t,"sessions",e,"messages.json"),(0,ht.join)(t,"transcripts",`${e}.md`)];for(let o of n)if((0,An.existsSync)(o))try{let r=(0,An.readFileSync)(o,"utf-8");if(Gp(r))return!0}catch{continue}return!1}function y_(e){let t=(0,ht.join)((0,bs.homedir)(),".claude"),n=[(0,ht.join)(t,"sessions",e,"transcript.md"),(0,ht.join)(t,"sessions",e,"messages.json"),(0,ht.join)(t,"transcripts",`${e}.md`)];for(let o of n)if((0,An.existsSync)(o))try{let r=(0,An.readFileSync)(o,"utf-8"),i=Bp(r);if(i.rejected)return i}catch{continue}return{rejected:!1,feedback:""}}async function k_(e,t){let n=t||process.cwd(),o=Rn(n);if(!o||!o.active||o.session_id&&e&&o.session_id!==e)return null;let r=mo(n);if(r?.pending){if(e){if(Jp(e))return fo(n),kr(n),{shouldBlock:!1,message:`[ASCENT LOOP VERIFIED COMPLETE] Oracle verified task completion after ${o.iteration} iteration(s). Excellent work!`,mode:"none"};let l=y_(e);if(l.rejected){Wp(n,!1,l.feedback);let u=mo(n);if(u)return{shouldBlock:!0,message:Hp(u),mode:"ascent",metadata:{iteration:o.iteration,maxIterations:o.max_iterations}}}}return{shouldBlock:!0,message:Ss(r),mode:"ascent",metadata:{iteration:o.iteration,maxIterations:o.max_iterations}}}if(Lp(e||"",o.completion_promise)){Up(n,o.completion_promise,o.prompt);let c=mo(n);return c?{shouldBlock:!0,message:Ss(c),mode:"ascent",metadata:{iteration:o.iteration,maxIterations:o.max_iterations}}:(kr(n),{shouldBlock:!1,message:`[ASCENT LOOP COMPLETE] Task completed after ${o.iteration} iteration(s). Great work!`,mode:"none"})}if(o.iteration>=o.max_iterations)return kr(n),fo(n),{shouldBlock:!1,message:`[ASCENT LOOP STOPPED] Max iterations (${o.max_iterations}) reached without completion promise. Consider reviewing the task requirements.`,mode:"none"};let s=Mp(n);return s?{shouldBlock:!0,message:`<ascent-continuation>
1326
1326
 
1327
1327
  [ASCENT LOOP - ITERATION ${s.iteration}/${s.max_iterations}]
1328
1328
 
@@ -1341,7 +1341,7 @@ ${s.prompt?`Original task: ${s.prompt}`:""}
1341
1341
 
1342
1342
  ---
1343
1343
 
1344
- `,mode:"ascent",metadata:{iteration:s.iteration,maxIterations:s.max_iterations}}:null}async function yS(e,t,n){let o=_t(t);if(!o||!o.active||o.session_id&&e&&o.session_id!==e)return null;if(!n)return ac(t),{shouldBlock:!1,message:"[ULTRAWORK COMPLETE] All tasks finished. Ultrawork mode deactivated. Well done!",mode:"none"};let r=cc(t);return r?{shouldBlock:!0,message:lc(r),mode:"ultrawork",metadata:{reinforcementCount:r.reinforcement_count}}:null}async function kS(e,t,n){let o=Xt(t);if(!o||!o.active||o.session_id&&e&&o.session_id!==e)return null;if(!n&&o.oracle_approved)return vs(t),{shouldBlock:!1,message:"[OLYMPUS COMPLETE] All tasks finished and Oracle verified. Orchestration mode deactivated. Excellent work!",mode:"none"};if(!n&&!o.oracle_approved&&o.requires_oracle_verification)return e&&Yp(e)?(qp(t),vs(t),{shouldBlock:!1,message:"[OLYMPUS VERIFIED COMPLETE] Oracle approved. Orchestration mode deactivated. Excellent work!",mode:"none"}):{shouldBlock:!0,message:`<olympus-verification-required>
1344
+ `,mode:"ascent",metadata:{iteration:s.iteration,maxIterations:s.max_iterations}}:null}async function w_(e,t,n){let o=St(t);if(!o||!o.active||o.session_id&&e&&o.session_id!==e)return null;if(!n)return lc(t),{shouldBlock:!1,message:"[ULTRAWORK COMPLETE] All tasks finished. Ultrawork mode deactivated. Well done!",mode:"none"};let r=uc(t);return r?{shouldBlock:!0,message:dc(r),mode:"ultrawork",metadata:{reinforcementCount:r.reinforcement_count}}:null}async function S_(e,t,n){let o=Xt(t);if(!o||!o.active||o.session_id&&e&&o.session_id!==e)return null;if(!n&&o.oracle_approved)return Es(t),{shouldBlock:!1,message:"[OLYMPUS COMPLETE] All tasks finished and Oracle verified. Orchestration mode deactivated. Excellent work!",mode:"none"};if(!n&&!o.oracle_approved&&o.requires_oracle_verification)return e&&Jp(e)?(Yp(t),Es(t),{shouldBlock:!1,message:"[OLYMPUS VERIFIED COMPLETE] Oracle approved. Orchestration mode deactivated. Excellent work!",mode:"none"}):{shouldBlock:!0,message:`<olympus-verification-required>
1345
1345
 
1346
1346
  [OLYMPUS MODE - ORACLE VERIFICATION REQUIRED]
1347
1347
 
@@ -1364,11 +1364,11 @@ DO NOT stop until Oracle has approved.
1364
1364
 
1365
1365
  ---
1366
1366
 
1367
- `,mode:"olympus",metadata:{reinforcementCount:o.reinforcement_count}};let r=Bp(t);return r?{shouldBlock:!0,message:Vp(r),mode:"olympus",metadata:{reinforcementCount:r.reinforcement_count}}:null}async function wS(e,t){let n=await co(e,t);if(n.count===0)return null;let o=Ep(n),r=o?`
1367
+ `,mode:"olympus",metadata:{reinforcementCount:o.reinforcement_count}};let r=Vp(t);return r?{shouldBlock:!0,message:Kp(r),mode:"olympus",metadata:{reinforcementCount:r.reinforcement_count}}:null}async function __(e,t){let n=await lo(e,t);if(n.count===0)return null;let o=Cp(n),r=o?`
1368
1368
 
1369
1369
  Next task: "${o.content}" (${o.status})`:"";return{shouldBlock:!0,message:`<todo-continuation>
1370
1370
 
1371
- ${gc}
1371
+ ${yc}
1372
1372
 
1373
1373
  [Status: ${n.count} of ${n.total} tasks remaining]${r}
1374
1374
 
@@ -1376,11 +1376,11 @@ ${gc}
1376
1376
 
1377
1377
  ---
1378
1378
 
1379
- `,mode:"todo-continuation",metadata:{todoCount:n.count}}}async function _S(e,t,n){let o=t||process.cwd();try{let r=await yr(o);if(!r)return null;let i=uo(r.manifest),s=r.pendingBolts.length>0,a=`
1379
+ `,mode:"todo-continuation",metadata:{todoCount:n.count}}}async function v_(e,t,n){let o=t||process.cwd();try{let r=await yr(o);if(!r)return null;let i=po(r.manifest),s=r.pendingBolts.length>0,a=`
1380
1380
  Workflow '${r.featureName}': ${i.completed}/${i.total} BOLTs complete (${i.percentage}%)`;if(r.pendingBolts.length>0){let l=r.pendingBolts[0];a+=`
1381
- Next: ${l}`}try{await $(o,r.checkpoint)}catch{}return{progressMessage:a,shouldBlock:s&&(n==="ascent"||n==="ultrawork"||n==="olympus")}}catch{return null}}async function Kp(e,t){let n=t||process.cwd(),r=(await co(e,n)).count>0,i=Rn(n),s=_t(n),a=Xt(n),c=null;i?.active?c="ascent":s?.active?c="ultrawork":a?.active&&(c="olympus");let l=await _S(e,n,c),u=await hS(e,n);if(u?.shouldBlock)return l&&(u.message=u.message+`
1382
- ${l.progressMessage}`),u;let d=await yS(e,n,r);if(d?.shouldBlock)return l&&(d.message=d.message+`
1383
- ${l.progressMessage}`),d;let f=await kS(e,n,r);if(f?.shouldBlock)return l&&(f.message=f.message+`
1381
+ Next: ${l}`}try{await $(o,r.checkpoint)}catch{}return{progressMessage:a,shouldBlock:s&&(n==="ascent"||n==="ultrawork"||n==="olympus")}}catch{return null}}async function zp(e,t){let n=t||process.cwd(),r=(await lo(e,n)).count>0,i=Rn(n),s=St(n),a=Xt(n),c=null;i?.active?c="ascent":s?.active?c="ultrawork":a?.active&&(c="olympus");let l=await v_(e,n,c),u=await k_(e,n);if(u?.shouldBlock)return l&&(u.message=u.message+`
1382
+ ${l.progressMessage}`),u;let d=await w_(e,n,r);if(d?.shouldBlock)return l&&(d.message=d.message+`
1383
+ ${l.progressMessage}`),d;let f=await S_(e,n,r);if(f?.shouldBlock)return l&&(f.message=f.message+`
1384
1384
  ${l.progressMessage}`),f;if(l?.shouldBlock)return{shouldBlock:!0,message:`<workflow-continuation>
1385
1385
 
1386
1386
  [WORKFLOW IN PROGRESS - DO NOT STOP]
@@ -1393,21 +1393,21 @@ You are in ${c} mode with pending BOLTs. Continue executing the remaining BOLTs.
1393
1393
 
1394
1394
  ---
1395
1395
 
1396
- `,mode:c||"none",metadata:{}};if(r){let m=await wS(e,n);if(m?.shouldBlock)return l&&(m.message=m.message+`
1397
- ${l.progressMessage}`),m}return l?{shouldBlock:!1,message:l.progressMessage,mode:"none"}:{shouldBlock:!1,message:"",mode:"none"}}function Jp(e){return e.shouldBlock?{continue:!1,stopReason:e.message}:{continue:!0,message:e.message||void 0}}var Pn=require("fs"),Es=require("path"),zp=require("os");Ae();fe();var Qp=require("crypto");function SS(){let e=(0,Es.join)((0,zp.homedir)(),".claude","todos");if(!(0,Pn.existsSync)(e))return 0;let t=0;try{let n=(0,Pn.readdirSync)(e).filter(o=>o.endsWith(".json"));for(let o of n)try{let r=(0,Pn.readFileSync)((0,Es.join)(e,o),"utf-8"),i=JSON.parse(r);Array.isArray(i)&&(t+=i.filter(s=>s.status!=="completed"&&s.status!=="cancelled").length)}catch{}}catch{}return t}async function Xp(e){let{directory:t,sessionId:n}=e;if(!t)return;let o=V(t,n),r=SS();if(r>0&&o.pending_completion){let i={id:(0,Qp.randomUUID)(),timestamp:new Date().toISOString(),session_id:o.session_id,project_path:t,event_type:"cancellation",original_task:o.pending_completion.task_description,agent_used:o.pending_completion.agent_used,user_message:`[Stopped with ${r} incomplete todos]`,feedback_category:"rejection",confidence:.7};St(i)}o.pending_completion=null,o.todo_snapshot={total:0,completed:0,pending:r},Q(t,o)}function Zp(){_({name:"persistentMode",event:"Stop",priority:10,handler:async e=>{let t=e.sessionId,n=e.directory||process.cwd(),o=await Kp(t,n),r=Jp(o);return{continue:r.continue,message:r.message,stopReason:r.stopReason}}}),_({name:"learningCancellationCapture",event:"Stop",priority:100,handler:async e=>e.directory?(Promise.resolve().then(async()=>{try{await Xp({directory:e.directory,sessionId:e.sessionId})}catch(t){console.error("[Olympus Learning]",t)}}),{continue:!0}):{continue:!0}})}var Ns=require("fs"),Ds=require("os"),go=require("path");var Ve=require("fs"),De=require("path");var bs=require("path"),ef=require("os"),vS=(0,bs.join)((0,ef.homedir)(),".olympus"),wr=(0,bs.join)(vS,"rules-injector"),tf=[".git","pyproject.toml","package.json","Cargo.toml","go.mod",".venv"],nf=[[".github","instructions"],[".cursor","rules"],[".claude","rules"]],of=[".github/copilot-instructions.md"],rf=/\.instructions\.md$/,sf=".claude/rules",af=[".md",".mdc"],Cs=["read","write","edit","multiedit"];function TS(e){return e.includes(".github/instructions")||e.endsWith(".github/instructions")}function ES(e,t){return TS(t)?rf.test(e):af.some(n=>e.endsWith(n))}function Os(e){let t;try{t=(0,Ve.statSync)(e).isDirectory()?e:(0,De.dirname)(e)}catch{t=(0,De.dirname)(e)}for(;;){for(let o of tf){let r=(0,De.join)(t,o);if((0,Ve.existsSync)(r))return t}let n=(0,De.dirname)(t);if(n===t)return null;t=n}}function Rs(e,t){if((0,Ve.existsSync)(e))try{let n=(0,Ve.readdirSync)(e,{withFileTypes:!0});for(let o of n){let r=(0,De.join)(e,o.name);o.isDirectory()?Rs(r,t):o.isFile()&&ES(o.name,e)&&t.push(r)}}catch{}}function Is(e){try{return(0,Ve.realpathSync)(e)}catch{return e}}function As(e,t,n){let o=[],r=new Set,i=(0,De.dirname)(n),s=0;for(;;){for(let[u,d]of nf){let f=(0,De.join)(i,u,d),m=[];Rs(f,m);for(let p of m){let g=Is(p);r.has(g)||(r.add(g),o.push({path:p,realPath:g,isGlobal:!1,distance:s}))}}if(e&&i===e)break;let l=(0,De.dirname)(i);if(l===i)break;i=l,s++}if(e)for(let l of of){let u=(0,De.join)(e,l);if((0,Ve.existsSync)(u))try{if((0,Ve.statSync)(u).isFile()){let f=Is(u);r.has(f)||(r.add(f),o.push({path:u,realPath:f,isGlobal:!1,distance:0,isSingleFile:!0}))}}catch{}}let a=(0,De.join)(t,sf),c=[];Rs(a,c);for(let l of c){let u=Is(l);r.has(u)||(r.add(u),o.push({path:l,realPath:u,isGlobal:!0,distance:9999}))}return o.sort((l,u)=>l.isGlobal!==u.isGlobal?l.isGlobal?1:-1:l.distance-u.distance),o}var cf=require("crypto"),lf=require("path");function bS(e,t){let n=e.replace(/\./g,"\\.").replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/<<<GLOBSTAR>>>/g,".*").replace(/\?/g,".");return new RegExp(`^${n}$`).test(t)}function Ps(e,t,n){if(e.alwaysApply===!0)return{applies:!0,reason:"alwaysApply"};let o=e.globs;if(!o)return{applies:!1};let r=Array.isArray(o)?o:[o];if(r.length===0)return{applies:!1};let s=(n?(0,lf.relative)(n,t):t).replace(/\\/g,"/");for(let a of r)if(bS(a,s))return{applies:!0,reason:`glob: ${a}`};return{applies:!1}}function uf(e,t){return t.has(e)}function df(e){return(0,cf.createHash)("sha256").update(e).digest("hex").slice(0,16)}function pf(e,t){return t.has(e)}function xs(e){let t=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,n=e.match(t);if(!n)return{metadata:{},body:e};let o=n[1],r=n[2];try{return{metadata:CS(o),body:r}}catch{return{metadata:{},body:e}}}function CS(e){let t=e.split(`
1398
- `),n={},o=0;for(;o<t.length;){let r=t[o],i=r.indexOf(":");if(i===-1){o++;continue}let s=r.slice(0,i).trim(),a=r.slice(i+1).trim();if(s==="description")n.description=mo(a);else if(s==="alwaysApply")n.alwaysApply=a==="true";else if(s==="globs"||s==="paths"||s==="applyTo"){let{value:c,consumed:l}=IS(a,t,o);n.globs=OS(n.globs,c),o+=l;continue}o++}return n}function mo(e){return e?e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e:""}function IS(e,t,n){if(e.startsWith("["))return{value:RS(e),consumed:1};if(!e||e===""){let r=[],i=1;for(let s=n+1;s<t.length;s++){let a=t[s],c=a.match(/^\s+-\s*(.*)$/);if(c){let l=mo(c[1].trim());l&&r.push(l),i++}else if(a.trim()==="")i++;else break}if(r.length>0)return{value:r,consumed:i}}let o=mo(e);return o.includes(",")?{value:o.split(",").map(i=>i.trim()).filter(i=>i.length>0),consumed:1}:{value:o,consumed:1}}function RS(e){let t=e.slice(1,e.lastIndexOf("]")).trim();if(!t)return[];let n=[],o="",r=!1,i="";for(let a=0;a<t.length;a++){let c=t[a];if(!r&&(c==='"'||c==="'"))r=!0,i=c;else if(r&&c===i)r=!1,i="";else if(!r&&c===","){let l=o.trim();l&&n.push(mo(l)),o=""}else o+=c}let s=o.trim();return s&&n.push(mo(s)),n}function OS(e,t){if(!e)return t;let n=Array.isArray(e)?e:[e],o=Array.isArray(t)?t:[t];return[...n,...o]}var Le=require("fs"),ff=require("path");function $s(e){return(0,ff.join)(wr,`${e}.json`)}function mf(e){let t=$s(e);if(!(0,Le.existsSync)(t))return{contentHashes:new Set,realPaths:new Set};try{let n=(0,Le.readFileSync)(t,"utf-8"),o=JSON.parse(n);return{contentHashes:new Set(o.injectedHashes),realPaths:new Set(o.injectedRealPaths??[])}}catch{return{contentHashes:new Set,realPaths:new Set}}}function gf(e,t){(0,Le.existsSync)(wr)||(0,Le.mkdirSync)(wr,{recursive:!0});let n={sessionId:e,injectedHashes:[...t.contentHashes],injectedRealPaths:[...t.realPaths],updatedAt:Date.now()};(0,Le.writeFileSync)($s(e),JSON.stringify(n,null,2))}function hf(e){let t=$s(e);(0,Le.existsSync)(t)&&(0,Le.unlinkSync)(t)}function yf(e){let t=new Map;function n(s){return t.has(s)||t.set(s,mf(s)),t.get(s)}function o(s){return s?s.startsWith("/")?s:(0,go.resolve)(e,s):null}function r(s,a){let c=o(s);if(!c)return[];let l=Os(c),u=n(a),d=(0,Ds.homedir)(),f=As(l,d,c),m=[];for(let p of f)if(!uf(p.realPath,u.realPaths))try{let g=(0,Ns.readFileSync)(p.path,"utf-8"),{metadata:h,body:y}=xs(g),w;if(p.isSingleFile)w="copilot-instructions (always apply)";else{let v=Ps(h,c,l);if(!v.applies)continue;w=v.reason??"matched"}let k=df(y);if(pf(k,u.contentHashes))continue;let A=l?(0,go.relative)(l,p.path):p.path;m.push({relativePath:A,matchReason:w,content:y,distance:p.distance}),u.realPaths.add(p.realPath),u.contentHashes.add(k)}catch{}return m.length>0&&(m.sort((p,g)=>p.distance-g.distance),gf(a,u)),m}function i(s){if(s.length===0)return"";let a="";for(let c of s)a+=`
1396
+ `,mode:c||"none",metadata:{}};if(r){let m=await __(e,n);if(m?.shouldBlock)return l&&(m.message=m.message+`
1397
+ ${l.progressMessage}`),m}return l?{shouldBlock:!1,message:l.progressMessage,mode:"none"}:{shouldBlock:!1,message:"",mode:"none"}}function Qp(e){return e.shouldBlock?{continue:!1,stopReason:e.message}:{continue:!0,message:e.message||void 0}}var Pn=require("fs"),Cs=require("path"),Xp=require("os");Pe();fe();var Zp=require("crypto");function T_(){let e=(0,Cs.join)((0,Xp.homedir)(),".claude","todos");if(!(0,Pn.existsSync)(e))return 0;let t=0;try{let n=(0,Pn.readdirSync)(e).filter(o=>o.endsWith(".json"));for(let o of n)try{let r=(0,Pn.readFileSync)((0,Cs.join)(e,o),"utf-8"),i=JSON.parse(r);Array.isArray(i)&&(t+=i.filter(s=>s.status!=="completed"&&s.status!=="cancelled").length)}catch{}}catch{}return t}async function ef(e){let{directory:t,sessionId:n}=e;if(!t)return;let o=V(t,n),r=T_();if(r>0&&o.pending_completion){let i={id:(0,Zp.randomUUID)(),timestamp:new Date().toISOString(),session_id:o.session_id,project_path:t,event_type:"cancellation",original_task:o.pending_completion.task_description,agent_used:o.pending_completion.agent_used,user_message:`[Stopped with ${r} incomplete todos]`,feedback_category:"rejection",confidence:.7};_t(i)}o.pending_completion=null,o.todo_snapshot={total:0,completed:0,pending:r},Q(t,o)}function tf(){S({name:"persistentMode",event:"Stop",priority:10,handler:async e=>{let t=e.sessionId,n=e.directory||process.cwd(),o=await zp(t,n),r=Qp(o);return{continue:r.continue,message:r.message,stopReason:r.stopReason}}}),S({name:"learningCancellationCapture",event:"Stop",priority:100,handler:async e=>e.directory?(Promise.resolve().then(async()=>{try{await ef({directory:e.directory,sessionId:e.sessionId})}catch(t){console.error("[Olympus Learning]",t)}}),{continue:!0}):{continue:!0}})}var js=require("fs"),Ms=require("os"),ho=require("path");var Ve=require("fs"),De=require("path");var Is=require("path"),nf=require("os"),E_=(0,Is.join)((0,nf.homedir)(),".olympus"),wr=(0,Is.join)(E_,"rules-injector"),of=[".git","pyproject.toml","package.json","Cargo.toml","go.mod",".venv"],rf=[[".github","instructions"],[".cursor","rules"],[".claude","rules"]],sf=[".github/copilot-instructions.md"],af=/\.instructions\.md$/,cf=".claude/rules",lf=[".md",".mdc"],Rs=["read","write","edit","multiedit"];function b_(e){return e.includes(".github/instructions")||e.endsWith(".github/instructions")}function C_(e,t){return b_(t)?af.test(e):lf.some(n=>e.endsWith(n))}function Ps(e){let t;try{t=(0,Ve.statSync)(e).isDirectory()?e:(0,De.dirname)(e)}catch{t=(0,De.dirname)(e)}for(;;){for(let o of of){let r=(0,De.join)(t,o);if((0,Ve.existsSync)(r))return t}let n=(0,De.dirname)(t);if(n===t)return null;t=n}}function As(e,t){if((0,Ve.existsSync)(e))try{let n=(0,Ve.readdirSync)(e,{withFileTypes:!0});for(let o of n){let r=(0,De.join)(e,o.name);o.isDirectory()?As(r,t):o.isFile()&&C_(o.name,e)&&t.push(r)}}catch{}}function Os(e){try{return(0,Ve.realpathSync)(e)}catch{return e}}function xs(e,t,n){let o=[],r=new Set,i=(0,De.dirname)(n),s=0;for(;;){for(let[u,d]of rf){let f=(0,De.join)(i,u,d),m=[];As(f,m);for(let p of m){let g=Os(p);r.has(g)||(r.add(g),o.push({path:p,realPath:g,isGlobal:!1,distance:s}))}}if(e&&i===e)break;let l=(0,De.dirname)(i);if(l===i)break;i=l,s++}if(e)for(let l of sf){let u=(0,De.join)(e,l);if((0,Ve.existsSync)(u))try{if((0,Ve.statSync)(u).isFile()){let f=Os(u);r.has(f)||(r.add(f),o.push({path:u,realPath:f,isGlobal:!1,distance:0,isSingleFile:!0}))}}catch{}}let a=(0,De.join)(t,cf),c=[];As(a,c);for(let l of c){let u=Os(l);r.has(u)||(r.add(u),o.push({path:l,realPath:u,isGlobal:!0,distance:9999}))}return o.sort((l,u)=>l.isGlobal!==u.isGlobal?l.isGlobal?1:-1:l.distance-u.distance),o}var uf=require("crypto"),df=require("path");function I_(e,t){let n=e.replace(/\./g,"\\.").replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/<<<GLOBSTAR>>>/g,".*").replace(/\?/g,".");return new RegExp(`^${n}$`).test(t)}function $s(e,t,n){if(e.alwaysApply===!0)return{applies:!0,reason:"alwaysApply"};let o=e.globs;if(!o)return{applies:!1};let r=Array.isArray(o)?o:[o];if(r.length===0)return{applies:!1};let s=(n?(0,df.relative)(n,t):t).replace(/\\/g,"/");for(let a of r)if(I_(a,s))return{applies:!0,reason:`glob: ${a}`};return{applies:!1}}function pf(e,t){return t.has(e)}function ff(e){return(0,uf.createHash)("sha256").update(e).digest("hex").slice(0,16)}function mf(e,t){return t.has(e)}function Ns(e){let t=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,n=e.match(t);if(!n)return{metadata:{},body:e};let o=n[1],r=n[2];try{return{metadata:R_(o),body:r}}catch{return{metadata:{},body:e}}}function R_(e){let t=e.split(`
1398
+ `),n={},o=0;for(;o<t.length;){let r=t[o],i=r.indexOf(":");if(i===-1){o++;continue}let s=r.slice(0,i).trim(),a=r.slice(i+1).trim();if(s==="description")n.description=go(a);else if(s==="alwaysApply")n.alwaysApply=a==="true";else if(s==="globs"||s==="paths"||s==="applyTo"){let{value:c,consumed:l}=O_(a,t,o);n.globs=P_(n.globs,c),o+=l;continue}o++}return n}function go(e){return e?e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e:""}function O_(e,t,n){if(e.startsWith("["))return{value:A_(e),consumed:1};if(!e||e===""){let r=[],i=1;for(let s=n+1;s<t.length;s++){let a=t[s],c=a.match(/^\s+-\s*(.*)$/);if(c){let l=go(c[1].trim());l&&r.push(l),i++}else if(a.trim()==="")i++;else break}if(r.length>0)return{value:r,consumed:i}}let o=go(e);return o.includes(",")?{value:o.split(",").map(i=>i.trim()).filter(i=>i.length>0),consumed:1}:{value:o,consumed:1}}function A_(e){let t=e.slice(1,e.lastIndexOf("]")).trim();if(!t)return[];let n=[],o="",r=!1,i="";for(let a=0;a<t.length;a++){let c=t[a];if(!r&&(c==='"'||c==="'"))r=!0,i=c;else if(r&&c===i)r=!1,i="";else if(!r&&c===","){let l=o.trim();l&&n.push(go(l)),o=""}else o+=c}let s=o.trim();return s&&n.push(go(s)),n}function P_(e,t){if(!e)return t;let n=Array.isArray(e)?e:[e],o=Array.isArray(t)?t:[t];return[...n,...o]}var Le=require("fs"),gf=require("path");function Ds(e){return(0,gf.join)(wr,`${e}.json`)}function hf(e){let t=Ds(e);if(!(0,Le.existsSync)(t))return{contentHashes:new Set,realPaths:new Set};try{let n=(0,Le.readFileSync)(t,"utf-8"),o=JSON.parse(n);return{contentHashes:new Set(o.injectedHashes),realPaths:new Set(o.injectedRealPaths??[])}}catch{return{contentHashes:new Set,realPaths:new Set}}}function yf(e,t){(0,Le.existsSync)(wr)||(0,Le.mkdirSync)(wr,{recursive:!0});let n={sessionId:e,injectedHashes:[...t.contentHashes],injectedRealPaths:[...t.realPaths],updatedAt:Date.now()};(0,Le.writeFileSync)(Ds(e),JSON.stringify(n,null,2))}function kf(e){let t=Ds(e);(0,Le.existsSync)(t)&&(0,Le.unlinkSync)(t)}function wf(e){let t=new Map;function n(s){return t.has(s)||t.set(s,hf(s)),t.get(s)}function o(s){return s?s.startsWith("/")?s:(0,ho.resolve)(e,s):null}function r(s,a){let c=o(s);if(!c)return[];let l=Ps(c),u=n(a),d=(0,Ms.homedir)(),f=xs(l,d,c),m=[];for(let p of f)if(!pf(p.realPath,u.realPaths))try{let g=(0,js.readFileSync)(p.path,"utf-8"),{metadata:h,body:y}=Ns(g),w;if(p.isSingleFile)w="copilot-instructions (always apply)";else{let v=$s(h,c,l);if(!v.applies)continue;w=v.reason??"matched"}let k=ff(y);if(mf(k,u.contentHashes))continue;let A=l?(0,ho.relative)(l,p.path):p.path;m.push({relativePath:A,matchReason:w,content:y,distance:p.distance}),u.realPaths.add(p.realPath),u.contentHashes.add(k)}catch{}return m.length>0&&(m.sort((p,g)=>p.distance-g.distance),yf(a,u)),m}function i(s){if(s.length===0)return"";let a="";for(let c of s)a+=`
1399
1399
 
1400
1400
  [Rule: ${c.relativePath}]
1401
1401
  [Match: ${c.matchReason}]
1402
- ${c.content}`;return a}return{processToolExecution:(s,a,c)=>{if(!Cs.includes(s.toLowerCase()))return"";let l=r(a,c);return i(l)},getRulesForFile:s=>{let a=o(s);if(!a)return[];let c=Os(a),l=(0,Ds.homedir)(),u=As(c,l,a),d=[];for(let f of u)try{let m=(0,Ns.readFileSync)(f.path,"utf-8"),{metadata:p,body:g}=xs(m),h;if(f.isSingleFile)h="copilot-instructions (always apply)";else{let w=Ps(p,a,c);if(!w.applies)continue;h=w.reason??"matched"}let y=c?(0,go.relative)(c,f.path):f.path;d.push({relativePath:y,matchReason:h,content:g,distance:f.distance})}catch{}return d.sort((f,m)=>f.distance-m.distance)},clearSession:s=>{t.delete(s),hf(s)},isTrackedTool:s=>Cs.includes(s.toLowerCase())}}var Sr=require("node:fs"),yt=require("node:path");var Fe=require("node:fs"),_f=require("node:path");var js=require("node:path"),kf=require("node:os"),AS=(0,js.join)((0,kf.homedir)(),".olympus"),_r=(0,js.join)(AS,"directory-readme"),wf="README.md",Ms=["read","write","edit","multiedit"];function Ls(e){return(0,_f.join)(_r,`${e}.json`)}function Sf(e){let t=Ls(e);if(!(0,Fe.existsSync)(t))return new Set;try{let n=(0,Fe.readFileSync)(t,"utf-8"),o=JSON.parse(n);return new Set(o.injectedPaths)}catch{return new Set}}function vf(e,t){(0,Fe.existsSync)(_r)||(0,Fe.mkdirSync)(_r,{recursive:!0});let n={sessionID:e,injectedPaths:Array.from(t),updatedAt:Date.now()};(0,Fe.writeFileSync)(Ls(e),JSON.stringify(n,null,2))}function Tf(e){let t=Ls(e);(0,Fe.existsSync)(t)&&(0,Fe.unlinkSync)(t)}var Ef=4,PS=5e3;function xS(e,t=PS){if(Math.ceil(e.length/Ef)<=t)return{result:e,truncated:!1};let o=t*Ef;return{result:e.slice(0,o),truncated:!0}}function bf(e){let t=new Map;function n(s){return t.has(s)||t.set(s,Sf(s)),t.get(s)}function o(s){return s?s.startsWith("/")?s:(0,yt.resolve)(e,s):null}function r(s){let a=[],c=s;for(;;){let l=(0,yt.join)(c,wf);if((0,Sr.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 i(s,a){let c=o(s);if(!c)return"";let l=(0,yt.dirname)(c),u=n(a),d=r(l),f="";for(let m of d){let p=(0,yt.dirname)(m);if(!u.has(p))try{let g=(0,Sr.readFileSync)(m,"utf-8"),{result:h,truncated:y}=xS(g),w=y?`
1402
+ ${c.content}`;return a}return{processToolExecution:(s,a,c)=>{if(!Rs.includes(s.toLowerCase()))return"";let l=r(a,c);return i(l)},getRulesForFile:s=>{let a=o(s);if(!a)return[];let c=Ps(a),l=(0,Ms.homedir)(),u=xs(c,l,a),d=[];for(let f of u)try{let m=(0,js.readFileSync)(f.path,"utf-8"),{metadata:p,body:g}=Ns(m),h;if(f.isSingleFile)h="copilot-instructions (always apply)";else{let w=$s(p,a,c);if(!w.applies)continue;h=w.reason??"matched"}let y=c?(0,ho.relative)(c,f.path):f.path;d.push({relativePath:y,matchReason:h,content:g,distance:f.distance})}catch{}return d.sort((f,m)=>f.distance-m.distance)},clearSession:s=>{t.delete(s),kf(s)},isTrackedTool:s=>Rs.includes(s.toLowerCase())}}var _r=require("node:fs"),yt=require("node:path");var Fe=require("node:fs"),vf=require("node:path");var Ls=require("node:path"),Sf=require("node:os"),x_=(0,Ls.join)((0,Sf.homedir)(),".olympus"),Sr=(0,Ls.join)(x_,"directory-readme"),_f="README.md",Fs=["read","write","edit","multiedit"];function Us(e){return(0,vf.join)(Sr,`${e}.json`)}function Tf(e){let t=Us(e);if(!(0,Fe.existsSync)(t))return new Set;try{let n=(0,Fe.readFileSync)(t,"utf-8"),o=JSON.parse(n);return new Set(o.injectedPaths)}catch{return new Set}}function Ef(e,t){(0,Fe.existsSync)(Sr)||(0,Fe.mkdirSync)(Sr,{recursive:!0});let n={sessionID:e,injectedPaths:Array.from(t),updatedAt:Date.now()};(0,Fe.writeFileSync)(Us(e),JSON.stringify(n,null,2))}function bf(e){let t=Us(e);(0,Fe.existsSync)(t)&&(0,Fe.unlinkSync)(t)}var Cf=4,$_=5e3;function N_(e,t=$_){if(Math.ceil(e.length/Cf)<=t)return{result:e,truncated:!1};let o=t*Cf;return{result:e.slice(0,o),truncated:!0}}function If(e){let t=new Map;function n(s){return t.has(s)||t.set(s,Tf(s)),t.get(s)}function o(s){return s?s.startsWith("/")?s:(0,yt.resolve)(e,s):null}function r(s){let a=[],c=s;for(;;){let l=(0,yt.join)(c,_f);if((0,_r.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 i(s,a){let c=o(s);if(!c)return"";let l=(0,yt.dirname)(c),u=n(a),d=r(l),f="";for(let m of d){let p=(0,yt.dirname)(m);if(!u.has(p))try{let g=(0,_r.readFileSync)(m,"utf-8"),{result:h,truncated:y}=N_(g),w=y?`
1403
1403
 
1404
1404
  [Note: Content was truncated to save context window space. For full context, please read the file directly: ${m}]`:"";f+=`
1405
1405
 
1406
1406
  [Project README: ${m}]
1407
- ${h}${w}`,u.add(p)}catch{}}return f&&vf(a,u),f}return{processToolExecution:(s,a,c)=>Ms.includes(s.toLowerCase())?i(a,c):"",getReadmesForFile:s=>{let a=o(s);if(!a)return[];let c=(0,yt.dirname)(a);return r(c)},clearSession:s=>{t.delete(s),Tf(s)},isTrackedTool:s=>Ms.includes(s.toLowerCase())}}var Cf="non-interactive-env",If={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"},Fs={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
1407
+ ${h}${w}`,u.add(p)}catch{}}return f&&Ef(a,u),f}return{processToolExecution:(s,a,c)=>Fs.includes(s.toLowerCase())?i(a,c):"",getReadmesForFile:s=>{let a=o(s);if(!a)return[];let c=(0,yt.dirname)(a);return r(c)},clearSession:s=>{t.delete(s),bf(s)},isTrackedTool:s=>Fs.includes(s.toLowerCase())}}var Rf="non-interactive-env",Of={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"},Ws={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
1408
1408
  option1
1409
1409
  option2
1410
- EOF`,expectAlternative:"Use environment variables or config files instead of expect"}};var Rf=Fs.banned.filter(e=>!e.includes("(")).map(e=>new RegExp(`\\b${e}\\b`));function $S(e){for(let t=0;t<Rf.length;t++)if(Rf[t].test(e))return Fs.banned[t]}function NS(e){return e===""?"''":/[^a-zA-Z0-9_\-.:\/]/.test(e)?`'${e.replace(/'/g,"'\\''")}'`:e}function DS(e){return`export ${Object.entries(e).map(([n,o])=>`${n}=${NS(o)}`).join(" ")};`}var Us={name:Cf,async beforeCommand(e){let t=$S(e),n=t?`Warning: '${t}' is an interactive command that may hang in non-interactive environments.`:void 0;return/\bgit\b/.test(e)?{command:`${DS(If)} ${e}`,warning:n}:{command:e,warning:n}}};var Hs=require("child_process");var Of="olympus-orchestrator",Af=".olympus/",Pf=["Write","Edit","write","edit"],xf=`
1410
+ EOF`,expectAlternative:"Use environment variables or config files instead of expect"}};var Af=Ws.banned.filter(e=>!e.includes("(")).map(e=>new RegExp(`\\b${e}\\b`));function D_(e){for(let t=0;t<Af.length;t++)if(Af[t].test(e))return Ws.banned[t]}function j_(e){return e===""?"''":/[^a-zA-Z0-9_\-.:\/]/.test(e)?`'${e.replace(/'/g,"'\\''")}'`:e}function M_(e){return`export ${Object.entries(e).map(([n,o])=>`${n}=${j_(o)}`).join(" ")};`}var Hs={name:Rf,async beforeCommand(e){let t=D_(e),n=t?`Warning: '${t}' is an interactive command that may hang in non-interactive environments.`:void 0;return/\bgit\b/.test(e)?{command:`${M_(Of)} ${e}`,warning:n}:{command:e,warning:n}}};var Bs=require("child_process");var Pf="olympus-orchestrator",xf=".olympus/",$f=["Write","Edit","write","edit"],Nf=`
1411
1411
 
1412
1412
  ---
1413
1413
 
@@ -1433,7 +1433,7 @@ You should NOT:
1433
1433
  3. Verify the subagent's work after completion
1434
1434
 
1435
1435
  ---
1436
- `;var $f=`[SYSTEM REMINDER - QUEST CONTINUATION]
1436
+ `;var Df=`[SYSTEM REMINDER - QUEST CONTINUATION]
1437
1437
 
1438
1438
  You have an active work plan with incomplete tasks. Continue working.
1439
1439
 
@@ -1442,7 +1442,7 @@ RULES:
1442
1442
  - Mark each checkbox [x] in the plan file when done
1443
1443
  - Learnings are automatically captured in .olympus/learning/discoveries.jsonl
1444
1444
  - Do not stop until all tasks are complete
1445
- - If blocked, document the blocker and move to the next task`,Nf=`**MANDATORY VERIFICATION - SUBAGENTS LIE**
1445
+ - If blocked, document the blocker and move to the next task`,jf=`**MANDATORY VERIFICATION - SUBAGENTS LIE**
1446
1446
 
1447
1447
  Subagents FREQUENTLY claim completion when:
1448
1448
  - Tests are actually FAILING
@@ -1457,7 +1457,7 @@ Subagents FREQUENTLY claim completion when:
1457
1457
  3. Check build/typecheck - Must succeed
1458
1458
 
1459
1459
  DO NOT TRUST THE AGENT'S SELF-REPORT.
1460
- VERIFY EACH CLAIM WITH YOUR OWN TOOL CALLS.`,Df=`
1460
+ VERIFY EACH CLAIM WITH YOUR OWN TOOL CALLS.`,Mf=`
1461
1461
 
1462
1462
  [SYSTEM DIRECTIVE - SINGLE TASK ONLY]
1463
1463
 
@@ -1480,7 +1480,7 @@ If you were NOT given **exactly ONE atomic task**, you MUST:
1480
1480
  - Batch delegation = sloppy work = rework = wasted tokens
1481
1481
 
1482
1482
  **REFUSE multi-task requests. DEMAND single-task clarity.**
1483
- `,jf=`
1483
+ `,Lf=`
1484
1484
 
1485
1485
  ================================================================================
1486
1486
  HARD BLOCK: DELEGATION REQUIRED
@@ -1519,41 +1519,41 @@ This is a HARD BLOCK. The operation will NOT be executed.
1519
1519
  Delegate to a subagent to proceed.
1520
1520
 
1521
1521
  ================================================================================
1522
- `;var ho=".olympus",vr="quest.json",jS=`${ho}/${vr}`,Mf="notepads",MS=`${ho}/${Mf}`;var Ye=require("fs"),Tr=require("path");function Lf(e){return(0,Tr.join)(e,ho,vr)}function Er(e){let t=Lf(e);if(!(0,Ye.existsSync)(t))return null;try{let n=(0,Ye.readFileSync)(t,"utf-8");return JSON.parse(n)}catch{return null}}function br(e){if(!(0,Ye.existsSync)(e))return{total:0,completed:0,isComplete:!0};try{let t=(0,Ye.readFileSync)(e,"utf-8"),n=t.match(/^[-*]\s*\[\s*\]/gm)||[],o=t.match(/^[-*]\s*\[[xX]\]/gm)||[],r=n.length+o.length,i=o.length;return{total:r,completed:i,isComplete:r===0||i===r}}catch{return{total:0,completed:0,isComplete:!0}}}var yo=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(r=>r.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}},LO=new yo;var Zt=require("fs"),Ws=require("path");function ko(e,t){let n=t||process.cwd(),o=(0,Ws.join)(n,".olympus","logs"),r=(0,Ws.join)(o,"hook-violations.jsonl");try{(0,Zt.existsSync)(o)||(0,Zt.mkdirSync)(o,{recursive:!0});let i=JSON.stringify(e)+`
1523
- `;(0,Zt.appendFileSync)(r,i,"utf-8")}catch(i){console.error("[Hook Logging] Failed to log violation:",i)}}var Ff=new yo;function Uf(e){return e?e.replace(/\\/g,"/").includes(Af):!0}function US(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 WS(e,t){if(!t)return 0;if(e==="Edit"||e==="edit"){let n=t.old_string??"",o=t.new_string??"";if(!n&&!o)return 0;let r=n.split(`
1522
+ `;var yo=".olympus",vr="quest.json",L_=`${yo}/${vr}`,Ff="notepads",F_=`${yo}/${Ff}`;var Ye=require("fs"),Tr=require("path");function Uf(e){return(0,Tr.join)(e,yo,vr)}function Er(e){let t=Uf(e);if(!(0,Ye.existsSync)(t))return null;try{let n=(0,Ye.readFileSync)(t,"utf-8");return JSON.parse(n)}catch{return null}}function br(e){if(!(0,Ye.existsSync)(e))return{total:0,completed:0,isComplete:!0};try{let t=(0,Ye.readFileSync)(e,"utf-8"),n=t.match(/^[-*]\s*\[\s*\]/gm)||[],o=t.match(/^[-*]\s*\[[xX]\]/gm)||[],r=n.length+o.length,i=o.length;return{total:r,completed:i,isComplete:r===0||i===r}}catch{return{total:0,completed:0,isComplete:!0}}}var ko=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(r=>r.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}},UO=new ko;var Zt=require("fs"),Gs=require("path");function wo(e,t){let n=t||process.cwd(),o=(0,Gs.join)(n,".olympus","logs"),r=(0,Gs.join)(o,"hook-violations.jsonl");try{(0,Zt.existsSync)(o)||(0,Zt.mkdirSync)(o,{recursive:!0});let i=JSON.stringify(e)+`
1523
+ `;(0,Zt.appendFileSync)(r,i,"utf-8")}catch(i){console.error("[Hook Logging] Failed to log violation:",i)}}var Wf=new ko;function Hf(e){return e?e.replace(/\\/g,"/").includes(xf):!0}function H_(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 G_(e,t){if(!t)return 0;if(e==="Edit"||e==="edit"){let n=t.old_string??"",o=t.new_string??"";if(!n&&!o)return 0;let r=n.split(`
1524
1524
  `).length,i=o.split(`
1525
1525
  `).length;return Math.abs(i-r)}if(e==="Write"||e==="write"){let n=t.content??"";return n?n.split(`
1526
- `).length:0}return 0}function Wf(e){return Pf.includes(e)}function HS(e){try{let t=(0,Hs.execSync)("git diff --numstat HEAD",{cwd:e,encoding:"utf-8",timeout:5e3}).trim();if(!t)return[];let n=(0,Hs.execSync)("git status --porcelain",{cwd:e,encoding:"utf-8",timeout:5e3}).trim(),o=new Map;for(let i of n.split(`
1526
+ `).length:0}return 0}function Gf(e){return $f.includes(e)}function B_(e){try{let t=(0,Bs.execSync)("git diff --numstat HEAD",{cwd:e,encoding:"utf-8",timeout:5e3}).trim();if(!t)return[];let n=(0,Bs.execSync)("git status --porcelain",{cwd:e,encoding:"utf-8",timeout:5e3}).trim(),o=new Map;for(let i of n.split(`
1527
1527
  `)){if(!i)continue;let s=i.substring(0,2).trim(),a=i.substring(3);s==="A"||s==="??"?o.set(a,"added"):s==="D"?o.set(a,"deleted"):o.set(a,"modified")}let r=[];for(let i of t.split(`
1528
- `)){let s=i.split(" ");if(s.length<3)continue;let[a,c,l]=s,u=a==="-"?0:parseInt(a,10),d=c==="-"?0:parseInt(c,10);r.push({path:l,added:u,removed:d,status:o.get(l)??"modified"})}return r}catch{return[]}}function GS(e){if(e.length===0)return`[FILE CHANGES SUMMARY]
1528
+ `)){let s=i.split(" ");if(s.length<3)continue;let[a,c,l]=s,u=a==="-"?0:parseInt(a,10),d=c==="-"?0:parseInt(c,10);r.push({path:l,added:u,removed:d,status:o.get(l)??"modified"})}return r}catch{return[]}}function q_(e){if(e.length===0)return`[FILE CHANGES SUMMARY]
1529
1529
  No file changes detected.
1530
1530
  `;let t=e.filter(i=>i.status==="modified"),n=e.filter(i=>i.status==="added"),o=e.filter(i=>i.status==="deleted"),r=["[FILE CHANGES SUMMARY]"];if(t.length>0){r.push("Modified files:");for(let i of t)r.push(` ${i.path} (+${i.added}, -${i.removed})`);r.push("")}if(n.length>0){r.push("Created files:");for(let i of n)r.push(` ${i.path} (+${i.added})`);r.push("")}if(o.length>0){r.push("Deleted files:");for(let i of o)r.push(` ${i.path} (-${i.removed})`);r.push("")}return r.join(`
1531
- `)}function Hf(e){let t=Nf;return e&&(t+=`
1531
+ `)}function Bf(e){let t=jf;return e&&(t+=`
1532
1532
 
1533
1533
  ---
1534
1534
 
1535
1535
  **If ANY verification fails, resume the subagent with the fix:**
1536
- Task tool with resume="${e}", prompt="fix: [describe the specific failure]"`),t}function BS(e,t,n){let o=t.total-t.completed;return`
1536
+ Task tool with resume="${e}", prompt="fix: [describe the specific failure]"`),t}function V_(e,t,n){let o=t.total-t.completed;return`
1537
1537
  ---
1538
1538
 
1539
1539
  **State:** Plan: ${e} | ${t.completed}/${t.total} done, ${o} left
1540
1540
 
1541
1541
  ---
1542
1542
 
1543
- ${Hf(n)}
1543
+ ${Bf(n)}
1544
1544
 
1545
- ALL pass? \u2192 commit atomic unit, mark \`[x]\`, next task.`}function qS(e,t,n){return $f.replace(/{PLAN_NAME}/g,e)+`
1545
+ ALL pass? \u2192 commit atomic unit, mark \`[x]\`, next task.`}function Y_(e,t,n){return Df.replace(/{PLAN_NAME}/g,e)+`
1546
1546
 
1547
- [Status: ${n-t}/${n} completed, ${t} remaining]`}function VS(e){let{toolName:t,toolInput:n,directory:o}=e,r=o||process.cwd();if(!Wf(t))return{continue:!0};let i=n?.filePath??n?.path??n?.file;if(!i)return{continue:!0};let s=i.replace(/\\/g,"/");if(Uf(s))return ko({timestamp:new Date().toISOString(),filePath:s,toolName:t,wasBlocked:!1,reason:"Allowed: .olympus/ path"},r),{continue:!0};if(US(s))return ko({timestamp:new Date().toISOString(),filePath:s,toolName:t,wasBlocked:!1,reason:"Allowed: Test file"},r),{continue:!0};let a=WS(t,n);return Ff.isVerificationEdit(s,a)?(ko({timestamp:new Date().toISOString(),filePath:s,toolName:t,linesChanged:a,wasBlocked:!1,reason:`Allowed: Verification edit (${a} lines on recent task file)`},r),{continue:!0}):(ko({timestamp:new Date().toISOString(),filePath:s,toolName:t,linesChanged:a,wasBlocked:!0,reason:"Blocked: Direct source file modification (delegation required)"},r),{continue:!1,message:jf})}function YS(e,t){let{toolName:n,toolInput:o,directory:r,sessionId:i}=e,s=r||process.cwd();if(Wf(n)){let a=o?.filePath??o?.path??o?.file;if(a&&!Uf(a))return{continue:!0,modifiedOutput:t+xf}}if(n==="Task"||n==="task"){if(t.includes("Background task launched")||t.includes("Background task resumed"))return{continue:!0};let c=HS(s),l=c.map(f=>f.path);Ff.recordTaskCompletion({timestamp:Date.now(),filesModified:l,taskId:i||`task-${Date.now()}`});let u=GS(c),d=Er(s);if(d){let f=br(d.active_plan);return{continue:!0,modifiedOutput:`
1547
+ [Status: ${n-t}/${n} completed, ${t} remaining]`}function K_(e){let{toolName:t,toolInput:n,directory:o}=e,r=o||process.cwd();if(!Gf(t))return{continue:!0};let i=n?.filePath??n?.path??n?.file;if(!i)return{continue:!0};let s=i.replace(/\\/g,"/");if(Hf(s))return wo({timestamp:new Date().toISOString(),filePath:s,toolName:t,wasBlocked:!1,reason:"Allowed: .olympus/ path"},r),{continue:!0};if(H_(s))return wo({timestamp:new Date().toISOString(),filePath:s,toolName:t,wasBlocked:!1,reason:"Allowed: Test file"},r),{continue:!0};let a=G_(t,n);return Wf.isVerificationEdit(s,a)?(wo({timestamp:new Date().toISOString(),filePath:s,toolName:t,linesChanged:a,wasBlocked:!1,reason:`Allowed: Verification edit (${a} lines on recent task file)`},r),{continue:!0}):(wo({timestamp:new Date().toISOString(),filePath:s,toolName:t,linesChanged:a,wasBlocked:!0,reason:"Blocked: Direct source file modification (delegation required)"},r),{continue:!1,message:Lf})}function J_(e,t){let{toolName:n,toolInput:o,directory:r,sessionId:i}=e,s=r||process.cwd();if(Gf(n)){let a=o?.filePath??o?.path??o?.file;if(a&&!Hf(a))return{continue:!0,modifiedOutput:t+Nf}}if(n==="Task"||n==="task"){if(t.includes("Background task launched")||t.includes("Background task resumed"))return{continue:!0};let c=B_(s),l=c.map(f=>f.path);Wf.recordTaskCompletion({timestamp:Date.now(),filesModified:l,taskId:i||`task-${Date.now()}`});let u=q_(c),d=Er(s);if(d){let f=br(d.active_plan);return{continue:!0,modifiedOutput:`
1548
1548
  ## SUBAGENT WORK COMPLETED
1549
1549
 
1550
1550
  ${u}
1551
1551
  <system-reminder>
1552
- ${BS(d.plan_name,f,i)}
1552
+ ${V_(d.plan_name,f,i)}
1553
1553
  </system-reminder>`}}return{continue:!0,modifiedOutput:t+`
1554
1554
  <system-reminder>
1555
- ${Hf(i)}
1556
- </system-reminder>`}}return{continue:!0}}function KS(e){let t=Er(e);if(!t)return{shouldContinue:!1};let n=br(t.active_plan);if(n.isComplete)return{shouldContinue:!1};let o=n.total-n.completed;return{shouldContinue:!0,message:qS(t.plan_name,o,n.total)}}function Cr(e){return{name:Of,preTool:(t,n)=>VS({toolName:t,toolInput:n,directory:e}),postTool:(t,n,o)=>YS({toolName:t,toolInput:n,directory:e},o),checkContinuation:()=>KS(e),getSingleTaskDirective:()=>Df}}function Gf(e){if(!e||typeof e!="object")return null;let t=e;return t.file_path||t.filePath||t.path||t.file}function Bf(){_({name:"rulesInjector",event:"PreToolUse",priority:10,matcher:/^(read|edit|write|glob|grep)$/i,handler:e=>{let t=yf(e.directory||process.cwd()),n=Gf(e.toolInput);if(!n)return{continue:!0};let o=t.processToolExecution(e.toolName,n,e.sessionId||"default");return{continue:!0,hookSpecificOutput:o?{hookEventName:"PreToolUse",additionalContext:o}:void 0}}}),_({name:"directoryReadmeInjector",event:"PreToolUse",priority:20,matcher:/^(read|edit|write|glob|grep|bash)$/i,handler:e=>{let t=bf(e.directory||process.cwd()),n=Gf(e.toolInput);if(!n)return{continue:!0};let o=t.processToolExecution(e.toolName,n,e.sessionId||"default");return{continue:!0,hookSpecificOutput:o?{hookEventName:"PreToolUse",additionalContext:o}:void 0}}}),_({name:"nonInteractiveEnv",event:"PreToolUse",priority:30,matcher:/^bash$/i,handler:async e=>{let t=e.toolInput;if(!t?.command)return{continue:!0};try{if(!Us.beforeCommand)return{continue:!0};let n=await Us.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}}}}),_({name:"olympusOrchestratorPre",event:"PreToolUse",priority:40,matcher:/^(write|edit|bash|task)$/i,handler:e=>Cr(e.directory||process.cwd()).preTool(e.toolName,e.toolInput)})}var JS=["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"],zS=`
1555
+ ${Bf(i)}
1556
+ </system-reminder>`}}return{continue:!0}}function z_(e){let t=Er(e);if(!t)return{shouldContinue:!1};let n=br(t.active_plan);if(n.isComplete)return{shouldContinue:!1};let o=n.total-n.completed;return{shouldContinue:!0,message:Y_(t.plan_name,o,n.total)}}function Cr(e){return{name:Pf,preTool:(t,n)=>K_({toolName:t,toolInput:n,directory:e}),postTool:(t,n,o)=>J_({toolName:t,toolInput:n,directory:e},o),checkContinuation:()=>z_(e),getSingleTaskDirective:()=>Mf}}function qf(e){if(!e||typeof e!="object")return null;let t=e;return t.file_path||t.filePath||t.path||t.file}function Vf(){S({name:"rulesInjector",event:"PreToolUse",priority:10,matcher:/^(read|edit|write|glob|grep)$/i,handler:e=>{let t=wf(e.directory||process.cwd()),n=qf(e.toolInput);if(!n)return{continue:!0};let o=t.processToolExecution(e.toolName,n,e.sessionId||"default");return{continue:!0,hookSpecificOutput:o?{hookEventName:"PreToolUse",additionalContext:o}:void 0}}}),S({name:"directoryReadmeInjector",event:"PreToolUse",priority:20,matcher:/^(read|edit|write|glob|grep|bash)$/i,handler:e=>{let t=If(e.directory||process.cwd()),n=qf(e.toolInput);if(!n)return{continue:!0};let o=t.processToolExecution(e.toolName,n,e.sessionId||"default");return{continue:!0,hookSpecificOutput:o?{hookEventName:"PreToolUse",additionalContext:o}:void 0}}}),S({name:"nonInteractiveEnv",event:"PreToolUse",priority:30,matcher:/^bash$/i,handler:async e=>{let t=e.toolInput;if(!t?.command)return{continue:!0};try{if(!Hs.beforeCommand)return{continue:!0};let n=await Hs.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}}}}),S({name:"olympusOrchestratorPre",event:"PreToolUse",priority:40,matcher:/^(write|edit|bash|task)$/i,handler:e=>Cr(e.directory||process.cwd()).preTool(e.toolName,e.toolInput)})}var Q_=["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"],X_=`
1557
1557
  [EDIT ERROR - IMMEDIATE ACTION REQUIRED]
1558
1558
 
1559
1559
  You made an Edit mistake. STOP and do this NOW:
@@ -1564,7 +1564,7 @@ You made an Edit mistake. STOP and do this NOW:
1564
1564
  4. CONTINUE with corrected action based on the real file content
1565
1565
 
1566
1566
  DO NOT attempt another edit until you've read and verified the file state.
1567
- `;function QS(e){let t=e.toLowerCase();return JS.some(n=>t.includes(n.toLowerCase()))}function qf(){return{afterToolExecute:(e,t)=>e.tool.toLowerCase()!=="edit"?t:QS(t.output)?{...t,output:t.output+zS}:t}}var Kf=b(require("fs"),1),Rr=b(require("path"),1),Jf=require("os");var Ir=new Set(["given","when","then","arrange","act","assert","when & then","when&then"]),Gs=["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"],Bs=`COMMENT/DOCSTRING DETECTED - IMMEDIATE ACTION REQUIRED
1567
+ `;function Z_(e){let t=e.toLowerCase();return Q_.some(n=>t.includes(n.toLowerCase()))}function Yf(){return{afterToolExecute:(e,t)=>e.tool.toLowerCase()!=="edit"?t:Z_(t.output)?{...t,output:t.output+X_}:t}}var zf=b(require("fs"),1),Rr=b(require("path"),1),Qf=require("os");var Ir=new Set(["given","when","then","arrange","act","assert","when & then","when&then"]),qs=["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"],Vs=`COMMENT/DOCSTRING DETECTED - IMMEDIATE ACTION REQUIRED
1568
1568
 
1569
1569
  Your recent changes contain comments or docstrings, which triggered this hook.
1570
1570
  You need to take immediate action. You must follow the conditions below.
@@ -1602,13 +1602,13 @@ MANDATORY REQUIREMENT: You must acknowledge this hook message and take one of th
1602
1602
  Review in the above priority order and take the corresponding action EVERY TIME this appears.
1603
1603
 
1604
1604
  Detected comments/docstrings:
1605
- `,qs={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},Vs={".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 XS(e){return e.text.trim().startsWith("#!")&&e.lineNumber===1?{shouldSkip:!0,reason:"shebang"}:{shouldSkip:!1}}function ZS(e){if(e.isDocstring)return{shouldSkip:!1};let t=e.text.toLowerCase().trim();for(let n of Ir){if(t.startsWith(`#${n}`)||t.startsWith(`// ${n}`))return{shouldSkip:!0,reason:`BDD keyword: ${n}`};if(t.includes(n)&&t.split(/\s+/).some(r=>Ir.has(r.replace(/[^a-z&]/g,""))))return{shouldSkip:!0,reason:"BDD keyword detected"}}return{shouldSkip:!1}}function ev(e){let t=e.text.toLowerCase().trim();for(let n of Gs)if(t.includes(n.toLowerCase()))return{shouldSkip:!0,reason:`directive: ${n}`};return{shouldSkip:!1}}function tv(e){return{shouldSkip:!1}}function nv(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 o of n)if(t.includes(o))return{shouldSkip:!0,reason:"copyright/license"};return{shouldSkip:!1}}function ov(e){let t=e.text.toUpperCase(),n=["TODO","FIXME","HACK","XXX","NOTE","REVIEW"];for(let o of n)if(t.includes(o))return{shouldSkip:!0,reason:`todo marker: ${o}`};return{shouldSkip:!1}}var rv=[XS,ZS,ev,nv,ov,tv];function Ys(e){return e.filter(t=>{for(let n of rv)if(n(t).shouldSkip)return!1;return!0})}var iv=process.env.COMMENT_CHECKER_DEBUG==="1",sv=Rr.join((0,Jf.tmpdir)(),"comment-checker-debug.log");function en(...e){if(iv){let t=`[${new Date().toISOString()}] [comment-checker] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
1606
- `;Kf.appendFileSync(sv,t)}}function av(e){let t=Rr.extname(e).toLowerCase();return Vs[t]}function Ks(e,t){let n=av(t);if(!n)return en("unsupported language for:",t),[];let o=qs[n];if(!o)return en("no pattern for language:",n),[];let r=[],i=e.split(`
1605
+ `,Ys={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},Ks={".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 ev(e){return e.text.trim().startsWith("#!")&&e.lineNumber===1?{shouldSkip:!0,reason:"shebang"}:{shouldSkip:!1}}function tv(e){if(e.isDocstring)return{shouldSkip:!1};let t=e.text.toLowerCase().trim();for(let n of Ir){if(t.startsWith(`#${n}`)||t.startsWith(`// ${n}`))return{shouldSkip:!0,reason:`BDD keyword: ${n}`};if(t.includes(n)&&t.split(/\s+/).some(r=>Ir.has(r.replace(/[^a-z&]/g,""))))return{shouldSkip:!0,reason:"BDD keyword detected"}}return{shouldSkip:!1}}function nv(e){let t=e.text.toLowerCase().trim();for(let n of qs)if(t.includes(n.toLowerCase()))return{shouldSkip:!0,reason:`directive: ${n}`};return{shouldSkip:!1}}function ov(e){return{shouldSkip:!1}}function rv(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 o of n)if(t.includes(o))return{shouldSkip:!0,reason:"copyright/license"};return{shouldSkip:!1}}function iv(e){let t=e.text.toUpperCase(),n=["TODO","FIXME","HACK","XXX","NOTE","REVIEW"];for(let o of n)if(t.includes(o))return{shouldSkip:!0,reason:`todo marker: ${o}`};return{shouldSkip:!1}}var sv=[ev,tv,nv,rv,iv,ov];function Js(e){return e.filter(t=>{for(let n of sv)if(n(t).shouldSkip)return!1;return!0})}var av=process.env.COMMENT_CHECKER_DEBUG==="1",cv=Rr.join((0,Qf.tmpdir)(),"comment-checker-debug.log");function en(...e){if(av){let t=`[${new Date().toISOString()}] [comment-checker] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
1606
+ `;zf.appendFileSync(cv,t)}}function lv(e){let t=Rr.extname(e).toLowerCase();return Ks[t]}function zs(e,t){let n=lv(t);if(!n)return en("unsupported language for:",t),[];let o=Ys[n];if(!o)return en("no pattern for language:",n),[];let r=[],i=e.split(`
1607
1607
  `);o.lastIndex=0;let s;for(;(s=o.exec(e))!==null;){let a=s.index,c=s[0],u=e.substring(0,a).split(`
1608
- `).length,d="line",f=!1;c.startsWith("/*")||c.startsWith("<!--")?d="block":(c.startsWith("'''")||c.startsWith('"""')||c.startsWith("=begin"))&&(d="docstring",f=!0),r.push({text:c.trim(),lineNumber:u,filePath:t,commentType:d,isDocstring:f})}return r}function cv(e,t){return Ks(e,t)}function Vf(e,t,n){let o=Ks(e,t);if(n){let r=Ks(n,t),i=new Set(r.map(s=>s.text));return o.filter(s=>!i.has(s.text))}return o}function lv(e){if(e.length===0)return"";let t=new Map;for(let o of e){let r=t.get(o.filePath)||[];r.push(o),t.set(o.filePath,r)}let n=Bs;for(let[o,r]of t){n+=`
1608
+ `).length,d="line",f=!1;c.startsWith("/*")||c.startsWith("<!--")?d="block":(c.startsWith("'''")||c.startsWith('"""')||c.startsWith("=begin"))&&(d="docstring",f=!0),r.push({text:c.trim(),lineNumber:u,filePath:t,commentType:d,isDocstring:f})}return r}function uv(e,t){return zs(e,t)}function Kf(e,t,n){let o=zs(e,t);if(n){let r=zs(n,t),i=new Set(r.map(s=>s.text));return o.filter(s=>!i.has(s.text))}return o}function dv(e){if(e.length===0)return"";let t=new Map;for(let o of e){let r=t.get(o.filePath)||[];r.push(o),t.set(o.filePath,r)}let n=Vs;for(let[o,r]of t){n+=`
1609
1609
  File: ${o}
1610
1610
  `;for(let i of r){let s=i.isDocstring?"docstring":i.commentType;n+=` Line ${i.lineNumber} (${s}): ${i.text.substring(0,100)}${i.text.length>100?"...":""}
1611
- `}}return n}function uv(e,t,n,o,r){let i=[];if(t)i=cv(t,e);else if(o)i=Vf(o,e,n);else if(r&&r.length>0)for(let a of r){let c=Vf(a.new_string,e,a.old_string);i.push(...c)}let s=Ys(i);return en(`found ${i.length} comments, ${s.length} flagged after filtering`),s.length===0?{hasComments:!1,count:0,comments:[]}:{hasComments:!0,count:s.length,message:lv(s),comments:s}}var wo=new Map,dv=6e4;function pv(){let e=Date.now();for(let[t,n]of wo)e-n.timestamp>dv&&wo.delete(t)}var Yf=!1;function zf(e){return en("createCommentCheckerHook called",{config:e}),Yf||(Yf=!0,setInterval(pv,1e4)),{preToolUse:t=>{let n=t.tool_name.toLowerCase();if(n!=="write"&&n!=="edit"&&n!=="multiedit")return null;let o=t.tool_input.file_path??t.tool_input.filePath??t.tool_input.path,r=t.tool_input.content,i=t.tool_input.old_string??t.tool_input.oldString,s=t.tool_input.new_string??t.tool_input.newString,a=t.tool_input.edits;if(!o)return null;let c=`${t.session_id}-${Date.now()}-${Math.random().toString(36).slice(2)}`;return en("registering pendingCall:",{callId:c,filePath:o,tool:n}),wo.set(c,{filePath:o,content:r,oldString:i,newString:s,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 o,r;for(let[s,a]of wo)if(a.sessionId===t.session_id&&a.tool===n){o=a,r=s;break}if(!o){let s=t.tool_input.file_path??t.tool_input.filePath??t.tool_input.path;if(!s)return null;o={filePath:s,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(r&&wo.delete(r),t.tool_response){let s=t.tool_response.toLowerCase();if(s.includes("error:")||s.includes("failed to")||s.includes("could not")||s.startsWith("error"))return en("skipping due to tool failure in response"),null}let i=uv(o.filePath,o.content,o.oldString,o.newString,o.edits);return i.hasComments&&i.message?(en("detected comments, returning message"),e?.customPrompt||i.message):null}}}var om=b(require("fs"),1),rm=b(require("path"),1),im=require("os");var Xf=[/(\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],Zf=["prompt is too long","is too long","context_length_exceeded","max_tokens","token limit","context length","too many tokens","non-empty content"],fv=[/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],mv=/messages\.(\d+)/;function gv(e){return fv.some(t=>t.test(e))}function Js(e){for(let t of Xf){let n=e.match(t);if(n){let o=parseInt(n[1],10),r=parseInt(n[2],10);return o>r?{current:o,max:r}:{current:r,max:o}}}return null}function Qf(e){let t=e.match(mv);if(t)return parseInt(t[1],10)}function xn(e){if(gv(e))return!1;let t=e.toLowerCase();return Zf.some(n=>t.includes(n.toLowerCase()))}function Or(e){if(typeof e=="string"){if(e.toLowerCase().includes("non-empty content"))return{currentTokens:0,maxTokens:0,errorType:"non-empty content",messageIndex:Qf(e)};if(xn(e)){let l=Js(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=[],o=t.data,r=o?.responseBody,i=t.message,s=t.error,a=s?.error;if(typeof r=="string"&&n.push(r),typeof i=="string"&&n.push(i),typeof s?.message=="string"&&n.push(s.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 o?.message=="string"&&n.push(o.message),typeof o?.error=="string"&&n.push(o.error),n.length===0)try{let l=JSON.stringify(t);xn(l)&&n.push(l)}catch{}let c=n.join(" ");if(!xn(c))return null;if(typeof r=="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 f=r.match(d);if(f)try{let m=JSON.parse(f[1]),p=m.error?.message||"",g=Js(p);if(g)return{currentTokens:g.current,maxTokens:g.max,requestId:m.request_id,errorType:m.error?.type||"token_limit_exceeded"}}catch{}}let u=JSON.parse(r);if(typeof u.message=="string"&&xn(u.message))return{currentTokens:0,maxTokens:0,errorType:"bedrock_input_too_long"}}catch{}for(let l of n){let u=Js(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:Qf(c)}:xn(c)?{currentTokens:0,maxTokens:0,errorType:"token_limit_exceeded_unknown"}:null}function zs(e){return xn(e)}var Qs=`CONTEXT WINDOW LIMIT REACHED - IMMEDIATE ACTION REQUIRED
1611
+ `}}return n}function pv(e,t,n,o,r){let i=[];if(t)i=uv(t,e);else if(o)i=Kf(o,e,n);else if(r&&r.length>0)for(let a of r){let c=Kf(a.new_string,e,a.old_string);i.push(...c)}let s=Js(i);return en(`found ${i.length} comments, ${s.length} flagged after filtering`),s.length===0?{hasComments:!1,count:0,comments:[]}:{hasComments:!0,count:s.length,message:dv(s),comments:s}}var So=new Map,fv=6e4;function mv(){let e=Date.now();for(let[t,n]of So)e-n.timestamp>fv&&So.delete(t)}var Jf=!1;function Xf(e){return en("createCommentCheckerHook called",{config:e}),Jf||(Jf=!0,setInterval(mv,1e4)),{preToolUse:t=>{let n=t.tool_name.toLowerCase();if(n!=="write"&&n!=="edit"&&n!=="multiedit")return null;let o=t.tool_input.file_path??t.tool_input.filePath??t.tool_input.path,r=t.tool_input.content,i=t.tool_input.old_string??t.tool_input.oldString,s=t.tool_input.new_string??t.tool_input.newString,a=t.tool_input.edits;if(!o)return null;let c=`${t.session_id}-${Date.now()}-${Math.random().toString(36).slice(2)}`;return en("registering pendingCall:",{callId:c,filePath:o,tool:n}),So.set(c,{filePath:o,content:r,oldString:i,newString:s,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 o,r;for(let[s,a]of So)if(a.sessionId===t.session_id&&a.tool===n){o=a,r=s;break}if(!o){let s=t.tool_input.file_path??t.tool_input.filePath??t.tool_input.path;if(!s)return null;o={filePath:s,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(r&&So.delete(r),t.tool_response){let s=t.tool_response.toLowerCase();if(s.includes("error:")||s.includes("failed to")||s.includes("could not")||s.startsWith("error"))return en("skipping due to tool failure in response"),null}let i=pv(o.filePath,o.content,o.oldString,o.newString,o.edits);return i.hasComments&&i.message?(en("detected comments, returning message"),e?.customPrompt||i.message):null}}}var im=b(require("fs"),1),sm=b(require("path"),1),am=require("os");var em=[/(\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],tm=["prompt is too long","is too long","context_length_exceeded","max_tokens","token limit","context length","too many tokens","non-empty content"],gv=[/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],hv=/messages\.(\d+)/;function yv(e){return gv.some(t=>t.test(e))}function Qs(e){for(let t of em){let n=e.match(t);if(n){let o=parseInt(n[1],10),r=parseInt(n[2],10);return o>r?{current:o,max:r}:{current:r,max:o}}}return null}function Zf(e){let t=e.match(hv);if(t)return parseInt(t[1],10)}function xn(e){if(yv(e))return!1;let t=e.toLowerCase();return tm.some(n=>t.includes(n.toLowerCase()))}function Or(e){if(typeof e=="string"){if(e.toLowerCase().includes("non-empty content"))return{currentTokens:0,maxTokens:0,errorType:"non-empty content",messageIndex:Zf(e)};if(xn(e)){let l=Qs(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=[],o=t.data,r=o?.responseBody,i=t.message,s=t.error,a=s?.error;if(typeof r=="string"&&n.push(r),typeof i=="string"&&n.push(i),typeof s?.message=="string"&&n.push(s.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 o?.message=="string"&&n.push(o.message),typeof o?.error=="string"&&n.push(o.error),n.length===0)try{let l=JSON.stringify(t);xn(l)&&n.push(l)}catch{}let c=n.join(" ");if(!xn(c))return null;if(typeof r=="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 f=r.match(d);if(f)try{let m=JSON.parse(f[1]),p=m.error?.message||"",g=Qs(p);if(g)return{currentTokens:g.current,maxTokens:g.max,requestId:m.request_id,errorType:m.error?.type||"token_limit_exceeded"}}catch{}}let u=JSON.parse(r);if(typeof u.message=="string"&&xn(u.message))return{currentTokens:0,maxTokens:0,errorType:"bedrock_input_too_long"}}catch{}for(let l of n){let u=Qs(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:Zf(c)}:xn(c)?{currentTokens:0,maxTokens:0,errorType:"token_limit_exceeded_unknown"}:null}function Xs(e){return xn(e)}var Zs=`CONTEXT WINDOW LIMIT REACHED - IMMEDIATE ACTION REQUIRED
1612
1612
 
1613
1613
  The conversation has exceeded the model's context window limit. To continue working effectively, you must take one of these actions:
1614
1614
 
@@ -1633,7 +1633,7 @@ Current Status:
1633
1633
  - Context limit exceeded
1634
1634
  - Further API calls will fail until context is reduced
1635
1635
  - Action required before continuing
1636
- `,Xs="Context window limit reached. Please use /compact to summarize the conversation or start a new session.",Zs=`API ERROR: Non-empty content validation failed.
1636
+ `,ea="Context window limit reached. Please use /compact to summarize the conversation or start a new session.",ta=`API ERROR: Non-empty content validation failed.
1637
1637
 
1638
1638
  This error typically occurs when:
1639
1639
  - A message has empty text content
@@ -1644,7 +1644,7 @@ Suggested actions:
1644
1644
  2. If the error persists, start a new session
1645
1645
 
1646
1646
  The system will attempt automatic recovery.
1647
- `;var ea=`CONTEXT RECOVERY FAILED
1647
+ `;var na=`CONTEXT RECOVERY FAILED
1648
1648
 
1649
1649
  All automatic recovery attempts have been exhausted.
1650
1650
  Please start a new session to continue.
@@ -1655,13 +1655,13 @@ Before starting a new session:
1655
1655
  3. Document the current state of the task
1656
1656
 
1657
1657
  You can copy this conversation summary to continue in a new session.
1658
- `;var ta={maxAttempts:2,initialDelayMs:2e3,backoffFactor:2,maxDelayMs:3e4};var hv=process.env.CONTEXT_LIMIT_RECOVERY_DEBUG==="1",yv=rm.join((0,im.tmpdir)(),"context-limit-recovery-debug.log");function Ar(...e){if(hv){let t=`[${new Date().toISOString()}] [context-limit-recovery] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
1659
- `;om.appendFileSync(yv,t)}}var Pr=new Map,sm=3e5;function em(e){let t=Pr.get(e),n=Date.now();return t&&n-t.lastErrorTime>sm&&(t=void 0),t||(t={retryState:{attempt:0,lastAttemptTime:0},truncateState:{truncateAttempt:0},lastErrorTime:n,errorCount:0},Pr.set(e,t)),t}function kv(){let e=Date.now();for(let[t,n]of Pr)e-n.lastErrorTime>sm&&Pr.delete(t)}var tm=!1;function am(e){return Ar("createContextLimitRecoveryHook called",{config:e}),tm||(tm=!0,setInterval(kv,6e4)),{postToolUse:t=>{if(!t.tool_response)return null;let n=Or(t.tool_response);if(!n&&!zs(t.tool_response))return null;Ar("detected token limit error",{tool:t.tool_name,sessionId:t.session_id,parsed:n});let o=em(t.session_id);o.lastErrorTime=Date.now(),o.errorCount++;let r=nm(n,o,e);return r.message?(Ar("injecting recovery message",{errorType:r.errorType,attempt:o.retryState.attempt}),r.message):null},onError:t=>{let n=Or(t.error);if(!n)return{attempted:!1,success:!1};Ar("error notification contains token limit error",{sessionId:t.session_id,parsed:n});let o=em(t.session_id);o.lastErrorTime=Date.now(),o.errorCount++;let r=nm(n,o,e);return{attempted:!0,success:!!r.message,message:r.message,errorType:r.errorType}}}}function nm(e,t,n){if(n?.customMessage)return{message:n.customMessage,errorType:e?.errorType};if(e?.errorType?.includes("non-empty content"))return{message:Zs,errorType:"non-empty content"};if(t.retryState.attempt++,t.retryState.lastAttemptTime=Date.now(),t.retryState.attempt>ta.maxAttempts)return{message:ea,errorType:"recovery_exhausted"};if(n?.detailed!==!1){let o=Qs;return e?.currentTokens&&e?.maxTokens&&(o+=`
1658
+ `;var oa={maxAttempts:2,initialDelayMs:2e3,backoffFactor:2,maxDelayMs:3e4};var kv=process.env.CONTEXT_LIMIT_RECOVERY_DEBUG==="1",wv=sm.join((0,am.tmpdir)(),"context-limit-recovery-debug.log");function Ar(...e){if(kv){let t=`[${new Date().toISOString()}] [context-limit-recovery] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
1659
+ `;im.appendFileSync(wv,t)}}var Pr=new Map,cm=3e5;function nm(e){let t=Pr.get(e),n=Date.now();return t&&n-t.lastErrorTime>cm&&(t=void 0),t||(t={retryState:{attempt:0,lastAttemptTime:0},truncateState:{truncateAttempt:0},lastErrorTime:n,errorCount:0},Pr.set(e,t)),t}function Sv(){let e=Date.now();for(let[t,n]of Pr)e-n.lastErrorTime>cm&&Pr.delete(t)}var om=!1;function lm(e){return Ar("createContextLimitRecoveryHook called",{config:e}),om||(om=!0,setInterval(Sv,6e4)),{postToolUse:t=>{if(!t.tool_response)return null;let n=Or(t.tool_response);if(!n&&!Xs(t.tool_response))return null;Ar("detected token limit error",{tool:t.tool_name,sessionId:t.session_id,parsed:n});let o=nm(t.session_id);o.lastErrorTime=Date.now(),o.errorCount++;let r=rm(n,o,e);return r.message?(Ar("injecting recovery message",{errorType:r.errorType,attempt:o.retryState.attempt}),r.message):null},onError:t=>{let n=Or(t.error);if(!n)return{attempted:!1,success:!1};Ar("error notification contains token limit error",{sessionId:t.session_id,parsed:n});let o=nm(t.session_id);o.lastErrorTime=Date.now(),o.errorCount++;let r=rm(n,o,e);return{attempted:!0,success:!!r.message,message:r.message,errorType:r.errorType}}}}function rm(e,t,n){if(n?.customMessage)return{message:n.customMessage,errorType:e?.errorType};if(e?.errorType?.includes("non-empty content"))return{message:ta,errorType:"non-empty content"};if(t.retryState.attempt++,t.retryState.lastAttemptTime=Date.now(),t.retryState.attempt>oa.maxAttempts)return{message:na,errorType:"recovery_exhausted"};if(n?.detailed!==!1){let o=Zs;return e?.currentTokens&&e?.maxTokens&&(o+=`
1660
1660
  Token Details:
1661
1661
  - Current: ${e.currentTokens.toLocaleString()} tokens
1662
1662
  - Maximum: ${e.maxTokens.toLocaleString()} tokens
1663
1663
  - Over limit by: ${(e.currentTokens-e.maxTokens).toLocaleString()} tokens
1664
- `),{message:o,errorType:e?.errorType||"token_limit_exceeded"}}return{message:Xs,errorType:e?.errorType||"token_limit_exceeded"}}var cm=/File content \((\d+) tokens\) exceeds maximum allowed tokens \((\d+)\)/i,wv=/exceeds maximum allowed tokens/i;function _v(e){let t=e.match(cm);return t?{current:parseInt(t[1],10),max:parseInt(t[2],10)}:null}function Sv(e,t){return e.toLowerCase()==="read"&&(cm.test(t)||wv.test(t))}function vv(e,t){return`[SYSTEM RECOVERY - READ TOOL FILE SIZE LIMIT]
1664
+ `),{message:o,errorType:e?.errorType||"token_limit_exceeded"}}return{message:ea,errorType:e?.errorType||"token_limit_exceeded"}}var um=/File content \((\d+) tokens\) exceeds maximum allowed tokens \((\d+)\)/i,_v=/exceeds maximum allowed tokens/i;function vv(e){let t=e.match(um);return t?{current:parseInt(t[1],10),max:parseInt(t[2],10)}:null}function Tv(e,t){return e.toLowerCase()==="read"&&(um.test(t)||_v.test(t))}function Ev(e,t){return`[SYSTEM RECOVERY - READ TOOL FILE SIZE LIMIT]
1665
1665
 
1666
1666
  ${t?`The file contains ${t.current} tokens, exceeding the ${t.max} token limit.`:"The file is too large to read in one operation."}
1667
1667
 
@@ -1691,7 +1691,7 @@ ${t?`The file contains ${t.current} tokens, exceeding the ${t.max} token limit.`
1691
1691
  - Need overview/summary? \u2192 Use multimodal-looker agent
1692
1692
  - Need specific section? \u2192 Grep to find it, then Read that portion
1693
1693
 
1694
- Proceed with one of these strategies.`.trim()}function lm(){return{postToolUse:e=>{if(!e.tool_response||!Sv(e.tool_name,e.tool_response))return null;let t=e.tool_input?.file_path||"<unknown file>",n=_v(e.tool_response);return vv(t,n||void 0)}}}var gm=b(require("fs"),1),hm=b(require("path"),1),ym=require("os");var na=process.env.ANTHROPIC_1M_CONTEXT==="true"||process.env.VERTEX_ANTHROPIC_1M_CONTEXT==="true"?1e6:2e5,xr=4,oa=`CONTEXT WINDOW WARNING - APPROACHING LIMIT
1694
+ Proceed with one of these strategies.`.trim()}function dm(){return{postToolUse:e=>{if(!e.tool_response||!Tv(e.tool_name,e.tool_response))return null;let t=e.tool_input?.file_path||"<unknown file>",n=vv(e.tool_response);return Ev(t,n||void 0)}}}var ym=b(require("fs"),1),km=b(require("path"),1),wm=require("os");var ra=process.env.ANTHROPIC_1M_CONTEXT==="true"||process.env.VERTEX_ANTHROPIC_1M_CONTEXT==="true"?1e6:2e5,xr=4,ia=`CONTEXT WINDOW WARNING - APPROACHING LIMIT
1695
1695
 
1696
1696
  Your context usage is getting high. Consider these actions to prevent hitting the limit:
1697
1697
 
@@ -1711,7 +1711,7 @@ Your context usage is getting high. Consider these actions to prevent hitting th
1711
1711
 
1712
1712
  Current Status: Context usage is high but recoverable.
1713
1713
  Action recommended: Use /compact when convenient.
1714
- `,ra=`CRITICAL: CONTEXT WINDOW ALMOST FULL
1714
+ `,sa=`CRITICAL: CONTEXT WINDOW ALMOST FULL
1715
1715
 
1716
1716
  Your context usage is critically high. Immediate action required:
1717
1717
 
@@ -1730,8 +1730,8 @@ Your context usage is critically high. Immediate action required:
1730
1730
 
1731
1731
  WARNING: Further messages may fail if context is not reduced.
1732
1732
  Action required: Run /compact now.
1733
- `;var Tv=process.env.PREEMPTIVE_COMPACTION_DEBUG==="1",Ev=hm.join((0,ym.tmpdir)(),"preemptive-compaction-debug.log");function $n(...e){if(Tv){let t=`[${new Date().toISOString()}] [preemptive-compaction] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
1734
- `;gm.appendFileSync(Ev,t)}}var $r=new Map;function bv(){let e=Date.now(),t=1800*1e3;for(let[n,o]of $r)e-o.lastWarningTime>t&&$r.delete(n)}var um=!1;function km(e){return Math.ceil(e.length/xr)}function Cv(e,t){let n=t?.warningThreshold??.85,o=t?.criticalThreshold??.95,r=na,i=km(e),s=i/r,a=s>=n,c=s>=o,l="none";return c?l="compact":a&&(l="warn"),{totalTokens:i,usageRatio:s,isWarning:a,isCritical:c,action:l}}function Nr(e){let t=$r.get(e);return t||(t={lastWarningTime:0,warningCount:0,estimatedTokens:0},$r.set(e,t)),t}function Iv(e,t){let n=Nr(e),o=t?.cooldownMs??6e4,r=t?.maxWarnings??3,i=Date.now();return i-n.lastWarningTime<o?($n("skipping warning - cooldown active",{sessionId:e,elapsed:i-n.lastWarningTime,cooldown:o}),!1):n.warningCount>=r?($n("skipping warning - max reached",{sessionId:e,warningCount:n.warningCount,maxWarnings:r}),!1):!0}function Rv(e){let t=Nr(e);t.lastWarningTime=Date.now(),t.warningCount++}function wm(e){return $n("createPreemptiveCompactionHook called",{config:e}),e?.enabled===!1?{postToolUse:()=>null,stop:()=>null}:(um||(um=!0,setInterval(bv,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 r=km(t.tool_response),i=Nr(t.session_id);i.estimatedTokens+=r,$n("tracking tool output",{tool:n,responseTokens:r,cumulativeTokens:i.estimatedTokens});let s=Cv("x".repeat(i.estimatedTokens*xr),e);return!s.isWarning||!Iv(t.session_id,e)?null:(Rv(t.session_id),$n("injecting context warning",{sessionId:t.session_id,usageRatio:s.usageRatio,isCritical:s.isCritical}),e?.customMessage?e.customMessage:s.isCritical?ra:oa)},stop:t=>{let n=Nr(t.session_id);return n.warningCount>0&&($n("resetting warning count on stop",{sessionId:t.session_id,previousCount:n.warningCount}),n.warningCount=0),null}})}var Ue=require("fs"),Sm=require("path");var ia=require("path"),_m=require("os"),Ov=(0,ia.join)((0,_m.homedir)(),".olympus"),Dr=(0,ia.join)(Ov,"agent-usage-reminder"),sa=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"]),aa=new Set(["task","call_omo_agent","olympus_task"]),ca=`
1733
+ `;var bv=process.env.PREEMPTIVE_COMPACTION_DEBUG==="1",Cv=km.join((0,wm.tmpdir)(),"preemptive-compaction-debug.log");function $n(...e){if(bv){let t=`[${new Date().toISOString()}] [preemptive-compaction] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
1734
+ `;ym.appendFileSync(Cv,t)}}var $r=new Map;function Iv(){let e=Date.now(),t=1800*1e3;for(let[n,o]of $r)e-o.lastWarningTime>t&&$r.delete(n)}var pm=!1;function Sm(e){return Math.ceil(e.length/xr)}function Rv(e,t){let n=t?.warningThreshold??.85,o=t?.criticalThreshold??.95,r=ra,i=Sm(e),s=i/r,a=s>=n,c=s>=o,l="none";return c?l="compact":a&&(l="warn"),{totalTokens:i,usageRatio:s,isWarning:a,isCritical:c,action:l}}function Nr(e){let t=$r.get(e);return t||(t={lastWarningTime:0,warningCount:0,estimatedTokens:0},$r.set(e,t)),t}function Ov(e,t){let n=Nr(e),o=t?.cooldownMs??6e4,r=t?.maxWarnings??3,i=Date.now();return i-n.lastWarningTime<o?($n("skipping warning - cooldown active",{sessionId:e,elapsed:i-n.lastWarningTime,cooldown:o}),!1):n.warningCount>=r?($n("skipping warning - max reached",{sessionId:e,warningCount:n.warningCount,maxWarnings:r}),!1):!0}function Av(e){let t=Nr(e);t.lastWarningTime=Date.now(),t.warningCount++}function _m(e){return $n("createPreemptiveCompactionHook called",{config:e}),e?.enabled===!1?{postToolUse:()=>null,stop:()=>null}:(pm||(pm=!0,setInterval(Iv,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 r=Sm(t.tool_response),i=Nr(t.session_id);i.estimatedTokens+=r,$n("tracking tool output",{tool:n,responseTokens:r,cumulativeTokens:i.estimatedTokens});let s=Rv("x".repeat(i.estimatedTokens*xr),e);return!s.isWarning||!Ov(t.session_id,e)?null:(Av(t.session_id),$n("injecting context warning",{sessionId:t.session_id,usageRatio:s.usageRatio,isCritical:s.isCritical}),e?.customMessage?e.customMessage:s.isCritical?sa:ia)},stop:t=>{let n=Nr(t.session_id);return n.warningCount>0&&($n("resetting warning count on stop",{sessionId:t.session_id,previousCount:n.warningCount}),n.warningCount=0),null}})}var Ue=require("fs"),Tm=require("path");var aa=require("path"),vm=require("os"),Pv=(0,aa.join)((0,vm.homedir)(),".olympus"),Dr=(0,aa.join)(Pv,"agent-usage-reminder"),ca=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"]),la=new Set(["task","call_omo_agent","olympus_task"]),ua=`
1735
1735
  [Agent Usage Reminder]
1736
1736
 
1737
1737
  You called a search/fetch tool directly without leveraging specialized agents.
@@ -1755,7 +1755,7 @@ WHY:
1755
1755
  - Reduces context window usage in main session
1756
1756
 
1757
1757
  ALWAYS prefer: Multiple parallel Task calls > Direct tool calls
1758
- `;function la(e){return(0,Sm.join)(Dr,`${e}.json`)}function ua(e){let t=la(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 jr(e){(0,Ue.existsSync)(Dr)||(0,Ue.mkdirSync)(Dr,{recursive:!0});let t=la(e.sessionID);(0,Ue.writeFileSync)(t,JSON.stringify(e,null,2))}function da(e){let t=la(e);(0,Ue.existsSync)(t)&&(0,Ue.unlinkSync)(t)}function Av(e){let t=e||process.cwd();return Rn(t)?.active?{active:!0,mode:"ascent"}:Xt(t)?.active?{active:!0,mode:"olympus"}:_t(t)?.active?{active:!0,mode:"ultrawork"}:{active:!1,mode:"none"}}function Pv(e){if(!e||typeof e!="object")return null;let t=e;return t.file_path||t.filePath||t.path}function xv(e,t){if(e<3)return null;let n=e>=5?"CRITICAL":"WARNING";return`<conductor-violation severity="${n}">
1758
+ `;function da(e){return(0,Tm.join)(Dr,`${e}.json`)}function pa(e){let t=da(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 jr(e){(0,Ue.existsSync)(Dr)||(0,Ue.mkdirSync)(Dr,{recursive:!0});let t=da(e.sessionID);(0,Ue.writeFileSync)(t,JSON.stringify(e,null,2))}function fa(e){let t=da(e);(0,Ue.existsSync)(t)&&(0,Ue.unlinkSync)(t)}function xv(e){let t=e||process.cwd();return Rn(t)?.active?{active:!0,mode:"ascent"}:Xt(t)?.active?{active:!0,mode:"olympus"}:St(t)?.active?{active:!0,mode:"ultrawork"}:{active:!1,mode:"none"}}function $v(e){if(!e||typeof e!="object")return null;let t=e;return t.file_path||t.filePath||t.path}function Nv(e,t){if(e<3)return null;let n=e>=5?"CRITICAL":"WARNING";return`<conductor-violation severity="${n}">
1759
1759
 
1760
1760
  [${n}: CONDUCTOR MODE VIOLATION - ${t.toUpperCase()} ACTIVE]
1761
1761
 
@@ -1781,36 +1781,36 @@ ${e>=5?"**CRITICAL**: Too many direct operations. Your next action MUST be deleg
1781
1781
 
1782
1782
  ---
1783
1783
 
1784
- `}function vm(){let e=new Map,t=new Map;function n(c){if(!e.has(c)){let u=ua(c)??{sessionID:c,agentUsed:!1,reminderCount:0,updatedAt:Date.now()};e.set(c,u)}return e.get(c)}function o(c){let l=n(c);l.agentUsed=!0,l.updatedAt=Date.now(),jr(l)}function r(c){e.delete(c),da(c),t.delete(c)}function i(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,f=u.toLowerCase();if(aa.has(f)){o(d),i(d,f,"");return}let m=c.properties||{},p=Pv(m),g=i(d,f,p||""),h=Av();if(h.active){let w=xv(g,h.mode);if(w){l.output=w+l.output;return}}if(!sa.has(f))return;let y=n(d);y.agentUsed||(l.output+=ca,y.reminderCount++,y.updatedAt=Date.now(),jr(y))},event:async({event:c})=>{let l=c.properties;if(c.type==="session.deleted"){let u=l?.info;u?.id&&r(u.id)}if(c.type==="session.compacted"){let u=l?.sessionID??l?.info?.id;u&&r(u)}}}}function Tm(){let e=process.cwd(),t=qf();_({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=zf();_({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 o=am();_({name:"contextWindowLimitRecovery",event:"PostToolUse",priority:30,handler:async c=>{if(!c.toolName)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 r=lm();_({name:"readToolLimitRecovery",event:"PostToolUse",matcher:/^read$/i,priority:35,handler:async c=>{if(!c.toolName||c.toolName.toLowerCase()!=="read")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 i=wm();_({name:"preemptiveCompaction",event:"PostToolUse",matcher:/^(read|grep|glob|bash|webfetch)$/i,priority:40,handler:async c=>{if(!c.toolName)return{continue:!0};let l=i.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=vm();_({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 s["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=Cr(e);_({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 Dm=require("node:fs");var G=require("node:fs"),Oe=require("node:path");var Nn=require("node:path"),Mr=require("node:os");function $v(){return process.env.XDG_DATA_HOME??(0,Nn.join)((0,Mr.homedir)(),".local","share")}function Nv(){return(0,Nn.join)($v(),"claude-code","storage")}var Em=Nv(),_o=(0,Nn.join)(Em,"message"),Dn=(0,Nn.join)(Em,"part"),Mt=new Set(["thinking","redacted_thinking","reasoning"]),bm=new Set(["step-start","step-finish"]);var We="[user interrupted]",Lr={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 Cm=process.env.SESSION_RECOVERY_DEBUG==="1",Im=(0,Nn.join)((0,Mr.tmpdir)(),"session-recovery-debug.log");function Dv(){let e=Date.now().toString(16),t=Math.random().toString(36).substring(2,10);return`prt_${e}${t}`}function jv(e){if(!(0,G.existsSync)(_o))return"";let t=(0,Oe.join)(_o,e);if((0,G.existsSync)(t))return t;for(let n of(0,G.readdirSync)(_o)){let o=(0,Oe.join)(_o,n,e);if((0,G.existsSync)(o))return o}return""}function kt(e){let t=jv(e);if(!t||!(0,G.existsSync)(t))return[];let n=[];for(let o of(0,G.readdirSync)(t))if(o.endsWith(".json"))try{let r=(0,G.readFileSync)((0,Oe.join)(t,o),"utf-8");n.push(JSON.parse(r))}catch{continue}return n.sort((o,r)=>{let i=o.time?.created??0,s=r.time?.created??0;return i!==s?i-s:o.id.localeCompare(r.id)})}function it(e){let t=(0,Oe.join)(Dn,e);if(!(0,G.existsSync)(t))return[];let n=[];for(let o of(0,G.readdirSync)(t))if(o.endsWith(".json"))try{let r=(0,G.readFileSync)((0,Oe.join)(t,o),"utf-8");n.push(JSON.parse(r))}catch{continue}return n}function Rm(e){return Mt.has(e.type)||bm.has(e.type)?!1:e.type==="text"?!!e.text?.trim():e.type==="tool"||e.type==="tool_use"||e.type==="tool_result"}function Om(e){return it(e).some(Rm)}function So(e,t,n){let o=(0,Oe.join)(Dn,t);(0,G.existsSync)(o)||(0,G.mkdirSync)(o,{recursive:!0});let r=Dv(),i={id:r,sessionID:e,messageID:t,type:"text",text:n,synthetic:!0};try{return(0,G.writeFileSync)((0,Oe.join)(o,`${r}.json`),JSON.stringify(i,null,2)),!0}catch{return!1}}function pa(e){let t=kt(e),n=[];for(let o of t)Om(o.id)||n.push(o.id);return n}function Am(e,t){let n=kt(e),o=[t,t-1,t+1,t-2,t+2,t-3,t-4,t-5];for(let r of o){if(r<0||r>=n.length)continue;let i=n[r];if(!Om(i.id))return i.id}return null}function fa(e){let t=kt(e),n=[];for(let o of t){if(o.role!=="assistant")continue;it(o.id).some(s=>Mt.has(s.type))&&n.push(o.id)}return n}function Pm(e){let t=kt(e),n=[];for(let o of t){if(o.role!=="assistant")continue;let r=it(o.id);if(r.length===0)continue;let i=r.some(a=>Mt.has(a.type)),s=r.some(Rm);i&&!s&&n.push(o.id)}return n}function ma(e){let t=kt(e),n=[];for(let o of t){if(o.role!=="assistant")continue;let r=it(o.id);if(r.length===0)continue;let s=[...r].sort((c,l)=>c.id.localeCompare(l.id))[0];Mt.has(s.type)||n.push(o.id)}return n}function Mv(e,t){let n=kt(e),o=n.findIndex(r=>r.id===t);if(o===-1)return"";for(let r=o-1;r>=0;r--){let i=n[r];if(i.role!=="assistant")continue;let s=it(i.id);for(let a of s)if(Mt.has(a.type)){let c=a.thinking,l=a.text,u=c||l;if(u&&u.trim().length>0)return u}}return""}function ga(e,t){let n=(0,Oe.join)(Dn,t);(0,G.existsSync)(n)||(0,G.mkdirSync)(n,{recursive:!0});let o=Mv(e,t),r="prt_0000000000_thinking",i={id:r,sessionID:e,messageID:t,type:"thinking",thinking:o||"[Continuing from previous reasoning]",synthetic:!0};try{return(0,G.writeFileSync)((0,Oe.join)(n,`${r}.json`),JSON.stringify(i,null,2)),!0}catch{return!1}}function xm(e){let t=(0,Oe.join)(Dn,e);if(!(0,G.existsSync)(t))return!1;let n=!1;for(let o of(0,G.readdirSync)(t))if(o.endsWith(".json"))try{let r=(0,Oe.join)(t,o),i=(0,G.readFileSync)(r,"utf-8"),s=JSON.parse(i);Mt.has(s.type)&&((0,G.unlinkSync)(r),n=!0)}catch{continue}return n}function vo(e,t=We){let n=(0,Oe.join)(Dn,e);if(!(0,G.existsSync)(n))return!1;let o=!1;for(let r of(0,G.readdirSync)(n))if(r.endsWith(".json"))try{let i=(0,Oe.join)(n,r),s=(0,G.readFileSync)(i,"utf-8"),a=JSON.parse(s);if(a.type==="text"){let c=a;c.text?.trim()||(c.text=t,c.synthetic=!0,(0,G.writeFileSync)(i,JSON.stringify(c,null,2)),o=!0)}}catch{continue}return o}function $m(e){let t=kt(e),n=[];for(let o of t)it(o.id).some(s=>s.type!=="text"?!1:!s.text?.trim())&&n.push(o.id);return n}function Nm(e,t){let n=kt(e);if(t<0||t>=n.length)return null;let o=n[t];if(o.role!=="assistant")return null;let r=it(o.id);if(r.length===0)return null;let s=[...r].sort((c,l)=>c.id.localeCompare(l.id))[0];return Mt.has(s.type)?null:o.id}function ye(...e){if(Cm){let t=`[${new Date().toISOString()}] [session-recovery] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
1785
- `;(0,Dm.appendFileSync)(Im,t)}}function jm(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 o of n)if(o&&typeof o=="object"){let r=o.message;if(typeof r=="string"&&r.length>0)return r.toLowerCase()}try{return JSON.stringify(e).toLowerCase()}catch{return""}}function Mm(e){let n=jm(e).match(/messages\.(\d+)/);return n?parseInt(n[1],10):null}function Lm(e){let t=jm(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 Lv(e){return Lm(e)!==null}function Fv(e){return e.filter(t=>t.type==="tool_use"&&!!t.id).map(t=>t.id)}async function Uv(e,t){ye("recoverToolResultMissing",{sessionID:e,msgId:t.info?.id});let n=t.parts||[];n.length===0&&t.info?.id&&(n=it(t.info.id).map(i=>({type:i.type==="tool"?"tool_use":i.type,id:"callID"in i?i.callID:i.id,name:"tool"in i?i.tool:void 0,input:"state"in i?i.state?.input:void 0})));let o=Fv(n);return o.length===0?(ye("No tool_use IDs found"),!1):(ye("Found tool_use IDs to inject results for",o),!0)}async function Wv(e,t,n){ye("recoverThinkingBlockOrder",{sessionID:e});let o=Mm(n);if(o!==null){let s=Nm(e,o);if(s)return ye("Found target message by index",{targetIndex:o,targetMessageID:s}),ga(e,s)}let r=ma(e);if(r.length===0)return ye("No orphan thinking messages found"),!1;ye("Found orphan thinking messages",r);let i=!1;for(let s of r)ga(e,s)&&(i=!0);return i}async function Hv(e,t){ye("recoverThinkingDisabledViolation",{sessionID:e});let n=fa(e);if(n.length===0)return ye("No messages with thinking blocks found"),!1;ye("Found messages with thinking blocks",n);let o=!1;for(let r of n)xm(r)&&(o=!0);return o}async function Gv(e,t,n){ye("recoverEmptyContentMessage",{sessionID:e});let o=Mm(n),r=t.info?.id,i=!1,s=$m(e);for(let l of s)vo(l,We)&&(i=!0);let a=Pm(e);for(let l of a)So(e,l,We)&&(i=!0);if(o!==null){let l=Am(e,o);if(l&&(vo(l,We)||So(e,l,We)))return!0}if(r&&(vo(r,We)||So(e,r,We)))return!0;let c=pa(e);for(let l of c)vo(l,We)&&(i=!0),So(e,l,We)&&(i=!0);return i}async function Bv(e,t,n,o){ye("handleSessionRecovery",{sessionID:e,error:t});let r=Lm(t);if(!r)return ye("Not a recoverable error"),{attempted:!1,success:!1};ye("Detected recoverable error type",r);try{let i=!1,s=n||{info:{},parts:[]};switch(r){case"tool_result_missing":i=await Uv(e,s);break;case"thinking_block_order":i=await Wv(e,s,t);break;case"thinking_disabled_violation":i=await Hv(e,s);break;case"empty_content":i=await Gv(e,s,t);break}ye("Recovery result",{errorType:r,success:i});let a=o?.customMessages?.[r]||Lr[r]?.message||`Session recovery attempted for ${r}`;return{attempted:!0,success:i,message:i?a:void 0,errorType:r}}catch(i){return ye("Recovery failed with error",i),{attempted:!0,success:!1,errorType:r}}}function Fm(e){return ye("createSessionRecoveryHook",{config:e}),{onError:async t=>Bv(t.session_id,t.error,t.message,e),isRecoverable:t=>Lv(t),getRecoveryMessage:t=>{if(t)return e?.customMessages?.[t]||Lr[t]?.message}}}function Um(){let e=Fm();_({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 o=await e.onError({session_id:t.sessionId||"default",error:n,message:void 0});return o.attempted&&o.success?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:o.message||`[session-recovery] Recovered from ${o.errorType} error. Please retry.`}}:o.attempted&&!o.success?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:`[session-recovery] Attempted recovery for ${o.errorType} but could not fix automatically. You may need to restart the session.`}}:{continue:!0}}})}var He=require("fs"),Fr=require("path"),Wm=require("os");var To=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 o=t.split("/")[0],r=this.config?.providerConcurrency?.[o];if(r!==void 0)return r===0?1/0:r;let i=this.config?.defaultConcurrency;return i!==void 0?i===0?1/0:i:5}async acquire(t){let n=this.getConcurrencyLimit(t);if(n===1/0)return;let o=this.counts.get(t)??0;if(o<n){this.counts.set(t,o+1);return}return new Promise(r=>{let i=this.queues.get(t)??[];i.push(r),this.queues.set(t,i)})}release(t){if(this.getConcurrencyLimit(t)===1/0)return;let o=this.queues.get(t);if(o&&o.length>0)o.shift()();else{let r=this.counts.get(t)??0;r>0&&this.counts.set(t,r-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 qv=1800*1e3,jn=(0,Fr.join)((0,Wm.homedir)(),".claude",".olympus","background-tasks"),Ur=class{tasks=new Map;notifications=new Map;concurrencyManager;config;pruneInterval;constructor(t){this.config=t??{},this.concurrencyManager=new To(t),this.ensureStorageDir(),this.loadPersistedTasks(),this.startPruning()}ensureStorageDir(){(0,He.existsSync)(jn)||(0,He.mkdirSync)(jn,{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,Fr.join)(jn,`${t}.json`)}persistTask(t){let n=this.getTaskPath(t.id);(0,He.writeFileSync)(n,JSON.stringify(t,null,2))}unpersistTask(t){let n=this.getTaskPath(t);(0,He.existsSync)(n)&&(0,He.unlinkSync)(n)}loadPersistedTasks(){if((0,He.existsSync)(jn))try{let{readdirSync:t}=require("fs"),n=t(jn);for(let o of n)if(o.endsWith(".json"))try{let r=(0,Fr.join)(jn,o),i=(0,He.readFileSync)(r,"utf-8"),s=JSON.parse(i);s.startedAt=new Date(s.startedAt),s.completedAt&&(s.completedAt=new Date(s.completedAt)),s.progress?.lastUpdate&&(s.progress.lastUpdate=new Date(s.progress.lastUpdate)),s.progress?.lastMessageAt&&(s.progress.lastMessageAt=new Date(s.progress.lastMessageAt)),this.tasks.set(s.id,s)}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??qv;for(let[o,r]of this.tasks.entries())t-r.startedAt.getTime()>n&&r.status==="running"&&(r.status="error",r.error=`Task timed out after ${Math.round(n/6e4)} minutes`,r.completedAt=new Date,r.concurrencyKey&&this.concurrencyManager.release(r.concurrencyKey),this.clearNotificationsForTask(o),this.unpersistTask(o),this.tasks.delete(o));for(let[o,r]of this.notifications.entries()){let i=r.filter(s=>t-s.startedAt.getTime()<=n);i.length===0?this.notifications.delete(o):i.length!==r.length&&this.notifications.set(o,i)}}async launch(t){let n=t.agent,o=this.config.maxTotalTasks??10;if(Array.from(this.tasks.values()).filter(c=>c.status==="running").length>=o)throw new Error(`Maximum concurrent background tasks (${o}) reached. Wait for some tasks to complete.`);await this.concurrencyManager.acquire(n);let i=this.generateTaskId(),s=`ses_${this.generateTaskId()}`,a={id:i,sessionId:s,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(i,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 o of this.tasks.values())o.parentSessionId===t&&n.push(o);return n}getAllTasks(){return Array.from(this.tasks.values())}getRunningTasks(){return Array.from(this.tasks.values()).filter(t=>t.status==="running")}updateTaskStatus(t,n,o,r){let i=this.tasks.get(t);i&&(i.status=n,o&&(i.result=o),r&&(i.error=r),(n==="completed"||n==="error"||n==="cancelled")&&(i.completedAt=new Date,i.concurrencyKey&&this.concurrencyManager.release(i.concurrencyKey),this.markForNotification(i)),this.persistTask(i))}updateTaskProgress(t,n){let o=this.tasks.get(t);o&&(o.progress||(o.progress={toolCalls:0,lastUpdate:new Date}),Object.assign(o.progress,n,{lastUpdate:new Date}),this.persistTask(o))}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,o]of this.notifications.entries()){let r=o.filter(i=>i.id!==t);r.length===0?this.notifications.delete(n):this.notifications.set(n,r)}}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 o=(n??new Date).getTime()-t.getTime(),r=Math.floor(o/1e3),i=Math.floor(r/60),s=Math.floor(i/60);return s>0?`${s}h ${i%60}m ${r%60}s`:i>0?`${i}m ${r%60}s`:`${r}s`}getStatusSummary(){let t=this.getRunningTasks(),n=this.getAllTasks();if(n.length===0)return"No background tasks.";let o=[`Background Tasks: ${t.length} running, ${n.length} total`,""];for(let r of n){let i=this.formatDuration(r.startedAt,r.completedAt),s=r.status.toUpperCase(),a=r.progress?` (${r.progress.toolCalls} tools)`:"";o.push(` [${s}] ${r.description} - ${i}${a}`),r.error&&o.push(` Error: ${r.error}`)}return o.join(`
1786
- `)}cleanup(){this.stopPruning(),this.tasks.clear(),this.notifications.clear()}},ha;function ya(e){return ha||(ha=new Ur(e)),ha}function Vv(e){let t=e.status.toUpperCase(),n=Yv(e.startedAt,e.completedAt),r=[`${e.status==="completed"?"\u2713":e.status==="error"?"\u2717":"\u25CB"} [${t}] ${e.description}`,` Agent: ${e.agent}`,` Duration: ${n}`];if(e.progress?.toolCalls&&r.push(` Tool calls: ${e.progress.toolCalls}`),e.result){let i=e.result.substring(0,200),s=e.result.length>200?"...":"";r.push(` Result: ${i}${s}`)}return e.error&&r.push(` Error: ${e.error}`),r.join(`
1787
- `)}function Yv(e,t){let n=(t??new Date).getTime()-e.getTime(),o=Math.floor(n/1e3),r=Math.floor(o/60),i=Math.floor(r/60);return i>0?`${i}h ${r%60}m ${o%60}s`:r>0?`${r}m ${o%60}s`:`${o}s`}function Kv(e){if(e.length===0)return"";let t=e.length===1?`
1784
+ `}function Em(){let e=new Map,t=new Map;function n(c){if(!e.has(c)){let u=pa(c)??{sessionID:c,agentUsed:!1,reminderCount:0,updatedAt:Date.now()};e.set(c,u)}return e.get(c)}function o(c){let l=n(c);l.agentUsed=!0,l.updatedAt=Date.now(),jr(l)}function r(c){e.delete(c),fa(c),t.delete(c)}function i(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,f=u.toLowerCase();if(la.has(f)){o(d),i(d,f,"");return}let m=c.properties||{},p=$v(m),g=i(d,f,p||""),h=xv();if(h.active){let w=Nv(g,h.mode);if(w){l.output=w+l.output;return}}if(!ca.has(f))return;let y=n(d);y.agentUsed||(l.output+=ua,y.reminderCount++,y.updatedAt=Date.now(),jr(y))},event:async({event:c})=>{let l=c.properties;if(c.type==="session.deleted"){let u=l?.info;u?.id&&r(u.id)}if(c.type==="session.compacted"){let u=l?.sessionID??l?.info?.id;u&&r(u)}}}}function bm(){let e=process.cwd(),t=Yf();S({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=Xf();S({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 o=lm();S({name:"contextWindowLimitRecovery",event:"PostToolUse",priority:30,handler:async c=>{if(!c.toolName)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 r=dm();S({name:"readToolLimitRecovery",event:"PostToolUse",matcher:/^read$/i,priority:35,handler:async c=>{if(!c.toolName||c.toolName.toLowerCase()!=="read")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 i=_m();S({name:"preemptiveCompaction",event:"PostToolUse",matcher:/^(read|grep|glob|bash|webfetch)$/i,priority:40,handler:async c=>{if(!c.toolName)return{continue:!0};let l=i.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=Em();S({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 s["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=Cr(e);S({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 Mm=require("node:fs");var G=require("node:fs"),Ae=require("node:path");var Nn=require("node:path"),Mr=require("node:os");function Dv(){return process.env.XDG_DATA_HOME??(0,Nn.join)((0,Mr.homedir)(),".local","share")}function jv(){return(0,Nn.join)(Dv(),"claude-code","storage")}var Cm=jv(),_o=(0,Nn.join)(Cm,"message"),Dn=(0,Nn.join)(Cm,"part"),Mt=new Set(["thinking","redacted_thinking","reasoning"]),Im=new Set(["step-start","step-finish"]);var We="[user interrupted]",Lr={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 Rm=process.env.SESSION_RECOVERY_DEBUG==="1",Om=(0,Nn.join)((0,Mr.tmpdir)(),"session-recovery-debug.log");function Mv(){let e=Date.now().toString(16),t=Math.random().toString(36).substring(2,10);return`prt_${e}${t}`}function Lv(e){if(!(0,G.existsSync)(_o))return"";let t=(0,Ae.join)(_o,e);if((0,G.existsSync)(t))return t;for(let n of(0,G.readdirSync)(_o)){let o=(0,Ae.join)(_o,n,e);if((0,G.existsSync)(o))return o}return""}function kt(e){let t=Lv(e);if(!t||!(0,G.existsSync)(t))return[];let n=[];for(let o of(0,G.readdirSync)(t))if(o.endsWith(".json"))try{let r=(0,G.readFileSync)((0,Ae.join)(t,o),"utf-8");n.push(JSON.parse(r))}catch{continue}return n.sort((o,r)=>{let i=o.time?.created??0,s=r.time?.created??0;return i!==s?i-s:o.id.localeCompare(r.id)})}function it(e){let t=(0,Ae.join)(Dn,e);if(!(0,G.existsSync)(t))return[];let n=[];for(let o of(0,G.readdirSync)(t))if(o.endsWith(".json"))try{let r=(0,G.readFileSync)((0,Ae.join)(t,o),"utf-8");n.push(JSON.parse(r))}catch{continue}return n}function Am(e){return Mt.has(e.type)||Im.has(e.type)?!1:e.type==="text"?!!e.text?.trim():e.type==="tool"||e.type==="tool_use"||e.type==="tool_result"}function Pm(e){return it(e).some(Am)}function vo(e,t,n){let o=(0,Ae.join)(Dn,t);(0,G.existsSync)(o)||(0,G.mkdirSync)(o,{recursive:!0});let r=Mv(),i={id:r,sessionID:e,messageID:t,type:"text",text:n,synthetic:!0};try{return(0,G.writeFileSync)((0,Ae.join)(o,`${r}.json`),JSON.stringify(i,null,2)),!0}catch{return!1}}function ma(e){let t=kt(e),n=[];for(let o of t)Pm(o.id)||n.push(o.id);return n}function xm(e,t){let n=kt(e),o=[t,t-1,t+1,t-2,t+2,t-3,t-4,t-5];for(let r of o){if(r<0||r>=n.length)continue;let i=n[r];if(!Pm(i.id))return i.id}return null}function ga(e){let t=kt(e),n=[];for(let o of t){if(o.role!=="assistant")continue;it(o.id).some(s=>Mt.has(s.type))&&n.push(o.id)}return n}function $m(e){let t=kt(e),n=[];for(let o of t){if(o.role!=="assistant")continue;let r=it(o.id);if(r.length===0)continue;let i=r.some(a=>Mt.has(a.type)),s=r.some(Am);i&&!s&&n.push(o.id)}return n}function ha(e){let t=kt(e),n=[];for(let o of t){if(o.role!=="assistant")continue;let r=it(o.id);if(r.length===0)continue;let s=[...r].sort((c,l)=>c.id.localeCompare(l.id))[0];Mt.has(s.type)||n.push(o.id)}return n}function Fv(e,t){let n=kt(e),o=n.findIndex(r=>r.id===t);if(o===-1)return"";for(let r=o-1;r>=0;r--){let i=n[r];if(i.role!=="assistant")continue;let s=it(i.id);for(let a of s)if(Mt.has(a.type)){let c=a.thinking,l=a.text,u=c||l;if(u&&u.trim().length>0)return u}}return""}function ya(e,t){let n=(0,Ae.join)(Dn,t);(0,G.existsSync)(n)||(0,G.mkdirSync)(n,{recursive:!0});let o=Fv(e,t),r="prt_0000000000_thinking",i={id:r,sessionID:e,messageID:t,type:"thinking",thinking:o||"[Continuing from previous reasoning]",synthetic:!0};try{return(0,G.writeFileSync)((0,Ae.join)(n,`${r}.json`),JSON.stringify(i,null,2)),!0}catch{return!1}}function Nm(e){let t=(0,Ae.join)(Dn,e);if(!(0,G.existsSync)(t))return!1;let n=!1;for(let o of(0,G.readdirSync)(t))if(o.endsWith(".json"))try{let r=(0,Ae.join)(t,o),i=(0,G.readFileSync)(r,"utf-8"),s=JSON.parse(i);Mt.has(s.type)&&((0,G.unlinkSync)(r),n=!0)}catch{continue}return n}function To(e,t=We){let n=(0,Ae.join)(Dn,e);if(!(0,G.existsSync)(n))return!1;let o=!1;for(let r of(0,G.readdirSync)(n))if(r.endsWith(".json"))try{let i=(0,Ae.join)(n,r),s=(0,G.readFileSync)(i,"utf-8"),a=JSON.parse(s);if(a.type==="text"){let c=a;c.text?.trim()||(c.text=t,c.synthetic=!0,(0,G.writeFileSync)(i,JSON.stringify(c,null,2)),o=!0)}}catch{continue}return o}function Dm(e){let t=kt(e),n=[];for(let o of t)it(o.id).some(s=>s.type!=="text"?!1:!s.text?.trim())&&n.push(o.id);return n}function jm(e,t){let n=kt(e);if(t<0||t>=n.length)return null;let o=n[t];if(o.role!=="assistant")return null;let r=it(o.id);if(r.length===0)return null;let s=[...r].sort((c,l)=>c.id.localeCompare(l.id))[0];return Mt.has(s.type)?null:o.id}function ye(...e){if(Rm){let t=`[${new Date().toISOString()}] [session-recovery] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
1785
+ `;(0,Mm.appendFileSync)(Om,t)}}function Lm(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 o of n)if(o&&typeof o=="object"){let r=o.message;if(typeof r=="string"&&r.length>0)return r.toLowerCase()}try{return JSON.stringify(e).toLowerCase()}catch{return""}}function Fm(e){let n=Lm(e).match(/messages\.(\d+)/);return n?parseInt(n[1],10):null}function Um(e){let t=Lm(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 Uv(e){return Um(e)!==null}function Wv(e){return e.filter(t=>t.type==="tool_use"&&!!t.id).map(t=>t.id)}async function Hv(e,t){ye("recoverToolResultMissing",{sessionID:e,msgId:t.info?.id});let n=t.parts||[];n.length===0&&t.info?.id&&(n=it(t.info.id).map(i=>({type:i.type==="tool"?"tool_use":i.type,id:"callID"in i?i.callID:i.id,name:"tool"in i?i.tool:void 0,input:"state"in i?i.state?.input:void 0})));let o=Wv(n);return o.length===0?(ye("No tool_use IDs found"),!1):(ye("Found tool_use IDs to inject results for",o),!0)}async function Gv(e,t,n){ye("recoverThinkingBlockOrder",{sessionID:e});let o=Fm(n);if(o!==null){let s=jm(e,o);if(s)return ye("Found target message by index",{targetIndex:o,targetMessageID:s}),ya(e,s)}let r=ha(e);if(r.length===0)return ye("No orphan thinking messages found"),!1;ye("Found orphan thinking messages",r);let i=!1;for(let s of r)ya(e,s)&&(i=!0);return i}async function Bv(e,t){ye("recoverThinkingDisabledViolation",{sessionID:e});let n=ga(e);if(n.length===0)return ye("No messages with thinking blocks found"),!1;ye("Found messages with thinking blocks",n);let o=!1;for(let r of n)Nm(r)&&(o=!0);return o}async function qv(e,t,n){ye("recoverEmptyContentMessage",{sessionID:e});let o=Fm(n),r=t.info?.id,i=!1,s=Dm(e);for(let l of s)To(l,We)&&(i=!0);let a=$m(e);for(let l of a)vo(e,l,We)&&(i=!0);if(o!==null){let l=xm(e,o);if(l&&(To(l,We)||vo(e,l,We)))return!0}if(r&&(To(r,We)||vo(e,r,We)))return!0;let c=ma(e);for(let l of c)To(l,We)&&(i=!0),vo(e,l,We)&&(i=!0);return i}async function Vv(e,t,n,o){ye("handleSessionRecovery",{sessionID:e,error:t});let r=Um(t);if(!r)return ye("Not a recoverable error"),{attempted:!1,success:!1};ye("Detected recoverable error type",r);try{let i=!1,s=n||{info:{},parts:[]};switch(r){case"tool_result_missing":i=await Hv(e,s);break;case"thinking_block_order":i=await Gv(e,s,t);break;case"thinking_disabled_violation":i=await Bv(e,s);break;case"empty_content":i=await qv(e,s,t);break}ye("Recovery result",{errorType:r,success:i});let a=o?.customMessages?.[r]||Lr[r]?.message||`Session recovery attempted for ${r}`;return{attempted:!0,success:i,message:i?a:void 0,errorType:r}}catch(i){return ye("Recovery failed with error",i),{attempted:!0,success:!1,errorType:r}}}function Wm(e){return ye("createSessionRecoveryHook",{config:e}),{onError:async t=>Vv(t.session_id,t.error,t.message,e),isRecoverable:t=>Uv(t),getRecoveryMessage:t=>{if(t)return e?.customMessages?.[t]||Lr[t]?.message}}}function Hm(){let e=Wm();S({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 o=await e.onError({session_id:t.sessionId||"default",error:n,message:void 0});return o.attempted&&o.success?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:o.message||`[session-recovery] Recovered from ${o.errorType} error. Please retry.`}}:o.attempted&&!o.success?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:`[session-recovery] Attempted recovery for ${o.errorType} but could not fix automatically. You may need to restart the session.`}}:{continue:!0}}})}var He=require("fs"),Fr=require("path"),Gm=require("os");var Eo=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 o=t.split("/")[0],r=this.config?.providerConcurrency?.[o];if(r!==void 0)return r===0?1/0:r;let i=this.config?.defaultConcurrency;return i!==void 0?i===0?1/0:i:5}async acquire(t){let n=this.getConcurrencyLimit(t);if(n===1/0)return;let o=this.counts.get(t)??0;if(o<n){this.counts.set(t,o+1);return}return new Promise(r=>{let i=this.queues.get(t)??[];i.push(r),this.queues.set(t,i)})}release(t){if(this.getConcurrencyLimit(t)===1/0)return;let o=this.queues.get(t);if(o&&o.length>0)o.shift()();else{let r=this.counts.get(t)??0;r>0&&this.counts.set(t,r-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 Yv=1800*1e3,jn=(0,Fr.join)((0,Gm.homedir)(),".claude",".olympus","background-tasks"),Ur=class{tasks=new Map;notifications=new Map;concurrencyManager;config;pruneInterval;constructor(t){this.config=t??{},this.concurrencyManager=new Eo(t),this.ensureStorageDir(),this.loadPersistedTasks(),this.startPruning()}ensureStorageDir(){(0,He.existsSync)(jn)||(0,He.mkdirSync)(jn,{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,Fr.join)(jn,`${t}.json`)}persistTask(t){let n=this.getTaskPath(t.id);(0,He.writeFileSync)(n,JSON.stringify(t,null,2))}unpersistTask(t){let n=this.getTaskPath(t);(0,He.existsSync)(n)&&(0,He.unlinkSync)(n)}loadPersistedTasks(){if((0,He.existsSync)(jn))try{let{readdirSync:t}=require("fs"),n=t(jn);for(let o of n)if(o.endsWith(".json"))try{let r=(0,Fr.join)(jn,o),i=(0,He.readFileSync)(r,"utf-8"),s=JSON.parse(i);s.startedAt=new Date(s.startedAt),s.completedAt&&(s.completedAt=new Date(s.completedAt)),s.progress?.lastUpdate&&(s.progress.lastUpdate=new Date(s.progress.lastUpdate)),s.progress?.lastMessageAt&&(s.progress.lastMessageAt=new Date(s.progress.lastMessageAt)),this.tasks.set(s.id,s)}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??Yv;for(let[o,r]of this.tasks.entries())t-r.startedAt.getTime()>n&&r.status==="running"&&(r.status="error",r.error=`Task timed out after ${Math.round(n/6e4)} minutes`,r.completedAt=new Date,r.concurrencyKey&&this.concurrencyManager.release(r.concurrencyKey),this.clearNotificationsForTask(o),this.unpersistTask(o),this.tasks.delete(o));for(let[o,r]of this.notifications.entries()){let i=r.filter(s=>t-s.startedAt.getTime()<=n);i.length===0?this.notifications.delete(o):i.length!==r.length&&this.notifications.set(o,i)}}async launch(t){let n=t.agent,o=this.config.maxTotalTasks??10;if(Array.from(this.tasks.values()).filter(c=>c.status==="running").length>=o)throw new Error(`Maximum concurrent background tasks (${o}) reached. Wait for some tasks to complete.`);await this.concurrencyManager.acquire(n);let i=this.generateTaskId(),s=`ses_${this.generateTaskId()}`,a={id:i,sessionId:s,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(i,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 o of this.tasks.values())o.parentSessionId===t&&n.push(o);return n}getAllTasks(){return Array.from(this.tasks.values())}getRunningTasks(){return Array.from(this.tasks.values()).filter(t=>t.status==="running")}updateTaskStatus(t,n,o,r){let i=this.tasks.get(t);i&&(i.status=n,o&&(i.result=o),r&&(i.error=r),(n==="completed"||n==="error"||n==="cancelled")&&(i.completedAt=new Date,i.concurrencyKey&&this.concurrencyManager.release(i.concurrencyKey),this.markForNotification(i)),this.persistTask(i))}updateTaskProgress(t,n){let o=this.tasks.get(t);o&&(o.progress||(o.progress={toolCalls:0,lastUpdate:new Date}),Object.assign(o.progress,n,{lastUpdate:new Date}),this.persistTask(o))}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,o]of this.notifications.entries()){let r=o.filter(i=>i.id!==t);r.length===0?this.notifications.delete(n):this.notifications.set(n,r)}}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 o=(n??new Date).getTime()-t.getTime(),r=Math.floor(o/1e3),i=Math.floor(r/60),s=Math.floor(i/60);return s>0?`${s}h ${i%60}m ${r%60}s`:i>0?`${i}m ${r%60}s`:`${r}s`}getStatusSummary(){let t=this.getRunningTasks(),n=this.getAllTasks();if(n.length===0)return"No background tasks.";let o=[`Background Tasks: ${t.length} running, ${n.length} total`,""];for(let r of n){let i=this.formatDuration(r.startedAt,r.completedAt),s=r.status.toUpperCase(),a=r.progress?` (${r.progress.toolCalls} tools)`:"";o.push(` [${s}] ${r.description} - ${i}${a}`),r.error&&o.push(` Error: ${r.error}`)}return o.join(`
1786
+ `)}cleanup(){this.stopPruning(),this.tasks.clear(),this.notifications.clear()}},ka;function wa(e){return ka||(ka=new Ur(e)),ka}function Kv(e){let t=e.status.toUpperCase(),n=Jv(e.startedAt,e.completedAt),r=[`${e.status==="completed"?"\u2713":e.status==="error"?"\u2717":"\u25CB"} [${t}] ${e.description}`,` Agent: ${e.agent}`,` Duration: ${n}`];if(e.progress?.toolCalls&&r.push(` Tool calls: ${e.progress.toolCalls}`),e.result){let i=e.result.substring(0,200),s=e.result.length>200?"...":"";r.push(` Result: ${i}${s}`)}return e.error&&r.push(` Error: ${e.error}`),r.join(`
1787
+ `)}function Jv(e,t){let n=(t??new Date).getTime()-e.getTime(),o=Math.floor(n/1e3),r=Math.floor(o/60),i=Math.floor(r/60);return i>0?`${i}h ${r%60}m ${o%60}s`:r>0?`${r}m ${o%60}s`:`${o}s`}function zv(e){if(e.length===0)return"";let t=e.length===1?`
1788
1788
  [BACKGROUND TASK COMPLETED]
1789
1789
  `:`
1790
1790
  [${e.length} BACKGROUND TASKS COMPLETED]
1791
- `,n=e.map(o=>Vv(o)).join(`
1791
+ `,n=e.map(o=>Kv(o)).join(`
1792
1792
 
1793
1793
  `);return`${t}
1794
1794
  ${n}
1795
- `}function Jv(e,t,n){let o=t.getPendingNotifications(e);if(o.length===0)return{hasNotifications:!1,tasks:[]};let i=(n?.formatNotification??Kv)(o);return{hasNotifications:!0,tasks:o,message:i}}function Hm(e,t){let n=e.sessionId;if(!n)return{continue:!0};let o=ya(),r=Jv(n,o,t);return r.hasNotifications?((t?.autoClear??!0)&&o.clearNotifications(n),{continue:!0,message:r.message,notificationCount:r.tasks.length}):{continue:!0}}function Gm(){_({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 Hm(t);return{continue:n.continue,hookSpecificOutput:n.message?{hookEventName:"Notification",additionalContext:n.message}:void 0}}})}var wa=null,ka=!1;async function zv(){if(!ka)try{let{encode:e}=await import("gpt-tokenizer");wa=e,ka=!0}catch{ka=!0}}function Qv(e){return Math.ceil(e.length/4)}async function tn(e){if(!e||e.length===0)return 0;await zv();try{if(wa)return wa(e).length}catch{}return Qv(e)}async function Bm(e){if(!e)return 0;if(typeof e=="object"&&e!==null){let n=e;if("content"in n&&typeof n.content=="string")return tn(n.content);if("output"in n&&typeof n.output=="string")return tn(n.output);if("text"in n&&typeof n.text=="string")return tn(n.text);if("result"in n&&typeof n.result=="string")return tn(n.result)}let t=typeof e=="string"?e:JSON.stringify(e);return tn(t)}var _a=[{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 qm(e,t,n,o=_a){let r=o.find(a=>new RegExp(a.model_pattern,"i").test(n));if(!r){let a=o.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 i=e/1e6*r.input_per_million,s=t/1e6*r.output_per_million;return{inputCost:i,outputCost:s,totalCost:i+s,pricingVersion:r.effective_date}}Ae();fe();var Mn=b(require("fs"),1),Wr=b(require("path"),1),Qm=b(require("os"),1),Xm=process.env.OLYMPUS_DEBUG_HOOKS==="1",Km=Wr.join(Qm.homedir(),".claude","olympus","learning","hooks-debug.log");function T(e,t,n){if(Xm)try{let r=`[${new Date().toISOString()}] [${e}] ${t}`;n!==void 0&&(typeof n=="object"?r+=`
1795
+ `}function Qv(e,t,n){let o=t.getPendingNotifications(e);if(o.length===0)return{hasNotifications:!1,tasks:[]};let i=(n?.formatNotification??zv)(o);return{hasNotifications:!0,tasks:o,message:i}}function Bm(e,t){let n=e.sessionId;if(!n)return{continue:!0};let o=wa(),r=Qv(n,o,t);return r.hasNotifications?((t?.autoClear??!0)&&o.clearNotifications(n),{continue:!0,message:r.message,notificationCount:r.tasks.length}):{continue:!0}}function qm(){S({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 Bm(t);return{continue:n.continue,hookSpecificOutput:n.message?{hookEventName:"Notification",additionalContext:n.message}:void 0}}})}var _a=null,Sa=!1;async function Xv(){if(!Sa)try{let{encode:e}=await import("gpt-tokenizer");_a=e,Sa=!0}catch{Sa=!0}}function Zv(e){return Math.ceil(e.length/4)}async function tn(e){if(!e||e.length===0)return 0;await Xv();try{if(_a)return _a(e).length}catch{}return Zv(e)}async function Vm(e){if(!e)return 0;if(typeof e=="object"&&e!==null){let n=e;if("content"in n&&typeof n.content=="string")return tn(n.content);if("output"in n&&typeof n.output=="string")return tn(n.output);if("text"in n&&typeof n.text=="string")return tn(n.text);if("result"in n&&typeof n.result=="string")return tn(n.result)}let t=typeof e=="string"?e:JSON.stringify(e);return tn(t)}var va=[{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 Ym(e,t,n,o=va){let r=o.find(a=>new RegExp(a.model_pattern,"i").test(n));if(!r){let a=o.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 i=e/1e6*r.input_per_million,s=t/1e6*r.output_per_million;return{inputCost:i,outputCost:s,totalCost:i+s,pricingVersion:r.effective_date}}Pe();fe();var Mn=b(require("fs"),1),Wr=b(require("path"),1),Zm=b(require("os"),1),eg=process.env.OLYMPUS_DEBUG_HOOKS==="1",zm=Wr.join(Zm.homedir(),".claude","olympus","learning","hooks-debug.log");function T(e,t,n){if(eg)try{let r=`[${new Date().toISOString()}] [${e}] ${t}`;n!==void 0&&(typeof n=="object"?r+=`
1796
1796
  ${JSON.stringify(n,null,2)}`:r+=` ${n}`),r+=`
1797
- `;let i=Wr.dirname(Km);Mn.existsSync(i)||Mn.mkdirSync(i,{recursive:!0}),Mn.appendFileSync(Km,r,"utf8")}catch(o){console.error("[Olympus Debug] Failed to write debug log:",o)}}function Sa(e,t){Xm&&T(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 Zv(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 Jm(e){if(e.message?.model){let{providerId:t,modelId:n}=e.message.model;if(t&&n)return`${t}/${n}`;if(n)return n}}function zm(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 Zm(){_({name:"learningCapturePrompt",event:"UserPromptSubmit",priority:110,handler:async e=>{T("learningCapturePrompt","Hook fired"),Sa("learningCapturePrompt",e);try{if(!e.directory)return T("learningCapturePrompt","No directory in context - skipping"),{continue:!0};T("learningCapturePrompt","Extracting prompt text");let t=Zv(e);if(!t)return T("learningCapturePrompt","No prompt text extracted - skipping"),{continue:!0};T("learningCapturePrompt",`Prompt text extracted (${t.length} chars)`),T("learningCapturePrompt","Estimating input tokens");let n=await tn(t);T("learningCapturePrompt",`Estimated tokens: ${n}`),T("learningCapturePrompt","Loading session state",{directory:e.directory,sessionId:e.sessionId});let o=V(e.directory,e.sessionId);T("learningCapturePrompt","Session state loaded",{hasTokenBudget:!!o.token_budget,currentUsage:o.token_budget?.current_usage,inputTokens:o.token_budget?.input_tokens,outputTokens:o.token_budget?.output_tokens}),zm(o),T("learningCapturePrompt","Token budget ensured");let r=Jm(e);if(T("learningCapturePrompt",`Model identifier: ${r||"none"}`),r&&o.token_budget&&(o.token_budget.current_model=r,T("learningCapturePrompt",`Model set in token budget: ${r}`)),o.token_budget){let i=o.token_budget.input_tokens,s=o.token_budget.current_usage;o.token_budget.input_tokens+=n,o.token_budget.current_usage+=n,T("learningCapturePrompt","Tokens accumulated",{addedTokens:n,inputTokens:{before:i,after:o.token_budget.input_tokens},currentUsage:{before:s,after:o.token_budget.current_usage}}),T("learningCapturePrompt","Saving session state"),Q(e.directory,o),T("learningCapturePrompt","Session state saved successfully")}else T("learningCapturePrompt","WARNING: No token budget after ensure - this should not happen")}catch(t){T("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 T("learningCapturePrompt","Hook completed"),{continue:!0}}}),_({name:"learningCaptureTool",event:"PostToolUse",priority:70,handler:async e=>{T("learningCaptureTool","Hook fired"),Sa("learningCaptureTool",e);try{if(!e.directory||!e.toolName)return T("learningCaptureTool","Missing directory or toolName - skipping",{hasDirectory:!!e.directory,hasToolName:!!e.toolName}),{continue:!0};T("learningCaptureTool",`Processing tool: ${e.toolName}`),T("learningCaptureTool","Estimating output tokens from tool result");let t=e.toolOutput?await Bm(e.toolOutput):0;T("learningCaptureTool",`Estimated output tokens: ${t}`),T("learningCaptureTool","Loading session state",{directory:e.directory,sessionId:e.sessionId});let n=V(e.directory,e.sessionId);T("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}),zm(n),T("learningCaptureTool","Token budget ensured");let o=Jm(e);if(T("learningCaptureTool",`Model identifier: ${o||"none"}`),o&&n.token_budget&&(n.token_budget.current_model=o,T("learningCaptureTool",`Model set in token budget: ${o}`)),n.token_budget){let r=n.token_budget.output_tokens,i=n.token_budget.current_usage;n.token_budget.output_tokens+=t,n.token_budget.current_usage+=t,T("learningCaptureTool","Tokens accumulated",{addedTokens:t,outputTokens:{before:r,after:n.token_budget.output_tokens},currentUsage:{before:i,after:n.token_budget.current_usage}}),T("learningCaptureTool","Saving session state"),Q(e.directory,n),T("learningCaptureTool","Session state saved successfully")}else T("learningCaptureTool","WARNING: No token budget after ensure - this should not happen")}catch(t){T("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 T("learningCaptureTool","Hook completed"),{continue:!0}}}),_({name:"learningCaptureStop",event:"Stop",priority:90,handler:async e=>{T("learningCaptureStop","Hook fired"),Sa("learningCaptureStop",e);try{if(!e.directory)return T("learningCaptureStop","No directory in context - skipping"),{continue:!0};T("learningCaptureStop","Loading session state",{directory:e.directory,sessionId:e.sessionId});let t=V(e.directory,e.sessionId);if(T("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 T("learningCaptureStop","No token budget in session state - skipping (backward compatibility)"),{continue:!0};let n=t.token_budget.current_usage,o=t.token_budget.input_tokens||0,r=t.token_budget.output_tokens||0;if(T("learningCaptureStop","Token totals",{totalTokens:n,inputTokens:o,outputTokens:r}),n===0)return T("learningCaptureStop","No token usage recorded - skipping feedback entry creation"),{continue:!0};let i=t.token_budget.current_model||"unknown";T("learningCaptureStop",`Using model identifier: ${i}`),T("learningCaptureStop","Token usage object created",{input_tokens:o,output_tokens:r,total_tokens:n,estimated:!0,model:i}),T("learningCaptureStop","Calculating cost estimate");let a={input_cost:0,output_cost:0,total_cost:0,pricing_version:"2025-01-01"};try{let l=qm(o,r,i);a.input_cost=l.inputCost,a.output_cost=l.outputCost,a.total_cost=l.totalCost,a.pricing_version=l.pricingVersion,T("learningCaptureStop","Cost calculated successfully",{inputCost:l.inputCost,outputCost:l.outputCost,totalCost:l.totalCost})}catch(l){T("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:o,total_output_tokens:r,total_tokens:n,estimated_cost:a.total_cost,model:i,outcome:"success"};T("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{bc(c),T("learningCaptureStop","Session summary saved successfully")}catch(l){T("learningCaptureStop","Failed to save session summary (non-critical)",{error:l instanceof Error?l.message:String(l)})}try{let{formatSessionSummaryLine:l}=await Promise.resolve().then(()=>(Ym(),Vm)),u=l(c);console.error(u)}catch{}T("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,T("learningCaptureStop","Saving reset session state"),Q(e.directory,t),T("learningCaptureStop","Session state saved successfully")}catch(t){T("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 T("learningCaptureStop","Hook completed"),{continue:!0}}})}Ae();function eg(){_({name:"budgetWarning",event:"PostToolUse",priority:90,handler:e=>{if(!e.directory)return{continue:!0};try{let t=V(e.directory,e.sessionId),n=0;if(e.toolOutput&&typeof e.toolOutput=="object"){let o=e.toolOutput;o.token_usage&&typeof o.token_usage=="object"&&(n=o.token_usage.total_tokens??0)}if(n>0&&Nc(t,n),jc(t)){let o=t.token_budget,r=(o.current_usage/1e3).toFixed(1),i=(o.session_baseline/1e3).toFixed(0),s=(o.current_usage/o.session_baseline).toFixed(2);return Dc(t),Q(e.directory,t),{continue:!0,message:`[TOKEN AWARENESS] Session at ${r}k tokens (${s}x baseline of ${i}k).
1797
+ `;let i=Wr.dirname(zm);Mn.existsSync(i)||Mn.mkdirSync(i,{recursive:!0}),Mn.appendFileSync(zm,r,"utf8")}catch(o){console.error("[Olympus Debug] Failed to write debug log:",o)}}function Ta(e,t){eg&&T(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 tT(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 Qm(e){if(e.message?.model){let{providerId:t,modelId:n}=e.message.model;if(t&&n)return`${t}/${n}`;if(n)return n}}function Xm(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 tg(){S({name:"learningCapturePrompt",event:"UserPromptSubmit",priority:110,handler:async e=>{T("learningCapturePrompt","Hook fired"),Ta("learningCapturePrompt",e);try{if(!e.directory)return T("learningCapturePrompt","No directory in context - skipping"),{continue:!0};T("learningCapturePrompt","Extracting prompt text");let t=tT(e);if(!t)return T("learningCapturePrompt","No prompt text extracted - skipping"),{continue:!0};T("learningCapturePrompt",`Prompt text extracted (${t.length} chars)`),T("learningCapturePrompt","Estimating input tokens");let n=await tn(t);T("learningCapturePrompt",`Estimated tokens: ${n}`),T("learningCapturePrompt","Loading session state",{directory:e.directory,sessionId:e.sessionId});let o=V(e.directory,e.sessionId);T("learningCapturePrompt","Session state loaded",{hasTokenBudget:!!o.token_budget,currentUsage:o.token_budget?.current_usage,inputTokens:o.token_budget?.input_tokens,outputTokens:o.token_budget?.output_tokens}),Xm(o),T("learningCapturePrompt","Token budget ensured");let r=Qm(e);if(T("learningCapturePrompt",`Model identifier: ${r||"none"}`),r&&o.token_budget&&(o.token_budget.current_model=r,T("learningCapturePrompt",`Model set in token budget: ${r}`)),o.token_budget){let i=o.token_budget.input_tokens,s=o.token_budget.current_usage;o.token_budget.input_tokens+=n,o.token_budget.current_usage+=n,T("learningCapturePrompt","Tokens accumulated",{addedTokens:n,inputTokens:{before:i,after:o.token_budget.input_tokens},currentUsage:{before:s,after:o.token_budget.current_usage}}),T("learningCapturePrompt","Saving session state"),Q(e.directory,o),T("learningCapturePrompt","Session state saved successfully")}else T("learningCapturePrompt","WARNING: No token budget after ensure - this should not happen")}catch(t){T("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 T("learningCapturePrompt","Hook completed"),{continue:!0}}}),S({name:"learningCaptureTool",event:"PostToolUse",priority:70,handler:async e=>{T("learningCaptureTool","Hook fired"),Ta("learningCaptureTool",e);try{if(!e.directory||!e.toolName)return T("learningCaptureTool","Missing directory or toolName - skipping",{hasDirectory:!!e.directory,hasToolName:!!e.toolName}),{continue:!0};T("learningCaptureTool",`Processing tool: ${e.toolName}`),T("learningCaptureTool","Estimating output tokens from tool result");let t=e.toolOutput?await Vm(e.toolOutput):0;T("learningCaptureTool",`Estimated output tokens: ${t}`),T("learningCaptureTool","Loading session state",{directory:e.directory,sessionId:e.sessionId});let n=V(e.directory,e.sessionId);T("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}),Xm(n),T("learningCaptureTool","Token budget ensured");let o=Qm(e);if(T("learningCaptureTool",`Model identifier: ${o||"none"}`),o&&n.token_budget&&(n.token_budget.current_model=o,T("learningCaptureTool",`Model set in token budget: ${o}`)),n.token_budget){let r=n.token_budget.output_tokens,i=n.token_budget.current_usage;n.token_budget.output_tokens+=t,n.token_budget.current_usage+=t,T("learningCaptureTool","Tokens accumulated",{addedTokens:t,outputTokens:{before:r,after:n.token_budget.output_tokens},currentUsage:{before:i,after:n.token_budget.current_usage}}),T("learningCaptureTool","Saving session state"),Q(e.directory,n),T("learningCaptureTool","Session state saved successfully")}else T("learningCaptureTool","WARNING: No token budget after ensure - this should not happen")}catch(t){T("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 T("learningCaptureTool","Hook completed"),{continue:!0}}}),S({name:"learningCaptureStop",event:"Stop",priority:90,handler:async e=>{T("learningCaptureStop","Hook fired"),Ta("learningCaptureStop",e);try{if(!e.directory)return T("learningCaptureStop","No directory in context - skipping"),{continue:!0};T("learningCaptureStop","Loading session state",{directory:e.directory,sessionId:e.sessionId});let t=V(e.directory,e.sessionId);if(T("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 T("learningCaptureStop","No token budget in session state - skipping (backward compatibility)"),{continue:!0};let n=t.token_budget.current_usage,o=t.token_budget.input_tokens||0,r=t.token_budget.output_tokens||0;if(T("learningCaptureStop","Token totals",{totalTokens:n,inputTokens:o,outputTokens:r}),n===0)return T("learningCaptureStop","No token usage recorded - skipping feedback entry creation"),{continue:!0};let i=t.token_budget.current_model||"unknown";T("learningCaptureStop",`Using model identifier: ${i}`),T("learningCaptureStop","Token usage object created",{input_tokens:o,output_tokens:r,total_tokens:n,estimated:!0,model:i}),T("learningCaptureStop","Calculating cost estimate");let a={input_cost:0,output_cost:0,total_cost:0,pricing_version:"2025-01-01"};try{let l=Ym(o,r,i);a.input_cost=l.inputCost,a.output_cost=l.outputCost,a.total_cost=l.totalCost,a.pricing_version=l.pricingVersion,T("learningCaptureStop","Cost calculated successfully",{inputCost:l.inputCost,outputCost:l.outputCost,totalCost:l.totalCost})}catch(l){T("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:o,total_output_tokens:r,total_tokens:n,estimated_cost:a.total_cost,model:i,outcome:"success"};T("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{Ic(c),T("learningCaptureStop","Session summary saved successfully")}catch(l){T("learningCaptureStop","Failed to save session summary (non-critical)",{error:l instanceof Error?l.message:String(l)})}try{let{formatSessionSummaryLine:l}=await Promise.resolve().then(()=>(Jm(),Km)),u=l(c);console.error(u)}catch{}T("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,T("learningCaptureStop","Saving reset session state"),Q(e.directory,t),T("learningCaptureStop","Session state saved successfully")}catch(t){T("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 T("learningCaptureStop","Hook completed"),{continue:!0}}})}Pe();function ng(){S({name:"budgetWarning",event:"PostToolUse",priority:90,handler:e=>{if(!e.directory)return{continue:!0};try{let t=V(e.directory,e.sessionId),n=0;if(e.toolOutput&&typeof e.toolOutput=="object"){let o=e.toolOutput;o.token_usage&&typeof o.token_usage=="object"&&(n=o.token_usage.total_tokens??0)}if(n>0&&jc(t,n),Lc(t)){let o=t.token_budget,r=(o.current_usage/1e3).toFixed(1),i=(o.session_baseline/1e3).toFixed(0),s=(o.current_usage/o.session_baseline).toFixed(2);return Mc(t),Q(e.directory,t),{continue:!0,message:`[TOKEN AWARENESS] Session at ${r}k tokens (${s}x baseline of ${i}k).
1798
1798
  This is informational - continue if task requires it.
1799
- Consider: delegate to subagent, break into smaller tasks.`}}return Q(e.directory,t),{continue:!0}}catch(t){return console.error("[Olympus Learning] Budget warning error:",t),{continue:!0}}}})}Ae();Ee();J();Qo();pt();var Ln=b(require("fs"),1),Eo=b(require("path"),1),cg=b(require("os"),1),iT=process.env.OLYMPUS_DEBUG_HOOKS==="1",ag=Eo.join(cg.homedir(),".claude","olympus","learning","hooks-debug.log");function L(e,t,n){if(iT)try{let r=`[${new Date().toISOString()}] [${e}] ${t}`;n!==void 0&&(typeof n=="object"?r+=`
1799
+ Consider: delegate to subagent, break into smaller tasks.`}}return Q(e.directory,t),{continue:!0}}catch(t){return console.error("[Olympus Learning] Budget warning error:",t),{continue:!0}}}})}Pe();Ee();J();Xo();pt();var Ln=b(require("fs"),1),bo=b(require("path"),1),ug=b(require("os"),1),aT=process.env.OLYMPUS_DEBUG_HOOKS==="1",lg=bo.join(ug.homedir(),".claude","olympus","learning","hooks-debug.log");function L(e,t,n){if(aT)try{let r=`[${new Date().toISOString()}] [${e}] ${t}`;n!==void 0&&(typeof n=="object"?r+=`
1800
1800
  ${JSON.stringify(n,null,2)}`:r+=` ${n}`),r+=`
1801
- `;let i=Eo.dirname(ag);Ln.existsSync(i)||Ln.mkdirSync(i,{recursive:!0}),Ln.appendFileSync(ag,r,"utf8")}catch(o){console.error("[Olympus Debug] Failed to write debug log:",o)}}async function sT(e,t){try{let n=e.includes("executing a coding task as part of a structured workflow"),o=e.match(/BOLT-(\d+)/i);if(!n&&!o)return null;let r=await te(t);if(r.length===0)return null;let i=await I(t,r[0]);return i?i.active_code_plan_path?{boltId:i.active_code_plan_path,workflowId:i.workflow_id}:o&&n?{boltId:`BOLT-${o[1].padStart(3,"0")}`,workflowId:i.workflow_id}:null:null}catch(n){return L("agentTracking","Error detecting BOLT execution",{error:n instanceof Error?n.message:String(n)}),null}}function lg(){_({name:"agentTracking",event:"PreToolUse",priority:50,handler:async e=>{L("agentTracking","Hook fired"),L("agentTracking","Context received",{directory:e.directory,sessionId:e.sessionId,toolName:e.toolName,hasToolInput:!!e.toolInput});let t=null;try{if(e.toolName!=="Task")return L("agentTracking",`Skipping non-Task tool: ${e.toolName}`),{continue:!0};if(L("agentTracking","Task tool detected - processing"),!e.directory)return L("agentTracking","No directory in context - skipping"),{continue:!0};if(!e.sessionId)return L("agentTracking","No sessionId in context - skipping"),{continue:!0};if(!e.toolInput)return L("agentTracking","No toolInput in context - skipping"),{continue:!0};let n=e.toolInput,o=n.subagent_type,r=n.prompt;if(L("agentTracking","Tool input extracted",{subagentType:o,hasPrompt:!!r,promptLength:typeof r=="string"?r.length:0}),!o||typeof o!="string")return L("agentTracking","Missing or invalid subagent_type - skipping"),{continue:!0};if(!r||typeof r!="string")return L("agentTracking","Missing or invalid prompt - skipping"),{continue:!0};L("agentTracking","Loading session state",{directory:e.directory,sessionId:e.sessionId});let i=V(e.directory,e.sessionId);L("agentTracking","Session state loaded",{sessionId:i.session_id,hasPendingCompletion:!!i.pending_completion});try{let{getRoutingRecommendation:a}=await Promise.resolve().then(()=>(sg(),ig));t=a(o,r),t&&L("agentTracking","Routing recommendation generated",{recommendation:t})}catch{}let s=await sT(r,e.directory);if(L("agentTracking","BOLT detection result",{isBoltExecution:!!s,boltId:s?.boltId,workflowId:s?.workflowId}),L("agentTracking","Marking completion claim",{agent:o,taskLength:r.length,hasBoltMetadata:!!s}),Pc(i,r,o),s&&i.pending_completion){i.pending_completion.bolt_id=s.boltId,i.pending_completion.workflow_id=s.workflowId,L("agentTracking","BOLT metadata added to pending_completion",{bolt_id:s.boltId,workflow_id:s.workflowId});try{let a=await te(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)L("agentTracking","No active workflow found for manifest update");else{let l=Eo.join(e.directory,"aidlc-docs",c,"manifest.json"),u=D(l);if(u){let d=u.artifacts.find(f=>f.id===s.boltId);d&&(d.executedBy=o,F(l,u),L("agentTracking","Set executedBy on BOLT artifact",{boltId:s.boltId,executedBy:o}))}}}catch(a){L("agentTracking","Error setting executedBy on manifest",{error:a instanceof Error?a.message:String(a)})}}L("agentTracking","Completion claim marked",{claimedAt:i.pending_completion?.claimed_at,agentUsed:i.pending_completion?.agent_used,bolt_id:i.pending_completion?.bolt_id,workflow_id:i.pending_completion?.workflow_id}),i.token_budget&&(i.token_budget.agents_used||(i.token_budget.agents_used=[]),i.token_budget.agents_used.includes(o)||i.token_budget.agents_used.push(o),L("agentTracking","Agents accumulated",{agents_used:i.token_budget.agents_used})),L("agentTracking","Saving session state"),Q(e.directory,i),L("agentTracking","Session state saved successfully")}catch(n){L("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 L("agentTracking","Hook completed"),t?{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:t}}:{continue:!0}}}),_({name:"agentTrackingBoltCompletion",event:"PostToolUse",priority:51,handler:async e=>{L("agentTrackingBoltCompletion","Hook fired");try{if(e.toolName!=="Task")return L("agentTrackingBoltCompletion",`Skipping non-Task tool: ${e.toolName}`),{continue:!0};if(!e.directory||!e.sessionId)return L("agentTrackingBoltCompletion","Missing directory or sessionId - skipping"),{continue:!0};let t=V(e.directory,e.sessionId);if(L("agentTrackingBoltCompletion","Session state loaded",{hasPendingCompletion:!!t.pending_completion,bolt_id:t.pending_completion?.bolt_id}),!t.pending_completion||!t.pending_completion.bolt_id)return L("agentTrackingBoltCompletion","No BOLT execution detected - skipping"),{continue:!0};let{bolt_id:n,workflow_id:o,agent_used:r,task_description:i}=t.pending_completion;if(!r)return L("agentTrackingBoltCompletion","No agent_used in pending_completion - skipping"),{continue:!0};L("agentTrackingBoltCompletion","Recording BOLT execution",{boltId:n,agentName:r,workflowId:o}),rd({boltId:n,agentName:r,success:!0,sessionId:e.sessionId,projectPath:e.directory,taskDescription:i}),L("agentTrackingBoltCompletion","BOLT execution recorded successfully");try{let s={type:"bolt_execution_complete",phase:"construction",stage:"code-generation",details:`BOLT ${n} executed by ${r}`,artifactId:n,agentName:r},a={workflowId:o||"unknown",featureName:o||"unknown",projectPath:e.directory,sessionId:e.sessionId,phase:"construction"},c=xe(s,a);ie(c),L("agentTrackingBoltCompletion","BOLT completion discovery recorded",{boltId:n,discoveryId:c.id})}catch(s){console.error("[Olympus Agent Tracking] Failed to capture BOLT completion discovery:",s),L("agentTrackingBoltCompletion","Failed to capture BOLT completion discovery",{error:s instanceof Error?s.message:String(s)})}}catch(t){L("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 L("agentTrackingBoltCompletion","Hook completed"),{continue:!0}}})}Ae();var Ta=require("path"),ug=require("os");fe();var aT={enabled:!0,minConfidence:.6,maxPerSession:5,maxPerDay:20,deduplicationWindowDays:7};function Fn(e){let t=(0,Ta.join)((0,ug.homedir)(),".claude","olympus","config.json"),n=me(t,{}),o={};if(e){let i=(0,Ta.join)(e,".olympus","config.json");o=me(i,{})}let r={...aT,...n.autoDiscovery||{},...o.autoDiscovery||{}};return r.minConfidence=Math.max(0,Math.min(1,r.minConfidence)),r.maxPerSession=Math.max(1,Math.min(50,r.maxPerSession)),r.maxPerDay=Math.max(1,Math.min(200,r.maxPerDay)),r.deduplicationWindowDays=Math.max(1,Math.min(90,r.deduplicationWindowDays)),r}var Hr=require("fs"),dg=require("path");fe();var cT={praise:.85,problem_solved:.7,topic_change:.6},lT=[{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 pg(e,t){if(!e.pending_completion?.task_description)return null;let n=e.pending_completion.task_description,o=e.pending_completion.agent_used||"unknown",r=mT(n),i=gT(n),s=uT(n,o),a=cT[t]??.6;return{session_id:e.session_id,category:s,summary:r,details:i,agent_name:o,task_context:n.substring(0,200),confidence:a,scope:"project"}}function fg(e,t,n=7){let o=hT(t,n);if(o.length===0)return!1;let r=e.summary||"",i=e.details||"";for(let s of o)if(s.details===i&&i.length>0||r.length>0&&s.summary&&dT(r,s.summary)>.7)return!0;return!1}function uT(e,t){for(let{pattern:n,category:o}of lT)if(n.test(e))return o;return"technical_insight"}function dT(e,t){let n=a=>new Set(a.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter(c=>c.length>3)),o=n(e),r=n(t);if(o.size===0&&r.size===0)return 1;if(o.size===0||r.size===0)return 0;let i=new Set([...o].filter(a=>r.has(a))),s=new Set([...o,...r]);return s.size>0?i.size/s.size:0}function Un(e,t){if(e.length<=t)return e;let n=e.substring(0,t),o=n.lastIndexOf(" ");return o>t*.5?n.substring(0,o)+"...":n+"..."}function pT(e,t=100){if(!e||e.length===0)return"";let n=e.match(/^[^.]+\./),o=e.indexOf(`
1802
- `),r=e.length;n&&n[0].length<=t&&(r=Math.min(r,n[0].length)),o>0&&o<=t&&(r=Math.min(r,o)),r=Math.min(r,t);let i=e.substring(0,r).trim();return i.length<e.length&&!i.endsWith(".")?Un(i,t):i}function fT(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 mT(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=fT(e),o=pT(n,150);for(let[i,s]of Object.entries(t)){let a=new RegExp(`^${i}\\b`,"i");if(a.test(o)){let c=o.replace(a,s);return Un(c.trim(),100)}}let r=n.match(/^In the .+? project,\s*(.+)/i);if(r){let i=r[1].trim();if(i.toLowerCase().startsWith("i need to")){let s=i.replace(/^i need to\s+/i,"");return Un(s.charAt(0).toUpperCase()+s.slice(1),100)}return Un(i,100)}return Un(o,100)}function gT(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 o=t.match(/^\d+\.\s+(.+)/gm);return o&&o.length>0&&(t=o.slice(0,3).map(s=>s.replace(/^\d+\.\s+/,"").trim()).join("; ")),t=t.split(/\n\n/)[0]||t,t=t.replace(/\s+/g," ").trim(),t.length>500?Un(t,500):t}function hT(e,t){let n=Qe(e),o=(0,dg.join)(n,"discoveries.jsonl");if(!(0,Hr.existsSync)(o))return[];try{let r=(0,Hr.readFileSync)(o,"utf-8"),i=new Date(Date.now()-t*24*60*60*1e3);return r.split(`
1803
- `).filter(s=>s.trim()).map(s=>{try{return JSON.parse(s)}catch{return null}}).filter(s=>s?new Date(s.timestamp)>=i:!1)}catch{return[]}}pt();function mg(){_({name:"discoveryCapture",event:"Stop",priority:92,handler:async e=>{try{if(!e.directory)return{continue:!0};let t=Fn(e.directory);if(!t.enabled)return{continue:!0};let n=V(e.directory,e.sessionId);if(Lc(n,t))return{continue:!0};if(!No(n))return{continue:!0};let o=yT(n);if(!o)return{continue:!0};let r=pg(n,o);if(!r)return{continue:!0};if((r.confidence||0)<t.minConfidence)return{continue:!0};if(fg(r,e.directory,t.deduplicationWindowDays))return{continue:!0};ie({...r,project_path:e.directory,session_id:n.session_id,category:r.category||"technical_insight",summary:r.summary||"",details:r.details||"",agent_name:r.agent_name||"unknown",confidence:r.confidence||.6,scope:"project"}),Mc(n),Q(e.directory,n)}catch(t){console.error("[Olympus Discovery Capture] Error:",t)}return{continue:!0}}})}function yT(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&&kT(n.prompt,e.pending_completion.task_description)<.2?"topic_change":null}function kT(e,t){let n=a=>new Set(a.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter(c=>c.length>3)),o=n(e),r=n(t);if(o.size===0&&r.size===0)return 1;if(o.size===0||r.size===0)return 0;let i=new Set([...o].filter(a=>r.has(a))),s=new Set([...o,...r]);return s.size>0?i.size/s.size:0}Ae();var Wn=require("fs"),yg=require("path"),gg=new Map;function kg(e,t,n){try{if(!(0,Wn.existsSync)(t))return null;let o=(0,yg.relative)(e,t),r=(0,Wn.readFileSync)(t,"utf-8"),s=(0,Wn.statSync)(t).mtimeMs,a=gg.get(t),c=a===void 0;if(gg.set(t,s),!c&&a===s)return null;let l=wT(r);if(c)return{event_type:"plan_created",plan_path:o,plan_summary:l,revision_count:0,session_id:n,timestamp:new Date().toISOString()};let u=ST(t);return{event_type:"plan_revised",plan_path:o,plan_summary:l,revision_count:u,session_id:n,timestamp:new Date().toISOString()}}catch{return null}}function wg(e){let t=typeof e=="string"?e:String(e||"");if(!t)return{passed:!1,issues:["Empty review output"]};let n=t.toUpperCase(),r=["APPROVED","LOOKS GOOD","NO CRITICAL ISSUES","PLAN IS SOLID"].some(c=>n.includes(c)),s=["CRITICAL","REVISE","REJECT","MAJOR ISSUE","MISSING","INCOMPLETE"].some(c=>n.includes(c)),a=_T(t);return r&&!s?{passed:!0,issues:a}:s?{passed:!1,issues:a.length>0?a:["Plan requires revision"]}:{passed:!0,issues:a}}function Ea(e,t,n){let o=e.plan_path.split("/").pop()||e.plan_path,r=t.length,i=e.event_type==="plan_review_failed"?`Plan '${o}' failed review: ${r} issue${r!==1?"s":""}`:`Plan '${o}' failed: ${r} issue${r!==1?"s":""}`,s=t.map(c=>`- ${c}`).join(`
1801
+ `;let i=bo.dirname(lg);Ln.existsSync(i)||Ln.mkdirSync(i,{recursive:!0}),Ln.appendFileSync(lg,r,"utf8")}catch(o){console.error("[Olympus Debug] Failed to write debug log:",o)}}async function cT(e,t){try{let n=e.includes("executing a coding task as part of a structured workflow"),o=e.match(/BOLT-(\d+)/i);if(!n&&!o)return null;let r=await te(t);if(r.length===0)return null;let i=await C(t,r[0]);return i?i.active_code_plan_path?{boltId:i.active_code_plan_path,workflowId:i.workflow_id}:o&&n?{boltId:`BOLT-${o[1].padStart(3,"0")}`,workflowId:i.workflow_id}:null:null}catch(n){return L("agentTracking","Error detecting BOLT execution",{error:n instanceof Error?n.message:String(n)}),null}}function dg(){S({name:"agentTracking",event:"PreToolUse",priority:50,handler:async e=>{L("agentTracking","Hook fired"),L("agentTracking","Context received",{directory:e.directory,sessionId:e.sessionId,toolName:e.toolName,hasToolInput:!!e.toolInput});let t=null;try{if(e.toolName!=="Task")return L("agentTracking",`Skipping non-Task tool: ${e.toolName}`),{continue:!0};if(L("agentTracking","Task tool detected - processing"),!e.directory)return L("agentTracking","No directory in context - skipping"),{continue:!0};if(!e.sessionId)return L("agentTracking","No sessionId in context - skipping"),{continue:!0};if(!e.toolInput)return L("agentTracking","No toolInput in context - skipping"),{continue:!0};let n=e.toolInput,o=n.subagent_type,r=n.prompt;if(L("agentTracking","Tool input extracted",{subagentType:o,hasPrompt:!!r,promptLength:typeof r=="string"?r.length:0}),!o||typeof o!="string")return L("agentTracking","Missing or invalid subagent_type - skipping"),{continue:!0};if(!r||typeof r!="string")return L("agentTracking","Missing or invalid prompt - skipping"),{continue:!0};L("agentTracking","Loading session state",{directory:e.directory,sessionId:e.sessionId});let i=V(e.directory,e.sessionId);L("agentTracking","Session state loaded",{sessionId:i.session_id,hasPendingCompletion:!!i.pending_completion});try{let{getRoutingRecommendation:a}=await Promise.resolve().then(()=>(cg(),ag));t=a(o,r),t&&L("agentTracking","Routing recommendation generated",{recommendation:t})}catch{}let s=await cT(r,e.directory);if(L("agentTracking","BOLT detection result",{isBoltExecution:!!s,boltId:s?.boltId,workflowId:s?.workflowId}),L("agentTracking","Marking completion claim",{agent:o,taskLength:r.length,hasBoltMetadata:!!s}),$c(i,r,o),s&&i.pending_completion){i.pending_completion.bolt_id=s.boltId,i.pending_completion.workflow_id=s.workflowId,L("agentTracking","BOLT metadata added to pending_completion",{bolt_id:s.boltId,workflow_id:s.workflowId});try{let a=await te(e.directory),c=null;for(let l of a){let u=await C(e.directory,l);if(u&&u.status!=="complete"&&u.status!=="archived"&&u.status!=="deferred"){c=l;break}}if(!c)L("agentTracking","No active workflow found for manifest update");else{let l=bo.join(e.directory,"aidlc-docs",c,"manifest.json"),u=D(l);if(u){let d=u.artifacts.find(f=>f.id===s.boltId);d&&(d.executedBy=o,F(l,u),L("agentTracking","Set executedBy on BOLT artifact",{boltId:s.boltId,executedBy:o}))}}}catch(a){L("agentTracking","Error setting executedBy on manifest",{error:a instanceof Error?a.message:String(a)})}}L("agentTracking","Completion claim marked",{claimedAt:i.pending_completion?.claimed_at,agentUsed:i.pending_completion?.agent_used,bolt_id:i.pending_completion?.bolt_id,workflow_id:i.pending_completion?.workflow_id}),i.token_budget&&(i.token_budget.agents_used||(i.token_budget.agents_used=[]),i.token_budget.agents_used.includes(o)||i.token_budget.agents_used.push(o),L("agentTracking","Agents accumulated",{agents_used:i.token_budget.agents_used})),L("agentTracking","Saving session state"),Q(e.directory,i),L("agentTracking","Session state saved successfully")}catch(n){L("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 L("agentTracking","Hook completed"),t?{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:t}}:{continue:!0}}}),S({name:"agentTrackingBoltCompletion",event:"PostToolUse",priority:51,handler:async e=>{L("agentTrackingBoltCompletion","Hook fired");try{if(e.toolName!=="Task")return L("agentTrackingBoltCompletion",`Skipping non-Task tool: ${e.toolName}`),{continue:!0};if(!e.directory||!e.sessionId)return L("agentTrackingBoltCompletion","Missing directory or sessionId - skipping"),{continue:!0};let t=V(e.directory,e.sessionId);if(L("agentTrackingBoltCompletion","Session state loaded",{hasPendingCompletion:!!t.pending_completion,bolt_id:t.pending_completion?.bolt_id}),!t.pending_completion||!t.pending_completion.bolt_id)return L("agentTrackingBoltCompletion","No BOLT execution detected - skipping"),{continue:!0};let{bolt_id:n,workflow_id:o,agent_used:r,task_description:i}=t.pending_completion;if(!r)return L("agentTrackingBoltCompletion","No agent_used in pending_completion - skipping"),{continue:!0};L("agentTrackingBoltCompletion","Recording BOLT execution",{boltId:n,agentName:r,workflowId:o}),sd({boltId:n,agentName:r,success:!0,sessionId:e.sessionId,projectPath:e.directory,taskDescription:i}),L("agentTrackingBoltCompletion","BOLT execution recorded successfully");try{let s={type:"bolt_execution_complete",phase:"construction",stage:"code-generation",details:`BOLT ${n} executed by ${r}`,artifactId:n,agentName:r},a={workflowId:o||"unknown",featureName:o||"unknown",projectPath:e.directory,sessionId:e.sessionId,phase:"construction"},c=$e(s,a);ie(c),L("agentTrackingBoltCompletion","BOLT completion discovery recorded",{boltId:n,discoveryId:c.id})}catch(s){console.error("[Olympus Agent Tracking] Failed to capture BOLT completion discovery:",s),L("agentTrackingBoltCompletion","Failed to capture BOLT completion discovery",{error:s instanceof Error?s.message:String(s)})}}catch(t){L("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 L("agentTrackingBoltCompletion","Hook completed"),{continue:!0}}})}Pe();var ba=require("path"),pg=require("os");fe();var lT={enabled:!0,minConfidence:.6,maxPerSession:5,maxPerDay:20,deduplicationWindowDays:7};function Fn(e){let t=(0,ba.join)((0,pg.homedir)(),".claude","olympus","config.json"),n=me(t,{}),o={};if(e){let i=(0,ba.join)(e,".olympus","config.json");o=me(i,{})}let r={...lT,...n.autoDiscovery||{},...o.autoDiscovery||{}};return r.minConfidence=Math.max(0,Math.min(1,r.minConfidence)),r.maxPerSession=Math.max(1,Math.min(50,r.maxPerSession)),r.maxPerDay=Math.max(1,Math.min(200,r.maxPerDay)),r.deduplicationWindowDays=Math.max(1,Math.min(90,r.deduplicationWindowDays)),r}var Hr=require("fs"),fg=require("path");fe();var uT={praise:.85,problem_solved:.7,topic_change:.6},dT=[{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 mg(e,t){if(!e.pending_completion?.task_description)return null;let n=e.pending_completion.task_description,o=e.pending_completion.agent_used||"unknown",r=hT(n),i=yT(n),s=pT(n,o),a=uT[t]??.6;return{session_id:e.session_id,category:s,summary:r,details:i,agent_name:o,task_context:n.substring(0,200),confidence:a,scope:"project"}}function gg(e,t,n=7){let o=kT(t,n);if(o.length===0)return!1;let r=e.summary||"",i=e.details||"";for(let s of o)if(s.details===i&&i.length>0||r.length>0&&s.summary&&fT(r,s.summary)>.7)return!0;return!1}function pT(e,t){for(let{pattern:n,category:o}of dT)if(n.test(e))return o;return"technical_insight"}function fT(e,t){let n=a=>new Set(a.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter(c=>c.length>3)),o=n(e),r=n(t);if(o.size===0&&r.size===0)return 1;if(o.size===0||r.size===0)return 0;let i=new Set([...o].filter(a=>r.has(a))),s=new Set([...o,...r]);return s.size>0?i.size/s.size:0}function Un(e,t){if(e.length<=t)return e;let n=e.substring(0,t),o=n.lastIndexOf(" ");return o>t*.5?n.substring(0,o)+"...":n+"..."}function mT(e,t=100){if(!e||e.length===0)return"";let n=e.match(/^[^.]+\./),o=e.indexOf(`
1802
+ `),r=e.length;n&&n[0].length<=t&&(r=Math.min(r,n[0].length)),o>0&&o<=t&&(r=Math.min(r,o)),r=Math.min(r,t);let i=e.substring(0,r).trim();return i.length<e.length&&!i.endsWith(".")?Un(i,t):i}function gT(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 hT(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=gT(e),o=mT(n,150);for(let[i,s]of Object.entries(t)){let a=new RegExp(`^${i}\\b`,"i");if(a.test(o)){let c=o.replace(a,s);return Un(c.trim(),100)}}let r=n.match(/^In the .+? project,\s*(.+)/i);if(r){let i=r[1].trim();if(i.toLowerCase().startsWith("i need to")){let s=i.replace(/^i need to\s+/i,"");return Un(s.charAt(0).toUpperCase()+s.slice(1),100)}return Un(i,100)}return Un(o,100)}function yT(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 o=t.match(/^\d+\.\s+(.+)/gm);return o&&o.length>0&&(t=o.slice(0,3).map(s=>s.replace(/^\d+\.\s+/,"").trim()).join("; ")),t=t.split(/\n\n/)[0]||t,t=t.replace(/\s+/g," ").trim(),t.length>500?Un(t,500):t}function kT(e,t){let n=Qe(e),o=(0,fg.join)(n,"discoveries.jsonl");if(!(0,Hr.existsSync)(o))return[];try{let r=(0,Hr.readFileSync)(o,"utf-8"),i=new Date(Date.now()-t*24*60*60*1e3);return r.split(`
1803
+ `).filter(s=>s.trim()).map(s=>{try{return JSON.parse(s)}catch{return null}}).filter(s=>s?new Date(s.timestamp)>=i:!1)}catch{return[]}}pt();function hg(){S({name:"discoveryCapture",event:"Stop",priority:92,handler:async e=>{try{if(!e.directory)return{continue:!0};let t=Fn(e.directory);if(!t.enabled)return{continue:!0};let n=V(e.directory,e.sessionId);if(Uc(n,t))return{continue:!0};if(!Do(n))return{continue:!0};let o=wT(n);if(!o)return{continue:!0};let r=mg(n,o);if(!r)return{continue:!0};if((r.confidence||0)<t.minConfidence)return{continue:!0};if(gg(r,e.directory,t.deduplicationWindowDays))return{continue:!0};ie({...r,project_path:e.directory,session_id:n.session_id,category:r.category||"technical_insight",summary:r.summary||"",details:r.details||"",agent_name:r.agent_name||"unknown",confidence:r.confidence||.6,scope:"project"}),Fc(n),Q(e.directory,n)}catch(t){console.error("[Olympus Discovery Capture] Error:",t)}return{continue:!0}}})}function wT(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&&ST(n.prompt,e.pending_completion.task_description)<.2?"topic_change":null}function ST(e,t){let n=a=>new Set(a.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter(c=>c.length>3)),o=n(e),r=n(t);if(o.size===0&&r.size===0)return 1;if(o.size===0||r.size===0)return 0;let i=new Set([...o].filter(a=>r.has(a))),s=new Set([...o,...r]);return s.size>0?i.size/s.size:0}Pe();var Wn=require("fs"),wg=require("path"),yg=new Map;function Sg(e,t,n){try{if(!(0,Wn.existsSync)(t))return null;let o=(0,wg.relative)(e,t),r=(0,Wn.readFileSync)(t,"utf-8"),s=(0,Wn.statSync)(t).mtimeMs,a=yg.get(t),c=a===void 0;if(yg.set(t,s),!c&&a===s)return null;let l=_T(r);if(c)return{event_type:"plan_created",plan_path:o,plan_summary:l,revision_count:0,session_id:n,timestamp:new Date().toISOString()};let u=TT(t);return{event_type:"plan_revised",plan_path:o,plan_summary:l,revision_count:u,session_id:n,timestamp:new Date().toISOString()}}catch{return null}}function _g(e){let t=typeof e=="string"?e:String(e||"");if(!t)return{passed:!1,issues:["Empty review output"]};let n=t.toUpperCase(),r=["APPROVED","LOOKS GOOD","NO CRITICAL ISSUES","PLAN IS SOLID"].some(c=>n.includes(c)),s=["CRITICAL","REVISE","REJECT","MAJOR ISSUE","MISSING","INCOMPLETE"].some(c=>n.includes(c)),a=vT(t);return r&&!s?{passed:!0,issues:a}:s?{passed:!1,issues:a.length>0?a:["Plan requires revision"]}:{passed:!0,issues:a}}function Ca(e,t,n){let o=e.plan_path.split("/").pop()||e.plan_path,r=t.length,i=e.event_type==="plan_review_failed"?`Plan '${o}' failed review: ${r} issue${r!==1?"s":""}`:`Plan '${o}' failed: ${r} issue${r!==1?"s":""}`,s=t.map(c=>`- ${c}`).join(`
1804
1804
  `).substring(0,500),a=[e.reviewer?`Issues found by ${e.reviewer}:`:"Issues:",s].join(`
1805
- `);return{session_id:e.session_id,project_path:n,category:"planning_insight",summary:i,details:a,agent_name:"prometheus",task_context:`Plan lifecycle: ${e.event_type}`,files_involved:[e.plan_path],confidence:.9,scope:"project"}}function _g(e){if(e.length===0)return"";let t=["<plan-learnings>","## Planning Insights (from previous sessions)",""],n=[],o=[];for(let i of e.slice(0,5))i.summary.includes("failed")?n.push(`- ${i.summary}`):o.push(`- ${i.summary}`);n.length>0&&(t.push("**Common Planning Mistakes:**"),t.push(...n),t.push("")),o.length>0&&(t.push("**Required Considerations:**"),t.push(...o),t.push("")),t.push("</plan-learnings>");let r=t.join(`
1805
+ `);return{session_id:e.session_id,project_path:n,category:"planning_insight",summary:i,details:a,agent_name:"prometheus",task_context:`Plan lifecycle: ${e.event_type}`,files_involved:[e.plan_path],confidence:.9,scope:"project"}}function vg(e){if(e.length===0)return"";let t=["<plan-learnings>","## Planning Insights (from previous sessions)",""],n=[],o=[];for(let i of e.slice(0,5))i.summary.includes("failed")?n.push(`- ${i.summary}`):o.push(`- ${i.summary}`);n.length>0&&(t.push("**Common Planning Mistakes:**"),t.push(...n),t.push("")),o.length>0&&(t.push("**Required Considerations:**"),t.push(...o),t.push("")),t.push("</plan-learnings>");let r=t.join(`
1806
1806
  `);return r.length>1200?r.substring(0,1200)+`
1807
- </plan-learnings>`:r}function wT(e){let t=e;if(t.startsWith("---")){let o=t.indexOf("---",3);o>0&&(t=t.substring(o+3).trim())}return t.replace(/^#+\s*/gm,"").replace(/\n+/g," ").trim().substring(0,200)}function _T(e){let t=[],n=e.split(`
1808
- `);for(let o of n){let r=o.trim();/^[-*]\s+(CRITICAL|ISSUE|PROBLEM|MISSING|BUG|CONCERN):/i.test(r)&&t.push(r.replace(/^[-*]\s+/,"")),/\b(CRITICAL|MAJOR)\s+(ISSUE|PROBLEM|BUG|GAP)/i.test(r)&&r.length<200&&(t.includes(r)||t.push(r))}return t.slice(0,10)}var hg=new Map;function ST(e){let n=(hg.get(e)||0)+1;return hg.set(e,n),n}pt();pt();J();Ee();rs();var Sg=b(require("path"),1);function vg(){_({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(!Fn(e.directory).enabled)return{continue:!0};let o=e.toolInput?.file_path;if(!o)return{continue:!0};let r=o.replace(/\\/g,"/");if(!r.includes(".olympus/plans/")||!r.endsWith(".md"))return{continue:!0};let i=kg(e.directory,o,e.sessionId);if(!i)return{continue:!0};if(i.event_type==="plan_revised"&&i.revision_count&&i.revision_count>=2){let s=Ea(i,[`Plan revised ${i.revision_count} times - may indicate unclear requirements`],e.directory);s.summary&&s.details&&ie({...s,project_path:e.directory,session_id:e.sessionId,category:s.category||"planning_insight",summary:s.summary,details:s.details,agent_name:s.agent_name||"prometheus",confidence:s.confidence||.7,scope:"project"})}}catch(t){console.error("[Olympus Plan Lifecycle] Error in plan file monitor:",t)}return{continue:!0}}}),_({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(!Fn(e.directory).enabled)return{continue:!0};let n=e.toolInput;if(n?.subagent_type!=="momus")return{continue:!0};let r=e.toolOutput,i=typeof r=="string"?r:JSON.stringify(r||""),s=wg(i);if(!s.passed&&s.issues.length>0){if(!s.issues.some(p=>p!=="Plan requires revision"&&p.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",f={event_type:"plan_review_failed",plan_path:u,plan_summary:`Momus review failed with ${s.issues.length} issues`,failure_reasons:s.issues,reviewer:"momus",session_id:e.sessionId,timestamp:new Date().toISOString()},m=Ea(f,s.issues,e.directory);m.summary&&m.details&&ie({...m,project_path:e.directory,session_id:e.sessionId,category:"planning_insight",summary:m.summary,details:m.details,agent_name:"momus",confidence:.9,scope:"project"})}}catch(t){console.error("[Olympus Plan Lifecycle] Error in Momus review tracker:",t)}return{continue:!0}}}),_({name:"completePlanTracker",event:"UserPromptSubmit",priority:115,handler:async e=>{try{if(!e.directory||!e.sessionId)return{continue:!0};if(!Fn(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 s=V(e.directory,e.sessionId);s.pending_completion||(s.pending_completion={claimed_at:new Date().toISOString(),task_description:"plan_completion_verification",agent_used:"complete-plan"},Q(e.directory,s))}catch(t){console.error("[Olympus Plan Lifecycle] Error in complete-plan tracker:",t)}return{continue:!0}}}),_({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 r=rr(e.directory,20).filter(s=>s.category==="planning_insight");if(r.length===0)return{continue:!0};let i=_g(r.slice(0,5));if(i)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:i}}}catch(t){console.error("[Olympus Plan Lifecycle] Error in Prometheus learnings injection:",t)}return{continue:!0}}}),_({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 te(t),o=null,r=null;for(let u of n){let d=await I(t,u);if(d&&d.status!=="complete"&&d.status!=="archived"&&d.status!=="deferred"){o=u,r=d;break}}if(!o||!r)return{continue:!0};let i=Sg.join(t,"aidlc-docs",o,"manifest.json"),s=D(i);if(!s)return{continue:!0};let a=V(t,e.sessionId),c=r.current_phase,l=a.last_tracked_phase;if(l&&l!==c){let u=new Date().toISOString();s.gate_audit.push({phase:c,timestamp:u,action:"approved",actor:"trust",reason:`Phase transition: ${l} -> ${c}`});let d=l;s.phases[d]&&(s.phases[d].status="complete",s.phases[d].completed_at=u),s.phases[c]&&s.phases[c].status==="not_started"&&(s.phases[c].status="in_progress",s.phases[c].started_at=u),F(i,s),os(t,o,r),(r.status==="complete"||r.current_stage==="complete")&&(s.phases.operations.status="complete",s.phases.operations.completed_at=u,F(i,s)),a.last_tracked_phase=c,Q(t,a);let f={discovery:"Discovery",inception:"Inception",construction:"Construction",operations:"Operations"},m=f[l]||l,p=f[c]||c,g=`Phase transition: ${m} \u2192 ${p}`;return c==="operations"&&(g+=`
1807
+ </plan-learnings>`:r}function _T(e){let t=e;if(t.startsWith("---")){let o=t.indexOf("---",3);o>0&&(t=t.substring(o+3).trim())}return t.replace(/^#+\s*/gm,"").replace(/\n+/g," ").trim().substring(0,200)}function vT(e){let t=[],n=e.split(`
1808
+ `);for(let o of n){let r=o.trim();/^[-*]\s+(CRITICAL|ISSUE|PROBLEM|MISSING|BUG|CONCERN):/i.test(r)&&t.push(r.replace(/^[-*]\s+/,"")),/\b(CRITICAL|MAJOR)\s+(ISSUE|PROBLEM|BUG|GAP)/i.test(r)&&r.length<200&&(t.includes(r)||t.push(r))}return t.slice(0,10)}var kg=new Map;function TT(e){let n=(kg.get(e)||0)+1;return kg.set(e,n),n}pt();pt();J();Ee();is();var Tg=b(require("path"),1);function Eg(){S({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(!Fn(e.directory).enabled)return{continue:!0};let o=e.toolInput?.file_path;if(!o)return{continue:!0};let r=o.replace(/\\/g,"/");if(!r.includes(".olympus/plans/")||!r.endsWith(".md"))return{continue:!0};let i=Sg(e.directory,o,e.sessionId);if(!i)return{continue:!0};if(i.event_type==="plan_revised"&&i.revision_count&&i.revision_count>=2){let s=Ca(i,[`Plan revised ${i.revision_count} times - may indicate unclear requirements`],e.directory);s.summary&&s.details&&ie({...s,project_path:e.directory,session_id:e.sessionId,category:s.category||"planning_insight",summary:s.summary,details:s.details,agent_name:s.agent_name||"prometheus",confidence:s.confidence||.7,scope:"project"})}}catch(t){console.error("[Olympus Plan Lifecycle] Error in plan file monitor:",t)}return{continue:!0}}}),S({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(!Fn(e.directory).enabled)return{continue:!0};let n=e.toolInput;if(n?.subagent_type!=="momus")return{continue:!0};let r=e.toolOutput,i=typeof r=="string"?r:JSON.stringify(r||""),s=_g(i);if(!s.passed&&s.issues.length>0){if(!s.issues.some(p=>p!=="Plan requires revision"&&p.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",f={event_type:"plan_review_failed",plan_path:u,plan_summary:`Momus review failed with ${s.issues.length} issues`,failure_reasons:s.issues,reviewer:"momus",session_id:e.sessionId,timestamp:new Date().toISOString()},m=Ca(f,s.issues,e.directory);m.summary&&m.details&&ie({...m,project_path:e.directory,session_id:e.sessionId,category:"planning_insight",summary:m.summary,details:m.details,agent_name:"momus",confidence:.9,scope:"project"})}}catch(t){console.error("[Olympus Plan Lifecycle] Error in Momus review tracker:",t)}return{continue:!0}}}),S({name:"completePlanTracker",event:"UserPromptSubmit",priority:115,handler:async e=>{try{if(!e.directory||!e.sessionId)return{continue:!0};if(!Fn(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 s=V(e.directory,e.sessionId);s.pending_completion||(s.pending_completion={claimed_at:new Date().toISOString(),task_description:"plan_completion_verification",agent_used:"complete-plan"},Q(e.directory,s))}catch(t){console.error("[Olympus Plan Lifecycle] Error in complete-plan tracker:",t)}return{continue:!0}}}),S({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 r=ir(e.directory,20).filter(s=>s.category==="planning_insight");if(r.length===0)return{continue:!0};let i=vg(r.slice(0,5));if(i)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:i}}}catch(t){console.error("[Olympus Plan Lifecycle] Error in Prometheus learnings injection:",t)}return{continue:!0}}}),S({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 te(t),o=null,r=null;for(let u of n){let d=await C(t,u);if(d&&d.status!=="complete"&&d.status!=="archived"&&d.status!=="deferred"){o=u,r=d;break}}if(!o||!r)return{continue:!0};let i=Tg.join(t,"aidlc-docs",o,"manifest.json"),s=D(i);if(!s)return{continue:!0};let a=V(t,e.sessionId),c=r.current_phase,l=a.last_tracked_phase;if(l&&l!==c){let u=new Date().toISOString();s.gate_audit.push({phase:c,timestamp:u,action:"approved",actor:"trust",reason:`Phase transition: ${l} -> ${c}`});let d=l;s.phases[d]&&(s.phases[d].status="complete",s.phases[d].completed_at=u),s.phases[c]&&s.phases[c].status==="not_started"&&(s.phases[c].status="in_progress",s.phases[c].started_at=u),F(i,s),rs(t,o,r),(r.status==="complete"||r.current_stage==="complete")&&(s.phases.operations.status="complete",s.phases.operations.completed_at=u,F(i,s)),a.last_tracked_phase=c,Q(t,a);let f={discovery:"Discovery",inception:"Inception",construction:"Construction",operations:"Operations"},m=f[l]||l,p=f[c]||c,g=`Phase transition: ${m} \u2192 ${p}`;return c==="operations"&&(g+=`
1809
1809
  \u2192 Generating deployment artifacts...`),{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`<phase-transition>
1810
1810
  ${g}
1811
- </phase-transition>`}}}if(l||(a.last_tracked_phase=c,Q(t,a)),r.status==="complete"&&s.phases.operations.status!=="complete"){let u=new Date().toISOString();return s.phases.operations.status="complete",s.phases.operations.completed_at=u,F(i,s),os(t,o,r),{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`<phase-transition>
1811
+ </phase-transition>`}}}if(l||(a.last_tracked_phase=c,Q(t,a)),r.status==="complete"&&s.phases.operations.status!=="complete"){let u=new Date().toISOString();return s.phases.operations.status="complete",s.phases.operations.completed_at=u,F(i,s),rs(t,o,r),{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`<phase-transition>
1812
1812
  \u2713 Workflow complete! All phases finished.
1813
- </phase-transition>`}}}}catch(t){console.error("[Olympus Plan Lifecycle] Error in phase transition tracker:",t)}return{continue:!0}}})}Ee();J();$t();Ko();function ba(e,t){return t===3||e<=1?"blocking":"auto-advance"}function Ca(e,t){return t===3||e<=1?"blocking":e===2?"summary-review":"notification-only"}function Ia(e,t){let n=e.links.find(o=>o.target_id===t&&o.link_type==="derives");return n?n.source_id:null}function Tg(e,t){let n=e.artifacts.filter(r=>r.stage==="unit"),o=e.risk_tier?.tier??null;return n.map(r=>{let i=e.links.filter(c=>c.source_id===r.id&&c.link_type==="derives").map(c=>e.artifacts.find(l=>l.id===c.target_id)).filter(c=>c!==void 0),s=i.length>0?`
1813
+ </phase-transition>`}}}}catch(t){console.error("[Olympus Plan Lifecycle] Error in phase transition tracker:",t)}return{continue:!0}}})}Ee();J();$t();Jo();function Ia(e,t){return t===3||e<=1?"blocking":"auto-advance"}function Ra(e,t){return t===3||e<=1?"blocking":e===2?"summary-review":"notification-only"}function Oa(e,t){let n=e.links.find(o=>o.target_id===t&&o.link_type==="derives");return n?n.source_id:null}function bg(e,t){let n=e.artifacts.filter(r=>r.stage==="unit"),o=e.risk_tier?.tier??null;return n.map(r=>{let i=e.links.filter(c=>c.source_id===r.id&&c.link_type==="derives").map(c=>e.artifacts.find(l=>l.id===c.target_id)).filter(c=>c!==void 0),s=i.length>0?`
1814
1814
 
1815
1815
  Child BOLTs:
1816
1816
  ${i.map(c=>` - ${c.id} (${c.path})`).join(`
@@ -1819,7 +1819,7 @@ ${i.map(c=>` - ${c.id} (${c.path})`).join(`
1819
1819
  No child BOLTs found.`,a=`UNIT Artifact: ${r.path}
1820
1820
  Contract Status: ${r.contract_status}${s}`;return o===3&&(a+=`
1821
1821
 
1822
- NOTE: Risk Tier 3 - Momus review mandatory for architecture decisions.`),{gateNumber:3,gateType:"architecture-review",artifactId:r.id,summary:`Architecture review for ${r.id}`,reviewContent:a,trustLevel:t,trustBehavior:ba(t,o)}})}function Eg(e,t,n,o){let r=e.artifacts.find(c=>c.id===t);if(!r)throw new Error(`BOLT artifact not found: ${t}`);let i=Ca(n,o),s="";n<=1?s=`
1822
+ NOTE: Risk Tier 3 - Momus review mandatory for architecture decisions.`),{gateNumber:3,gateType:"architecture-review",artifactId:r.id,summary:`Architecture review for ${r.id}`,reviewContent:a,trustLevel:t,trustBehavior:Ia(t,o)}})}function Cg(e,t,n,o){let r=e.artifacts.find(c=>c.id===t);if(!r)throw new Error(`BOLT artifact not found: ${t}`);let i=Ra(n,o),s="";n<=1?s=`
1823
1823
 
1824
1824
  Review Instructions: Full code review required.`:n===2?s=`
1825
1825
 
@@ -1828,7 +1828,7 @@ Review Instructions: Summary review - verify major changes only.`:s=`
1828
1828
  Review Instructions: Notification only - AI proceeds automatically.`;let a=`BOLT Spec: ${r.path}
1829
1829
  Contract Status: ${r.contract_status}${s}`;return o===3&&(a+=`
1830
1830
 
1831
- 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:i}}function bg(e,t){let n=e.artifacts.length,o=e.artifacts.filter(c=>c.stage==="code-generation"),r=e.gate_audit.filter(c=>c.action==="approved").length,i=e.gate_audit.filter(c=>c.action==="rejected").length,s=o.length>0?o.map(c=>` - ${c.id}: ${c.contract_status}`).join(`
1831
+ 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:i}}function Ig(e,t){let n=e.artifacts.length,o=e.artifacts.filter(c=>c.stage==="code-generation"),r=e.gate_audit.filter(c=>c.action==="approved").length,i=e.gate_audit.filter(c=>c.action==="rejected").length,s=o.length>0?o.map(c=>` - ${c.id}: ${c.contract_status}`).join(`
1832
1832
  `):" No BOLTs found.",a=`Release Approval Review
1833
1833
 
1834
1834
  Feature: ${e.feature_name}
@@ -1841,7 +1841,7 @@ Gate Audit Summary:
1841
1841
  BOLT Artifacts:
1842
1842
  ${s}
1843
1843
 
1844
- 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 Lt=b(ue(),1),Gr=require("path");function Ra(e,t,n){Lt.ensureDirSync((0,Gr.dirname)(e));let o="";Lt.existsSync(e)?o=Lt.readFileSync(e,"utf-8"):o=`# Validation Report: ${t}
1844
+ 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 Lt=b(ue(),1),Gr=require("path");function Aa(e,t,n){Lt.ensureDirSync((0,Gr.dirname)(e));let o="";Lt.existsSync(e)?o=Lt.readFileSync(e,"utf-8"):o=`# Validation Report: ${t}
1845
1845
 
1846
1846
  `;let r=n.commandsExecuted.length>0?n.commandsExecuted.map(d=>`- \`${d.command}\` -> exit ${d.exitCode} (${d.result})`).join(`
1847
1847
  `):"- No commands recorded",i=`| Suite | Pass | Fail | Skip |
@@ -1868,16 +1868,16 @@ ${a}
1868
1868
 
1869
1869
  ---
1870
1870
 
1871
- `,u=o+l;Lt.writeFileSync(e,u,"utf-8")}function Oa(e,t,n){return(0,Gr.join)(e,"aidlc-docs",t,"construction",n,"validation-report.md")}function vT(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 Cg(e,t,n,o=5){try{let r=n.attemptNumber>=o,i=vT(n.gateNumber),s;switch(n.gateNumber){case 1:s=`Revise the INTENT based on this feedback: ${n.rejectionReason}`;break;case 2:s=`Update the INTENT based on this feedback: ${n.rejectionReason}`;break;case 3:s=`Regenerate UNITs based on this feedback: ${n.rejectionReason}`;break;case 4:s=`Re-implement this BOLT based on this feedback: ${n.rejectionReason}`;break;case 5:s=`Revise operations artifacts based on this feedback: ${n.rejectionReason}`;break;default:s=`Address this feedback: ${n.rejectionReason}`}let a=r?`Maximum revision attempts reached for ${n.artifactId}. Consider manual intervention or scope change.`:`${s}
1871
+ `,u=o+l;Lt.writeFileSync(e,u,"utf-8")}function Pa(e,t,n){return(0,Gr.join)(e,"aidlc-docs",t,"construction",n,"validation-report.md")}function ET(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 Rg(e,t,n,o=5){try{let r=n.attemptNumber>=o,i=ET(n.gateNumber),s;switch(n.gateNumber){case 1:s=`Revise the INTENT based on this feedback: ${n.rejectionReason}`;break;case 2:s=`Update the INTENT based on this feedback: ${n.rejectionReason}`;break;case 3:s=`Regenerate UNITs based on this feedback: ${n.rejectionReason}`;break;case 4:s=`Re-implement this BOLT based on this feedback: ${n.rejectionReason}`;break;case 5:s=`Revise operations artifacts based on this feedback: ${n.rejectionReason}`;break;default:s=`Address this feedback: ${n.rejectionReason}`}let a=r?`Maximum revision attempts reached for ${n.artifactId}. Consider manual intervention or scope change.`:`${s}
1872
1872
 
1873
1873
  Artifact ID: ${n.artifactId}
1874
1874
  Workflow ID: ${t}
1875
1875
  Attempt Number: ${n.attemptNumber}
1876
1876
  Rejected By: ${n.rejectedBy}
1877
1877
 
1878
- Please revise the artifact to address the feedback above and re-submit for approval.`;return{agentType:i,prompt:a,maxRetriesReached:r,contractStatusUpdate:{from:"violated",to:"draft"}}}catch(r){throw console.error("Error in dispatchRejection:",r),r}}pt();var qr=b(ue(),1),Ke=require("path"),Gn=require("fs"),Hn={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 Br(e){try{let t=await te(e);if(t.length===0)return null;let n=null;for(let o of t){let r=await I(e,o);if(!r||r.status==="complete")continue;let i=r.manifest_path||(0,Ke.join)(e,".olympus","workflow",o,"manifest.json");(!n||r.updated_at>n.updatedAt)&&(n={workflowId:o,checkpoint:r,manifestPath:i,updatedAt:r.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 TT(e,t){let n=e.current_phase;if(!n)return e.current_stage==="intent"||e.current_stage==="complete"?"inception":null;if(t){let o=t.phases[n];if(o&&o.status==="in_progress"&&(!o.gate_result||o.gate_result&&!o.gate_result.passed&&o.gate_result.approved_by===null))return o.gate_result&&o.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 ET(e){try{let t=(0,Ke.join)(e,".olympus","config.json");if(qr.existsSync(t)){let n=qr.readJsonSync(t);if(n?.workflow?.qualityGates?.enabled===!1||n?.hooks?.qualityGate?.enabled===!1)return!0}}catch{}return!1}function Aa(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 bT(e,t){return e==="inception"?t==="intent"?2:1:e==="construction"?t==="code-generation"?4:3:e==="operations"?5:1}function CT(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 IT(e){try{if(e.toolName!=="Task")return{continue:!0};if(!e.directory||!e.sessionId)return{continue:!0};let t=await Br(e.directory);if(!t)return{continue:!0};let{workflowId:n,checkpoint:o,manifestPath:r}=t,i=D(r);if(!i)return console.error("[Olympus Quality Gate] Manifest corrupted or missing - failing open"),{continue:!0};let s=TT(o,i);if(!s)return{continue:!0};let a=we(e.directory),c=(typeof o.risk_tier=="number"?o.risk_tier:o.risk_tier?.tier)||i.risk_tier?.tier||2;if(c===3&&s==="inception"&&!i.artifacts.some(y=>y.type?.toLowerCase().includes("momus")||y.type?.toLowerCase()==="momus-review"))return i.phases[s].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}},F(r,i),await $(e.directory,o),{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`[BLOCKING - Acknowledgment Required] BLOCKED: Risk Tier 3 requires Momus review before INTENT approval. Run /review to invoke Momus.
1878
+ Please revise the artifact to address the feedback above and re-submit for approval.`;return{agentType:i,prompt:a,maxRetriesReached:r,contractStatusUpdate:{from:"violated",to:"draft"}}}catch(r){throw console.error("Error in dispatchRejection:",r),r}}pt();var qr=b(ue(),1),Ke=require("path"),Gn=require("fs"),Hn={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 Br(e){try{let t=await te(e);if(t.length===0)return null;let n=null;for(let o of t){let r=await C(e,o);if(!r||r.status==="complete")continue;let i=r.manifest_path||(0,Ke.join)(e,".olympus","workflow",o,"manifest.json");(!n||r.updated_at>n.updatedAt)&&(n={workflowId:o,checkpoint:r,manifestPath:i,updatedAt:r.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 bT(e,t){let n=e.current_phase;if(!n)return e.current_stage==="intent"||e.current_stage==="complete"?"inception":null;if(t){let o=t.phases[n];if(o&&o.status==="in_progress"&&(!o.gate_result||o.gate_result&&!o.gate_result.passed&&o.gate_result.approved_by===null))return o.gate_result&&o.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 CT(e){try{let t=(0,Ke.join)(e,".olympus","config.json");if(qr.existsSync(t)){let n=qr.readJsonSync(t);if(n?.workflow?.qualityGates?.enabled===!1||n?.hooks?.qualityGate?.enabled===!1)return!0}}catch{}return!1}function xa(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 IT(e,t){return e==="inception"?t==="intent"?2:1:e==="construction"?t==="code-generation"?4:3:e==="operations"?5:1}function RT(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 OT(e){try{if(e.toolName!=="Task")return{continue:!0};if(!e.directory||!e.sessionId)return{continue:!0};let t=await Br(e.directory);if(!t)return{continue:!0};let{workflowId:n,checkpoint:o,manifestPath:r}=t,i=D(r);if(!i)return console.error("[Olympus Quality Gate] Manifest corrupted or missing - failing open"),{continue:!0};let s=bT(o,i);if(!s)return{continue:!0};let a=we(e.directory),c=(typeof o.risk_tier=="number"?o.risk_tier:o.risk_tier?.tier)||i.risk_tier?.tier||2;if(c===3&&s==="inception"&&!i.artifacts.some(y=>y.type?.toLowerCase().includes("momus")||y.type?.toLowerCase()==="momus-review"))return i.phases[s].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}},F(r,i),await $(e.directory,o),{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`[BLOCKING - Acknowledgment Required] BLOCKED: Risk Tier 3 requires Momus review before INTENT approval. Run /review to invoke Momus.
1879
1879
 
1880
- [GATE_PENDING]`}};if(s==="construction"&&o.current_stage==="unit"){if(ba(a.current_level,c)==="auto-advance"&&c!==3){Ce(r,{phase:"construction",action:"approved",actor:"trust",reason:`Gate 3 auto-advanced by Trust Level ${a.current_level} for Tier ${c}`});let Z=new Date().toISOString();i.phases.construction.gate_result={passed:!0,approved_by:"trust",approved_at:Z,feedback:null,verification:{conformance_score:100,coverage_percentage:100,missing_items:[],passed:!0},validation:{alignment_score:100,alignment_questions:[],passed:!0}};for(let S of i.artifacts)S.stage==="unit"&&(S.reviewedBy="auto-approved");F(r,i),await $(e.directory,o);try{let S={type:"gate_approval",phase:"construction",stage:"unit",details:`Gate 3 auto-advanced by Trust Level ${a.current_level} for Tier ${c}`},O={workflowId:n,featureName:o.feature_name||n,projectPath:e.directory,sessionId:e.sessionId||"unknown",phase:"construction"},x=xe(S,O);ie(x)}catch(S){console.error("[Olympus Quality Gate] Failed to capture Gate 3 auto-advance discovery:",S)}return{continue:!0}}let y;try{let Z=(0,Ke.join)(e.directory,"aidlc-docs",n,"inception"),S=(0,Gn.readFileSync)((0,Ke.join)(Z,"intent.md"),"utf-8"),O=i.artifacts.filter(M=>M.stage==="unit"),x=O.length>0?(0,Gn.readFileSync)((0,Ke.join)(e.directory,O[0].path),"utf-8"):"",P=gn(x,S,S,"intent-to-unit","unit-to-intent","intent",O[0]?.id||"unit","intent");y={conformance_score:P.parentCheck.verification.conformance_score,coverage_percentage:P.parentCheck.verification.coverage_percentage,missing_items:P.parentCheck.verification.missing_items,passed:P.passed}}catch{y={conformance_score:0,coverage_percentage:0,missing_items:["Could not read construction artifacts for alignment check"],passed:!1}}let w=Hn.gate3||[],k={alignment_score:0,alignment_questions:w,passed:!1},v=Tg(i,a.current_level).map(Z=>Z.reviewContent).join(`
1880
+ [GATE_PENDING]`}};if(s==="construction"&&o.current_stage==="unit"){if(Ia(a.current_level,c)==="auto-advance"&&c!==3){Ce(r,{phase:"construction",action:"approved",actor:"trust",reason:`Gate 3 auto-advanced by Trust Level ${a.current_level} for Tier ${c}`});let Z=new Date().toISOString();i.phases.construction.gate_result={passed:!0,approved_by:"trust",approved_at:Z,feedback:null,verification:{conformance_score:100,coverage_percentage:100,missing_items:[],passed:!0},validation:{alignment_score:100,alignment_questions:[],passed:!0}};for(let _ of i.artifacts)_.stage==="unit"&&(_.reviewedBy="auto-approved");F(r,i),await $(e.directory,o);try{let _={type:"gate_approval",phase:"construction",stage:"unit",details:`Gate 3 auto-advanced by Trust Level ${a.current_level} for Tier ${c}`},O={workflowId:n,featureName:o.feature_name||n,projectPath:e.directory,sessionId:e.sessionId||"unknown",phase:"construction"},x=$e(_,O);ie(x)}catch(_){console.error("[Olympus Quality Gate] Failed to capture Gate 3 auto-advance discovery:",_)}return{continue:!0}}let y;try{let Z=(0,Ke.join)(e.directory,"aidlc-docs",n,"inception"),_=(0,Gn.readFileSync)((0,Ke.join)(Z,"intent.md"),"utf-8"),O=i.artifacts.filter(M=>M.stage==="unit"),x=O.length>0?(0,Gn.readFileSync)((0,Ke.join)(e.directory,O[0].path),"utf-8"):"",P=gn(x,_,_,"intent-to-unit","unit-to-intent","intent",O[0]?.id||"unit","intent");y={conformance_score:P.parentCheck.verification.conformance_score,coverage_percentage:P.parentCheck.verification.coverage_percentage,missing_items:P.parentCheck.verification.missing_items,passed:P.passed}}catch{y={conformance_score:0,coverage_percentage:0,missing_items:["Could not read construction artifacts for alignment check"],passed:!1}}let w=Hn.gate3||[],k={alignment_score:0,alignment_questions:w,passed:!1},v=bg(i,a.current_level).map(Z=>Z.reviewContent).join(`
1881
1881
 
1882
1882
  `);return i.phases.construction.gate_result={passed:!1,approved_by:null,approved_at:null,feedback:null,verification:y,validation:k},Ce(r,{phase:"construction",action:"approved",actor:"trust",reason:"Gate 3 pending review"}),F(r,i),await $(e.directory,o),{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`${c===3?"[BLOCKING - Acknowledgment Required] ":""}STOP: Gate 3 (UNIT decomposition review) requires approval.
1883
1883
 
@@ -1887,12 +1887,12 @@ VERIFICATION: ${y.conformance_score}% conformance, ${y.coverage_percentage}% cov
1887
1887
  Missing: ${y.missing_items.join(", ")}
1888
1888
 
1889
1889
  VALIDATION: Review alignment questions:
1890
- ${w.map((Z,S)=>`${S+1}. ${Z.question}`).join(`
1890
+ ${w.map((Z,_)=>`${_+1}. ${Z.question}`).join(`
1891
1891
  `)}
1892
1892
 
1893
1893
  Type "approve" to proceed or "reject <reason>" to block.
1894
1894
 
1895
- [GATE_PENDING]`}}}if(s==="construction"&&o.current_stage==="code-generation"&&o.active_code_plan_path){let h=o.active_code_plan_path,y=Ca(a.current_level,c),w;try{let S=(0,Ke.join)(e.directory,"aidlc-docs",n,"inception"),O=(0,Gn.readFileSync)((0,Ke.join)(S,"intent.md"),"utf-8"),x=i.artifacts.find(E=>E.id===h),P=x?(0,Gn.readFileSync)((0,Ke.join)(e.directory,x.path),"utf-8"):"",M=gn(P,O,O,"unit-to-bolt","bolt-to-intent","intent",h,"intent");w={conformance_score:M.parentCheck.verification.conformance_score,coverage_percentage:M.parentCheck.verification.coverage_percentage,missing_items:M.parentCheck.verification.missing_items,passed:M.passed}}catch{w={conformance_score:0,coverage_percentage:0,missing_items:["Could not read BOLT artifacts for alignment check"],passed:!1}}let k=Hn.gate4||[],A={alignment_score:0,alignment_questions:k,passed:!1};if(y==="notification-only"&&c!==3){Ce(r,{phase:"construction",action:"approved",actor:"trust",reason:`Gate 4 notification-only for BOLT ${h} at Trust Level ${a.current_level}`});let S=new Date().toISOString();i.phases.construction.gate_result={passed:!0,approved_by:"trust",approved_at:S,feedback:null,verification:w,validation:A};let O=i.artifacts.find(P=>P.id===h);O&&(O.reviewedBy="auto-approved"),tt(r,h,"fulfilled");try{let P=Ia(i,h);if(P&&e.directory){let M=Oa(e.directory,n,P);Ra(M,P,{boltId:h,boltTitle:O?.type||"auto-approved",commandsExecuted:[],testResults:[],filesChanged:[],gateApprovedBy:"auto-approved",dualValidation:{parentConformance:w.conformance_score,rootConformance:0},riskTier:c})}}catch(P){console.error("[Olympus Quality Gate] Failed to generate validation report:",P)}F(r,i),await $(e.directory,o);try{let P={type:"gate_approval",phase:"construction",stage:"code-generation",details:`Gate 4 notification-only for BOLT ${h} at Trust Level ${a.current_level}`,artifactId:h},M={workflowId:n,featureName:o.feature_name||n,projectPath:e.directory,sessionId:e.sessionId||"unknown",phase:"construction"},E=xe(P,M);ie(E)}catch(P){console.error("[Olympus Quality Gate] Failed to capture Gate 4 auto-advance discovery:",P)}let x="";try{let{isWorkflowComplete:P}=await Promise.resolve().then(()=>(J(),Vt)),M=D(r);M&&P(M)&&(o.current_phase="operations",o.current_stage="code-generation",ut(r,"construction","complete"),ut(r,"operations","in_progress"),await $(e.directory,o),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(P){console.error("[Olympus Quality Gate] Failed to check workflow completion:",P)}return{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`Gate 4 (BOLT ${h} review): Auto-approved at Trust Level ${a.current_level}. Notification only.${x}`}}}let v;try{v=Eg(i,h,a.current_level,c)}catch{return{continue:!0}}return i.phases.construction.gate_result={passed:!1,approved_by:null,approved_at:null,feedback:null,verification:w,validation:A},Ce(r,{phase:"construction",action:"approved",actor:"trust",reason:`Gate 4 pending review for BOLT ${h}`}),F(r,i),await $(e.directory,o),{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`${c===3?"[BLOCKING - Acknowledgment Required] ":""}STOP: Gate 4 (BOLT ${h} review)${y==="summary-review"?" (Summary Review)":""} requires approval.
1895
+ [GATE_PENDING]`}}}if(s==="construction"&&o.current_stage==="code-generation"&&o.active_code_plan_path){let h=o.active_code_plan_path,y=Ra(a.current_level,c),w;try{let _=(0,Ke.join)(e.directory,"aidlc-docs",n,"inception"),O=(0,Gn.readFileSync)((0,Ke.join)(_,"intent.md"),"utf-8"),x=i.artifacts.find(E=>E.id===h),P=x?(0,Gn.readFileSync)((0,Ke.join)(e.directory,x.path),"utf-8"):"",M=gn(P,O,O,"unit-to-bolt","bolt-to-intent","intent",h,"intent");w={conformance_score:M.parentCheck.verification.conformance_score,coverage_percentage:M.parentCheck.verification.coverage_percentage,missing_items:M.parentCheck.verification.missing_items,passed:M.passed}}catch{w={conformance_score:0,coverage_percentage:0,missing_items:["Could not read BOLT artifacts for alignment check"],passed:!1}}let k=Hn.gate4||[],A={alignment_score:0,alignment_questions:k,passed:!1};if(y==="notification-only"&&c!==3){Ce(r,{phase:"construction",action:"approved",actor:"trust",reason:`Gate 4 notification-only for BOLT ${h} at Trust Level ${a.current_level}`});let _=new Date().toISOString();i.phases.construction.gate_result={passed:!0,approved_by:"trust",approved_at:_,feedback:null,verification:w,validation:A};let O=i.artifacts.find(P=>P.id===h);O&&(O.reviewedBy="auto-approved"),tt(r,h,"fulfilled");try{let P=Oa(i,h);if(P&&e.directory){let M=Pa(e.directory,n,P);Aa(M,P,{boltId:h,boltTitle:O?.type||"auto-approved",commandsExecuted:[],testResults:[],filesChanged:[],gateApprovedBy:"auto-approved",dualValidation:{parentConformance:w.conformance_score,rootConformance:0},riskTier:c})}}catch(P){console.error("[Olympus Quality Gate] Failed to generate validation report:",P)}F(r,i),await $(e.directory,o);try{let P={type:"gate_approval",phase:"construction",stage:"code-generation",details:`Gate 4 notification-only for BOLT ${h} at Trust Level ${a.current_level}`,artifactId:h},M={workflowId:n,featureName:o.feature_name||n,projectPath:e.directory,sessionId:e.sessionId||"unknown",phase:"construction"},E=$e(P,M);ie(E)}catch(P){console.error("[Olympus Quality Gate] Failed to capture Gate 4 auto-advance discovery:",P)}let x="";try{let{isWorkflowComplete:P}=await Promise.resolve().then(()=>(J(),Vt)),M=D(r);M&&P(M)&&(o.current_phase="operations",o.current_stage="code-generation",ut(r,"construction","complete"),ut(r,"operations","in_progress"),await $(e.directory,o),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(P){console.error("[Olympus Quality Gate] Failed to check workflow completion:",P)}return{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`Gate 4 (BOLT ${h} review): Auto-approved at Trust Level ${a.current_level}. Notification only.${x}`}}}let v;try{v=Cg(i,h,a.current_level,c)}catch{return{continue:!0}}return i.phases.construction.gate_result={passed:!1,approved_by:null,approved_at:null,feedback:null,verification:w,validation:A},Ce(r,{phase:"construction",action:"approved",actor:"trust",reason:`Gate 4 pending review for BOLT ${h}`}),F(r,i),await $(e.directory,o),{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`${c===3?"[BLOCKING - Acknowledgment Required] ":""}STOP: Gate 4 (BOLT ${h} review)${y==="summary-review"?" (Summary Review)":""} requires approval.
1896
1896
 
1897
1897
  ${v.reviewContent}
1898
1898
 
@@ -1900,12 +1900,12 @@ VERIFICATION: ${w.conformance_score}% conformance, ${w.coverage_percentage}% cov
1900
1900
  Missing: ${w.missing_items.join(", ")}
1901
1901
 
1902
1902
  VALIDATION: Review alignment questions:
1903
- ${k.map((S,O)=>`${O+1}. ${S.question}`).join(`
1903
+ ${k.map((_,O)=>`${O+1}. ${_.question}`).join(`
1904
1904
  `)}
1905
1905
 
1906
1906
  Type "approve" to proceed or "reject <reason>" to block.
1907
1907
 
1908
- [GATE_PENDING]`}}}if(s==="operations"){let h;try{h=bg(i,a.current_level)}catch{return{continue:!0}}let y=Hn.operations||[],w={conformance_score:0,coverage_percentage:0,missing_items:["Release review pending"],passed:!1},k={alignment_score:0,alignment_questions:y,passed:!1};return i.phases.operations.gate_result={passed:!1,approved_by:null,approved_at:null,feedback:null,verification:w,validation:k},F(r,i),await $(e.directory,o),{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`[BLOCKING - Acknowledgment Required] STOP: Gate 5 (Release review) requires approval.
1908
+ [GATE_PENDING]`}}}if(s==="operations"){let h;try{h=Ig(i,a.current_level)}catch{return{continue:!0}}let y=Hn.operations||[],w={conformance_score:0,coverage_percentage:0,missing_items:["Release review pending"],passed:!1},k={alignment_score:0,alignment_questions:y,passed:!1};return i.phases.operations.gate_result={passed:!1,approved_by:null,approved_at:null,feedback:null,verification:w,validation:k},F(r,i),await $(e.directory,o),{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`[BLOCKING - Acknowledgment Required] STOP: Gate 5 (Release review) requires approval.
1909
1909
 
1910
1910
  ${h.reviewContent}
1911
1911
 
@@ -1915,7 +1915,7 @@ ${y.map((v,R)=>`${R+1}. ${v.question}`).join(`
1915
1915
 
1916
1916
  Type "approve" to proceed or "reject <reason>" to block.
1917
1917
 
1918
- [GATE_PENDING]`}}}if(Kd(c,a.current_level)){Ce(r,{phase:s,action:"approved",actor:"trust",reason:`Auto-advanced by Trust Level ${a.current_level} for Tier ${c}`});let h=new Date().toISOString();i.phases[s].gate_result={passed:!0,approved_by:"trust",approved_at:h,feedback:null,verification:{conformance_score:100,coverage_percentage:100,missing_items:[],passed:!0},validation:{alignment_score:100,alignment_questions:[],passed:!0}},F(r,i),await $(e.directory,o);try{let y={type:"gate_approval",phase:s,stage:o.current_stage,details:`Auto-advanced by Trust Level ${a.current_level} for Tier ${c}`},w={workflowId:n,featureName:o.feature_name||n,projectPath:e.directory,sessionId:e.sessionId||"unknown",phase:s},k=xe(y,w);ie(k)}catch(y){console.error("[Olympus Quality Gate] Failed to capture auto-advance discovery:",y)}return{continue:!0}}let l,u;if(s==="inception")try{let h=(0,Ke.join)(e.directory,"aidlc-docs",n,"inception"),y=(0,Gn.readFileSync)((0,Ke.join)(h,"intent.md"),"utf-8");l=Yo(y,y,"intent-to-unit"),u=Hn[s]||[]}catch{l={conformance_score:0,coverage_percentage:0,missing_items:["Could not read inception artifacts for alignment check"],passed:!1},u=Hn[s]||[]}else l={conformance_score:0,coverage_percentage:0,missing_items:["Alignment check not yet implemented for this phase"],passed:!1},u=Hn[s]||[];let d={alignment_score:0,alignment_questions:u,passed:!1},f="";if(s==="inception"){let h=o.depth_score||i.depth_assessment?.total_score;h&&h>=21&&(i.artifacts.some(w=>w.type?.toLowerCase().includes("metis"))||(f=`
1918
+ [GATE_PENDING]`}}}if(zd(c,a.current_level)){Ce(r,{phase:s,action:"approved",actor:"trust",reason:`Auto-advanced by Trust Level ${a.current_level} for Tier ${c}`});let h=new Date().toISOString();i.phases[s].gate_result={passed:!0,approved_by:"trust",approved_at:h,feedback:null,verification:{conformance_score:100,coverage_percentage:100,missing_items:[],passed:!0},validation:{alignment_score:100,alignment_questions:[],passed:!0}},F(r,i),await $(e.directory,o);try{let y={type:"gate_approval",phase:s,stage:o.current_stage,details:`Auto-advanced by Trust Level ${a.current_level} for Tier ${c}`},w={workflowId:n,featureName:o.feature_name||n,projectPath:e.directory,sessionId:e.sessionId||"unknown",phase:s},k=$e(y,w);ie(k)}catch(y){console.error("[Olympus Quality Gate] Failed to capture auto-advance discovery:",y)}return{continue:!0}}let l,u;if(s==="inception")try{let h=(0,Ke.join)(e.directory,"aidlc-docs",n,"inception"),y=(0,Gn.readFileSync)((0,Ke.join)(h,"intent.md"),"utf-8");l=Ko(y,y,"intent-to-unit"),u=Hn[s]||[]}catch{l={conformance_score:0,coverage_percentage:0,missing_items:["Could not read inception artifacts for alignment check"],passed:!1},u=Hn[s]||[]}else l={conformance_score:0,coverage_percentage:0,missing_items:["Alignment check not yet implemented for this phase"],passed:!1},u=Hn[s]||[];let d={alignment_score:0,alignment_questions:u,passed:!1},f="";if(s==="inception"){let h=o.depth_score||i.depth_assessment?.total_score;h&&h>=21&&(i.artifacts.some(w=>w.type?.toLowerCase().includes("metis"))||(f=`
1919
1919
 
1920
1920
  WARNING: DEEP workflow without Metis consultation detected. Metis blind-spot analysis is strongly recommended for complex workflows.`))}i.phases[s].gate_result={passed:!1,approved_by:null,approved_at:null,feedback:null,verification:l,validation:d},F(r,i),await $(e.directory,o);let m=c===3?"[BLOCKING - Acknowledgment Required] ":"",p=o.current_stage==="intent"?"Gate 1 (INTENT review)":o.current_stage==="complete"?"Gate 2 (INTENT review)":`${s} transition`;return{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`${m}STOP: ${p} requires approval.
1921
1921
 
@@ -1928,10 +1928,10 @@ ${u.map((h,y)=>`${y+1}. ${h.question}`).join(`
1928
1928
 
1929
1929
  Type "approve" to proceed or "reject <reason>" to block.${f}
1930
1930
 
1931
- [GATE_PENDING]`}}}catch(t){return console.error("[Olympus Quality Gate] Error in qualityGateBlocker:",t),{continue:!0}}}async function RT(e){try{let t=CT(e);if(!e.directory)return{continue:!0};if(t.includes("--no-gates")||ET(e.directory)){let n=await Br(e.directory);if(n){let{manifestPath:o}=n,r=D(o);if(r){let i=Aa(r);if(i){let s=t.includes("--no-gates")?"flag":"config";Ce(o,{phase:i,action:"bypassed",actor:s,reason:s==="flag"?"--no-gates flag detected":"Quality gates disabled in config"}),r.phases[i].gate_result=null,r.phases[i].gate_bypassed=!0,r.phases[i].bypass_reason=s==="flag"?"--no-gates flag":"Config disabled",F(o,r),await $(e.directory,n.checkpoint)}}}return{continue:!0}}if(t.trim().toLowerCase().startsWith("approve")){let n=await Br(e.directory);if(!n)return{continue:!0};let{manifestPath:o}=n,r=D(o);if(!r)return{continue:!0};let i=Aa(r);if(!i)return{continue:!0};let s=new Date().toISOString();r.phases[i].gate_result&&(r.phases[i].gate_result.passed=!0,r.phases[i].gate_result.approved_by="human",r.phases[i].gate_result.approved_at=s);let{checkpoint:a}=n;if(i==="construction"){if(a.current_stage==="code-generation"&&a.active_code_plan_path){let d=a.active_code_plan_path;tt(o,d,"fulfilled");let f=r.artifacts.find(m=>m.id===d);f&&(f.reviewedBy="human");try{let m=Ia(r,d);if(m){let p=Oa(e.directory,n.workflowId,m),g=(typeof a.risk_tier=="number"?a.risk_tier:a.risk_tier?.tier)||r.risk_tier?.tier||2;Ra(p,m,{boltId:d,boltTitle:f?.type||d,commandsExecuted:[],testResults:[],filesChanged:[],gateApprovedBy:"human",dualValidation:{parentConformance:r.phases.construction.gate_result?.verification?.conformance_score??0,rootConformance:0},riskTier:g})}}catch(m){console.error("[Olympus Quality Gate] Failed to generate validation report:",m)}try{let{isWorkflowComplete:m}=await Promise.resolve().then(()=>(J(),Vt)),p=D(o);p&&m(p)&&(a.current_phase="operations",a.current_stage="code-generation",ut(o,"construction","complete"),ut(o,"operations","in_progress"),await $(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 d=r.artifacts.filter(f=>f.stage==="unit");for(let f of d)tt(o,f.id,"active"),f.reviewedBy="human"}}else{let d=r.artifacts.filter(f=>f.phase===i);for(let f of d)tt(o,f.id,"active")}Ce(o,{phase:i,action:"approved",actor:"human",reason:null});try{let d={type:"gate_approval",phase:i,stage:a.current_stage,details:`Gate approved for ${i} phase`},f={workflowId:n.workflowId,featureName:a.feature_name||n.workflowId,projectPath:e.directory,sessionId:e.sessionId||"unknown",phase:i},m=xe(d,f);ie(m)}catch(d){console.error("[Olympus Quality Gate] Failed to capture gate approval discovery:",d)}let c=we(e.directory);c.total_transitions+=1,c.total_transitions>0&&(c.rejection_rate=c.rejection_count/c.total_transitions),is(c,e.directory),F(o,r),await $(e.directory,n.checkpoint),r.phases[i].gate_result?.passed&&(r.phases[i].gate_result=null,F(o,r));let l="",u=n.checkpoint.depth_score;return u&&u<=10?l=" SHALLOW depth: Skip UNIT decomposition, proceed directly to single BOLT generation.":u&&u>=21&&(l=" DEEP depth: Full UNIT + BOLT decomposition with design artifacts required."),{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:`Gate approved. Phase ${i} transition approved. Proceeding to next phase.${l}`}}}if(t.trim().toLowerCase().startsWith("reject")){let n=await Br(e.directory);if(!n)return{continue:!0};let{manifestPath:o}=n,r=D(o);if(!r)return{continue:!0};let i=Aa(r);if(!i)return{continue:!0};let s=t.trim().substring(6).trim()||"No reason provided";r.phases[i].gate_result&&(r.phases[i].gate_result.passed=!1,r.phases[i].gate_result.feedback=s);let{checkpoint:a}=n,c="";if(i==="construction")if(a.current_stage==="code-generation"&&a.active_code_plan_path){let p=a.active_code_plan_path;tt(o,p,"violated",s),c=`The reviewer rejected ${p}: ${s}. Revise and re-submit.`}else if(a.current_stage==="unit"){let p=r.artifacts.filter(g=>g.stage==="unit");for(let g of p)tt(o,g.id,"violated",s);c=`The reviewer rejected UNIT decomposition: ${s}. Revise and re-submit.`}else{let p=r.artifacts.filter(g=>g.phase===i);for(let g of p)tt(o,g.id,"violated",s)}else{let p=r.artifacts.filter(g=>g.phase===i);for(let g of p)tt(o,g.id,"violated",s)}Ce(o,{phase:i,action:"rejected",actor:"human",reason:s});try{let p={type:"gate_rejection",phase:i,stage:a.current_stage,details:s},g={workflowId:n.workflowId,featureName:a.feature_name||n.workflowId,projectPath:e.directory,sessionId:e.sessionId||"unknown",phase:i},h=xe(p,g);ie(h)}catch(p){console.error("[Olympus Quality Gate] Failed to capture gate rejection discovery:",p)}let l=we(e.directory);l.rejection_count+=1,l.total_transitions+=1,l.total_transitions>0&&(l.rejection_rate=l.rejection_count/l.total_transitions),is(l,e.directory),F(o,r),await $(e.directory,n.checkpoint);let u=bT(i,a.current_stage),d=i==="construction"&&a.current_stage==="code-generation"&&a.active_code_plan_path?a.active_code_plan_path:r.artifacts.find(p=>p.phase===i)?.id??`${i}-artifact`,f=r.gate_audit.filter(p=>p.phase===i&&p.action==="rejected").length,m;try{let p=await Cg(e.directory,r.workflow_id,{gateNumber:u,artifactId:d,rejectionReason:s,rejectedBy:"human",attemptNumber:f+1});m=`Gate ${u} rejected ${d}: ${s}.
1931
+ [GATE_PENDING]`}}}catch(t){return console.error("[Olympus Quality Gate] Error in qualityGateBlocker:",t),{continue:!0}}}async function AT(e){try{let t=RT(e);if(!e.directory)return{continue:!0};if(t.includes("--no-gates")||CT(e.directory)){let n=await Br(e.directory);if(n){let{manifestPath:o}=n,r=D(o);if(r){let i=xa(r);if(i){let s=t.includes("--no-gates")?"flag":"config";Ce(o,{phase:i,action:"bypassed",actor:s,reason:s==="flag"?"--no-gates flag detected":"Quality gates disabled in config"}),r.phases[i].gate_result=null,r.phases[i].gate_bypassed=!0,r.phases[i].bypass_reason=s==="flag"?"--no-gates flag":"Config disabled",F(o,r),await $(e.directory,n.checkpoint)}}}return{continue:!0}}if(t.trim().toLowerCase().startsWith("approve")){let n=await Br(e.directory);if(!n)return{continue:!0};let{manifestPath:o}=n,r=D(o);if(!r)return{continue:!0};let i=xa(r);if(!i)return{continue:!0};let s=new Date().toISOString();r.phases[i].gate_result&&(r.phases[i].gate_result.passed=!0,r.phases[i].gate_result.approved_by="human",r.phases[i].gate_result.approved_at=s);let{checkpoint:a}=n;if(i==="construction"){if(a.current_stage==="code-generation"&&a.active_code_plan_path){let f=a.active_code_plan_path;tt(o,f,"fulfilled");let m=r.artifacts.find(p=>p.id===f);m&&(m.reviewedBy="human");try{let p=Oa(r,f);if(p){let g=Pa(e.directory,n.workflowId,p),h=(typeof a.risk_tier=="number"?a.risk_tier:a.risk_tier?.tier)||r.risk_tier?.tier||2;Aa(g,p,{boltId:f,boltTitle:m?.type||f,commandsExecuted:[],testResults:[],filesChanged:[],gateApprovedBy:"human",dualValidation:{parentConformance:r.phases.construction.gate_result?.verification?.conformance_score??0,rootConformance:0},riskTier:h})}}catch(p){console.error("[Olympus Quality Gate] Failed to generate validation report:",p)}try{let{isWorkflowComplete:p}=await Promise.resolve().then(()=>(J(),Vt)),g=D(o);g&&p(g)&&(a.current_phase="operations",a.current_stage="code-generation",ut(o,"construction","complete"),ut(o,"operations","in_progress"),await $(e.directory,a),console.log("[Olympus Quality Gate] All BOLTs fulfilled \u2014 auto-transitioning to Operations phase"))}catch(p){console.error("[Olympus Quality Gate] Failed to check workflow completion:",p)}}else if(a.current_stage==="unit"){let f=r.artifacts.filter(m=>m.stage==="unit");for(let m of f)tt(o,m.id,"active"),m.reviewedBy="human"}}else{let f=r.artifacts.filter(m=>m.phase===i);for(let m of f)tt(o,m.id,"active")}Ce(o,{phase:i,action:"approved",actor:"human",reason:null});try{let f={type:"gate_approval",phase:i,stage:a.current_stage,details:`Gate approved for ${i} phase`},m={workflowId:n.workflowId,featureName:a.feature_name||n.workflowId,projectPath:e.directory,sessionId:e.sessionId||"unknown",phase:i},p=$e(f,m);ie(p)}catch(f){console.error("[Olympus Quality Gate] Failed to capture gate approval discovery:",f)}let c=we(e.directory),l=as(c,!0,!1);ss(l,e.directory),F(o,r),await $(e.directory,n.checkpoint),r.phases[i].gate_result?.passed&&(r.phases[i].gate_result=null,F(o,r));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 ${i} transition approved. Proceeding to next phase.${u}`}}}if(t.trim().toLowerCase().startsWith("reject")){let n=await Br(e.directory);if(!n)return{continue:!0};let{manifestPath:o}=n,r=D(o);if(!r)return{continue:!0};let i=xa(r);if(!i)return{continue:!0};let s=t.trim().substring(6).trim()||"No reason provided";r.phases[i].gate_result&&(r.phases[i].gate_result.passed=!1,r.phases[i].gate_result.feedback=s);let{checkpoint:a}=n,c="";if(i==="construction")if(a.current_stage==="code-generation"&&a.active_code_plan_path){let g=a.active_code_plan_path;tt(o,g,"violated",s),c=`The reviewer rejected ${g}: ${s}. Revise and re-submit.`}else if(a.current_stage==="unit"){let g=r.artifacts.filter(h=>h.stage==="unit");for(let h of g)tt(o,h.id,"violated",s);c=`The reviewer rejected UNIT decomposition: ${s}. Revise and re-submit.`}else{let g=r.artifacts.filter(h=>h.phase===i);for(let h of g)tt(o,h.id,"violated",s)}else{let g=r.artifacts.filter(h=>h.phase===i);for(let h of g)tt(o,h.id,"violated",s)}Ce(o,{phase:i,action:"rejected",actor:"human",reason:s});try{let g={type:"gate_rejection",phase:i,stage:a.current_stage,details:s},h={workflowId:n.workflowId,featureName:a.feature_name||n.workflowId,projectPath:e.directory,sessionId:e.sessionId||"unknown",phase:i},y=$e(g,h);ie(y)}catch(g){console.error("[Olympus Quality Gate] Failed to capture gate rejection discovery:",g)}let l=we(e.directory),u=as(l,!1,!0);ss(u,e.directory),F(o,r),await $(e.directory,n.checkpoint);let d=IT(i,a.current_stage),f=i==="construction"&&a.current_stage==="code-generation"&&a.active_code_plan_path?a.active_code_plan_path:r.artifacts.find(g=>g.phase===i)?.id??`${i}-artifact`,m=r.gate_audit.filter(g=>g.phase===i&&g.action==="rejected").length,p;try{let g=await Rg(e.directory,r.workflow_id,{gateNumber:d,artifactId:f,rejectionReason:s,rejectedBy:"human",attemptNumber:m+1});p=`Gate ${d} rejected ${f}: ${s}.
1932
1932
 
1933
- ${p.prompt}`}catch{m=c||`Gate rejected. Reason: ${s}. 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 Ig(){_({name:"qualityGateBlocker",event:"PostToolUse",priority:80,matcher:"task",handler:IT}),_({name:"qualityGateApprover",event:"UserPromptSubmit",priority:12,handler:RT})}var OT=["explore","explore-medium","librarian","librarian-low","oracle","oracle-low","oracle-medium","momus","metis","multimodal-looker"];function Rg(e){return OT.includes(e)}var Og=/(?:^|\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)/,Vr={debounceMs:1e4,mode:"soft",enabled:!0};Ae();function Ag(){_({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=V(e.directory,e.sessionId).pending_completion?.agent_used;if(!n)return{continue:!0};if(!Rg(n))return{continue:!0};let o=e.toolName;if(o==="write"||o==="edit"||o==="multiedit")return{continue:!1,stopReason:`Agent "${n}" is read-only and cannot perform ${o} operations. Use an agent like "olympian" or "frontend-engineer" for file modifications.`};if(o==="bash"){let i=e.toolInput?.command;if(typeof i=="string"&&Og.test(i))return{continue:!1,stopReason:`Agent "${n}" is read-only and cannot execute bash commands that modify files. Detected write operation in: ${i.substring(0,100)}${i.length>100?"...":""}`}}return{continue:!0}}catch(t){return console.error("[Olympus Agent Role Guard] Error in handler:",t),{continue:!0}}}})}var Yr=require("child_process"),Kr=require("path"),Bn=require("fs"),Pg=0,Ft=null,Ut=null;function xg(e){let t=(0,Kr.join)(e,".olympus","config.json"),n={enabled:Vr.enabled,mode:Vr.mode,debounceMs:Vr.debounceMs};try{if((0,Bn.existsSync)(t)){let o=(0,Bn.readFileSync)(t,"utf8"),r=JSON.parse(o);if(r.hooks?.buildCheck){let i=r.hooks.buildCheck;typeof i.enabled=="boolean"&&(n.enabled=i.enabled),(i.mode==="soft"||i.mode==="strict")&&(n.mode=i.mode),typeof i.debounceMs=="number"&&i.debounceMs>0&&(n.debounceMs=i.debounceMs)}}}catch(o){console.error("[Olympus Build Check] Failed to load config:",o)}return n}function AT(e){let t=(0,Kr.join)(e,"node_modules",".bin","tsc"),n=process.platform==="win32"?`${t}.cmd`:t;if((0,Bn.existsSync)(n))return n;try{let o=process.platform==="win32"?"where":"which",i=require("child_process").execSync(`${o} tsc`,{encoding:"utf8"}).trim().split(`
1934
- `)[0];if(i)return i}catch{}return null}function PT(){if(!Ut||!Ut.pid)return;let e=Ut.pid;try{Ut.kill("SIGTERM")}catch{if(process.platform==="win32")try{(0,Yr.exec)(`taskkill /PID ${e} /F`,n=>{n&&console.error("[Olympus Build Check] Failed to kill process with taskkill:",n)})}catch{}}Ut=null}function $g(){_({name:"buildCheckTrigger",event:"PostToolUse",priority:65,matcher:/write|edit|multiedit/i,handler:async e=>{try{if(!e.directory)return{continue:!0};let t=xg(e.directory);if(!t.enabled)return{continue:!0};let n=Date.now();if(n-Pg<t.debounceMs)return{continue:!0};let o=(0,Kr.join)(e.directory,"tsconfig.json");if(!(0,Bn.existsSync)(o))return{continue:!0};let r=AT(e.directory);if(!r)return{continue:!0};PT();try{let i=(0,Yr.spawn)(r,["--noEmit"],{cwd:e.directory,detached:!0,stdio:"pipe"});Ut=i,Pg=n;let s="",a="";i.stdout&&i.stdout.on("data",c=>{s+=c.toString()}),i.stderr&&i.stderr.on("data",c=>{a+=c.toString()}),i.on("exit",c=>{let l=(s+a).trim();Ft={passed:c===0,output:l,timestamp:Date.now()},Ut=null}),i.on("error",c=>{console.error("[Olympus Build Check] tsc spawn error:",c),Ut=null})}catch(i){console.error("[Olympus Build Check] Failed to spawn tsc:",i)}}catch(t){console.error("[Olympus Build Check] Error in buildCheckTrigger:",t)}return{continue:!0}}}),_({name:"buildCheckInjector",event:"PostToolUse",priority:66,handler:async e=>{try{if(!Ft)return{continue:!0};let t=e.directory?xg(e.directory):{mode:"soft"};if(Ft.passed)return Ft=null,{continue:!0};let n=Ft.output.length>500?Ft.output.substring(0,500)+`
1933
+ ${g.prompt}`}catch{p=c||`Gate rejected. Reason: ${s}. Revise artifacts before retrying.`}return{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:p}}}return{continue:!0}}catch(t){return console.error("[Olympus Quality Gate] Error in qualityGateApprover:",t),{continue:!0}}}function Og(){S({name:"qualityGateBlocker",event:"PostToolUse",priority:80,matcher:"task",handler:OT}),S({name:"qualityGateApprover",event:"UserPromptSubmit",priority:12,handler:AT})}var PT=["explore","explore-medium","librarian","librarian-low","oracle","oracle-low","oracle-medium","momus","metis","multimodal-looker"];function Ag(e){return PT.includes(e)}var Pg=/(?:^|\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)/,Vr={debounceMs:1e4,mode:"soft",enabled:!0};Pe();function xg(){S({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=V(e.directory,e.sessionId).pending_completion?.agent_used;if(!n)return{continue:!0};if(!Ag(n))return{continue:!0};let o=e.toolName;if(o==="write"||o==="edit"||o==="multiedit")return{continue:!1,stopReason:`Agent "${n}" is read-only and cannot perform ${o} operations. Use an agent like "olympian" or "frontend-engineer" for file modifications.`};if(o==="bash"){let i=e.toolInput?.command;if(typeof i=="string"&&Pg.test(i))return{continue:!1,stopReason:`Agent "${n}" is read-only and cannot execute bash commands that modify files. Detected write operation in: ${i.substring(0,100)}${i.length>100?"...":""}`}}return{continue:!0}}catch(t){return console.error("[Olympus Agent Role Guard] Error in handler:",t),{continue:!0}}}})}var Yr=require("child_process"),Kr=require("path"),Bn=require("fs"),$g=0,Ft=null,Ut=null;function Ng(e){let t=(0,Kr.join)(e,".olympus","config.json"),n={enabled:Vr.enabled,mode:Vr.mode,debounceMs:Vr.debounceMs};try{if((0,Bn.existsSync)(t)){let o=(0,Bn.readFileSync)(t,"utf8"),r=JSON.parse(o);if(r.hooks?.buildCheck){let i=r.hooks.buildCheck;typeof i.enabled=="boolean"&&(n.enabled=i.enabled),(i.mode==="soft"||i.mode==="strict")&&(n.mode=i.mode),typeof i.debounceMs=="number"&&i.debounceMs>0&&(n.debounceMs=i.debounceMs)}}}catch(o){console.error("[Olympus Build Check] Failed to load config:",o)}return n}function xT(e){let t=(0,Kr.join)(e,"node_modules",".bin","tsc"),n=process.platform==="win32"?`${t}.cmd`:t;if((0,Bn.existsSync)(n))return n;try{let o=process.platform==="win32"?"where":"which",i=require("child_process").execSync(`${o} tsc`,{encoding:"utf8"}).trim().split(`
1934
+ `)[0];if(i)return i}catch{}return null}function $T(){if(!Ut||!Ut.pid)return;let e=Ut.pid;try{Ut.kill("SIGTERM")}catch{if(process.platform==="win32")try{(0,Yr.exec)(`taskkill /PID ${e} /F`,n=>{n&&console.error("[Olympus Build Check] Failed to kill process with taskkill:",n)})}catch{}}Ut=null}function Dg(){S({name:"buildCheckTrigger",event:"PostToolUse",priority:65,matcher:/write|edit|multiedit/i,handler:async e=>{try{if(!e.directory)return{continue:!0};let t=Ng(e.directory);if(!t.enabled)return{continue:!0};let n=Date.now();if(n-$g<t.debounceMs)return{continue:!0};let o=(0,Kr.join)(e.directory,"tsconfig.json");if(!(0,Bn.existsSync)(o))return{continue:!0};let r=xT(e.directory);if(!r)return{continue:!0};$T();try{let i=(0,Yr.spawn)(r,["--noEmit"],{cwd:e.directory,detached:!0,stdio:"pipe"});Ut=i,$g=n;let s="",a="";i.stdout&&i.stdout.on("data",c=>{s+=c.toString()}),i.stderr&&i.stderr.on("data",c=>{a+=c.toString()}),i.on("exit",c=>{let l=(s+a).trim();Ft={passed:c===0,output:l,timestamp:Date.now()},Ut=null}),i.on("error",c=>{console.error("[Olympus Build Check] tsc spawn error:",c),Ut=null})}catch(i){console.error("[Olympus Build Check] Failed to spawn tsc:",i)}}catch(t){console.error("[Olympus Build Check] Error in buildCheckTrigger:",t)}return{continue:!0}}}),S({name:"buildCheckInjector",event:"PostToolUse",priority:66,handler:async e=>{try{if(!Ft)return{continue:!0};let t=e.directory?Ng(e.directory):{mode:"soft"};if(Ft.passed)return Ft=null,{continue:!0};let n=Ft.output.length>500?Ft.output.substring(0,500)+`
1935
1935
  ... (truncated)`:Ft.output,o=t.mode==="strict"?`[BUILD CHECK FAILED - BLOCKING]
1936
1936
 
1937
1937
  TypeScript compilation failed:
@@ -1944,16 +1944,16 @@ TypeScript compilation failed:
1944
1944
 
1945
1945
  ${n}
1946
1946
 
1947
- Consider fixing these errors.`;return Ft=null,t.mode==="strict"?{continue:!1,stopReason:"Build check failed (strict mode)",hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:o}}:{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:o}}}catch(t){console.error("[Olympus Build Check] Error in buildCheckInjector:",t)}return{continue:!0}}})}Ae();Ee();J();var qn=require("path"),Vn=require("fs"),xT={prometheus:"inception"};async function $T(e){try{let t=await te(e);if(t.length===0)return null;let n=null;for(let o of t){let r=await I(e,o);!r||r.status==="complete"||(!n||r.updated_at>n.updatedAt)&&(n={workflowId:o,checkpoint:r,updatedAt:r.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 NT(e,t){let n=(0,qn.join)(e,"inception"),o=e;switch(t){case"intent":{let r=(0,qn.join)(n,"intent.md"),i=(0,qn.join)(o,"intent.md"),s=(0,Vn.existsSync)(r)?r:i;return(0,Vn.existsSync)(s)?{artifactPath:s,referencePaths:[]}:null}default:return null}}async function DT(e,t,n){try{switch(e){case"intent":return await zo(t);default:return null}}catch(o){return console.error(`[Olympus Artifact Gate] Validation error for ${e}:`,o),null}}function jT(e,t){let n=e.toUpperCase();if(t.passed)return`[Artifact Validation] ${n} validation PASSED (${t.coverage_percentage}% coverage). Good work!`;let o=t.blocking_issues.map((r,i)=>` ${i+1}. ${r}`).join(`
1947
+ Consider fixing these errors.`;return Ft=null,t.mode==="strict"?{continue:!1,stopReason:"Build check failed (strict mode)",hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:o}}:{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:o}}}catch(t){console.error("[Olympus Build Check] Error in buildCheckInjector:",t)}return{continue:!0}}})}Pe();Ee();J();var qn=require("path"),Vn=require("fs"),NT={prometheus:"inception"};async function DT(e){try{let t=await te(e);if(t.length===0)return null;let n=null;for(let o of t){let r=await C(e,o);!r||r.status==="complete"||(!n||r.updated_at>n.updatedAt)&&(n={workflowId:o,checkpoint:r,updatedAt:r.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 jT(e,t){let n=(0,qn.join)(e,"inception"),o=e;switch(t){case"intent":{let r=(0,qn.join)(n,"intent.md"),i=(0,qn.join)(o,"intent.md"),s=(0,Vn.existsSync)(r)?r:i;return(0,Vn.existsSync)(s)?{artifactPath:s,referencePaths:[]}:null}default:return null}}async function MT(e,t,n){try{switch(e){case"intent":return await Qo(t);default:return null}}catch(o){return console.error(`[Olympus Artifact Gate] Validation error for ${e}:`,o),null}}function LT(e,t){let n=e.toUpperCase();if(t.passed)return`[Artifact Validation] ${n} validation PASSED (${t.coverage_percentage}% coverage). Good work!`;let o=t.blocking_issues.map((r,i)=>` ${i+1}. ${r}`).join(`
1948
1948
  `);return`[Artifact Validation] WARNING: ${n} validation FAILED (${t.coverage_percentage}% coverage)
1949
1949
 
1950
1950
  Blocking issues:
1951
1951
  ${o}
1952
1952
 
1953
1953
  ${t.reviewer?`Reviewer: ${t.reviewer}
1954
- `:""}Please review and address these issues before proceeding to the next stage.`}async function MT(e){try{if(e.toolName!=="Task")return{continue:!0};if(!e.directory||!e.sessionId)return{continue:!0};let n=V(e.directory,e.sessionId).pending_completion?.agent_used;if(!n)return{continue:!0};if(!xT[n])return{continue:!0};let r=await $T(e.directory);if(!r)return{continue:!0};let{workflowId:i,checkpoint:s}=r,a="intent",c=(0,qn.join)(e.directory,"aidlc-docs",i);if(!(0,Vn.existsSync)(c))return console.error("[Olympus Artifact Gate] Workflow directory not found:",c),{continue:!0};let l=NT(c,a);if(!l)return console.error(`[Olympus Artifact Gate] Could not find artifact paths for ${a} in ${c}`),{continue:!0};let u=await DT(a,l.artifactPath,l.referencePaths);if(!u)return console.error(`[Olympus Artifact Gate] Validation failed to run for ${a}`),{continue:!0};let d=jT(a,u);if(a==="intent"&&u.passed)try{let f=(0,Vn.readFileSync)(l.artifactPath,"utf-8"),m=lr(f),p=s.manifest_path||(0,qn.join)(e.directory,"aidlc-docs",i,"manifest.json"),g=D(p);g&&(g.depth_assessment=m,g.risk_tier=m.risk_tier,F(p,g)),s.depth_score=m.total_score,s.risk_tier=m.risk_tier.tier,await $(e.directory,s);let h=m.recommended_depth==="minimal"?"SHALLOW":m.recommended_depth==="standard"?"MEDIUM":"DEEP";d+=`
1954
+ `:""}Please review and address these issues before proceeding to the next stage.`}async function FT(e){try{if(e.toolName!=="Task")return{continue:!0};if(!e.directory||!e.sessionId)return{continue:!0};let n=V(e.directory,e.sessionId).pending_completion?.agent_used;if(!n)return{continue:!0};if(!NT[n])return{continue:!0};let r=await DT(e.directory);if(!r)return{continue:!0};let{workflowId:i,checkpoint:s}=r,a="intent",c=(0,qn.join)(e.directory,"aidlc-docs",i);if(!(0,Vn.existsSync)(c))return console.error("[Olympus Artifact Gate] Workflow directory not found:",c),{continue:!0};let l=jT(c,a);if(!l)return console.error(`[Olympus Artifact Gate] Could not find artifact paths for ${a} in ${c}`),{continue:!0};let u=await MT(a,l.artifactPath,l.referencePaths);if(!u)return console.error(`[Olympus Artifact Gate] Validation failed to run for ${a}`),{continue:!0};let d=LT(a,u);if(a==="intent"&&u.passed)try{let f=(0,Vn.readFileSync)(l.artifactPath,"utf-8"),m=ur(f),p=s.manifest_path||(0,qn.join)(e.directory,"aidlc-docs",i,"manifest.json"),g=D(p);g&&(g.depth_assessment=m,g.risk_tier=m.risk_tier,F(p,g)),s.depth_score=m.total_score,s.risk_tier=m.risk_tier.tier,await $(e.directory,s);let h=m.recommended_depth==="minimal"?"SHALLOW":m.recommended_depth==="standard"?"MEDIUM":"DEEP";d+=`
1955
1955
 
1956
- [Depth Assessment] Score: ${m.total_score}/30 \u2192 ${h} | Risk Tier: ${m.risk_tier.tier}`}catch(f){console.error("[Olympus Artifact Gate] Failed to assess depth after INTENT validation:",f)}return{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:d}}}catch(t){return console.error("[Olympus Artifact Gate] Error in workflowArtifactGateHandler:",t),{continue:!0}}}function Ng(){_({name:"workflowArtifactGate",event:"PostToolUse",priority:78,matcher:"task",handler:MT})}Ee();J();var nn=b(ue(),1),Jr=require("path"),Dg=require("child_process");function jg(e){let t=(0,Jr.join)(e,".olympus","config.json");try{if(nn.existsSync(t)){let n=nn.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 LT()}function LT(){return{staticQuality:{enabled:!0},security:{enabled:!0,auditLevel:"moderate"},complexity:{enabled:!0,agent:"oracle-low"},customChecks:[]}}function FT(e){let t=[];try{let n=(0,Jr.join)(e,"package.json");if(nn.existsSync(n)){let r=nn.readJsonSync(n)?.scripts||{};r.lint&&t.push("npm run lint"),r.typecheck&&t.push("npm run typecheck"),r.test&&t.push("npm test"),!r.typecheck&&nn.existsSync((0,Jr.join)(e,"tsconfig.json"))&&t.push("npx tsc --noEmit")}}catch{}return t}function Pa(e,t,n,o){let r=Date.now();try{let i=(0,Dg.execSync)(e,{cwd:t,timeout:12e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return{name:n,layer:o,passed:!0,command:e,exitCode:0,stdout:(i||"").substring(0,2e3),stderr:"",duration_ms:Date.now()-r}}catch(i){return{name:n,layer:o,passed:!1,command:e,exitCode:i.status||1,stdout:(i.stdout||"").substring(0,2e3),stderr:(i.stderr||"").substring(0,2e3),duration_ms:Date.now()-r}}}function Mg(e){let t=[{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}],n=[];for(let{name:o,pattern:r}of t){let i=e.match(r);i&&n.push(`${o} detected (${i.length} occurrence${i.length>1?"s":""})`)}return n}function Lg(e){let t=[{name:"eval() usage",pattern:/\beval\s*\(/g},{name:"exec() usage",pattern:/\bexec\s*\(/g},{name:"innerHTML assignment",pattern:/\.innerHTML\s*=/g},{name:"dangerouslySetInnerHTML",pattern:/dangerouslySetInnerHTML/g}],n=[];for(let{name:o,pattern:r}of t){let i=e.match(r);i&&n.push(`${o} (${i.length} occurrence${i.length>1?"s":""})`)}return n}function Fg(e,t){let n=[],o=Date.now();if(t.staticQuality.enabled){let i=t.staticQuality.commands||FT(e);for(let s of i)n.push(Pa(s,e,`Static: ${s}`,"static-quality"))}if(t.security.enabled){let i=t.security.auditLevel||"moderate";n.push(Pa(`npm audit --audit-level=${i}`,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 i of t.customChecks)n.push(Pa(i.command,e,`Custom: ${i.name}`,"custom"));let r=n.filter(i=>!i.passed).map(i=>i.name);return{allPassed:r.length===0,results:n,totalDuration_ms:Date.now()-o,failedChecks:r}}function Ug(e){let t=e.allPassed?"CI Review Pipeline: ALL CHECKS PASSED":`CI Review Pipeline: ${e.failedChecks.length} CHECK(S) FAILED`,n=e.results.map(o=>{let i=`[${o.passed?"PASS":"FAIL"}] ${o.name}`;return o.passed||(i+=`
1956
+ [Depth Assessment] Score: ${m.total_score}/30 \u2192 ${h} | Risk Tier: ${m.risk_tier.tier}`}catch(f){console.error("[Olympus Artifact Gate] Failed to assess depth after INTENT validation:",f)}return{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:d}}}catch(t){return console.error("[Olympus Artifact Gate] Error in workflowArtifactGateHandler:",t),{continue:!0}}}function jg(){S({name:"workflowArtifactGate",event:"PostToolUse",priority:78,matcher:"task",handler:FT})}Ee();J();var nn=b(ue(),1),Jr=require("path"),Mg=require("child_process");function Lg(e){let t=(0,Jr.join)(e,".olympus","config.json");try{if(nn.existsSync(t)){let n=nn.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 UT()}function UT(){return{staticQuality:{enabled:!0},security:{enabled:!0,auditLevel:"moderate"},complexity:{enabled:!0,agent:"oracle-low"},customChecks:[]}}function WT(e){let t=[];try{let n=(0,Jr.join)(e,"package.json");if(nn.existsSync(n)){let r=nn.readJsonSync(n)?.scripts||{};r.lint&&t.push("npm run lint"),r.typecheck&&t.push("npm run typecheck"),r.test&&t.push("npm test"),!r.typecheck&&nn.existsSync((0,Jr.join)(e,"tsconfig.json"))&&t.push("npx tsc --noEmit")}}catch{}return t}function $a(e,t,n,o){let r=Date.now();try{let i=(0,Mg.execSync)(e,{cwd:t,timeout:12e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return{name:n,layer:o,passed:!0,command:e,exitCode:0,stdout:(i||"").substring(0,2e3),stderr:"",duration_ms:Date.now()-r}}catch(i){return{name:n,layer:o,passed:!1,command:e,exitCode:i.status||1,stdout:(i.stdout||"").substring(0,2e3),stderr:(i.stderr||"").substring(0,2e3),duration_ms:Date.now()-r}}}function Fg(e){let t=[{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}],n=[];for(let{name:o,pattern:r}of t){let i=e.match(r);i&&n.push(`${o} detected (${i.length} occurrence${i.length>1?"s":""})`)}return n}function Ug(e){let t=[{name:"eval() usage",pattern:/\beval\s*\(/g},{name:"exec() usage",pattern:/\bexec\s*\(/g},{name:"innerHTML assignment",pattern:/\.innerHTML\s*=/g},{name:"dangerouslySetInnerHTML",pattern:/dangerouslySetInnerHTML/g}],n=[];for(let{name:o,pattern:r}of t){let i=e.match(r);i&&n.push(`${o} (${i.length} occurrence${i.length>1?"s":""})`)}return n}function Wg(e,t){let n=[],o=Date.now();if(t.staticQuality.enabled){let i=t.staticQuality.commands||WT(e);for(let s of i)n.push($a(s,e,`Static: ${s}`,"static-quality"))}if(t.security.enabled){let i=t.security.auditLevel||"moderate";n.push($a(`npm audit --audit-level=${i}`,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 i of t.customChecks)n.push($a(i.command,e,`Custom: ${i.name}`,"custom"));let r=n.filter(i=>!i.passed).map(i=>i.name);return{allPassed:r.length===0,results:n,totalDuration_ms:Date.now()-o,failedChecks:r}}function Hg(e){let t=e.allPassed?"CI Review Pipeline: ALL CHECKS PASSED":`CI Review Pipeline: ${e.failedChecks.length} CHECK(S) FAILED`,n=e.results.map(o=>{let i=`[${o.passed?"PASS":"FAIL"}] ${o.name}`;return o.passed||(i+=`
1957
1957
  Command: ${o.command}`,i+=`
1958
1958
  Exit code: ${o.exitCode}`,o.stderr&&(i+=`
1959
1959
  Error: ${o.stderr.substring(0,500)}`)),i}).join(`
@@ -1961,7 +1961,7 @@ ${t.reviewer?`Reviewer: ${t.reviewer}
1961
1961
 
1962
1962
  ${n}
1963
1963
 
1964
- Total duration: ${e.totalDuration_ms}ms`}var Wg=require("fs");async function UT(e){try{if(e.toolName!=="Task")return{continue:!0};if(!e.directory||!e.sessionId)return{continue:!0};let t=await te(e.directory);if(t.length===0)return{continue:!0};let n=null,o="";for(let m of t){let p=await I(e.directory,m);if(p&&p.status!=="complete"){n=p,o=p.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 r=n.active_code_plan_path,i=D(o);if(!i)return{continue:!0};let s=jg(e.directory),a=Fg(e.directory,s),c=i.artifacts.find(m=>m.id===r),l=[],u=[];if(c)try{let m=(0,Wg.readFileSync)(c.path,"utf-8");l=Mg(m),u=Lg(m)}catch{}let d=Ug(a),f="";return l.length>0&&(f=`
1964
+ Total duration: ${e.totalDuration_ms}ms`}var Gg=require("fs");async function HT(e){try{if(e.toolName!=="Task")return{continue:!0};if(!e.directory||!e.sessionId)return{continue:!0};let t=await te(e.directory);if(t.length===0)return{continue:!0};let n=null,o="";for(let m of t){let p=await C(e.directory,m);if(p&&p.status!=="complete"){n=p,o=p.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 r=n.active_code_plan_path,i=D(o);if(!i)return{continue:!0};let s=Lg(e.directory),a=Wg(e.directory,s),c=i.artifacts.find(m=>m.id===r),l=[],u=[];if(c)try{let m=(0,Gg.readFileSync)(c.path,"utf-8");l=Fg(m),u=Ug(m)}catch{}let d=Hg(a),f="";return l.length>0&&(f=`
1965
1965
 
1966
1966
  SECURITY FINDINGS:
1967
1967
  ${l.map(m=>` - ${m}`).join(`
@@ -1973,16 +1973,22 @@ ${u.map(m=>` - ${m}`).join(`
1973
1973
 
1974
1974
  ${d}${f}
1975
1975
 
1976
- 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 Hg(){_({name:"ciReviewPipeline",event:"PostToolUse",priority:79,matcher:"task",handler:UT})}fe();function Gg(e,t=2){let o=e.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter(i=>i.length>0);if(o.length<t)return new Set(o);let r=new Set;for(let i=0;i<=o.length-t;i++)r.add(o.slice(i,i+t).join(" "));return r}function xa(e,t){let n=Gg(e),o=Gg(t),r=new Set([...n].filter(s=>o.has(s))),i=new Set([...n,...o]);return i.size>0?r.size/i.size:0}function WT(e,t=.4){let n=[],o=new Set;for(let r of e){if(o.has(r.id))continue;let i=[r];o.add(r.id);for(let s of e){if(o.has(s.id))continue;xa(r.user_message,s.user_message)>=t&&(i.push(s),o.add(s.id))}n.push(i)}return n}function Bg(e,t=3,n=1e3,o){let s=(o?e.filter(c=>c.project_path===o):e).slice(-n).filter(c=>c.feedback_category==="correction"||c.feedback_category==="clarification"||c.feedback_category==="explicit_preference");return WT(s).filter(c=>c.length>=t).map(c=>{let l=c.sort((p,g)=>new Date(g.timestamp).getTime()-new Date(p.timestamp).getTime())[0],u=c.reduce((p,g)=>p+g.confidence,0)/c.length,f=new Set(c.map(p=>p.project_path)).size===1?"project":"global",m=GT(c);return{pattern:HT(c),confidence:u,evidence_count:c.length,evidence_examples:c.slice(0,3).map(p=>p.user_message.substring(0,150)),scope:f,category:m}})}function HT(e){let t=new Map;for(let r of e){let i=r.user_message.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter(s=>s.length>3);for(let s of i)t.set(s,(t.get(s)||0)+1)}let n=[...t.entries()].sort((r,i)=>i[1]-r[1]).slice(0,3).map(([r])=>r);return e[0].user_message.substring(0,100)+(n.length>0?` [themes: ${n.join(", ")}]`:"")}function GT(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 BT={verbosity:"unknown",autonomy:"unknown",explanation_depth:"unknown",explicit_rules:[],inferred_preferences:[],recurring_corrections:[],last_updated:new Date().toISOString()},qT=30;function VT(e){let t=e.filter(o=>o.feedback_category==="explicit_preference"),n=[];for(let o of t){let r=o.user_message.match(/always\s+(.+?)(?:\.|$)/i),i=o.user_message.match(/never\s+(.+?)(?:\.|$)/i);r&&n.push(`Always: ${r[1].trim()}`),i&&n.push(`Never: ${i[1].trim()}`)}return[...new Set(n)]}function YT(e){let t=e.filter(o=>/too (long|verbose|much|wordy)/i.test(o.user_message)).length,n=e.filter(o=>/more (detail|info|explanation)|too (brief|short)/i.test(o.user_message)).length;return t>=3&&t>n?"concise":n>=3&&n>t?"detailed":"unknown"}function KT(e){let t=e.filter(o=>/ask (me )?(first|before)|don't assume|confirm/i.test(o.user_message)).length,n=e.filter(o=>/just (do|make|fix)|don't ask|stop asking/i.test(o.user_message)).length;return t>=3&&t>n?"ask_first":n>=3&&n>t?"just_do_it":t>=2&&n>=2?"balanced":"unknown"}function qg(e,t,n,o){let r={...e},i=o??t.find(m=>m.project_path)?.project_path,s=VT(t),a=new Set(r.explicit_rules.map(m=>m.rule)),c=s.filter(m=>!a.has(m)).map(m=>({rule:m,created_at:new Date().toISOString(),...i?{project_path:i}:{}}));r.explicit_rules=[...r.explicit_rules,...c];let l=YT(t);l!=="unknown"&&(r.verbosity=l);let u=KT(t);u!=="unknown"&&(r.autonomy=u);let d=n.filter(m=>m.confidence>.7&&m.scope==="global").map(m=>m.pattern);r.inferred_preferences=[...new Set([...r.inferred_preferences,...d])];for(let m of n){let p=r.recurring_corrections.find(g=>xa(g.pattern,m.pattern)>.5);p?(p.count=m.evidence_count,p.last_seen=new Date().toISOString(),p.examples=m.evidence_examples):r.recurring_corrections.push({pattern:m.pattern,count:m.evidence_count,last_seen:new Date().toISOString(),examples:m.evidence_examples})}let f=Date.now();if(r.recurring_corrections=r.recurring_corrections.filter(m=>{if(!m.last_seen)return!0;let p=Date.parse(m.last_seen);return isNaN(p)?!0:f-p<=qT*864e5}),n.length>0){let m=new Set(n.map(p=>p.pattern));r.inferred_preferences=r.inferred_preferences.filter(p=>m.has(p))}return r.last_updated=new Date().toISOString(),r}function Vg(){return{...BT,last_updated:new Date().toISOString()}}var bo=require("path"),Yn=require("fs"),JT=3,zT=10;function QT(e){let t=(0,bo.join)(e,"feedback-log.jsonl"),n=(0,bo.join)(e,"agent-performance.json");if(!(0,Yn.existsSync)(t))return!1;if(!(0,Yn.existsSync)(n))return!0;try{let o=(0,Yn.statSync)(t),r=(0,Yn.statSync)(n);return o.mtime>r.mtime}catch(o){return console.error("[Olympus Learning Aggregation] Failed to check file times:",o),!0}}function Yg(){_({name:"learningAggregation",event:"Stop",priority:95,handler:async e=>{try{if(!e.directory)return{continue:!0};let t=ae();if(!QT(t))return{continue:!0};let n=xo();if(n.length<JT)return{continue:!0};let o=new Set;for(let d of n)d.agent_used&&o.add(d.agent_used);let r=Array.from(o);if(r.length===0)return{continue:!0};let i={};for(let d of r){let f=$o(d,n);f&&(i[d]=f)}let s=(0,bo.join)(t,"agent-performance.json");Ge(s,i);let a=(0,bo.join)(t,"user-preferences.json"),c=me(a,Vg()),l=[];if(n.length>=zT)try{l=Bg(n)}catch(d){console.error("[Olympus Learning Aggregation] Pattern extraction failed:",d)}let u=qg(c,n,l);Ge(a,u)}catch(t){console.error("[Olympus Learning Aggregation] Error in aggregation handler:",t)}return{continue:!0}}})}var Na=["discovery","inception","construction","operations"],XT={draft:"o",active:"+",fulfilled:"++",violated:"X",stale:"!"},ZT={0:"Baseline",1:"Earned",2:"Extended",3:"Trusted"};function Kg(e,t=null,n=null){let o=eE(e),r=nE(e),i=oE(e.risks),s=rE(e.gate_audit),a=iE(t),c=sE(e.alignment_checks),l=aE(e.depth_assessment),u=cE(e.risk_tier),d=uE(e,o),f=lE(e),m=n?.inception_stages?pE(n.inception_stages,n.current_inception_stage):null,p=[`# Workflow Status: ${e.feature_name}`,`ID: ${e.workflow_id}`,"",d,"","## Phase Progress",...o.map(g=>tE(g)),"",...m?[m,""]:[],f,l,u,a,"","## Artifacts",r,"","## Alignment",c,"","## Risk Summary",i,"","## Gate Audit",s].filter(g=>g!==null).join(`
1977
- `);return{summary:d,phaseProgress:o,artifactTree:r,riskSummary:i,gateSummary:s,trustDisplay:a,alignmentSummary:c,fullReport:p}}function eE(e){return Na.map(t=>{let n=e.phases[t],o=e.artifacts.filter(a=>a.phase===t),r=o.length;if(r===0)return{phase:t,percentage:n.status==="complete"?100:0,status:n.status,artifactCount:0};let i=o.filter(a=>a.contract_status==="active"||a.contract_status==="fulfilled").length,s=Math.round(i/r*100);return{phase:t,percentage:s,status:n.status,artifactCount:r}})}function tE(e){let n=Math.round(e.percentage/100*20),o=20-n,r="=".repeat(n)+"-".repeat(o);return`${(e.phase.charAt(0).toUpperCase()+e.phase.slice(1)).padEnd(8)} [${r}] ${String(e.percentage).padStart(3)}% (${e.status}) ${e.artifactCount} artifacts`}function nE(e){let t=[];for(let n of Na){let o=e.artifacts.filter(s=>s.phase===n);if(o.length===0)continue;let r=n.charAt(0).toUpperCase()+n.slice(1);t.push(`[${r}]`);let i=new Map;for(let s of o){let a=s.stage;i.has(a)||i.set(a,[]),i.get(a).push(s)}for(let[s,a]of i){t.push(` ${s}/`);for(let c of a){let l=XT[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(`
1978
- `)}function oE(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,o=e.filter(a=>a.status==="accepted").length,r=e.filter(a=>a.status==="closed").length,i=[`Total: ${e.length} | Open: ${t} | Mitigated: ${n} | Accepted: ${o} | Closed: ${r}`],s=e.filter(a=>a.status==="open");for(let a of s)i.push(` [OPEN] ${a.id}: ${a.description} (${a.likelihood}/${a.impact})`);return i.join(`
1979
- `)}function rE(e){if(e.length===0)return"No gate transitions recorded";let t=e.filter(i=>i.action==="approved").length,n=e.filter(i=>i.action==="rejected").length,o=e.filter(i=>i.action==="bypassed").length,r=[`Total: ${e.length} | Approved: ${t} | Rejected: ${n} | Bypassed: ${o}`];for(let i of e){let s=i.phase.charAt(0).toUpperCase()+i.phase.slice(1);r.push(` [${i.action.toUpperCase()}] ${s} by ${i.actor}${i.reason?": "+i.reason:""}`)}return r.join(`
1980
- `)}function iE(e){if(!e)return"Trust: Not initialized";let t=ZT[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(`
1981
- `)}function sE(e){if(e.length===0)return"No alignment checks recorded";let t=e.filter(r=>r.alignment_passed).length,n=e.filter(r=>!r.alignment_passed).length,o=[`Total: ${e.length} | Passed: ${t} | Failed: ${n}`];for(let r of e){let i=r.alignment_passed?"PASS":"FAIL",s=r.verification.conformance_score,a=r.verification.passed?"v":"x",c=r.validation.passed?"v":"x";o.push(` [${i}] ${r.source_artifact_id} -> ${r.target_artifact_id}: verification=${s}% [${a}] validation [${c}]`)}return o.join(`
1982
- `)}function aE(e){return e?`Depth: ${e.recommended_depth} (score: ${e.total_score}/30)${e.skip_units?" [skip-units]":""}`:"Depth: Not assessed"}function cE(e){return e?`Risk Tier: ${e.tier} (${e.rationale})`:"Risk Tier: Not classified"}function lE(e){let t=e.artifacts.filter(r=>r.stage==="code-generation"),n=t.length;return n===0?"Bolts: 0/0":`Bolts: ${t.filter(r=>r.contract_status==="active"||r.contract_status==="fulfilled").length}/${n} complete`}function uE(e,t){let n=e.artifacts.length,o=t.filter(i=>i.status!=="not_started");return`${t.filter(i=>i.percentage===100&&i.status==="complete").length}/${Na.length} phases complete | ${n} artifacts total`}var $a=["workspace-detection","reverse-engineering","requirements-analysis","user-stories","workflow-planning","application-design","units-generation"],dE={"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 pE(e,t){let n=$a.length,o=$a.filter(l=>e[l]?.status==="completed").length,r=Math.round(o/n*100),i=10,s=Math.round(r/100*i),c=[`Inception [${s>=i?"=".repeat(i):"=".repeat(s)+">"+"-".repeat(i-s-1)}] ${r}% (${o}/${n} stages)`];for(let l of $a){let u=e[l],d=dE[l];if(!u){c.push(` [ ] ${d}`);continue}if(u.status==="completed")c.push(` [x] ${d}`);else if(u.status==="skipped"){let f=u.skip_reason?` (${u.skip_reason})`:" (skipped)";c.push(` [-] ${d}${f}`)}else u.status==="in_progress"||l===t?c.push(` [ ] ${d} <- current`):c.push(` [ ] ${d}`)}return c.join(`
1983
- `)}J();$t();Ee();var Jg=b(require("path"),1);function zg(){_({name:"workflowStatusReporter",event:"UserPromptSubmit",priority:6,handler:async e=>{try{let t=e.directory||process.cwd(),n=e.prompt||"",r=(e.parts||[]).map(f=>f.text||"").join(" ")||n;if(!(r.includes("Show status of all active structured workflows")||r.includes("workflow-status")))return{continue:!0};let s=await te(t),a=null;for(let f of s){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=Jg.join(t,"aidlc-docs",a,"manifest.json"),l=D(c);if(!l)return{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:"<workflow-status>\nNo active workflows found. Start one with `/plan <description>`\n</workflow-status>"}};let u=we(t);return{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:`<workflow-status>
1984
- ${Kg(l,u).fullReport}
1985
- </workflow-status>`}}}catch(t){return console.error("[Olympus Workflow Status] Error generating report:",t),{continue:!0}}}})}J();$t();Ee();var Qg=b(require("path"),1);function Xg(){_({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 te(t),o=null,r=null;for(let p of n){let g=await I(t,p);if(g&&g.status!=="complete"&&g.status!=="archived"&&g.status!=="deferred"){o=p,r=g;break}}if(!o||!r)return{continue:!0};let i=Qg.join(t,"aidlc-docs",o,"manifest.json"),s=D(i);if(!s)return{continue:!0};let a=we(t),c=s.gate_audit.length>0?s.gate_audit[s.gate_audit.length-1]:null,l=null,u=nt(s),d=u.filter(p=>p.contract_status==="fulfilled"),f=qt(s),m=s.artifacts.filter(p=>p.stage==="intent");if(u.length>0&&d.length===u.length&&r.current_stage==="code-generation"&&s.phases.construction.status==="complete")l=`\u2713 All ${u.length} BOLTs executed and reviewed
1976
+ 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 Bg(){S({name:"ciReviewPipeline",event:"PostToolUse",priority:79,matcher:"task",handler:HT})}fe();function qg(e,t=2){let o=e.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter(i=>i.length>0);if(o.length<t)return new Set(o);let r=new Set;for(let i=0;i<=o.length-t;i++)r.add(o.slice(i,i+t).join(" "));return r}function Na(e,t){let n=qg(e),o=qg(t),r=new Set([...n].filter(s=>o.has(s))),i=new Set([...n,...o]);return i.size>0?r.size/i.size:0}function GT(e,t=.4){let n=[],o=new Set;for(let r of e){if(o.has(r.id))continue;let i=[r];o.add(r.id);for(let s of e){if(o.has(s.id))continue;Na(r.user_message,s.user_message)>=t&&(i.push(s),o.add(s.id))}n.push(i)}return n}function Vg(e,t=3,n=1e3,o){let s=(o?e.filter(c=>c.project_path===o):e).slice(-n).filter(c=>c.feedback_category==="correction"||c.feedback_category==="clarification"||c.feedback_category==="explicit_preference");return GT(s).filter(c=>c.length>=t).map(c=>{let l=c.sort((p,g)=>new Date(g.timestamp).getTime()-new Date(p.timestamp).getTime())[0],u=c.reduce((p,g)=>p+g.confidence,0)/c.length,f=new Set(c.map(p=>p.project_path)).size===1?"project":"global",m=qT(c);return{pattern:BT(c),confidence:u,evidence_count:c.length,evidence_examples:c.slice(0,3).map(p=>p.user_message.substring(0,150)),scope:f,category:m}})}function BT(e){let t=new Map;for(let r of e){let i=r.user_message.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter(s=>s.length>3);for(let s of i)t.set(s,(t.get(s)||0)+1)}let n=[...t.entries()].sort((r,i)=>i[1]-r[1]).slice(0,3).map(([r])=>r);return e[0].user_message.substring(0,100)+(n.length>0?` [themes: ${n.join(", ")}]`:"")}function qT(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 VT={verbosity:"unknown",autonomy:"unknown",explanation_depth:"unknown",explicit_rules:[],inferred_preferences:[],recurring_corrections:[],last_updated:new Date().toISOString()},YT=30;function KT(e){let t=e.filter(o=>o.feedback_category==="explicit_preference"),n=[];for(let o of t){let r=o.user_message.match(/always\s+(.+?)(?:\.|$)/i),i=o.user_message.match(/never\s+(.+?)(?:\.|$)/i);r&&n.push(`Always: ${r[1].trim()}`),i&&n.push(`Never: ${i[1].trim()}`)}return[...new Set(n)]}function JT(e){let t=e.filter(o=>/too (long|verbose|much|wordy)/i.test(o.user_message)).length,n=e.filter(o=>/more (detail|info|explanation)|too (brief|short)/i.test(o.user_message)).length;return t>=3&&t>n?"concise":n>=3&&n>t?"detailed":"unknown"}function zT(e){let t=e.filter(o=>/ask (me )?(first|before)|don't assume|confirm/i.test(o.user_message)).length,n=e.filter(o=>/just (do|make|fix)|don't ask|stop asking/i.test(o.user_message)).length;return t>=3&&t>n?"ask_first":n>=3&&n>t?"just_do_it":t>=2&&n>=2?"balanced":"unknown"}function Yg(e,t,n,o){let r={...e},i=o??t.find(m=>m.project_path)?.project_path,s=KT(t),a=new Set(r.explicit_rules.map(m=>m.rule)),c=s.filter(m=>!a.has(m)).map(m=>({rule:m,created_at:new Date().toISOString(),...i?{project_path:i}:{}}));r.explicit_rules=[...r.explicit_rules,...c];let l=JT(t);l!=="unknown"&&(r.verbosity=l);let u=zT(t);u!=="unknown"&&(r.autonomy=u);let d=n.filter(m=>m.confidence>.7&&m.scope==="global").map(m=>m.pattern);r.inferred_preferences=[...new Set([...r.inferred_preferences,...d])];for(let m of n){let p=r.recurring_corrections.find(g=>Na(g.pattern,m.pattern)>.5);p?(p.count=m.evidence_count,p.last_seen=new Date().toISOString(),p.examples=m.evidence_examples):r.recurring_corrections.push({pattern:m.pattern,count:m.evidence_count,last_seen:new Date().toISOString(),examples:m.evidence_examples})}let f=Date.now();if(r.recurring_corrections=r.recurring_corrections.filter(m=>{if(!m.last_seen)return!0;let p=Date.parse(m.last_seen);return isNaN(p)?!0:f-p<=YT*864e5}),n.length>0){let m=new Set(n.map(p=>p.pattern));r.inferred_preferences=r.inferred_preferences.filter(p=>m.has(p))}return r.last_updated=new Date().toISOString(),r}function Kg(){return{...VT,last_updated:new Date().toISOString()}}var Co=require("path"),Yn=require("fs"),QT=3,XT=10;function ZT(e){let t=(0,Co.join)(e,"feedback-log.jsonl"),n=(0,Co.join)(e,"agent-performance.json");if(!(0,Yn.existsSync)(t))return!1;if(!(0,Yn.existsSync)(n))return!0;try{let o=(0,Yn.statSync)(t),r=(0,Yn.statSync)(n);return o.mtime>r.mtime}catch(o){return console.error("[Olympus Learning Aggregation] Failed to check file times:",o),!0}}function Jg(){S({name:"learningAggregation",event:"Stop",priority:95,handler:async e=>{try{if(!e.directory)return{continue:!0};let t=ae();if(!ZT(t))return{continue:!0};let n=$o();if(n.length<QT)return{continue:!0};let o=new Set;for(let d of n)d.agent_used&&o.add(d.agent_used);let r=Array.from(o);if(r.length===0)return{continue:!0};let i={};for(let d of r){let f=No(d,n);f&&(i[d]=f)}let s=(0,Co.join)(t,"agent-performance.json");Ge(s,i);let a=(0,Co.join)(t,"user-preferences.json"),c=me(a,Kg()),l=[];if(n.length>=XT)try{l=Vg(n)}catch(d){console.error("[Olympus Learning Aggregation] Pattern extraction failed:",d)}let u=Yg(c,n,l);Ge(a,u)}catch(t){console.error("[Olympus Learning Aggregation] Error in aggregation handler:",t)}return{continue:!0}}})}var ja=["discovery","inception","construction","operations"],eE={draft:"o",active:"+",fulfilled:"++",violated:"X",stale:"!"},tE={0:"Baseline",1:"Earned",2:"Extended",3:"Trusted"};function zg(e,t=null,n=null){let o=nE(e),r=rE(e),i=iE(e.risks),s=sE(e.gate_audit),a=aE(t),c=cE(e.alignment_checks),l=lE(e.depth_assessment),u=uE(e.risk_tier),d=pE(e,o),f=dE(e),m=n?.inception_stages?mE(n.inception_stages,n.current_inception_stage):null,p=[`# Workflow Status: ${e.feature_name}`,`ID: ${e.workflow_id}`,"",d,"","## Phase Progress",...o.map(g=>oE(g)),"",...m?[m,""]:[],f,l,u,a,"","## Artifacts",r,"","## Alignment",c,"","## Risk Summary",i,"","## Gate Audit",s].filter(g=>g!==null).join(`
1977
+ `);return{summary:d,phaseProgress:o,artifactTree:r,riskSummary:i,gateSummary:s,trustDisplay:a,alignmentSummary:c,fullReport:p}}function nE(e){return ja.map(t=>{let n=e.phases[t],o=e.artifacts.filter(a=>a.phase===t),r=o.length;if(r===0)return{phase:t,percentage:n.status==="complete"?100:0,status:n.status,artifactCount:0};let i=o.filter(a=>a.contract_status==="active"||a.contract_status==="fulfilled").length,s=Math.round(i/r*100);return{phase:t,percentage:s,status:n.status,artifactCount:r}})}function oE(e){let n=Math.round(e.percentage/100*20),o=20-n,r="=".repeat(n)+"-".repeat(o);return`${(e.phase.charAt(0).toUpperCase()+e.phase.slice(1)).padEnd(8)} [${r}] ${String(e.percentage).padStart(3)}% (${e.status}) ${e.artifactCount} artifacts`}function rE(e){let t=[];for(let n of ja){let o=e.artifacts.filter(s=>s.phase===n);if(o.length===0)continue;let r=n.charAt(0).toUpperCase()+n.slice(1);t.push(`[${r}]`);let i=new Map;for(let s of o){let a=s.stage;i.has(a)||i.set(a,[]),i.get(a).push(s)}for(let[s,a]of i){t.push(` ${s}/`);for(let c of a){let l=eE[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(`
1978
+ `)}function iE(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,o=e.filter(a=>a.status==="accepted").length,r=e.filter(a=>a.status==="closed").length,i=[`Total: ${e.length} | Open: ${t} | Mitigated: ${n} | Accepted: ${o} | Closed: ${r}`],s=e.filter(a=>a.status==="open");for(let a of s)i.push(` [OPEN] ${a.id}: ${a.description} (${a.likelihood}/${a.impact})`);return i.join(`
1979
+ `)}function sE(e){if(e.length===0)return"No gate transitions recorded";let t=e.filter(i=>i.action==="approved").length,n=e.filter(i=>i.action==="rejected").length,o=e.filter(i=>i.action==="bypassed").length,r=[`Total: ${e.length} | Approved: ${t} | Rejected: ${n} | Bypassed: ${o}`];for(let i of e){let s=i.phase.charAt(0).toUpperCase()+i.phase.slice(1);r.push(` [${i.action.toUpperCase()}] ${s} by ${i.actor}${i.reason?": "+i.reason:""}`)}return r.join(`
1980
+ `)}function aE(e){if(!e)return"Trust: Not initialized";let t=tE[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(`
1981
+ `)}function cE(e){if(e.length===0)return"No alignment checks recorded";let t=e.filter(r=>r.alignment_passed).length,n=e.filter(r=>!r.alignment_passed).length,o=[`Total: ${e.length} | Passed: ${t} | Failed: ${n}`];for(let r of e){let i=r.alignment_passed?"PASS":"FAIL",s=r.verification.conformance_score,a=r.verification.passed?"v":"x",c=r.validation.passed?"v":"x";o.push(` [${i}] ${r.source_artifact_id} -> ${r.target_artifact_id}: verification=${s}% [${a}] validation [${c}]`)}return o.join(`
1982
+ `)}function lE(e){return e?`Depth: ${e.recommended_depth} (score: ${e.total_score}/30)${e.skip_units?" [skip-units]":""}`:"Depth: Not assessed"}function uE(e){return e?`Risk Tier: ${e.tier} (${e.rationale})`:"Risk Tier: Not classified"}function dE(e){let t=e.artifacts.filter(r=>r.stage==="code-generation"),n=t.length;return n===0?"Bolts: 0/0":`Bolts: ${t.filter(r=>r.contract_status==="active"||r.contract_status==="fulfilled").length}/${n} complete`}function pE(e,t){let n=e.artifacts.length,o=t.filter(i=>i.status!=="not_started");return`${t.filter(i=>i.percentage===100&&i.status==="complete").length}/${ja.length} phases complete | ${n} artifacts total`}var Da=["workspace-detection","reverse-engineering","requirements-analysis","user-stories","workflow-planning","application-design","units-generation"],fE={"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 mE(e,t){let n=Da.length,o=Da.filter(l=>e[l]?.status==="completed").length,r=Math.round(o/n*100),i=10,s=Math.round(r/100*i),c=[`Inception [${s>=i?"=".repeat(i):"=".repeat(s)+">"+"-".repeat(i-s-1)}] ${r}% (${o}/${n} stages)`];for(let l of Da){let u=e[l],d=fE[l];if(!u){c.push(` [ ] ${d}`);continue}if(u.status==="completed")c.push(` [x] ${d}`);else if(u.status==="skipped"){let f=u.skip_reason?` (${u.skip_reason})`:" (skipped)";c.push(` [-] ${d}${f}`)}else u.status==="in_progress"||l===t?c.push(` [ ] ${d} <- current`):c.push(` [ ] ${d}`)}return c.join(`
1983
+ `)}J();$t();Ee();var Qg=b(require("path"),1);function Xg(){S({name:"workflowStatusReporter",event:"UserPromptSubmit",priority:6,handler:async e=>{try{let t=e.directory||process.cwd(),n=e.prompt||"",r=(e.parts||[]).map(m=>m.text||"").join(" ")||n;if(!(r.includes("Show status of all active structured workflows")||r.includes("workflow-status")))return{continue:!0};let s=await te(t),a=null;for(let m of s){let p=await C(t,m);if(p&&p.status!=="complete"&&p.status!=="archived"&&p.status!=="deferred"){a=m;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=Qg.join(t,"aidlc-docs",a,"manifest.json"),l=D(c);if(!l){let m=await C(t,a),p=m?.current_phase||"unknown",g=m?.current_stage||"unknown";return{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:`<workflow-status>
1984
+ # Workflow Status: ${a}
1985
+
1986
+ Phase: ${p} | Stage: ${g}
1987
+
1988
+ Note: manifest.json not found. Detailed artifact tracking unavailable. The workflow is active and can proceed normally.
1989
+ </workflow-status>`}}}let u=we(t),d=await C(t,a);return{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:`<workflow-status>
1990
+ ${zg(l,u,d).fullReport}
1991
+ </workflow-status>`}}}catch(t){return console.error("[Olympus Workflow Status] Error generating report:",t),{continue:!0}}}})}J();$t();Ee();var Zg=b(require("path"),1);function eh(){S({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 te(t),o=null,r=null;for(let p of n){let g=await C(t,p);if(g&&g.status!=="complete"&&g.status!=="archived"&&g.status!=="deferred"){o=p,r=g;break}}if(!o||!r)return{continue:!0};let i=Zg.join(t,"aidlc-docs",o,"manifest.json"),s=D(i);if(!s)return{continue:!0};let a=we(t),c=s.gate_audit.length>0?s.gate_audit[s.gate_audit.length-1]:null,l=null,u=nt(s),d=u.filter(p=>p.contract_status==="fulfilled"),f=qt(s),m=s.artifacts.filter(p=>p.stage==="intent");if(u.length>0&&d.length===u.length&&r.current_stage==="code-generation"&&s.phases.construction.status==="complete")l=`\u2713 All ${u.length} BOLTs executed and reviewed
1986
1992
  \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 p=u.length-d.length,g=d[d.length-1];l=`\u2713 BOLT ${d.length}/${u.length} complete \u2014 '${g.id}'
1987
1993
  Gate 4: Dev review of ${g.id} code
1988
1994
  \u2192 Current: ${p} remaining`}else if(f.length>0&&s.phases.construction.status==="in_progress"&&r.current_stage==="unit"&&c?.phase==="inception"&&c?.action==="approved"){let p=f.map(g=>g.id).join(", ");l=`\u2713 ${f.length} UNITs created: ${p}
@@ -1994,14 +2000,14 @@ ${f.length} UNITs decomposed | ${u.length} BOLTs queued
1994
2000
  \u2192 Ready: /ascent, /olympus, or /ultrawork to begin Construction${g}`}if(!l&&r.inception_stages&&r.current_inception_stage){let p=r.inception_stages,g=r.current_inception_stage;if(p[g]?.status==="completed"){let w=Object.values(p).filter(k=>k.status==="completed").length;l=`Inception stage '${g}' complete (${w}/7)
1995
2001
  \u2192 Next: continue inception pipeline`}}if(l)return{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`<workflow-transition>
1996
2002
  ${l}
1997
- </workflow-transition>`}}}catch(t){console.error("[Olympus Workflow Transition] Error:",t)}return{continue:!0}}})}var Zg=!1;function eh(){Zg||(Ag(),zg(),Sp(),$p(),Zp(),Bf(),Tm(),Um(),Gm(),Zm(),eg(),lg(),mg(),vg(),$g(),Ng(),Hg(),Ig(),Xg(),Yg(),Zg=!0)}var ei=require("fs"),lh=require("os"),Zr=require("path");function zr(e,t=!1){let n=e.length,o=0,r="",i=0,s=16,a=0,c=0,l=0,u=0,d=0;function f(k,A){let v=0,R=0;for(;v<k||!A;){let C=e.charCodeAt(o);if(C>=48&&C<=57)R=R*16+C-48;else if(C>=65&&C<=70)R=R*16+C-65+10;else if(C>=97&&C<=102)R=R*16+C-97+10;else break;o++,v++}return v<k&&(R=-1),R}function m(k){o=k,r="",i=0,s=16,d=0}function p(){let k=o;if(e.charCodeAt(o)===48)o++;else for(o++;o<e.length&&Kn(e.charCodeAt(o));)o++;if(o<e.length&&e.charCodeAt(o)===46)if(o++,o<e.length&&Kn(e.charCodeAt(o)))for(o++;o<e.length&&Kn(e.charCodeAt(o));)o++;else return d=3,e.substring(k,o);let A=o;if(o<e.length&&(e.charCodeAt(o)===69||e.charCodeAt(o)===101))if(o++,(o<e.length&&e.charCodeAt(o)===43||e.charCodeAt(o)===45)&&o++,o<e.length&&Kn(e.charCodeAt(o))){for(o++;o<e.length&&Kn(e.charCodeAt(o));)o++;A=o}else d=3;return e.substring(k,A)}function g(){let k="",A=o;for(;;){if(o>=n){k+=e.substring(A,o),d=2;break}let v=e.charCodeAt(o);if(v===34){k+=e.substring(A,o),o++;break}if(v===92){if(k+=e.substring(A,o),o++,o>=n){d=2;break}switch(e.charCodeAt(o++)){case 34:k+='"';break;case 92:k+="\\";break;case 47:k+="/";break;case 98:k+="\b";break;case 102:k+="\f";break;case 110:k+=`
1998
- `;break;case 114:k+="\r";break;case 116:k+=" ";break;case 117:let C=f(4,!0);C>=0?k+=String.fromCharCode(C):d=4;break;default:d=5}A=o;continue}if(v>=0&&v<=31)if(Co(v)){k+=e.substring(A,o),d=2;break}else d=6;o++}return k}function h(){if(r="",d=0,i=o,c=a,u=l,o>=n)return i=n,s=17;let k=e.charCodeAt(o);if(Da(k)){do o++,r+=String.fromCharCode(k),k=e.charCodeAt(o);while(Da(k));return s=15}if(Co(k))return o++,r+=String.fromCharCode(k),k===13&&e.charCodeAt(o)===10&&(o++,r+=`
1999
- `),a++,l=o,s=14;switch(k){case 123:return o++,s=1;case 125:return o++,s=2;case 91:return o++,s=3;case 93:return o++,s=4;case 58:return o++,s=6;case 44:return o++,s=5;case 34:return o++,r=g(),s=10;case 47:let A=o-1;if(e.charCodeAt(o+1)===47){for(o+=2;o<n&&!Co(e.charCodeAt(o));)o++;return r=e.substring(A,o),s=12}if(e.charCodeAt(o+1)===42){o+=2;let v=n-1,R=!1;for(;o<v;){let C=e.charCodeAt(o);if(C===42&&e.charCodeAt(o+1)===47){o+=2,R=!0;break}o++,Co(C)&&(C===13&&e.charCodeAt(o)===10&&o++,a++,l=o)}return R||(o++,d=1),r=e.substring(A,o),s=13}return r+=String.fromCharCode(k),o++,s=16;case 45:if(r+=String.fromCharCode(k),o++,o===n||!Kn(e.charCodeAt(o)))return s=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return r+=p(),s=11;default:for(;o<n&&y(k);)o++,k=e.charCodeAt(o);if(i!==o){switch(r=e.substring(i,o),r){case"true":return s=8;case"false":return s=9;case"null":return s=7}return s=16}return r+=String.fromCharCode(k),o++,s=16}}function y(k){if(Da(k)||Co(k))return!1;switch(k){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}function w(){let k;do k=h();while(k>=12&&k<=15);return k}return{setPosition:m,getPosition:()=>o,scan:t?w:h,getToken:()=>s,getTokenValue:()=>r,getTokenOffset:()=>i,getTokenLength:()=>o-i,getTokenStartLine:()=>c,getTokenStartCharacter:()=>i-u,getTokenError:()=>d}}function Da(e){return e===32||e===9}function Co(e){return e===10||e===13}function Kn(e){return e>=48&&e<=57}var th;(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"})(th||(th={}));var mE=new Array(20).fill(0).map((e,t)=>" ".repeat(t)),Jn=200,gE={" ":{"\n":new Array(Jn).fill(0).map((e,t)=>`
2003
+ </workflow-transition>`}}}catch(t){console.error("[Olympus Workflow Transition] Error:",t)}return{continue:!0}}})}var th=!1;function nh(){th||(xg(),Xg(),Tp(),Dp(),tf(),Vf(),bm(),Hm(),qm(),tg(),ng(),dg(),hg(),Eg(),Dg(),jg(),Bg(),Og(),eh(),Jg(),th=!0)}var ei=require("fs"),dh=require("os"),Zr=require("path");function zr(e,t=!1){let n=e.length,o=0,r="",i=0,s=16,a=0,c=0,l=0,u=0,d=0;function f(k,A){let v=0,R=0;for(;v<k||!A;){let I=e.charCodeAt(o);if(I>=48&&I<=57)R=R*16+I-48;else if(I>=65&&I<=70)R=R*16+I-65+10;else if(I>=97&&I<=102)R=R*16+I-97+10;else break;o++,v++}return v<k&&(R=-1),R}function m(k){o=k,r="",i=0,s=16,d=0}function p(){let k=o;if(e.charCodeAt(o)===48)o++;else for(o++;o<e.length&&Kn(e.charCodeAt(o));)o++;if(o<e.length&&e.charCodeAt(o)===46)if(o++,o<e.length&&Kn(e.charCodeAt(o)))for(o++;o<e.length&&Kn(e.charCodeAt(o));)o++;else return d=3,e.substring(k,o);let A=o;if(o<e.length&&(e.charCodeAt(o)===69||e.charCodeAt(o)===101))if(o++,(o<e.length&&e.charCodeAt(o)===43||e.charCodeAt(o)===45)&&o++,o<e.length&&Kn(e.charCodeAt(o))){for(o++;o<e.length&&Kn(e.charCodeAt(o));)o++;A=o}else d=3;return e.substring(k,A)}function g(){let k="",A=o;for(;;){if(o>=n){k+=e.substring(A,o),d=2;break}let v=e.charCodeAt(o);if(v===34){k+=e.substring(A,o),o++;break}if(v===92){if(k+=e.substring(A,o),o++,o>=n){d=2;break}switch(e.charCodeAt(o++)){case 34:k+='"';break;case 92:k+="\\";break;case 47:k+="/";break;case 98:k+="\b";break;case 102:k+="\f";break;case 110:k+=`
2004
+ `;break;case 114:k+="\r";break;case 116:k+=" ";break;case 117:let I=f(4,!0);I>=0?k+=String.fromCharCode(I):d=4;break;default:d=5}A=o;continue}if(v>=0&&v<=31)if(Io(v)){k+=e.substring(A,o),d=2;break}else d=6;o++}return k}function h(){if(r="",d=0,i=o,c=a,u=l,o>=n)return i=n,s=17;let k=e.charCodeAt(o);if(Ma(k)){do o++,r+=String.fromCharCode(k),k=e.charCodeAt(o);while(Ma(k));return s=15}if(Io(k))return o++,r+=String.fromCharCode(k),k===13&&e.charCodeAt(o)===10&&(o++,r+=`
2005
+ `),a++,l=o,s=14;switch(k){case 123:return o++,s=1;case 125:return o++,s=2;case 91:return o++,s=3;case 93:return o++,s=4;case 58:return o++,s=6;case 44:return o++,s=5;case 34:return o++,r=g(),s=10;case 47:let A=o-1;if(e.charCodeAt(o+1)===47){for(o+=2;o<n&&!Io(e.charCodeAt(o));)o++;return r=e.substring(A,o),s=12}if(e.charCodeAt(o+1)===42){o+=2;let v=n-1,R=!1;for(;o<v;){let I=e.charCodeAt(o);if(I===42&&e.charCodeAt(o+1)===47){o+=2,R=!0;break}o++,Io(I)&&(I===13&&e.charCodeAt(o)===10&&o++,a++,l=o)}return R||(o++,d=1),r=e.substring(A,o),s=13}return r+=String.fromCharCode(k),o++,s=16;case 45:if(r+=String.fromCharCode(k),o++,o===n||!Kn(e.charCodeAt(o)))return s=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return r+=p(),s=11;default:for(;o<n&&y(k);)o++,k=e.charCodeAt(o);if(i!==o){switch(r=e.substring(i,o),r){case"true":return s=8;case"false":return s=9;case"null":return s=7}return s=16}return r+=String.fromCharCode(k),o++,s=16}}function y(k){if(Ma(k)||Io(k))return!1;switch(k){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}function w(){let k;do k=h();while(k>=12&&k<=15);return k}return{setPosition:m,getPosition:()=>o,scan:t?w:h,getToken:()=>s,getTokenValue:()=>r,getTokenOffset:()=>i,getTokenLength:()=>o-i,getTokenStartLine:()=>c,getTokenStartCharacter:()=>i-u,getTokenError:()=>d}}function Ma(e){return e===32||e===9}function Io(e){return e===10||e===13}function Kn(e){return e>=48&&e<=57}var oh;(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"})(oh||(oh={}));var hE=new Array(20).fill(0).map((e,t)=>" ".repeat(t)),Jn=200,yE={" ":{"\n":new Array(Jn).fill(0).map((e,t)=>`
2000
2006
  `+" ".repeat(t)),"\r":new Array(Jn).fill(0).map((e,t)=>"\r"+" ".repeat(t)),"\r\n":new Array(Jn).fill(0).map((e,t)=>`\r
2001
2007
  `+" ".repeat(t))}," ":{"\n":new Array(Jn).fill(0).map((e,t)=>`
2002
2008
  `+" ".repeat(t)),"\r":new Array(Jn).fill(0).map((e,t)=>"\r"+" ".repeat(t)),"\r\n":new Array(Jn).fill(0).map((e,t)=>`\r
2003
- `+" ".repeat(t))}};var Qr;(function(e){e.DEFAULT={allowTrailingComma:!1}})(Qr||(Qr={}));function nh(e,t=[],n=Qr.DEFAULT){let o=null,r=[],i=[];function s(c){Array.isArray(r)?r.push(c):o!==null&&(r[o]=c)}return oh(e,{onObjectBegin:()=>{let c={};s(c),i.push(r),r=c,o=null},onObjectProperty:c=>{o=c},onObjectEnd:()=>{r=i.pop()},onArrayBegin:()=>{let c=[];s(c),i.push(r),r=c,o=null},onArrayEnd:()=>{r=i.pop()},onLiteralValue:s,onError:(c,l,u)=>{t.push({error:c,offset:l,length:u})}},n),r[0]}function oh(e,t,n=Qr.DEFAULT){let o=zr(e,!1),r=[],i=0;function s(E){return E?()=>i===0&&E(o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter()):()=>!0}function a(E){return E?N=>i===0&&E(N,o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter()):()=>!0}function c(E){return E?N=>i===0&&E(N,o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter(),()=>r.slice()):()=>!0}function l(E){return E?()=>{i>0?i++:E(o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter(),()=>r.slice())===!1&&(i=1)}:()=>!0}function u(E){return E?()=>{i>0&&i--,i===0&&E(o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter())}:()=>!0}let d=l(t.onObjectBegin),f=c(t.onObjectProperty),m=u(t.onObjectEnd),p=l(t.onArrayBegin),g=u(t.onArrayEnd),h=c(t.onLiteralValue),y=a(t.onSeparator),w=s(t.onComment),k=a(t.onError),A=n&&n.disallowComments,v=n&&n.allowTrailingComma;function R(){for(;;){let E=o.scan();switch(o.getTokenError()){case 4:C(14);break;case 5:C(15);break;case 3:C(13);break;case 1:A||C(11);break;case 2:C(12);break;case 6:C(16);break}switch(E){case 12:case 13:A?C(10):w();break;case 16:C(1);break;case 15:case 14:break;default:return E}}}function C(E,N=[],Y=[]){if(k(E),N.length+Y.length>0){let H=o.getToken();for(;H!==17;){if(N.indexOf(H)!==-1){R();break}else if(Y.indexOf(H)!==-1)break;H=R()}}}function Z(E){let N=o.getTokenValue();return E?h(N):(f(N),r.push(N)),R(),!0}function S(){switch(o.getToken()){case 11:let E=o.getTokenValue(),N=Number(E);isNaN(N)&&(C(2),N=0),h(N);break;case 7:h(null);break;case 8:h(!0);break;case 9:h(!1);break;default:return!1}return R(),!0}function O(){return o.getToken()!==10?(C(3,[],[2,5]),!1):(Z(!1),o.getToken()===6?(y(":"),R(),M()||C(4,[],[2,5])):C(5,[],[2,5]),r.pop(),!0)}function x(){d(),R();let E=!1;for(;o.getToken()!==2&&o.getToken()!==17;){if(o.getToken()===5){if(E||C(4,[],[]),y(","),R(),o.getToken()===2&&v)break}else E&&C(6,[],[]);O()||C(4,[],[2,5]),E=!0}return m(),o.getToken()!==2?C(7,[2],[]):R(),!0}function P(){p(),R();let E=!0,N=!1;for(;o.getToken()!==4&&o.getToken()!==17;){if(o.getToken()===5){if(N||C(4,[],[]),y(","),R(),o.getToken()===4&&v)break}else N&&C(6,[],[]);E?(r.push(0),E=!1):r[r.length-1]++,M()||C(4,[],[4,5]),N=!0}return g(),E||r.pop(),o.getToken()!==4?C(8,[4],[]):R(),!0}function M(){switch(o.getToken()){case 3:return P();case 1:return x();case 10:return Z(!0);default:return S()}}return R(),o.getToken()===17?n.allowEmptyContent?!0:(C(4,[],[]),!1):M()?(o.getToken()!==17&&C(9,[],[]),!0):(C(4,[],[]),!1)}var rh;(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"})(rh||(rh={}));var ih;(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"})(ih||(ih={}));var ah=nh;var sh;(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"})(sh||(sh={}));var TE={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:_a,customPricing:[]}};function EE(){return{user:(0,Zr.join)((0,lh.homedir)(),".claude","olympus","config.jsonc"),project:(0,Zr.join)(process.cwd(),".claude","olympus.jsonc")}}function ch(e){if(!(0,ei.existsSync)(e))return null;try{let t=(0,ei.readFileSync)(e,"utf-8"),n=[],o=ah(t,n,{allowTrailingComma:!0,allowEmptyContent:!0});return n.length>0&&console.warn(`Warning: Parse errors in ${e}:`,n),o}catch(t){return console.error(`Error loading config from ${e}:`,t),null}}function Xr(e,t){let n={...e};for(let o of Object.keys(t)){let r=t[o],i=n[o];r!==void 0&&typeof r=="object"&&r!==null&&!Array.isArray(r)&&typeof i=="object"&&i!==null&&!Array.isArray(i)?n[o]=Xr(i,r):r!==void 0&&(n[o]=r)}return n}function bE(){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 uh(){let e=EE(),t={...TE},n=ch(e.user);n&&(t=Xr(t,n));let o=ch(e.project);o&&(t=Xr(t,o));let r=bE();return t=Xr(t,r),t}function CE(e){let t=e.hooks;return t&&typeof t.timeoutMs=="number"?t.timeoutMs:5e3}function IE(e,t){let n=e.hooks;if(n&&typeof n.enabled=="boolean"&&!n.enabled)return!1;if(n&&t in n){let o=n[t];if(typeof o=="object"&&o!==null){let r=o.enabled;if(typeof r=="boolean")return r}}return!0}async function RE(e,t){return Promise.race([Promise.resolve(e()),new Promise(n=>setTimeout(()=>n(null),t))])}function OE(e,t){return!e||!t?!0:(typeof e=="string"?new RegExp(e,"i"):e).test(t)}async function dh(e,t){let n=uh(),o=Ma(e),r=CE(n),i=!0,s=[],a,c=t.toolInput,l=t.messages;for(let u of o)if(IE(n,u.name)&&OE(u.matcher,t.toolName))try{let d=await RE(()=>u.handler({...t,toolInput:c,messages:l}),r);if(d===null){console.error(`[hook-router] ${u.name} timed out after ${r}ms`);continue}d.continue||(i=!1,a=d.stopReason),d.message&&s.push(d.message),d.hookSpecificOutput?.additionalContext&&s.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:i,message:s.length>0?s.join(`
2009
+ `+" ".repeat(t))}};var Qr;(function(e){e.DEFAULT={allowTrailingComma:!1}})(Qr||(Qr={}));function rh(e,t=[],n=Qr.DEFAULT){let o=null,r=[],i=[];function s(c){Array.isArray(r)?r.push(c):o!==null&&(r[o]=c)}return ih(e,{onObjectBegin:()=>{let c={};s(c),i.push(r),r=c,o=null},onObjectProperty:c=>{o=c},onObjectEnd:()=>{r=i.pop()},onArrayBegin:()=>{let c=[];s(c),i.push(r),r=c,o=null},onArrayEnd:()=>{r=i.pop()},onLiteralValue:s,onError:(c,l,u)=>{t.push({error:c,offset:l,length:u})}},n),r[0]}function ih(e,t,n=Qr.DEFAULT){let o=zr(e,!1),r=[],i=0;function s(E){return E?()=>i===0&&E(o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter()):()=>!0}function a(E){return E?N=>i===0&&E(N,o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter()):()=>!0}function c(E){return E?N=>i===0&&E(N,o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter(),()=>r.slice()):()=>!0}function l(E){return E?()=>{i>0?i++:E(o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter(),()=>r.slice())===!1&&(i=1)}:()=>!0}function u(E){return E?()=>{i>0&&i--,i===0&&E(o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter())}:()=>!0}let d=l(t.onObjectBegin),f=c(t.onObjectProperty),m=u(t.onObjectEnd),p=l(t.onArrayBegin),g=u(t.onArrayEnd),h=c(t.onLiteralValue),y=a(t.onSeparator),w=s(t.onComment),k=a(t.onError),A=n&&n.disallowComments,v=n&&n.allowTrailingComma;function R(){for(;;){let E=o.scan();switch(o.getTokenError()){case 4:I(14);break;case 5:I(15);break;case 3:I(13);break;case 1:A||I(11);break;case 2:I(12);break;case 6:I(16);break}switch(E){case 12:case 13:A?I(10):w();break;case 16:I(1);break;case 15:case 14:break;default:return E}}}function I(E,N=[],Y=[]){if(k(E),N.length+Y.length>0){let H=o.getToken();for(;H!==17;){if(N.indexOf(H)!==-1){R();break}else if(Y.indexOf(H)!==-1)break;H=R()}}}function Z(E){let N=o.getTokenValue();return E?h(N):(f(N),r.push(N)),R(),!0}function _(){switch(o.getToken()){case 11:let E=o.getTokenValue(),N=Number(E);isNaN(N)&&(I(2),N=0),h(N);break;case 7:h(null);break;case 8:h(!0);break;case 9:h(!1);break;default:return!1}return R(),!0}function O(){return o.getToken()!==10?(I(3,[],[2,5]),!1):(Z(!1),o.getToken()===6?(y(":"),R(),M()||I(4,[],[2,5])):I(5,[],[2,5]),r.pop(),!0)}function x(){d(),R();let E=!1;for(;o.getToken()!==2&&o.getToken()!==17;){if(o.getToken()===5){if(E||I(4,[],[]),y(","),R(),o.getToken()===2&&v)break}else E&&I(6,[],[]);O()||I(4,[],[2,5]),E=!0}return m(),o.getToken()!==2?I(7,[2],[]):R(),!0}function P(){p(),R();let E=!0,N=!1;for(;o.getToken()!==4&&o.getToken()!==17;){if(o.getToken()===5){if(N||I(4,[],[]),y(","),R(),o.getToken()===4&&v)break}else N&&I(6,[],[]);E?(r.push(0),E=!1):r[r.length-1]++,M()||I(4,[],[4,5]),N=!0}return g(),E||r.pop(),o.getToken()!==4?I(8,[4],[]):R(),!0}function M(){switch(o.getToken()){case 3:return P();case 1:return x();case 10:return Z(!0);default:return _()}}return R(),o.getToken()===17?n.allowEmptyContent?!0:(I(4,[],[]),!1):M()?(o.getToken()!==17&&I(9,[],[]),!0):(I(4,[],[]),!1)}var sh;(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"})(sh||(sh={}));var ah;(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"})(ah||(ah={}));var lh=rh;var ch;(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"})(ch||(ch={}));var bE={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:va,customPricing:[]}};function CE(){return{user:(0,Zr.join)((0,dh.homedir)(),".claude","olympus","config.jsonc"),project:(0,Zr.join)(process.cwd(),".claude","olympus.jsonc")}}function uh(e){if(!(0,ei.existsSync)(e))return null;try{let t=(0,ei.readFileSync)(e,"utf-8"),n=[],o=lh(t,n,{allowTrailingComma:!0,allowEmptyContent:!0});return n.length>0&&console.warn(`Warning: Parse errors in ${e}:`,n),o}catch(t){return console.error(`Error loading config from ${e}:`,t),null}}function Xr(e,t){let n={...e};for(let o of Object.keys(t)){let r=t[o],i=n[o];r!==void 0&&typeof r=="object"&&r!==null&&!Array.isArray(r)&&typeof i=="object"&&i!==null&&!Array.isArray(i)?n[o]=Xr(i,r):r!==void 0&&(n[o]=r)}return n}function IE(){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 ph(){let e=CE(),t={...bE},n=uh(e.user);n&&(t=Xr(t,n));let o=uh(e.project);o&&(t=Xr(t,o));let r=IE();return t=Xr(t,r),t}function RE(e){let t=e.hooks;return t&&typeof t.timeoutMs=="number"?t.timeoutMs:5e3}function OE(e,t){let n=e.hooks;if(n&&typeof n.enabled=="boolean"&&!n.enabled)return!1;if(n&&t in n){let o=n[t];if(typeof o=="object"&&o!==null){let r=o.enabled;if(typeof r=="boolean")return r}}return!0}async function AE(e,t){return Promise.race([Promise.resolve(e()),new Promise(n=>setTimeout(()=>n(null),t))])}function PE(e,t){return!e||!t?!0:(typeof e=="string"?new RegExp(e,"i"):e).test(t)}async function fh(e,t){let n=ph(),o=Fa(e),r=RE(n),i=!0,s=[],a,c=t.toolInput,l=t.messages;for(let u of o)if(OE(n,u.name)&&PE(u.matcher,t.toolName))try{let d=await AE(()=>u.handler({...t,toolInput:c,messages:l}),r);if(d===null){console.error(`[hook-router] ${u.name} timed out after ${r}ms`);continue}d.continue||(i=!1,a=d.stopReason),d.message&&s.push(d.message),d.hookSpecificOutput?.additionalContext&&s.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:i,message:s.length>0?s.join(`
2004
2010
 
2005
2011
  ---
2006
2012
 
2007
- `):void 0,stopReason:a,modifiedInput:c!==t.toolInput?c:void 0,modifiedMessages:l!==t.messages?l:void 0}}eh();async function AE(){return process.stdin.isTTY?"{}":new Promise(e=>{let t=[],n=!1,o=setTimeout(()=>{process.stdin.pause(),process.stdin.destroy(),e(n?Buffer.concat(t).toString("utf-8"):"{}")},1e3);process.stdin.on("data",r=>{n=!0,t.push(r)}),process.stdin.on("end",()=>{clearTimeout(o),e(n?Buffer.concat(t).toString("utf-8"):"{}")}),process.stdin.on("error",()=>{clearTimeout(o),e("{}")}),process.stdin.resume()})}async function ph(){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],o=await AE(),r;try{let a=JSON.parse(o);r={...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{r={}}let i=await dh(n,r),s={continue:i.continue};i.stopReason&&(s.stopReason=i.stopReason),i.message&&(s.hookSpecificOutput={hookEventName:n,additionalContext:i.message}),console.log(JSON.stringify(s)),process.exit(0)}var ti=process.argv[1]||"",PE=ti.endsWith("entry.ts")||ti.endsWith("entry.js")||ti.endsWith("olympus-hooks.mjs")||ti.includes("olympus-hooks");PE&&ph().catch(e=>{console.error("[olympus-hooks] Fatal error:",e),process.exit(1)});0&&(module.exports={main});
2013
+ `):void 0,stopReason:a,modifiedInput:c!==t.toolInput?c:void 0,modifiedMessages:l!==t.messages?l:void 0}}nh();async function xE(){return process.stdin.isTTY?"{}":new Promise(e=>{let t=[],n=!1,o=setTimeout(()=>{process.stdin.pause(),process.stdin.destroy(),e(n?Buffer.concat(t).toString("utf-8"):"{}")},1e3);process.stdin.on("data",r=>{n=!0,t.push(r)}),process.stdin.on("end",()=>{clearTimeout(o),e(n?Buffer.concat(t).toString("utf-8"):"{}")}),process.stdin.on("error",()=>{clearTimeout(o),e("{}")}),process.stdin.resume()})}async function mh(){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],o=await xE(),r;try{let a=JSON.parse(o);r={...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{r={}}let i=await fh(n,r),s={continue:i.continue};i.stopReason&&(s.stopReason=i.stopReason),i.message&&(s.hookSpecificOutput={hookEventName:n,additionalContext:i.message}),console.log(JSON.stringify(s)),process.exit(0)}var ti=process.argv[1]||"",$E=ti.endsWith("entry.ts")||ti.endsWith("entry.js")||ti.endsWith("olympus-hooks.mjs")||ti.includes("olympus-hooks");$E&&mh().catch(e=>{console.error("[olympus-hooks] Fatal error:",e),process.exit(1)});0&&(module.exports={main});