olympus-ai 4.4.13 → 4.4.15
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.
- package/.claude-plugin/plugin.json +1 -1
- package/dist/features/workflow-engine/checkpoint.d.ts.map +1 -1
- package/dist/features/workflow-engine/checkpoint.js +33 -6
- package/dist/features/workflow-engine/checkpoint.js.map +1 -1
- package/dist/features/workflow-engine/construction/executor.d.ts +38 -3
- package/dist/features/workflow-engine/construction/executor.d.ts.map +1 -1
- package/dist/features/workflow-engine/construction/executor.js +245 -3
- package/dist/features/workflow-engine/construction/executor.js.map +1 -1
- package/dist/features/workflow-engine/construction/regression-baseline.d.ts +76 -0
- package/dist/features/workflow-engine/construction/regression-baseline.d.ts.map +1 -0
- package/dist/features/workflow-engine/construction/regression-baseline.js +274 -0
- package/dist/features/workflow-engine/construction/regression-baseline.js.map +1 -0
- package/dist/features/workflow-engine/construction/regression-categorizer.d.ts +44 -0
- package/dist/features/workflow-engine/construction/regression-categorizer.d.ts.map +1 -0
- package/dist/features/workflow-engine/construction/regression-categorizer.js +54 -0
- package/dist/features/workflow-engine/construction/regression-categorizer.js.map +1 -0
- package/dist/features/workflow-engine/construction/validators/index.d.ts +6 -0
- package/dist/features/workflow-engine/construction/validators/index.d.ts.map +1 -0
- package/dist/features/workflow-engine/construction/validators/index.js +4 -0
- package/dist/features/workflow-engine/construction/validators/index.js.map +1 -0
- package/dist/features/workflow-engine/construction/validators/pipeline.d.ts +10 -0
- package/dist/features/workflow-engine/construction/validators/pipeline.d.ts.map +1 -0
- package/dist/features/workflow-engine/construction/validators/pipeline.js +84 -0
- package/dist/features/workflow-engine/construction/validators/pipeline.js.map +1 -0
- package/dist/features/workflow-engine/construction/validators/quality-patterns.d.ts +18 -0
- package/dist/features/workflow-engine/construction/validators/quality-patterns.d.ts.map +1 -0
- package/dist/features/workflow-engine/construction/validators/quality-patterns.js +245 -0
- package/dist/features/workflow-engine/construction/validators/quality-patterns.js.map +1 -0
- package/dist/features/workflow-engine/construction/validators/quality-validator.d.ts +3 -0
- package/dist/features/workflow-engine/construction/validators/quality-validator.d.ts.map +1 -0
- package/dist/features/workflow-engine/construction/validators/quality-validator.js +132 -0
- package/dist/features/workflow-engine/construction/validators/quality-validator.js.map +1 -0
- package/dist/features/workflow-engine/construction/validators/types.d.ts +26 -0
- package/dist/features/workflow-engine/construction/validators/types.d.ts.map +1 -0
- package/dist/features/workflow-engine/construction/validators/types.js +2 -0
- package/dist/features/workflow-engine/construction/validators/types.js.map +1 -0
- package/dist/features/workflow-engine/index.d.ts +3 -1
- package/dist/features/workflow-engine/index.d.ts.map +1 -1
- package/dist/features/workflow-engine/index.js +1 -0
- package/dist/features/workflow-engine/index.js.map +1 -1
- package/dist/features/workflow-engine/phase-types.d.ts +73 -1
- package/dist/features/workflow-engine/phase-types.d.ts.map +1 -1
- package/dist/hooks/olympus-hooks.cjs +334 -280
- package/dist/hooks/registry.d.ts +18 -0
- package/dist/hooks/registry.d.ts.map +1 -1
- package/dist/hooks/registry.js +18 -0
- package/dist/hooks/registry.js.map +1 -1
- package/dist/installer/index.d.ts +1 -1
- package/dist/installer/index.js +1 -1
- package/package.json +1 -1
- package/resources/agents/frontend-engineer-high.md +12 -0
- package/resources/agents/olympian-high.md +77 -1
- package/resources/agents/olympian.md +31 -7
- package/resources/claude-md.md +44 -0
- package/resources/config/risk-keywords.json +5 -0
- package/resources/rules/common/pathway-behaviors.md +100 -0
- package/resources/rules/common/terminal-formatting.md +161 -0
- package/resources/rules/construction/build-and-test.md +58 -0
- package/resources/rules/construction/code-generation.md +26 -5
- package/resources/rules/construction/test-generation.md +82 -0
- package/resources/skills/continue/SKILL.md +4 -0
|
@@ -1,31 +1,52 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// Olympus Hooks Bundle - Generated by esbuild
|
|
3
|
-
"use strict";var
|
|
4
|
-
`).filter(
|
|
5
|
-
`,"utf-8");return}catch(n){console.error("[Olympus Learning] Project write failed, using global fallback:",n)}cn();let t=(0,
|
|
6
|
-
`,"utf-8")}function
|
|
7
|
-
`).filter(o=>o.trim()).map(o=>JSON.parse(o)):[]}function
|
|
8
|
-
`,"utf-8");return}catch(o){console.error("[Olympus Learning] Project session summary write failed, using global fallback:",o)}cn();let n=(0,
|
|
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;
|
|
3
|
+
"use strict";var vh=Object.create;var Po=Object.defineProperty;var Th=Object.getOwnPropertyDescriptor;var Eh=Object.getOwnPropertyNames;var bh=Object.getPrototypeOf,Ch=Object.prototype.hasOwnProperty;var B=(e,t)=>()=>(e&&(t=e(e=0)),t);var W=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Je=(e,t)=>{for(var n in t)Po(e,n,{get:t[n],enumerable:!0})},Ua=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Eh(t))!Ch.call(e,r)&&r!==n&&Po(e,r,{get:()=>t[r],enumerable:!(o=Th(t,r))||o.enumerable});return e};var E=(e,t,n)=>(n=e!=null?vh(bh(e)):{},Ua(t||!e||!e.__esModule?Po(n,"default",{value:e,enumerable:!0}):n,e)),Rh=e=>Ua(Po({},"__esModule",{value:!0}),e);var hs,_c=B(()=>{"use strict";hs={maxAgeInDays:30,maxArchiveCount:5}});function ys(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 ys(e)?.total_tokens||0}var Sc=B(()=>{"use strict"});function Kh(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,Tc.createHash)("sha256").update(e).digest("hex").substring(0,8);return`${n}-${o}`}function Wt(e){return(0,sn.join)(ce(),"projects",Kh(e))}function ks(e){try{(0,vc.mkdirSync)(Wt(e),{recursive:!0})}catch(t){t.code!=="EEXIST"&&console.error("Failed to create project directory:",t)}}var sn,Yh,vc,Tc,Ec=B(()=>{"use strict";sn=require("path"),Yh=require("child_process"),vc=require("fs"),Tc=require("crypto");fe();Ae()});function ce(){return process.env.OLYMPUS_TEST_LEARNING_DIR?process.env.OLYMPUS_TEST_LEARNING_DIR:(0,te.join)((0,Cc.homedir)(),".claude","olympus","learning")}function Xe(e){return(0,te.join)(e,".olympus","learning")}function Ic(e){let t=(0,te.resolve)(e);return(0,Rc.createHash)("sha256").update(t).digest("hex").substring(0,16)}function cn(e){let t=ce();if((0,q.existsSync)(t)||(0,q.mkdirSync)(t,{recursive:!0}),e){let n=Xe(e);(0,q.existsSync)(n)||(0,q.mkdirSync)(n,{recursive:!0})}}function zh(e,t=hs){try{let n=(0,te.dirname)(e),o=(0,te.basename)(e,".jsonl"),r=(0,q.readdirSync)(n),s=new RegExp(`^${o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\..*\\.old\\.jsonl$`),i=r.filter(d=>s.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,te.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<i.length;d++){let f=i[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=Jh,n=hs){if((0,q.existsSync)(e))try{let r=(0,q.readFileSync)(e,"utf-8").split(`
|
|
4
|
+
`).filter(s=>s.trim()).length;if(r>=t){let s=new Date().toISOString().replace(/[:.]/g,"-"),i=e.replace(".jsonl",`.${s}.old.jsonl`);(0,q.renameSync)(e,i),console.log(`[Olympus Learning] Archived ${r} entries to ${i}`),zh(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{ks(e.project_path);let n=(0,te.join)(Wt(e.project_path),"feedback-log.jsonl");an(n),(0,q.appendFileSync)(n,JSON.stringify(e)+`
|
|
5
|
+
`,"utf-8");return}catch(n){console.error("[Olympus Learning] Project write failed, using global fallback:",n)}cn();let t=(0,te.join)(ce(),"feedback-log.jsonl");an(t),(0,q.appendFileSync)(t,JSON.stringify(e)+`
|
|
6
|
+
`,"utf-8")}function Do(e){let t=e?(0,te.join)(Wt(e),"feedback-log.jsonl"):(0,te.join)(ce(),"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 Qh(e){let t=e.filter(r=>r.event_type==="revision"||r.event_type==="cancellation"),n=new Map;for(let r of t){let s=r.extracted_lesson||r.feedback_category||"unknown",i=n.get(s);i?(i.count++,i.examples.length<3&&i.examples.push(r.user_message.substring(0,100))):n.set(s,{count:1,examples:[r.user_message.substring(0,100)]})}let o=[];for(let[r,s]of n)s.count>=2&&o.push({pattern:r,count:s.count,examples:s.examples});return o}function Xh(e){let t=[];return e>=.85&&t.push("high success rate"),t}function Zh(e,t){let n=[];return e<.6&&n.push("low success rate"),t>2&&n.push("frequently cancelled"),n}function jo(e,t,n){let o=t.filter(p=>p.agent_used===e);if(o.length===0)return null;let r=o.length,s=o.filter(p=>p.event_type==="success").length,i=o.filter(p=>p.event_type==="revision").length,a=o.filter(p=>p.event_type==="cancellation").length,c=r>0?s/r:0,l,u=o.filter(p=>ys(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,O)=>v+rn(O),0),y=p.reduce((v,O)=>v+rn(O),0),w=g.reduce((v,O)=>v+rn(O),0),k=p.length>0?y/p.length:0,I=g.length>0?w/g.length:0;if(l={avg_tokens_per_success:k,avg_tokens_per_failure:I,total_tokens:h,invocation_count:u.length,efficiency_score:k,trend:"insufficient_data"},u.length>=10){let v=Math.floor(u.length/2),O=u.slice(0,v),R=u.slice(v),ee=O.reduce((x,M)=>x+rn(M),0)/O.length,P=R.reduce((x,M)=>x+rn(M),0)/R.length-ee,$=ee*.1;Math.abs(P)<$?l.trend="stable":P<0?l.trend="improving":l.trend="declining"}}let d={agent_name:e,total_invocations:r,success_count:s,revision_count:i,cancellation_count:a,success_rate:c,failure_patterns:Qh(o),strong_areas:Xh(c),weak_areas:Zh(c,a),last_updated:new Date().toISOString(),token_efficiency:l};if(n)try{let p=(0,te.join)(Wt(n),"agent-performance.json"),g=me(p,{});g[e]=d,Be(p,g)}catch(p){console.error("[Olympus Learning] Failed to write project agent performance:",p)}let f=(0,te.join)(ce(),"agent-performance.json"),m=me(f,{});return m[e]=d,Be(f,m),d}function ln(e){let t=e?(0,te.join)(Wt(e),"agent-performance.json"):(0,te.join)(ce(),"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 Be(e,t){try{let n=(0,te.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 Oc(e,t){if(t)try{ks(t);let o=(0,te.join)(Wt(t),"session-summaries.jsonl");an(o,bc),(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,te.join)(ce(),"session-summaries.jsonl");an(n,bc),(0,q.appendFileSync)(n,JSON.stringify(e)+`
|
|
9
|
+
`,"utf-8")}var Cc,te,q,Rc,Jh,bc,fe=B(()=>{"use strict";Cc=require("os"),te=require("path"),q=require("fs"),Rc=require("crypto");_c();Sc();Ec();Jh=1e4,bc=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 ws=B(()=>{"use strict"});function $c(e){return(0,Ac.join)(e,".olympus","session-state.json")}function Pc(e,t){let n=Ht();return{session_id:e||(0,xc.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=$c(e),o=me(n,null);if(!o)return Pc(t,e);let r=new Date(o.last_updated).getTime();if(Date.now()-r>ty)return Pc(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 i=Ht();o.token_budget={session_baseline:i,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 X(e,t){let n=$c(e);t.last_updated=new Date().toISOString(),Be(n,t)}function Nc(e,t,n){let o={prompt:t,timestamp:new Date().toISOString(),detected_feedback:n};return e.recent_prompts=[o,...e.recent_prompts].slice(0,ey),e.last_updated=new Date().toISOString(),e}function Dc(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 jc(e){return e.pending_completion=null,e.last_updated=new Date().toISOString(),e}function Mo(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 Mc(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 Lc(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 Fc(e){return e.token_budget&&(e.token_budget.warning_issued=!0,e.last_updated=new Date().toISOString()),e}function Uc(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 Wc(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 Hc(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 Ac,xc,ey,ty,Ae=B(()=>{"use strict";Ac=require("path");fe();xc=require("crypto");ws();ey=10,ty=1800*1e3});var le=W(Ss=>{"use strict";Ss.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,s)=>r!=null?o(r):n(s)),e.apply(this,t)})},"name",{value:e.name})};Ss.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 Kc=W((Jb,Yc)=>{var vt=require("constants"),oy=process.cwd,Lo=null,ry=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return Lo||(Lo=oy.call(process)),Lo};try{process.cwd()}catch{}typeof process.chdir=="function"&&(vs=process.chdir,process.chdir=function(e){Lo=null,vs.call(process,e)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,vs));var vs;Yc.exports=sy;function sy(e){vt.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&t(e),e.lutimes||n(e),e.chown=s(e.chown),e.fchown=s(e.fchown),e.lchown=s(e.lchown),e.chmod=o(e.chmod),e.fchmod=o(e.fchmod),e.lchmod=o(e.lchmod),e.chownSync=i(e.chownSync),e.fchownSync=i(e.fchownSync),e.lchownSync=i(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(){}),ry==="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,I){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(I,v,O){if(I&&I.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 s(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 i(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 Qc=W((zb,zc)=>{var Jc=require("stream").Stream;zc.exports=iy;function iy(e){return{ReadStream:t,WriteStream:n};function t(o,r){if(!(this instanceof t))return new t(o,r);Jc.call(this);var s=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 i=Object.keys(r),a=0,c=i.length;a<c;a++){var l=i[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(){s._read()});return}e.open(this.path,this.flags,this.mode,function(u,d){if(u){s.emit("error",u),s.readable=!1;return}s.fd=d,s.emit("open",d),s._read()})}function n(o,r){if(!(this instanceof n))return new n(o,r);Jc.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 s=Object.keys(r),i=0,a=s.length;i<a;i++){var c=s[i];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 Zc=W((Qb,Xc)=>{"use strict";Xc.exports=cy;var ay=Object.getPrototypeOf||function(e){return e.__proto__};function cy(e){if(e===null||typeof e!="object")return e;if(e instanceof Object)var t={__proto__:ay(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=W((Xb,bs)=>{var Z=require("fs"),ly=Kc(),uy=Qc(),dy=Zc(),Fo=require("util"),ge,Wo;typeof Symbol=="function"&&typeof Symbol.for=="function"?(ge=Symbol.for("graceful-fs.queue"),Wo=Symbol.for("graceful-fs.previous")):(ge="___graceful-fs.queue",Wo="___graceful-fs.previous");function py(){}function nl(e,t){Object.defineProperty(e,ge,{get:function(){return t}})}var Bt=py;Fo.debuglog?Bt=Fo.debuglog("gfs4"):/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&(Bt=function(){var e=Fo.format.apply(Fo,arguments);e="GFS4: "+e.split(/\n/).join(`
|
|
10
|
+
GFS4: `),console.error(e)});Z[ge]||(el=global[ge]||[],nl(Z,el),Z.close=(function(e){function t(n,o){return e.call(Z,n,function(r){r||tl(),typeof o=="function"&&o.apply(this,arguments)})}return Object.defineProperty(t,Wo,{value:e}),t})(Z.close),Z.closeSync=(function(e){function t(n){e.apply(Z,arguments),tl()}return Object.defineProperty(t,Wo,{value:e}),t})(Z.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&process.on("exit",function(){Bt(Z[ge]),require("assert").equal(Z[ge].length,0)}));var el;global[ge]||nl(global,Z[ge]);bs.exports=Ts(dy(Z));process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!Z.__patched&&(bs.exports=Ts(Z),Z.__patched=!0);function Ts(e){ly(e),e.gracefulify=Ts,e.createReadStream=v,e.createWriteStream=O;var t=e.readFile;e.readFile=n;function n(S,P,$){return typeof P=="function"&&($=P,P=null),x(S,P,$);function x(M,C,N,K){return t(M,C,function(H){H&&(H.code==="EMFILE"||H.code==="ENFILE")?un([x,[M,C,N],H,K||Date.now(),Date.now()]):typeof N=="function"&&N.apply(this,arguments)})}}var o=e.writeFile;e.writeFile=r;function r(S,P,$,x){return typeof $=="function"&&(x=$,$=null),M(S,P,$,x);function M(C,N,K,H,de){return o(C,N,K,function(Q){Q&&(Q.code==="EMFILE"||Q.code==="ENFILE")?un([M,[C,N,K,H],Q,de||Date.now(),Date.now()]):typeof H=="function"&&H.apply(this,arguments)})}}var s=e.appendFile;s&&(e.appendFile=i);function i(S,P,$,x){return typeof $=="function"&&(x=$,$=null),M(S,P,$,x);function M(C,N,K,H,de){return s(C,N,K,function(Q){Q&&(Q.code==="EMFILE"||Q.code==="ENFILE")?un([M,[C,N,K,H],Q,de||Date.now(),Date.now()]):typeof H=="function"&&H.apply(this,arguments)})}}var a=e.copyFile;a&&(e.copyFile=c);function c(S,P,$,x){return typeof $=="function"&&(x=$,$=0),M(S,P,$,x);function M(C,N,K,H,de){return a(C,N,K,function(Q){Q&&(Q.code==="EMFILE"||Q.code==="ENFILE")?un([M,[C,N,K,H],Q,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,P,$){typeof P=="function"&&($=P,P=null);var x=u.test(process.version)?function(N,K,H,de){return l(N,M(N,K,H,de))}:function(N,K,H,de){return l(N,K,M(N,K,H,de))};return x(S,P,$);function M(C,N,K,H){return function(de,Q){de&&(de.code==="EMFILE"||de.code==="ENFILE")?un([x,[C,N,K],de,H||Date.now(),Date.now()]):(Q&&Q.sort&&Q.sort(),typeof K=="function"&&K.call(this,de,Q))}}}if(process.version.substr(0,4)==="v0.8"){var f=uy(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=I),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,P){return this instanceof y?(m.apply(this,arguments),this):y.apply(Object.create(y.prototype),arguments)}function w(){var S=this;ee(S.path,S.flags,S.mode,function(P,$){P?(S.autoClose&&S.destroy(),S.emit("error",P)):(S.fd=$,S.emit("open",$),S.read())})}function k(S,P){return this instanceof k?(p.apply(this,arguments),this):k.apply(Object.create(k.prototype),arguments)}function I(){var S=this;ee(S.path,S.flags,S.mode,function(P,$){P?(S.destroy(),S.emit("error",P)):(S.fd=$,S.emit("open",$))})}function v(S,P){return new e.ReadStream(S,P)}function O(S,P){return new e.WriteStream(S,P)}var R=e.open;e.open=ee;function ee(S,P,$,x){return typeof $=="function"&&(x=$,$=null),M(S,P,$,x);function M(C,N,K,H,de){return R(C,N,K,function(Q,JE){Q&&(Q.code==="EMFILE"||Q.code==="ENFILE")?un([M,[C,N,K,H],Q,de||Date.now(),Date.now()]):typeof H=="function"&&H.apply(this,arguments)})}}return e}function un(e){Bt("ENQUEUE",e[0].name,e[1]),Z[ge].push(e),Es()}var Uo;function tl(){for(var e=Date.now(),t=0;t<Z[ge].length;++t)Z[ge][t].length>2&&(Z[ge][t][3]=e,Z[ge][t][4]=e);Es()}function Es(){if(clearTimeout(Uo),Uo=void 0,Z[ge].length!==0){var e=Z[ge].shift(),t=e[0],n=e[1],o=e[2],r=e[3],s=e[4];if(r===void 0)Bt("RETRY",t.name,n),t.apply(null,n);else if(Date.now()-r>=6e4){Bt("TIMEOUT",t.name,n);var i=n.pop();typeof i=="function"&&i.call(null,o)}else{var a=Date.now()-s,c=Math.max(s-r,1),l=Math.min(c*1.2,100);a>=l?(Bt("RETRY",t.name,n),t.apply(null,n.concat([r]))):Z[ge].push(e)}Uo===void 0&&(Uo=setTimeout(Es,0))}}});var ve=W(ct=>{"use strict";var ol=le().fromCallback,Se=dn(),fy=["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);fy.forEach(e=>{ct[e]=ol(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,s){return typeof s=="function"?Se.read(e,t,n,o,r,s):new Promise((i,a)=>{Se.read(e,t,n,o,r,(c,l,u)=>{if(c)return a(c);i({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,(s,i,a)=>{if(s)return r(s);o({bytesWritten:i,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,(s,i,a)=>{if(s)return r(s);o({bytesRead:i,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,(s,i,a)=>{if(s)return r(s);o({bytesWritten:i,buffers:a})})})};typeof Se.realpath.native=="function"?ct.realpath.native=ol(Se.realpath.native):process.emitWarning("fs.realpath.native is not a function. Is fs being monkey-patched?","Warning","fs-extra-WARN0003")});var sl=W((eC,rl)=>{"use strict";var my=require("path");rl.exports.checkPath=function(t){if(process.platform==="win32"&&/[<>:"|?*]/.test(t.replace(my.parse(t).root,""))){let o=new Error(`Path contains invalid characters: ${t}`);throw o.code="EINVAL",o}}});var ll=W((tC,Cs)=>{"use strict";var il=ve(),{checkPath:al}=sl(),cl=e=>{let t={mode:511};return typeof e=="number"?e:{...t,...e}.mode};Cs.exports.makeDir=async(e,t)=>(al(e),il.mkdir(e,{mode:cl(t),recursive:!0}));Cs.exports.makeDirSync=(e,t)=>(al(e),il.mkdirSync(e,{mode:cl(t),recursive:!0}))});var Ge=W((nC,ul)=>{"use strict";var gy=le().fromPromise,{makeDir:hy,makeDirSync:Rs}=ll(),Is=gy(hy);ul.exports={mkdirs:Is,mkdirsSync:Rs,mkdirp:Is,mkdirpSync:Rs,ensureDir:Is,ensureDirSync:Rs}});var Tt=W((oC,pl)=>{"use strict";var yy=le().fromPromise,dl=ve();function ky(e){return dl.access(e).then(()=>!0).catch(()=>!1)}pl.exports={pathExists:yy(ky),pathExistsSync:dl.existsSync}});var Os=W((rC,fl)=>{"use strict";var pn=ve(),wy=le().fromPromise;async function _y(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(s){r=s}}if(r)throw r}function Sy(e,t,n){let o=pn.openSync(e,"r+");return pn.futimesSync(o,t,n),pn.closeSync(o)}fl.exports={utimesMillis:wy(_y),utimesMillisSync:Sy}});var Gt=W((sC,yl)=>{"use strict";var fn=ve(),ue=require("path"),ml=le().fromPromise;function vy(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,s])=>({srcStat:r,destStat:s}))}function Ty(e,t,n){let o,r=n.dereference?i=>fn.statSync(i,{bigint:!0}):i=>fn.lstatSync(i,{bigint:!0}),s=r(e);try{o=r(t)}catch(i){if(i.code==="ENOENT")return{srcStat:s,destStat:null};throw i}return{srcStat:s,destStat:o}}async function Ey(e,t,n,o){let{srcStat:r,destStat:s}=await vy(e,t,o);if(s){if(zn(r,s)){let i=ue.basename(e),a=ue.basename(t);if(n==="move"&&i!==a&&i.toLowerCase()===a.toLowerCase())return{srcStat:r,destStat:s,isChangingCase:!0};throw new Error("Source and destination must not be the same.")}if(r.isDirectory()&&!s.isDirectory())throw new Error(`Cannot overwrite non-directory '${t}' with directory '${e}'.`);if(!r.isDirectory()&&s.isDirectory())throw new Error(`Cannot overwrite directory '${t}' with non-directory '${e}'.`)}if(r.isDirectory()&&Ps(e,t))throw new Error(Ho(e,t,n));return{srcStat:r,destStat:s}}function by(e,t,n,o){let{srcStat:r,destStat:s}=Ty(e,t,o);if(s){if(zn(r,s)){let i=ue.basename(e),a=ue.basename(t);if(n==="move"&&i!==a&&i.toLowerCase()===a.toLowerCase())return{srcStat:r,destStat:s,isChangingCase:!0};throw new Error("Source and destination must not be the same.")}if(r.isDirectory()&&!s.isDirectory())throw new Error(`Cannot overwrite non-directory '${t}' with directory '${e}'.`);if(!r.isDirectory()&&s.isDirectory())throw new Error(`Cannot overwrite directory '${t}' with non-directory '${e}'.`)}if(r.isDirectory()&&Ps(e,t))throw new Error(Ho(e,t,n));return{srcStat:r,destStat:s}}async function gl(e,t,n,o){let r=ue.resolve(ue.dirname(e)),s=ue.resolve(ue.dirname(n));if(s===r||s===ue.parse(s).root)return;let i;try{i=await fn.stat(s,{bigint:!0})}catch(a){if(a.code==="ENOENT")return;throw a}if(zn(t,i))throw new Error(Ho(e,n,o));return gl(e,t,s,o)}function hl(e,t,n,o){let r=ue.resolve(ue.dirname(e)),s=ue.resolve(ue.dirname(n));if(s===r||s===ue.parse(s).root)return;let i;try{i=fn.statSync(s,{bigint:!0})}catch(a){if(a.code==="ENOENT")return;throw a}if(zn(t,i))throw new Error(Ho(e,n,o));return hl(e,t,s,o)}function zn(e,t){return t.ino!==void 0&&t.dev!==void 0&&t.ino===e.ino&&t.dev===e.dev}function Ps(e,t){let n=ue.resolve(e).split(ue.sep).filter(r=>r),o=ue.resolve(t).split(ue.sep).filter(r=>r);return n.every((r,s)=>o[s]===r)}function Ho(e,t,n){return`Cannot ${n} '${e}' to a subdirectory of itself, '${t}'.`}yl.exports={checkPaths:ml(Ey),checkPathsSync:by,checkParentPaths:ml(gl),checkParentPathsSync:hl,isSrcSubdir:Ps,areIdentical:zn}});var wl=W((iC,kl)=>{"use strict";async function Cy(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})))}kl.exports={asyncIteratorConcurrentProcess:Cy}});var El=W((aC,Tl)=>{"use strict";var ke=ve(),Qn=require("path"),{mkdirs:Ry}=Ge(),{pathExists:Iy}=Tt(),{utimesMillis:Oy}=Os(),Xn=Gt(),{asyncIteratorConcurrentProcess:Py}=wl();async function Ay(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
|
|
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 Sl(e,t,n))return;let i=Qn.dirname(t);await Iy(i)||await Ry(i),await vl(r,e,t,n)}async function Sl(e,t,n){return n.filter?n.filter(e,t):!0}async function vl(e,t,n,o){let s=await(o.dereference?ke.stat:ke.lstat)(t);if(s.isDirectory())return Dy(s,e,t,n,o);if(s.isFile()||s.isCharacterDevice()||s.isBlockDevice())return xy(s,e,t,n,o);if(s.isSymbolicLink())return jy(e,t,n,o);throw s.isSocket()?new Error(`Cannot copy a socket file: ${t}`):s.isFIFO()?new Error(`Cannot copy a FIFO pipe: ${t}`):new Error(`Unknown file: ${t}`)}async function xy(e,t,n,o,r){if(!t)return _l(e,n,o,r);if(r.overwrite)return await ke.unlink(o),_l(e,n,o,r);if(r.errorOnExist)throw new Error(`'${o}' already exists`)}async function _l(e,t,n,o){if(await ke.copyFile(t,n),o.preserveTimestamps){$y(e.mode)&&await Ny(n,e.mode);let r=await ke.stat(t);await Oy(n,r.atime,r.mtime)}return ke.chmod(n,e.mode)}function $y(e){return(e&128)===0}function Ny(e,t){return ke.chmod(e,t|128)}async function Dy(e,t,n,o,r){t||await ke.mkdir(o),await Py(await ke.opendir(n),async s=>{let i=Qn.join(n,s.name),a=Qn.join(o,s.name);if(await Sl(i,a,r)){let{destStat:l}=await Xn.checkPaths(i,a,"copy",r);await vl(l,i,a,r)}}),t||await ke.chmod(o,e.mode)}async function jy(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 s=null;try{s=await ke.readlink(n)}catch(i){if(i.code==="EINVAL"||i.code==="UNKNOWN")return ke.symlink(r,n);throw i}if(o.dereference&&(s=Qn.resolve(process.cwd(),s)),r!==s){if(Xn.isSrcSubdir(r,s))throw new Error(`Cannot copy '${r}' to a subdirectory of itself, '${s}'.`);if(Xn.isSrcSubdir(s,r))throw new Error(`Cannot overwrite '${s}' with '${r}'.`)}return await ke.unlink(n),ke.symlink(r,n)}Tl.exports=Ay});var Ol=W((cC,Il)=>{"use strict";var Te=dn(),Zn=require("path"),My=Ge().mkdirsSync,Ly=Os().utimesMillisSync,eo=Gt();function Fy(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
|
|
15
|
-
`,finalEOL:n=!0,replacer:o=null,spaces:r}={}){let
|
|
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 s=Zn.dirname(t);return Te.existsSync(s)||My(s),bl(r,e,t,n)}function bl(e,t,n,o){let s=(o.dereference?Te.statSync:Te.lstatSync)(t);if(s.isDirectory())return Vy(s,e,t,n,o);if(s.isFile()||s.isCharacterDevice()||s.isBlockDevice())return Uy(s,e,t,n,o);if(s.isSymbolicLink())return Jy(e,t,n,o);throw s.isSocket()?new Error(`Cannot copy a socket file: ${t}`):s.isFIFO()?new Error(`Cannot copy a FIFO pipe: ${t}`):new Error(`Unknown file: ${t}`)}function Uy(e,t,n,o,r){return t?Wy(e,n,o,r):Cl(e,n,o,r)}function Wy(e,t,n,o){if(o.overwrite)return Te.unlinkSync(n),Cl(e,t,n,o);if(o.errorOnExist)throw new Error(`'${n}' already exists`)}function Cl(e,t,n,o){return Te.copyFileSync(t,n),o.preserveTimestamps&&Hy(e.mode,t,n),As(n,e.mode)}function Hy(e,t,n){return By(e)&&Gy(n,e),qy(t,n)}function By(e){return(e&128)===0}function Gy(e,t){return As(e,t|128)}function As(e,t){return Te.chmodSync(e,t)}function qy(e,t){let n=Te.statSync(e);return Ly(t,n.atime,n.mtime)}function Vy(e,t,n,o,r){return t?Rl(n,o,r):Yy(e.mode,n,o,r)}function Yy(e,t,n,o){return Te.mkdirSync(n),Rl(t,n,o),As(n,e)}function Rl(e,t,n){let o=Te.opendirSync(e);try{let r;for(;(r=o.readSync())!==null;)Ky(r.name,e,t,n)}finally{o.closeSync()}}function Ky(e,t,n,o){let r=Zn.join(t,e),s=Zn.join(n,e);if(o.filter&&!o.filter(r,s))return;let{destStat:i}=eo.checkPathsSync(r,s,"copy",o);return bl(i,r,s,o)}function Jy(e,t,n,o){let r=Te.readlinkSync(t);if(o.dereference&&(r=Zn.resolve(process.cwd(),r)),e){let s;try{s=Te.readlinkSync(n)}catch(i){if(i.code==="EINVAL"||i.code==="UNKNOWN")return Te.symlinkSync(r,n);throw i}if(o.dereference&&(s=Zn.resolve(process.cwd(),s)),r!==s){if(eo.isSrcSubdir(r,s))throw new Error(`Cannot copy '${r}' to a subdirectory of itself, '${s}'.`);if(eo.isSrcSubdir(s,r))throw new Error(`Cannot overwrite '${s}' with '${r}'.`)}return zy(r,n)}else return Te.symlinkSync(r,n)}function zy(e,t){return Te.unlinkSync(t),Te.symlinkSync(e,t)}Il.exports=Fy});var Bo=W((lC,Pl)=>{"use strict";var Qy=le().fromPromise;Pl.exports={copy:Qy(El()),copySync:Ol()}});var to=W((uC,xl)=>{"use strict";var Al=dn(),Xy=le().fromCallback;function Zy(e,t){Al.rm(e,{recursive:!0,force:!0},t)}function ek(e){Al.rmSync(e,{recursive:!0,force:!0})}xl.exports={remove:Xy(Zy),removeSync:ek}});var Ul=W((dC,Fl)=>{"use strict";var tk=le().fromPromise,Dl=ve(),jl=require("path"),Ml=Ge(),Ll=to(),$l=tk(async function(t){let n;try{n=await Dl.readdir(t)}catch{return Ml.mkdirs(t)}return Promise.all(n.map(o=>Ll.remove(jl.join(t,o))))});function Nl(e){let t;try{t=Dl.readdirSync(e)}catch{return Ml.mkdirsSync(e)}t.forEach(n=>{n=jl.join(e,n),Ll.removeSync(n)})}Fl.exports={emptyDirSync:Nl,emptydirSync:Nl,emptyDir:$l,emptydir:$l}});var Gl=W((pC,Bl)=>{"use strict";var nk=le().fromPromise,Wl=require("path"),lt=ve(),Hl=Ge();async function ok(e){let t;try{t=await lt.stat(e)}catch{}if(t&&t.isFile())return;let n=Wl.dirname(e),o=null;try{o=await lt.stat(n)}catch(r){if(r.code==="ENOENT"){await Hl.mkdirs(n),await lt.writeFile(e,"");return}else throw r}o.isDirectory()?await lt.writeFile(e,""):await lt.readdir(n)}function rk(e){let t;try{t=lt.statSync(e)}catch{}if(t&&t.isFile())return;let n=Wl.dirname(e);try{lt.statSync(n).isDirectory()||lt.readdirSync(n)}catch(o){if(o&&o.code==="ENOENT")Hl.mkdirsSync(n);else throw o}lt.writeFileSync(e,"")}Bl.exports={createFile:nk(ok),createFileSync:rk}});var Jl=W((fC,Kl)=>{"use strict";var sk=le().fromPromise,ql=require("path"),Et=ve(),Vl=Ge(),{pathExists:ik}=Tt(),{areIdentical:Yl}=Gt();async function ak(e,t){let n;try{n=await Et.lstat(t)}catch{}let o;try{o=await Et.lstat(e)}catch(i){throw i.message=i.message.replace("lstat","ensureLink"),i}if(n&&Yl(o,n))return;let r=ql.dirname(t);await ik(r)||await Vl.mkdirs(r),await Et.link(e,t)}function ck(e,t){let n;try{n=Et.lstatSync(t)}catch{}try{let s=Et.lstatSync(e);if(n&&Yl(s,n))return}catch(s){throw s.message=s.message.replace("lstat","ensureLink"),s}let o=ql.dirname(t);return Et.existsSync(o)||Vl.mkdirsSync(o),Et.linkSync(e,t)}Kl.exports={createLink:sk(ak),createLinkSync:ck}});var Ql=W((mC,zl)=>{"use strict";var bt=require("path"),no=ve(),{pathExists:lk}=Tt(),uk=le().fromPromise;async function dk(e,t){if(bt.isAbsolute(e)){try{await no.lstat(e)}catch(s){throw s.message=s.message.replace("lstat","ensureSymlink"),s}return{toCwd:e,toDst:e}}let n=bt.dirname(t),o=bt.join(n,e);if(await lk(o))return{toCwd:o,toDst:e};try{await no.lstat(e)}catch(s){throw s.message=s.message.replace("lstat","ensureSymlink"),s}return{toCwd:e,toDst:bt.relative(n,e)}}function pk(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)}}zl.exports={symlinkPaths:uk(dk),symlinkPathsSync:pk}});var eu=W((gC,Zl)=>{"use strict";var Xl=ve(),fk=le().fromPromise;async function mk(e,t){if(t)return t;let n;try{n=await Xl.lstat(e)}catch{return"file"}return n&&n.isDirectory()?"dir":"file"}function gk(e,t){if(t)return t;let n;try{n=Xl.lstatSync(e)}catch{return"file"}return n&&n.isDirectory()?"dir":"file"}Zl.exports={symlinkType:fk(mk),symlinkTypeSync:gk}});var ru=W((hC,ou)=>{"use strict";var hk=le().fromPromise,tu=require("path"),Ze=ve(),{mkdirs:yk,mkdirsSync:kk}=Ge(),{symlinkPaths:wk,symlinkPathsSync:_k}=Ql(),{symlinkType:Sk,symlinkTypeSync:vk}=eu(),{pathExists:Tk}=Tt(),{areIdentical:nu}=Gt();async function Ek(e,t,n){let o;try{o=await Ze.lstat(t)}catch{}if(o&&o.isSymbolicLink()){let[a,c]=await Promise.all([Ze.stat(e),Ze.stat(t)]);if(nu(a,c))return}let r=await wk(e,t);e=r.toDst;let s=await Sk(r.toCwd,n),i=tu.dirname(t);return await Tk(i)||await yk(i),Ze.symlink(e,t,s)}function bk(e,t,n){let o;try{o=Ze.lstatSync(t)}catch{}if(o&&o.isSymbolicLink()){let a=Ze.statSync(e),c=Ze.statSync(t);if(nu(a,c))return}let r=_k(e,t);e=r.toDst,n=vk(r.toCwd,n);let s=tu.dirname(t);return Ze.existsSync(s)||kk(s),Ze.symlinkSync(e,t,n)}ou.exports={createSymlink:hk(Ek),createSymlinkSync:bk}});var pu=W((yC,du)=>{"use strict";var{createFile:su,createFileSync:iu}=Gl(),{createLink:au,createLinkSync:cu}=Jl(),{createSymlink:lu,createSymlinkSync:uu}=ru();du.exports={createFile:su,createFileSync:iu,ensureFile:su,ensureFileSync:iu,createLink:au,createLinkSync:cu,ensureLink:au,ensureLinkSync:cu,createSymlink:lu,createSymlinkSync:uu,ensureSymlink:lu,ensureSymlinkSync:uu}});var Go=W((kC,fu)=>{function Ck(e,{EOL:t=`
|
|
15
|
+
`,finalEOL:n=!0,replacer:o=null,spaces:r}={}){let s=n?t:"";return JSON.stringify(e,o,r).replace(/\n/g,t)+s}function Rk(e){return Buffer.isBuffer(e)&&(e=e.toString("utf8")),e.replace(/^\uFEFF/,"")}fu.exports={stringify:Ck,stripBom:Rk}});var yu=W((wC,hu)=>{var mn;try{mn=dn()}catch{mn=require("fs")}var qo=le(),{stringify:mu,stripBom:gu}=Go();async function Ik(e,t={}){typeof t=="string"&&(t={encoding:t});let n=t.fs||mn,o="throws"in t?t.throws:!0,r=await qo.fromCallback(n.readFile)(e,t);r=gu(r);let s;try{s=JSON.parse(r,t?t.reviver:null)}catch(i){if(o)throw i.message=`${e}: ${i.message}`,i;return null}return s}var Ok=qo.fromPromise(Ik);function Pk(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=gu(r),JSON.parse(r,t.reviver)}catch(r){if(o)throw r.message=`${e}: ${r.message}`,r;return null}}async function Ak(e,t,n={}){let o=n.fs||mn,r=mu(t,n);await qo.fromCallback(o.writeFile)(e,r,n)}var xk=qo.fromPromise(Ak);function $k(e,t,n={}){let o=n.fs||mn,r=mu(t,n);return o.writeFileSync(e,r,n)}hu.exports={readFile:Ok,readFileSync:Pk,writeFile:xk,writeFileSync:$k}});var wu=W((_C,ku)=>{"use strict";var Vo=yu();ku.exports={readJson:Vo.readFile,readJsonSync:Vo.readFileSync,writeJson:Vo.writeFile,writeJsonSync:Vo.writeFileSync}});var Yo=W((SC,vu)=>{"use strict";var Nk=le().fromPromise,xs=ve(),_u=require("path"),Su=Ge(),Dk=Tt().pathExists;async function jk(e,t,n="utf-8"){let o=_u.dirname(e);return await Dk(o)||await Su.mkdirs(o),xs.writeFile(e,t,n)}function Mk(e,...t){let n=_u.dirname(e);xs.existsSync(n)||Su.mkdirsSync(n),xs.writeFileSync(e,...t)}vu.exports={outputFile:Nk(jk),outputFileSync:Mk}});var Eu=W((vC,Tu)=>{"use strict";var{stringify:Lk}=Go(),{outputFile:Fk}=Yo();async function Uk(e,t,n={}){let o=Lk(t,n);await Fk(e,o,n)}Tu.exports=Uk});var Cu=W((TC,bu)=>{"use strict";var{stringify:Wk}=Go(),{outputFileSync:Hk}=Yo();function Bk(e,t,n){let o=Wk(t,n);Hk(e,o,n)}bu.exports=Bk});var Iu=W((EC,Ru)=>{"use strict";var Gk=le().fromPromise,Ee=wu();Ee.outputJson=Gk(Eu());Ee.outputJsonSync=Cu();Ee.outputJSON=Ee.outputJson;Ee.outputJSONSync=Ee.outputJsonSync;Ee.writeJSON=Ee.writeJson;Ee.writeJSONSync=Ee.writeJsonSync;Ee.readJSON=Ee.readJson;Ee.readJSONSync=Ee.readJsonSync;Ru.exports=Ee});var $u=W((bC,xu)=>{"use strict";var qk=ve(),Ou=require("path"),{copy:Vk}=Bo(),{remove:Au}=to(),{mkdirp:Yk}=Ge(),{pathExists:Kk}=Tt(),Pu=Gt();async function Jk(e,t,n={}){let o=n.overwrite||n.clobber||!1,{srcStat:r,isChangingCase:s=!1}=await Pu.checkPaths(e,t,"move",n);await Pu.checkParentPaths(e,r,t,"move");let i=Ou.dirname(t);return Ou.parse(i).root!==i&&await Yk(i),zk(e,t,o,s)}async function zk(e,t,n,o){if(!o){if(n)await Au(t);else if(await Kk(t))throw new Error("dest already exists.")}try{await qk.rename(e,t)}catch(r){if(r.code!=="EXDEV")throw r;await Qk(e,t,n)}}async function Qk(e,t,n){return await Vk(e,t,{overwrite:n,errorOnExist:!0,preserveTimestamps:!0}),Au(e)}xu.exports=Jk});var Lu=W((CC,Mu)=>{"use strict";var Du=dn(),Ns=require("path"),Xk=Bo().copySync,ju=to().removeSync,Zk=Ge().mkdirpSync,Nu=Gt();function ew(e,t,n){n=n||{};let o=n.overwrite||n.clobber||!1,{srcStat:r,isChangingCase:s=!1}=Nu.checkPathsSync(e,t,"move",n);return Nu.checkParentPathsSync(e,r,t,"move"),tw(t)||Zk(Ns.dirname(t)),nw(e,t,o,s)}function tw(e){let t=Ns.dirname(e);return Ns.parse(t).root===t}function nw(e,t,n,o){if(o)return $s(e,t,n);if(n)return ju(t),$s(e,t,n);if(Du.existsSync(t))throw new Error("dest already exists.");return $s(e,t,n)}function $s(e,t,n){try{Du.renameSync(e,t)}catch(o){if(o.code!=="EXDEV")throw o;return ow(e,t,n)}}function ow(e,t,n){return Xk(e,t,{overwrite:n,errorOnExist:!0,preserveTimestamps:!0}),ju(e)}Mu.exports=ew});var Uu=W((RC,Fu)=>{"use strict";var rw=le().fromPromise;Fu.exports={move:rw($u()),moveSync:Lu()}});var se=W((IC,Wu)=>{"use strict";Wu.exports={...ve(),...Bo(),...Ul(),...pu(),...Iu(),...Ge(),...Uu(),...Yo(),...Tt(),...to()}});function Ds(e,t){return`${e}:${t}`}function iw(e){return Date.now()-e.timestamp<sw}function Hu(e){if(e.current_stage==="idea"&&(e.current_stage="intent"),!!e.construction_units)for(let t of Object.values(e.construction_units)){if(!t.stages["test-generation"]){let n=t.code_generation_status==="completed";t.stages["test-generation"]={status:n?"skipped":"not_started",artifact_path:null,completed_at:null}}t.quality_validation_status===void 0&&(t.quality_validation_status="not_started"),t.mutation_validation_status===void 0&&(t.mutation_validation_status="not_started"),t.traceability_status===void 0&&(t.traceability_status="not_started"),t.contract_validation_status===void 0&&(t.contract_validation_status="not_started"),t.coverage_status===void 0&&(t.coverage_status="not_started"),t.coverage_percentage===void 0&&(t.coverage_percentage=null)}}function Rt(e,t){let n=Ds(e,t);Ko.delete(n)}async function A(e,t){let n=(0,et.join)(e,Ct,t.workflow_id),o=(0,et.join)(n,Jo);try{if(t.updated_at=new Date().toISOString(),t.schema_version="3.0.0",await J.ensureDir(n),JSON.stringify(t).length>1e4){let a=JSON.stringify(t);await J.writeFile(o,a,"utf-8")}else await J.writeJson(o,t,{spaces:2});let i=Ds(e,t.workflow_id);Ko.set(i,{checkpoint:structuredClone(t),timestamp:Date.now(),dirty:!1})}catch(r){let s=r;throw s.code==="ENOSPC"?(console.error("[Checkpoint] Failed to save checkpoint: Disk full"),console.error("[Checkpoint] Please free up disk space and try again."),console.error(`[Checkpoint] Attempted path: ${o}`),new Error("Failed to save checkpoint: Disk is full. Please free up space and retry.")):s.code==="EACCES"||s.code==="EPERM"?(console.error("[Checkpoint] Failed to save checkpoint: Permission denied"),console.error(`[Checkpoint] Path: ${o}`),new Error(`Failed to save checkpoint: Permission denied for ${o}`)):s.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:",s.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}: ${s.message}`))}}async function T(e,t){let n=Ds(e,t),o=Ko.get(n);if(o&&iw(o)){let s=structuredClone(o.checkpoint);return Hu(s),s}let r=(0,et.join)(e,Ct,t,Jo);try{let s=await J.readFile(r,"utf-8"),i=JSON.parse(s);return i.schema_version?i.schema_version!=="3.0.0"?(console.warn(`[Checkpoint] Unknown checkpoint schema version ${i.schema_version} for workflow ${t}`),console.warn("[Checkpoint] Expected 3.0.0"),null):(i.current_stage==="idea"&&console.warn(`[Checkpoint] Migrating legacy 'idea' stage to 'intent' for workflow ${t}`),Hu(i),Ko.set(n,{checkpoint:structuredClone(i),timestamp:Date.now(),dirty:!1}),i):(console.warn(`[Checkpoint] Checkpoint ${t} missing schema_version, treating as invalid`),console.warn("[Checkpoint] Checkpoint may be corrupt or from an older version"),console.warn(`[Checkpoint] Consider deleting: ${r}`),null)}catch(s){let i=s,a=i;return a.code==="ENOENT"?null:i.name==="SyntaxError"||i.message.includes("JSON")?(console.warn(`[Checkpoint] Corrupt checkpoint detected for workflow ${t}`),console.warn(`[Checkpoint] Path: ${r}`),console.warn(`[Checkpoint] Error: ${i.message}`),console.warn("[Checkpoint] To reset this workflow, delete the checkpoint file and start over"),null):a.code==="EACCES"||a.code==="EPERM"?(console.warn(`[Checkpoint] Permission denied reading checkpoint ${t}`),console.warn(`[Checkpoint] Path: ${r}`),null):(console.warn(`[Checkpoint] Failed to load checkpoint ${t}: ${i.message}`),console.warn(`[Checkpoint] Path: ${r}`),null)}}async function ne(e){let t=(0,et.join)(e,Ct);try{if(!await J.pathExists(t))return[];let o=await J.readdir(t,{withFileTypes:!0}),r=[];for(let s of o){if(!s.isDirectory()||s.name==="completed")continue;let i=(0,et.join)(t,s.name,Jo);if(await J.pathExists(i))try{let a=await J.readFile(i,"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 Bu(e,t){let n=await T(e,t);if(!n||n.status!=="complete")return;let o=(0,et.join)(e,Ct,t),r=(0,et.join)(e,Ct,"completed",t),s=(0,et.join)(r,Jo);if(await J.pathExists(s))try{let i=await J.readFile(s,"utf-8");if(JSON.parse(i).workflow_id===t){console.log(`[Checkpoint] Workflow ${t} already archived at ${r}`);return}}catch{await J.remove(r)}else await J.pathExists(r)&&await J.remove(r);n.archived_at=new Date().toISOString(),n.archived_path=`${Ct}/completed/${t}`,await A(e,n);try{await J.move(o,r,{overwrite:!1}),Rt(e,t),console.log(`[Checkpoint] Workflow archived to ${Ct}/completed/${t}/`)}catch(i){let a=i,c=a.code==="EBUSY"&&process.platform==="win32"?" \u2014 try closing open files in the workflow directory":"";console.warn(`[Checkpoint] Failed to move workflow folder (non-fatal): ${a.message}${c}`)}try{let i=(0,et.join)(e,".olympus","plans",`${t}-plan.md`);if(await J.pathExists(i)){let a=`
|
|
16
16
|
|
|
17
17
|
---
|
|
18
18
|
_This workflow was archived to \`${Ct}/completed/${t}/\` on ${n.archived_at}_
|
|
19
|
-
`;await
|
|
20
|
-
`),o=null,r=[];for(let
|
|
21
|
-
`)),o=
|
|
19
|
+
`;await J.appendFile(i,a,"utf-8")}}catch{}}var J,et,Ct,Jo,Ko,sw,we=B(()=>{"use strict";J=E(se(),1),et=require("path"),Ct="aidlc-docs",Jo="checkpoint.json",Ko=new Map,sw=5e3});var Vu={};Je(Vu,{computeVerification:()=>zo,generateValidationQuestions:()=>qu,getAdaptiveThreshold:()=>dw,getConformanceThreshold:()=>fw,recordAlignmentResult:()=>pw,runAlignmentCheck:()=>Ms,runDualValidation:()=>gn});function lw(e){return e.replace(/^---\n[\s\S]*?\n---\n/,"")}function js(e){let t=new Map,n=e.split(`
|
|
20
|
+
`),o=null,r=[];for(let s of n){let i=s.match(/^##\s+(.+)$/);i?(o&&t.set(o,r.join(`
|
|
21
|
+
`)),o=i[1].trim(),r=[]):o&&r.push(s)}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 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
|
-
`)
|
|
23
|
+
`);for(let o of n){let r=o.match(/^\s*[-*+]\s+(?:\[[ x]\]\s+)?(.+)$/);r&&t.push(r[1].trim())}return t}function uw(e,t){let n=lw(e);if(t==="intent-to-unit"){let i=js(n),a=[],c=i.get("Business Requirements");c&&a.push(...oo(c));let l=i.get("Implementation Plan");return l&&a.push(...oo(l)),a}if(t==="unit-to-bolt"){let i=js(n),a=[],c=i.get("Acceptance Criteria");c&&a.push(...oo(c));let l=i.get("Target Files");return l&&a.push(...oo(l)),a}let o=js(n),r=cw[t],s=[];for(let i of r){let a=o.get(i);if(a){let c=oo(a);s.push(...c)}}return s}function zo(e,t,n){try{let o=uw(e,n);if(o.length===0)return{conformance_score:100,coverage_percentage:100,missing_items:[],passed:!0};let r=t.toLowerCase(),s=[],i=0;for(let d of o){let f=d.toLowerCase();r.includes(f)?i++:s.push(d)}let a=Math.round(i/o.length*100),c=a,l=Gu[n],u=a>=l;return{conformance_score:a,coverage_percentage:c,missing_items:s,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 qu(e){let t=aw[e];return[{question:t.verification,answer:null,answered_by:null,passed:null},{question:t.validation,answer:null,answered_by:null,passed:null}]}function Ms(e,t,n,o,r){try{let s=zo(e,t,r),i=qu(r),a=i.every(m=>m.answer!==null),c=i.every(m=>m.passed===!0),u={alignment_score:a&&c?100:0,alignment_questions:i,passed:c},d=s.passed&&u.passed;return{source_artifact_id:n,target_artifact_id:o,verification:s,validation:u,alignment_passed:d,checked_at:new Date().toISOString()}}catch(s){return console.error("[Alignment] Alignment check failed:",s),{source_artifact_id:n,target_artifact_id: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,s,i,a){let c=Ms(t,e,s,i,o),l=Ms(n,e,a,i,r),u=c.alignment_passed&&l.alignment_passed;return{parentCheck:c,rootCheck:l,passed:u}}function dw(e,t){let n=0;t>=2&&(n+=10),t>=3&&(n+=10);let o=e-n;return Math.max(0,o)}function pw(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 fw(e){return Gu[e]}var Gu,aw,cw,Qo=B(()=>{"use strict";z();Gu={"intent-to-unit":95,"unit-to-bolt":100,"unit-to-intent":80,"bolt-to-intent":70},aw={"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?"}},cw={"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={};Je(Vt,{addGateAuditEntry:()=>Ce,cascadeInvalidation:()=>gw,computeChecksum:()=>Xo,createManifest:()=>Fs,detectStaleArtifacts:()=>mw,getArtifactById:()=>kw,getArtifactsByPhase:()=>ww,getBoltArtifacts:()=>ot,getBoltsByStatus:()=>Ws,getUnitArtifacts:()=>qt,isWorkflowComplete:()=>Ku,linkArtifacts:()=>Us,loadManifest:()=>D,normalizePath:()=>Ls,recoverManifest:()=>yw,registerArtifact:()=>xe,revalidateStaleArtifacts:()=>Sw,runAlignmentCheck:()=>hw,saveManifest:()=>F,transitionToActive:()=>Hs,transitionToDraft:()=>Ju,transitionToFulfilled:()=>Bs,transitionToStale:()=>Qu,transitionToViolated:()=>zu,updateContractStatus:()=>nt,updatePhaseStatus:()=>ut});function Ls(e){return e.replace(/\\/g,"/")}function It(){return{status:"not_started",started_at:null,completed_at:null,gate_result:null,gate_bypassed:!1,bypass_reason:null}}function Fs(e,t,n){let o=tt.join(n,"aidlc-docs",e),r=tt.join(o,"manifest.json");try{oe.ensureDirSync(o);let s=new Date().toISOString(),i={schema_version:"2.0.0",workflow_id:e,feature_name:t,created_at:s,updated_at:s,phases:{discovery:It(),inception:It(),construction:It(),operations:It()},depth_assessment:null,artifacts:[],links:[],risks:[],gate_audit:[],metrics:null,alignment_checks:[],risk_tier:null};return oe.writeFileSync(r,JSON.stringify(i,null,2),"utf-8"),r}catch(s){throw console.error(`Failed to create manifest at ${r}:`,s),s}}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 Xo(e){try{if(!oe.existsSync(e))return null;let t=oe.readFileSync(e),n=(0,Yu.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=Ls(t.path),s=n.artifacts.findIndex(a=>a.id===t.id),i=Xo(t.path);if(s>=0){let a=n.artifacts[s];n.artifacts[s]={...a,...t,path:r,updated_at:o,contract_version:a.contract_version+1,checksum:i}}else{let a={...t,path:r,created_at:o,updated_at:o,contract_version:1,contract_status:"draft",stale_reason:null,checksum:i};n.artifacts.push(a)}F(e,n)}catch(n){throw console.error(`Failed to register artifact in ${e}:`,n),n}}function Us(e,t){try{let n=D(e);if(!n)throw new Error(`Manifest not found at ${e}`);let o=n.artifacts.some(i=>i.id===t.source_id),r=n.artifacts.some(i=>i.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(i=>i.source_id===t.source_id&&i.target_id===t.target_id&&i.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 mw(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=Xo(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 gw(e,t){try{let n=D(e);if(!n)return;let o=new Set,r=[t];for(;r.length>0;){let s=r.shift();if(o.has(s))continue;o.add(s);let i=n.artifacts.find(c=>c.id===s);if(i){let c=s===t?"Artifact content was modified":`Parent artifact ${s} was modified`;_w(i,c)}let a=n.links.filter(c=>c.source_id===s);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 hw(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 yw(e,t){try{let n=tt.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:It(),inception:It(),construction:It(),operations:It()},depth_assessment:null,artifacts:[],links:[],risks:[],gate_audit:[],metrics:null,alignment_checks:[],risk_tier:null},s=oe.readdirSync(n,{recursive:!0,withFileTypes:!0});for(let i of s)if(i.isFile()&&i.name!=="manifest.json"){let a=tt.join(i.path,i.name),c=tt.relative(n,a),l=Ls(a),u={id:`recovered-${Date.now()}-${r.artifacts.length}`,type:tt.extname(i.name)||"unknown",phase:"inception",stage:"intent",path:l,created_at:o,updated_at:o,validation_passed:null,write_complete:!0,checksum:Xo(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 s=D(e);if(!s)return;s.phases[t].status=n,o!==void 0&&(s.phases[t].started_at=o),r!==void 0&&(s.phases[t].completed_at=r),F(e,s)}catch(s){console.error(`Failed to update phase status in ${e}:`,s)}}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 kw(e,t){return e.artifacts.find(n=>n.id===t)}function ww(e,t){return e.artifacts.filter(n=>n.phase===t)}function nt(e,t,n,o){try{switch(n){case"draft":Ju(e,t);break;case"active":Hs(e,t);break;case"fulfilled":Bs(e,t);break;case"violated":zu(e,t);break;case"stale":if(!o)throw new Error('staleReason is required when setting status to "stale"');Qu(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 ot(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 Ws(e,t){return e.artifacts.filter(n=>n.stage==="code-generation"&&n.contract_status===t)}function Ku(e){let t=e.artifacts.filter(n=>n.stage==="code-generation");return t.length===0?!1:t.every(n=>n.contract_status==="fulfilled")}function _w(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 Ju(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 Hs(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 Bs(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 zu(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 Qu(e,t,n){let o=D(e);if(!o)throw new Error(`Manifest not found at ${e}`);let r=o.artifacts.find(s=>s.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 Sw(e,t){let n={restored:[],stillStale:[],errors:[]},o=tt.join(e,"aidlc-docs",t,"manifest.json"),r=D(o);if(!r)return n.errors.push("Manifest not found"),n;let s=r.artifacts.filter(i=>i.contract_status==="stale");for(let i of s)try{let a=r.links.find(y=>y.target_id===i.id);if(!a){n.stillStale.push(i.id);continue}let c=r.artifacts.find(y=>y.id===a.source_id);if(!c){n.stillStale.push(i.id);continue}let l=r.artifacts.find(y=>y.stage==="intent");if(!l){n.stillStale.push(i.id);continue}let u=oe.existsSync(i.path)?oe.readFileSync(i.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(i.id);continue}let{runDualValidation:m}=await Promise.resolve().then(()=>(Qo(),Vu)),p,g;if(i.stage==="unit")p="intent-to-unit",g="unit-to-intent";else if(i.stage==="code-generation")p="unit-to-bolt",g="bolt-to-intent";else{n.stillStale.push(i.id);continue}m(u,d,f,p,g,c.id,i.id,l.id).passed?(i.contract_status="active",i.stale_reason=null,i.statusHistory||(i.statusHistory=[]),i.statusHistory.push({status:"active",timestamp:new Date().toISOString()}),n.restored.push(i.id)):n.stillStale.push(i.id)}catch(a){n.errors.push(`Error revalidating ${i.id}: ${a}`),n.stillStale.push(i.id)}return F(o,r),n}var oe,tt,Yu,z=B(()=>{"use strict";oe=E(se(),1),tt=E(require("path"),1),Yu=require("crypto")});async function Xu(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 s=r;throw s.code==="ENOSPC"?(console.error("[Artifacts] Failed to create workflow directory: Disk full"),console.error("[Artifacts] Please free up disk space and try again."),console.error(`[Artifacts] Attempted path: ${n}`),new Error("Failed to create workflow directory: Disk is full. Please free up space and retry.")):s.code==="EACCES"||s.code==="EPERM"?(console.error("[Artifacts] Failed to create workflow directory: Permission denied"),console.error(`[Artifacts] Path: ${n}`),new Error(`Failed to create workflow directory: Permission denied for ${n}`)):s.code==="EROFS"?(console.error("[Artifacts] Failed to create workflow directory: Read-only filesystem"),console.error(`[Artifacts] Path: ${n}`),new Error("Failed to create workflow directory: Filesystem is read-only")):(console.error(`[Artifacts] Failed to create workflow directory: ${s.message}`),console.error(`[Artifacts] Workflow ID: ${t}`),console.error(`[Artifacts] Path: ${n}`),new Error(`Failed to create workflow directory for ${t}: ${s.message}`))}}function Ot(e,t,n,o,r){let s=j.join(e,"aidlc-docs",t);switch(n){case"intent":return j.join(s,"inception","intent.md");case"nfr":return j.join(s,"inception","requirements","nfr.md");case"unit":if(!o)throw new Error("artifactId is required for unit artifacts");return j.join(s,"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(s,"construction",r,`${o}.md`);case"validation-report":if(!o)throw new Error("artifactId is required for validation-report artifacts");return j.join(s,"construction",o,"validation-report.md");case"interfaces":return j.join(s,"construction","design","interfaces.json");case"data-flow":return j.join(s,"construction","design","data-flow.json");case"components":return j.join(s,"construction","design","components.json");case"deploy-guide":return j.join(s,"operations","deploy-guide.md");case"runbook":return j.join(s,"operations","runbook.md");case"monitoring":return j.join(s,"operations","monitoring.json");case"release-notes":return j.join(s,"operations","release-notes.md");case"state":return j.join(s,"state.md");case"audit":return j.join(s,"audit.md");case"analysis-plan":return j.join(s,"discovery","analysis-plan.md");case"current-state-analysis":return j.join(s,"discovery","current-state-analysis.md");case"regression-baseline":return j.join(s,"discovery","regression-baseline.md");case"change-impact":return j.join(s,"discovery","change-impact.md");case"static-model":return j.join(s,"discovery","static-model.md");case"dynamic-model":return j.join(s,"discovery","dynamic-model.md");case"WORKFLOW_ROUTING":return j.join(s,"inception","plans","workflow-routing.md");case"requirements-qa":return j.join(s,"inception","requirements","requirements-analysis-questions.md");case"requirements":return j.join(s,"inception","requirements","requirements.md");case"personas":return j.join(s,"inception","user-stories","personas.md");case"user-stories":return j.join(s,"inception","user-stories","stories.md");case"execution-plan":return j.join(s,"inception","plans","execution-plan.md");case"units-generation":return j.join(s,"inception","application-design","unit-of-work.md");case"unit-dependency":return j.join(s,"inception","application-design","unit-of-work-dependency.md");case"unit-story-map":return j.join(s,"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,s){let i=Ot(e,t,n,r,s),a=await he.pathExists(i);try{await he.ensureDir(j.dirname(i)),await he.writeFile(i,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: ${i}`),new Error(`Failed to write ${n} artifact: Disk is full. Please free up space and retry.`)):l.code==="EACCES"||l.code==="EPERM"?(console.error(`[Artifacts] Failed to write ${n} artifact: Permission denied`),console.error(`[Artifacts] Path: ${i}`),new Error(`Failed to write ${n} artifact: Permission denied for ${i}`)):l.code==="EROFS"?(console.error(`[Artifacts] Failed to write ${n} artifact: Read-only filesystem`),console.error(`[Artifacts] Path: ${i}`),new Error(`Failed to write ${n} artifact: Filesystem is read-only`)):(console.error(`[Artifacts] Failed to write ${n} artifact: ${l.message}`),console.error(`[Artifacts] Path: ${i}`),new Error(`Failed to write ${n} artifact: ${l.message}`))}if(a)try{let c=j.join(e,"aidlc-docs",t,"manifest.json"),{cascadeInvalidation:l,loadManifest:u,saveManifest:d,computeChecksum:f}=await Promise.resolve().then(()=>(z(),Vt)),m=u(c);if(m){let p=i.replace(/\\/g,"/"),g=m.artifacts.find(h=>h.path===p||h.path.endsWith(j.basename(i)));if(g){let h=f(i);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 Gs(e,t){let n=j.join(e,"aidlc-docs",t,"discovery");await he.ensureDir(n)}var j,he,qs=B(()=>{"use strict";j=E(require("path"),1),he=E(se(),1)});var ud={};Je(ud,{captureBaseline:()=>Bw,compareAgainstBaseline:()=>Gw,writeRegressionReport:()=>qw});async function Bw(e,t,n){let o=so.default.join(e,"aidlc-docs",t,"construction");await ro.default.ensureDir(o);let r=Vw(n),s="",i="";try{s=(0,ld.execSync)(n,{cwd:e,encoding:"utf-8",stdio:"pipe"})}catch(p){let g=p;s=g.stdout??"",i=g.stderr??""}let c=Yw(s||i,r),l=c.filter(p=>p.status==="passed").length,u=c.filter(p=>p.status==="failed").length,d=c.filter(p=>p.status==="skipped").length,f={tests:c.map(p=>({name:p.name,filePath:p.filePath,status:p.status,duration_ms:p.duration_ms})),captured_at:new Date().toISOString(),test_command:n,framework:r,total:c.length,passed:l,failed:u,skipped:d},m=so.default.join(o,"regression-baseline.json");return await ro.default.writeJson(m,f,{spaces:2}),f}function Gw(e,t){let n=new Map;for(let i of e.tests)n.set(i.name,i);let o=[],r=[],s=[];for(let i of t){let a=n.get(i.name);if(!a){i.status==="failed"&&o.push({name:i.name,filePath:i.filePath});continue}(a.status==="passed"||a.status==="skipped")&&i.status==="failed"&&o.push({name:i.name,filePath:i.filePath}),a.status==="failed"&&i.status==="passed"&&r.push({name:i.name,filePath:i.filePath});let c=Math.abs(i.duration_ms-a.duration_ms);c>100&&s.push({name:i.name,before_ms:a.duration_ms,after_ms:i.duration_ms,delta_ms:c})}return{new_failures:o,new_passes:r,timing_changes:s,computed_at:new Date().toISOString()}}async function qw(e,t,n,o){let r=so.default.join(e,"aidlc-docs",t,"construction",n,"testing");await ro.default.ensureDir(r);let s=so.default.join(r,"regression-report.md"),i=o.failures.map(c=>`| ${c.test_name} | ${c.file_path} | ${c.category} | ${c.rationale} |`).join(`
|
|
24
|
+
`),a=`# Regression Report
|
|
25
|
+
|
|
26
|
+
**Workflow ID**: ${o.workflow_id}
|
|
27
|
+
**Unit ID**: ${o.unit_id}
|
|
28
|
+
**Baseline Captured At**: ${o.baseline_captured_at}
|
|
29
|
+
**Compared At**: ${o.compared_at}
|
|
30
|
+
|
|
31
|
+
## Summary
|
|
32
|
+
|
|
33
|
+
| Metric | Count |
|
|
34
|
+
|---|---|
|
|
35
|
+
| Total Regressions | ${o.total_regressions} |
|
|
36
|
+
| Legitimate Regressions | ${o.legitimate_regressions} |
|
|
37
|
+
|
|
38
|
+
## Failures
|
|
39
|
+
|
|
40
|
+
| Test Name | File Path | Category | Rationale |
|
|
41
|
+
|---|---|---|---|
|
|
42
|
+
${i||"| _No failures_ | | | |"}
|
|
43
|
+
`;await ro.default.writeFile(s,a,"utf-8")}function Vw(e){return e.includes("vitest")?"vitest":e.includes("jest")?"jest":"unknown"}function Yw(e,t){if(e.includes('"numPassedTests"'))try{let n=e.indexOf("{");if(n!==-1){let o=JSON.parse(e.slice(n)),r=[];if(Array.isArray(o.testResults))for(let s of o.testResults){let i=s.testFilePath??s.name??"unknown";for(let a of s.assertionResults??[])r.push({name:a.fullName??a.title??"unnamed",filePath:i,status:Kw(a.status),duration_ms:a.duration??0})}if(r.length>0)return r}}catch{}return Jw(e)}function Kw(e){return e==="passed"?"passed":e==="failed"?"failed":"skipped"}function Jw(e){let t=e.split(`
|
|
44
|
+
`),n=[],o="unknown";for(let r of t){let s=r.trim(),i=s.match(/^(?:FAIL|PASS)\s+(src\S+)/);if(i){o=i[1];continue}let a=[/^[✓√]\s+(.+?)(?:\s+\((\d+)ms\)|\s+(\d+)ms)?$/,/^ok\s+\d+\s+-\s+(.+?)(?:\s+#.*)?(?:\s+(\d+)ms)?$/],c=[/^[✗×]\s+(.+?)(?:\s+\((\d+)ms\)|\s+(\d+)ms)?$/,/^not ok\s+\d+\s+-\s+(.+?)(?:\s+#.*)?(?:\s+(\d+)ms)?$/],l=!1;for(let u of a){let d=s.match(u);if(d){n.push({name:d[1].trim(),filePath:o,status:"passed",duration_ms:cd(d[2]??d[3])}),l=!0;break}}if(!l)for(let u of c){let d=s.match(u);if(d){n.push({name:d[1].trim(),filePath:o,status:"failed",duration_ms:cd(d[2]??d[3])});break}}}return n}function cd(e){if(!e)return 0;let t=parseInt(e,10);return isNaN(t)?0:t}var ro,so,ld,dd=B(()=>{"use strict";ro=E(se(),1),so=E(require("path"),1),ld=require("child_process")});function fd(e){let t={id:(0,pd.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 md(e){let t=Do();return jo(e,t)}var pd,er=B(()=>{"use strict";pd=require("crypto");fe()});var tr={};Je(tr,{CODE_PLAN_FORMAT_INSTRUCTIONS:()=>Xw,buildCodeGenerationPrompt:()=>kd,buildCodePlanPath:()=>zw,dispatchCodeGeneration:()=>Qw,extractSections:()=>Zs,extractTargetFiles:()=>ei,selectAgentForCodeGeneration:()=>yd});function zw(e,t,n){return(0,_n.join)(e,"aidlc-docs",t,"construction",n,"code-plan.md")}function Zs(e,t){if(!e)return"";let n=[],o=e.split(`
|
|
45
|
+
`);for(let r=0;r<o.length;r++){let s=o[r],i=s.match(/^##\s+(.+)$/)||s.match(/^###\s+(.+)$/);if(i){let a=i[1].trim();if(t.some(c=>a.includes(c))){let c=[s],l=s.match(/^(#+)/)?.[1].length||2;for(let u=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
46
|
`))}}}return n.length>0?n.join(`
|
|
26
47
|
|
|
27
|
-
`):e}function
|
|
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
|
|
48
|
+
`):e}function ei(e){let t=[],n=e.split(`
|
|
49
|
+
`),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 s=r.match(/^-\s+(.+)$/);s&&t.push(s[1].trim())}}return t}function yd(e){let t=ei(e),n=["olympian-low","frontend-engineer-low","oracle-low"];for(let o of n){let r=md(o);if(r&&r.success_rate>.8&&r.total_invocations>10)return gd(t,e)?o.startsWith("frontend")?o:"frontend-engineer-low":hd(e)?o.startsWith("oracle")?o:"oracle-low":o.startsWith("olympian")?o:"olympian-low"}return gd(t,e)?"frontend-engineer":hd(e)?"oracle":"olympian"}function gd(e,t){let n=[".tsx",".jsx",".css",".scss","/ui/","/component","/page","/layout"];for(let o of e){let r=o.toLowerCase();if(n.some(s=>r.includes(s)))return!0}return!1}function hd(e){let t=["debug","fix","investigate","diagnose"],n=e.toLowerCase();return t.some(o=>n.includes(o))}function kd(e,t,n,o){let r=o?`
|
|
29
50
|
## Execution Protocol (Two-Part Code Generation)
|
|
30
51
|
PART 1 - PLAN:
|
|
31
52
|
1. Create an execution plan in a markdown file with checkboxes for each step
|
|
@@ -52,13 +73,13 @@ Generate code for this unit according to the spec above.
|
|
|
52
73
|
- Create/modify files listed in "Target Files"
|
|
53
74
|
- Write tests per "Test Requirements"
|
|
54
75
|
- Meet all "Acceptance Criteria"
|
|
55
|
-
- Do NOT modify files outside the target list without justification`}async function
|
|
76
|
+
- Do NOT modify files outside the target list without justification`}async function Qw(e,t,n){let o=(0,_n.join)(e,"aidlc-docs",t),r=(0,_n.join)(o,"construction"),s=(0,_n.join)(r,n,"spec.md"),i=(0,Sn.existsSync)(s)?(0,Sn.readFileSync)(s,"utf-8"):"",a=(0,_n.join)(o,"inception","intent.md"),c=(0,Sn.existsSync)(a)?(0,Sn.readFileSync)(a,"utf-8"):"",l=Zs(c,["Business Requirements","Technical Specification"]),u=Zs(c,["Problem Statement","Success Metrics"]),d=ei(i),f=yd(i),m=kd(u,l,i);return{unitName:n,agentType:f,prompt:m,context:{unitSpec:i,intentSummary:l,intentSummary2:u,targetFiles:d}}}var Sn,_n,Xw,nr=B(()=>{"use strict";Sn=require("fs"),_n=require("path");er();Xw=`A code generation plan must contain:
|
|
56
77
|
1. A title line: "# Code Plan: {unitName}"
|
|
57
78
|
2. A checklist of implementation steps using markdown checkboxes (- [ ] step)
|
|
58
79
|
3. Each step should be specific and actionable
|
|
59
80
|
4. Steps should be ordered by dependency (prerequisites first)
|
|
60
81
|
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
|
|
82
|
+
The plan file is saved at: aidlc-docs/{workflowId}/construction/{unitName}/code-plan.md`});async function wd(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"),s=vn.default.join(e,"aidlc-docs",t,"construction",n,"nfr-requirements.md"),i="";try{await Kt.default.pathExists(o)&&(i=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=Zw(i,a,l),d=new Date().toISOString(),f=`---
|
|
62
83
|
id: ${n}-nfr-requirements
|
|
63
84
|
parent_unit: ${n}
|
|
64
85
|
generated_at: ${d}
|
|
@@ -75,15 +96,15 @@ ${u||"_No specific NFRs identified for this unit. Inherit project-level defaults
|
|
|
75
96
|
|
|
76
97
|
## Unit Context
|
|
77
98
|
${l}
|
|
78
|
-
`;await Kt.default.ensureDir(vn.default.dirname(
|
|
79
|
-
`)}function
|
|
99
|
+
`;await Kt.default.ensureDir(vn.default.dirname(s)),await Kt.default.writeFile(s,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:s,validation_passed:null,write_complete:!0,checksum:null})}catch(m){console.error(`[NFRRequirements] Failed to register artifact for ${n}:`,m)}return{artifactPath:s,nfrContent:u}}function Zw(e,t,n){if(!e.trim())return"";let o=e.split(/(?=^## )/m).filter(a=>a.trim());if(o.length===0)return e;let r=e_(t+" "+n);if(r.length===0)return e;let i=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 i.length===0?e:i.map(a=>a.section).join(`
|
|
100
|
+
`)}function e_(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,_d=B(()=>{"use strict";Kt=E(se(),1),vn=E(require("path"),1);z()});var Sd={};Je(Sd,{UnitStageRunner:()=>ti});var Re,dt,t_,ti,vd=B(()=>{"use strict";Re=E(se(),1),dt=E(require("path"),1);_d();t_={SHALLOW:[],MEDIUM:["functional-design","nfr-requirements"],DEEP:["functional-design","nfr-requirements","nfr-design","infrastructure-design"]},ti=class{projectPath;workflowId;constructor(t,n){this.projectPath=t,this.workflowId=n}async executeForUnit(t,n,o,r){let s=t_[n],i=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:s.includes(u)?"not_started":"skipped",artifact_path:null,completed_at:null};if(s.length===0)return console.log(`[UnitStageRunner] SHALLOW depth: skipping all design stages for ${t}`),c;console.log(`[UnitStageRunner] Running ${s.length} design stages for ${t} (${n})`);let l="";try{let u=dt.default.join(i,"spec.md");await Re.default.pathExists(u)&&(l=await Re.default.readFile(u,"utf-8"))}catch{}for(let u of s){c.stages[u].status="in_progress";try{let d=await this.executeStage(u,t,i,l,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,s,c),c}async executeStage(t,n,o,r,s,i){switch(await Re.default.ensureDir(o),t){case"functional-design":{let a=dt.default.join(o,"functional-design.md"),c=this.buildFunctionalDesignContent(n,r,s);return await Re.default.writeFile(a,c,"utf-8"),a}case"nfr-requirements":return(await wd(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=i||"";try{await Re.default.pathExists(c)&&(l=await Re.default.readFile(c,"utf-8"))}catch{}let u=this.buildNFRDesignContent(n,r,l);return await Re.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 Re.default.pathExists(c)&&(l=await Re.default.readFile(c,"utf-8"))}catch{}let u=this.buildInfrastructureDesignContent(n,r,l);return await Re.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),s=r?r[1].trim().replace(/^["']|["']$/g,""):t,i=new Date().toISOString();return`---
|
|
80
101
|
id: ${t}-functional-design
|
|
81
102
|
parent_unit: ${t}
|
|
82
103
|
stage: functional-design
|
|
83
|
-
generated_at: ${
|
|
104
|
+
generated_at: ${i}
|
|
84
105
|
---
|
|
85
106
|
|
|
86
|
-
# Functional Design: ${
|
|
107
|
+
# Functional Design: ${s}
|
|
87
108
|
|
|
88
109
|
## Business Logic Model
|
|
89
110
|
Derived from intent and unit specification.
|
|
@@ -99,14 +120,14 @@ ${this.extractSection(n,"Acceptance Criteria")||"- See unit spec for acceptance
|
|
|
99
120
|
Entity interactions and state transitions relevant to this unit.
|
|
100
121
|
|
|
101
122
|
${this.extractSection(n,"Scope & Responsibility")||"See unit spec for scope details."}
|
|
102
|
-
`}buildNFRDesignContent(t,n,o){let r=n.match(/^title:\s*(.+)$/m),
|
|
123
|
+
`}buildNFRDesignContent(t,n,o){let r=n.match(/^title:\s*(.+)$/m),s=r?r[1].trim().replace(/^["']|["']$/g,""):t,i=new Date().toISOString();return`---
|
|
103
124
|
id: ${t}-nfr-design
|
|
104
125
|
parent_unit: ${t}
|
|
105
126
|
stage: nfr-design
|
|
106
|
-
generated_at: ${
|
|
127
|
+
generated_at: ${i}
|
|
107
128
|
---
|
|
108
129
|
|
|
109
|
-
# NFR Design: ${
|
|
130
|
+
# NFR Design: ${s}
|
|
110
131
|
|
|
111
132
|
## NFR Requirements Reference
|
|
112
133
|
${o||"No NFR requirements available."}
|
|
@@ -116,14 +137,14 @@ Fault tolerance strategies for this unit.
|
|
|
116
137
|
|
|
117
138
|
## Logical Components
|
|
118
139
|
Component definitions satisfying functional and non-functional requirements.
|
|
119
|
-
`}buildInfrastructureDesignContent(t,n,o){let r=n.match(/^title:\s*(.+)$/m),
|
|
140
|
+
`}buildInfrastructureDesignContent(t,n,o){let r=n.match(/^title:\s*(.+)$/m),s=r?r[1].trim().replace(/^["']|["']$/g,""):t,i=new Date().toISOString();return`---
|
|
120
141
|
id: ${t}-infrastructure-design
|
|
121
142
|
parent_unit: ${t}
|
|
122
143
|
stage: infrastructure-design
|
|
123
|
-
generated_at: ${
|
|
144
|
+
generated_at: ${i}
|
|
124
145
|
---
|
|
125
146
|
|
|
126
|
-
# Infrastructure Design: ${
|
|
147
|
+
# Infrastructure Design: ${s}
|
|
127
148
|
|
|
128
149
|
## NFR Design Reference
|
|
129
150
|
${o||"No NFR design available."}
|
|
@@ -133,21 +154,21 @@ Infrastructure resource mapping for this unit.
|
|
|
133
154
|
|
|
134
155
|
## Deployment Architecture
|
|
135
156
|
Deployment topology and environment configuration.
|
|
136
|
-
`}extractSection(t,n){try{let o=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(`##\\s+${o}\\s*\\n([\\s\\S]*?)(?=\\n##|$)`,"i").exec(t);return r?r[1].trim():""}catch{return""}}async appendAudit(t,n,o){try{let r=dt.default.join(this.projectPath,"aidlc-docs",this.workflowId,"audit.md"),
|
|
137
|
-
## ${t} Design Stages \u2014 ${
|
|
157
|
+
`}extractSection(t,n){try{let o=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(`##\\s+${o}\\s*\\n([\\s\\S]*?)(?=\\n##|$)`,"i").exec(t);return r?r[1].trim():""}catch{return""}}async appendAudit(t,n,o){try{let r=dt.default.join(this.projectPath,"aidlc-docs",this.workflowId,"audit.md"),s=new Date().toISOString(),i=n.filter(c=>o.stages[c]?.status==="completed"),a=`
|
|
158
|
+
## ${t} Design Stages \u2014 ${s}
|
|
138
159
|
|
|
139
|
-
`+
|
|
160
|
+
`+i.map(c=>`- [x] ${c}: ${o.stages[c].artifact_path}`).join(`
|
|
140
161
|
`)+`
|
|
141
|
-
`;await
|
|
142
|
-
${a}`,"utf-8")}catch(r){console.error(`[UnitStageRunner] Failed to update audit for ${t}:`,r)}}}});function
|
|
143
|
-
`).length}catch{return 0}}function
|
|
162
|
+
`;await Re.default.pathExists(r)?await Re.default.appendFile(r,a,"utf-8"):await Re.default.writeFile(r,`# Audit Trail
|
|
163
|
+
${a}`,"utf-8")}catch(r){console.error(`[UnitStageRunner] Failed to update audit for ${t}:`,r)}}}});function bd(e){try{return(0,rr.readFileSync)(e,"utf8").split(`
|
|
164
|
+
`).length}catch{return 0}}function Cd(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 s=/export\s+(?:.*?\s+from\s+)?['"]([^'"]+)['"]/g;for(;(o=s.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 s=/^from\s+([^\s;#]+)\s+import/gm;for(;(o=s.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 s=/^\s+"([^"]+)"/gm;for(;(o=s.exec(e))!==null;)n.push(o[1])}return n}async function Rd(e){let t={value:0},n={value:0},o={},r=[],s=[],i={},a=[];async function c(f,m){let p={name:At.basename(f),path:f,fileCount:0,children:[]},g;try{g=await ni.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(".")||Td.has(h.name))continue;let y=At.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=At.extname(h.name);if(sr.includes(w)){n.value+=1,o[w]=(o[w]??0)+1,Ed.has(h.name)&&s.push(y);let I=m??"(root)";i[I]||(i[I]=[]),i[I].push({file:y,lines:bd(y)});try{let v=(0,rr.readFileSync)(y,"utf8");for(let O of Cd(v,w))r.push({sourceFile:y,importedModule:O})}catch(v){console.error(`[brownfield-scanner] Cannot read file ${y}:`,v)}}}}return p}let l=[];try{l=await ni.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=At.join(e,f.name);if(f.isDirectory()){if(Td.has(f.name))continue;let p=await c(m,f.name);u.push(p)}else if(f.isFile()){t.value+=1;let p=At.extname(f.name);if(sr.includes(p)){n.value+=1,o[p]=(o[p]??0)+1,Ed.has(f.name)&&s.push(m),i["(root)"]||(i["(root)"]=[]),i["(root)"].push({file:m,lines:bd(m)});try{let h=(0,rr.readFileSync)(m,"utf8");for(let y of Cd(h,p))r.push({sourceFile:m,importedModule:y})}catch(h){console.error(`[brownfield-scanner] Cannot read file ${m}:`,h)}}n_.has(f.name)&&a.push(f.name)}}let d={};for(let[f,m]of Object.entries(i)){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:s,largestFilesByDirectory:d,configFiles:a}}function Id(e,t=20){let n=[],o=new Set;function r(i){o.has(i)||(o.add(i),n.push(i))}for(let i of e.entryPoints.slice(0,5))r(i);let s=Object.keys(e.largestFilesByDirectory).slice(0,10);for(let i of s){let a=e.largestFilesByDirectory[i];a&&a.length>0&&r(a[0])}for(let i of e.configFiles.slice(0,5))r(i);return n.slice(0,t)}function Od(e,t,n=15){let o=t.split(/\s+/).map(d=>d.toLowerCase().replace(/[^a-z0-9]/g,"")).filter(d=>d.length>=3&&!o_.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 s=new Map;for(let d of e.importGraph){let f=s.get(d.sourceFile)??[];f.push(d.importedModule),s.set(d.sourceFile,f)}function i(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 s.get(d)??[])for(let m of i(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 At,ni,rr,Td,n_,Ed,o_,Pd=B(()=>{"use strict";At=E(require("path"),1),ni=E(require("fs/promises"),1),rr=require("fs");ir();Td=new Set(["node_modules",".git","dist","build",".olympus","aidlc-docs",".next","__pycache__",".venv","vendor","target"]),n_=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"]),Ed=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"]),o_=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 i_(e){let t=new Set;for(let n of Object.keys(e.languageDistribution)){let o=r_[n];o&&t.add(o)}for(let n of e.configFiles){let o=s_[n];o&&t.add(o)}return Array.from(t)}function a_(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 xd(e,t){try{cn(e);let n=(0,Ad.join)(Xe(e),"patterns.json"),o=me(n,null),r=i_(t),s=a_(t),i;o?i={...o,tech_stack:Array.from(new Set([...o.tech_stack,...r])),conventions:Array.from(new Set([...o.conventions,...s])),learned_rules:o.learned_rules||[],common_mistakes:o.common_mistakes||[],last_updated:new Date().toISOString()}:i={project_hash:Ic(e),project_path:e,tech_stack:r,conventions:s,learned_rules:[],common_mistakes:[],last_updated:new Date().toISOString()},Be(n,i)}catch(n){console.error("[Olympus Learning] Failed to write project patterns:",n)}}var Ad,r_,s_,$d=B(()=>{"use strict";Ad=require("path");fe();fe();r_={".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"},s_={"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 l_(e,t){let n=e.split(`
|
|
144
165
|
`);return n.length<=t?e:n.slice(0,t).join(`
|
|
145
166
|
`)+`
|
|
146
|
-
... (truncated)`}function
|
|
147
|
-
`)}function
|
|
148
|
-
`),a=o.importGraph.slice(0,50).map(d=>` ${
|
|
167
|
+
... (truncated)`}function jd(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(jd(r.children,t+1));return n.join(`
|
|
168
|
+
`)}function u_(e){try{return(0,Dd.readFileSync)(e,"utf8")}catch{return"(unable to read)"}}function d_(e,t){return io.isAbsolute(e)?e:io.resolve(t,e)}function Nd(e){return e.replace(/\\/g,"/")}function Md(e){let{projectPath:t,featureName:n,scanResult:o,keyFiles:r}=e,s=jd(o.directoryTree,0),i=Object.entries(o.languageDistribution).sort((d,f)=>f[1]-d[1]).map(([d,f])=>` ${d}: ${f} files`).join(`
|
|
169
|
+
`),a=o.importGraph.slice(0,50).map(d=>` ${Nd(d.sourceFile)} -> ${d.importedModule}`).join(`
|
|
149
170
|
`),c=o.importGraph.length>50?`
|
|
150
|
-
... (${o.importGraph.length-50} more edges omitted)`:"",l=r.map(d=>{let f=
|
|
171
|
+
... (${o.importGraph.length-50} more edges omitted)`:"",l=r.map(d=>{let f=d_(d,t),m=u_(f),p=l_(m,200);return`### ${Nd(d)}
|
|
151
172
|
\`\`\`
|
|
152
173
|
${p}
|
|
153
174
|
\`\`\``}).join(`
|
|
@@ -156,10 +177,10 @@ ${p}
|
|
|
156
177
|
`):" (none detected)";return`You are performing a static code analysis of an existing project to support the feature: "${n}".
|
|
157
178
|
|
|
158
179
|
## Project Directory Tree
|
|
159
|
-
${
|
|
180
|
+
${s||" (empty)"}
|
|
160
181
|
|
|
161
182
|
## Language Distribution
|
|
162
|
-
${
|
|
183
|
+
${i||" (none)"}
|
|
163
184
|
|
|
164
185
|
## Import Graph (first 50 edges)
|
|
165
186
|
${a||" (none)"}${c}
|
|
@@ -175,9 +196,9 @@ ${l||"(no key files provided)"}
|
|
|
175
196
|
|
|
176
197
|
Based on the above project structure and source files, produce a Static Code Model.
|
|
177
198
|
|
|
178
|
-
${
|
|
199
|
+
${c_}
|
|
179
200
|
|
|
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
|
|
201
|
+
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 io,Dd,c_,Ld=B(()=>{"use strict";io=E(require("path"),1),Dd=require("fs");z();c_=`A Static Code Model must contain these markdown sections:
|
|
181
202
|
## Modules
|
|
182
203
|
| Name | Path | Responsibility | Public Interface |
|
|
183
204
|
|------|------|----------------|------------------|
|
|
@@ -193,7 +214,7 @@ Be precise and concise. Each module row should capture the real public exports o
|
|
|
193
214
|
(one row per data model)
|
|
194
215
|
|
|
195
216
|
## Configuration Summary
|
|
196
|
-
(paragraph describing configuration approach)`});async function
|
|
217
|
+
(paragraph describing configuration approach)`});async function Fd(e){let t=0;try{let n=await co.readdir(e,{withFileTypes:!0});for(let o of n){if(o.name.startsWith(".")||p_.has(o.name))continue;let r=ao.join(e,o.name);if(o.isDirectory())t+=await Fd(r);else if(o.isFile()){let s=ao.extname(o.name);sr.includes(s)&&t++}}}catch(n){console.error(`Error reading directory ${e}:`,n)}return t}async function Tn(e){let t=await Fd(e);return{isBrownfield:t>=3,sourceFileCount:t}}function m_(e,t){return{"analysis-plan":`# Analysis Plan
|
|
197
218
|
|
|
198
219
|
## Feature: ${t}
|
|
199
220
|
|
|
@@ -305,13 +326,13 @@ Be precise and concise. Each module row should capture the real public exports o
|
|
|
305
326
|
|
|
306
327
|
## Error Handling Patterns
|
|
307
328
|
<!-- How errors propagate and are handled -->
|
|
308
|
-
`,"workspace-scan":""}[e]}async function
|
|
309
|
-
`,"utf-8"),t}function
|
|
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)(
|
|
329
|
+
`,"workspace-scan":""}[e]}async function Ud(e){let{projectPath:t,workflowId:n,featureName:o,manifestPath:r}=e;try{await Gs(t,n);let s=new Date().toISOString();ut(r,"discovery","in_progress",s);let i=[];for(let d of f_){if(d==="workspace-scan")continue;let f=m_(d,o),m=Ot(t,n,d);await hn(t,n,d,f),i.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 Rd(t);xd(t,d);let f=Id(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=Od(d,o),p=Ot(t,n,"workspace-scan");await hn(t,n,"workspace-scan",JSON.stringify(d,null,2)),i.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=Md({projectPath:t,workflowId:n,featureName:o,scanResult:d,keyFiles:f,relevantFiles:m,intentText:o}),y=ao.join(t,"aidlc-docs",n,"discovery","static-model-prompt.md");await Gs(t,n),await co.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 T(t,n);return u&&(u.current_phase="discovery",u.phases.discovery.status="blocked",await A(t,u)),{completed:!1,gateRequired:!0,artifactsGenerated:i,sourceFileCount:a,brownfieldData:l}}catch(s){throw console.error("[Discovery] Error executing discovery phase:",s),new Error(`Discovery phase failed: ${s instanceof Error?s.message:String(s)}`)}}var ao,co,sr,p_,f_,ir=B(()=>{"use strict";ao=E(require("path"),1),co=E(se(),1);qs();z();we();Pd();$d();Ld();sr=[".ts",".tsx",".js",".jsx",".py",".go",".rs",".java",".c",".cpp",".cs",".rb",".swift",".kt",".css",".scss",".html",".vue",".svelte"],p_=new Set(["node_modules",".git","dist","build",".olympus","aidlc-docs",".next","__pycache__",".venv","vendor","target"]),f_=["analysis-plan","current-state-analysis","regression-baseline","change-impact","static-model","dynamic-model","workspace-scan"]});function ie(e){let t={...e,id:(0,Bd.randomUUID)(),timestamp:new Date().toISOString(),verified:!1,verification_count:0,last_useful:new Date().toISOString()},n=t.scope==="global"?ce():Xe(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)+`
|
|
330
|
+
`,"utf-8"),t}function w_(e){let t=(0,xt.join)(ce(),"discoveries.jsonl"),n=Xe(e),o=(0,xt.join)(n,"discoveries.jsonl"),r=Hd(t),s=Hd(o),i=[...r,...s],a={technical_insight:0,workaround:0,pattern:0,gotcha:0,performance:0,dependency:0,configuration:0,planning_insight:0,workflow_gate:0,retro_insight:0};for(let l of i)a[l.category]++;let c=[...i].sort((l,u)=>u.verification_count-l.verification_count);return{project_discoveries:s,global_discoveries:r,total_discoveries:i.length,categories:a,most_useful:c.slice(0,5)}}function Gd(e,t){let n=(0,xt.join)(ce(),"discoveries.jsonl"),o=(0,xt.join)(t,".olympus","learning","discoveries.jsonl"),r=s=>{if(!(0,Ne.existsSync)(s))return!1;let a=(0,Ne.readFileSync)(s,"utf-8").trim().split(`
|
|
331
|
+
`).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)(s);(0,Ne.existsSync)(u)||(0,Ne.mkdirSync)(u,{recursive:!0}),(0,Ne.writeFileSync)(s,l.join(`
|
|
311
332
|
`)+`
|
|
312
|
-
`,"utf-8")}return c};r(o)||r(n)}function
|
|
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,
|
|
314
|
-
`),r=t.stages.map((i
|
|
333
|
+
`,"utf-8")}return c};r(o)||r(n)}function ar(e,t=10){let n=w_(e),o=[...n.project_discoveries,...n.global_discoveries],r=new Date,i=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 i.sort((a,c)=>c.score-a.score),i.slice(0,t).map(a=>a.discovery)}function Hd(e){if(!(0,Ne.existsSync)(e))return[];try{return(0,Ne.readFileSync)(e,"utf-8").split(`
|
|
334
|
+
`).filter(n=>n.trim()).map(n=>JSON.parse(n))}catch(t){return console.error(`[Olympus Learning] Failed to read discoveries: ${t}`),[]}}var xt,Ne,Bd,pt=B(()=>{"use strict";xt=require("path"),Ne=require("fs"),Bd=require("crypto");fe()});async function qd(e,t){let{isBrownfield:n}=await Tn(e);if(!n)return"greenfield";let o=t.toLowerCase();for(let{pathway:r,keywords:s}of __)for(let i of s)if(o.includes(i))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 cr(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 v_(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 T_(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 Vd(e){let{pathwayType:t,depthAssessment:n,sourceFileCount:o}=e,{recommended_depth:r,total_score:s,risk_tier:i}=n,a=S_(t),c={discovery:{included:a.discovery,rationale:cr("discovery",t,a.discovery)},inception:{included:a.inception,rationale:cr("inception",t,a.inception)},construction:{included:a.construction,rationale:cr("construction",t,a.construction)},operations:{included:a.operations,rationale:cr("operations",t,a.operations)}},l=["discovery","inception","construction","operations"],u=[];for(let m of l)if(a[m])for(let p of v_(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",I=!0;g&&r==="minimal"&&(I=!1),h&&t==="greenfield"&&(I=!1),(y||w)&&(t==="bugfix"||t==="optimization")&&(I=!1),k&&r==="minimal"&&(I=!1),u.push({phase:m,stage:p,included:I,rationale:T_(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=s<=10?"LOW":s<=20?"MEDIUM":"HIGH";return{pathway:t,risk_assessment:f,risk_tier:i.tier,phases:c,stages:u,estimated_code_generations:d,estimated_depth:r,generated_at:new Date().toISOString(),approved_at:null,approved_by:null}}function E_(e,t){let o=["discovery","inception","construction","operations"].map(s=>{let{included:i,rationale:a}=t.phases[s];return`| ${s} | ${i?"yes":"no"} | ${a} |`}).join(`
|
|
335
|
+
`),r=t.stages.map((s,i)=>`| ${i+1} | ${s.phase} | ${s.stage} | ${s.included?"yes":"no"} | ${s.rationale} |`).join(`
|
|
315
336
|
`);return`# Workflow Routing: ${e}
|
|
316
337
|
|
|
317
338
|
**Pathway:** ${t.pathway}
|
|
@@ -333,18 +354,18 @@ ${o}
|
|
|
333
354
|
| # | Phase | Stage | Included | Rationale |
|
|
334
355
|
|---|-------|-------|----------|-----------|
|
|
335
356
|
${r}
|
|
336
|
-
`}async function
|
|
357
|
+
`}async function oi(e,t,n){let o=Jt.join(e,"aidlc-docs",t,"inception","plans"),r=Jt.join(o,"workflow-routing.md"),s=Jt.posix.join("aidlc-docs",t,"inception","plans","workflow-routing.md");try{await lr.mkdir(o,{recursive:!0});let a=E_(t,n),c=R_(n),l=a+`
|
|
337
358
|
## Execution Plan Visualization
|
|
338
359
|
|
|
339
360
|
`+c+`
|
|
340
|
-
`;await
|
|
341
|
-
`)){let r=o.split("|").map(
|
|
342
|
-
`)){let r=o.split("|").map(
|
|
343
|
-
`)}var Jt,
|
|
344
|
-
`)}function
|
|
361
|
+
`;await lr.writeFile(r,l,"utf-8")}catch(a){throw console.error("[WorkflowRouting] Failed to write artifact:",a),a}let i=Jt.join(e,"aidlc-docs",t,"manifest.json");return xe(i,{id:`WORKFLOW-ROUTING-${t}`,type:"WORKFLOW_ROUTING",phase:"inception",stage:"intent",path:s,validation_passed:!0,write_complete:!0,checksum:null}),s}function b_(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(`
|
|
362
|
+
`)){let r=o.split("|").map(s=>s.trim()).filter(Boolean);if(r.length>=3){let[s,i,...a]=r;t[s]={included:i.toLowerCase()==="yes",rationale:a.join(" | ")}}}return t}function C_(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(`
|
|
363
|
+
`)){let r=o.split("|").map(s=>s.trim()).filter(Boolean);if(r.length>=5){let[s,i,a,c,...l]=r;t.push({phase:i,stage:a,included:c.toLowerCase()==="yes",rationale:l.join(" | ")})}}return t}function dr(e,t){let n=Jt.join(e,"aidlc-docs",t,"inception","plans","workflow-routing.md");if(!(0,ur.existsSync)(n))return null;let o;try{o=(0,ur.readFileSync)(n,"utf-8")}catch(r){return console.error("[WorkflowRouting] Failed to read artifact:",r),null}try{let r=o.match(/\*\*Pathway:\*\*\s*(.+)/),s=o.match(/\*\*Risk Assessment:\*\*\s*(.+)/),i=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||!s||!i||!a||!c||!l)return console.error("[WorkflowRouting] Missing required header fields"),null;let d=u?u[1].trim():"Pending",f=b_(o);return{pathway:r[1].trim(),risk_assessment:s[1].trim(),risk_tier:parseInt(i[1].trim(),10),estimated_code_generations:parseInt(a[1].trim(),10),estimated_depth:c[1].trim(),generated_at:l[1].trim(),approved_at:d==="Pending"?null:d,approved_by:null,phases:{discovery:f.discovery??{included:!0,rationale:""},inception:f.inception??{included:!0,rationale:""},construction:f.construction??{included:!0,rationale:""},operations:f.operations??{included:!0,rationale:""}},stages:C_(o)}}catch(r){return console.error("[WorkflowRouting] Failed to parse artifact:",r),null}}function ri(e,t){return e.phases[t]?.included??!0}function Yd(e,t,n){return e.stages.find(r=>r.phase===t&&r.stage===n)?.included??!0}function R_(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],s=o.charAt(0).toUpperCase()+o.slice(1);if(r.included){t.push(` subgraph ${s}["${s} Phase"]`);let i=e.stages.filter(c=>c.phase===o);for(let c of i){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=i.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 i=`${o}_skip`;t.push(` ${i}["${s} (SKIPPED)"]`),t.push(` class ${i} skip`)}t.push("")}for(let o=0;o<n.length-1;o++){let r=n[o],s=n[o+1],i=e.stages.filter(f=>f.phase===r),a=e.stages.filter(f=>f.phase===s),c=e.phases[r].included,l=e.phases[s].included,u,d;c&&i.length>0?u=`${r}_${i[i.length-1].stage.replace(/-/g,"_")}`:u=`${r}_skip`,l&&a.length>0?d=`${s}_${a[0].stage.replace(/-/g,"_")}`:d=`${s}_skip`,!c||!l?t.push(` ${u} -.-> ${d}`):t.push(` ${u} --> ${d}`)}return t.push("```"),t.join(`
|
|
364
|
+
`)}var Jt,lr,ur,__,si=B(()=>{"use strict";Jt=E(require("path"),1),lr=E(require("fs/promises"),1),ur=require("fs");ir();z();__=[{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 B_(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function G_(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 q_(e){let{inception_stages:t,current_inception_stage:n}=e;if(!t)return[];let o=[];for(let r of H_){let s=t[r];if(!s)continue;let i=B_(r),a=n===r,c,l;s.status==="completed"?(c="[x]",l=s.completed_at?`(completed ${s.completed_at})`:"(completed)"):s.status==="skipped"?(c="[ ]",l=s.skip_reason?`(skipped -- ${s.skip_reason})`:"(skipped)"):(c="[ ]",l="");let u=` - ${c} ${i} ${l}`.trimEnd();a&&(u+=" <- CURRENT"),o.push(u)}return o}function V_(e){let t=["## Progress"];for(let n of W_){let o=e.phases[n],r,s;o?.completed_at?(r="[x]",s=`(completed ${o.completed_at})`):e.current_phase===n?(r="[ ]",s="(in progress)"):(r="[ ]",s="");let i=n.charAt(0).toUpperCase()+n.slice(1);if(t.push(`- ${r} ${i} ${s}`.trimEnd()),n==="inception"&&e.inception_stages){let a=q_(e);t.push(...a)}}return t.join(`
|
|
365
|
+
`)}function Y_(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
366
|
`);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
|
|
347
|
-
`)}function
|
|
367
|
+
`)}function K_(e,t){let n=["## Key Artifacts",""];n.push("| Artifact | Path | Status |"),n.push("|----------|------|--------|");let o=Cn.join(e,lo,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 s of r){let i=ft.existsSync(Cn.join(o,s.path));n.push(`| ${s.name} | ${s.path} | ${i?"created":"pending"} |`)}return n.join(`
|
|
368
|
+
`)}function ii(e,t,n){let o=Cn.join(e,lo,t,ep);try{let r=G_(n.feature_name),s=V_(n),i=Y_(n),a=K_(e,t),c=`# ${r}
|
|
348
369
|
|
|
349
370
|
| Field | Value |
|
|
350
371
|
|-------|-------|
|
|
@@ -362,21 +383,21 @@ ${r}
|
|
|
362
383
|
|
|
363
384
|
${n.feature_name}
|
|
364
385
|
|
|
365
|
-
${i}
|
|
366
|
-
|
|
367
386
|
${s}
|
|
368
387
|
|
|
388
|
+
${i}
|
|
389
|
+
|
|
369
390
|
${a}
|
|
370
391
|
|
|
371
392
|
## Code Location
|
|
372
393
|
|
|
373
394
|
Application Code: ${e} (NEVER in aidlc-docs/)
|
|
374
|
-
Documentation: ${
|
|
375
|
-
`;ft.ensureDirSync(Cn.join(e,
|
|
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
|
|
377
|
-
`)}async function
|
|
378
|
-
`);je.ensureDirSync(
|
|
379
|
-
`;je.appendFileSync(o,r,"utf-8")}catch(o){console.error(`Failed to append to audit for workflow ${t}:`,o)}}var je,
|
|
395
|
+
Documentation: ${lo}/${t}/
|
|
396
|
+
`;ft.ensureDirSync(Cn.join(e,lo,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 mr(e,t,n,o){let r=Cn.join(e,lo,t,ep);try{let s=ft.readFileSync(r,"utf-8"),i=new RegExp(`^(- \\[[ x\\-]\\] ${n}.*)$`,"im"),a=s;o==="completed"?a=a.replace(i,(u,d)=>`${d.replace(/\[[ x\-]\]/,"[x]").replace(/\s*\(.*?\)\s*$/,"").replace(/\s*← CURRENT\s*$/,"")} (completed ${new Date().toISOString()})`):o==="in_progress"?a=a.replace(i,(u,d)=>`${d.replace(/\[[ x\-]\]/,"[ ]").replace(/\s*\(.*?\)\s*$/,"").replace(/\s*← CURRENT\s*$/,"")} \u2190 CURRENT`):o==="skipped"&&(a=a.replace(i,(u,d)=>`${d.replace(/\[[ x\-]\]/,"[-]").replace(/\s*\(.*?\)\s*$/,"").replace(/\s*← CURRENT\s*$/,"")} (skipped)`));let c=/\| \*\*Last Updated\*\* \| .+? \|/,l=/^\*\*Last Updated\*\*: .+$/m;c.test(a)?a=a.replace(c,`| **Last Updated** | ${new Date().toISOString()} |`):a=a.replace(l,`**Last Updated**: ${new Date().toISOString()}`),ft.writeFileSync(r,a,"utf-8")}catch(s){console.error(`[StateFile] Failed to update state file for workflow ${t}:`,s.message)}}var Cn,ft,lo,ep,W_,H_,ai=B(()=>{"use strict";Cn=E(require("path"),1),ft=E(se(),1),lo="aidlc-docs",ep="aidlc-state.md",W_=["discovery","inception","construction","operations"],H_=["workspace-detection","reverse-engineering","requirements-analysis","user-stories","workflow-planning","application-design","units-generation"]});function tp(){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 _e(e){try{let t=e||process.cwd(),n=(0,gr.join)(t,np);if(!(0,mt.existsSync)(n))return tp();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),tp()}}function ci(e,t){try{let n=t||process.cwd(),o=(0,gr.join)(n,".olympus"),r=(0,gr.join)(n,np);(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 J_(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 li(e,t,n,o){let r=e.total_transitions+1,s=n?e.rejection_count+1:e.rejection_count,i=s/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:s,rejection_rate:i,consecutive_rejections:a,transition_history:l},d=J_(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 op(e,t){return t>=e}var mt,gr,np,$t=B(()=>{"use strict";mt=require("fs"),gr=require("path"),np=".olympus/trust-state.json"});function rp(e,t){let n=t||"",o=n?(0,Rn.join)(e,"aidlc-docs",n,"manifest.json"):(0,Rn.join)(e,"aidlc-docs","manifest.json"),r=D(o),s=_e(e),i={workflowId:"",featureName:"",gateRejections:[],cascadeEvents:[],trustDecreases:[],ciFailureCount:0,totalGates:0,totalRejections:0};if(!r)return i;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=(s?.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,Rn.join)(e,"aidlc-docs",n,"construction"):(0,Rn.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,Rn.join)(d,g,"validation-report.md");if((0,gt.existsSync)(h)){let w=(0,gt.readFileSync)(h,"utf-8").split(`
|
|
397
|
+
`);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 sp(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 s=r.length,i=s>=3?"High":s===2?"Medium":"Low",c=`Gate rejections in ${r.map(u=>u.phase).join(", ")} with reason: "${o}"`,l=s>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:i,occurrences:s})}if(e.trustDecreases.length>0){let o=e.trustDecreases.length,r=o>=3?"High":o===2?"Medium":"Low",s=e.trustDecreases.map(i=>`${i.from} \u2192 ${i.to} (${i.reason})`).join("; ");t.push({description:"Trust level decreases detected",evidence:`Trust trajectory: ${s}`,suggestion:"Improve code quality and validation processes to rebuild trust. Consider more thorough review before gate submissions.",confidence:r,occurrences:o})}if(e.cascadeEvents.length>0){let o=e.cascadeEvents.length,r=o>=3?"High":o===2?"Medium":"Low",s=[...new Set(e.cascadeEvents.map(i=>i.artifactId))].join(", ");t.push({description:"Cascade invalidation events",evidence:`${o} invalidation event(s) affecting: ${s}`,suggestion:"Strengthen contract verification and dependency validation to prevent cascading failures. Consider improving artifact stability.",confidence:r,occurrences:o})}return t}var gt,Rn,ip=B(()=>{"use strict";gt=require("fs"),Rn=require("path");z();$t();pt()});function z_(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 Q_(e){let t=e.artifacts||[],n=e.links||[];return t.filter(r=>r.stage==="intent").map(r=>{let s=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")),i=[];for(let c of s){let l=n.filter(u=>u.source_id===c&&(u.link_type==="derives"||u.link_type==="implements")).map(u=>u.target_id).filter(u=>t.some(d=>d.id===u&&d.stage==="code-generation"));i.push(...l)}let a=[...new Set(i.flatMap(c=>{let l=t.find(d=>d.id===c);if(!l)return[];let u=rt.extname(l.path).toLowerCase();return u&&u!==".md"&&u!==".json"?[l.path]:[]}))];return{intentId:r.id,unitIds:s,codeGenerationIds:[...new Set(i)],codeFiles:a}})}function X_(e){return(e.level_history||[]).map(t=>({from:t.from,to:t.to,reason:t.reason,timestamp:t.timestamp}))}function Z_(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 s=o[r-1],i=o[r],a=i.status.toLowerCase();(a.includes("stale")||a.includes("violated"))&&t.push({artifactId:n.id,previousStatus:s.status,newStatus:i.status,reason:n.stale_reason??`Artifact transitioned to ${i.status}`,timestamp:i.timestamp})}}return t.sort((n,o)=>n.timestamp.localeCompare(o.timestamp))}function ap(e){return{workflowId:e,featureName:"",generatedAt:new Date().toISOString(),timeline:[],traceabilityMatrix:[],trustHistory:[],cascadeEvents:[],retroInsights:[]}}function cp(e,t){try{let n=rt.join(e,"aidlc-docs",t,"manifest.json"),o=D(n);if(!o)return ap(t);let r=_e(e),s=rp(e,t),a=sp(s).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:z_(o),traceabilityMatrix:Q_(o),trustHistory:X_(r),cascadeEvents:Z_(o),retroInsights:a}}catch(n){return console.error(`Failed to generate audit document for workflow ${t}:`,n),ap(t)}}function ui(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",s=n.codeFiles.length>0?n.codeFiles.join(", "):"\u2014";t.push(`| ${n.intentId} | ${o} | ${r} | ${s} |`)}}if(t.push(""),t.push("## Trust History"),t.push(""),e.trustHistory.length===0)t.push("_No trust level changes recorded._");else{t.push("| From | To | Reason | Timestamp |"),t.push("|------|----|--------|-----------|");for(let n of e.trustHistory)t.push(`| ${n.from} | ${n.to} | ${n.reason} | ${n.timestamp} |`)}if(t.push(""),t.push("## Cascade Events"),t.push(""),e.cascadeEvents.length===0)t.push("_No cascade invalidation events recorded._");else for(let n of e.cascadeEvents)t.push(`- **${n.artifactId}**: \`${n.previousStatus}\` \u2192 \`${n.newStatus}\` \u2014 ${n.reason} _(${n.timestamp})_`);if(t.push(""),t.push("## Retrospective Insights"),t.push(""),e.retroInsights.length===0)t.push("_No retrospective insights available._");else for(let n of e.retroInsights)t.push(`- ${n}`);return t.push(""),t.join(`
|
|
398
|
+
`)}async function lp(e,t,n){let o=rt.join(e,"aidlc-docs",t),r=rt.join(o,"audit.md"),s=rt.join(o,"manifest.json");try{let i=ui(n);await je.ensureDir(o),await je.writeFile(r,i,"utf-8"),xe(s,{id:`audit-${t}`,type:"AUDIT",phase:"operations",stage:"complete",path:r,validation_passed:null,write_complete:!0,checksum:null})}catch(i){console.error(`Failed to write audit artifact for workflow ${t}:`,i)}return r}function up(e,t,n){try{let o=rt.join(e,"aidlc-docs",t,"audit.md");if(!je.existsSync(o)){let s=["# Audit Report","",`Generated: ${new Date().toISOString()}`,`Workflow ID: ${t}`,"","## Timeline","","| Timestamp | Phase | Action | Actor | Reason |","|-----------|-------|--------|-------|--------|",""].join(`
|
|
399
|
+
`);je.ensureDirSync(rt.dirname(o)),je.writeFileSync(o,s,"utf-8")}let r=`| ${n.timestamp} | ${n.phase} | ${n.action} | ${n.actor} | ${n.reason??"\u2014"} |
|
|
400
|
+
`;je.appendFileSync(o,r,"utf-8")}catch(o){console.error(`Failed to append to audit for workflow ${t}:`,o)}}var je,rt,dp=B(()=>{"use strict";je=E(se(),1),rt=E(require("path"),1);z();$t();ip()});var yp={};Je(yp,{InceptionOrchestrator:()=>mi,registerStageHandler:()=>eS});function eS(e,t){fi[e]=t}function pp(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 di(e,t,n){return n&&!Yd(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 fp(e){for(let t of st){let n=e[t];if(n&&(n.status==="not_started"||n.status==="in_progress"))return t}return null}function tS(e,t){let n=st.indexOf(e);for(let o=n+1;o<st.length;o++){let r=st[o],s=t[r];if(s&&(s.status==="not_started"||s.status==="in_progress"))return r}}async function nS(e,t,n){if(!n.trust_state_path)return 0;try{let o=(0,hp.join)(e,"aidlc-docs",t,n.trust_state_path),r=await gp.readFile(o,"utf-8");return JSON.parse(r).current_level??0}catch{return 0}}function oS(e,t,n){let o=e==="workspace-detection",r=t.status==="awaiting_answers";return!(n>=3||n>=2&&!r||n>=1&&o&&!r)}function mp(e){return st.every(t=>{let n=e[t];return n&&(n.status==="completed"||n.status==="skipped")})}function rS(e){let t=e.phases?.discovery;if(!t)return!1;let n=t.status;return n==="complete"||n==="completed"}function pi(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 gp,hp,fi,st,mi,kp=B(()=>{"use strict";gp=E(se(),1),hp=require("path");we();ai();dp();si();fi={};st=["workspace-detection","reverse-engineering","requirements-analysis","user-stories","workflow-planning","application-design","units-generation"];mi=class{async migrateCheckpoint(t,n){let o=await T(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 st){let{skipReason:l}=di(c,r,null);a[c]=pi(c,l)}return o.inception_stages=a,o.current_inception_stage=void 0,await A(t,o),Rt(t,n),{migrated:!0,case:"already_past_inception"}}let s={};for(let a of st){let{status:c,skipReason:l}=di(a,r,null);s[a]=pp(a,c,l)}s["workspace-detection"].status!=="skipped"&&(s["workspace-detection"]=pi("workspace-detection")),s["reverse-engineering"].status!=="skipped"&&rS(o)&&(s["reverse-engineering"]=pi("reverse-engineering")),o.inception_stages=s;let i=fp(s);return o.current_inception_stage=i??void 0,await A(t,o),Rt(t,n),{migrated:!0,case:"paused_at_intent"}}async initialize(t,n,o,r){let s=await T(t,n);if(!s)throw new Error(`[InceptionOrchestrator] Checkpoint not found for workflow ${n}`);if(s.inception_stages)return;let i={},a;for(let c of st){let{status:l,skipReason:u}=di(c,o,r);i[c]=pp(c,l,u),!a&&l==="not_started"&&(a=c)}s.inception_stages=i,s.current_inception_stage=a??void 0,await A(t,s),Rt(t,n)}async executeNextStage(t,n){let o=await T(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 s=fp(r);if(!s)return{stage:"units-generation",status:"completed",requires_approval:!1,artifacts_generated:[],whats_next:"Inception is complete. Proceed to construction phase."};r[s].status="in_progress",r[s].started_at=new Date().toISOString(),o.current_inception_stage=s,await A(t,o),Rt(t,n);let i=fi[s],a;if(i)try{a=await i(t,n,o)}catch(c){let l=c;console.error(`[InceptionOrchestrator] Stage '${s}' handler threw:`,l.message);let u=await T(t,n);return u?.inception_stages&&(u.inception_stages[s].status="not_started",u.inception_stages[s].started_at=null,await A(t,u),Rt(t,n)),{stage:s,status:"review_required",requires_approval:!0,artifacts_generated:[],review_summary:`Stage '${s}' failed with error: ${l.message}`}}else a={stage:s,status:"completed",requires_approval:!0,artifacts_generated:[],review_summary:`Stage '${s}' has no handler registered yet.`,whats_next:"This stage will be implemented in a future TODO."};return await this._postStage(t,n,s,a),a}async processAnswers(t,n,o){let r=await T(t,n);if(!r)throw new Error(`[InceptionOrchestrator] Checkpoint not found for workflow ${n}`);let s=r.inception_stages;if(!s)throw new Error(`[InceptionOrchestrator] inception_stages not initialized for workflow ${n}`);let i=s[o];if(!i||i.status!=="in_progress")throw new Error(`[InceptionOrchestrator] Stage '${o}' is not in_progress (status: ${i?.status??"unknown"})`);let a=fi[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 T(t,n);if(!o)throw new Error(`[InceptionOrchestrator] Checkpoint not found for workflow ${n}`);let r=o.inception_stages??{},s=st.length,i=0,a=0;for(let c of st){let l=r[c];l&&(l.status==="completed"&&i++,l.status==="skipped"&&a++)}return{total_stages:s,completed_stages:i,skipped_stages:a,current_stage:o.current_inception_stage??null,stages:r}}async isComplete(t,n){let o=await T(t,n);return o?.inception_stages?mp(o.inception_stages):!1}async _postStage(t,n,o,r){let s=await T(t,n);if(!s?.inception_stages)return;let i=s.inception_stages,a=new Date().toISOString();r.status==="completed"?(i[o].status="completed",i[o].completed_at=a,i[o].artifacts_generated=r.artifacts_generated):r.status==="awaiting_answers"?(i[o].status="in_progress",i[o].questions_file=r.questions_file??null):r.status==="skipped"&&(i[o].status="skipped",i[o].completed_at=a),(r.status==="completed"||r.status==="skipped")&&(s.current_inception_stage=tS(o,i)),await A(t,s),Rt(t,n);try{r.status==="completed"?mr(t,n,o,"completed"):r.status==="awaiting_answers"?mr(t,n,o,"in_progress"):r.status==="skipped"&&mr(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};up(t,n,u)}catch(u){console.error(`[InceptionOrchestrator] Failed to append to audit for stage ${o}:`,u.message)}if(mp(i))try{let u=cp(t,n);ui(u),await lp(t,n,u)}catch(u){console.error("[InceptionOrchestrator] Failed to generate final audit document:",u.message)}try{let u=await nS(t,n,s);r.requires_approval=oS(o,r,u)}catch(u){console.error("[InceptionOrchestrator] Failed to compute trust level:",u.message),r.requires_approval=!0}let l=await T(t,n);l?.current_inception_stage&&(r.next_stage=l.current_inception_stage)}}});var Ep={};Je(Ep,{generateCostAnalysis:()=>Tp,generateDeployGuide:()=>wp,generateMonitoringConfig:()=>Sp,generateOperationsArtifacts:()=>sS,generateReleaseNotes:()=>vp,generateRunbook:()=>_p});function wp(e){let{featureName:t,workflowId:n,manifest:o}=e,r=new Date().toISOString(),s=o?.artifacts?.length??0,i=o?.artifacts?.filter(c=>c.phase==="inception").length??0,a=o?.artifacts?.filter(c=>c.phase==="construction").length??0;return`---
|
|
380
401
|
id: DEPLOY-GUIDE-001
|
|
381
402
|
feature: ${n}
|
|
382
403
|
created: ${r}
|
|
@@ -389,7 +410,7 @@ stage: deploy
|
|
|
389
410
|
## Overview
|
|
390
411
|
|
|
391
412
|
This deployment guide documents the deployment process for ${t}.
|
|
392
|
-
Generated from ${
|
|
413
|
+
Generated from ${s} artifacts (${i} Inception, ${a} Construction).
|
|
393
414
|
|
|
394
415
|
## Pre-Deployment Checklist
|
|
395
416
|
|
|
@@ -442,7 +463,7 @@ Generated from ${i} artifacts (${s} Inception, ${a} Construction).
|
|
|
442
463
|
|
|
443
464
|
---
|
|
444
465
|
*Generated by Operations Phase Templates*
|
|
445
|
-
`}function
|
|
466
|
+
`}function _p(e){let{featureName:t,workflowId:n}=e,o=new Date().toISOString();return`---
|
|
446
467
|
id: RUNBOOK-001
|
|
447
468
|
feature: ${n}
|
|
448
469
|
created: ${o}
|
|
@@ -526,7 +547,7 @@ grep -i error /var/log/service/${n}.log | tail -20
|
|
|
526
547
|
|
|
527
548
|
---
|
|
528
549
|
*Generated by Operations Phase Templates*
|
|
529
|
-
`}function
|
|
550
|
+
`}function Sp(e){let{featureName:t,workflowId:n,manifest:o}=e,r=new Date().toISOString(),s=o?.risk_tier?.tier??2,i=s===3?.5:s===2?1:2,a=s===3?500:s===2?1e3:2e3,l={id:"MONITORING-001",feature:n,feature_name:t,created:r,phase:"operations",stage:"monitor",risk_tier:s,health_checks:{endpoint:"/health",interval_seconds:s===3?30:s===2?60:120,timeout_seconds:5,unhealthy_threshold:3},alerts:[{name:`${n}-error-rate`,metric:"error_rate_percent",threshold:i,window_seconds:300,severity:"critical",notification_channels:["pagerduty","slack"]},{name:`${n}-latency-p99`,metric:"latency_p99_ms",threshold:a,window_seconds:300,severity:"warning",notification_channels:["slack"]},{name:`${n}-availability`,metric:"availability_percent",threshold:99.9,comparison:"less_than",window_seconds:3600,severity:"critical",notification_channels:["pagerduty","slack"]}],dashboards:{overview:{panels:[{title:"Request Rate",metric:"request_rate",type:"timeseries"},{title:"Error Rate",metric:"error_rate_percent",type:"timeseries"},{title:"Latency (p50/p95/p99)",metric:"latency_percentiles",type:"timeseries"},{title:"Availability",metric:"availability_percent",type:"stat"}]}},logging:{level:s===3?"debug":"info",retention_days:s===3?90:s===2?60:30,structured:!0}};return JSON.stringify(l,null,2)}function vp(e){let{featureName:t,workflowId:n,manifest:o}=e,r=new Date().toISOString(),s=o?.artifacts??[],i=s.filter(p=>p.phase==="inception"),a=s.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=s.map(p=>`- **${p.id}** (${p.phase}/${p.stage}): ${p.contract_status}`).join(`
|
|
530
551
|
`);return`---
|
|
531
552
|
id: RELEASE-NOTES-001
|
|
532
553
|
feature: ${n}
|
|
@@ -542,14 +563,14 @@ stage: deploy
|
|
|
542
563
|
**Feature**: ${t}
|
|
543
564
|
**Workflow ID**: ${n}
|
|
544
565
|
**Date**: ${r.split("T")[0]}
|
|
545
|
-
**Total Artifacts**: ${
|
|
566
|
+
**Total Artifacts**: ${s.length}
|
|
546
567
|
**Quality Gates Passed**: ${f.length}
|
|
547
568
|
|
|
548
569
|
## What's New
|
|
549
570
|
|
|
550
571
|
Implementation of ${t} following the AI-Driven Development Life Cycle (AIDLC) methodology.
|
|
551
572
|
|
|
552
|
-
### Inception Phase (${
|
|
573
|
+
### Inception Phase (${i.length} artifacts)
|
|
553
574
|
- INTENT: Problem definition and depth assessment
|
|
554
575
|
- PRD: Product requirements with user stories
|
|
555
576
|
- SPEC: Technical specification and architecture
|
|
@@ -592,7 +613,7 @@ This is a new feature deployment. No migration from previous versions required.
|
|
|
592
613
|
|
|
593
614
|
---
|
|
594
615
|
*Generated by Operations Phase Templates*
|
|
595
|
-
`}function
|
|
616
|
+
`}function Tp(e){let{featureName:t,workflowId:n,manifest:o}=e,r=new Date().toISOString(),s=o?.artifacts??[],i=s.filter(d=>d.stage==="code-generation"),a=s.filter(d=>d.stage==="unit"),l=(o?.gate_audit??[]).filter(d=>d.action==="rejected"),u=o?.metrics??null;return`---
|
|
596
617
|
id: COST-001
|
|
597
618
|
feature: ${n}
|
|
598
619
|
created: ${r}
|
|
@@ -606,9 +627,9 @@ phase: operations
|
|
|
606
627
|
| Metric | Value |
|
|
607
628
|
|--------|-------|
|
|
608
629
|
| Total UNITs | ${a.length} |
|
|
609
|
-
| Total Code Generations | ${
|
|
630
|
+
| Total Code Generations | ${i.length} |
|
|
610
631
|
| Gate Rejections | ${l.length} |
|
|
611
|
-
| Total Artifacts | ${
|
|
632
|
+
| Total Artifacts | ${s.length} |
|
|
612
633
|
|
|
613
634
|
## Agent Execution Summary
|
|
614
635
|
|
|
@@ -634,32 +655,32 @@ Estimated rework overhead: ${l.length} rejection cycle(s)
|
|
|
634
655
|
|
|
635
656
|
## Recommendations
|
|
636
657
|
|
|
637
|
-
${
|
|
658
|
+
${i.length>10?"- Consider breaking future features into smaller INTENTs to reduce code generation count":"- Code generation count is within recommended range"}
|
|
638
659
|
${l.length>2?"- High rejection rate suggests specification clarity could be improved":"- Rejection rate is acceptable"}
|
|
639
660
|
|
|
640
661
|
---
|
|
641
662
|
*Generated by Operations Phase Templates*
|
|
642
|
-
`}async function
|
|
643
|
-
`)){let a=
|
|
663
|
+
`}async function sS(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"),vp(e),"utf-8"),o.push("release-notes.md"),r==="SHALLOW"?{artifactsGenerated:o,operationsDir:n}:(await Nt.writeFile(zt.join(n,"deploy-guide.md"),wp(e),"utf-8"),o.push("deploy-guide.md"),await Nt.writeFile(zt.join(n,"runbook.md"),_p(e),"utf-8"),o.push("runbook.md"),await Nt.writeFile(zt.join(n,"monitoring.json"),Sp(e),"utf-8"),o.push("monitoring.json"),await Nt.writeFile(zt.join(n,"cost.md"),Tp(e),"utf-8"),o.push("cost.md"),{artifactsGenerated:o,operationsDir:n})}var Nt,zt,bp=B(()=>{"use strict";Nt=E(se(),1),zt=E(require("path"),1)});var tg={};Je(tg,{formatSessionSummaryLine:()=>mT});function mT(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,s;o>0?s=`${o}m ${r}s`:s=`${r}s`;let i=e.total_tokens.toLocaleString("en-US"),a=`$${e.estimated_cost.toFixed(e.estimated_cost>=.01?2:3)}`,c=e.agents_used.length,u=`[Olympus] Session: ${c} ${c===1?"agent":"agents"} (${t}) | ${i} tokens | ${a} | ${s}`;return u.length>200&&(u=u.substring(0,197)+"..."),u}var ng=B(()=>{"use strict"});function ug(e){if(!e)return[];let t=e.toLowerCase(),n=[];for(let[o,r]of Object.entries(hT))for(let s of r)if(t.includes(s)){n.push(o);break}return n}var hT,dg=B(()=>{"use strict";hT={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 mg={};Je(mg,{COLD_START_FALLBACK_RATE:()=>Ca,getRoutingRecommendation:()=>_T});function yT(){let e=(0,fg.join)(ce(),"routing-config.json"),t=me(e,null);if(t)return t;try{Be(e,pg)}catch{}return pg}function kT(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 wT(e,t){return!e||t===0?Ca:t*e.success_rate+(1-t)*Ca}function _T(e,t,n){try{let o=yT();if(!o.preferLowerTier)return null;let r=kT(e,o.agentTiers);if(!r||r.index===0)return null;let s=ln(n),i=r.tierList.slice(0,r.index);for(let a of i){let c=s[a],l=c?.total_invocations??0,u=Math.min(1,l/5),d=wT(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=ug(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 fg,Ca,pg,gg=B(()=>{"use strict";fg=require("path");fe();dg();Ca=.5,pg={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 KE={};Je(KE,{main:()=>Sh});module.exports=Rh(KE);var rs=new Map;function _(e){let t=rs.get(e.event)||[];t.push(e),t.sort((n,o)=>(n.priority??100)-(o.priority??100)),rs.set(e.event,t)}function Wa(e){return rs.get(e)||[]}var Ih={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},Oh=["ultrawork","ultrathink","olympus","search","analyze"];function Ha(e){let t=e.replace(/```[\s\S]*?```/g,"");return t=t.replace(/~~~[\s\S]*?~~~/g,""),t=t.replace(/`[^`]+`/g,""),t}function Ba(e,t){let n=[];for(let o of Oh){let r=Ih[o],s=e.match(r);s&&s.index!==void 0&&n.push({type:o,keyword:s[0],position:s.index})}return n}var Ga="auto-slash-command",Ao="<auto-slash-command>",xo="</auto-slash-command>",qa=/^\/([a-zA-Z][\w-]*)\s*(.*)/,Va=new Set(["ascent","cancel-ascent","help","clear","history","exit","quit"]);var Ph=/```[\s\S]*?```/g;function Ya(e){return e.replace(Ph,"")}function Ka(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.match(qa);if(!n)return null;let[o,r,s]=n;return{command:r.toLowerCase(),args:s.trim(),raw:o}}function Ja(e){return Va.has(e.toLowerCase())}function ss(e){let n=Ya(e).trim();if(!n.startsWith("/"))return null;let o=Ka(n);return!o||Ja(o.command)?null:o}function is(e){return e.filter(t=>t.type==="text").map(t=>t.text||"").join(" ")}var ze=require("fs"),at=require("path"),Xa=require("os"),za=(0,at.join)((0,Xa.homedir)(),".claude");function Za(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,s={};for(let i of o.split(`
|
|
664
|
+
`)){let a=i.indexOf(":");if(a===-1)continue;let c=i.slice(0,a).trim(),l=i.slice(a+1).trim();(l.startsWith('"')&&l.endsWith('"')||l.startsWith("'")&&l.endsWith("'"))&&(l=l.slice(1,-1)),s[c]=l}return{data:s,body:r}}function Qa(e,t){if(!(0,ze.existsSync)(e))return[];let n;try{n=(0,ze.readdirSync)(e,{withFileTypes:!0})}catch{return[]}let o=[];for(let r of n){if(!r.isFile()||!r.name.endsWith(".md"))continue;let s=(0,at.join)(e,r.name),i=(0,at.basename)(r.name,".md");try{let a=(0,ze.readFileSync)(s,"utf-8"),{data:c,body:l}=Za(a),u={name:i,description:c.description||"",argumentHint:c["argument-hint"],model:c.model,agent:c.agent};o.push({name:i,path:s,metadata:u,content:l,scope:t})}catch{continue}}return o}function as(){let e=(0,at.join)(za,"commands"),t=(0,at.join)(process.cwd(),".claude","commands"),n=(0,at.join)(za,"skills"),o=Qa(e,"user"),r=Qa(t,"project"),s=[];if((0,ze.existsSync)(n))try{let i=(0,ze.readdirSync)(n,{withFileTypes:!0});for(let a of i){if(!a.isDirectory())continue;let c=(0,at.join)(n,a.name,"SKILL.md");if((0,ze.existsSync)(c))try{let l=(0,ze.readFileSync)(c,"utf-8"),{data:u,body:d}=Za(l),f={name:u.name||a.name,description:u.description||"",argumentHint:u["argument-hint"],model:u.model,agent:u.agent};s.push({name:u.name||a.name,path:c,metadata:f,content:d,scope:"skill"})}catch{continue}}}catch{}return[...r,...o,...s]}function $o(e){return as().find(n=>n.name.toLowerCase()===e.toLowerCase())??null}function Ah(e,t){return e.replace(/\$ARGUMENTS/g,t||"(no arguments provided)")}function xh(e,t){let n=[];n.push(`<command-name>/${e.name}</command-name>
|
|
644
665
|
`),e.metadata.description&&n.push(`**Description**: ${e.metadata.description}
|
|
645
666
|
`),t&&n.push(`**Arguments**: ${t}
|
|
646
667
|
`),e.metadata.model&&n.push(`**Model**: ${e.metadata.model}
|
|
647
668
|
`),e.metadata.agent&&n.push(`**Agent**: ${e.metadata.agent}
|
|
648
669
|
`),n.push(`**Scope**: ${e.scope}
|
|
649
670
|
`),n.push(`---
|
|
650
|
-
`);let o=
|
|
671
|
+
`);let o=Ah(e.content||"",t);return n.push(o.trim()),t&&!e.content?.includes("$ARGUMENTS")&&(n.push(`
|
|
651
672
|
|
|
652
673
|
---
|
|
653
674
|
`),n.push(`## User Request
|
|
654
675
|
`),n.push(t)),n.join(`
|
|
655
|
-
`)}function
|
|
656
|
-
${
|
|
657
|
-
${
|
|
676
|
+
`)}function cs(e){let t=$o(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:xh(t,e.args)}}catch(n){return{success:!1,error:`Failed to load command "/${e.command}": ${n instanceof Error?n.message:String(n)}`}}}function ls(){return as().map(t=>({name:t.name,description:t.metadata.description,scope:t.scope}))}var No=new Set;function ec(){return{name:Ga,processMessage:(e,t)=>{let n=is(t);if(n.includes(Ao)||n.includes(xo))return{detected:!1};let o=ss(n);if(!o)return{detected:!1};let r=`${e.sessionId}:${e.messageId}:${o.command}`;if(No.has(r))return{detected:!1};No.add(r);let s=cs(o);if(s.success&&s.replacementText){let a=`${Ao}
|
|
677
|
+
${s.replacementText}
|
|
678
|
+
${xo}`;return{detected:!0,parsedCommand:o,injectedMessage:a}}let i=`${Ao}
|
|
658
679
|
[AUTO-SLASH-COMMAND ERROR]
|
|
659
|
-
${
|
|
680
|
+
${s.error}
|
|
660
681
|
|
|
661
682
|
Original input: ${o.raw}
|
|
662
|
-
${
|
|
683
|
+
${xo}`;return{detected:!0,parsedCommand:o,injectedMessage:i}},listCommands:()=>ls(),findCommand:e=>$o(e),clearSession:e=>{let t=[];for(let n of No)n.startsWith(`${e}:`)&&t.push(n);for(let n of t)No.delete(n)}}}var $h=[/\bultrathink\b/i,/\bthink\b/i],Nh=["\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"],Dh=Nh.map(e=>new RegExp(e,"i")),jh=[...$h,...Dh],Mh=/```[\s\S]*?```/g,Lh=/`[^`]+`/g;function Fh(e){return e.replace(Mh,"").replace(Lh,"")}function tc(e){let t=Fh(e);return jh.some(n=>n.test(t))}function nc(e){return e.filter(t=>t.type==="text").map(t=>t.text||"").join("")}function us(e){let t=e.indexOf("/");return t===-1?{prefix:"",base:e}:{prefix:e.slice(0,t+1),base:e.slice(t+1)}}function ds(e){return e.replace(/\.(\d+)/g,"-$1")}var oc={"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"},rc=new Set(Object.values(oc)),sc={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"}},Uh={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 ic(e){let t=ds(e),{prefix:n,base:o}=us(t);if(rc.has(o)||o.endsWith("-high"))return null;let r=oc[o];return r?n+r:null}function ps(e){let t=ds(e),{base:n}=us(t);return rc.has(n)||n.endsWith("-high")}function Wh(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 Hh(e){return e in sc}function ac(e,t){let n=ds(t),{base:o}=us(n);if(ps(n))return null;let r=Wh(e,t);if(!Hh(r))return null;let s=sc[r],i=Uh[r];if(!i)return null;let a=o.toLowerCase();return i.some(l=>a.includes(l.toLowerCase()))?s:null}var wt=new Map;function Bh(e){wt.delete(e)}function cc(){return{processChatParams:(e,t)=>{let n=nc(t.parts),o={requested:!1,modelSwitched:!1,thinkingConfigInjected:!1};if(!tc(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,ps(r.modelId)))return wt.set(e,o),o;let s=ic(r.modelId),i=ac(r.providerId,r.modelId);return s&&(t.message.model={providerId:r.providerId,modelId:s},o.modelSwitched=!0),i&&(Object.assign(t.message,i),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:Bh}}var re=require("fs"),on=require("path"),fs=require("os");function ms(e){let t=e||process.cwd(),n=(0,on.join)(t,".olympus");return(0,on.join)(n,"ultrawork-state.json")}function gs(){return(0,on.join)((0,fs.homedir)(),".claude","ultrawork-state.json")}function Gh(e){let t=e||process.cwd(),n=(0,on.join)(t,".olympus");(0,re.existsSync)(n)||(0,re.mkdirSync)(n,{recursive:!0})}function qh(){let e=(0,on.join)((0,fs.homedir)(),".claude");(0,re.existsSync)(e)||(0,re.mkdirSync)(e,{recursive:!0})}function _t(e){let t=ms(e);if((0,re.existsSync)(t))try{let o=(0,re.readFileSync)(t,"utf-8");return JSON.parse(o)}catch{}let n=gs();if((0,re.existsSync)(n))try{let o=(0,re.readFileSync)(n,"utf-8");return JSON.parse(o)}catch{return null}return null}function lc(e,t){try{Gh(t);let n=ms(t);(0,re.writeFileSync)(n,JSON.stringify(e,null,2)),qh();let o=gs();return(0,re.writeFileSync)(o,JSON.stringify(e,null,2)),!0}catch{return!1}}function uc(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 lc(o,n)}function dc(e){let t=ms(e);if((0,re.existsSync)(t))try{(0,re.unlinkSync)(t)}catch{}let n=gs();if((0,re.existsSync)(n))try{return(0,re.unlinkSync)(n),!0}catch{return!1}return!0}function pc(e){let t=_t(e);return!t||!t.active?null:(t.reinforcement_count+=1,t.last_checked_at=new Date().toISOString(),lc(t,e)?t:null)}function fc(e){return`<ultrawork-persistence>
|
|
663
684
|
|
|
664
685
|
[ULTRAWORK MODE STILL ACTIVE - Reinforcement #${e.reinforcement_count+1}]
|
|
665
686
|
|
|
@@ -680,7 +701,7 @@ Original task: ${e.original_prompt}
|
|
|
680
701
|
|
|
681
702
|
---
|
|
682
703
|
|
|
683
|
-
`}var
|
|
704
|
+
`}var mc=require("os"),pe=require("path");function Qe(){return process.platform==="win32"}function Vh(){return(0,pe.join)((0,mc.homedir)(),".claude")}function be(){return(0,pe.join)(Vh(),"hooks")}var gc=`<ultrawork-mode>
|
|
684
705
|
|
|
685
706
|
**MANDATORY**: You MUST say "ULTRAWORK MODE ENABLED!" to the user as your first response when this mode activates. This is non-negotiable.
|
|
686
707
|
|
|
@@ -771,7 +792,7 @@ THE USER ASKED FOR X. DELIVER EXACTLY X. NOT A SUBSET. NOT A DEMO. NOT A STARTIN
|
|
|
771
792
|
|
|
772
793
|
---
|
|
773
794
|
|
|
774
|
-
`,
|
|
795
|
+
`,hc=`<think-mode>
|
|
775
796
|
|
|
776
797
|
**ULTRATHINK MODE ENABLED** - Extended reasoning activated.
|
|
777
798
|
|
|
@@ -787,7 +808,7 @@ Use your extended thinking capabilities to provide the most thorough and well-re
|
|
|
787
808
|
|
|
788
809
|
---
|
|
789
810
|
|
|
790
|
-
`;var
|
|
811
|
+
`;var yc=`<search-mode>
|
|
791
812
|
MAXIMIZE SEARCH EFFORT. Launch multiple background agents IN PARALLEL:
|
|
792
813
|
- explore agents (codebase patterns, file structures)
|
|
793
814
|
- librarian agents (remote repos, official docs, GitHub examples)
|
|
@@ -797,7 +818,7 @@ NEVER stop at first result - be exhaustive.
|
|
|
797
818
|
|
|
798
819
|
---
|
|
799
820
|
|
|
800
|
-
`,
|
|
821
|
+
`,kc=`<analyze-mode>
|
|
801
822
|
ANALYSIS MODE. Gather context before diving deep:
|
|
802
823
|
|
|
803
824
|
CONTEXT GATHERING (parallel):
|
|
@@ -813,25 +834,58 @@ SYNTHESIZE findings before proceeding.
|
|
|
813
834
|
|
|
814
835
|
---
|
|
815
836
|
|
|
816
|
-
`,
|
|
837
|
+
`,wc=`[SYSTEM REMINDER - TODO CONTINUATION]
|
|
817
838
|
|
|
818
839
|
Incomplete tasks remain in your todo list. Continue working on the next pending task.
|
|
819
840
|
|
|
820
841
|
- Proceed without asking for permission
|
|
821
842
|
- Mark each task complete when finished
|
|
822
|
-
- Do not stop until all tasks are done`;var
|
|
823
|
-
`);for(let
|
|
824
|
-
`),o=null,r=[];for(let
|
|
825
|
-
`)),o=
|
|
826
|
-
`)),t}async function
|
|
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||
|
|
828
|
-
`),o=[];for(let r of n){let
|
|
829
|
-
`)}function
|
|
830
|
-
`);for(let
|
|
831
|
-
`),o=null,r=[];for(let
|
|
832
|
-
`)),o=
|
|
833
|
-
`)),t}function
|
|
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=`---
|
|
843
|
+
- Do not stop until all tasks are done`;var vb={hooks:{UserPromptSubmit:[{hooks:[{type:"command",command:Qe()?'node "%USERPROFILE%\\.claude\\hooks\\keyword-detector.mjs"':'node "$HOME/.claude/hooks/keyword-detector.mjs"'}]}],SessionStart:[{hooks:[{type:"command",command:Qe()?'node "%USERPROFILE%\\.claude\\hooks\\session-start.mjs"':'node "$HOME/.claude/hooks/session-start.mjs"'}]}],Stop:[{hooks:[{type:"command",command:Qe()?'node "%USERPROFILE%\\.claude\\hooks\\persistent-mode.mjs"':'node "$HOME/.claude/hooks/persistent-mode.mjs"'}]}]}},Tb={hooks:{UserPromptSubmit:[{hooks:[{type:"command",command:Qe()?`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:Qe()?`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:Qe()?`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:Qe()?`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:Qe()?`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:Qe()?`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:Qe()?`node "${(0,pe.join)(be(),"olympus-hooks.cjs")}" --event=Notification`:`node "${(0,pe.join)(be(),"olympus-hooks.cjs")}" --event=Notification`}]}]}};Ae();fe();var Bc=require("crypto"),ny={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 _s(e){let t=e.replace(/```[\s\S]*?```/g,"").replace(/`[^`]+`/g,""),n=null;for(let[o,r]of Object.entries(ny))for(let{regex:s,confidence:i}of r)s.test(t)&&(!n||i>n.confidence)&&(n={category:o,confidence:i});return n}async function Gc(e){let{prompt:t,directory:n,sessionId:o}=e;if(!t||!n)return;let r=V(n,o),s=_s(t),i=Nc(r,t,s?.category);if(s){let a={id:(0,Bc.randomUUID)(),timestamp:new Date().toISOString(),session_id:r.session_id,project_path:n,event_type:s.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:s.category,confidence:s.confidence};St(a)}X(n,i)}Ae();fe();var qc=require("crypto");async function Vc(e){let{prompt:t,directory:n,sessionId:o}=e;if(!t||!n)return;let r=V(n,o),s=_s(t);if(s?.category==="praise"&&s.confidence>.7){let a={id:(0,qc.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:s.confidence};if(St(a),Mo(r)){let c=jc(r);X(n,c)}}}var Ie=E(require("fs"),1),uo=E(require("path"),1);we();qs();var ed=require("fs"),Zu=new Map,vw=1e4;function Tw(e){let t=Zu.get(e);if(t&&Date.now()-t.timestamp<vw)return t.content;let n=(0,ed.readFileSync)(e,"utf-8");return Zu.set(e,{content:n,timestamp:Date.now()}),n}function Ew(e){let t=e.match(/^---\n([\s\S]*?)\n---/);if(!t)return null;let n=t[1];try{let o={},r=n.split(`
|
|
844
|
+
`);for(let s of r){let i=s.match(/^(\w+):\s*(.+)$/);if(i){let[,a,c]=i;o[a]=c.trim()}}return o}catch{return null}}function bw(e){return e.replace(/^---\n[\s\S]*?\n---\n/,"")}function Cw(e){let t=new Map,n=e.split(`
|
|
845
|
+
`),o=null,r=[];for(let s of n){let i=s.match(/^##\s+(.+)$/);i?(o&&t.set(o,r.join(`
|
|
846
|
+
`)),o=i[1].trim(),r=[]):o&&r.push(s)}return o&&t.set(o,r.join(`
|
|
847
|
+
`)),t}async function Zo(e){let t=new Date().toISOString(),n=[],o;try{o=Tw(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=Ew(o),s=["id","title","parent","status","depth_score","risk_tier"],i=!0;for(let m of s)(!r||!r[m])&&(n.push(`Frontmatter missing required field: ${m}`),i=!1);let a=bw(o),c=Cw(a),l=i?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 Y=E(se(),1),U=E(require("path"),1);we();var yn=E(se(),1),td=E(require("path"),1),Rw=10;function nd(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 Vs(e){try{if(!await yn.default.pathExists(e))return[];let o=(await yn.default.readdir(e)).filter(s=>s.startsWith("INTENT-")&&s.endsWith(".md")),r=[];for(let s of o)try{let i=td.default.join(e,s),c=(await yn.default.readFile(i,"utf-8")).match(/^---\n([\s\S]*?)\n---/);if(!c){console.error(`No frontmatter found in ${s}`);continue}let u=c[1].split(`
|
|
848
|
+
`),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||s.replace(".md",""),type:"intent",title:d.title||"Untitled Intent",parent_id:null,children_ids:[],status:d.status||"pending",assigned_agent:d.assigned_agent||null,estimated_effort:d.estimated_effort||0};r.push(f)}catch(i){console.error(`Failed to parse ${s}:`,i)}return r}catch(t){return console.error(`Failed to read intents from ${e}:`,t),[]}}async function Ys(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 s=r[1],i=/^-\s+\*\*([^*]+)\*\*:\s*(.+)$/gm,a,c=0;for(;(a=i.exec(s))!==null;){let l=a[1].trim(),u=a[2].trim(),d=nd(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 Ks(e,t,n=Rw){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 s=0;s<o.length;s++){let i=o[s],a=nd(i.title,s+1),c={id:a,type:"unit",title:i.title,parent_id:e.id,children_ids:[],status:"pending",assigned_agent:null,estimated_effort:i.estimated_effort};r.push(c),e.children_ids.push(a)}return r}function Js(e){let t=new Map;function n(o,r){t.set(o.id,o);for(let s of o.children_ids){let i=r.find(a=>a.id===s);i&&n(i,r)}}for(let o of e)t.set(o.id,o);return{roots:e,nodes:t}}var kn=E(se(),1),wn=E(require("path"),1);function rd(e,t){let n=[],o=1;for(let r of e){let s=Pt(r.title),i=Iw(t,s),a=od(i,"input"),c=od(i,"output"),l=Ow(r,e);n.push({id:`IFACE-${String(o++).padStart(3,"0")}`,unit_id:r.id,name:Pw(r.title),inputs:a,outputs:c,dependencies:l,description:`Interface contract for ${r.title}`})}return n}function sd(e,t){let n=[],o=1;for(let r of e){let s=t.filter(c=>c.unit_id===r.id),i=[],a=[];for(let c of s){i.push({id:`COMP-${c.id}`,name:c.name,type:"interface"});for(let l of c.dependencies){let u=t.find(d=>d.id===l);u&&a.push({from:`COMP-${u.id}`,to:`COMP-${c.id}`,data:`Data from ${u.name}`,direction:"unidirectional"})}if(xw(c)){let l=`STORE-${c.id}`;i.push({id:l,name:`${c.name}Store`,type:"store"}),a.push({from:`COMP-${c.id}`,to:l,data:"Persisted data",direction:"bidirectional"})}}n.push({id:`DFD-${String(o++).padStart(3,"0")}`,unit_id:r.id,components:i,flows:a,description:`Data flow diagram for ${r.title}`})}return n}function id(e,t,n){let o=[],r=1;for(let s of e){let i=t.filter(u=>u.unit_id===s.id),a=n.find(u=>u.unit_id===s.id),c=a?a.components.filter(u=>u.type==="store").map(u=>u.name):[],l=$w(s,i);o.push({id:`COMP-${String(r++).padStart(3,"0")}`,unit_id:s.id,name:Aw(s.title),responsibilities:l,interfaces_used:i.map(u=>u.id),data_stores:c,description:`Component design for ${s.title}`})}return o}function zs(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=Nw(t),s=Dw(e),i=jw(r,s);return{passed:n.length===0,coverage_percentage:i,blocking_issues:n,reviewer:"design-validator",timestamp:new Date().toISOString()}}async function ad(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=zs(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 Pt(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 Iw(e,t){let n=e.split(`
|
|
849
|
+
`),o=[];for(let r of n){let s=r.toLowerCase();t.some(i=>s.includes(i))&&o.push(r)}return o.join(`
|
|
850
|
+
`)}function od(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 Ow(e,t){let n=new Set(Pt(e.title)),o=[];for(let r of t){if(r.id===e.id)continue;Pt(r.title).filter(a=>n.has(a)).length>0&&o.push(r.id)}return o}function Pw(e){return e.split(/\s+/).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")+"Interface"}function Aw(e){return e.split(/\s+/).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")+"Component"}function xw(e){let t=["store","save","persist","database","repository"],n=e.name.toLowerCase();return t.some(o=>n.includes(o))}function $w(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 Nw(e){return new Set(Pt(e))}function Dw(e){let t=new Set;for(let n of e.interfaces)Pt(n.name).forEach(o=>t.add(o)),Pt(n.description).forEach(o=>t.add(o));for(let n of e.components)Pt(n.name).forEach(o=>t.add(o)),Pt(n.description).forEach(o=>t.add(o));return t}function jw(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"),Qs=require("path"),Mw=[1,2,4,8,16];function Lw(e){let t=e.match(/^---\n([\s\S]*?)\n---/);if(!t)return null;let n=t[1];try{let o={},r=n.split(`
|
|
851
|
+
`);for(let s of r){let i=s.match(/^(\w+):\s*(.+)$/);if(i){let[,a,c]=i;o[a]=c.trim()}}return o}catch{return null}}function Fw(e){return e.replace(/^---\n[\s\S]*?\n---\n/,"")}function Uw(e){let t=new Map,n=e.split(`
|
|
852
|
+
`),o=null,r=[];for(let s of n){let i=s.match(/^##\s+(.+)$/);i?(o&&t.set(o,r.join(`
|
|
853
|
+
`)),o=i[1].trim(),r=[]):o&&r.push(s)}return o&&t.set(o,r.join(`
|
|
854
|
+
`)),t}function Ww(e){let t=e.split(`
|
|
855
|
+
`),n=0;for(let o of t)o.trim().match(/^[-*+]\s+/)&&n++;return n}function Hw(e,t,n){let o=[],r=null,s=Lw(e);if(!s)return o.push(`${t}: Missing frontmatter`),{isValid:!1,blockingIssues:o,parentIntent:r};let i=["id","title","parent_intent","status","estimated_effort"],a=[];for(let h of i)s[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=s.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(s.estimated_effort,10);if(isNaN(c)||!Mw.includes(c))return o.push(`${t}: Invalid effort estimate ${s.estimated_effort} (must be 1, 2, 4, 8, or 16)`),{isValid:!1,blockingIssues:o,parentIntent:r};let l=Fw(e),u=Uw(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(Ww(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 Xs(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 s=r.filter(p=>p.isDirectory()&&p.name!=="design"),i=r.filter(p=>p.isFile()&&p.name.endsWith(".md")&&p.name!=="design.md"),a=new Set,c=[];for(let p of s){let g=p.name,h=(0,Qs.join)(e,p.name,"spec.md");(0,Yt.existsSync)(h)&&(a.add(g),c.push({unitId:g,filePath:h}))}for(let p of i){let g=p.name.replace(".md","");a.has(g)||(a.add(g),c.push({unitId:g,filePath:(0,Qs.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 I=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(I);continue}let y=Hw(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}}Qo();z();var or=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:s=8,max_total_code_gen:i=50,checkpointStatus:a,onCheckpointSave:c}=n;if(a==="awaiting_dev_review")return{passed:!1,coverage_percentage:0,blocking_issues:["Construction blocked: developer review of technical specification required (Risk Tier 3)."],reviewer:"construction-executor",timestamp:new Date().toISOString()};if(console.log(`[ConstructionExecutor] Starting Construction phase execution (depth: ${o})`),(n.pathwayType==="brownfield-enhancement"||n.pathwayType==="brownfield-refactor"||n.pathwayType==="bugfix")&&n.testCommand)try{let{captureBaseline:f}=await Promise.resolve().then(()=>(dd(),ud));await f(this.projectPath,this.workflowId,n.testCommand),console.log("[ConstructionExecutor] Regression baseline captured")}catch(f){console.error("[ConstructionExecutor] Baseline capture failed (non-fatal):",f)}if(o==="SHALLOW")return this.executeShallow();this.currentStage="unit";let u=await this.executeDecompositionPhase(r,s,i,o);if(!u.passed)return console.error("[ConstructionExecutor] Decomposition phase failed"),u;if(console.log("[ConstructionExecutor] Decomposition phase complete"),c)try{await c()}catch(f){console.error("[ConstructionExecutor] Checkpoint save callback failed:",f)}this.currentStage="design";let d=await this.executeDesignStage(t);return d.passed?(console.log("[ConstructionExecutor] Design stage complete"),{passed:!0,coverage_percentage:100,blocking_issues:[],reviewer:"construction-executor",timestamp:new Date().toISOString()}):(console.error("[ConstructionExecutor] Design stage failed validation"),d)}getProgress(){let t=0,n=0;if(this.tree)for(let i of this.tree.nodes.values())i.type==="unit"&&(t++,i.status==="complete"&&n++);let o=this.totalCodeGenerations,r=0,s=0;return this.currentStage==="unit"?s=t>0?Math.round(n/t*50):0:this.currentStage==="code-generation"?s=50+(o>0?Math.round(r/o*25):0):this.currentStage==="design"&&(s=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:s}}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:s,dispatchCodeGeneration:i,buildCodeGenerationPrompt:a}=await Promise.resolve().then(()=>(nr(),tr)),c=s(o,r,t),l=await i(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:s}=await Promise.resolve().then(()=>(nr(),tr)),{addGateAuditEntry:i}=await Promise.resolve().then(()=>(z(),Vt)),a=o(this.projectPath,this.workflowId,t);if(!await Y.default.pathExists(a))throw new Error(`Code plan file not found at ${a}. The agent must create the plan before it can be approved.`);let l=U.default.join(this.projectPath,"aidlc-docs",this.workflowId,"manifest.json");try{i(l,{phase:"construction",action:"approved",actor:"human",reason:n||`Code plan for ${t} approved by developer`})}catch(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:s(u.context.intentSummary2,u.context.intentSummary,u.context.unitSpec)}}async autoApproveCodePlan(t,n){let{addGateAuditEntry:o}=await Promise.resolve().then(()=>(z(),Vt)),r=U.default.join(this.projectPath,"aidlc-docs",this.workflowId,"manifest.json"),s=n>=3;try{o(r,{phase:"construction",action:"approved",actor:"trust",reason:s?`Code plan for ${t} auto-approved silently (trust level ${n})`:`Code plan for ${t} auto-approved with notification (trust level ${n})`})}catch(u){console.error(`[ConstructionExecutor] Failed to record gate audit for ${t}:`,u)}s||console.log(`[ConstructionExecutor] Code plan for ${t} auto-approved (trust level ${n})`);let{dispatchCodeGeneration:i,buildCodeGenerationPrompt:a}=await Promise.resolve().then(()=>(nr(),tr)),c=await i(this.projectPath,this.workflowId,t);return{status:"executing_code_plan",prompt:a(c.context.intentSummary2,c.context.intentSummary,c.context.unitSpec)}}async executeTestGeneration(t,n={}){let o=n.projectPath||this.projectPath,r=n.workflowId||this.workflowId,i=await T(o,r)??{schema_version:"3.0.0",workflow_id:r,feature_name:"",current_phase:"construction",current_stage:"code-generation",status:"in_progress",phases:{},manifest_path:"",trust_state_path:"",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),construction_units:{}};i.construction_units||(i.construction_units={});let a=i.construction_units[t]??{unitId:t,stages:{"functional-design":{status:"not_started",artifact_path:null,completed_at:null},"nfr-requirements":{status:"not_started",artifact_path:null,completed_at:null},"nfr-design":{status:"not_started",artifact_path:null,completed_at:null},"infrastructure-design":{status:"not_started",artifact_path:null,completed_at:null},"code-generation":{status:"not_started",artifact_path:null,completed_at:null},"test-generation":{status:"not_started",artifact_path:null,completed_at:null}},code_plan_path:null,code_generation_status:"not_started",tests_total:0,tests_passed:0,tests_failed:0,test_framework:"unknown",test_generation_status:"not_started"};a.stages["test-generation"].status="in_progress",a.test_generation_status="in_progress",i.construction_units[t]=a,await A(o,i);let c=U.default.join(o,"aidlc-docs",r,"construction",t,"testing");await Y.default.ensureDir(c);let l=U.default.join(c,"test-report.md"),u="",d=U.default.join(o,"aidlc-docs",r,"construction",t,"code","code-summary.md");try{await Y.default.pathExists(d)&&(u=await Y.default.readFile(d,"utf-8"))}catch{}let f=await this.detectTestFramework(o),m=new Date().toISOString(),p=this.buildTestReportScaffold(t,f,u,m);await Y.default.writeFile(l,p,"utf-8");let g=0,h=0,y=0,w="completed",k;return n.allowFailures!==!0&&(g===0?(w="blocked",k=`No tests detected for unit ${t}. Set allowFailures: true to override.`):y>0&&(w="blocked",k=`${y} test(s) failed for unit ${t}. Set allowFailures: true to override.`)),a.stages["test-generation"].status=w==="completed"?"completed":"in_progress",a.stages["test-generation"].artifact_path=l,w==="completed"&&(a.stages["test-generation"].completed_at=m),a.tests_total=g,a.tests_passed=h,a.tests_failed=y,a.test_framework=f,a.test_generation_status=w==="completed"?"completed":"in_progress",i.construction_units[t]=a,await A(o,i),{status:w,unitId:t,tests_total:g,tests_passed:h,tests_failed:y,test_framework:f,reportPath:l,blockingReason:k}}async validateBugfixTestRequirement(t,n={}){try{let o=n.projectPath||this.projectPath,r=n.workflowId||this.workflowId,s=await T(o,r);if(!s)return{valid:!1,reason:"checkpoint not found"};if(s.pathway_type!=="bugfix")return{valid:!0};let i=s.construction_units?.[t];return i?i.stages?.["test-generation"]?.status!=="completed"?{valid:!1,reason:"test-generation stage not completed for bugfix unit"}:(i.tests_total??0)===0?{valid:!1,reason:"bugfix unit must have at least one test (tests_total === 0)"}:{valid:!0}:{valid:!1,reason:`no unit progress found for unit ${t}`}}catch(o){let r=o instanceof Error?o.message:String(o);return console.error(`[ConstructionExecutor] validateBugfixTestRequirement error for ${t}:`,o),{valid:!1,reason:`validation error: ${r}`}}}async captureBugDescription(t,n){try{let o=n?.projectPath||this.projectPath,r=n?.workflowId||this.workflowId,i=await T(o,r)??{schema_version:"3.0.0",workflow_id:r,feature_name:"",current_phase:"construction",current_stage:"code-generation",status:"in_progress",phases:{},manifest_path:"",trust_state_path:"",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),construction_units:{}};i.bug_description=t,i.updated_at=new Date().toISOString(),await A(o,i)}catch(o){console.error("[ConstructionExecutor] captureBugDescription error:",o)}}async detectTestFramework(t){let n=U.default.join(t,"package.json");try{if(!await Y.default.pathExists(n))return"unknown";let o=await Y.default.readFile(n,"utf-8"),r=JSON.parse(o),s={...r.dependencies,...r.devDependencies};return s.vitest?"vitest":s.jest?"jest":s.mocha?"mocha":"unknown"}catch{return"unknown"}}buildTestReportScaffold(t,n,o,r){let s="_No code-summary.md found \u2014 files in scope unknown._";if(o){let i=o.match(/## Files (?:created|modified|created\/modified)[^\n]*\n([\s\S]*?)(?=\n##|$)/i);i&&i[1].trim()&&(s=i[1].trim())}return`---
|
|
856
|
+
unit_id: ${t}
|
|
857
|
+
framework: ${n}
|
|
858
|
+
generated_at: ${r}
|
|
859
|
+
---
|
|
860
|
+
|
|
861
|
+
# Test Report \u2014 ${t}
|
|
862
|
+
|
|
863
|
+
## Files in Scope
|
|
864
|
+
|
|
865
|
+
${s}
|
|
866
|
+
|
|
867
|
+
## Test Results
|
|
868
|
+
|
|
869
|
+
| Metric | Value |
|
|
870
|
+
|--------|-------|
|
|
871
|
+
| tests_total | 0 |
|
|
872
|
+
| tests_passed | 0 |
|
|
873
|
+
| tests_failed | 0 |
|
|
874
|
+
|
|
875
|
+
## Test Types
|
|
876
|
+
|
|
877
|
+
- [ ] Unit tests
|
|
878
|
+
- [ ] Integration tests
|
|
879
|
+
- [ ] E2E tests
|
|
880
|
+
|
|
881
|
+
## Failure Details
|
|
882
|
+
|
|
883
|
+
_No failures recorded._
|
|
884
|
+
|
|
885
|
+
## Override
|
|
886
|
+
|
|
887
|
+
_allowFailures was not set._
|
|
888
|
+
`}async executeShallow(){let t=U.default.join(this.projectPath,"aidlc-docs",this.workflowId,"inception","intent.md"),n=U.default.join(this.projectPath,"aidlc-docs",this.workflowId,"construction"),o="Shallow Implementation",r=2,s="",i=await Ys(t);if(i){s=i.content;let d=s.match(/^title:\s*(.+)$/m);d&&(o=d[1].trim().replace(/^["']|["']$/g,""));let f=s.match(/^estimated_effort:\s*(\d+)/m);f&&(r=Number(f[1]))}else{let d=U.default.join(this.projectPath,"aidlc-docs",this.workflowId,"inception"),f=await Vs(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 Y.default.ensureDir(n);let a="shallow-impl",c=U.default.join(n,a);await Y.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",s);await Y.default.writeFile(U.default.join(c,"spec.md"),u,"utf-8"),this.registerConstructionArtifact(a,"unit","unit",U.default.join(c,"spec.md")),this.totalCodeGenerations=1,this.totalEffort=r,console.log("[ConstructionExecutor] SHALLOW mode: created single unit for code generation from INTENT");try{await this.executeTestGeneration("shallow-impl")}catch(d){console.error("[ConstructionExecutor] Test generation failed for shallow-impl:",d)}return{passed:!0,coverage_percentage:100,blocking_issues:[],reviewer:"construction-executor",timestamp:l}}async executeDecompositionPhase(t,n,o,r="MEDIUM"){let s=U.default.join(this.projectPath,"aidlc-docs",this.workflowId,"inception"),i=U.default.join(this.projectPath,"aidlc-docs",this.workflowId,"construction");await Y.default.ensureDir(i);let a=U.default.join(s,"intent.md"),c=await Ys(a),l=U.default.join(s,"intent.md"),u="";try{await Y.default.pathExists(l)&&(u=await Y.default.readFile(l,"utf-8"))}catch{}return c?this.executeDecompositionFromIntent(c,s,i,t,n,o,u,r):this.executeDecompositionFromLegacyIntents(s,i,t,n,o,u)}async executeDecompositionFromIntent(t,n,o,r,s,i,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
889
|
id: ${p}
|
|
836
890
|
title: ${f}
|
|
837
891
|
status: pending
|
|
@@ -855,7 +909,7 @@ Auto-generated
|
|
|
855
909
|
|
|
856
910
|
## Technical Notes
|
|
857
911
|
Generated from inception/intent.md
|
|
858
|
-
`;await
|
|
912
|
+
`;await Y.default.writeFile(U.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=Ks(g,y,r),k=[];for(let v of w){let O=U.default.join(o,v.id);await Y.default.ensureDir(O);let R=this.formatUnitMarkdown(v,g.id,l);await Y.default.writeFile(U.default.join(O,"spec.md"),R,"utf-8"),await Y.default.writeFile(U.default.join(o,`${v.id}.md`),R,"utf-8"),this.registerConstructionArtifact(v.id,"unit","unit",U.default.join(O,"spec.md")),this.linkConstructionArtifacts(p,v.id,"derives"),this.runUnitValidation(R,l,a,g.id,v.id);try{let{UnitStageRunner:ee}=await Promise.resolve().then(()=>(vd(),Sd));await new ee(this.projectPath,this.workflowId).executeForUnit(v.id,c,a)}catch(ee){console.error(`[ConstructionExecutor] Unit stage runner failed for ${v.id}:`,ee)}}this.tree=Js([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,O)=>v+O.estimated_effort,0),console.log(`[ConstructionExecutor] Created ${w.length} units for code generation`);let I=await Xs(o,n);return I.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()}:I}async executeDecompositionFromLegacyIntents(t,n,o,r,s,i){let a=await Vs(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 Y.default.readdir(t)).find(p=>p.startsWith("INTENT-")&&p.endsWith(".md"));m&&(c=await Y.default.readFile(U.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=Ks(f,m,o);l.push(...p);for(let g of p){let h=U.default.join(n,`${g.id}.md`),y=this.formatUnitMarkdown(g,f.id);await Y.default.writeFile(h,y,"utf-8");let w=U.default.join(n,g.id);await Y.default.ensureDir(w),await Y.default.writeFile(U.default.join(w,"spec.md"),y,"utf-8"),this.registerConstructionArtifact(g.id,"unit","unit",U.default.join(w,"spec.md")),this.linkConstructionArtifacts(f.id,g.id,"derives"),this.runUnitValidation(y,c,i,f.id,g.id)}}console.log(`[ConstructionExecutor] Created ${l.length} units for code generation`),this.tree=Js(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 Xs(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=U.default.join(this.projectPath,"aidlc-docs",this.workflowId,"construction"),o=await Y.default.readdir(n,{withFileTypes:!0}),r=[];for(let l of o)if(l.isDirectory()&&l.name!=="design"){let u=U.default.join(n,l.name,"spec.md");if(await Y.default.pathExists(u)){let d=await Y.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=U.default.join(n,l.name),d=await Y.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 s=rd(r,t||""),i=sd(r,s),a=id(r,s,i);await ad(this.projectPath,this.workflowId,{interfaces:s,dataFlows:i,components:a});let c=U.default.join(this.projectPath,"aidlc-docs",this.workflowId,"construction","design");return this.registerConstructionArtifact("design-interfaces","interface-contracts","unit",U.default.join(c,"interfaces.json")),this.registerConstructionArtifact("design-data-flow","data-flow-diagram","unit",U.default.join(c,"data-flow.json")),this.registerConstructionArtifact("design-components","component-design","unit",U.default.join(c,"components.json")),t?zs({interfaces:s,dataFlows:i,components:a},t):{passed:!0,coverage_percentage:100,blocking_issues:[],reviewer:"construction-executor",timestamp:new Date().toISOString()}}runUnitValidation(t,n,o,r,s){if(!(!n||!o))try{let i=gn(t,n,o,"intent-to-unit","unit-to-intent",r,s,`intent-${this.workflowId}`);i.passed||console.warn(`[ConstructionExecutor] Dual validation warning for ${s}: parent=${i.parentCheck.alignment_passed}, root=${i.rootCheck.alignment_passed}`)}catch(i){console.error(`[ConstructionExecutor] Dual validation error for ${s}:`,i)}}registerConstructionArtifact(t,n,o,r){try{let s=U.default.join(this.projectPath,"aidlc-docs",this.workflowId,"manifest.json");xe(s,{id:t,type:n,phase:"construction",stage:o,path:r,validation_passed:null,write_complete:!0,checksum:null})}catch(s){console.error(`[ConstructionExecutor] Failed to register artifact ${t}:`,s)}}linkConstructionArtifacts(t,n,o){try{let r=U.default.join(this.projectPath,"aidlc-docs",this.workflowId,"manifest.json");Us(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
913
|
id: ${t.id}
|
|
860
914
|
title: ${t.title}
|
|
861
915
|
parent_intent: ${n}
|
|
@@ -905,17 +959,17 @@ Implementation details for ${t.title}.
|
|
|
905
959
|
## Traceability
|
|
906
960
|
- Parent INTENT: ${n} (inception/intent.md)
|
|
907
961
|
- Root INTENT: intent-${this.workflowId} (inception/intent.md)
|
|
908
|
-
`}parseUnitFromMarkdown(t,n){try{let o=t.match(/^---\n([\s\S]*?)\n---/);if(!o)return null;let
|
|
909
|
-
`),
|
|
910
|
-
`)}pt();
|
|
962
|
+
`}parseUnitFromMarkdown(t,n){try{let o=t.match(/^---\n([\s\S]*?)\n---/);if(!o)return null;let s=o[1].split(`
|
|
963
|
+
`),i={};for(let a of s){let c=a.match(/^(\w+):\s*(.+)$/);if(c){let[,l,u]=c,d=u.trim().replace(/^["']|["']$/g,"");isNaN(Number(d))?i[l]=d:i[l]=Number(d)}}return{id:n,type:"unit",title:i.title||"Untitled Unit",parent_id:i.parent_intent||null,children_ids:[],status:i.status||"pending",assigned_agent:i.assigned_agent||null,estimated_effort:i.estimated_effort||0}}catch(o){return console.error("Failed to parse unit from markdown:",o),null}}};ir();var Wd=require("crypto"),g_={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=g_[e.type],o=e.timestamp??new Date().toISOString(),r=h_(e.type),s=y_(e).slice(0,100),i=k_(e,t);return{id:(0,Wd.randomUUID)(),timestamp:o,session_id:t.sessionId,project_path:t.projectPath,category:n,summary:s,details:i,agent_name:e.agentName??"workflow-engine",task_context:`${t.featureName} (${e.phase}${e.stage?"/"+e.stage:""})`,files_involved:e.artifactId?[`${e.artifactId}`]:[],confidence:r,verified:e.type==="gate_approval"||e.type==="phase_complete"||e.type==="bolt_execution_complete",verification_count:0,scope:"project",last_useful:o}}function h_(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 y_(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 k_(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(`
|
|
964
|
+
`)}pt();si();function En(e){return Math.max(1,Math.min(5,Math.round(e)))}function I_(e){let t=En(e.clarity),n=En(e.complexity),o=En(e.scope),r=En(e.risk),s=En(e.context),i=En(e.preferences),a=t+n+o+r+s+i,c;a<=10?c="minimal":a<=20?c="standard":c="comprehensive";let l=a<=10,u=O_(r,n,o),d=Kd(u);return{clarity:t,complexity:n,scope:o,risk:r,context:s,preferences:i,total_score:a,recommended_depth:c,skip_units:l,risk_tier:d}}function O_(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 s;e>=4&&t>=3?s="user-facing":e>=3?s="internal":s="none";let i;return e>=5?i="major":e>=4?i="minor":i="none",{reversibility:o,blast_radius:r,data_sensitivity:s,compliance_impact:i}}function Kd(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,s=t+n+o+r,i;s<=6?i=1:s<=9?i=2:i=3;let a=P_(i,e);return{tier:i,rationale:a,factors:e,override_reason:null}}function P_(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 pr(e){let t=A_(e),n=x_(t),o=$_(t),r=N_(t),s=D_(t),i=j_(t),a=M_(t),c=L_(e,t),u=I_({clarity:n,complexity:o,scope:r,risk:s,context:i,preferences:a}),d=Kd(c);return u.risk_tier=d,u}function A_(e){let t={problemStatement:"",userPersonas:"",businessConstraints:"",successMetrics:"",outOfScope:""},n=/^## (.+)$/gm,o=[],r=0,s;for(;(s=n.exec(e))!==null;)o.length>0&&(o[o.length-1].content=e.substring(r,s.index).trim()),o.push({title:s[1].trim(),content:""}),r=s.index+s[0].length;o.length>0&&(o[o.length-1].content=e.substring(r).trim());for(let i of o){let a=i.title.toLowerCase();a.includes("problem")||a.includes("statement")?t.problemStatement=i.content:a.includes("persona")||a.includes("user persona")?t.userPersonas=i.content:a.includes("business constraint")||a.includes("constraint")?t.businessConstraints=i.content:a.includes("success")||a.includes("metric")?t.successMetrics=i.content:(a.includes("out of scope")||a.includes("scope"))&&(t.outOfScope=i.content)}return t}function x_(e){let t=e.problemStatement.length+e.userPersonas.length;return t>1e3?1:t>500?2:t>250?3:t>100?4:5}function $_(e){let t=(e.userPersonas.match(/^[-*+]\s/gm)||[]).length,o=["component","service","module","layer","system","integration","api"].filter(s=>e.userPersonas.toLowerCase().includes(s)).length,r=t+o;return r>=10?5:r>=7?4:r>=4?3:r>=2?2:1}function N_(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 D_(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(s=>o.includes(s)).length;return r>=5?5:r>=3?4:r>=2?3:r>=1?2:1}function j_(e){let t=e.outOfScope.length;return t>500?1:t>300?2:t>150?3:t>50?4:5}function M_(e){let t=["must","should","could","prefer","optional","required","nice to have"],o=(e.businessConstraints+e.userPersonas).toLowerCase(),r=t.filter(s=>o.includes(s)).length;return r>=8?5:r>=5?4:r>=3?3:r>=2?2:1}function L_(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 s="none";n.includes("pii")||n.includes("personal")||n.includes("authentication")||n.includes("payment")||n.includes("user data")||n.includes("sensitive")?s="user-facing":(n.includes("internal")||n.includes("logging")||n.includes("metrics")||n.includes("telemetry"))&&(s="internal");let i="none";return n.includes("gdpr")||n.includes("soc")||n.includes("hipaa")||n.includes("compliance")||n.includes("regulatory")?i="major":(n.includes("audit")||n.includes("policy"))&&(i="minor"),{reversibility:o,blast_radius:r,data_sensitivity:s,compliance_impact:i}}z();var Jd=require("fs"),F_=require("path"),U_=require("os"),fr="<!-- AIDLC-RULES-START -->",bn="<!-- AIDLC-RULES-END -->";function zd(e){return e.includes(fr)&&e.includes(bn)}function Qd(e,t){let n=`${fr}
|
|
911
965
|
${t}
|
|
912
|
-
${bn}`;if(
|
|
966
|
+
${bn}`;if(zd(e)){let r=e.indexOf(fr),s=e.indexOf(bn)+bn.length,i=e.slice(0,r).replace(/\s+$/,""),a=e.slice(s).replace(/^\s+/,"");return a?`${n}
|
|
913
967
|
|
|
914
968
|
${a}`:n}let o=e.replace(/^\s+/,"");return o?`${n}
|
|
915
969
|
|
|
916
|
-
${o}`:n}function
|
|
970
|
+
${o}`:n}function Xd(e){if(!zd(e))return e;let t=e.indexOf(fr),n=e.indexOf(bn)+bn.length,o=e.slice(0,t).replace(/\s+$/,""),r=e.slice(n).replace(/^\s+/,"");return o&&r?`${o}
|
|
917
971
|
|
|
918
|
-
${r}`:o||r||""}function
|
|
972
|
+
${r}`:o||r||""}function Zd(e,t){return`# AI-DLC Workflow Rules (Olympus-Native)
|
|
919
973
|
|
|
920
974
|
## Active Workflow
|
|
921
975
|
- **Workflow ID**: \`${e}\`
|
|
@@ -926,8 +980,8 @@ ${r}`:o||r||""}function Vd(e,t){return`# AI-DLC Workflow Rules (Olympus-Native)
|
|
|
926
980
|
|
|
927
981
|
All workflow stages, agent delegation, directory layout, and rules are defined in the
|
|
928
982
|
global \`~/.claude/CLAUDE.md\` (installed by Olympus). This block only tracks the active
|
|
929
|
-
workflow identity \u2014 do NOT search for a separate core-workflow.md file.`}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
|
|
983
|
+
workflow identity \u2014 do NOT search for a separate core-workflow.md file.`}var gi=["intent","unit","code-generation","complete"];function iS(e){let t=gi.indexOf(e);return t===-1||t>=gi.length-1?"complete":gi[t+1]}var hr=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 Xu(this.projectPath,this.workflowId)}catch(r){let s=r;throw console.error(`[WorkflowEngine] Failed to initialize workflow directory: ${s.message}`),new Error(`Failed to start workflow: Could not create directory structure - ${s.message}`)}let o=uo.join(this.projectPath,"aidlc-docs",this.workflowId,"manifest.json");if(!Ie.existsSync(o))try{Fs(this.workflowId,this.featureName,this.projectPath)}catch(r){console.warn(`[WorkflowEngine] Failed to create manifest: ${r.message}`)}try{await A(this.projectPath,n)}catch(r){let s=r;throw console.error(`[WorkflowEngine] Failed to save initial checkpoint: ${s.message}`),new Error(`Failed to start workflow: Could not save checkpoint - ${s.message}`)}try{let s=(await Tn(this.projectPath)).sourceFileCount??0,i=await qd(this.projectPath,t),a=pr(t),c=await Vd({projectPath:this.projectPath,workflowId:this.workflowId,intentText:t,depthAssessment:a,pathwayType:i,sourceFileCount:s}),l=await oi(this.projectPath,this.workflowId,c),u=await T(this.projectPath,this.workflowId);if(u){u.workflow_routing_path=l,u.pathway_type=i;let d=["discovery","inception","construction","operations"];u.skipped_phases=d.filter(f=>!ri(c,f)),await A(this.projectPath,u)}if(console.log(`[WorkflowEngine] Generated Workflow Routing: pathway=${i}, depth=${c.estimated_depth}, code-generations=${c.estimated_code_generations}`),c.stages.some(d=>!d.included)){let d=c.stages.filter(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 s=(await T(this.projectPath,this.workflowId))?.pathway_type;if(!s){let{isBrownfield:u}=await Tn(this.projectPath);s=u?"brownfield-enhancement":"greenfield"}let i=uo.join(this.projectPath,".claude","CLAUDE.md"),a=Ie.existsSync(i)?Ie.readFileSync(i,"utf-8"):"",c=Zd(this.workflowId,s),l=Qd(a,c);Ie.mkdirSync(uo.join(this.projectPath,".claude"),{recursive:!0}),Ie.writeFileSync(i,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 T(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 A(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 s=await T(this.projectPath,this.workflowId);s&&(s.status="paused",s.resume_context={...s.resume_context,error_message:r.message,failed_stage:n},await A(this.projectPath,s),console.log("[WorkflowEngine] Workflow saved as paused. Fix the issue and resume with `/continue`"))}catch(s){console.warn("[WorkflowEngine] Failed to save error checkpoint:",s.message)}throw new Error(`Failed to execute ${n} stage: ${r.message}`)}finally{this.cleanupInterruptHandler()}return`Resumed workflow from stage: ${n}`}async pause(){let t;try{t=await T(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 A(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 T(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=iS(t);n.current_stage=o,o==="complete"?await this.completeWorkflow(n):await A(this.projectPath,n)}async getStatus(){let t;try{t=await T(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=dr(this.projectPath,this.workflowId);if(n&&!ri(n,t)){console.log(`[WorkflowEngine] Skipping ${t} phase (excluded by Workflow Routing: ${n.phases[t]?.rationale||"no rationale"})`);let o=await T(this.projectPath,this.workflowId);if(o){let s=o;s.phases&&s.phases[t]&&(s.phases[t].status="complete",s.phases[t].completed_at=new Date().toISOString(),s.phases[t].gate_bypassed=!0,s.phases[t].bypass_reason="Excluded by Workflow Routing"),await A(this.projectPath,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 Ud({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 s={type:"phase_complete",phase:"discovery",details:`${r.artifactsGenerated.length} artifacts generated, ${r.sourceFileCount} source files`},i={workflowId:this.workflowId,featureName:this.featureName,projectPath:this.projectPath,sessionId:"engine",phase:"discovery"},a=$e(s,i);ie(a)}catch(s){console.error("[WorkflowEngine] Failed to capture discovery phase discovery:",s)}break}case"inception":{let{InceptionOrchestrator:o}=await Promise.resolve().then(()=>(kp(),yp)),r=new o,s=await T(this.projectPath,this.workflowId);if(!s)throw new Error(`No checkpoint found for workflow: ${this.workflowId}`);if(s.current_stage!=="intent"){console.log(`[WorkflowEngine] Skipping inception orchestrator \u2014 checkpoint already at stage '${s.current_stage}'`);break}if(!s.inception_stages){let i=dr(this.projectPath,this.workflowId),a=s;await r.initialize(this.projectPath,this.workflowId,a.pathway_type||"greenfield",i)}for(;!await r.isComplete(this.projectPath,this.workflowId);){let i=await r.executeNextStage(this.projectPath,this.workflowId);if(i.status==="awaiting_answers"||i.status==="review_required")break}try{let i={type:"phase_complete",phase:"inception",details:"Inception stages completed"},a={workflowId:this.workflowId,featureName:this.featureName,projectPath:this.projectPath,sessionId:"engine",phase:"inception"},c=$e(i,a);ie(c)}catch(i){console.error("[WorkflowEngine] Failed to capture inception phase discovery:",i)}break}case"construction":{let o=await T(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"),s;try{s=Ie.readFileSync(r,"utf-8")}catch{}let a=await new or(this.projectPath,this.workflowId).execute(s);if(!a.passed)throw console.error("[WorkflowEngine] Construction phase validation failed:",a.blocking_issues),new Error(`Construction phase validation failed: ${a.blocking_issues.join(", ")}`);try{let c={type:"phase_complete",phase:"construction",details:"Construction phase completed"},l={workflowId:this.workflowId,featureName:this.featureName,projectPath:this.projectPath,sessionId:"engine",phase:"construction"},u=$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(()=>(bp(),Ep)),{loadManifest:r,registerArtifact:s,updatePhaseStatus:i}=await Promise.resolve().then(()=>(z(),Vt)),a=`${this.projectPath}/aidlc-docs/${this.workflowId}/manifest.json`,c=r(a),l=null;try{l=Ie.readFileSync(Ot(this.projectPath,this.workflowId,"intent"),"utf-8")}catch{}let u=await T(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){i(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,"_");s(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 A(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=uo.join(this.projectPath,".claude","CLAUDE.md");if(Ie.existsSync(n)){let o=Ie.readFileSync(n,"utf-8"),r=Xd(o);Ie.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 A(this.projectPath,t),await Bu(this.projectPath,this.workflowId)}async approveWorkflowRouting(t){let n=dr(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 oi(this.projectPath,this.workflowId,n);let o=await T(this.projectPath,this.workflowId);if(o){let s=o;if(s.inception_stages?.["workflow-planning"]){let i=s.inception_stages["workflow-planning"];i.status!=="completed"&&i.status!=="skipped"&&(i.status="completed",i.completed_at=new Date().toISOString(),await A(this.projectPath,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(`
|
|
984
|
+
[WorkflowEngine] Workflow interrupted - saving checkpoint...`);try{let t=await T(this.projectPath,this.workflowId);t&&(t.status="paused",t.updated_at=new Date().toISOString(),t.resume_context={...t.resume_context,interrupted_at:new Date().toISOString(),current_stage:t.current_stage,message:`Workflow interrupted during ${t.current_stage} stage`},await A(this.projectPath,t),console.log("[WorkflowEngine] Checkpoint saved. Resume with `/continue`"))}catch(t){console.error("[WorkflowEngine] Failed to save checkpoint on interrupt:",t)}process.exit(0)},process.on("SIGINT",this.interruptHandler)}cleanupInterruptHandler(){this.interruptHandler&&(process.off("SIGINT",this.interruptHandler),this.interruptHandler=null)}async executeIntentStage(t){let n=t.resume_context?.initial_prompt||"No initial prompt provided";console.log(`[WorkflowEngine] Executing INTENT stage for feature: ${this.featureName}`),console.log(`[WorkflowEngine] Initial prompt: ${n}`),console.log("[WorkflowEngine] Generating merged INTENT artifact with full inception content");let o=`intent-${this.workflowId}`,r=new Date().toISOString(),s=`---
|
|
931
985
|
id: ${o}
|
|
932
986
|
title: ${this.featureName}
|
|
933
987
|
status: draft
|
|
@@ -1078,7 +1132,7 @@ The implementation follows the existing system architecture patterns. Core funct
|
|
|
1078
1132
|
|
|
1079
1133
|
---
|
|
1080
1134
|
*Generated by WorkflowEngine based on ${o}*
|
|
1081
|
-
`;await hn(this.projectPath,this.workflowId,"intent",
|
|
1135
|
+
`;await hn(this.projectPath,this.workflowId,"intent",s);let a=`---
|
|
1082
1136
|
id: ${`nfr-${this.workflowId}`}
|
|
1083
1137
|
parent: "${o}"
|
|
1084
1138
|
status: draft
|
|
@@ -1128,41 +1182,41 @@ created: ${r}
|
|
|
1128
1182
|
|
|
1129
1183
|
---
|
|
1130
1184
|
*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
|
|
1185
|
+
`;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 T(this.projectPath,this.workflowId);if(u){let d=u;d.interview_progress={stage:"intent",questions_asked:0,draft_artifact_path:c},u.updated_at=new Date().toISOString(),await A(this.projectPath,u)}}async executeUnitStage(t){throw console.log(`[WorkflowEngine] Executing UNIT stage for feature: ${this.featureName}`),new Error("UNIT stage execution not yet implemented")}async executeCodeGenerationStage(t){throw console.log(`[WorkflowEngine] Executing CODE-GENERATION stage for feature: ${this.featureName}`),new Error("Code generation stage execution not yet implemented")}};we();var Cp={intent:null,unit:null,"code-generation":null,complete:null};function Rp(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 Ip(e,t,n=!1){let o=t.current_stage,r=Cp[o],s=Rp(o),i=`You are beginning a structured workflow for feature: ${e}
|
|
1132
1186
|
|
|
1133
|
-
`;return
|
|
1134
|
-
`,
|
|
1187
|
+
`;return i+=`Current stage: ${o}
|
|
1188
|
+
`,i+=`Status: ${t.status}
|
|
1135
1189
|
|
|
1136
|
-
`,r?(
|
|
1190
|
+
`,r?(i+=`Next step: Invoke the ${r} agent to ${s}
|
|
1137
1191
|
|
|
1138
|
-
`,
|
|
1139
|
-
`):
|
|
1140
|
-
`,n&&(
|
|
1141
|
-
IMPORTANT: This is a BRAND NEW workflow just initialized. `,
|
|
1142
|
-
`),
|
|
1192
|
+
`,i+=`Use: Task(subagent_type="${r}", prompt="...")
|
|
1193
|
+
`):i+=`Next step: ${s}
|
|
1194
|
+
`,n&&(i+=`
|
|
1195
|
+
IMPORTANT: This is a BRAND NEW workflow just initialized. `,i+="Do NOT treat this as a resumed or existing workflow. ",i+=`Proceed with workspace detection as the first step.
|
|
1196
|
+
`),i}function Op(e,t){let n=t.current_stage,o=Cp[n],r=Rp(n),s=`Resuming workflow for feature: ${e}
|
|
1143
1197
|
|
|
1144
|
-
`;return
|
|
1145
|
-
`,
|
|
1198
|
+
`;return s+=`You were interrupted during: ${n}
|
|
1199
|
+
`,s+=`Last update: ${t.updated_at}
|
|
1146
1200
|
|
|
1147
|
-
`,t.resume_context?
|
|
1201
|
+
`,t.resume_context?s+=`Resume context: ${JSON.stringify(t.resume_context,null,2)}
|
|
1148
1202
|
|
|
1149
|
-
`:
|
|
1203
|
+
`:s+=`Resume context: No additional context available
|
|
1150
1204
|
|
|
1151
|
-
`,o?(
|
|
1205
|
+
`,o?(s+=`Continue from where you left off: Invoke the ${o} agent to ${r}
|
|
1152
1206
|
|
|
1153
|
-
`,
|
|
1154
|
-
`):
|
|
1155
|
-
`,
|
|
1207
|
+
`,s+=`Use: Task(subagent_type="${o}", prompt="...")
|
|
1208
|
+
`):s+=`Continue from where you left off: ${r}
|
|
1209
|
+
`,s}function hi(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 Pp(){_({name:"structuredWorkflowDetector",event:"UserPromptSubmit",priority:8,handler:async e=>{let t=hi(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 s,i=r.match(/\s+--depth\s+(shallow|medium|deep)\s*$/i);i&&(s=i[1].toLowerCase(),r=r.replace(i[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 hr(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 T(e.directory,d);if(!f)return{continue:!0};let m=Ip(r,f,!0),g=`${`[Workflow: ${d} | Phase: ${f.current_phase||"inception"} | Stage: ${f.current_stage||"intent"}]`}
|
|
1156
1210
|
|
|
1157
|
-
${m}`;return
|
|
1211
|
+
${m}`;return s&&(g+=`
|
|
1158
1212
|
|
|
1159
|
-
Depth override: ${
|
|
1213
|
+
Depth override: ${s}`),a&&(g+=`
|
|
1160
1214
|
|
|
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
|
|
1215
|
+
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 ne(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 s=r[0],i=await T(e.directory,s);if(!i)return{continue:!0};let a=Op(i.feature_name,i);return{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:`[TIP: For full AIDLC resume with behavioral rules, use /continue instead of /plan continue]
|
|
1162
1216
|
|
|
1163
|
-
${`[Workflow: ${
|
|
1217
|
+
${`[Workflow: ${s} | Phase: ${i.current_phase||"inception"} | Stage: ${i.current_stage||"intent"}]`}
|
|
1164
1218
|
|
|
1165
|
-
${a}`}}}catch(r){return console.error("[Workflow Resume]",r),{continue:!0}}return{continue:!0}}}),
|
|
1219
|
+
${a}`}}}catch(r){return console.error("[Workflow Resume]",r),{continue:!0}}return{continue:!0}}}),_({name:"keywordDetector",event:"UserPromptSubmit",priority:10,handler:e=>{let t=hi(e);if(!t)return{continue:!0};let n=Ha(t),o=Ba(n);if(o.length===0)return{continue:!0};let r=o.some(c=>c.type==="ultrawork"),s=o.some(c=>c.type==="ultrathink"),i=o.some(c=>c.type==="search"),a=o.some(c=>c.type==="analyze");return r?(uc(t,e.sessionId,e.directory||process.cwd()),{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:gc}}):s?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:hc}}:i?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:yc}}:a?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:kc}}:{continue:!0}}}),_({name:"autoSlashCommand",event:"UserPromptSubmit",priority:20,handler:e=>{if(!e.parts)return{continue:!0};let n=ec().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=cc(),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=hi(e);return!t||!e.directory?{continue:!0}:(Promise.resolve().then(async()=>{try{await Gc({prompt:t,directory:e.directory,sessionId:e.sessionId}),await Vc({prompt:t,directory:e.directory,sessionId:e.sessionId})}catch(n){console.error("[Olympus Learning]",n)}}),{continue:!0})}})}var yi=require("child_process");var aS="mcpProcessCleanup",cS=/mcp/i;function lS(e){return e?cS.test(e):!1}function uS(e,t){return e.filter(n=>lS(n.CommandLine)?!t.has(n.ParentProcessId):!1)}function dS(e){let t=0;for(let n of e)try{(0,yi.execSync)(`taskkill /T /F /PID ${n.ProcessId}`,{encoding:"utf8",timeout:5e3,stdio:"pipe"}),t++}catch{}return t}function pS(){if(process.platform!=="win32")return 0;try{let e=`
|
|
1166
1220
|
$nodeProcs = Get-CimInstance Win32_Process -Filter "Name='node.exe'" |
|
|
1167
1221
|
Select-Object ProcessId, ParentProcessId, CommandLine;
|
|
1168
1222
|
$allPids = (Get-Process -ErrorAction SilentlyContinue).Id;
|
|
@@ -1170,9 +1224,9 @@ ${a}`}}}catch(r){return console.error("[Workflow Resume]",r),{continue:!0}}retur
|
|
|
1170
1224
|
nodeProcesses = @($nodeProcs | ForEach-Object { @{ ProcessId=$_.ProcessId; ParentProcessId=$_.ParentProcessId; CommandLine=$_.CommandLine } });
|
|
1171
1225
|
allPids = @($allPids)
|
|
1172
1226
|
} | ConvertTo-Json -Depth 3
|
|
1173
|
-
`.replace(/\n/g," "),t=(0,
|
|
1227
|
+
`.replace(/\n/g," "),t=(0,yi.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]:[]),s=uS(o,r);return s.length===0?0:dS(s)}catch(e){return console.error("[Olympus MCP Cleanup] Error:",e),0}}function Ap(){_({name:aS,event:"SessionStart",priority:1,handler:e=>{let t=pS();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"),xp=require("os");function fS(e,t){let n=(0,Dt.join)((0,xp.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 s=(0,Qt.readdirSync)(r);for(let i of s)i.endsWith(".json")&&o.push((0,Dt.join)(r,i))}catch{}return o}function mS(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 gS(e){return e.status!=="completed"&&e.status!=="cancelled"}async function po(e,t){let n=fS(e,t),o=new Set,r=[],s=[];for(let i of n){if(!(0,Qt.existsSync)(i))continue;let a=mS(i);for(let c of a){let l=`${c.content}:${c.status}`;o.has(l)||(o.add(l),r.push(c),gS(c)&&s.push(c))}}return{count:s.length,todos:s,total:r.length}}function $p(e){let t=e.todos.find(n=>n.status==="in_progress");return t||(e.todos.find(n=>n.status==="pending")??null)}var ki=require("path");fe();er();fe();function Np(e,t=5){return(e.token_efficiency?.invocation_count??0)>=t}ws();var Dp=500;function jp(e){let t=me((0,ki.join)(ce(),"user-preferences.json"),null),n=me((0,ki.join)(Xe(e),"patterns.json"),null),o=ln(),r=ln(e),s={...o,...r},i=[];if(t&&hS(t)){let u=t.explicit_rules.filter(f=>!f.project_path||f.project_path===e),d={...t,explicit_rules:u};i.push(yS(d))}n&&(n.conventions.length>0||n.tech_stack.length>0||n.learned_rules&&n.learned_rules.length>0||n.common_mistakes&&n.common_mistakes.length>0)&&i.push(kS(n)),t?.recurring_corrections&&t.recurring_corrections.length>0&&i.push(wS(t.recurring_corrections.slice(0,5)));let a=Object.values(s).filter(u=>u.weak_areas.length>0);a.length>0&&i.push(_S(a));let c=SS(s);if(c&&i.push(c),i.length===0)return"";let l=`<learned-context>
|
|
1174
1228
|
|
|
1175
|
-
${
|
|
1229
|
+
${i.join(`
|
|
1176
1230
|
|
|
1177
1231
|
`)}
|
|
1178
1232
|
|
|
@@ -1180,21 +1234,21 @@ ${s.join(`
|
|
|
1180
1234
|
|
|
1181
1235
|
---
|
|
1182
1236
|
|
|
1183
|
-
`;return l.length>
|
|
1237
|
+
`;return l.length>Dp*4?l.substring(0,Dp*4)+`
|
|
1184
1238
|
...</learned-context>
|
|
1185
1239
|
|
|
1186
1240
|
---
|
|
1187
1241
|
|
|
1188
|
-
`:l}function
|
|
1189
|
-
`)}function
|
|
1190
|
-
`)}function
|
|
1191
|
-
`)}function
|
|
1192
|
-
`)}function
|
|
1193
|
-
`)}function
|
|
1194
|
-
`)}pt();
|
|
1195
|
-
`);for(let r of o){let
|
|
1196
|
-
`)}catch(t){return console.error("[WorkflowBridge] Failed to generate workflow summary:",t),""}}async function
|
|
1197
|
-
`)}catch(t){return console.error("[WorkflowBridge] Failed to generate bolt execution plan:",t),""}}async function
|
|
1242
|
+
`:l}function hS(e){return e.verbosity!=="unknown"||e.autonomy!=="unknown"||e.explicit_rules.length>0||e.inferred_preferences.length>0}function yS(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(`
|
|
1243
|
+
`)}function kS(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(`
|
|
1244
|
+
`)}function wS(e){let t=["## Avoid These Mistakes"];for(let n of e)t.push(`- ${n.pattern} (${n.count}x)`);return t.join(`
|
|
1245
|
+
`)}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(`
|
|
1246
|
+
`)}function SS(e){let t=Object.values(e).filter(a=>a.token_efficiency&&Np(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(),s=Math.round(o*1.5),i=s>=1e3?`${(s/1e3).toFixed(0)}k`:s.toString();return n.push(""),n.push(`SESSION BUDGET: ~${r} baseline | warn at ${i}`),n.push("PATTERNS: Parallel reads save 40%"),n.push(""),n.push("Quality remains priority. Use efficiency as tiebreaker."),n.push("</olympus-efficiency>"),n.join(`
|
|
1247
|
+
`)}function Mp(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(`
|
|
1248
|
+
`)}pt();Ae();var Up=E(require("path"),1);we();z();var qe=E(require("path"),1),kr=E(se(),1);z();we();$t();async function wr(e){try{let t=await ne(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 s=await T(e,n);if(!s)return null;let i=_e(e),a=vS(r),l=Ws(r,"fulfilled").map(f=>f.id),d=qt(r).filter(f=>f.contract_status!=="fulfilled").map(f=>f.id);return{workflowId:s.workflow_id,featureName:s.feature_name,currentPhase:s.current_phase,currentStage:s.current_stage,manifest:r,checkpoint:s,trustLevel:i.current_level,riskTier:s.risk_tier??0,depthScore:s.depth_score??0,pendingBolts:a,completedBolts:l,pendingUnits:d,executionMode:s.execution_mode??"manual"}}catch(t){return console.error("[WorkflowBridge] Failed to detect active workflow:",t),null}}function vS(e){return ot(e).filter(n=>n.contract_status!=="fulfilled").map(n=>n.id)}function TS(e){let t=qt(e),n=ot(e),o=[...t].sort((a,c)=>a.id.localeCompare(c.id)),r=[],s=new Set;for(let a of o){let l=[...ot(e,a.id)].sort((u,d)=>u.id.localeCompare(d.id));for(let u of l)r.push(u.id),s.add(u.id)}let i=n.filter(a=>!s.has(a.id)).sort((a,c)=>a.id.localeCompare(c.id));for(let a of i)r.push(a.id);return r}function mo(e){let t=ot(e),n=t.length;if(n===0)return{completed:0,total:0,percentage:0};let o=t.filter(s=>s.contract_status==="fulfilled").length,r=Math.round(o/n*100);return{completed:o,total:n,percentage:r}}function fo(e,t){try{if(!kr.existsSync(e))return t;let o=kr.readFileSync(e,"utf-8").split(`
|
|
1249
|
+
`);for(let r of o){let s=r.trim();if(s.startsWith("# "))return s.slice(2).trim()}return t}catch{return t}}function yr(e,t){return e.links.find(o=>o.target_id===t&&(o.link_type==="derives"||o.link_type==="implements"))?.source_id??null}function ES(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 Lp(e){try{let t=await wr(e);if(!t)return"";let n=mo(t.manifest),o=ot(t.manifest),r=[];for(let a of t.pendingBolts){if(!o.find(m=>m.id===a))continue;let l=yr(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=fo(u,a),f=l?` (${l})`:"";r.push(`- ${a} "${d}"${f}`)}let s=[];for(let a of t.completedBolts){if(!o.find(f=>f.id===a))continue;let l=yr(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=fo(u,a);s.push(`- ${a} "${d}" done`)}let i=["## Active Workflow",`Workflow: ${t.featureName} (${t.workflowId})`,`Phase: ${t.currentPhase} | Stage: ${t.currentStage}`,`Trust: Level ${t.trustLevel} | Risk: Tier ${t.riskTier} | Depth: ${t.depthScore}`,`Mode: ${t.executionMode}`,"","### Progress",`BOLTs: ${n.completed}/${n.total} (${n.percentage}%)`];return r.length>0&&(i.push("","### Pending BOLTs:"),i.push(...r)),s.length>0&&(i.push("","### Completed BOLTs:"),i.push(...s)),i.join(`
|
|
1250
|
+
`)}catch(t){return console.error("[WorkflowBridge] Failed to generate workflow summary:",t),""}}async function Fp(e){try{let t=await wr(e);if(!t)return"";let n=ot(t.manifest),o=TS(t.manifest),r=new Set(t.pendingBolts),s=qt(t.manifest),i=[],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=yr(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=fo(m,u),g=ES(d.path),h="";if(f){let y=s.find(I=>I.id===f),w=qe.join(e,"aidlc-docs",t.workflowId,"construction",f,"spec.md"),k=fo(w,f);h=` (${f}: ${k})`}i.push(`${a}. ${u} "${p}"${h}`),i.push(` Agent: ${g} | Files: ${d.path}`),a++}let c=[];for(let u of t.completedBolts){if(!n.find(g=>g.id===u))continue;let f=yr(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=fo(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 i.length>0&&(l.push("","### Pending BOLTs (execute in this order):"),l.push(...i)),c.length>0&&(l.push("","### Completed BOLTs:"),l.push(...c)),l.push("","### Instructions:"),l.push("For each pending BOLT: read its spec file, dispatch to the listed agent, then present Gate 4 review."),l.join(`
|
|
1251
|
+
`)}catch(t){return console.error("[WorkflowBridge] Failed to generate bolt execution plan:",t),""}}async function Wp(e){let t=[];try{let n=await ne(e);for(let o of n){let r=await T(e,o);if(!r||r.status==="complete"||r.status==="archived")continue;let s=Up.join(e,"aidlc-docs",o,"manifest.json"),i=D(s),a={completed:0,total:0};i&&(a=mo(i)),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 Hp(){Ap(),_({name:"learnedContextInjection",event:"SessionStart",priority:5,handler:e=>{if(!e.directory)return{continue:!0};try{let t=jp(e.directory),n=ar(e.directory,5),o=Mp(n),r=new Date,s=new Date(r.getTime()-1440*60*1e3);for(let c of n)try{new Date(c.last_useful)<s&&Gd(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
1252
|
[OLYMPUS MODE ACTIVE]
|
|
1199
1253
|
You are operating as an Olympus orchestrator. MANDATORY behaviors:
|
|
1200
1254
|
- DELEGATE multi-file changes to subagents (olympian, oracle, frontend-engineer, etc.) via the Task tool
|
|
@@ -1206,11 +1260,11 @@ You are operating as an Olympus orchestrator. MANDATORY behaviors:
|
|
|
1206
1260
|
|
|
1207
1261
|
`+t+(o?`
|
|
1208
1262
|
|
|
1209
|
-
`+o:"")}}}catch(t){console.error("[Olympus Learning]",t)}return{continue:!0}}}),
|
|
1263
|
+
`+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 Wp(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
1264
|
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
1265
|
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=
|
|
1213
|
-
`)}}}catch(t){console.error("[Olympus Resume Detection] Error:",t)}return{continue:!0}}}),
|
|
1266
|
+
Resume with /continue or check status with /workflow-status]`)}let r=_e(t);o.push(`[Trust Level: ${r.current_level}]`);let s=await Lp(t);s&&o.push(s);let i=await Fp(t);i&&o.push(i);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(`
|
|
1267
|
+
`)}}}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 i=V(n,t);i.token_budget||(Mc(i,n),X(n,i))}catch(i){console.error("[Olympus Learning] Failed to initialize token budget:",i)}let r=_t(n);r?.active&&o.push(`<session-restore>
|
|
1214
1268
|
|
|
1215
1269
|
[ULTRAWORK MODE RESTORED]
|
|
1216
1270
|
|
|
@@ -1223,11 +1277,11 @@ Continue working in ultrawork mode until all tasks are complete.
|
|
|
1223
1277
|
|
|
1224
1278
|
---
|
|
1225
1279
|
|
|
1226
|
-
`);let
|
|
1280
|
+
`);let s=await po(t,n);return s.count>0&&o.push(`<session-restore>
|
|
1227
1281
|
|
|
1228
1282
|
[PENDING TASKS DETECTED]
|
|
1229
1283
|
|
|
1230
|
-
You have ${
|
|
1284
|
+
You have ${s.count} incomplete tasks from a previous session.
|
|
1231
1285
|
Please continue working on these tasks.
|
|
1232
1286
|
|
|
1233
1287
|
</session-restore>
|
|
@@ -1235,7 +1289,7 @@ Please continue working on these tasks.
|
|
|
1235
1289
|
---
|
|
1236
1290
|
|
|
1237
1291
|
`),o.length>0?{continue:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:o.join(`
|
|
1238
|
-
`)}}:{continue:!0}}})}var
|
|
1292
|
+
`)}}:{continue:!0}}})}var Pn=require("fs"),ht=require("path"),Ri=require("os");var Oe=require("fs"),jt=require("path"),Bp=require("os");function wi(e){let t=(0,jt.join)(e,".olympus");return(0,jt.join)(t,"ascent-state.json")}function bS(e){let t=(0,jt.join)(e,".olympus");(0,Oe.existsSync)(t)||(0,Oe.mkdirSync)(t,{recursive:!0})}function In(e){let t=wi(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 CS(e,t){try{bS(e);let n=wi(e);return(0,Oe.writeFileSync)(n,JSON.stringify(t,null,2)),!0}catch{return!1}}function _r(e){let t=wi(e);if(!(0,Oe.existsSync)(t))return!0;try{return(0,Oe.unlinkSync)(t),!0}catch{return!1}}function Gp(e){let t=In(e);return!t||!t.active?null:(t.iteration+=1,CS(e,t)?t:null)}function qp(e,t){let n=(0,jt.join)((0,Bp.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 s=(0,Oe.readFileSync)(r,"utf-8");if(new RegExp(`<promise>\\s*${RS(t)}\\s*</promise>`,"is").test(s))return!0}catch{continue}return!1}function RS(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Me=require("fs"),_i=require("path"),IS=3;function Si(e){return(0,_i.join)(e,".olympus","ascent-verification.json")}function ho(e){let t=Si(e);if(!(0,Me.existsSync)(t))return null;try{return JSON.parse((0,Me.readFileSync)(t,"utf-8"))}catch{return null}}function Vp(e,t){let n=Si(e),o=(0,_i.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 go(e){let t=Si(e);if((0,Me.existsSync)(t))try{return(0,Me.unlinkSync)(t),!0}catch{return!1}return!0}function Yp(e,t,n){let o={pending:!0,completion_claim:t,verification_attempts:0,max_verification_attempts:IS,requested_at:new Date().toISOString(),original_task:n};return Vp(e,o),o}function Kp(e,t,n){let o=ho(e);return o?(o.verification_attempts+=1,o.oracle_approved=t,o.oracle_feedback=n,t?(go(e),{...o,pending:!1}):o.verification_attempts>=o.max_verification_attempts?(go(e),{...o,pending:!1}):(Vp(e,o),o)):null}function vi(e){return`<ascent-verification>
|
|
1239
1293
|
|
|
1240
1294
|
[ORACLE VERIFICATION REQUIRED - Attempt ${e.verification_attempts+1}/${e.max_verification_attempts}]
|
|
1241
1295
|
|
|
@@ -1275,7 +1329,7 @@ DO NOT output the completion promise again until Oracle approves.
|
|
|
1275
1329
|
|
|
1276
1330
|
---
|
|
1277
1331
|
|
|
1278
|
-
`}function
|
|
1332
|
+
`}function Jp(e){return`<ascent-continuation-after-rejection>
|
|
1279
1333
|
|
|
1280
1334
|
[ORACLE REJECTED - Continue Working]
|
|
1281
1335
|
|
|
@@ -1300,7 +1354,7 @@ Continue working now.
|
|
|
1300
1354
|
|
|
1301
1355
|
---
|
|
1302
1356
|
|
|
1303
|
-
`}function
|
|
1357
|
+
`}function zp(e){return/<oracle-approved>.*?VERIFIED_COMPLETE.*?<\/oracle-approved>/is.test(e)}function Qp(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 ae=require("fs"),On=require("path"),Ti=require("os");function Ei(e){let t=e||process.cwd(),n=(0,On.join)(t,".olympus");return(0,On.join)(n,"olympus-state.json")}function bi(){return(0,On.join)((0,Ti.homedir)(),".claude","olympus-state.json")}function OS(e){let t=e||process.cwd(),n=(0,On.join)(t,".olympus");(0,ae.existsSync)(n)||(0,ae.mkdirSync)(n,{recursive:!0})}function PS(){let e=(0,On.join)((0,Ti.homedir)(),".claude");(0,ae.existsSync)(e)||(0,ae.mkdirSync)(e,{recursive:!0})}function Xt(e){let t=Ei(e);if((0,ae.existsSync)(t))try{let o=(0,ae.readFileSync)(t,"utf-8");return JSON.parse(o)}catch{}let n=bi();if((0,ae.existsSync)(n))try{let o=(0,ae.readFileSync)(n,"utf-8");return JSON.parse(o)}catch{return null}return null}function Xp(e,t){try{OS(t);let n=Ei(t);(0,ae.writeFileSync)(n,JSON.stringify(e,null,2)),PS();let o=bi();return(0,ae.writeFileSync)(o,JSON.stringify(e,null,2)),!0}catch{return!1}}function Ci(e){let t=Ei(e);if((0,ae.existsSync)(t))try{(0,ae.unlinkSync)(t)}catch{}let n=bi();if((0,ae.existsSync)(n))try{return(0,ae.unlinkSync)(n),!0}catch{return!1}return!0}function Zp(e){let t=Xt(e);return!t||!t.active?null:(t.reinforcement_count+=1,t.last_checked_at=new Date().toISOString(),Xp(t,e)?t:null)}function ef(e){let t=Xt(e);return!t||!t.active?!1:(t.oracle_approved=!0,t.last_checked_at=new Date().toISOString(),Xp(t,e))}function tf(e){let t=e.requires_oracle_verification&&!e.oracle_approved?`
|
|
1304
1358
|
|
|
1305
1359
|
**ORACLE VERIFICATION REQUIRED**: Before declaring complete, you MUST get Oracle approval.`:"";return`<olympus-persistence>
|
|
1306
1360
|
|
|
@@ -1322,9 +1376,9 @@ Original task: ${e.original_prompt}
|
|
|
1322
1376
|
|
|
1323
1377
|
---
|
|
1324
1378
|
|
|
1325
|
-
`}
|
|
1379
|
+
`}we();function nf(e){let t=(0,ht.join)((0,Ri.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,Pn.existsSync)(o))try{let r=(0,Pn.readFileSync)(o,"utf-8");if(zp(r))return!0}catch{continue}return!1}function AS(e){let t=(0,ht.join)((0,Ri.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,Pn.existsSync)(o))try{let r=(0,Pn.readFileSync)(o,"utf-8"),s=Qp(r);if(s.rejected)return s}catch{continue}return{rejected:!1,feedback:""}}async function xS(e,t){let n=t||process.cwd(),o=In(n);if(!o||!o.active||o.session_id&&e&&o.session_id!==e)return null;let r=ho(n);if(r?.pending){if(e){if(nf(e))return go(n),_r(n),{shouldBlock:!1,message:`[ASCENT LOOP VERIFIED COMPLETE] Oracle verified task completion after ${o.iteration} iteration(s). Excellent work!`,mode:"none"};let l=AS(e);if(l.rejected){Kp(n,!1,l.feedback);let u=ho(n);if(u)return{shouldBlock:!0,message:Jp(u),mode:"ascent",metadata:{iteration:o.iteration,maxIterations:o.max_iterations}}}}return{shouldBlock:!0,message:vi(r),mode:"ascent",metadata:{iteration:o.iteration,maxIterations:o.max_iterations}}}if(qp(e||"",o.completion_promise)){Yp(n,o.completion_promise,o.prompt);let c=ho(n);return c?{shouldBlock:!0,message:vi(c),mode:"ascent",metadata:{iteration:o.iteration,maxIterations:o.max_iterations}}:(_r(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 _r(n),go(n),{shouldBlock:!1,message:`[ASCENT LOOP STOPPED] Max iterations (${o.max_iterations}) reached without completion promise. Consider reviewing the task requirements.`,mode:"none"};let i=Gp(n);return i?{shouldBlock:!0,message:`<ascent-continuation>
|
|
1326
1380
|
|
|
1327
|
-
[ASCENT LOOP - ITERATION ${
|
|
1381
|
+
[ASCENT LOOP - ITERATION ${i.iteration}/${i.max_iterations}]
|
|
1328
1382
|
|
|
1329
1383
|
Your previous attempt did not output the completion promise. The work is NOT done yet.
|
|
1330
1384
|
|
|
@@ -1332,16 +1386,16 @@ CRITICAL INSTRUCTIONS:
|
|
|
1332
1386
|
1. Review your progress and the original task
|
|
1333
1387
|
2. Check your todo list - are ALL items marked complete?
|
|
1334
1388
|
3. Continue from where you left off
|
|
1335
|
-
4. When FULLY complete, output: <promise>${
|
|
1389
|
+
4. When FULLY complete, output: <promise>${i.completion_promise}</promise>
|
|
1336
1390
|
5. Do NOT stop until the task is truly done
|
|
1337
1391
|
|
|
1338
|
-
${
|
|
1392
|
+
${i.prompt?`Original task: ${i.prompt}`:""}
|
|
1339
1393
|
|
|
1340
1394
|
</ascent-continuation>
|
|
1341
1395
|
|
|
1342
1396
|
---
|
|
1343
1397
|
|
|
1344
|
-
`,mode:"ascent",metadata:{iteration:
|
|
1398
|
+
`,mode:"ascent",metadata:{iteration:i.iteration,maxIterations:i.max_iterations}}:null}async function $S(e,t,n){let o=_t(t);if(!o||!o.active||o.session_id&&e&&o.session_id!==e)return null;if(!n)return dc(t),{shouldBlock:!1,message:"[ULTRAWORK COMPLETE] All tasks finished. Ultrawork mode deactivated. Well done!",mode:"none"};let r=pc(t);return r?{shouldBlock:!0,message:fc(r),mode:"ultrawork",metadata:{reinforcementCount:r.reinforcement_count}}:null}async function NS(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 Ci(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&&nf(e)?(ef(t),Ci(t),{shouldBlock:!1,message:"[OLYMPUS VERIFIED COMPLETE] Oracle approved. Orchestration mode deactivated. Excellent work!",mode:"none"}):{shouldBlock:!0,message:`<olympus-verification-required>
|
|
1345
1399
|
|
|
1346
1400
|
[OLYMPUS MODE - ORACLE VERIFICATION REQUIRED]
|
|
1347
1401
|
|
|
@@ -1364,11 +1418,11 @@ DO NOT stop until Oracle has approved.
|
|
|
1364
1418
|
|
|
1365
1419
|
---
|
|
1366
1420
|
|
|
1367
|
-
`,mode:"olympus",metadata:{reinforcementCount:o.reinforcement_count}};let r=
|
|
1421
|
+
`,mode:"olympus",metadata:{reinforcementCount:o.reinforcement_count}};let r=Zp(t);return r?{shouldBlock:!0,message:tf(r),mode:"olympus",metadata:{reinforcementCount:r.reinforcement_count}}:null}async function DS(e,t){let n=await po(e,t);if(n.count===0)return null;let o=$p(n),r=o?`
|
|
1368
1422
|
|
|
1369
1423
|
Next task: "${o.content}" (${o.status})`:"";return{shouldBlock:!0,message:`<todo-continuation>
|
|
1370
1424
|
|
|
1371
|
-
${
|
|
1425
|
+
${wc}
|
|
1372
1426
|
|
|
1373
1427
|
[Status: ${n.count} of ${n.total} tasks remaining]${r}
|
|
1374
1428
|
|
|
@@ -1376,11 +1430,11 @@ ${yc}
|
|
|
1376
1430
|
|
|
1377
1431
|
---
|
|
1378
1432
|
|
|
1379
|
-
`,mode:"todo-continuation",metadata:{todoCount:n.count}}}async function
|
|
1380
|
-
Workflow '${r.featureName}': ${
|
|
1381
|
-
Next: ${l}`}try{await
|
|
1382
|
-
${l.progressMessage}`),u;let d=await
|
|
1383
|
-
${l.progressMessage}`),d;let f=await
|
|
1433
|
+
`,mode:"todo-continuation",metadata:{todoCount:n.count}}}async function jS(e,t,n){let o=t||process.cwd();try{let r=await wr(o);if(!r)return null;let s=mo(r.manifest),i=r.pendingBolts.length>0,a=`
|
|
1434
|
+
Workflow '${r.featureName}': ${s.completed}/${s.total} BOLTs complete (${s.percentage}%)`;if(r.pendingBolts.length>0){let l=r.pendingBolts[0];a+=`
|
|
1435
|
+
Next: ${l}`}try{await A(o,r.checkpoint)}catch{}return{progressMessage:a,shouldBlock:i&&(n==="ascent"||n==="ultrawork"||n==="olympus")}}catch{return null}}async function of(e,t){let n=t||process.cwd(),r=(await po(e,n)).count>0,s=In(n),i=_t(n),a=Xt(n),c=null;s?.active?c="ascent":i?.active?c="ultrawork":a?.active&&(c="olympus");let l=await jS(e,n,c),u=await xS(e,n);if(u?.shouldBlock)return l&&(u.message=u.message+`
|
|
1436
|
+
${l.progressMessage}`),u;let d=await $S(e,n,r);if(d?.shouldBlock)return l&&(d.message=d.message+`
|
|
1437
|
+
${l.progressMessage}`),d;let f=await NS(e,n,r);if(f?.shouldBlock)return l&&(f.message=f.message+`
|
|
1384
1438
|
${l.progressMessage}`),f;if(l?.shouldBlock)return{shouldBlock:!0,message:`<workflow-continuation>
|
|
1385
1439
|
|
|
1386
1440
|
[WORKFLOW IN PROGRESS - DO NOT STOP]
|
|
@@ -1393,21 +1447,21 @@ You are in ${c} mode with pending BOLTs. Continue executing the remaining BOLTs.
|
|
|
1393
1447
|
|
|
1394
1448
|
---
|
|
1395
1449
|
|
|
1396
|
-
`,mode:c||"none",metadata:{}};if(r){let m=await
|
|
1397
|
-
${l.progressMessage}`),m}return l?{shouldBlock:!1,message:l.progressMessage,mode:"none"}:{shouldBlock:!1,message:"",mode:"none"}}function
|
|
1398
|
-
`),n={},o=0;for(;o<t.length;){let r=t[o],
|
|
1450
|
+
`,mode:c||"none",metadata:{}};if(r){let m=await DS(e,n);if(m?.shouldBlock)return l&&(m.message=m.message+`
|
|
1451
|
+
${l.progressMessage}`),m}return l?{shouldBlock:!1,message:l.progressMessage,mode:"none"}:{shouldBlock:!1,message:"",mode:"none"}}function rf(e){return e.shouldBlock?{continue:!1,stopReason:e.message}:{continue:!0,message:e.message||void 0}}var An=require("fs"),Ii=require("path"),sf=require("os");Ae();fe();var af=require("crypto");function MS(){let e=(0,Ii.join)((0,sf.homedir)(),".claude","todos");if(!(0,An.existsSync)(e))return 0;let t=0;try{let n=(0,An.readdirSync)(e).filter(o=>o.endsWith(".json"));for(let o of n)try{let r=(0,An.readFileSync)((0,Ii.join)(e,o),"utf-8"),s=JSON.parse(r);Array.isArray(s)&&(t+=s.filter(i=>i.status!=="completed"&&i.status!=="cancelled").length)}catch{}}catch{}return t}async function cf(e){let{directory:t,sessionId:n}=e;if(!t)return;let o=V(t,n),r=MS();if(r>0&&o.pending_completion){let s={id:(0,af.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(s)}o.pending_completion=null,o.todo_snapshot={total:0,completed:0,pending:r},X(t,o)}function lf(){_({name:"persistentMode",event:"Stop",priority:10,handler:async e=>{let t=e.sessionId,n=e.directory||process.cwd(),o=await of(t,n),r=rf(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 cf({directory:e.directory,sessionId:e.sessionId})}catch(t){console.error("[Olympus Learning]",t)}}),{continue:!0}):{continue:!0}})}var Li=require("fs"),Fi=require("os"),ko=require("path");var Ve=require("fs"),De=require("path");var Oi=require("path"),uf=require("os"),LS=(0,Oi.join)((0,uf.homedir)(),".olympus"),Sr=(0,Oi.join)(LS,"rules-injector"),df=[".git","pyproject.toml","package.json","Cargo.toml","go.mod",".venv"],pf=[[".github","instructions"],[".cursor","rules"],[".claude","rules"]],ff=[".github/copilot-instructions.md"],mf=/\.instructions\.md$/,gf=".claude/rules",hf=[".md",".mdc"],Pi=["read","write","edit","multiedit"];function FS(e){return e.includes(".github/instructions")||e.endsWith(".github/instructions")}function US(e,t){return FS(t)?mf.test(e):hf.some(n=>e.endsWith(n))}function $i(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 df){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 xi(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()?xi(r,t):o.isFile()&&US(o.name,e)&&t.push(r)}}catch{}}function Ai(e){try{return(0,Ve.realpathSync)(e)}catch{return e}}function Ni(e,t,n){let o=[],r=new Set,s=(0,De.dirname)(n),i=0;for(;;){for(let[u,d]of pf){let f=(0,De.join)(s,u,d),m=[];xi(f,m);for(let p of m){let g=Ai(p);r.has(g)||(r.add(g),o.push({path:p,realPath:g,isGlobal:!1,distance:i}))}}if(e&&s===e)break;let l=(0,De.dirname)(s);if(l===s)break;s=l,i++}if(e)for(let l of ff){let u=(0,De.join)(e,l);if((0,Ve.existsSync)(u))try{if((0,Ve.statSync)(u).isFile()){let f=Ai(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,gf),c=[];xi(a,c);for(let l of c){let u=Ai(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 yf=require("crypto"),kf=require("path");function WS(e,t){let n=e.replace(/\./g,"\\.").replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/<<<GLOBSTAR>>>/g,".*").replace(/\?/g,".");return new RegExp(`^${n}$`).test(t)}function Di(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 i=(n?(0,kf.relative)(n,t):t).replace(/\\/g,"/");for(let a of r)if(WS(a,i))return{applies:!0,reason:`glob: ${a}`};return{applies:!1}}function wf(e,t){return t.has(e)}function _f(e){return(0,yf.createHash)("sha256").update(e).digest("hex").slice(0,16)}function Sf(e,t){return t.has(e)}function ji(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:HS(o),body:r}}catch{return{metadata:{},body:e}}}function HS(e){let t=e.split(`
|
|
1452
|
+
`),n={},o=0;for(;o<t.length;){let r=t[o],s=r.indexOf(":");if(s===-1){o++;continue}let i=r.slice(0,s).trim(),a=r.slice(s+1).trim();if(i==="description")n.description=yo(a);else if(i==="alwaysApply")n.alwaysApply=a==="true";else if(i==="globs"||i==="paths"||i==="applyTo"){let{value:c,consumed:l}=BS(a,t,o);n.globs=qS(n.globs,c),o+=l;continue}o++}return n}function yo(e){return e?e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e:""}function BS(e,t,n){if(e.startsWith("["))return{value:GS(e),consumed:1};if(!e||e===""){let r=[],s=1;for(let i=n+1;i<t.length;i++){let a=t[i],c=a.match(/^\s+-\s*(.*)$/);if(c){let l=yo(c[1].trim());l&&r.push(l),s++}else if(a.trim()==="")s++;else break}if(r.length>0)return{value:r,consumed:s}}let o=yo(e);return o.includes(",")?{value:o.split(",").map(s=>s.trim()).filter(s=>s.length>0),consumed:1}:{value:o,consumed:1}}function GS(e){let t=e.slice(1,e.lastIndexOf("]")).trim();if(!t)return[];let n=[],o="",r=!1,s="";for(let a=0;a<t.length;a++){let c=t[a];if(!r&&(c==='"'||c==="'"))r=!0,s=c;else if(r&&c===s)r=!1,s="";else if(!r&&c===","){let l=o.trim();l&&n.push(yo(l)),o=""}else o+=c}let i=o.trim();return i&&n.push(yo(i)),n}function qS(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"),vf=require("path");function Mi(e){return(0,vf.join)(Sr,`${e}.json`)}function Tf(e){let t=Mi(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 Ef(e,t){(0,Le.existsSync)(Sr)||(0,Le.mkdirSync)(Sr,{recursive:!0});let n={sessionId:e,injectedHashes:[...t.contentHashes],injectedRealPaths:[...t.realPaths],updatedAt:Date.now()};(0,Le.writeFileSync)(Mi(e),JSON.stringify(n,null,2))}function bf(e){let t=Mi(e);(0,Le.existsSync)(t)&&(0,Le.unlinkSync)(t)}function Cf(e){let t=new Map;function n(i){return t.has(i)||t.set(i,Tf(i)),t.get(i)}function o(i){return i?i.startsWith("/")?i:(0,ko.resolve)(e,i):null}function r(i,a){let c=o(i);if(!c)return[];let l=$i(c),u=n(a),d=(0,Fi.homedir)(),f=Ni(l,d,c),m=[];for(let p of f)if(!wf(p.realPath,u.realPaths))try{let g=(0,Li.readFileSync)(p.path,"utf-8"),{metadata:h,body:y}=ji(g),w;if(p.isSingleFile)w="copilot-instructions (always apply)";else{let v=Di(h,c,l);if(!v.applies)continue;w=v.reason??"matched"}let k=_f(y);if(Sf(k,u.contentHashes))continue;let I=l?(0,ko.relative)(l,p.path):p.path;m.push({relativePath:I,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),Ef(a,u)),m}function s(i){if(i.length===0)return"";let a="";for(let c of i)a+=`
|
|
1399
1453
|
|
|
1400
1454
|
[Rule: ${c.relativePath}]
|
|
1401
1455
|
[Match: ${c.matchReason}]
|
|
1402
|
-
${c.content}`;return a}return{processToolExecution:(
|
|
1456
|
+
${c.content}`;return a}return{processToolExecution:(i,a,c)=>{if(!Pi.includes(i.toLowerCase()))return"";let l=r(a,c);return s(l)},getRulesForFile:i=>{let a=o(i);if(!a)return[];let c=$i(a),l=(0,Fi.homedir)(),u=Ni(c,l,a),d=[];for(let f of u)try{let m=(0,Li.readFileSync)(f.path,"utf-8"),{metadata:p,body:g}=ji(m),h;if(f.isSingleFile)h="copilot-instructions (always apply)";else{let w=Di(p,a,c);if(!w.applies)continue;h=w.reason??"matched"}let y=c?(0,ko.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:i=>{t.delete(i),bf(i)},isTrackedTool:i=>Pi.includes(i.toLowerCase())}}var Tr=require("node:fs"),yt=require("node:path");var Fe=require("node:fs"),Of=require("node:path");var Ui=require("node:path"),Rf=require("node:os"),VS=(0,Ui.join)((0,Rf.homedir)(),".olympus"),vr=(0,Ui.join)(VS,"directory-readme"),If="README.md",Wi=["read","write","edit","multiedit"];function Hi(e){return(0,Of.join)(vr,`${e}.json`)}function Pf(e){let t=Hi(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 Af(e,t){(0,Fe.existsSync)(vr)||(0,Fe.mkdirSync)(vr,{recursive:!0});let n={sessionID:e,injectedPaths:Array.from(t),updatedAt:Date.now()};(0,Fe.writeFileSync)(Hi(e),JSON.stringify(n,null,2))}function xf(e){let t=Hi(e);(0,Fe.existsSync)(t)&&(0,Fe.unlinkSync)(t)}var $f=4,YS=5e3;function KS(e,t=YS){if(Math.ceil(e.length/$f)<=t)return{result:e,truncated:!1};let o=t*$f;return{result:e.slice(0,o),truncated:!0}}function Nf(e){let t=new Map;function n(i){return t.has(i)||t.set(i,Pf(i)),t.get(i)}function o(i){return i?i.startsWith("/")?i:(0,yt.resolve)(e,i):null}function r(i){let a=[],c=i;for(;;){let l=(0,yt.join)(c,If);if((0,Tr.existsSync)(l)&&a.push(l),c===e)break;let u=(0,yt.dirname)(c);if(u===c||!u.startsWith(e))break;c=u}return a.reverse()}function s(i,a){let c=o(i);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,Tr.readFileSync)(m,"utf-8"),{result:h,truncated:y}=KS(g),w=y?`
|
|
1403
1457
|
|
|
1404
1458
|
[Note: Content was truncated to save context window space. For full context, please read the file directly: ${m}]`:"";f+=`
|
|
1405
1459
|
|
|
1406
1460
|
[Project README: ${m}]
|
|
1407
|
-
${h}${w}`,u.add(p)}catch{}}return f&&
|
|
1461
|
+
${h}${w}`,u.add(p)}catch{}}return f&&Af(a,u),f}return{processToolExecution:(i,a,c)=>Wi.includes(i.toLowerCase())?s(a,c):"",getReadmesForFile:i=>{let a=o(i);if(!a)return[];let c=(0,yt.dirname)(a);return r(c)},clearSession:i=>{t.delete(i),xf(i)},isTrackedTool:i=>Wi.includes(i.toLowerCase())}}var Df="non-interactive-env",jf={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"},Bi={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
1462
|
option1
|
|
1409
1463
|
option2
|
|
1410
|
-
EOF`,expectAlternative:"Use environment variables or config files instead of expect"}};var
|
|
1464
|
+
EOF`,expectAlternative:"Use environment variables or config files instead of expect"}};var Mf=Bi.banned.filter(e=>!e.includes("(")).map(e=>new RegExp(`\\b${e}\\b`));function JS(e){for(let t=0;t<Mf.length;t++)if(Mf[t].test(e))return Bi.banned[t]}function zS(e){return e===""?"''":/[^a-zA-Z0-9_\-.:\/]/.test(e)?`'${e.replace(/'/g,"'\\''")}'`:e}function QS(e){return`export ${Object.entries(e).map(([n,o])=>`${n}=${zS(o)}`).join(" ")};`}var Gi={name:Df,async beforeCommand(e){let t=JS(e),n=t?`Warning: '${t}' is an interactive command that may hang in non-interactive environments.`:void 0;return/\bgit\b/.test(e)?{command:`${QS(jf)} ${e}`,warning:n}:{command:e,warning:n}}};var Vi=require("child_process");var Lf="olympus-orchestrator",Ff=".olympus/",Uf=["Write","Edit","write","edit"],Wf=`
|
|
1411
1465
|
|
|
1412
1466
|
---
|
|
1413
1467
|
|
|
@@ -1433,7 +1487,7 @@ You should NOT:
|
|
|
1433
1487
|
3. Verify the subagent's work after completion
|
|
1434
1488
|
|
|
1435
1489
|
---
|
|
1436
|
-
`;var
|
|
1490
|
+
`;var Hf=`[SYSTEM REMINDER - QUEST CONTINUATION]
|
|
1437
1491
|
|
|
1438
1492
|
You have an active work plan with incomplete tasks. Continue working.
|
|
1439
1493
|
|
|
@@ -1442,7 +1496,7 @@ RULES:
|
|
|
1442
1496
|
- Mark each checkbox [x] in the plan file when done
|
|
1443
1497
|
- Learnings are automatically captured in .olympus/learning/discoveries.jsonl
|
|
1444
1498
|
- Do not stop until all tasks are complete
|
|
1445
|
-
- If blocked, document the blocker and move to the next task`,
|
|
1499
|
+
- If blocked, document the blocker and move to the next task`,Bf=`**MANDATORY VERIFICATION - SUBAGENTS LIE**
|
|
1446
1500
|
|
|
1447
1501
|
Subagents FREQUENTLY claim completion when:
|
|
1448
1502
|
- Tests are actually FAILING
|
|
@@ -1457,7 +1511,7 @@ Subagents FREQUENTLY claim completion when:
|
|
|
1457
1511
|
3. Check build/typecheck - Must succeed
|
|
1458
1512
|
|
|
1459
1513
|
DO NOT TRUST THE AGENT'S SELF-REPORT.
|
|
1460
|
-
VERIFY EACH CLAIM WITH YOUR OWN TOOL CALLS.`,
|
|
1514
|
+
VERIFY EACH CLAIM WITH YOUR OWN TOOL CALLS.`,Gf=`
|
|
1461
1515
|
|
|
1462
1516
|
[SYSTEM DIRECTIVE - SINGLE TASK ONLY]
|
|
1463
1517
|
|
|
@@ -1480,7 +1534,7 @@ If you were NOT given **exactly ONE atomic task**, you MUST:
|
|
|
1480
1534
|
- Batch delegation = sloppy work = rework = wasted tokens
|
|
1481
1535
|
|
|
1482
1536
|
**REFUSE multi-task requests. DEMAND single-task clarity.**
|
|
1483
|
-
`,
|
|
1537
|
+
`,qf=`
|
|
1484
1538
|
|
|
1485
1539
|
================================================================================
|
|
1486
1540
|
HARD BLOCK: DELEGATION REQUIRED
|
|
@@ -1519,41 +1573,41 @@ This is a HARD BLOCK. The operation will NOT be executed.
|
|
|
1519
1573
|
Delegate to a subagent to proceed.
|
|
1520
1574
|
|
|
1521
1575
|
================================================================================
|
|
1522
|
-
`;var
|
|
1523
|
-
`;(0,Zt.appendFileSync)(r,
|
|
1524
|
-
`).length,
|
|
1525
|
-
`).length;return Math.abs(
|
|
1526
|
-
`).length:0}return 0}function
|
|
1527
|
-
`)){if(!
|
|
1528
|
-
`)){let s
|
|
1576
|
+
`;var wo=".olympus",Er="quest.json",XS=`${wo}/${Er}`,Vf="notepads",ZS=`${wo}/${Vf}`;var Ye=require("fs"),br=require("path");function Yf(e){return(0,br.join)(e,wo,Er)}function Cr(e){let t=Yf(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 Rr(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,s=o.length;return{total:r,completed:s,isComplete:r===0||s===r}}catch{return{total:0,completed:0,isComplete:!0}}}var _o=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}},tP=new _o;var Zt=require("fs"),qi=require("path");function So(e,t){let n=t||process.cwd(),o=(0,qi.join)(n,".olympus","logs"),r=(0,qi.join)(o,"hook-violations.jsonl");try{(0,Zt.existsSync)(o)||(0,Zt.mkdirSync)(o,{recursive:!0});let s=JSON.stringify(e)+`
|
|
1577
|
+
`;(0,Zt.appendFileSync)(r,s,"utf-8")}catch(s){console.error("[Hook Logging] Failed to log violation:",s)}}var Kf=new _o;function Jf(e){return e?e.replace(/\\/g,"/").includes(Ff):!0}function nv(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 ov(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(`
|
|
1578
|
+
`).length,s=o.split(`
|
|
1579
|
+
`).length;return Math.abs(s-r)}if(e==="Write"||e==="write"){let n=t.content??"";return n?n.split(`
|
|
1580
|
+
`).length:0}return 0}function zf(e){return Uf.includes(e)}function rv(e){try{let t=(0,Vi.execSync)("git diff --numstat HEAD",{cwd:e,encoding:"utf-8",timeout:5e3}).trim();if(!t)return[];let n=(0,Vi.execSync)("git status --porcelain",{cwd:e,encoding:"utf-8",timeout:5e3}).trim(),o=new Map;for(let s of n.split(`
|
|
1581
|
+
`)){if(!s)continue;let i=s.substring(0,2).trim(),a=s.substring(3);i==="A"||i==="??"?o.set(a,"added"):i==="D"?o.set(a,"deleted"):o.set(a,"modified")}let r=[];for(let s of t.split(`
|
|
1582
|
+
`)){let i=s.split(" ");if(i.length<3)continue;let[a,c,l]=i,u=a==="-"?0:parseInt(a,10),d=c==="-"?0:parseInt(c,10);r.push({path:l,added:u,removed:d,status:o.get(l)??"modified"})}return r}catch{return[]}}function sv(e){if(e.length===0)return`[FILE CHANGES SUMMARY]
|
|
1529
1583
|
No file changes detected.
|
|
1530
|
-
`;let t=e.filter(
|
|
1531
|
-
`)}function
|
|
1584
|
+
`;let t=e.filter(s=>s.status==="modified"),n=e.filter(s=>s.status==="added"),o=e.filter(s=>s.status==="deleted"),r=["[FILE CHANGES SUMMARY]"];if(t.length>0){r.push("Modified files:");for(let s of t)r.push(` ${s.path} (+${s.added}, -${s.removed})`);r.push("")}if(n.length>0){r.push("Created files:");for(let s of n)r.push(` ${s.path} (+${s.added})`);r.push("")}if(o.length>0){r.push("Deleted files:");for(let s of o)r.push(` ${s.path} (-${s.removed})`);r.push("")}return r.join(`
|
|
1585
|
+
`)}function Qf(e){let t=Bf;return e&&(t+=`
|
|
1532
1586
|
|
|
1533
1587
|
---
|
|
1534
1588
|
|
|
1535
1589
|
**If ANY verification fails, resume the subagent with the fix:**
|
|
1536
|
-
Task tool with resume="${e}", prompt="fix: [describe the specific failure]"`),t}function
|
|
1590
|
+
Task tool with resume="${e}", prompt="fix: [describe the specific failure]"`),t}function iv(e,t,n){let o=t.total-t.completed;return`
|
|
1537
1591
|
---
|
|
1538
1592
|
|
|
1539
1593
|
**State:** Plan: ${e} | ${t.completed}/${t.total} done, ${o} left
|
|
1540
1594
|
|
|
1541
1595
|
---
|
|
1542
1596
|
|
|
1543
|
-
${
|
|
1597
|
+
${Qf(n)}
|
|
1544
1598
|
|
|
1545
|
-
ALL pass? \u2192 commit atomic unit, mark \`[x]\`, next task.`}function
|
|
1599
|
+
ALL pass? \u2192 commit atomic unit, mark \`[x]\`, next task.`}function av(e,t,n){return Hf.replace(/{PLAN_NAME}/g,e)+`
|
|
1546
1600
|
|
|
1547
|
-
[Status: ${n-t}/${n} completed, ${t} remaining]`}function
|
|
1601
|
+
[Status: ${n-t}/${n} completed, ${t} remaining]`}function cv(e){let{toolName:t,toolInput:n,directory:o}=e,r=o||process.cwd();if(!zf(t))return{continue:!0};let s=n?.filePath??n?.path??n?.file;if(!s)return{continue:!0};let i=s.replace(/\\/g,"/");if(Jf(i))return So({timestamp:new Date().toISOString(),filePath:i,toolName:t,wasBlocked:!1,reason:"Allowed: .olympus/ path"},r),{continue:!0};if(nv(i))return So({timestamp:new Date().toISOString(),filePath:i,toolName:t,wasBlocked:!1,reason:"Allowed: Test file"},r),{continue:!0};let a=ov(t,n);return Kf.isVerificationEdit(i,a)?(So({timestamp:new Date().toISOString(),filePath:i,toolName:t,linesChanged:a,wasBlocked:!1,reason:`Allowed: Verification edit (${a} lines on recent task file)`},r),{continue:!0}):(So({timestamp:new Date().toISOString(),filePath:i,toolName:t,linesChanged:a,wasBlocked:!0,reason:"Blocked: Direct source file modification (delegation required)"},r),{continue:!1,message:qf})}function lv(e,t){let{toolName:n,toolInput:o,directory:r,sessionId:s}=e,i=r||process.cwd();if(zf(n)){let a=o?.filePath??o?.path??o?.file;if(a&&!Jf(a))return{continue:!0,modifiedOutput:t+Wf}}if(n==="Task"||n==="task"){if(t.includes("Background task launched")||t.includes("Background task resumed"))return{continue:!0};let c=rv(i),l=c.map(f=>f.path);Kf.recordTaskCompletion({timestamp:Date.now(),filesModified:l,taskId:s||`task-${Date.now()}`});let u=sv(c),d=Cr(i);if(d){let f=Rr(d.active_plan);return{continue:!0,modifiedOutput:`
|
|
1548
1602
|
## SUBAGENT WORK COMPLETED
|
|
1549
1603
|
|
|
1550
1604
|
${u}
|
|
1551
1605
|
<system-reminder>
|
|
1552
|
-
${
|
|
1606
|
+
${iv(d.plan_name,f,s)}
|
|
1553
1607
|
</system-reminder>`}}return{continue:!0,modifiedOutput:t+`
|
|
1554
1608
|
<system-reminder>
|
|
1555
|
-
${
|
|
1556
|
-
</system-reminder>`}}return{continue:!0}}function
|
|
1609
|
+
${Qf(s)}
|
|
1610
|
+
</system-reminder>`}}return{continue:!0}}function uv(e){let t=Cr(e);if(!t)return{shouldContinue:!1};let n=Rr(t.active_plan);if(n.isComplete)return{shouldContinue:!1};let o=n.total-n.completed;return{shouldContinue:!0,message:av(t.plan_name,o,n.total)}}function Ir(e){return{name:Lf,preTool:(t,n)=>cv({toolName:t,toolInput:n,directory:e}),postTool:(t,n,o)=>lv({toolName:t,toolInput:n,directory:e},o),checkContinuation:()=>uv(e),getSingleTaskDirective:()=>Gf}}function Xf(e){if(!e||typeof e!="object")return null;let t=e;return t.file_path||t.filePath||t.path||t.file}function Zf(){_({name:"rulesInjector",event:"PreToolUse",priority:10,matcher:/^(read|edit|write|glob|grep)$/i,handler:e=>{let t=Cf(e.directory||process.cwd()),n=Xf(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=Nf(e.directory||process.cwd()),n=Xf(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(!Gi.beforeCommand)return{continue:!0};let n=await Gi.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=>Ir(e.directory||process.cwd()).preTool(e.toolName,e.toolInput)})}var dv=["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"],pv=`
|
|
1557
1611
|
[EDIT ERROR - IMMEDIATE ACTION REQUIRED]
|
|
1558
1612
|
|
|
1559
1613
|
You made an Edit mistake. STOP and do this NOW:
|
|
@@ -1564,7 +1618,7 @@ You made an Edit mistake. STOP and do this NOW:
|
|
|
1564
1618
|
4. CONTINUE with corrected action based on the real file content
|
|
1565
1619
|
|
|
1566
1620
|
DO NOT attempt another edit until you've read and verified the file state.
|
|
1567
|
-
`;function
|
|
1621
|
+
`;function fv(e){let t=e.toLowerCase();return dv.some(n=>t.includes(n.toLowerCase()))}function em(){return{afterToolExecute:(e,t)=>e.tool.toLowerCase()!=="edit"?t:fv(t.output)?{...t,output:t.output+pv}:t}}var om=E(require("fs"),1),Pr=E(require("path"),1),rm=require("os");var Or=new Set(["given","when","then","arrange","act","assert","when & then","when&then"]),Yi=["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"],Ki=`COMMENT/DOCSTRING DETECTED - IMMEDIATE ACTION REQUIRED
|
|
1568
1622
|
|
|
1569
1623
|
Your recent changes contain comments or docstrings, which triggered this hook.
|
|
1570
1624
|
You need to take immediate action. You must follow the conditions below.
|
|
@@ -1602,13 +1656,13 @@ MANDATORY REQUIREMENT: You must acknowledge this hook message and take one of th
|
|
|
1602
1656
|
Review in the above priority order and take the corresponding action EVERY TIME this appears.
|
|
1603
1657
|
|
|
1604
1658
|
Detected comments/docstrings:
|
|
1605
|
-
`,
|
|
1606
|
-
`;
|
|
1607
|
-
`);o.lastIndex=0;let
|
|
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
|
|
1659
|
+
`,Ji={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},zi={".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 mv(e){return e.text.trim().startsWith("#!")&&e.lineNumber===1?{shouldSkip:!0,reason:"shebang"}:{shouldSkip:!1}}function gv(e){if(e.isDocstring)return{shouldSkip:!1};let t=e.text.toLowerCase().trim();for(let n of Or){if(t.startsWith(`#${n}`)||t.startsWith(`// ${n}`))return{shouldSkip:!0,reason:`BDD keyword: ${n}`};if(t.includes(n)&&t.split(/\s+/).some(r=>Or.has(r.replace(/[^a-z&]/g,""))))return{shouldSkip:!0,reason:"BDD keyword detected"}}return{shouldSkip:!1}}function hv(e){let t=e.text.toLowerCase().trim();for(let n of Yi)if(t.includes(n.toLowerCase()))return{shouldSkip:!0,reason:`directive: ${n}`};return{shouldSkip:!1}}function yv(e){return{shouldSkip:!1}}function kv(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 wv(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 _v=[mv,gv,hv,kv,wv,yv];function Qi(e){return e.filter(t=>{for(let n of _v)if(n(t).shouldSkip)return!1;return!0})}var Sv=process.env.COMMENT_CHECKER_DEBUG==="1",vv=Pr.join((0,rm.tmpdir)(),"comment-checker-debug.log");function en(...e){if(Sv){let t=`[${new Date().toISOString()}] [comment-checker] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
|
|
1660
|
+
`;om.appendFileSync(vv,t)}}function Tv(e){let t=Pr.extname(e).toLowerCase();return zi[t]}function Xi(e,t){let n=Tv(t);if(!n)return en("unsupported language for:",t),[];let o=Ji[n];if(!o)return en("no pattern for language:",n),[];let r=[],s=e.split(`
|
|
1661
|
+
`);o.lastIndex=0;let i;for(;(i=o.exec(e))!==null;){let a=i.index,c=i[0],u=e.substring(0,a).split(`
|
|
1662
|
+
`).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 Ev(e,t){return Xi(e,t)}function tm(e,t,n){let o=Xi(e,t);if(n){let r=Xi(n,t),s=new Set(r.map(i=>i.text));return o.filter(i=>!s.has(i.text))}return o}function bv(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=Ki;for(let[o,r]of t){n+=`
|
|
1609
1663
|
File: ${o}
|
|
1610
|
-
`;for(let
|
|
1611
|
-
`}}return n}function
|
|
1664
|
+
`;for(let s of r){let i=s.isDocstring?"docstring":s.commentType;n+=` Line ${s.lineNumber} (${i}): ${s.text.substring(0,100)}${s.text.length>100?"...":""}
|
|
1665
|
+
`}}return n}function Cv(e,t,n,o,r){let s=[];if(t)s=Ev(t,e);else if(o)s=tm(o,e,n);else if(r&&r.length>0)for(let a of r){let c=tm(a.new_string,e,a.old_string);s.push(...c)}let i=Qi(s);return en(`found ${s.length} comments, ${i.length} flagged after filtering`),i.length===0?{hasComments:!1,count:0,comments:[]}:{hasComments:!0,count:i.length,message:bv(i),comments:i}}var vo=new Map,Rv=6e4;function Iv(){let e=Date.now();for(let[t,n]of vo)e-n.timestamp>Rv&&vo.delete(t)}var nm=!1;function sm(e){return en("createCommentCheckerHook called",{config:e}),nm||(nm=!0,setInterval(Iv,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,s=t.tool_input.old_string??t.tool_input.oldString,i=t.tool_input.new_string??t.tool_input.newString,a=t.tool_input.edits;if(!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}),vo.set(c,{filePath:o,content:r,oldString:s,newString:i,edits:a,tool:n,sessionId:t.session_id,timestamp:Date.now()}),null},postToolUse:t=>{let n=t.tool_name.toLowerCase();if(n!=="write"&&n!=="edit"&&n!=="multiedit")return null;let o,r;for(let[i,a]of vo)if(a.sessionId===t.session_id&&a.tool===n){o=a,r=i;break}if(!o){let i=t.tool_input.file_path??t.tool_input.filePath??t.tool_input.path;if(!i)return null;o={filePath:i,content:t.tool_input.content,oldString:t.tool_input.old_string??t.tool_input.oldString,newString:t.tool_input.new_string??t.tool_input.newString,edits:t.tool_input.edits,tool:n,sessionId:t.session_id,timestamp:Date.now()}}if(r&&vo.delete(r),t.tool_response){let i=t.tool_response.toLowerCase();if(i.includes("error:")||i.includes("failed to")||i.includes("could not")||i.startsWith("error"))return en("skipping due to tool failure in response"),null}let s=Cv(o.filePath,o.content,o.oldString,o.newString,o.edits);return s.hasComments&&s.message?(en("detected comments, returning message"),e?.customPrompt||s.message):null}}}var pm=E(require("fs"),1),fm=E(require("path"),1),mm=require("os");var am=[/(\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],cm=["prompt is too long","is too long","context_length_exceeded","max_tokens","token limit","context length","too many tokens","non-empty content"],Ov=[/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],Pv=/messages\.(\d+)/;function Av(e){return Ov.some(t=>t.test(e))}function Zi(e){for(let t of am){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 im(e){let t=e.match(Pv);if(t)return parseInt(t[1],10)}function xn(e){if(Av(e))return!1;let t=e.toLowerCase();return cm.some(n=>t.includes(n.toLowerCase()))}function Ar(e){if(typeof e=="string"){if(e.toLowerCase().includes("non-empty content"))return{currentTokens:0,maxTokens:0,errorType:"non-empty content",messageIndex:im(e)};if(xn(e)){let l=Zi(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,s=t.message,i=t.error,a=i?.error;if(typeof r=="string"&&n.push(r),typeof s=="string"&&n.push(s),typeof i?.message=="string"&&n.push(i.message),typeof t.body=="string"&&n.push(t.body),typeof t.details=="string"&&n.push(t.details),typeof t.reason=="string"&&n.push(t.reason),typeof t.description=="string"&&n.push(t.description),typeof a?.message=="string"&&n.push(a.message),typeof 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=Zi(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=Zi(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:im(c)}:xn(c)?{currentTokens:0,maxTokens:0,errorType:"token_limit_exceeded_unknown"}:null}function ea(e){return xn(e)}var ta=`CONTEXT WINDOW LIMIT REACHED - IMMEDIATE ACTION REQUIRED
|
|
1612
1666
|
|
|
1613
1667
|
The conversation has exceeded the model's context window limit. To continue working effectively, you must take one of these actions:
|
|
1614
1668
|
|
|
@@ -1633,7 +1687,7 @@ Current Status:
|
|
|
1633
1687
|
- Context limit exceeded
|
|
1634
1688
|
- Further API calls will fail until context is reduced
|
|
1635
1689
|
- Action required before continuing
|
|
1636
|
-
`,
|
|
1690
|
+
`,na="Context window limit reached. Please use /compact to summarize the conversation or start a new session.",oa=`API ERROR: Non-empty content validation failed.
|
|
1637
1691
|
|
|
1638
1692
|
This error typically occurs when:
|
|
1639
1693
|
- A message has empty text content
|
|
@@ -1644,7 +1698,7 @@ Suggested actions:
|
|
|
1644
1698
|
2. If the error persists, start a new session
|
|
1645
1699
|
|
|
1646
1700
|
The system will attempt automatic recovery.
|
|
1647
|
-
`;var
|
|
1701
|
+
`;var ra=`CONTEXT RECOVERY FAILED
|
|
1648
1702
|
|
|
1649
1703
|
All automatic recovery attempts have been exhausted.
|
|
1650
1704
|
Please start a new session to continue.
|
|
@@ -1655,13 +1709,13 @@ Before starting a new session:
|
|
|
1655
1709
|
3. Document the current state of the task
|
|
1656
1710
|
|
|
1657
1711
|
You can copy this conversation summary to continue in a new session.
|
|
1658
|
-
`;var
|
|
1659
|
-
`;
|
|
1712
|
+
`;var sa={maxAttempts:2,initialDelayMs:2e3,backoffFactor:2,maxDelayMs:3e4};var xv=process.env.CONTEXT_LIMIT_RECOVERY_DEBUG==="1",$v=fm.join((0,mm.tmpdir)(),"context-limit-recovery-debug.log");function xr(...e){if(xv){let t=`[${new Date().toISOString()}] [context-limit-recovery] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
|
|
1713
|
+
`;pm.appendFileSync($v,t)}}var $r=new Map,gm=3e5;function lm(e){let t=$r.get(e),n=Date.now();return t&&n-t.lastErrorTime>gm&&(t=void 0),t||(t={retryState:{attempt:0,lastAttemptTime:0},truncateState:{truncateAttempt:0},lastErrorTime:n,errorCount:0},$r.set(e,t)),t}function Nv(){let e=Date.now();for(let[t,n]of $r)e-n.lastErrorTime>gm&&$r.delete(t)}var um=!1;function hm(e){return xr("createContextLimitRecoveryHook called",{config:e}),um||(um=!0,setInterval(Nv,6e4)),{postToolUse:t=>{if(!t.tool_response)return null;let n=Ar(t.tool_response);if(!n&&!ea(t.tool_response))return null;xr("detected token limit error",{tool:t.tool_name,sessionId:t.session_id,parsed:n});let o=lm(t.session_id);o.lastErrorTime=Date.now(),o.errorCount++;let r=dm(n,o,e);return r.message?(xr("injecting recovery message",{errorType:r.errorType,attempt:o.retryState.attempt}),r.message):null},onError:t=>{let n=Ar(t.error);if(!n)return{attempted:!1,success:!1};xr("error notification contains token limit error",{sessionId:t.session_id,parsed:n});let o=lm(t.session_id);o.lastErrorTime=Date.now(),o.errorCount++;let r=dm(n,o,e);return{attempted:!0,success:!!r.message,message:r.message,errorType:r.errorType}}}}function dm(e,t,n){if(n?.customMessage)return{message:n.customMessage,errorType:e?.errorType};if(e?.errorType?.includes("non-empty content"))return{message:oa,errorType:"non-empty content"};if(t.retryState.attempt++,t.retryState.lastAttemptTime=Date.now(),t.retryState.attempt>sa.maxAttempts)return{message:ra,errorType:"recovery_exhausted"};if(n?.detailed!==!1){let o=ta;return e?.currentTokens&&e?.maxTokens&&(o+=`
|
|
1660
1714
|
Token Details:
|
|
1661
1715
|
- Current: ${e.currentTokens.toLocaleString()} tokens
|
|
1662
1716
|
- Maximum: ${e.maxTokens.toLocaleString()} tokens
|
|
1663
1717
|
- Over limit by: ${(e.currentTokens-e.maxTokens).toLocaleString()} tokens
|
|
1664
|
-
`),{message:o,errorType:e?.errorType||"token_limit_exceeded"}}return{message:
|
|
1718
|
+
`),{message:o,errorType:e?.errorType||"token_limit_exceeded"}}return{message:na,errorType:e?.errorType||"token_limit_exceeded"}}var ym=/File content \((\d+) tokens\) exceeds maximum allowed tokens \((\d+)\)/i,Dv=/exceeds maximum allowed tokens/i;function jv(e){let t=e.match(ym);return t?{current:parseInt(t[1],10),max:parseInt(t[2],10)}:null}function Mv(e,t){return e.toLowerCase()==="read"&&(ym.test(t)||Dv.test(t))}function Lv(e,t){return`[SYSTEM RECOVERY - READ TOOL FILE SIZE LIMIT]
|
|
1665
1719
|
|
|
1666
1720
|
${t?`The file contains ${t.current} tokens, exceeding the ${t.max} token limit.`:"The file is too large to read in one operation."}
|
|
1667
1721
|
|
|
@@ -1691,7 +1745,7 @@ ${t?`The file contains ${t.current} tokens, exceeding the ${t.max} token limit.`
|
|
|
1691
1745
|
- Need overview/summary? \u2192 Use multimodal-looker agent
|
|
1692
1746
|
- Need specific section? \u2192 Grep to find it, then Read that portion
|
|
1693
1747
|
|
|
1694
|
-
Proceed with one of these strategies.`.trim()}function
|
|
1748
|
+
Proceed with one of these strategies.`.trim()}function km(){return{postToolUse:e=>{if(!e.tool_response||!Mv(e.tool_name,e.tool_response))return null;let t=e.tool_input?.file_path||"<unknown file>",n=jv(e.tool_response);return Lv(t,n||void 0)}}}var Em=E(require("fs"),1),bm=E(require("path"),1),Cm=require("os");var ia=process.env.ANTHROPIC_1M_CONTEXT==="true"||process.env.VERTEX_ANTHROPIC_1M_CONTEXT==="true"?1e6:2e5,Nr=4,aa=`CONTEXT WINDOW WARNING - APPROACHING LIMIT
|
|
1695
1749
|
|
|
1696
1750
|
Your context usage is getting high. Consider these actions to prevent hitting the limit:
|
|
1697
1751
|
|
|
@@ -1711,7 +1765,7 @@ Your context usage is getting high. Consider these actions to prevent hitting th
|
|
|
1711
1765
|
|
|
1712
1766
|
Current Status: Context usage is high but recoverable.
|
|
1713
1767
|
Action recommended: Use /compact when convenient.
|
|
1714
|
-
`,
|
|
1768
|
+
`,ca=`CRITICAL: CONTEXT WINDOW ALMOST FULL
|
|
1715
1769
|
|
|
1716
1770
|
Your context usage is critically high. Immediate action required:
|
|
1717
1771
|
|
|
@@ -1730,8 +1784,8 @@ Your context usage is critically high. Immediate action required:
|
|
|
1730
1784
|
|
|
1731
1785
|
WARNING: Further messages may fail if context is not reduced.
|
|
1732
1786
|
Action required: Run /compact now.
|
|
1733
|
-
`;var
|
|
1734
|
-
`;
|
|
1787
|
+
`;var Fv=process.env.PREEMPTIVE_COMPACTION_DEBUG==="1",Uv=bm.join((0,Cm.tmpdir)(),"preemptive-compaction-debug.log");function $n(...e){if(Fv){let t=`[${new Date().toISOString()}] [preemptive-compaction] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
|
|
1788
|
+
`;Em.appendFileSync(Uv,t)}}var Dr=new Map;function Wv(){let e=Date.now(),t=1800*1e3;for(let[n,o]of Dr)e-o.lastWarningTime>t&&Dr.delete(n)}var wm=!1;function Rm(e){return Math.ceil(e.length/Nr)}function Hv(e,t){let n=t?.warningThreshold??.85,o=t?.criticalThreshold??.95,r=ia,s=Rm(e),i=s/r,a=i>=n,c=i>=o,l="none";return c?l="compact":a&&(l="warn"),{totalTokens:s,usageRatio:i,isWarning:a,isCritical:c,action:l}}function jr(e){let t=Dr.get(e);return t||(t={lastWarningTime:0,warningCount:0,estimatedTokens:0},Dr.set(e,t)),t}function Bv(e,t){let n=jr(e),o=t?.cooldownMs??6e4,r=t?.maxWarnings??3,s=Date.now();return s-n.lastWarningTime<o?($n("skipping warning - cooldown active",{sessionId:e,elapsed:s-n.lastWarningTime,cooldown:o}),!1):n.warningCount>=r?($n("skipping warning - max reached",{sessionId:e,warningCount:n.warningCount,maxWarnings:r}),!1):!0}function Gv(e){let t=jr(e);t.lastWarningTime=Date.now(),t.warningCount++}function Im(e){return $n("createPreemptiveCompactionHook called",{config:e}),e?.enabled===!1?{postToolUse:()=>null,stop:()=>null}:(wm||(wm=!0,setInterval(Wv,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=Rm(t.tool_response),s=jr(t.session_id);s.estimatedTokens+=r,$n("tracking tool output",{tool:n,responseTokens:r,cumulativeTokens:s.estimatedTokens});let i=Hv("x".repeat(s.estimatedTokens*Nr),e);return!i.isWarning||!Bv(t.session_id,e)?null:(Gv(t.session_id),$n("injecting context warning",{sessionId:t.session_id,usageRatio:i.usageRatio,isCritical:i.isCritical}),e?.customMessage?e.customMessage:i.isCritical?ca:aa)},stop:t=>{let n=jr(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"),Pm=require("path");var la=require("path"),Om=require("os"),qv=(0,la.join)((0,Om.homedir)(),".olympus"),Mr=(0,la.join)(qv,"agent-usage-reminder"),ua=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"]),da=new Set(["task","call_omo_agent","olympus_task"]),pa=`
|
|
1735
1789
|
[Agent Usage Reminder]
|
|
1736
1790
|
|
|
1737
1791
|
You called a search/fetch tool directly without leveraging specialized agents.
|
|
@@ -1755,7 +1809,7 @@ WHY:
|
|
|
1755
1809
|
- Reduces context window usage in main session
|
|
1756
1810
|
|
|
1757
1811
|
ALWAYS prefer: Multiple parallel Task calls > Direct tool calls
|
|
1758
|
-
`;function
|
|
1812
|
+
`;function fa(e){return(0,Pm.join)(Mr,`${e}.json`)}function ma(e){let t=fa(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 Lr(e){(0,Ue.existsSync)(Mr)||(0,Ue.mkdirSync)(Mr,{recursive:!0});let t=fa(e.sessionID);(0,Ue.writeFileSync)(t,JSON.stringify(e,null,2))}function ga(e){let t=fa(e);(0,Ue.existsSync)(t)&&(0,Ue.unlinkSync)(t)}function Vv(e){let t=e||process.cwd();return In(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 Yv(e){if(!e||typeof e!="object")return null;let t=e;return t.file_path||t.filePath||t.path}function Kv(e,t){if(e<3)return null;let n=e>=5?"CRITICAL":"WARNING";return`<conductor-violation severity="${n}">
|
|
1759
1813
|
|
|
1760
1814
|
[${n}: CONDUCTOR MODE VIOLATION - ${t.toUpperCase()} ACTIVE]
|
|
1761
1815
|
|
|
@@ -1781,54 +1835,54 @@ ${e>=5?"**CRITICAL**: Too many direct operations. Your next action MUST be deleg
|
|
|
1781
1835
|
|
|
1782
1836
|
---
|
|
1783
1837
|
|
|
1784
|
-
`}function
|
|
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()}},
|
|
1787
|
-
`)}function
|
|
1838
|
+
`}function Am(){let e=new Map,t=new Map;function n(c){if(!e.has(c)){let u=ma(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(),Lr(l)}function r(c){e.delete(c),ga(c),t.delete(c)}function s(c,l,u){let d=t.get(c)||{consecutiveCount:0,lastToolName:"",lastFilePath:"",sessionId:c};return l.toLowerCase()==="task"?(d.consecutiveCount=0,t.set(c,d),0):(["edit","write","multiedit"].includes(l.toLowerCase())&&(d.consecutiveCount++,d.lastToolName=l,d.lastFilePath=u,t.set(c,d)),d.consecutiveCount)}return{"tool.execute.after":async(c,l)=>{let{tool:u,sessionID:d}=c,f=u.toLowerCase();if(da.has(f)){o(d),s(d,f,"");return}let m=c.properties||{},p=Yv(m),g=s(d,f,p||""),h=Vv();if(h.active){let w=Kv(g,h.mode);if(w){l.output=w+l.output;return}}if(!ua.has(f))return;let y=n(d);y.agentUsed||(l.output+=pa,y.reminderCount++,y.updatedAt=Date.now(),Lr(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 xm(){let e=process.cwd(),t=em();_({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=sm();_({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=hm();_({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=km();_({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 s=Im();_({name:"preemptiveCompaction",event:"PostToolUse",matcher:/^(read|grep|glob|bash|webfetch)$/i,priority:40,handler:async c=>{if(!c.toolName)return{continue:!0};let l=s.postToolUse({tool_name:c.toolName,session_id:c.sessionId||"",tool_input:c.toolInput||{},tool_response:c.toolOutput?String(c.toolOutput):void 0});return l?{continue:!0,message:l}:{continue:!0}}});let i=Am();_({name:"agentUsageReminder",event:"PostToolUse",matcher:/^(read|grep|glob|edit|write)$/i,priority:50,handler:async c=>{if(!c.toolName)return{continue:!0};let l={title:"",output:c.toolOutput?String(c.toolOutput):"",metadata:void 0};await i["tool.execute.after"]({tool:c.toolName,sessionID:c.sessionId||"",callID:""},l);let u=c.toolOutput?String(c.toolOutput):"";return l.output!==u?{continue:!0,message:l.output.substring(u.length)}:{continue:!0}}});let a=Ir(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 Gm=require("node:fs");var G=require("node:fs"),Pe=require("node:path");var Nn=require("node:path"),Fr=require("node:os");function Jv(){return process.env.XDG_DATA_HOME??(0,Nn.join)((0,Fr.homedir)(),".local","share")}function zv(){return(0,Nn.join)(Jv(),"claude-code","storage")}var $m=zv(),To=(0,Nn.join)($m,"message"),Dn=(0,Nn.join)($m,"part"),Mt=new Set(["thinking","redacted_thinking","reasoning"]),Nm=new Set(["step-start","step-finish"]);var We="[user interrupted]",Ur={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 Dm=process.env.SESSION_RECOVERY_DEBUG==="1",jm=(0,Nn.join)((0,Fr.tmpdir)(),"session-recovery-debug.log");function Qv(){let e=Date.now().toString(16),t=Math.random().toString(36).substring(2,10);return`prt_${e}${t}`}function Xv(e){if(!(0,G.existsSync)(To))return"";let t=(0,Pe.join)(To,e);if((0,G.existsSync)(t))return t;for(let n of(0,G.readdirSync)(To)){let o=(0,Pe.join)(To,n,e);if((0,G.existsSync)(o))return o}return""}function kt(e){let t=Xv(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,Pe.join)(t,o),"utf-8");n.push(JSON.parse(r))}catch{continue}return n.sort((o,r)=>{let s=o.time?.created??0,i=r.time?.created??0;return s!==i?s-i:o.id.localeCompare(r.id)})}function it(e){let t=(0,Pe.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,Pe.join)(t,o),"utf-8");n.push(JSON.parse(r))}catch{continue}return n}function Mm(e){return Mt.has(e.type)||Nm.has(e.type)?!1:e.type==="text"?!!e.text?.trim():e.type==="tool"||e.type==="tool_use"||e.type==="tool_result"}function Lm(e){return it(e).some(Mm)}function Eo(e,t,n){let o=(0,Pe.join)(Dn,t);(0,G.existsSync)(o)||(0,G.mkdirSync)(o,{recursive:!0});let r=Qv(),s={id:r,sessionID:e,messageID:t,type:"text",text:n,synthetic:!0};try{return(0,G.writeFileSync)((0,Pe.join)(o,`${r}.json`),JSON.stringify(s,null,2)),!0}catch{return!1}}function ha(e){let t=kt(e),n=[];for(let o of t)Lm(o.id)||n.push(o.id);return n}function Fm(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 s=n[r];if(!Lm(s.id))return s.id}return null}function ya(e){let t=kt(e),n=[];for(let o of t){if(o.role!=="assistant")continue;it(o.id).some(i=>Mt.has(i.type))&&n.push(o.id)}return n}function Um(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.some(a=>Mt.has(a.type)),i=r.some(Mm);s&&!i&&n.push(o.id)}return n}function ka(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].sort((c,l)=>c.id.localeCompare(l.id))[0];Mt.has(i.type)||n.push(o.id)}return n}function Zv(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 s=n[r];if(s.role!=="assistant")continue;let i=it(s.id);for(let a of i)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 wa(e,t){let n=(0,Pe.join)(Dn,t);(0,G.existsSync)(n)||(0,G.mkdirSync)(n,{recursive:!0});let o=Zv(e,t),r="prt_0000000000_thinking",s={id:r,sessionID:e,messageID:t,type:"thinking",thinking:o||"[Continuing from previous reasoning]",synthetic:!0};try{return(0,G.writeFileSync)((0,Pe.join)(n,`${r}.json`),JSON.stringify(s,null,2)),!0}catch{return!1}}function Wm(e){let t=(0,Pe.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,Pe.join)(t,o),s=(0,G.readFileSync)(r,"utf-8"),i=JSON.parse(s);Mt.has(i.type)&&((0,G.unlinkSync)(r),n=!0)}catch{continue}return n}function bo(e,t=We){let n=(0,Pe.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 s=(0,Pe.join)(n,r),i=(0,G.readFileSync)(s,"utf-8"),a=JSON.parse(i);if(a.type==="text"){let c=a;c.text?.trim()||(c.text=t,c.synthetic=!0,(0,G.writeFileSync)(s,JSON.stringify(c,null,2)),o=!0)}}catch{continue}return o}function Hm(e){let t=kt(e),n=[];for(let o of t)it(o.id).some(i=>i.type!=="text"?!1:!i.text?.trim())&&n.push(o.id);return n}function Bm(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 i=[...r].sort((c,l)=>c.id.localeCompare(l.id))[0];return Mt.has(i.type)?null:o.id}function ye(...e){if(Dm){let t=`[${new Date().toISOString()}] [session-recovery] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
|
|
1839
|
+
`;(0,Gm.appendFileSync)(jm,t)}}function qm(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 Vm(e){let n=qm(e).match(/messages\.(\d+)/);return n?parseInt(n[1],10):null}function Ym(e){let t=qm(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 eT(e){return Ym(e)!==null}function tT(e){return e.filter(t=>t.type==="tool_use"&&!!t.id).map(t=>t.id)}async function nT(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(s=>({type:s.type==="tool"?"tool_use":s.type,id:"callID"in s?s.callID:s.id,name:"tool"in s?s.tool:void 0,input:"state"in s?s.state?.input:void 0})));let o=tT(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 oT(e,t,n){ye("recoverThinkingBlockOrder",{sessionID:e});let o=Vm(n);if(o!==null){let i=Bm(e,o);if(i)return ye("Found target message by index",{targetIndex:o,targetMessageID:i}),wa(e,i)}let r=ka(e);if(r.length===0)return ye("No orphan thinking messages found"),!1;ye("Found orphan thinking messages",r);let s=!1;for(let i of r)wa(e,i)&&(s=!0);return s}async function rT(e,t){ye("recoverThinkingDisabledViolation",{sessionID:e});let n=ya(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)Wm(r)&&(o=!0);return o}async function sT(e,t,n){ye("recoverEmptyContentMessage",{sessionID:e});let o=Vm(n),r=t.info?.id,s=!1,i=Hm(e);for(let l of i)bo(l,We)&&(s=!0);let a=Um(e);for(let l of a)Eo(e,l,We)&&(s=!0);if(o!==null){let l=Fm(e,o);if(l&&(bo(l,We)||Eo(e,l,We)))return!0}if(r&&(bo(r,We)||Eo(e,r,We)))return!0;let c=ha(e);for(let l of c)bo(l,We)&&(s=!0),Eo(e,l,We)&&(s=!0);return s}async function iT(e,t,n,o){ye("handleSessionRecovery",{sessionID:e,error:t});let r=Ym(t);if(!r)return ye("Not a recoverable error"),{attempted:!1,success:!1};ye("Detected recoverable error type",r);try{let s=!1,i=n||{info:{},parts:[]};switch(r){case"tool_result_missing":s=await nT(e,i);break;case"thinking_block_order":s=await oT(e,i,t);break;case"thinking_disabled_violation":s=await rT(e,i);break;case"empty_content":s=await sT(e,i,t);break}ye("Recovery result",{errorType:r,success:s});let a=o?.customMessages?.[r]||Ur[r]?.message||`Session recovery attempted for ${r}`;return{attempted:!0,success:s,message:s?a:void 0,errorType:r}}catch(s){return ye("Recovery failed with error",s),{attempted:!0,success:!1,errorType:r}}}function Km(e){return ye("createSessionRecoveryHook",{config:e}),{onError:async t=>iT(t.session_id,t.error,t.message,e),isRecoverable:t=>eT(t),getRecoveryMessage:t=>{if(t)return e?.customMessages?.[t]||Ur[t]?.message}}}function Jm(){let e=Km();_({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"),Wr=require("path"),zm=require("os");var Co=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 s=this.config?.defaultConcurrency;return s!==void 0?s===0?1/0:s:5}async acquire(t){let n=this.getConcurrencyLimit(t);if(n===1/0)return;let o=this.counts.get(t)??0;if(o<n){this.counts.set(t,o+1);return}return new Promise(r=>{let s=this.queues.get(t)??[];s.push(r),this.queues.set(t,s)})}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 aT=1800*1e3,jn=(0,Wr.join)((0,zm.homedir)(),".claude",".olympus","background-tasks"),Hr=class{tasks=new Map;notifications=new Map;concurrencyManager;config;pruneInterval;constructor(t){this.config=t??{},this.concurrencyManager=new Co(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,Wr.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,Wr.join)(jn,o),s=(0,He.readFileSync)(r,"utf-8"),i=JSON.parse(s);i.startedAt=new Date(i.startedAt),i.completedAt&&(i.completedAt=new Date(i.completedAt)),i.progress?.lastUpdate&&(i.progress.lastUpdate=new Date(i.progress.lastUpdate)),i.progress?.lastMessageAt&&(i.progress.lastMessageAt=new Date(i.progress.lastMessageAt)),this.tasks.set(i.id,i)}catch{}}catch{}}startPruning(){this.pruneInterval||(this.pruneInterval=setInterval(()=>{this.pruneStaleTasksAndNotifications()},6e4),this.pruneInterval.unref&&this.pruneInterval.unref())}stopPruning(){this.pruneInterval&&(clearInterval(this.pruneInterval),this.pruneInterval=void 0)}pruneStaleTasksAndNotifications(){let t=Date.now(),n=this.config.taskTimeoutMs??aT;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 s=r.filter(i=>t-i.startedAt.getTime()<=n);s.length===0?this.notifications.delete(o):s.length!==r.length&&this.notifications.set(o,s)}}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 s=this.generateTaskId(),i=`ses_${this.generateTaskId()}`,a={id:s,sessionId:i,parentSessionId:t.parentSessionId,description:t.description,prompt:t.prompt,agent:t.agent,status:"running",startedAt:new Date,progress:{toolCalls:0,lastUpdate:new Date},concurrencyKey:n};return this.tasks.set(s,a),this.persistTask(a),a}async resume(t){let n=this.findBySession(t.sessionId);if(!n)throw new Error(`Task not found for session: ${t.sessionId}`);return n.status="running",n.completedAt=void 0,n.error=void 0,n.parentSessionId=t.parentSessionId,n.progress||(n.progress={toolCalls:0,lastUpdate:new Date}),n.progress.lastUpdate=new Date,this.persistTask(n),n}getTask(t){return this.tasks.get(t)}findBySession(t){for(let n of this.tasks.values())if(n.sessionId===t)return n}getTasksByParentSession(t){let n=[];for(let 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 s=this.tasks.get(t);s&&(s.status=n,o&&(s.result=o),r&&(s.error=r),(n==="completed"||n==="error"||n==="cancelled")&&(s.completedAt=new Date,s.concurrencyKey&&this.concurrencyManager.release(s.concurrencyKey),this.markForNotification(s)),this.persistTask(s))}updateTaskProgress(t,n){let 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(s=>s.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),s=Math.floor(r/60),i=Math.floor(s/60);return i>0?`${i}h ${s%60}m ${r%60}s`:s>0?`${s}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 s=this.formatDuration(r.startedAt,r.completedAt),i=r.status.toUpperCase(),a=r.progress?` (${r.progress.toolCalls} tools)`:"";o.push(` [${i}] ${r.description} - ${s}${a}`),r.error&&o.push(` Error: ${r.error}`)}return o.join(`
|
|
1840
|
+
`)}cleanup(){this.stopPruning(),this.tasks.clear(),this.notifications.clear()}},_a;function Sa(e){return _a||(_a=new Hr(e)),_a}function cT(e){let t=e.status.toUpperCase(),n=lT(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 s=e.result.substring(0,200),i=e.result.length>200?"...":"";r.push(` Result: ${s}${i}`)}return e.error&&r.push(` Error: ${e.error}`),r.join(`
|
|
1841
|
+
`)}function lT(e,t){let n=(t??new Date).getTime()-e.getTime(),o=Math.floor(n/1e3),r=Math.floor(o/60),s=Math.floor(r/60);return s>0?`${s}h ${r%60}m ${o%60}s`:r>0?`${r}m ${o%60}s`:`${o}s`}function uT(e){if(e.length===0)return"";let t=e.length===1?`
|
|
1788
1842
|
[BACKGROUND TASK COMPLETED]
|
|
1789
1843
|
`:`
|
|
1790
1844
|
[${e.length} BACKGROUND TASKS COMPLETED]
|
|
1791
|
-
`,n=e.map(o=>
|
|
1845
|
+
`,n=e.map(o=>cT(o)).join(`
|
|
1792
1846
|
|
|
1793
1847
|
`);return`${t}
|
|
1794
1848
|
${n}
|
|
1795
|
-
`}function
|
|
1849
|
+
`}function dT(e,t,n){let o=t.getPendingNotifications(e);if(o.length===0)return{hasNotifications:!1,tasks:[]};let s=(n?.formatNotification??uT)(o);return{hasNotifications:!0,tasks:o,message:s}}function Qm(e,t){let n=e.sessionId;if(!n)return{continue:!0};let o=Sa(),r=dT(n,o,t);return r.hasNotifications?((t?.autoClear??!0)&&o.clearNotifications(n),{continue:!0,message:r.message,notificationCount:r.tasks.length}):{continue:!0}}function Xm(){_({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 Qm(t);return{continue:n.continue,hookSpecificOutput:n.message?{hookEventName:"Notification",additionalContext:n.message}:void 0}}})}var Ta=null,va=!1;async function pT(){if(!va)try{let{encode:e}=await import("gpt-tokenizer");Ta=e,va=!0}catch{va=!0}}function fT(e){return Math.ceil(e.length/4)}async function tn(e){if(!e||e.length===0)return 0;await pT();try{if(Ta)return Ta(e).length}catch{}return fT(e)}async function Zm(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 Ea=[{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 eg(e,t,n,o=Ea){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 s=e/1e6*r.input_per_million,i=t/1e6*r.output_per_million;return{inputCost:s,outputCost:i,totalCost:s+i,pricingVersion:r.effective_date}}Ae();fe();var Mn=E(require("fs"),1),Br=E(require("path"),1),ig=E(require("os"),1),ag=process.env.OLYMPUS_DEBUG_HOOKS==="1",og=Br.join(ig.homedir(),".claude","olympus","learning","hooks-debug.log");function b(e,t,n){if(ag)try{let r=`[${new Date().toISOString()}] [${e}] ${t}`;n!==void 0&&(typeof n=="object"?r+=`
|
|
1796
1850
|
${JSON.stringify(n,null,2)}`:r+=` ${n}`),r+=`
|
|
1797
|
-
`;let
|
|
1851
|
+
`;let s=Br.dirname(og);Mn.existsSync(s)||Mn.mkdirSync(s,{recursive:!0}),Mn.appendFileSync(og,r,"utf8")}catch(o){console.error("[Olympus Debug] Failed to write debug log:",o)}}function ba(e,t){ag&&b(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 gT(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 rg(e){if(e.message?.model){let{providerId:t,modelId:n}=e.message.model;if(t&&n)return`${t}/${n}`;if(n)return n}}function sg(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 cg(){_({name:"learningCapturePrompt",event:"UserPromptSubmit",priority:110,handler:async e=>{b("learningCapturePrompt","Hook fired"),ba("learningCapturePrompt",e);try{if(!e.directory)return b("learningCapturePrompt","No directory in context - skipping"),{continue:!0};b("learningCapturePrompt","Extracting prompt text");let t=gT(e);if(!t)return b("learningCapturePrompt","No prompt text extracted - skipping"),{continue:!0};b("learningCapturePrompt",`Prompt text extracted (${t.length} chars)`),b("learningCapturePrompt","Estimating input tokens");let n=await tn(t);b("learningCapturePrompt",`Estimated tokens: ${n}`),b("learningCapturePrompt","Loading session state",{directory:e.directory,sessionId:e.sessionId});let o=V(e.directory,e.sessionId);b("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}),sg(o),b("learningCapturePrompt","Token budget ensured");let r=rg(e);if(b("learningCapturePrompt",`Model identifier: ${r||"none"}`),r&&o.token_budget&&(o.token_budget.current_model=r,b("learningCapturePrompt",`Model set in token budget: ${r}`)),o.token_budget){let s=o.token_budget.input_tokens,i=o.token_budget.current_usage;o.token_budget.input_tokens+=n,o.token_budget.current_usage+=n,b("learningCapturePrompt","Tokens accumulated",{addedTokens:n,inputTokens:{before:s,after:o.token_budget.input_tokens},currentUsage:{before:i,after:o.token_budget.current_usage}}),b("learningCapturePrompt","Saving session state"),X(e.directory,o),b("learningCapturePrompt","Session state saved successfully")}else b("learningCapturePrompt","WARNING: No token budget after ensure - this should not happen")}catch(t){b("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 b("learningCapturePrompt","Hook completed"),{continue:!0}}}),_({name:"learningCaptureTool",event:"PostToolUse",priority:70,handler:async e=>{b("learningCaptureTool","Hook fired"),ba("learningCaptureTool",e);try{if(!e.directory||!e.toolName)return b("learningCaptureTool","Missing directory or toolName - skipping",{hasDirectory:!!e.directory,hasToolName:!!e.toolName}),{continue:!0};b("learningCaptureTool",`Processing tool: ${e.toolName}`),b("learningCaptureTool","Estimating output tokens from tool result");let t=e.toolOutput?await Zm(e.toolOutput):0;b("learningCaptureTool",`Estimated output tokens: ${t}`),b("learningCaptureTool","Loading session state",{directory:e.directory,sessionId:e.sessionId});let n=V(e.directory,e.sessionId);b("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}),sg(n),b("learningCaptureTool","Token budget ensured");let o=rg(e);if(b("learningCaptureTool",`Model identifier: ${o||"none"}`),o&&n.token_budget&&(n.token_budget.current_model=o,b("learningCaptureTool",`Model set in token budget: ${o}`)),n.token_budget){let r=n.token_budget.output_tokens,s=n.token_budget.current_usage;n.token_budget.output_tokens+=t,n.token_budget.current_usage+=t,b("learningCaptureTool","Tokens accumulated",{addedTokens:t,outputTokens:{before:r,after:n.token_budget.output_tokens},currentUsage:{before:s,after:n.token_budget.current_usage}}),b("learningCaptureTool","Saving session state"),X(e.directory,n),b("learningCaptureTool","Session state saved successfully")}else b("learningCaptureTool","WARNING: No token budget after ensure - this should not happen")}catch(t){b("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 b("learningCaptureTool","Hook completed"),{continue:!0}}}),_({name:"learningCaptureStop",event:"Stop",priority:90,handler:async e=>{b("learningCaptureStop","Hook fired"),ba("learningCaptureStop",e);try{if(!e.directory)return b("learningCaptureStop","No directory in context - skipping"),{continue:!0};b("learningCaptureStop","Loading session state",{directory:e.directory,sessionId:e.sessionId});let t=V(e.directory,e.sessionId);if(b("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 b("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(b("learningCaptureStop","Token totals",{totalTokens:n,inputTokens:o,outputTokens:r}),n===0)return b("learningCaptureStop","No token usage recorded - skipping feedback entry creation"),{continue:!0};let s=t.token_budget.current_model||"unknown";b("learningCaptureStop",`Using model identifier: ${s}`),b("learningCaptureStop","Token usage object created",{input_tokens:o,output_tokens:r,total_tokens:n,estimated:!0,model:s}),b("learningCaptureStop","Calculating cost estimate");let a={input_cost:0,output_cost:0,total_cost:0,pricing_version:"2025-01-01"};try{let l=eg(o,r,s);a.input_cost=l.inputCost,a.output_cost=l.outputCost,a.total_cost=l.totalCost,a.pricing_version=l.pricingVersion,b("learningCaptureStop","Cost calculated successfully",{inputCost:l.inputCost,outputCost:l.outputCost,totalCost:l.totalCost})}catch(l){b("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:s,outcome:"success"};b("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{Oc(c),b("learningCaptureStop","Session summary saved successfully")}catch(l){b("learningCaptureStop","Failed to save session summary (non-critical)",{error:l instanceof Error?l.message:String(l)})}try{let{formatSessionSummaryLine:l}=await Promise.resolve().then(()=>(ng(),tg)),u=l(c);console.error(u)}catch{}b("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,b("learningCaptureStop","Saving reset session state"),X(e.directory,t),b("learningCaptureStop","Session state saved successfully")}catch(t){b("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 b("learningCaptureStop","Hook completed"),{continue:!0}}})}Ae();function lg(){_({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&&Lc(t,n),Uc(t)){let o=t.token_budget,r=(o.current_usage/1e3).toFixed(1),s=(o.session_baseline/1e3).toFixed(0),i=(o.current_usage/o.session_baseline).toFixed(2);return Fc(t),X(e.directory,t),{continue:!0,message:`[TOKEN AWARENESS] Session at ${r}k tokens (${i}x baseline of ${s}k).
|
|
1798
1852
|
This is informational - continue if task requires it.
|
|
1799
|
-
Consider: delegate to subagent, break into smaller tasks.`}}return
|
|
1853
|
+
Consider: delegate to subagent, break into smaller tasks.`}}return X(e.directory,t),{continue:!0}}catch(t){return console.error("[Olympus Learning] Budget warning error:",t),{continue:!0}}}})}Ae();we();z();er();pt();var Ln=E(require("fs"),1),Ro=E(require("path"),1),yg=E(require("os"),1),ST=process.env.OLYMPUS_DEBUG_HOOKS==="1",hg=Ro.join(yg.homedir(),".claude","olympus","learning","hooks-debug.log");function L(e,t,n){if(ST)try{let r=`[${new Date().toISOString()}] [${e}] ${t}`;n!==void 0&&(typeof n=="object"?r+=`
|
|
1800
1854
|
${JSON.stringify(n,null,2)}`:r+=` ${n}`),r+=`
|
|
1801
|
-
`;let
|
|
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
|
|
1803
|
-
`).filter(
|
|
1804
|
-
`).substring(0,500),a=[e.reviewer?`Issues found by ${e.reviewer}:`:"Issues:",
|
|
1805
|
-
`);return{session_id:e.session_id,project_path:n,category:"planning_insight",summary:
|
|
1855
|
+
`;let s=Ro.dirname(hg);Ln.existsSync(s)||Ln.mkdirSync(s,{recursive:!0}),Ln.appendFileSync(hg,r,"utf8")}catch(o){console.error("[Olympus Debug] Failed to write debug log:",o)}}async function vT(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 ne(t);if(r.length===0)return null;let s=await T(t,r[0]);return s?s.active_code_plan_path?{boltId:s.active_code_plan_path,workflowId:s.workflow_id}:o&&n?{boltId:`BOLT-${o[1].padStart(3,"0")}`,workflowId:s.workflow_id}:null:null}catch(n){return L("agentTracking","Error detecting BOLT execution",{error:n instanceof Error?n.message:String(n)}),null}}function kg(){_({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 s=V(e.directory,e.sessionId);L("agentTracking","Session state loaded",{sessionId:s.session_id,hasPendingCompletion:!!s.pending_completion});try{let{getRoutingRecommendation:a}=await Promise.resolve().then(()=>(gg(),mg));t=a(o,r),t&&L("agentTracking","Routing recommendation generated",{recommendation:t})}catch{}let i=await vT(r,e.directory);if(L("agentTracking","BOLT detection result",{isBoltExecution:!!i,boltId:i?.boltId,workflowId:i?.workflowId}),L("agentTracking","Marking completion claim",{agent:o,taskLength:r.length,hasBoltMetadata:!!i}),Dc(s,r,o),i&&s.pending_completion){s.pending_completion.bolt_id=i.boltId,s.pending_completion.workflow_id=i.workflowId,L("agentTracking","BOLT metadata added to pending_completion",{bolt_id:i.boltId,workflow_id:i.workflowId});try{let a=await ne(e.directory),c=null;for(let l of a){let u=await T(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=Ro.join(e.directory,"aidlc-docs",c,"manifest.json"),u=D(l);if(u){let d=u.artifacts.find(f=>f.id===i.boltId);d&&(d.executedBy=o,F(l,u),L("agentTracking","Set executedBy on BOLT artifact",{boltId:i.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:s.pending_completion?.claimed_at,agentUsed:s.pending_completion?.agent_used,bolt_id:s.pending_completion?.bolt_id,workflow_id:s.pending_completion?.workflow_id}),s.token_budget&&(s.token_budget.agents_used||(s.token_budget.agents_used=[]),s.token_budget.agents_used.includes(o)||s.token_budget.agents_used.push(o),L("agentTracking","Agents accumulated",{agents_used:s.token_budget.agents_used})),L("agentTracking","Saving session state"),X(e.directory,s),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:s}=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}),fd({boltId:n,agentName:r,success:!0,sessionId:e.sessionId,projectPath:e.directory,taskDescription:s}),L("agentTrackingBoltCompletion","BOLT execution recorded successfully");try{let i={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(i,a);ie(c),L("agentTrackingBoltCompletion","BOLT completion discovery recorded",{boltId:n,discoveryId:c.id})}catch(i){console.error("[Olympus Agent Tracking] Failed to capture BOLT completion discovery:",i),L("agentTrackingBoltCompletion","Failed to capture BOLT completion discovery",{error:i instanceof Error?i.message:String(i)})}}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 Ra=require("path"),wg=require("os");fe();var TT={enabled:!0,minConfidence:.6,maxPerSession:5,maxPerDay:20,deduplicationWindowDays:7};function Fn(e){let t=(0,Ra.join)((0,wg.homedir)(),".claude","olympus","config.json"),n=me(t,{}),o={};if(e){let s=(0,Ra.join)(e,".olympus","config.json");o=me(s,{})}let r={...TT,...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 Gr=require("fs"),_g=require("path");fe();var ET={praise:.85,problem_solved:.7,topic_change:.6},bT=[{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 Sg(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=PT(n),s=AT(n),i=CT(n,o),a=ET[t]??.6;return{session_id:e.session_id,category:i,summary:r,details:s,agent_name:o,task_context:n.substring(0,200),confidence:a,scope:"project"}}function vg(e,t,n=7){let o=xT(t,n);if(o.length===0)return!1;let r=e.summary||"",s=e.details||"";for(let i of o)if(i.details===s&&s.length>0||r.length>0&&i.summary&&RT(r,i.summary)>.7)return!0;return!1}function CT(e,t){for(let{pattern:n,category:o}of bT)if(n.test(e))return o;return"technical_insight"}function RT(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 s=new Set([...o].filter(a=>r.has(a))),i=new Set([...o,...r]);return i.size>0?s.size/i.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 IT(e,t=100){if(!e||e.length===0)return"";let n=e.match(/^[^.]+\./),o=e.indexOf(`
|
|
1856
|
+
`),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 s=e.substring(0,r).trim();return s.length<e.length&&!s.endsWith(".")?Un(s,t):s}function OT(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 PT(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=OT(e),o=IT(n,150);for(let[s,i]of Object.entries(t)){let a=new RegExp(`^${s}\\b`,"i");if(a.test(o)){let c=o.replace(a,i);return Un(c.trim(),100)}}let r=n.match(/^In the .+? project,\s*(.+)/i);if(r){let s=r[1].trim();if(s.toLowerCase().startsWith("i need to")){let i=s.replace(/^i need to\s+/i,"");return Un(i.charAt(0).toUpperCase()+i.slice(1),100)}return Un(s,100)}return Un(o,100)}function AT(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(i=>i.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 xT(e,t){let n=Xe(e),o=(0,_g.join)(n,"discoveries.jsonl");if(!(0,Gr.existsSync)(o))return[];try{let r=(0,Gr.readFileSync)(o,"utf-8"),s=new Date(Date.now()-t*24*60*60*1e3);return r.split(`
|
|
1857
|
+
`).filter(i=>i.trim()).map(i=>{try{return JSON.parse(i)}catch{return null}}).filter(i=>i?new Date(i.timestamp)>=s:!1)}catch{return[]}}pt();function Tg(){_({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(Hc(n,t))return{continue:!0};if(!Mo(n))return{continue:!0};let o=$T(n);if(!o)return{continue:!0};let r=Sg(n,o);if(!r)return{continue:!0};if((r.confidence||0)<t.minConfidence)return{continue:!0};if(vg(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"}),Wc(n),X(e.directory,n)}catch(t){console.error("[Olympus Discovery Capture] Error:",t)}return{continue:!0}}})}function $T(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&&NT(n.prompt,e.pending_completion.task_description)<.2?"topic_change":null}function NT(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 s=new Set([...o].filter(a=>r.has(a))),i=new Set([...o,...r]);return i.size>0?s.size/i.size:0}Ae();var Wn=require("fs"),Cg=require("path"),Eg=new Map;function Rg(e,t,n){try{if(!(0,Wn.existsSync)(t))return null;let o=(0,Cg.relative)(e,t),r=(0,Wn.readFileSync)(t,"utf-8"),i=(0,Wn.statSync)(t).mtimeMs,a=Eg.get(t),c=a===void 0;if(Eg.set(t,i),!c&&a===i)return null;let l=DT(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=MT(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 Ig(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)),i=["CRITICAL","REVISE","REJECT","MAJOR ISSUE","MISSING","INCOMPLETE"].some(c=>n.includes(c)),a=jT(t);return r&&!i?{passed:!0,issues:a}:i?{passed:!1,issues:a.length>0?a:["Plan requires revision"]}:{passed:!0,issues:a}}function Ia(e,t,n){let o=e.plan_path.split("/").pop()||e.plan_path,r=t.length,s=e.event_type==="plan_review_failed"?`Plan '${o}' failed review: ${r} issue${r!==1?"s":""}`:`Plan '${o}' failed: ${r} issue${r!==1?"s":""}`,i=t.map(c=>`- ${c}`).join(`
|
|
1858
|
+
`).substring(0,500),a=[e.reviewer?`Issues found by ${e.reviewer}:`:"Issues:",i].join(`
|
|
1859
|
+
`);return{session_id:e.session_id,project_path:n,category:"planning_insight",summary:s,details:a,agent_name:"prometheus",task_context:`Plan lifecycle: ${e.event_type}`,files_involved:[e.plan_path],confidence:.9,scope:"project"}}function Og(e){if(e.length===0)return"";let t=["<plan-learnings>","## Planning Insights (from previous sessions)",""],n=[],o=[];for(let s of e.slice(0,5))s.summary.includes("failed")?n.push(`- ${s.summary}`):o.push(`- ${s.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
1860
|
`);return r.length>1200?r.substring(0,1200)+`
|
|
1807
|
-
</plan-learnings>`:r}function
|
|
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
|
|
1861
|
+
</plan-learnings>`:r}function DT(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 jT(e){let t=[],n=e.split(`
|
|
1862
|
+
`);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 bg=new Map;function MT(e){let n=(bg.get(e)||0)+1;return bg.set(e,n),n}pt();pt();z();we();ai();var Pg=E(require("path"),1);function Ag(){_({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 s=Rg(e.directory,o,e.sessionId);if(!s)return{continue:!0};if(s.event_type==="plan_revised"&&s.revision_count&&s.revision_count>=2){let i=Ia(s,[`Plan revised ${s.revision_count} times - may indicate unclear requirements`],e.directory);i.summary&&i.details&&ie({...i,project_path:e.directory,session_id:e.sessionId,category:i.category||"planning_insight",summary:i.summary,details:i.details,agent_name:i.agent_name||"prometheus",confidence:i.confidence||.7,scope:"project"})}}catch(t){console.error("[Olympus Plan Lifecycle] Error in plan file monitor:",t)}return{continue:!0}}}),_({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,s=typeof r=="string"?r:JSON.stringify(r||""),i=Ig(s);if(!i.passed&&i.issues.length>0){if(!i.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 ${i.issues.length} issues`,failure_reasons:i.issues,reviewer:"momus",session_id:e.sessionId,timestamp:new Date().toISOString()},m=Ia(f,i.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 i=V(e.directory,e.sessionId);i.pending_completion||(i.pending_completion={claimed_at:new Date().toISOString(),task_description:"plan_completion_verification",agent_used:"complete-plan"},X(e.directory,i))}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=ar(e.directory,20).filter(i=>i.category==="planning_insight");if(r.length===0)return{continue:!0};let s=Og(r.slice(0,5));if(s)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:s}}}catch(t){console.error("[Olympus Plan Lifecycle] Error in Prometheus learnings injection:",t)}return{continue:!0}}}),_({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 ne(t),o=null,r=null;for(let u of n){let d=await T(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 s=Pg.join(t,"aidlc-docs",o,"manifest.json"),i=D(s);if(!i)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();i.gate_audit.push({phase:c,timestamp:u,action:"approved",actor:"trust",reason:`Phase transition: ${l} -> ${c}`});let d=l;i.phases[d]&&(i.phases[d].status="complete",i.phases[d].completed_at=u),i.phases[c]&&i.phases[c].status==="not_started"&&(i.phases[c].status="in_progress",i.phases[c].started_at=u),F(s,i),ii(t,o,r),(r.status==="complete"||r.current_stage==="complete")&&(i.phases.operations.status="complete",i.phases.operations.completed_at=u,F(s,i)),a.last_tracked_phase=c,X(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
1863
|
\u2192 Generating deployment artifacts...`),{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`<phase-transition>
|
|
1810
1864
|
${g}
|
|
1811
|
-
</phase-transition>`}}}if(l||(a.last_tracked_phase=c,
|
|
1865
|
+
</phase-transition>`}}}if(l||(a.last_tracked_phase=c,X(t,a)),r.status==="complete"&&i.phases.operations.status!=="complete"){let u=new Date().toISOString();return i.phases.operations.status="complete",i.phases.operations.completed_at=u,F(s,i),ii(t,o,r),{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`<phase-transition>
|
|
1812
1866
|
\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}}})}
|
|
1867
|
+
</phase-transition>`}}}}catch(t){console.error("[Olympus Plan Lifecycle] Error in phase transition tracker:",t)}return{continue:!0}}})}we();z();$t();Qo();function Oa(e,t){return t===3||e<=1?"blocking":"auto-advance"}function Pa(e,t){return t===3||e<=1?"blocking":e===2?"summary-review":"notification-only"}function Aa(e,t){let n=e.links.find(o=>o.target_id===t&&o.link_type==="derives");return n?n.source_id:null}function xg(e,t){let n=e.artifacts.filter(r=>r.stage==="unit"),o=e.risk_tier?.tier??null;return n.map(r=>{let s=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),i=s.length>0?`
|
|
1814
1868
|
|
|
1815
1869
|
Child BOLTs:
|
|
1816
|
-
${
|
|
1870
|
+
${s.map(c=>` - ${c.id} (${c.path})`).join(`
|
|
1817
1871
|
`)}`:`
|
|
1818
1872
|
|
|
1819
1873
|
No child BOLTs found.`,a=`UNIT Artifact: ${r.path}
|
|
1820
|
-
Contract Status: ${r.contract_status}${
|
|
1874
|
+
Contract Status: ${r.contract_status}${i}`;return o===3&&(a+=`
|
|
1821
1875
|
|
|
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:
|
|
1876
|
+
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:Oa(t,o)}})}function $g(e,t,n,o){let r=e.artifacts.find(c=>c.id===t);if(!r)throw new Error(`BOLT artifact not found: ${t}`);let s=Pa(n,o),i="";n<=1?i=`
|
|
1823
1877
|
|
|
1824
|
-
Review Instructions: Full code review required.`:n===2?
|
|
1878
|
+
Review Instructions: Full code review required.`:n===2?i=`
|
|
1825
1879
|
|
|
1826
|
-
Review Instructions: Summary review - verify major changes only.`:
|
|
1880
|
+
Review Instructions: Summary review - verify major changes only.`:i=`
|
|
1827
1881
|
|
|
1828
1882
|
Review Instructions: Notification only - AI proceeds automatically.`;let a=`BOLT Spec: ${r.path}
|
|
1829
|
-
Contract Status: ${r.contract_status}${
|
|
1883
|
+
Contract Status: ${r.contract_status}${i}`;return o===3&&(a+=`
|
|
1830
1884
|
|
|
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:
|
|
1885
|
+
NOTE: Risk Tier 3 - Developer review mandatory for every BOLT.`),{gateNumber:4,gateType:"code-review",artifactId:t,summary:`Code review for ${t}`,reviewContent:a,trustLevel:n,trustBehavior:s}}function Ng(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,s=e.gate_audit.filter(c=>c.action==="rejected").length,i=o.length>0?o.map(c=>` - ${c.id}: ${c.contract_status}`).join(`
|
|
1832
1886
|
`):" No BOLTs found.",a=`Release Approval Review
|
|
1833
1887
|
|
|
1834
1888
|
Feature: ${e.feature_name}
|
|
@@ -1836,16 +1890,16 @@ Total Artifacts: ${n}
|
|
|
1836
1890
|
|
|
1837
1891
|
Gate Audit Summary:
|
|
1838
1892
|
Approvals: ${r}
|
|
1839
|
-
Rejections: ${
|
|
1893
|
+
Rejections: ${s}
|
|
1840
1894
|
|
|
1841
1895
|
BOLT Artifacts:
|
|
1842
|
-
${
|
|
1896
|
+
${i}
|
|
1843
1897
|
|
|
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=
|
|
1898
|
+
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=E(se(),1),qr=require("path");function xa(e,t,n){Lt.ensureDirSync((0,qr.dirname)(e));let o="";Lt.existsSync(e)?o=Lt.readFileSync(e,"utf-8"):o=`# Validation Report: ${t}
|
|
1845
1899
|
|
|
1846
1900
|
`;let r=n.commandsExecuted.length>0?n.commandsExecuted.map(d=>`- \`${d.command}\` -> exit ${d.exitCode} (${d.result})`).join(`
|
|
1847
|
-
`):"- No commands recorded",
|
|
1848
|
-
|-------|------|------|------|`,
|
|
1901
|
+
`):"- No commands recorded",s=`| Suite | Pass | Fail | Skip |
|
|
1902
|
+
|-------|------|------|------|`,i=n.testResults.length>0?n.testResults.map(d=>`| ${d.suite} | ${d.pass} | ${d.fail} | ${d.skip} |`).join(`
|
|
1849
1903
|
`):"| - | - | - | - |",a=n.filesChanged.length>0?n.filesChanged.map(d=>`- ${d.path} (${d.action})`).join(`
|
|
1850
1904
|
`):"- No files recorded",c=n.ciCheckResults&&n.ciCheckResults.length>0?`
|
|
1851
1905
|
### CI Check Results
|
|
@@ -1855,8 +1909,8 @@ ${n.ciCheckResults.map(d=>`- ${d.name}: ${d.passed?"PASS":"FAIL"} - ${d.details}
|
|
|
1855
1909
|
${r}
|
|
1856
1910
|
|
|
1857
1911
|
### Test Results
|
|
1858
|
-
${i}
|
|
1859
1912
|
${s}
|
|
1913
|
+
${i}
|
|
1860
1914
|
|
|
1861
1915
|
### Files Changed
|
|
1862
1916
|
${a}
|
|
@@ -1868,18 +1922,18 @@ ${a}
|
|
|
1868
1922
|
|
|
1869
1923
|
---
|
|
1870
1924
|
|
|
1871
|
-
`,u=o+l;Lt.writeFileSync(e,u,"utf-8")}function
|
|
1925
|
+
`,u=o+l;Lt.writeFileSync(e,u,"utf-8")}function $a(e,t,n){return(0,qr.join)(e,"aidlc-docs",t,"construction",n,"validation-report.md")}function LT(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 Dg(e,t,n,o=5){try{let r=n.attemptNumber>=o,s=LT(n.gateNumber),i;switch(n.gateNumber){case 1:i=`Revise the INTENT based on this feedback: ${n.rejectionReason}`;break;case 2:i=`Update the INTENT based on this feedback: ${n.rejectionReason}`;break;case 3:i=`Regenerate UNITs based on this feedback: ${n.rejectionReason}`;break;case 4:i=`Re-implement this BOLT based on this feedback: ${n.rejectionReason}`;break;case 5:i=`Revise operations artifacts based on this feedback: ${n.rejectionReason}`;break;default:i=`Address this feedback: ${n.rejectionReason}`}let a=r?`Maximum revision attempts reached for ${n.artifactId}. Consider manual intervention or scope change.`:`${i}
|
|
1872
1926
|
|
|
1873
1927
|
Artifact ID: ${n.artifactId}
|
|
1874
1928
|
Workflow ID: ${t}
|
|
1875
1929
|
Attempt Number: ${n.attemptNumber}
|
|
1876
1930
|
Rejected By: ${n.rejectedBy}
|
|
1877
1931
|
|
|
1878
|
-
Please revise the artifact to address the feedback above and re-submit for approval.`;return{agentType:
|
|
1932
|
+
Please revise the artifact to address the feedback above and re-submit for approval.`;return{agentType:s,prompt:a,maxRetriesReached:r,contractStatusUpdate:{from:"violated",to:"draft"}}}catch(r){throw console.error("Error in dispatchRejection:",r),r}}pt();var Yr=E(se(),1),Ke=require("path"),Bn=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 Vr(e){try{let t=await ne(e);if(t.length===0)return null;let n=null;for(let o of t){let r=await T(e,o);if(!r||r.status==="complete")continue;let s=r.manifest_path||(0,Ke.join)(e,".olympus","workflow",o,"manifest.json");(!n||r.updated_at>n.updatedAt)&&(n={workflowId:o,checkpoint:r,manifestPath:s,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 FT(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 UT(e){try{let t=(0,Ke.join)(e,".olympus","config.json");if(Yr.existsSync(t)){let n=Yr.readJsonSync(t);if(n?.workflow?.qualityGates?.enabled===!1||n?.hooks?.qualityGate?.enabled===!1)return!0}}catch{}return!1}function Na(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 WT(e,t){return e==="inception"?t==="intent"?2:1:e==="construction"?t==="code-generation"?4:3:e==="operations"?5:1}function HT(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 BT(e){try{if(e.toolName!=="Task")return{continue:!0};if(!e.directory||!e.sessionId)return{continue:!0};let t=await Vr(e.directory);if(!t)return{continue:!0};let{workflowId:n,checkpoint:o,manifestPath:r}=t,s=D(r);if(!s)return console.error("[Olympus Quality Gate] Manifest corrupted or missing - failing open"),{continue:!0};let i=FT(o,s);if(!i)return{continue:!0};let a=_e(e.directory),c=(typeof o.risk_tier=="number"?o.risk_tier:o.risk_tier?.tier)||s.risk_tier?.tier||2;if(c===3&&i==="inception"&&!s.artifacts.some(y=>y.type?.toLowerCase().includes("momus")||y.type?.toLowerCase()==="momus-review"))return s.phases[i].gate_result={passed:!1,approved_by:null,approved_at:null,feedback:"Momus review required for Risk Tier 3",verification:{conformance_score:0,coverage_percentage:0,missing_items:["Momus review artifact missing"],passed:!1},validation:{alignment_score:0,alignment_questions:[],passed:!1}},F(r,s),await A(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
1933
|
|
|
1880
|
-
[GATE_PENDING]`}};if(
|
|
1934
|
+
[GATE_PENDING]`}};if(i==="construction"&&o.current_stage==="unit"){if(Oa(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 ee=new Date().toISOString();s.phases.construction.gate_result={passed:!0,approved_by:"trust",approved_at:ee,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 s.artifacts)S.stage==="unit"&&(S.reviewedBy="auto-approved");F(r,s),await A(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}`},P={workflowId:n,featureName:o.feature_name||n,projectPath:e.directory,sessionId:e.sessionId||"unknown",phase:"construction"},$=$e(S,P);ie($)}catch(S){console.error("[Olympus Quality Gate] Failed to capture Gate 3 auto-advance discovery:",S)}return{continue:!0}}let y;try{let ee=(0,Ke.join)(e.directory,"aidlc-docs",n,"inception"),S=(0,Bn.readFileSync)((0,Ke.join)(ee,"intent.md"),"utf-8"),P=s.artifacts.filter(M=>M.stage==="unit"),$=P.length>0?(0,Bn.readFileSync)((0,Ke.join)(e.directory,P[0].path),"utf-8"):"",x=gn($,S,S,"intent-to-unit","unit-to-intent","intent",P[0]?.id||"unit","intent");y={conformance_score:x.parentCheck.verification.conformance_score,coverage_percentage:x.parentCheck.verification.coverage_percentage,missing_items:x.parentCheck.verification.missing_items,passed:x.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=xg(s,a.current_level).map(ee=>ee.reviewContent).join(`
|
|
1881
1935
|
|
|
1882
|
-
`);return
|
|
1936
|
+
`);return s.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,s),await A(e.directory,o),{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`${c===3?"[BLOCKING - Acknowledgment Required] ":""}STOP: Gate 3 (UNIT decomposition review) requires approval.
|
|
1883
1937
|
|
|
1884
1938
|
${v}
|
|
1885
1939
|
|
|
@@ -1887,12 +1941,12 @@ VERIFICATION: ${y.conformance_score}% conformance, ${y.coverage_percentage}% cov
|
|
|
1887
1941
|
Missing: ${y.missing_items.join(", ")}
|
|
1888
1942
|
|
|
1889
1943
|
VALIDATION: Review alignment questions:
|
|
1890
|
-
${w.map((
|
|
1944
|
+
${w.map((ee,S)=>`${S+1}. ${ee.question}`).join(`
|
|
1891
1945
|
`)}
|
|
1892
1946
|
|
|
1893
1947
|
Type "approve" to proceed or "reject <reason>" to block.
|
|
1894
1948
|
|
|
1895
|
-
[GATE_PENDING]`}}}if(
|
|
1949
|
+
[GATE_PENDING]`}}}if(i==="construction"&&o.current_stage==="code-generation"&&o.active_code_plan_path){let h=o.active_code_plan_path,y=Pa(a.current_level,c),w;try{let S=(0,Ke.join)(e.directory,"aidlc-docs",n,"inception"),P=(0,Bn.readFileSync)((0,Ke.join)(S,"intent.md"),"utf-8"),$=s.artifacts.find(C=>C.id===h),x=$?(0,Bn.readFileSync)((0,Ke.join)(e.directory,$.path),"utf-8"):"",M=gn(x,P,P,"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||[],I={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();s.phases.construction.gate_result={passed:!0,approved_by:"trust",approved_at:S,feedback:null,verification:w,validation:I};let P=s.artifacts.find(x=>x.id===h);P&&(P.reviewedBy="auto-approved"),nt(r,h,"fulfilled");try{let x=Aa(s,h);if(x&&e.directory){let M=$a(e.directory,n,x);xa(M,x,{boltId:h,boltTitle:P?.type||"auto-approved",commandsExecuted:[],testResults:[],filesChanged:[],gateApprovedBy:"auto-approved",dualValidation:{parentConformance:w.conformance_score,rootConformance:0},riskTier:c})}}catch(x){console.error("[Olympus Quality Gate] Failed to generate validation report:",x)}F(r,s),await A(e.directory,o);try{let x={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"},C=$e(x,M);ie(C)}catch(x){console.error("[Olympus Quality Gate] Failed to capture Gate 4 auto-advance discovery:",x)}let $="";try{let{isWorkflowComplete:x}=await Promise.resolve().then(()=>(z(),Vt)),M=D(r);M&&x(M)&&(o.current_phase="operations",o.current_stage="code-generation",ut(r,"construction","complete"),ut(r,"operations","in_progress"),await A(e.directory,o),$=" All BOLTs fulfilled \u2014 auto-transitioning to Operations phase.",console.log("[Olympus Quality Gate] All BOLTs fulfilled \u2014 auto-transitioning to Operations phase"))}catch(x){console.error("[Olympus Quality Gate] Failed to check workflow completion:",x)}return{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`Gate 4 (BOLT ${h} review): Auto-approved at Trust Level ${a.current_level}. Notification only.${$}`}}}let v;try{v=$g(s,h,a.current_level,c)}catch{return{continue:!0}}return s.phases.construction.gate_result={passed:!1,approved_by:null,approved_at:null,feedback:null,verification:w,validation:I},Ce(r,{phase:"construction",action:"approved",actor:"trust",reason:`Gate 4 pending review for BOLT ${h}`}),F(r,s),await A(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
1950
|
|
|
1897
1951
|
${v.reviewContent}
|
|
1898
1952
|
|
|
@@ -1900,24 +1954,24 @@ VERIFICATION: ${w.conformance_score}% conformance, ${w.coverage_percentage}% cov
|
|
|
1900
1954
|
Missing: ${w.missing_items.join(", ")}
|
|
1901
1955
|
|
|
1902
1956
|
VALIDATION: Review alignment questions:
|
|
1903
|
-
${k.map((
|
|
1957
|
+
${k.map((S,P)=>`${P+1}. ${S.question}`).join(`
|
|
1904
1958
|
`)}
|
|
1905
1959
|
|
|
1906
1960
|
Type "approve" to proceed or "reject <reason>" to block.
|
|
1907
1961
|
|
|
1908
|
-
[GATE_PENDING]`}}}if(
|
|
1962
|
+
[GATE_PENDING]`}}}if(i==="operations"){let h;try{h=Ng(s,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 s.phases.operations.gate_result={passed:!1,approved_by:null,approved_at:null,feedback:null,verification:w,validation:k},F(r,s),await A(e.directory,o),{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`[BLOCKING - Acknowledgment Required] STOP: Gate 5 (Release review) requires approval.
|
|
1909
1963
|
|
|
1910
1964
|
${h.reviewContent}
|
|
1911
1965
|
|
|
1912
1966
|
VALIDATION: Review alignment questions:
|
|
1913
|
-
${y.map((v,
|
|
1967
|
+
${y.map((v,O)=>`${O+1}. ${v.question}`).join(`
|
|
1914
1968
|
`)}
|
|
1915
1969
|
|
|
1916
1970
|
Type "approve" to proceed or "reject <reason>" to block.
|
|
1917
1971
|
|
|
1918
|
-
[GATE_PENDING]`}}}if(
|
|
1972
|
+
[GATE_PENDING]`}}}if(op(c,a.current_level)){Ce(r,{phase:i,action:"approved",actor:"trust",reason:`Auto-advanced by Trust Level ${a.current_level} for Tier ${c}`});let h=new Date().toISOString();s.phases[i].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,s),await A(e.directory,o);try{let y={type:"gate_approval",phase:i,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:i},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(i==="inception")try{let h=(0,Ke.join)(e.directory,"aidlc-docs",n,"inception"),y=(0,Bn.readFileSync)((0,Ke.join)(h,"intent.md"),"utf-8");l=zo(y,y,"intent-to-unit"),u=Hn[i]||[]}catch{l={conformance_score:0,coverage_percentage:0,missing_items:["Could not read inception artifacts for alignment check"],passed:!1},u=Hn[i]||[]}else l={conformance_score:0,coverage_percentage:0,missing_items:["Alignment check not yet implemented for this phase"],passed:!1},u=Hn[i]||[];let d={alignment_score:0,alignment_questions:u,passed:!1},f="";if(i==="inception"){let h=o.depth_score||s.depth_assessment?.total_score;h&&h>=21&&(s.artifacts.some(w=>w.type?.toLowerCase().includes("metis"))||(f=`
|
|
1919
1973
|
|
|
1920
|
-
WARNING: DEEP workflow without Metis consultation detected. Metis blind-spot analysis is strongly recommended for complex workflows.`))}
|
|
1974
|
+
WARNING: DEEP workflow without Metis consultation detected. Metis blind-spot analysis is strongly recommended for complex workflows.`))}s.phases[i].gate_result={passed:!1,approved_by:null,approved_at:null,feedback:null,verification:l,validation:d},F(r,s),await A(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)":`${i} transition`;return{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`${m}STOP: ${p} requires approval.
|
|
1921
1975
|
|
|
1922
1976
|
VERIFICATION: ${l.conformance_score}% conformance, ${l.coverage_percentage}% coverage.
|
|
1923
1977
|
Missing: ${l.missing_items.join(", ")}
|
|
@@ -1928,10 +1982,10 @@ ${u.map((h,y)=>`${y+1}. ${h.question}`).join(`
|
|
|
1928
1982
|
|
|
1929
1983
|
Type "approve" to proceed or "reject <reason>" to block.${f}
|
|
1930
1984
|
|
|
1931
|
-
[GATE_PENDING]`}}}catch(t){return console.error("[Olympus Quality Gate] Error in qualityGateBlocker:",t),{continue:!0}}}async function
|
|
1985
|
+
[GATE_PENDING]`}}}catch(t){return console.error("[Olympus Quality Gate] Error in qualityGateBlocker:",t),{continue:!0}}}async function GT(e){try{let t=HT(e);if(!e.directory)return{continue:!0};if(t.includes("--no-gates")||UT(e.directory)){let n=await Vr(e.directory);if(n){let{manifestPath:o}=n,r=D(o);if(r){let s=Na(r);if(s){let i=t.includes("--no-gates")?"flag":"config";Ce(o,{phase:s,action:"bypassed",actor:i,reason:i==="flag"?"--no-gates flag detected":"Quality gates disabled in config"}),r.phases[s].gate_result=null,r.phases[s].gate_bypassed=!0,r.phases[s].bypass_reason=i==="flag"?"--no-gates flag":"Config disabled",F(o,r),await A(e.directory,n.checkpoint)}}}return{continue:!0}}if(t.trim().toLowerCase().startsWith("approve")){let n=await Vr(e.directory);if(!n)return{continue:!0};let{manifestPath:o}=n,r=D(o);if(!r)return{continue:!0};let s=Na(r);if(!s)return{continue:!0};let i=new Date().toISOString();r.phases[s].gate_result&&(r.phases[s].gate_result.passed=!0,r.phases[s].gate_result.approved_by="human",r.phases[s].gate_result.approved_at=i);let{checkpoint:a}=n;if(s==="construction"){if(a.current_stage==="code-generation"&&a.active_code_plan_path){let f=a.active_code_plan_path;nt(o,f,"fulfilled");let m=r.artifacts.find(p=>p.id===f);m&&(m.reviewedBy="human");try{let p=Aa(r,f);if(p){let g=$a(e.directory,n.workflowId,p),h=(typeof a.risk_tier=="number"?a.risk_tier:a.risk_tier?.tier)||r.risk_tier?.tier||2;xa(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(()=>(z(),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 A(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)nt(o,m.id,"active"),m.reviewedBy="human"}}else{let f=r.artifacts.filter(m=>m.phase===s);for(let m of f)nt(o,m.id,"active")}Ce(o,{phase:s,action:"approved",actor:"human",reason:null});try{let f={type:"gate_approval",phase:s,stage:a.current_stage,details:`Gate approved for ${s} phase`},m={workflowId:n.workflowId,featureName:a.feature_name||n.workflowId,projectPath:e.directory,sessionId:e.sessionId||"unknown",phase:s},p=$e(f,m);ie(p)}catch(f){console.error("[Olympus Quality Gate] Failed to capture gate approval discovery:",f)}let c=_e(e.directory),l=li(c,!0,!1);ci(l,e.directory),F(o,r),await A(e.directory,n.checkpoint),r.phases[s].gate_result?.passed&&(r.phases[s].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 ${s} transition approved. Proceeding to next phase.${u}`}}}if(t.trim().toLowerCase().startsWith("reject")){let n=await Vr(e.directory);if(!n)return{continue:!0};let{manifestPath:o}=n,r=D(o);if(!r)return{continue:!0};let s=Na(r);if(!s)return{continue:!0};let i=t.trim().substring(6).trim()||"No reason provided";r.phases[s].gate_result&&(r.phases[s].gate_result.passed=!1,r.phases[s].gate_result.feedback=i);let{checkpoint:a}=n,c="";if(s==="construction")if(a.current_stage==="code-generation"&&a.active_code_plan_path){let g=a.active_code_plan_path;nt(o,g,"violated",i),c=`The reviewer rejected ${g}: ${i}. Revise and re-submit.`}else if(a.current_stage==="unit"){let g=r.artifacts.filter(h=>h.stage==="unit");for(let h of g)nt(o,h.id,"violated",i);c=`The reviewer rejected UNIT decomposition: ${i}. Revise and re-submit.`}else{let g=r.artifacts.filter(h=>h.phase===s);for(let h of g)nt(o,h.id,"violated",i)}else{let g=r.artifacts.filter(h=>h.phase===s);for(let h of g)nt(o,h.id,"violated",i)}Ce(o,{phase:s,action:"rejected",actor:"human",reason:i});try{let g={type:"gate_rejection",phase:s,stage:a.current_stage,details:i},h={workflowId:n.workflowId,featureName:a.feature_name||n.workflowId,projectPath:e.directory,sessionId:e.sessionId||"unknown",phase:s},y=$e(g,h);ie(y)}catch(g){console.error("[Olympus Quality Gate] Failed to capture gate rejection discovery:",g)}let l=_e(e.directory),u=li(l,!1,!0);ci(u,e.directory),F(o,r),await A(e.directory,n.checkpoint);let d=WT(s,a.current_stage),f=s==="construction"&&a.current_stage==="code-generation"&&a.active_code_plan_path?a.active_code_plan_path:r.artifacts.find(g=>g.phase===s)?.id??`${s}-artifact`,m=r.gate_audit.filter(g=>g.phase===s&&g.action==="rejected").length,p;try{let g=await Dg(e.directory,r.workflow_id,{gateNumber:d,artifactId:f,rejectionReason:i,rejectedBy:"human",attemptNumber:m+1});p=`Gate ${d} rejected ${f}: ${i}.
|
|
1932
1986
|
|
|
1933
|
-
${g.prompt}`}catch{p=c||`Gate rejected. Reason: ${
|
|
1934
|
-
`)[0];if(
|
|
1987
|
+
${g.prompt}`}catch{p=c||`Gate rejected. Reason: ${i}. 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 jg(){_({name:"qualityGateBlocker",event:"PostToolUse",priority:80,matcher:"task",handler:BT}),_({name:"qualityGateApprover",event:"UserPromptSubmit",priority:12,handler:GT})}var qT=["explore","explore-medium","librarian","librarian-low","oracle","oracle-low","oracle-medium","momus","metis","multimodal-looker"];function Mg(e){return qT.includes(e)}var Lg=/(?:^|\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)/,Kr={debounceMs:1e4,mode:"soft",enabled:!0};Ae();function Fg(){_({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(!Mg(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 s=e.toolInput?.command;if(typeof s=="string"&&Lg.test(s))return{continue:!1,stopReason:`Agent "${n}" is read-only and cannot execute bash commands that modify files. Detected write operation in: ${s.substring(0,100)}${s.length>100?"...":""}`}}return{continue:!0}}catch(t){return console.error("[Olympus Agent Role Guard] Error in handler:",t),{continue:!0}}}})}var Jr=require("child_process"),zr=require("path"),Gn=require("fs"),Ug=0,Ft=null,Ut=null;function Wg(e){let t=(0,zr.join)(e,".olympus","config.json"),n={enabled:Kr.enabled,mode:Kr.mode,debounceMs:Kr.debounceMs};try{if((0,Gn.existsSync)(t)){let o=(0,Gn.readFileSync)(t,"utf8"),r=JSON.parse(o);if(r.hooks?.buildCheck){let s=r.hooks.buildCheck;typeof s.enabled=="boolean"&&(n.enabled=s.enabled),(s.mode==="soft"||s.mode==="strict")&&(n.mode=s.mode),typeof s.debounceMs=="number"&&s.debounceMs>0&&(n.debounceMs=s.debounceMs)}}}catch(o){console.error("[Olympus Build Check] Failed to load config:",o)}return n}function VT(e){let t=(0,zr.join)(e,"node_modules",".bin","tsc"),n=process.platform==="win32"?`${t}.cmd`:t;if((0,Gn.existsSync)(n))return n;try{let o=process.platform==="win32"?"where":"which",s=require("child_process").execSync(`${o} tsc`,{encoding:"utf8"}).trim().split(`
|
|
1988
|
+
`)[0];if(s)return s}catch{}return null}function YT(){if(!Ut||!Ut.pid)return;let e=Ut.pid;try{Ut.kill("SIGTERM")}catch{if(process.platform==="win32")try{(0,Jr.exec)(`taskkill /PID ${e} /F`,n=>{n&&console.error("[Olympus Build Check] Failed to kill process with taskkill:",n)})}catch{}}Ut=null}function Hg(){_({name:"buildCheckTrigger",event:"PostToolUse",priority:65,matcher:/write|edit|multiedit/i,handler:async e=>{try{if(!e.directory)return{continue:!0};let t=Wg(e.directory);if(!t.enabled)return{continue:!0};let n=Date.now();if(n-Ug<t.debounceMs)return{continue:!0};let o=(0,zr.join)(e.directory,"tsconfig.json");if(!(0,Gn.existsSync)(o))return{continue:!0};let r=VT(e.directory);if(!r)return{continue:!0};YT();try{let s=(0,Jr.spawn)(r,["--noEmit"],{cwd:e.directory,detached:!0,stdio:"pipe"});Ut=s,Ug=n;let i="",a="";s.stdout&&s.stdout.on("data",c=>{i+=c.toString()}),s.stderr&&s.stderr.on("data",c=>{a+=c.toString()}),s.on("exit",c=>{let l=(i+a).trim();Ft={passed:c===0,output:l,timestamp:Date.now()},Ut=null}),s.on("error",c=>{console.error("[Olympus Build Check] tsc spawn error:",c),Ut=null})}catch(s){console.error("[Olympus Build Check] Failed to spawn tsc:",s)}}catch(t){console.error("[Olympus Build Check] Error in buildCheckTrigger:",t)}return{continue:!0}}}),_({name:"buildCheckInjector",event:"PostToolUse",priority:66,handler:async e=>{try{if(!Ft)return{continue:!0};let t=e.directory?Wg(e.directory):{mode:"soft"};if(Ft.passed)return Ft=null,{continue:!0};let n=Ft.output.length>500?Ft.output.substring(0,500)+`
|
|
1935
1989
|
... (truncated)`:Ft.output,o=t.mode==="strict"?`[BUILD CHECK FAILED - BLOCKING]
|
|
1936
1990
|
|
|
1937
1991
|
TypeScript compilation failed:
|
|
@@ -1944,24 +1998,24 @@ TypeScript compilation failed:
|
|
|
1944
1998
|
|
|
1945
1999
|
${n}
|
|
1946
2000
|
|
|
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}}})}
|
|
2001
|
+
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();we();z();var qn=require("path"),Vn=require("fs"),KT={prometheus:"inception"};async function JT(e){try{let t=await ne(e);if(t.length===0)return null;let n=null;for(let o of t){let r=await T(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 zT(e,t){let n=(0,qn.join)(e,"inception"),o=e;switch(t){case"intent":{let r=(0,qn.join)(n,"intent.md"),s=(0,qn.join)(o,"intent.md"),i=(0,Vn.existsSync)(r)?r:s;return(0,Vn.existsSync)(i)?{artifactPath:i,referencePaths:[]}:null}default:return null}}async function QT(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 XT(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,s)=>` ${s+1}. ${r}`).join(`
|
|
1948
2002
|
`);return`[Artifact Validation] WARNING: ${n} validation FAILED (${t.coverage_percentage}% coverage)
|
|
1949
2003
|
|
|
1950
2004
|
Blocking issues:
|
|
1951
2005
|
${o}
|
|
1952
2006
|
|
|
1953
2007
|
${t.reviewer?`Reviewer: ${t.reviewer}
|
|
1954
|
-
`:""}Please review and address these issues before proceeding to the next stage.`}async function
|
|
2008
|
+
`:""}Please review and address these issues before proceeding to the next stage.`}async function ZT(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(!KT[n])return{continue:!0};let r=await JT(e.directory);if(!r)return{continue:!0};let{workflowId:s,checkpoint:i}=r,a="intent",c=(0,qn.join)(e.directory,"aidlc-docs",s);if(!(0,Vn.existsSync)(c))return console.error("[Olympus Artifact Gate] Workflow directory not found:",c),{continue:!0};let l=zT(c,a);if(!l)return console.error(`[Olympus Artifact Gate] Could not find artifact paths for ${a} in ${c}`),{continue:!0};let u=await QT(a,l.artifactPath,l.referencePaths);if(!u)return console.error(`[Olympus Artifact Gate] Validation failed to run for ${a}`),{continue:!0};let d=XT(a,u);if(a==="intent"&&u.passed)try{let f=(0,Vn.readFileSync)(l.artifactPath,"utf-8"),m=pr(f),p=i.manifest_path||(0,qn.join)(e.directory,"aidlc-docs",s,"manifest.json"),g=D(p);g&&(g.depth_assessment=m,g.risk_tier=m.risk_tier,F(p,g)),i.depth_score=m.total_score,i.risk_tier=m.risk_tier.tier,await A(e.directory,i);let h=m.recommended_depth==="minimal"?"SHALLOW":m.recommended_depth==="standard"?"MEDIUM":"DEEP";d+=`
|
|
1955
2009
|
|
|
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
|
|
1957
|
-
Command: ${o.command}`,
|
|
1958
|
-
Exit code: ${o.exitCode}`,o.stderr&&(
|
|
1959
|
-
Error: ${o.stderr.substring(0,500)}`)),
|
|
2010
|
+
[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 Bg(){_({name:"workflowArtifactGate",event:"PostToolUse",priority:78,matcher:"task",handler:ZT})}we();z();var nn=E(se(),1),Qr=require("path"),Gg=require("child_process");function qg(e){let t=(0,Qr.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 eE()}function eE(){return{staticQuality:{enabled:!0},security:{enabled:!0,auditLevel:"moderate"},complexity:{enabled:!0,agent:"oracle-low"},customChecks:[]}}function tE(e){let t=[];try{let n=(0,Qr.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,Qr.join)(e,"tsconfig.json"))&&t.push("npx tsc --noEmit")}}catch{}return t}function Da(e,t,n,o){let r=Date.now();try{let s=(0,Gg.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:(s||"").substring(0,2e3),stderr:"",duration_ms:Date.now()-r}}catch(s){return{name:n,layer:o,passed:!1,command:e,exitCode:s.status||1,stdout:(s.stdout||"").substring(0,2e3),stderr:(s.stderr||"").substring(0,2e3),duration_ms:Date.now()-r}}}function Vg(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 s=e.match(r);s&&n.push(`${o} detected (${s.length} occurrence${s.length>1?"s":""})`)}return n}function Yg(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 s=e.match(r);s&&n.push(`${o} (${s.length} occurrence${s.length>1?"s":""})`)}return n}function Kg(e,t){let n=[],o=Date.now();if(t.staticQuality.enabled){let s=t.staticQuality.commands||tE(e);for(let i of s)n.push(Da(i,e,`Static: ${i}`,"static-quality"))}if(t.security.enabled){let s=t.security.auditLevel||"moderate";n.push(Da(`npm audit --audit-level=${s}`,e,"Security: npm audit","security"))}if(t.complexity.enabled&&n.push({name:"Complexity: AI review",layer:"complexity",passed:!0,command:`dispatch ${t.complexity.agent||"oracle-low"}`,exitCode:0,stdout:"AI complexity review dispatched",stderr:"",duration_ms:0}),t.customChecks)for(let s of t.customChecks)n.push(Da(s.command,e,`Custom: ${s.name}`,"custom"));let r=n.filter(s=>!s.passed).map(s=>s.name);return{allPassed:r.length===0,results:n,totalDuration_ms:Date.now()-o,failedChecks:r}}function Jg(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 s=`[${o.passed?"PASS":"FAIL"}] ${o.name}`;return o.passed||(s+=`
|
|
2011
|
+
Command: ${o.command}`,s+=`
|
|
2012
|
+
Exit code: ${o.exitCode}`,o.stderr&&(s+=`
|
|
2013
|
+
Error: ${o.stderr.substring(0,500)}`)),s}).join(`
|
|
1960
2014
|
`);return`${t}
|
|
1961
2015
|
|
|
1962
2016
|
${n}
|
|
1963
2017
|
|
|
1964
|
-
Total duration: ${e.totalDuration_ms}ms`}var
|
|
2018
|
+
Total duration: ${e.totalDuration_ms}ms`}var zg=require("fs");async function nE(e){try{if(e.toolName!=="Task")return{continue:!0};if(!e.directory||!e.sessionId)return{continue:!0};let t=await ne(e.directory);if(t.length===0)return{continue:!0};let n=null,o="";for(let m of t){let p=await T(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,s=D(o);if(!s)return{continue:!0};let i=qg(e.directory),a=Kg(e.directory,i),c=s.artifacts.find(m=>m.id===r),l=[],u=[];if(c)try{let m=(0,zg.readFileSync)(c.path,"utf-8");l=Vg(m),u=Yg(m)}catch{}let d=Jg(a),f="";return l.length>0&&(f=`
|
|
1965
2019
|
|
|
1966
2020
|
SECURITY FINDINGS:
|
|
1967
2021
|
${l.map(m=>` - ${m}`).join(`
|
|
@@ -1973,41 +2027,41 @@ ${u.map(m=>` - ${m}`).join(`
|
|
|
1973
2027
|
|
|
1974
2028
|
${d}${f}
|
|
1975
2029
|
|
|
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
|
|
1977
|
-
`);return{summary:d,phaseProgress:o,artifactTree:r,riskSummary:
|
|
1978
|
-
`)}function
|
|
1979
|
-
`)}function
|
|
1980
|
-
`)}function
|
|
1981
|
-
`)}function
|
|
1982
|
-
`)}function
|
|
1983
|
-
`)}
|
|
2030
|
+
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 Qg(){_({name:"ciReviewPipeline",event:"PostToolUse",priority:79,matcher:"task",handler:nE})}fe();function Xg(e,t=2){let o=e.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter(s=>s.length>0);if(o.length<t)return new Set(o);let r=new Set;for(let s=0;s<=o.length-t;s++)r.add(o.slice(s,s+t).join(" "));return r}function ja(e,t){let n=Xg(e),o=Xg(t),r=new Set([...n].filter(i=>o.has(i))),s=new Set([...n,...o]);return s.size>0?r.size/s.size:0}function oE(e,t=.4){let n=[],o=new Set;for(let r of e){if(o.has(r.id))continue;let s=[r];o.add(r.id);for(let i of e){if(o.has(i.id))continue;ja(r.user_message,i.user_message)>=t&&(s.push(i),o.add(i.id))}n.push(s)}return n}function Zg(e,t=3,n=1e3,o){let i=(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 oE(i).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=sE(c);return{pattern:rE(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 rE(e){let t=new Map;for(let r of e){let s=r.user_message.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter(i=>i.length>3);for(let i of s)t.set(i,(t.get(i)||0)+1)}let n=[...t.entries()].sort((r,s)=>s[1]-r[1]).slice(0,3).map(([r])=>r);return e[0].user_message.substring(0,100)+(n.length>0?` [themes: ${n.join(", ")}]`:"")}function sE(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 iE={verbosity:"unknown",autonomy:"unknown",explanation_depth:"unknown",explicit_rules:[],inferred_preferences:[],recurring_corrections:[],last_updated:new Date().toISOString()},aE=30;function cE(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),s=o.user_message.match(/never\s+(.+?)(?:\.|$)/i);r&&n.push(`Always: ${r[1].trim()}`),s&&n.push(`Never: ${s[1].trim()}`)}return[...new Set(n)]}function lE(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 uE(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 eh(e,t,n,o){let r={...e},s=o??t.find(m=>m.project_path)?.project_path,i=cE(t),a=new Set(r.explicit_rules.map(m=>m.rule)),c=i.filter(m=>!a.has(m)).map(m=>({rule:m,created_at:new Date().toISOString(),...s?{project_path:s}:{}}));r.explicit_rules=[...r.explicit_rules,...c];let l=lE(t);l!=="unknown"&&(r.verbosity=l);let u=uE(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=>ja(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<=aE*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 th(){return{...iE,last_updated:new Date().toISOString()}}var Io=require("path"),Yn=require("fs"),dE=3,pE=10;function fE(e){let t=(0,Io.join)(e,"feedback-log.jsonl"),n=(0,Io.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 nh(){_({name:"learningAggregation",event:"Stop",priority:95,handler:async e=>{try{if(!e.directory)return{continue:!0};let t=ce();if(!fE(t))return{continue:!0};let n=Do();if(n.length<dE)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 s={};for(let d of r){let f=jo(d,n);f&&(s[d]=f)}let i=(0,Io.join)(t,"agent-performance.json");Be(i,s);let a=(0,Io.join)(t,"user-preferences.json"),c=me(a,th()),l=[];if(n.length>=pE)try{l=Zg(n)}catch(d){console.error("[Olympus Learning Aggregation] Pattern extraction failed:",d)}let u=eh(c,n,l);Be(a,u)}catch(t){console.error("[Olympus Learning Aggregation] Error in aggregation handler:",t)}return{continue:!0}}})}var La=["discovery","inception","construction","operations"],mE={draft:"o",active:"+",fulfilled:"++",violated:"X",stale:"!"},gE={0:"Baseline",1:"Earned",2:"Extended",3:"Trusted"};function oh(e,t=null,n=null){let o=hE(e),r=kE(e),s=wE(e.risks),i=_E(e.gate_audit),a=SE(t),c=vE(e.alignment_checks),l=TE(e.depth_assessment),u=EE(e.risk_tier),d=CE(e,o),f=bE(e),m=n?.inception_stages?IE(n.inception_stages,n.current_inception_stage):null,p=[`# Workflow Status: ${e.feature_name}`,`ID: ${e.workflow_id}`,"",d,"","## Phase Progress",...o.map(g=>yE(g)),"",...m?[m,""]:[],f,l,u,a,"","## Artifacts",r,"","## Alignment",c,"","## Risk Summary",s,"","## Gate Audit",i].filter(g=>g!==null).join(`
|
|
2031
|
+
`);return{summary:d,phaseProgress:o,artifactTree:r,riskSummary:s,gateSummary:i,trustDisplay:a,alignmentSummary:c,fullReport:p}}function hE(e){return La.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 s=o.filter(a=>a.contract_status==="active"||a.contract_status==="fulfilled").length,i=Math.round(s/r*100);return{phase:t,percentage:i,status:n.status,artifactCount:r}})}function yE(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 kE(e){let t=[];for(let n of La){let o=e.artifacts.filter(i=>i.phase===n);if(o.length===0)continue;let r=n.charAt(0).toUpperCase()+n.slice(1);t.push(`[${r}]`);let s=new Map;for(let i of o){let a=i.stage;s.has(a)||s.set(a,[]),s.get(a).push(i)}for(let[i,a]of s){t.push(` ${i}/`);for(let c of a){let l=mE[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(`
|
|
2032
|
+
`)}function wE(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,s=[`Total: ${e.length} | Open: ${t} | Mitigated: ${n} | Accepted: ${o} | Closed: ${r}`],i=e.filter(a=>a.status==="open");for(let a of i)s.push(` [OPEN] ${a.id}: ${a.description} (${a.likelihood}/${a.impact})`);return s.join(`
|
|
2033
|
+
`)}function _E(e){if(e.length===0)return"No gate transitions recorded";let t=e.filter(s=>s.action==="approved").length,n=e.filter(s=>s.action==="rejected").length,o=e.filter(s=>s.action==="bypassed").length,r=[`Total: ${e.length} | Approved: ${t} | Rejected: ${n} | Bypassed: ${o}`];for(let s of e){let i=s.phase.charAt(0).toUpperCase()+s.phase.slice(1);r.push(` [${s.action.toUpperCase()}] ${i} by ${s.actor}${s.reason?": "+s.reason:""}`)}return r.join(`
|
|
2034
|
+
`)}function SE(e){if(!e)return"Trust: Not initialized";let t=gE[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(`
|
|
2035
|
+
`)}function vE(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 s=r.alignment_passed?"PASS":"FAIL",i=r.verification.conformance_score,a=r.verification.passed?"v":"x",c=r.validation.passed?"v":"x";o.push(` [${s}] ${r.source_artifact_id} -> ${r.target_artifact_id}: verification=${i}% [${a}] validation [${c}]`)}return o.join(`
|
|
2036
|
+
`)}function TE(e){return e?`Depth: ${e.recommended_depth} (score: ${e.total_score}/30)${e.skip_units?" [skip-units]":""}`:"Depth: Not assessed"}function EE(e){return e?`Risk Tier: ${e.tier} (${e.rationale})`:"Risk Tier: Not classified"}function bE(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 CE(e,t){let n=e.artifacts.length,o=t.filter(s=>s.status!=="not_started");return`${t.filter(s=>s.percentage===100&&s.status==="complete").length}/${La.length} phases complete | ${n} artifacts total`}var Ma=["workspace-detection","reverse-engineering","requirements-analysis","user-stories","workflow-planning","application-design","units-generation"],RE={"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 IE(e,t){let n=Ma.length,o=Ma.filter(l=>e[l]?.status==="completed").length,r=Math.round(o/n*100),s=10,i=Math.round(r/100*s),c=[`Inception [${i>=s?"=".repeat(s):"=".repeat(i)+">"+"-".repeat(s-i-1)}] ${r}% (${o}/${n} stages)`];for(let l of Ma){let u=e[l],d=RE[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(`
|
|
2037
|
+
`)}z();$t();we();var rh=E(require("path"),1);function sh(){_({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 i=await ne(t),a=null;for(let m of i){let p=await T(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=rh.join(t,"aidlc-docs",a,"manifest.json"),l=D(c);if(!l){let m=await T(t,a),p=m?.current_phase||"unknown",g=m?.current_stage||"unknown";return{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:`<workflow-status>
|
|
1984
2038
|
# Workflow Status: ${a}
|
|
1985
2039
|
|
|
1986
2040
|
Phase: ${p} | Stage: ${g}
|
|
1987
2041
|
|
|
1988
2042
|
Note: manifest.json not found. Detailed artifact tracking unavailable. The workflow is active and can proceed normally.
|
|
1989
|
-
</workflow-status>`}}}let u=
|
|
1990
|
-
${
|
|
1991
|
-
</workflow-status>`}}}catch(t){return console.error("[Olympus Workflow Status] Error generating report:",t),{continue:!0}}}})}
|
|
2043
|
+
</workflow-status>`}}}let u=_e(t),d=await T(t,a);return{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:`<workflow-status>
|
|
2044
|
+
${oh(l,u,d).fullReport}
|
|
2045
|
+
</workflow-status>`}}}catch(t){return console.error("[Olympus Workflow Status] Error generating report:",t),{continue:!0}}}})}z();$t();we();var ih=E(require("path"),1);function ah(){_({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 ne(t),o=null,r=null;for(let p of n){let g=await T(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 s=ih.join(t,"aidlc-docs",o,"manifest.json"),i=D(s);if(!i)return{continue:!0};let a=_e(t),c=i.gate_audit.length>0?i.gate_audit[i.gate_audit.length-1]:null,l=null,u=ot(i),d=u.filter(p=>p.contract_status==="fulfilled"),f=qt(i),m=i.artifacts.filter(p=>p.stage==="intent");if(u.length>0&&d.length===u.length&&r.current_stage==="code-generation"&&i.phases.construction.status==="complete")l=`\u2713 All ${u.length} BOLTs executed and reviewed
|
|
1992
2046
|
\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}'
|
|
1993
2047
|
Gate 4: Dev review of ${g.id} code
|
|
1994
|
-
\u2192 Current: ${p} remaining`}else if(f.length>0&&
|
|
2048
|
+
\u2192 Current: ${p} remaining`}else if(f.length>0&&i.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}
|
|
1995
2049
|
Gate 3: Dev review required (Trust Level ${a.current_level})
|
|
1996
|
-
\u2192 Waiting: Developer reviews architectural decomposition`}else if(m.some(p=>p.contract_status==="active"||p.contract_status==="fulfilled")&&r.current_stage==="intent"&&c?.phase==="inception"){let p=
|
|
1997
|
-
\u26A0 Risk Tier 3: Dev review REQUIRED before Construction`,r.status!=="awaiting_dev_review"&&(r.status="awaiting_dev_review",await
|
|
2050
|
+
\u2192 Waiting: Developer reviews architectural decomposition`}else if(m.some(p=>p.contract_status==="active"||p.contract_status==="fulfilled")&&r.current_stage==="intent"&&c?.phase==="inception"){let p=i.risk_tier?.tier??0,g="";p===3&&(g=`
|
|
2051
|
+
\u26A0 Risk Tier 3: Dev review REQUIRED before Construction`,r.status!=="awaiting_dev_review"&&(r.status="awaiting_dev_review",await A(t,r)));let h=m.length>0?m[0].path:`aidlc-docs/${o}/inception/intent.md`;l=`\u2713 INTENT locked \u2014 '${i.feature_name}'
|
|
1998
2052
|
Tech spec: ${h} | Risk: Tier ${p}
|
|
1999
2053
|
${f.length} UNITs decomposed | ${u.length} BOLTs queued
|
|
2000
2054
|
\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)
|
|
2001
2055
|
\u2192 Next: continue inception pipeline`}}if(l)return{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`<workflow-transition>
|
|
2002
2056
|
${l}
|
|
2003
|
-
</workflow-transition>`}}}catch(t){console.error("[Olympus Workflow Transition] Error:",t)}return{continue:!0}}})}var
|
|
2004
|
-
`;break;case 114:k+="\r";break;case 116:k+=" ";break;case 117:let
|
|
2005
|
-
`),a++,l=o,
|
|
2057
|
+
</workflow-transition>`}}}catch(t){console.error("[Olympus Workflow Transition] Error:",t)}return{continue:!0}}})}var ch=!1;function lh(){ch||(Fg(),sh(),Pp(),Hp(),lf(),Zf(),xm(),Jm(),Xm(),cg(),lg(),kg(),Tg(),Ag(),Hg(),Bg(),Qg(),jg(),ah(),nh(),ch=!0)}var ns=require("fs"),kh=require("os"),ts=require("path");function Xr(e,t=!1){let n=e.length,o=0,r="",s=0,i=16,a=0,c=0,l=0,u=0,d=0;function f(k,I){let v=0,O=0;for(;v<k||!I;){let R=e.charCodeAt(o);if(R>=48&&R<=57)O=O*16+R-48;else if(R>=65&&R<=70)O=O*16+R-65+10;else if(R>=97&&R<=102)O=O*16+R-97+10;else break;o++,v++}return v<k&&(O=-1),O}function m(k){o=k,r="",s=0,i=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 I=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++;I=o}else d=3;return e.substring(k,I)}function g(){let k="",I=o;for(;;){if(o>=n){k+=e.substring(I,o),d=2;break}let v=e.charCodeAt(o);if(v===34){k+=e.substring(I,o),o++;break}if(v===92){if(k+=e.substring(I,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+=`
|
|
2058
|
+
`;break;case 114:k+="\r";break;case 116:k+=" ";break;case 117:let R=f(4,!0);R>=0?k+=String.fromCharCode(R):d=4;break;default:d=5}I=o;continue}if(v>=0&&v<=31)if(Oo(v)){k+=e.substring(I,o),d=2;break}else d=6;o++}return k}function h(){if(r="",d=0,s=o,c=a,u=l,o>=n)return s=n,i=17;let k=e.charCodeAt(o);if(Fa(k)){do o++,r+=String.fromCharCode(k),k=e.charCodeAt(o);while(Fa(k));return i=15}if(Oo(k))return o++,r+=String.fromCharCode(k),k===13&&e.charCodeAt(o)===10&&(o++,r+=`
|
|
2059
|
+
`),a++,l=o,i=14;switch(k){case 123:return o++,i=1;case 125:return o++,i=2;case 91:return o++,i=3;case 93:return o++,i=4;case 58:return o++,i=6;case 44:return o++,i=5;case 34:return o++,r=g(),i=10;case 47:let I=o-1;if(e.charCodeAt(o+1)===47){for(o+=2;o<n&&!Oo(e.charCodeAt(o));)o++;return r=e.substring(I,o),i=12}if(e.charCodeAt(o+1)===42){o+=2;let v=n-1,O=!1;for(;o<v;){let R=e.charCodeAt(o);if(R===42&&e.charCodeAt(o+1)===47){o+=2,O=!0;break}o++,Oo(R)&&(R===13&&e.charCodeAt(o)===10&&o++,a++,l=o)}return O||(o++,d=1),r=e.substring(I,o),i=13}return r+=String.fromCharCode(k),o++,i=16;case 45:if(r+=String.fromCharCode(k),o++,o===n||!Kn(e.charCodeAt(o)))return i=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return r+=p(),i=11;default:for(;o<n&&y(k);)o++,k=e.charCodeAt(o);if(s!==o){switch(r=e.substring(s,o),r){case"true":return i=8;case"false":return i=9;case"null":return i=7}return i=16}return r+=String.fromCharCode(k),o++,i=16}}function y(k){if(Fa(k)||Oo(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:()=>i,getTokenValue:()=>r,getTokenOffset:()=>s,getTokenLength:()=>o-s,getTokenStartLine:()=>c,getTokenStartCharacter:()=>s-u,getTokenError:()=>d}}function Fa(e){return e===32||e===9}function Oo(e){return e===10||e===13}function Kn(e){return e>=48&&e<=57}var uh;(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"})(uh||(uh={}));var PE=new Array(20).fill(0).map((e,t)=>" ".repeat(t)),Jn=200,AE={" ":{"\n":new Array(Jn).fill(0).map((e,t)=>`
|
|
2006
2060
|
`+" ".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
|
|
2007
2061
|
`+" ".repeat(t))}," ":{"\n":new Array(Jn).fill(0).map((e,t)=>`
|
|
2008
2062
|
`+" ".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
|
|
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(`
|
|
2063
|
+
`+" ".repeat(t))}};var Zr;(function(e){e.DEFAULT={allowTrailingComma:!1}})(Zr||(Zr={}));function dh(e,t=[],n=Zr.DEFAULT){let o=null,r=[],s=[];function i(c){Array.isArray(r)?r.push(c):o!==null&&(r[o]=c)}return ph(e,{onObjectBegin:()=>{let c={};i(c),s.push(r),r=c,o=null},onObjectProperty:c=>{o=c},onObjectEnd:()=>{r=s.pop()},onArrayBegin:()=>{let c=[];i(c),s.push(r),r=c,o=null},onArrayEnd:()=>{r=s.pop()},onLiteralValue:i,onError:(c,l,u)=>{t.push({error:c,offset:l,length:u})}},n),r[0]}function ph(e,t,n=Zr.DEFAULT){let o=Xr(e,!1),r=[],s=0;function i(C){return C?()=>s===0&&C(o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter()):()=>!0}function a(C){return C?N=>s===0&&C(N,o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter()):()=>!0}function c(C){return C?N=>s===0&&C(N,o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter(),()=>r.slice()):()=>!0}function l(C){return C?()=>{s>0?s++:C(o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter(),()=>r.slice())===!1&&(s=1)}:()=>!0}function u(C){return C?()=>{s>0&&s--,s===0&&C(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=i(t.onComment),k=a(t.onError),I=n&&n.disallowComments,v=n&&n.allowTrailingComma;function O(){for(;;){let C=o.scan();switch(o.getTokenError()){case 4:R(14);break;case 5:R(15);break;case 3:R(13);break;case 1:I||R(11);break;case 2:R(12);break;case 6:R(16);break}switch(C){case 12:case 13:I?R(10):w();break;case 16:R(1);break;case 15:case 14:break;default:return C}}}function R(C,N=[],K=[]){if(k(C),N.length+K.length>0){let H=o.getToken();for(;H!==17;){if(N.indexOf(H)!==-1){O();break}else if(K.indexOf(H)!==-1)break;H=O()}}}function ee(C){let N=o.getTokenValue();return C?h(N):(f(N),r.push(N)),O(),!0}function S(){switch(o.getToken()){case 11:let C=o.getTokenValue(),N=Number(C);isNaN(N)&&(R(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 O(),!0}function P(){return o.getToken()!==10?(R(3,[],[2,5]),!1):(ee(!1),o.getToken()===6?(y(":"),O(),M()||R(4,[],[2,5])):R(5,[],[2,5]),r.pop(),!0)}function $(){d(),O();let C=!1;for(;o.getToken()!==2&&o.getToken()!==17;){if(o.getToken()===5){if(C||R(4,[],[]),y(","),O(),o.getToken()===2&&v)break}else C&&R(6,[],[]);P()||R(4,[],[2,5]),C=!0}return m(),o.getToken()!==2?R(7,[2],[]):O(),!0}function x(){p(),O();let C=!0,N=!1;for(;o.getToken()!==4&&o.getToken()!==17;){if(o.getToken()===5){if(N||R(4,[],[]),y(","),O(),o.getToken()===4&&v)break}else N&&R(6,[],[]);C?(r.push(0),C=!1):r[r.length-1]++,M()||R(4,[],[4,5]),N=!0}return g(),C||r.pop(),o.getToken()!==4?R(8,[4],[]):O(),!0}function M(){switch(o.getToken()){case 3:return x();case 1:return $();case 10:return ee(!0);default:return S()}}return O(),o.getToken()===17?n.allowEmptyContent?!0:(R(4,[],[]),!1):M()?(o.getToken()!==17&&R(9,[],[]),!0):(R(4,[],[]),!1)}var fh;(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"})(fh||(fh={}));var mh;(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"})(mh||(mh={}));var hh=dh;var gh;(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"})(gh||(gh={}));var FE={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:Ea,customPricing:[]}};function UE(){return{user:(0,ts.join)((0,kh.homedir)(),".claude","olympus","config.jsonc"),project:(0,ts.join)(process.cwd(),".claude","olympus.jsonc")}}function yh(e){if(!(0,ns.existsSync)(e))return null;try{let t=(0,ns.readFileSync)(e,"utf-8"),n=[],o=hh(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 es(e,t){let n={...e};for(let o of Object.keys(t)){let r=t[o],s=n[o];r!==void 0&&typeof r=="object"&&r!==null&&!Array.isArray(r)&&typeof s=="object"&&s!==null&&!Array.isArray(s)?n[o]=es(s,r):r!==void 0&&(n[o]=r)}return n}function WE(){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 wh(){let e=UE(),t={...FE},n=yh(e.user);n&&(t=es(t,n));let o=yh(e.project);o&&(t=es(t,o));let r=WE();return t=es(t,r),t}function HE(e){let t=e.hooks;return t&&typeof t.timeoutMs=="number"?t.timeoutMs:5e3}function BE(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 GE(e,t){return Promise.race([Promise.resolve(e()),new Promise(n=>setTimeout(()=>n(null),t))])}function qE(e,t){return!e||!t?!0:(typeof e=="string"?new RegExp(e,"i"):e).test(t)}async function _h(e,t){let n=wh(),o=Wa(e),r=HE(n),s=!0,i=[],a,c=t.toolInput,l=t.messages;for(let u of o)if(BE(n,u.name)&&qE(u.matcher,t.toolName))try{let d=await GE(()=>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||(s=!1,a=d.stopReason),d.message&&i.push(d.message),d.hookSpecificOutput?.additionalContext&&i.push(d.hookSpecificOutput.additionalContext),d.modifiedInput!==void 0&&(c=d.modifiedInput),d.modifiedMessages!==void 0&&(l=d.modifiedMessages)}catch(d){console.error(`[hook-router] ${u.name} error:`,d)}return{continue:s,message:i.length>0?i.join(`
|
|
2010
2064
|
|
|
2011
2065
|
---
|
|
2012
2066
|
|
|
2013
|
-
`):void 0,stopReason:a,modifiedInput:c!==t.toolInput?c:void 0,modifiedMessages:l!==t.messages?l:void 0}}
|
|
2067
|
+
`):void 0,stopReason:a,modifiedInput:c!==t.toolInput?c:void 0,modifiedMessages:l!==t.messages?l:void 0}}lh();async function VE(){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 Sh(){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 VE(),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 s=await _h(n,r),i={continue:s.continue};s.stopReason&&(i.stopReason=s.stopReason),s.message&&(n==="PreToolUse"||n==="UserPromptSubmit"||n==="PostToolUse"?i.hookSpecificOutput={hookEventName:n,additionalContext:s.message}:i.reason=s.message),console.log(JSON.stringify(i)),process.exit(0)}var os=process.argv[1]||"",YE=os.endsWith("entry.ts")||os.endsWith("entry.js")||os.endsWith("olympus-hooks.mjs")||os.includes("olympus-hooks");YE&&Sh().catch(e=>{console.error("[olympus-hooks] Fatal error:",e),process.exit(1)});0&&(module.exports={main});
|