olympus-ai 4.5.13 → 4.5.14
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/cli/index.js +63 -27
- package/dist/cli/index.js.map +1 -1
- package/dist/hooks/olympus-hooks.cjs +257 -257
- package/dist/installer/hooks.d.ts +47 -14
- package/dist/installer/hooks.d.ts.map +1 -1
- package/dist/installer/hooks.js +45 -77
- package/dist/installer/hooks.js.map +1 -1
- package/dist/installer/index.d.ts +8 -7
- package/dist/installer/index.d.ts.map +1 -1
- package/dist/installer/index.js +49 -46
- package/dist/installer/index.js.map +1 -1
- package/package.json +1 -1
- package/resources/config/risk-keywords.json +5 -5
- package/resources/rules/common/ascii-diagram-standards.md +115 -115
- package/resources/rules/common/content-validation.md +131 -131
- package/resources/rules/common/error-handling.md +430 -430
- package/resources/rules/common/markdown-formatting.md +170 -170
- package/resources/rules/common/overconfidence-prevention.md +100 -100
- package/resources/rules/common/pathway-behaviors.json +60 -60
- package/resources/rules/common/pathway-behaviors.md +100 -100
- package/resources/rules/common/process-overview.md +157 -157
- package/resources/rules/common/terminal-formatting.md +161 -161
- package/resources/rules/common/terminology.md +189 -189
- package/resources/rules/common/welcome-message.md +118 -118
- package/resources/rules/common/workflow-changes.md +285 -285
- package/resources/rules/construction/bolt-planning.md +153 -153
- package/resources/rules/construction/bolt-review.md +143 -143
- package/resources/rules/construction/build-and-test.md +527 -527
- package/resources/rules/construction/code-generation.md +414 -414
- package/resources/rules/construction/documentation.md +201 -201
- package/resources/rules/construction/functional-design.md +135 -135
- package/resources/rules/construction/infrastructure-design.md +110 -110
- package/resources/rules/construction/nfr-design.md +106 -106
- package/resources/rules/construction/nfr-requirements.md +118 -118
- package/resources/rules/construction/test-generation.md +112 -112
- package/resources/rules/core-workflow.md +196 -196
- package/resources/rules/inception/application-design.md +195 -195
- package/resources/rules/inception/bolt-planning.md +588 -588
- package/resources/rules/inception/reverse-engineering.md +354 -354
- package/resources/rules/inception/units-generation.md +505 -505
- package/resources/rules/inception/user-stories.md +527 -527
- package/resources/rules/inception/workspace-detection.md +82 -82
- package/resources/rules/operations/operations.md +19 -19
- package/resources/skills/brief/templates/ai-dlc-intent-brief-template.md +149 -149
- package/resources/skills/getting-started/SKILL.md +79 -79
- package/resources/templates/construction/bolt-spec-template.md +270 -270
- package/resources/templates/inception/unit-brief-template.md +188 -188
- package/resources/templates/inception/units-template.md +99 -99
|
@@ -1,38 +1,38 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// Olympus Hooks Bundle - Generated by esbuild
|
|
3
|
-
"use strict";var
|
|
4
|
-
`).filter(s=>s.trim()).length;if(o>=t){let s=new Date().toISOString().replace(/[:.]/g,"-"),i=e.replace(".jsonl",`.${s}.old.jsonl`);(0,z.renameSync)(e,i),console.log(`[Olympus Learning] Archived ${o} entries to ${i}`),
|
|
5
|
-
`,"utf-8");return}catch(n){console.error("[Olympus Learning] Project write failed, using global fallback:",n)}
|
|
6
|
-
`,"utf-8")}function
|
|
7
|
-
`).filter(r=>r.trim()).map(r=>JSON.parse(r)):[]}function
|
|
8
|
-
`,"utf-8");return}catch(r){console.error("[Olympus Learning] Project session summary write failed, using global fallback:",r)}
|
|
9
|
-
`,"utf-8")}var cu,se,z,lu,z_,au,we=U(()=>{"use strict";cu=require("os"),se=require("path"),z=require("fs"),lu=require("crypto");nu();ru();iu();z_=1e4,au=500});function wn(e,t){return!t||t.sample_count<5?1e4:e&&t.by_task_type[e]!==void 0?t.by_task_type[e]:t.overall_avg}var Ei=U(()=>{"use strict"});function gu(e){return(0,fu.join)(e,".olympus","session-state.json")}function pu(e,t){let n=wn();return{session_id:e||(0,mu.randomUUID)(),started_at:new Date().toISOString(),last_updated:new Date().toISOString(),recent_prompts:[],pending_completion:null,todo_snapshot:null,token_budget:{session_baseline:n,current_usage:0,input_tokens:0,output_tokens:0,warning_threshold:1.5,warning_issued:!1,started_at:new Date().toISOString()},discovery_volume:{session_count:0,daily_count:0,daily_reset_at:new Date().toISOString()},resolved_project_root:null}}function Q(e,t){let n=gu(e),r=_e(n,null);if(!r)return pu(t,e);let o=new Date(r.last_updated).getTime();if(Date.now()-o>nk)return pu(t,e);if(t&&r.session_id!==t&&(r.session_id=t),r.token_budget)r.token_budget.input_tokens===void 0&&(r.token_budget.input_tokens=0),r.token_budget.output_tokens===void 0&&(r.token_budget.output_tokens=0);else{let i=wn();r.token_budget={session_baseline:i,current_usage:0,input_tokens:0,output_tokens:0,warning_threshold:1.5,warning_issued:!1,started_at:r.started_at}}return r.discovery_volume||(r.discovery_volume={session_count:0,daily_count:0,daily_reset_at:new Date().toISOString()}),r.resolved_project_root===void 0&&(r.resolved_project_root=null),r}function ee(e,t){let n=gu(e);t.last_updated=new Date().toISOString(),at(n,t)}function hu(e,t,n){let r={prompt:t,timestamp:new Date().toISOString(),detected_feedback:n};return e.recent_prompts=[r,...e.recent_prompts].slice(0,tk),e.last_updated=new Date().toISOString(),e}function yu(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 wu(e){return e.pending_completion=null,e.last_updated=new Date().toISOString(),e}function xo(e){if(!e.pending_completion?.claimed_at)return!1;let t=new Date(e.pending_completion.claimed_at).getTime();return Date.now()-t<300*1e3}function _u(e,t){let n=wn();return e.token_budget={session_baseline:n,current_usage:0,input_tokens:0,output_tokens:0,warning_threshold:1.5,warning_issued:!1,started_at:new Date().toISOString()},e.last_updated=new Date().toISOString(),e}function ku(e,t){return e.token_budget||(e.token_budget={session_baseline:wn(),current_usage:0,input_tokens:0,output_tokens:0,warning_threshold:1.5,warning_issued:!1,started_at:new Date().toISOString()}),e.token_budget.current_usage+=t,e.last_updated=new Date().toISOString(),e}function Su(e){return e.token_budget&&(e.token_budget.warning_issued=!0,e.last_updated=new Date().toISOString()),e}function vu(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 bu(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 Eu(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 fu,mu,tk,nk,Be=U(()=>{"use strict";fu=require("path");we();mu=require("crypto");Ei();tk=10,nk=1800*1e3});var fe=V(Ci=>{"use strict";Ci.fromCallback=function(e){return Object.defineProperty(function(...t){if(typeof t[t.length-1]=="function")e.apply(this,t);else return new Promise((n,r)=>{t.push((o,s)=>o!=null?r(o):n(s)),e.apply(this,t)})},"name",{value:e.name})};Ci.fromPromise=function(e){return Object.defineProperty(function(...t){let n=t[t.length-1];if(typeof n!="function")return e.apply(this,t);t.pop(),e.apply(this,t).then(r=>n(null,r),n)},"name",{value:e.name})}});var Au=V((yI,Pu)=>{var Zt=require("constants"),ok=process.cwd,Po=null,sk=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return Po||(Po=ok.call(process)),Po};try{process.cwd()}catch{}typeof process.chdir=="function"&&(Ri=process.chdir,process.chdir=function(e){Po=null,Ri.call(process,e)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,Ri));var Ri;Pu.exports=ik;function ik(e){Zt.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&t(e),e.lutimes||n(e),e.chown=s(e.chown),e.fchown=s(e.fchown),e.lchown=s(e.lchown),e.chmod=r(e.chmod),e.fchmod=r(e.fchmod),e.lchmod=r(e.lchmod),e.chownSync=i(e.chownSync),e.fchownSync=i(e.fchownSync),e.lchownSync=i(e.lchownSync),e.chmodSync=o(e.chmodSync),e.fchmodSync=o(e.fchmodSync),e.lchmodSync=o(e.lchmodSync),e.stat=a(e.stat),e.fstat=a(e.fstat),e.lstat=a(e.lstat),e.statSync=c(e.statSync),e.fstatSync=c(e.fstatSync),e.lstatSync=c(e.lstatSync),e.chmod&&!e.lchmod&&(e.lchmod=function(u,d,p){p&&process.nextTick(p)},e.lchmodSync=function(){}),e.chown&&!e.lchown&&(e.lchown=function(u,d,p,f){f&&process.nextTick(f)},e.lchownSync=function(){}),sk==="win32"&&(e.rename=typeof e.rename!="function"?e.rename:(function(u){function d(p,f,m){var g=Date.now(),y=0;u(p,f,function w(_){if(_&&(_.code==="EACCES"||_.code==="EPERM"||_.code==="EBUSY")&&Date.now()-g<6e4){setTimeout(function(){e.stat(f,function(h,b){h&&h.code==="ENOENT"?u(p,f,w):m(_)})},y),y<100&&(y+=10);return}m&&m(_)})}return Object.setPrototypeOf&&Object.setPrototypeOf(d,u),d})(e.rename)),e.read=typeof e.read!="function"?e.read:(function(u){function d(p,f,m,g,y,w){var _;if(w&&typeof w=="function"){var h=0;_=function(b,S,T){if(b&&b.code==="EAGAIN"&&h<10)return h++,u.call(e,p,f,m,g,y,_);w.apply(this,arguments)}}return u.call(e,p,f,m,g,y,_)}return Object.setPrototypeOf&&Object.setPrototypeOf(d,u),d})(e.read),e.readSync=typeof e.readSync!="function"?e.readSync:(function(u){return function(d,p,f,m,g){for(var y=0;;)try{return u.call(e,d,p,f,m,g)}catch(w){if(w.code==="EAGAIN"&&y<10){y++;continue}throw w}}})(e.readSync);function t(u){u.lchmod=function(d,p,f){u.open(d,Zt.O_WRONLY|Zt.O_SYMLINK,p,function(m,g){if(m){f&&f(m);return}u.fchmod(g,p,function(y){u.close(g,function(w){f&&f(y||w)})})})},u.lchmodSync=function(d,p){var f=u.openSync(d,Zt.O_WRONLY|Zt.O_SYMLINK,p),m=!0,g;try{g=u.fchmodSync(f,p),m=!1}finally{if(m)try{u.closeSync(f)}catch{}else u.closeSync(f)}return g}}function n(u){Zt.hasOwnProperty("O_SYMLINK")&&u.futimes?(u.lutimes=function(d,p,f,m){u.open(d,Zt.O_SYMLINK,function(g,y){if(g){m&&m(g);return}u.futimes(y,p,f,function(w){u.close(y,function(_){m&&m(w||_)})})})},u.lutimesSync=function(d,p,f){var m=u.openSync(d,Zt.O_SYMLINK),g,y=!0;try{g=u.futimesSync(m,p,f),y=!1}finally{if(y)try{u.closeSync(m)}catch{}else u.closeSync(m)}return g}):u.futimes&&(u.lutimes=function(d,p,f,m){m&&process.nextTick(m)},u.lutimesSync=function(){})}function r(u){return u&&function(d,p,f){return u.call(e,d,p,function(m){l(m)&&(m=null),f&&f.apply(this,arguments)})}}function o(u){return u&&function(d,p){try{return u.call(e,d,p)}catch(f){if(!l(f))throw f}}}function s(u){return u&&function(d,p,f,m){return u.call(e,d,p,f,function(g){l(g)&&(g=null),m&&m.apply(this,arguments)})}}function i(u){return u&&function(d,p,f){try{return u.call(e,d,p,f)}catch(m){if(!l(m))throw m}}}function a(u){return u&&function(d,p,f){typeof p=="function"&&(f=p,p=null);function m(g,y){y&&(y.uid<0&&(y.uid+=4294967296),y.gid<0&&(y.gid+=4294967296)),f&&f.apply(this,arguments)}return p?u.call(e,d,p,m):u.call(e,d,m)}}function c(u){return u&&function(d,p){var f=p?u.call(e,d,p):u.call(e,d);return f&&(f.uid<0&&(f.uid+=4294967296),f.gid<0&&(f.gid+=4294967296)),f}}function l(u){if(!u||u.code==="ENOSYS")return!0;var d=!process.getuid||process.getuid()!==0;return!!(d&&(u.code==="EINVAL"||u.code==="EPERM"))}}});var $u=V((wI,Ou)=>{var Iu=require("stream").Stream;Ou.exports=ak;function ak(e){return{ReadStream:t,WriteStream:n};function t(r,o){if(!(this instanceof t))return new t(r,o);Iu.call(this);var s=this;this.path=r,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=64*1024,o=o||{};for(var i=Object.keys(o),a=0,c=i.length;a<c;a++){var l=i[a];this[l]=o[l]}if(this.encoding&&this.setEncoding(this.encoding),this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.end===void 0)this.end=1/0;else if(typeof this.end!="number")throw TypeError("end must be a Number");if(this.start>this.end)throw new Error("start must be <= end");this.pos=this.start}if(this.fd!==null){process.nextTick(function(){s._read()});return}e.open(this.path,this.flags,this.mode,function(u,d){if(u){s.emit("error",u),s.readable=!1;return}s.fd=d,s.emit("open",d),s._read()})}function n(r,o){if(!(this instanceof n))return new n(r,o);Iu.call(this),this.path=r,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,o=o||{};for(var s=Object.keys(o),i=0,a=s.length;i<a;i++){var c=s[i];this[c]=o[c]}if(this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.start<0)throw new Error("start must be >= zero");this.pos=this.start}this.busy=!1,this._queue=[],this.fd===null&&(this._open=e.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}});var Nu=V((_I,Du)=>{"use strict";Du.exports=lk;var ck=Object.getPrototypeOf||function(e){return e.__proto__};function lk(e){if(e===null||typeof e!="object")return e;if(e instanceof Object)var t={__proto__:ck(e)};else var t=Object.create(null);return Object.getOwnPropertyNames(e).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(e,n))}),t}});var Yn=V((kI,Ai)=>{var ne=require("fs"),uk=Au(),dk=$u(),pk=Nu(),Ao=require("util"),ke,Oo;typeof Symbol=="function"&&typeof Symbol.for=="function"?(ke=Symbol.for("graceful-fs.queue"),Oo=Symbol.for("graceful-fs.previous")):(ke="___graceful-fs.queue",Oo="___graceful-fs.previous");function fk(){}function Mu(e,t){Object.defineProperty(e,ke,{get:function(){return t}})}var _n=fk;Ao.debuglog?_n=Ao.debuglog("gfs4"):/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&(_n=function(){var e=Ao.format.apply(Ao,arguments);e="GFS4: "+e.split(/\n/).join(`
|
|
10
|
-
GFS4: `),console.error(e)});ne[ke]||(ju=global[ke]||[],Mu(ne,ju),ne.close=(function(e){function t(n,r){return e.call(ne,n,function(o){o||Fu(),typeof r=="function"&&r.apply(this,arguments)})}return Object.defineProperty(t,Oo,{value:e}),t})(ne.close),ne.closeSync=(function(e){function t(n){e.apply(ne,arguments),Fu()}return Object.defineProperty(t,Oo,{value:e}),t})(ne.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&process.on("exit",function(){_n(ne[ke]),require("assert").equal(ne[ke].length,0)}));var ju;global[ke]||Mu(global,ne[ke]);Ai.exports=xi(pk(ne));process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!ne.__patched&&(Ai.exports=xi(ne),ne.__patched=!0);function xi(e){uk(e),e.gracefulify=xi,e.createReadStream=S,e.createWriteStream=T;var t=e.readFile;e.readFile=n;function n(R,O,C){return typeof O=="function"&&(C=O,O=null),$(R,O,C);function $(D,x,E,L){return t(D,x,function(j){j&&(j.code==="EMFILE"||j.code==="ENFILE")?Vn([$,[D,x,E],j,L||Date.now(),Date.now()]):typeof E=="function"&&E.apply(this,arguments)})}}var r=e.writeFile;e.writeFile=o;function o(R,O,C,$){return typeof C=="function"&&($=C,C=null),D(R,O,C,$);function D(x,E,L,j,K){return r(x,E,L,function(q){q&&(q.code==="EMFILE"||q.code==="ENFILE")?Vn([D,[x,E,L,j],q,K||Date.now(),Date.now()]):typeof j=="function"&&j.apply(this,arguments)})}}var s=e.appendFile;s&&(e.appendFile=i);function i(R,O,C,$){return typeof C=="function"&&($=C,C=null),D(R,O,C,$);function D(x,E,L,j,K){return s(x,E,L,function(q){q&&(q.code==="EMFILE"||q.code==="ENFILE")?Vn([D,[x,E,L,j],q,K||Date.now(),Date.now()]):typeof j=="function"&&j.apply(this,arguments)})}}var a=e.copyFile;a&&(e.copyFile=c);function c(R,O,C,$){return typeof C=="function"&&($=C,C=0),D(R,O,C,$);function D(x,E,L,j,K){return a(x,E,L,function(q){q&&(q.code==="EMFILE"||q.code==="ENFILE")?Vn([D,[x,E,L,j],q,K||Date.now(),Date.now()]):typeof j=="function"&&j.apply(this,arguments)})}}var l=e.readdir;e.readdir=d;var u=/^v[0-5]\./;function d(R,O,C){typeof O=="function"&&(C=O,O=null);var $=u.test(process.version)?function(E,L,j,K){return l(E,D(E,L,j,K))}:function(E,L,j,K){return l(E,L,D(E,L,j,K))};return $(R,O,C);function D(x,E,L,j){return function(K,q){K&&(K.code==="EMFILE"||K.code==="ENFILE")?Vn([$,[x,E,L],K,j||Date.now(),Date.now()]):(q&&q.sort&&q.sort(),typeof L=="function"&&L.call(this,K,q))}}}if(process.version.substr(0,4)==="v0.8"){var p=dk(e);w=p.ReadStream,h=p.WriteStream}var f=e.ReadStream;f&&(w.prototype=Object.create(f.prototype),w.prototype.open=_);var m=e.WriteStream;m&&(h.prototype=Object.create(m.prototype),h.prototype.open=b),Object.defineProperty(e,"ReadStream",{get:function(){return w},set:function(R){w=R},enumerable:!0,configurable:!0}),Object.defineProperty(e,"WriteStream",{get:function(){return h},set:function(R){h=R},enumerable:!0,configurable:!0});var g=w;Object.defineProperty(e,"FileReadStream",{get:function(){return g},set:function(R){g=R},enumerable:!0,configurable:!0});var y=h;Object.defineProperty(e,"FileWriteStream",{get:function(){return y},set:function(R){y=R},enumerable:!0,configurable:!0});function w(R,O){return this instanceof w?(f.apply(this,arguments),this):w.apply(Object.create(w.prototype),arguments)}function _(){var R=this;F(R.path,R.flags,R.mode,function(O,C){O?(R.autoClose&&R.destroy(),R.emit("error",O)):(R.fd=C,R.emit("open",C),R.read())})}function h(R,O){return this instanceof h?(m.apply(this,arguments),this):h.apply(Object.create(h.prototype),arguments)}function b(){var R=this;F(R.path,R.flags,R.mode,function(O,C){O?(R.destroy(),R.emit("error",O)):(R.fd=C,R.emit("open",C))})}function S(R,O){return new e.ReadStream(R,O)}function T(R,O){return new e.WriteStream(R,O)}var k=e.open;e.open=F;function F(R,O,C,$){return typeof C=="function"&&($=C,C=null),D(R,O,C,$);function D(x,E,L,j,K){return k(x,E,L,function(q,hn){q&&(q.code==="EMFILE"||q.code==="ENFILE")?Vn([D,[x,E,L,j],q,K||Date.now(),Date.now()]):typeof j=="function"&&j.apply(this,arguments)})}}return e}function Vn(e){_n("ENQUEUE",e[0].name,e[1]),ne[ke].push(e),Pi()}var Io;function Fu(){for(var e=Date.now(),t=0;t<ne[ke].length;++t)ne[ke][t].length>2&&(ne[ke][t][3]=e,ne[ke][t][4]=e);Pi()}function Pi(){if(clearTimeout(Io),Io=void 0,ne[ke].length!==0){var e=ne[ke].shift(),t=e[0],n=e[1],r=e[2],o=e[3],s=e[4];if(o===void 0)_n("RETRY",t.name,n),t.apply(null,n);else if(Date.now()-o>=6e4){_n("TIMEOUT",t.name,n);var i=n.pop();typeof i=="function"&&i.call(null,r)}else{var a=Date.now()-s,c=Math.max(s-o,1),l=Math.min(c*1.2,100);a>=l?(_n("RETRY",t.name,n),t.apply(null,n.concat([o]))):ne[ke].push(e)}Io===void 0&&(Io=setTimeout(Pi,0))}}});var Re=V(Dt=>{"use strict";var Lu=fe().fromCallback,Ce=Yn(),mk=["access","appendFile","chmod","chown","close","copyFile","cp","fchmod","fchown","fdatasync","fstat","fsync","ftruncate","futimes","glob","lchmod","lchown","lutimes","link","lstat","mkdir","mkdtemp","open","opendir","readdir","readFile","readlink","realpath","rename","rm","rmdir","stat","statfs","symlink","truncate","unlink","utimes","writeFile"].filter(e=>typeof Ce[e]=="function");Object.assign(Dt,Ce);mk.forEach(e=>{Dt[e]=Lu(Ce[e])});Dt.exists=function(e,t){return typeof t=="function"?Ce.exists(e,t):new Promise(n=>Ce.exists(e,n))};Dt.read=function(e,t,n,r,o,s){return typeof s=="function"?Ce.read(e,t,n,r,o,s):new Promise((i,a)=>{Ce.read(e,t,n,r,o,(c,l,u)=>{if(c)return a(c);i({bytesRead:l,buffer:u})})})};Dt.write=function(e,t,...n){return typeof n[n.length-1]=="function"?Ce.write(e,t,...n):new Promise((r,o)=>{Ce.write(e,t,...n,(s,i,a)=>{if(s)return o(s);r({bytesWritten:i,buffer:a})})})};Dt.readv=function(e,t,...n){return typeof n[n.length-1]=="function"?Ce.readv(e,t,...n):new Promise((r,o)=>{Ce.readv(e,t,...n,(s,i,a)=>{if(s)return o(s);r({bytesRead:i,buffers:a})})})};Dt.writev=function(e,t,...n){return typeof n[n.length-1]=="function"?Ce.writev(e,t,...n):new Promise((r,o)=>{Ce.writev(e,t,...n,(s,i,a)=>{if(s)return o(s);r({bytesWritten:i,buffers:a})})})};typeof Ce.realpath.native=="function"?Dt.realpath.native=Lu(Ce.realpath.native):process.emitWarning("fs.realpath.native is not a function. Is fs being monkey-patched?","Warning","fs-extra-WARN0003")});var Wu=V((vI,Uu)=>{"use strict";var gk=require("path");Uu.exports.checkPath=function(t){if(process.platform==="win32"&&/[<>:"|?*]/.test(t.replace(gk.parse(t).root,""))){let r=new Error(`Path contains invalid characters: ${t}`);throw r.code="EINVAL",r}}});var qu=V((bI,Ii)=>{"use strict";var Bu=Re(),{checkPath:Gu}=Wu(),Hu=e=>{let t={mode:511};return typeof e=="number"?e:{...t,...e}.mode};Ii.exports.makeDir=async(e,t)=>(Gu(e),Bu.mkdir(e,{mode:Hu(t),recursive:!0}));Ii.exports.makeDirSync=(e,t)=>(Gu(e),Bu.mkdirSync(e,{mode:Hu(t),recursive:!0}))});var ct=V((EI,Vu)=>{"use strict";var hk=fe().fromPromise,{makeDir:yk,makeDirSync:Oi}=qu(),$i=hk(yk);Vu.exports={mkdirs:$i,mkdirsSync:Oi,mkdirp:$i,mkdirpSync:Oi,ensureDir:$i,ensureDirSync:Oi}});var en=V((TI,Ku)=>{"use strict";var wk=fe().fromPromise,Yu=Re();function _k(e){return Yu.access(e).then(()=>!0).catch(()=>!1)}Ku.exports={pathExists:wk(_k),pathExistsSync:Yu.existsSync}});var Di=V((CI,Ju)=>{"use strict";var Kn=Re(),kk=fe().fromPromise;async function Sk(e,t,n){let r=await Kn.open(e,"r+"),o=null;try{await Kn.futimes(r,t,n)}finally{try{await Kn.close(r)}catch(s){o=s}}if(o)throw o}function vk(e,t,n){let r=Kn.openSync(e,"r+");return Kn.futimesSync(r,t,n),Kn.closeSync(r)}Ju.exports={utimesMillis:kk(Sk),utimesMillisSync:vk}});var kn=V((RI,Zu)=>{"use strict";var Jn=Re(),me=require("path"),zu=fe().fromPromise;function bk(e,t,n){let r=n.dereference?o=>Jn.stat(o,{bigint:!0}):o=>Jn.lstat(o,{bigint:!0});return Promise.all([r(e),r(t).catch(o=>{if(o.code==="ENOENT")return null;throw o})]).then(([o,s])=>({srcStat:o,destStat:s}))}function Ek(e,t,n){let r,o=n.dereference?i=>Jn.statSync(i,{bigint:!0}):i=>Jn.lstatSync(i,{bigint:!0}),s=o(e);try{r=o(t)}catch(i){if(i.code==="ENOENT")return{srcStat:s,destStat:null};throw i}return{srcStat:s,destStat:r}}async function Tk(e,t,n,r){let{srcStat:o,destStat:s}=await bk(e,t,r);if(s){if(Nr(o,s)){let i=me.basename(e),a=me.basename(t);if(n==="move"&&i!==a&&i.toLowerCase()===a.toLowerCase())return{srcStat:o,destStat:s,isChangingCase:!0};throw new Error("Source and destination must not be the same.")}if(o.isDirectory()&&!s.isDirectory())throw new Error(`Cannot overwrite non-directory '${t}' with directory '${e}'.`);if(!o.isDirectory()&&s.isDirectory())throw new Error(`Cannot overwrite directory '${t}' with non-directory '${e}'.`)}if(o.isDirectory()&&Ni(e,t))throw new Error($o(e,t,n));return{srcStat:o,destStat:s}}function Ck(e,t,n,r){let{srcStat:o,destStat:s}=Ek(e,t,r);if(s){if(Nr(o,s)){let i=me.basename(e),a=me.basename(t);if(n==="move"&&i!==a&&i.toLowerCase()===a.toLowerCase())return{srcStat:o,destStat:s,isChangingCase:!0};throw new Error("Source and destination must not be the same.")}if(o.isDirectory()&&!s.isDirectory())throw new Error(`Cannot overwrite non-directory '${t}' with directory '${e}'.`);if(!o.isDirectory()&&s.isDirectory())throw new Error(`Cannot overwrite directory '${t}' with non-directory '${e}'.`)}if(o.isDirectory()&&Ni(e,t))throw new Error($o(e,t,n));return{srcStat:o,destStat:s}}async function Qu(e,t,n,r){let o=me.resolve(me.dirname(e)),s=me.resolve(me.dirname(n));if(s===o||s===me.parse(s).root)return;let i;try{i=await Jn.stat(s,{bigint:!0})}catch(a){if(a.code==="ENOENT")return;throw a}if(Nr(t,i))throw new Error($o(e,n,r));return Qu(e,t,s,r)}function Xu(e,t,n,r){let o=me.resolve(me.dirname(e)),s=me.resolve(me.dirname(n));if(s===o||s===me.parse(s).root)return;let i;try{i=Jn.statSync(s,{bigint:!0})}catch(a){if(a.code==="ENOENT")return;throw a}if(Nr(t,i))throw new Error($o(e,n,r));return Xu(e,t,s,r)}function Nr(e,t){return t.ino!==void 0&&t.dev!==void 0&&t.ino===e.ino&&t.dev===e.dev}function Ni(e,t){let n=me.resolve(e).split(me.sep).filter(o=>o),r=me.resolve(t).split(me.sep).filter(o=>o);return n.every((o,s)=>r[s]===o)}function $o(e,t,n){return`Cannot ${n} '${e}' to a subdirectory of itself, '${t}'.`}Zu.exports={checkPaths:zu(Tk),checkPathsSync:Ck,checkParentPaths:zu(Qu),checkParentPathsSync:Xu,isSrcSubdir:Ni,areIdentical:Nr}});var td=V((xI,ed)=>{"use strict";async function Rk(e,t){let n=[];for await(let r of e)n.push(t(r).then(()=>null,o=>o??new Error("unknown error")));await Promise.all(n.map(r=>r.then(o=>{if(o!==null)throw o})))}ed.exports={asyncIteratorConcurrentProcess:Rk}});var id=V((PI,sd)=>{"use strict";var ve=Re(),jr=require("path"),{mkdirs:xk}=ct(),{pathExists:Pk}=en(),{utimesMillis:Ak}=Di(),Fr=kn(),{asyncIteratorConcurrentProcess:Ik}=td();async function Ok(e,t,n={}){typeof n=="function"&&(n={filter:n}),n.clobber="clobber"in n?!!n.clobber:!0,n.overwrite="overwrite"in n?!!n.overwrite:n.clobber,n.preserveTimestamps&&process.arch==="ia32"&&process.emitWarning(`Using the preserveTimestamps option in 32-bit node is not recommended;
|
|
3
|
+
"use strict";var v_=Object.create;var _o=Object.defineProperty;var b_=Object.getOwnPropertyDescriptor;var E_=Object.getOwnPropertyNames;var T_=Object.getPrototypeOf,C_=Object.prototype.hasOwnProperty;var U=(e,t)=>()=>(e&&(t=e(e=0)),t);var V=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),he=(e,t)=>{for(var n in t)_o(e,n,{get:t[n],enumerable:!0})},Sl=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of E_(t))!C_.call(e,o)&&o!==n&&_o(e,o,{get:()=>t[o],enumerable:!(r=b_(t,o))||r.enumerable});return e};var v=(e,t,n)=>(n=e!=null?v_(T_(e)):{},Sl(t||!e||!e.__esModule?_o(n,"default",{value:e,enumerable:!0}):n,e)),R_=e=>Sl(_o({},"__esModule",{value:!0}),e);var ki,tu=U(()=>{"use strict";ki={maxAgeInDays:30,maxArchiveCount:5}});function Si(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 Ln(e){return Si(e)?.total_tokens||0}var nu=U(()=>{"use strict"});function z_(e){let t=(0,Un.basename)(e);(!t||/^[A-Za-z]:[\\/]?$/.test(e)||/^[A-Za-z]:$/.test(t))&&(t="root");let n=t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"").substring(0,30);n||(n="unknown");let r=(0,ou.createHash)("sha256").update(e).digest("hex").substring(0,8);return`${n}-${r}`}function gn(e){return(0,Un.join)(pe(),"projects",z_(e))}function vi(e){try{(0,ru.mkdirSync)(gn(e),{recursive:!0})}catch(t){t.code!=="EEXIST"&&console.error("Failed to create project directory:",t)}}var Un,J_,ru,ou,su=U(()=>{"use strict";Un=require("path"),J_=require("child_process"),ru=require("fs"),ou=require("crypto");ye();Ue()});function pe(){return process.env.OLYMPUS_TEST_LEARNING_DIR?process.env.OLYMPUS_TEST_LEARNING_DIR:(0,se.join)((0,au.homedir)(),".claude","olympus","learning")}function yt(e){return(0,se.join)(e,".olympus","learning")}function lu(e){let t=(0,se.resolve)(e);return(0,cu.createHash)("sha256").update(t).digest("hex").substring(0,16)}function Bn(e){let t=pe();if((0,z.existsSync)(t)||(0,z.mkdirSync)(t,{recursive:!0}),e){let n=yt(e);(0,z.existsSync)(n)||(0,z.mkdirSync)(n,{recursive:!0})}}function X_(e,t=ki){try{let n=(0,se.dirname)(e),r=(0,se.basename)(e,".jsonl"),o=(0,z.readdirSync)(n),s=new RegExp(`^${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\..*\\.old\\.jsonl$`),i=o.filter(d=>s.test(d)).map(d=>{let p=d.match(/\.(\d{4}-\d{2}-\d{2})T/),f=p?new Date(p[1]):null;return{filename:d,filepath:(0,se.join)(n,d),timestamp:f}}).filter(d=>d.timestamp!==null&&!isNaN(d.timestamp.getTime())).sort((d,p)=>p.timestamp.getTime()-d.timestamp.getTime()),a=t.maxAgeInDays??30,c=t.maxArchiveCount??5,l=new Date(Date.now()-a*24*60*60*1e3),u=0;for(let d=0;d<i.length;d++){let p=i[d],f=p.timestamp<l,m=d>=c;if(f||m)try{(0,z.unlinkSync)(p.filepath),u++}catch{}}u>0&&console.log(`[Olympus Learning] Pruned ${u} old archives`)}catch(n){console.error("[Olympus Learning] Failed to prune archives:",n)}}function Wn(e,t=Q_,n=ki){if((0,z.existsSync)(e))try{let o=(0,z.readFileSync)(e,"utf-8").split(`
|
|
4
|
+
`).filter(s=>s.trim()).length;if(o>=t){let s=new Date().toISOString().replace(/[:.]/g,"-"),i=e.replace(".jsonl",`.${s}.old.jsonl`);(0,z.renameSync)(e,i),console.log(`[Olympus Learning] Archived ${o} entries to ${i}`),X_(e,n)}}catch(r){console.error(`[Olympus Learning] Failed to rotate ${e}:`,r)}}function zt(e){if(e.project_path&&typeof e.project_path=="string")try{vi(e.project_path);let n=(0,se.join)(gn(e.project_path),"feedback-log.jsonl");Wn(n),(0,z.appendFileSync)(n,JSON.stringify(e)+`
|
|
5
|
+
`,"utf-8");return}catch(n){console.error("[Olympus Learning] Project write failed, using global fallback:",n)}Bn();let t=(0,se.join)(pe(),"feedback-log.jsonl");Wn(t),(0,z.appendFileSync)(t,JSON.stringify(e)+`
|
|
6
|
+
`,"utf-8")}function Eo(e){let t=e?(0,se.join)(gn(e),"feedback-log.jsonl"):(0,se.join)(pe(),"feedback-log.jsonl");return(0,z.existsSync)(t)?(0,z.readFileSync)(t,"utf-8").split(`
|
|
7
|
+
`).filter(r=>r.trim()).map(r=>JSON.parse(r)):[]}function Z_(e){let t=e.filter(o=>o.event_type==="revision"||o.event_type==="cancellation"),n=new Map;for(let o of t){let s=o.extracted_lesson||o.feedback_category||"unknown",i=n.get(s);i?(i.count++,i.examples.length<3&&i.examples.push(o.user_message.substring(0,100))):n.set(s,{count:1,examples:[o.user_message.substring(0,100)]})}let r=[];for(let[o,s]of n)s.count>=2&&r.push({pattern:o,count:s.count,examples:s.examples});return r}function ek(e){let t=[];return e>=.85&&t.push("high success rate"),t}function tk(e,t){let n=[];return e<.6&&n.push("low success rate"),t>2&&n.push("frequently cancelled"),n}function To(e,t,n){let r=t.filter(m=>m.agent_used===e);if(r.length===0)return null;let o=r.length,s=r.filter(m=>m.event_type==="success").length,i=r.filter(m=>m.event_type==="revision").length,a=r.filter(m=>m.event_type==="cancellation").length,c=o>0?s/o:0,l,u=r.filter(m=>Si(m)!==null);if(u.length>0){let m=u.filter(S=>S.event_type==="success"),g=u.filter(S=>S.event_type==="revision"||S.event_type==="cancellation"),y=u.reduce((S,T)=>S+Ln(T),0),w=m.reduce((S,T)=>S+Ln(T),0),_=g.reduce((S,T)=>S+Ln(T),0),h=m.length>0?w/m.length:0,b=g.length>0?_/g.length:0;if(l={avg_tokens_per_success:h,avg_tokens_per_failure:b,total_tokens:y,invocation_count:u.length,efficiency_score:h,trend:"insufficient_data"},u.length>=10){let S=Math.floor(u.length/2),T=u.slice(0,S),k=u.slice(S),F=T.reduce(($,D)=>$+Ln(D),0)/T.length,O=k.reduce(($,D)=>$+Ln(D),0)/k.length-F,C=F*.1;Math.abs(O)<C?l.trend="stable":O<0?l.trend="improving":l.trend="declining"}}let d={agent_name:e,total_invocations:o,success_count:s,revision_count:i,cancellation_count:a,success_rate:c,failure_patterns:Z_(r),strong_areas:ek(c),weak_areas:tk(c,a),last_updated:new Date().toISOString(),token_efficiency:l};if(n)try{let m=(0,se.join)(gn(n),"agent-performance.json"),g=we(m,{});g[e]=d,st(m,g)}catch(m){console.error("[Olympus Learning] Failed to write project agent performance:",m)}let p=(0,se.join)(pe(),"agent-performance.json"),f=we(p,{});return f[e]=d,st(p,f),d}function Gn(e){let t=e?(0,se.join)(gn(e),"agent-performance.json"):(0,se.join)(pe(),"agent-performance.json");return we(t,{})}function we(e,t){if(!(0,z.existsSync)(e))return t;try{return JSON.parse((0,z.readFileSync)(e,"utf-8"))}catch(n){return console.error(`[Olympus Learning] Failed to read ${e}:`,n),t}}function st(e,t){try{let n=(0,se.dirname)(e);n&&!(0,z.existsSync)(n)&&(0,z.mkdirSync)(n,{recursive:!0}),(0,z.writeFileSync)(e,JSON.stringify(t,null,2),"utf-8")}catch(n){console.error(`[Olympus Learning] Failed to write ${e}:`,n)}}function uu(e,t){if(t)try{vi(t);let r=(0,se.join)(gn(t),"session-summaries.jsonl");Wn(r,iu),(0,z.appendFileSync)(r,JSON.stringify(e)+`
|
|
8
|
+
`,"utf-8");return}catch(r){console.error("[Olympus Learning] Project session summary write failed, using global fallback:",r)}Bn();let n=(0,se.join)(pe(),"session-summaries.jsonl");Wn(n,iu),(0,z.appendFileSync)(n,JSON.stringify(e)+`
|
|
9
|
+
`,"utf-8")}var au,se,z,cu,Q_,iu,ye=U(()=>{"use strict";au=require("os"),se=require("path"),z=require("fs"),cu=require("crypto");tu();nu();su();Q_=1e4,iu=500});function hn(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 bi=U(()=>{"use strict"});function mu(e){return(0,pu.join)(e,".olympus","session-state.json")}function du(e,t){let n=hn();return{session_id:e||(0,fu.randomUUID)(),started_at:new Date().toISOString(),last_updated:new Date().toISOString(),recent_prompts:[],pending_completion:null,todo_snapshot:null,token_budget:{session_baseline:n,current_usage:0,input_tokens:0,output_tokens:0,warning_threshold:1.5,warning_issued:!1,started_at:new Date().toISOString()},discovery_volume:{session_count:0,daily_count:0,daily_reset_at:new Date().toISOString()},resolved_project_root:null}}function Q(e,t){let n=mu(e),r=we(n,null);if(!r)return du(t,e);let o=new Date(r.last_updated).getTime();if(Date.now()-o>rk)return du(t,e);if(t&&r.session_id!==t&&(r.session_id=t),r.token_budget)r.token_budget.input_tokens===void 0&&(r.token_budget.input_tokens=0),r.token_budget.output_tokens===void 0&&(r.token_budget.output_tokens=0);else{let i=hn();r.token_budget={session_baseline:i,current_usage:0,input_tokens:0,output_tokens:0,warning_threshold:1.5,warning_issued:!1,started_at:r.started_at}}return r.discovery_volume||(r.discovery_volume={session_count:0,daily_count:0,daily_reset_at:new Date().toISOString()}),r.resolved_project_root===void 0&&(r.resolved_project_root=null),r}function ee(e,t){let n=mu(e);t.last_updated=new Date().toISOString(),st(n,t)}function gu(e,t,n){let r={prompt:t,timestamp:new Date().toISOString(),detected_feedback:n};return e.recent_prompts=[r,...e.recent_prompts].slice(0,nk),e.last_updated=new Date().toISOString(),e}function hu(e,t,n){return e.pending_completion={claimed_at:new Date().toISOString(),task_description:t,agent_used:n},e.last_updated=new Date().toISOString(),e}function yu(e){return e.pending_completion=null,e.last_updated=new Date().toISOString(),e}function Co(e){if(!e.pending_completion?.claimed_at)return!1;let t=new Date(e.pending_completion.claimed_at).getTime();return Date.now()-t<300*1e3}function wu(e,t){let n=hn();return e.token_budget={session_baseline:n,current_usage:0,input_tokens:0,output_tokens:0,warning_threshold:1.5,warning_issued:!1,started_at:new Date().toISOString()},e.last_updated=new Date().toISOString(),e}function _u(e,t){return e.token_budget||(e.token_budget={session_baseline:hn(),current_usage:0,input_tokens:0,output_tokens:0,warning_threshold:1.5,warning_issued:!1,started_at:new Date().toISOString()}),e.token_budget.current_usage+=t,e.last_updated=new Date().toISOString(),e}function ku(e){return e.token_budget&&(e.token_budget.warning_issued=!0,e.last_updated=new Date().toISOString()),e}function Su(e){if(!e.token_budget||e.token_budget.warning_issued)return!1;let t=e.token_budget.session_baseline*e.token_budget.warning_threshold;return e.token_budget.current_usage>=t}function vu(e){e.discovery_volume||(e.discovery_volume={session_count:0,daily_count:0,daily_reset_at:new Date().toISOString()});let t=new Date(e.discovery_volume.daily_reset_at),n=new Date;return n.toDateString()!==t.toDateString()&&(e.discovery_volume.daily_count=0,e.discovery_volume.daily_reset_at=n.toISOString()),e.discovery_volume.session_count++,e.discovery_volume.daily_count++,e.last_updated=n.toISOString(),e}function bu(e,t){if(!e.discovery_volume)return!1;let n=new Date(e.discovery_volume.daily_reset_at);return new Date().toDateString()!==n.toDateString()?!1:e.discovery_volume.session_count>=t.maxPerSession||e.discovery_volume.daily_count>=t.maxPerDay}var pu,fu,nk,rk,Ue=U(()=>{"use strict";pu=require("path");ye();fu=require("crypto");bi();nk=10,rk=1800*1e3});var fe=V(Ti=>{"use strict";Ti.fromCallback=function(e){return Object.defineProperty(function(...t){if(typeof t[t.length-1]=="function")e.apply(this,t);else return new Promise((n,r)=>{t.push((o,s)=>o!=null?r(o):n(s)),e.apply(this,t)})},"name",{value:e.name})};Ti.fromPromise=function(e){return Object.defineProperty(function(...t){let n=t[t.length-1];if(typeof n!="function")return e.apply(this,t);t.pop(),e.apply(this,t).then(r=>n(null,r),n)},"name",{value:e.name})}});var Pu=V((wI,xu)=>{var Qt=require("constants"),sk=process.cwd,Ro=null,ik=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return Ro||(Ro=sk.call(process)),Ro};try{process.cwd()}catch{}typeof process.chdir=="function"&&(Ci=process.chdir,process.chdir=function(e){Ro=null,Ci.call(process,e)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,Ci));var Ci;xu.exports=ak;function ak(e){Qt.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&t(e),e.lutimes||n(e),e.chown=s(e.chown),e.fchown=s(e.fchown),e.lchown=s(e.lchown),e.chmod=r(e.chmod),e.fchmod=r(e.fchmod),e.lchmod=r(e.lchmod),e.chownSync=i(e.chownSync),e.fchownSync=i(e.fchownSync),e.lchownSync=i(e.lchownSync),e.chmodSync=o(e.chmodSync),e.fchmodSync=o(e.fchmodSync),e.lchmodSync=o(e.lchmodSync),e.stat=a(e.stat),e.fstat=a(e.fstat),e.lstat=a(e.lstat),e.statSync=c(e.statSync),e.fstatSync=c(e.fstatSync),e.lstatSync=c(e.lstatSync),e.chmod&&!e.lchmod&&(e.lchmod=function(u,d,p){p&&process.nextTick(p)},e.lchmodSync=function(){}),e.chown&&!e.lchown&&(e.lchown=function(u,d,p,f){f&&process.nextTick(f)},e.lchownSync=function(){}),ik==="win32"&&(e.rename=typeof e.rename!="function"?e.rename:(function(u){function d(p,f,m){var g=Date.now(),y=0;u(p,f,function w(_){if(_&&(_.code==="EACCES"||_.code==="EPERM"||_.code==="EBUSY")&&Date.now()-g<6e4){setTimeout(function(){e.stat(f,function(h,b){h&&h.code==="ENOENT"?u(p,f,w):m(_)})},y),y<100&&(y+=10);return}m&&m(_)})}return Object.setPrototypeOf&&Object.setPrototypeOf(d,u),d})(e.rename)),e.read=typeof e.read!="function"?e.read:(function(u){function d(p,f,m,g,y,w){var _;if(w&&typeof w=="function"){var h=0;_=function(b,S,T){if(b&&b.code==="EAGAIN"&&h<10)return h++,u.call(e,p,f,m,g,y,_);w.apply(this,arguments)}}return u.call(e,p,f,m,g,y,_)}return Object.setPrototypeOf&&Object.setPrototypeOf(d,u),d})(e.read),e.readSync=typeof e.readSync!="function"?e.readSync:(function(u){return function(d,p,f,m,g){for(var y=0;;)try{return u.call(e,d,p,f,m,g)}catch(w){if(w.code==="EAGAIN"&&y<10){y++;continue}throw w}}})(e.readSync);function t(u){u.lchmod=function(d,p,f){u.open(d,Qt.O_WRONLY|Qt.O_SYMLINK,p,function(m,g){if(m){f&&f(m);return}u.fchmod(g,p,function(y){u.close(g,function(w){f&&f(y||w)})})})},u.lchmodSync=function(d,p){var f=u.openSync(d,Qt.O_WRONLY|Qt.O_SYMLINK,p),m=!0,g;try{g=u.fchmodSync(f,p),m=!1}finally{if(m)try{u.closeSync(f)}catch{}else u.closeSync(f)}return g}}function n(u){Qt.hasOwnProperty("O_SYMLINK")&&u.futimes?(u.lutimes=function(d,p,f,m){u.open(d,Qt.O_SYMLINK,function(g,y){if(g){m&&m(g);return}u.futimes(y,p,f,function(w){u.close(y,function(_){m&&m(w||_)})})})},u.lutimesSync=function(d,p,f){var m=u.openSync(d,Qt.O_SYMLINK),g,y=!0;try{g=u.futimesSync(m,p,f),y=!1}finally{if(y)try{u.closeSync(m)}catch{}else u.closeSync(m)}return g}):u.futimes&&(u.lutimes=function(d,p,f,m){m&&process.nextTick(m)},u.lutimesSync=function(){})}function r(u){return u&&function(d,p,f){return u.call(e,d,p,function(m){l(m)&&(m=null),f&&f.apply(this,arguments)})}}function o(u){return u&&function(d,p){try{return u.call(e,d,p)}catch(f){if(!l(f))throw f}}}function s(u){return u&&function(d,p,f,m){return u.call(e,d,p,f,function(g){l(g)&&(g=null),m&&m.apply(this,arguments)})}}function i(u){return u&&function(d,p,f){try{return u.call(e,d,p,f)}catch(m){if(!l(m))throw m}}}function a(u){return u&&function(d,p,f){typeof p=="function"&&(f=p,p=null);function m(g,y){y&&(y.uid<0&&(y.uid+=4294967296),y.gid<0&&(y.gid+=4294967296)),f&&f.apply(this,arguments)}return p?u.call(e,d,p,m):u.call(e,d,m)}}function c(u){return u&&function(d,p){var f=p?u.call(e,d,p):u.call(e,d);return f&&(f.uid<0&&(f.uid+=4294967296),f.gid<0&&(f.gid+=4294967296)),f}}function l(u){if(!u||u.code==="ENOSYS")return!0;var d=!process.getuid||process.getuid()!==0;return!!(d&&(u.code==="EINVAL"||u.code==="EPERM"))}}});var Ou=V((_I,Iu)=>{var Au=require("stream").Stream;Iu.exports=ck;function ck(e){return{ReadStream:t,WriteStream:n};function t(r,o){if(!(this instanceof t))return new t(r,o);Au.call(this);var s=this;this.path=r,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=64*1024,o=o||{};for(var i=Object.keys(o),a=0,c=i.length;a<c;a++){var l=i[a];this[l]=o[l]}if(this.encoding&&this.setEncoding(this.encoding),this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.end===void 0)this.end=1/0;else if(typeof this.end!="number")throw TypeError("end must be a Number");if(this.start>this.end)throw new Error("start must be <= end");this.pos=this.start}if(this.fd!==null){process.nextTick(function(){s._read()});return}e.open(this.path,this.flags,this.mode,function(u,d){if(u){s.emit("error",u),s.readable=!1;return}s.fd=d,s.emit("open",d),s._read()})}function n(r,o){if(!(this instanceof n))return new n(r,o);Au.call(this),this.path=r,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,o=o||{};for(var s=Object.keys(o),i=0,a=s.length;i<a;i++){var c=s[i];this[c]=o[c]}if(this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.start<0)throw new Error("start must be >= zero");this.pos=this.start}this.busy=!1,this._queue=[],this.fd===null&&(this._open=e.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}});var Du=V((kI,$u)=>{"use strict";$u.exports=uk;var lk=Object.getPrototypeOf||function(e){return e.__proto__};function uk(e){if(e===null||typeof e!="object")return e;if(e instanceof Object)var t={__proto__:lk(e)};else var t=Object.create(null);return Object.getOwnPropertyNames(e).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(e,n))}),t}});var qn=V((SI,Pi)=>{var ne=require("fs"),dk=Pu(),pk=Ou(),fk=Du(),xo=require("util"),_e,Ao;typeof Symbol=="function"&&typeof Symbol.for=="function"?(_e=Symbol.for("graceful-fs.queue"),Ao=Symbol.for("graceful-fs.previous")):(_e="___graceful-fs.queue",Ao="___graceful-fs.previous");function mk(){}function Fu(e,t){Object.defineProperty(e,_e,{get:function(){return t}})}var yn=mk;xo.debuglog?yn=xo.debuglog("gfs4"):/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&(yn=function(){var e=xo.format.apply(xo,arguments);e="GFS4: "+e.split(/\n/).join(`
|
|
10
|
+
GFS4: `),console.error(e)});ne[_e]||(Nu=global[_e]||[],Fu(ne,Nu),ne.close=(function(e){function t(n,r){return e.call(ne,n,function(o){o||ju(),typeof r=="function"&&r.apply(this,arguments)})}return Object.defineProperty(t,Ao,{value:e}),t})(ne.close),ne.closeSync=(function(e){function t(n){e.apply(ne,arguments),ju()}return Object.defineProperty(t,Ao,{value:e}),t})(ne.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&process.on("exit",function(){yn(ne[_e]),require("assert").equal(ne[_e].length,0)}));var Nu;global[_e]||Fu(global,ne[_e]);Pi.exports=Ri(fk(ne));process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!ne.__patched&&(Pi.exports=Ri(ne),ne.__patched=!0);function Ri(e){dk(e),e.gracefulify=Ri,e.createReadStream=S,e.createWriteStream=T;var t=e.readFile;e.readFile=n;function n(R,O,C){return typeof O=="function"&&(C=O,O=null),$(R,O,C);function $(D,x,E,L){return t(D,x,function(j){j&&(j.code==="EMFILE"||j.code==="ENFILE")?Hn([$,[D,x,E],j,L||Date.now(),Date.now()]):typeof E=="function"&&E.apply(this,arguments)})}}var r=e.writeFile;e.writeFile=o;function o(R,O,C,$){return typeof C=="function"&&($=C,C=null),D(R,O,C,$);function D(x,E,L,j,K){return r(x,E,L,function(q){q&&(q.code==="EMFILE"||q.code==="ENFILE")?Hn([D,[x,E,L,j],q,K||Date.now(),Date.now()]):typeof j=="function"&&j.apply(this,arguments)})}}var s=e.appendFile;s&&(e.appendFile=i);function i(R,O,C,$){return typeof C=="function"&&($=C,C=null),D(R,O,C,$);function D(x,E,L,j,K){return s(x,E,L,function(q){q&&(q.code==="EMFILE"||q.code==="ENFILE")?Hn([D,[x,E,L,j],q,K||Date.now(),Date.now()]):typeof j=="function"&&j.apply(this,arguments)})}}var a=e.copyFile;a&&(e.copyFile=c);function c(R,O,C,$){return typeof C=="function"&&($=C,C=0),D(R,O,C,$);function D(x,E,L,j,K){return a(x,E,L,function(q){q&&(q.code==="EMFILE"||q.code==="ENFILE")?Hn([D,[x,E,L,j],q,K||Date.now(),Date.now()]):typeof j=="function"&&j.apply(this,arguments)})}}var l=e.readdir;e.readdir=d;var u=/^v[0-5]\./;function d(R,O,C){typeof O=="function"&&(C=O,O=null);var $=u.test(process.version)?function(E,L,j,K){return l(E,D(E,L,j,K))}:function(E,L,j,K){return l(E,L,D(E,L,j,K))};return $(R,O,C);function D(x,E,L,j){return function(K,q){K&&(K.code==="EMFILE"||K.code==="ENFILE")?Hn([$,[x,E,L],K,j||Date.now(),Date.now()]):(q&&q.sort&&q.sort(),typeof L=="function"&&L.call(this,K,q))}}}if(process.version.substr(0,4)==="v0.8"){var p=pk(e);w=p.ReadStream,h=p.WriteStream}var f=e.ReadStream;f&&(w.prototype=Object.create(f.prototype),w.prototype.open=_);var m=e.WriteStream;m&&(h.prototype=Object.create(m.prototype),h.prototype.open=b),Object.defineProperty(e,"ReadStream",{get:function(){return w},set:function(R){w=R},enumerable:!0,configurable:!0}),Object.defineProperty(e,"WriteStream",{get:function(){return h},set:function(R){h=R},enumerable:!0,configurable:!0});var g=w;Object.defineProperty(e,"FileReadStream",{get:function(){return g},set:function(R){g=R},enumerable:!0,configurable:!0});var y=h;Object.defineProperty(e,"FileWriteStream",{get:function(){return y},set:function(R){y=R},enumerable:!0,configurable:!0});function w(R,O){return this instanceof w?(f.apply(this,arguments),this):w.apply(Object.create(w.prototype),arguments)}function _(){var R=this;F(R.path,R.flags,R.mode,function(O,C){O?(R.autoClose&&R.destroy(),R.emit("error",O)):(R.fd=C,R.emit("open",C),R.read())})}function h(R,O){return this instanceof h?(m.apply(this,arguments),this):h.apply(Object.create(h.prototype),arguments)}function b(){var R=this;F(R.path,R.flags,R.mode,function(O,C){O?(R.destroy(),R.emit("error",O)):(R.fd=C,R.emit("open",C))})}function S(R,O){return new e.ReadStream(R,O)}function T(R,O){return new e.WriteStream(R,O)}var k=e.open;e.open=F;function F(R,O,C,$){return typeof C=="function"&&($=C,C=null),D(R,O,C,$);function D(x,E,L,j,K){return k(x,E,L,function(q,mn){q&&(q.code==="EMFILE"||q.code==="ENFILE")?Hn([D,[x,E,L,j],q,K||Date.now(),Date.now()]):typeof j=="function"&&j.apply(this,arguments)})}}return e}function Hn(e){yn("ENQUEUE",e[0].name,e[1]),ne[_e].push(e),xi()}var Po;function ju(){for(var e=Date.now(),t=0;t<ne[_e].length;++t)ne[_e][t].length>2&&(ne[_e][t][3]=e,ne[_e][t][4]=e);xi()}function xi(){if(clearTimeout(Po),Po=void 0,ne[_e].length!==0){var e=ne[_e].shift(),t=e[0],n=e[1],r=e[2],o=e[3],s=e[4];if(o===void 0)yn("RETRY",t.name,n),t.apply(null,n);else if(Date.now()-o>=6e4){yn("TIMEOUT",t.name,n);var i=n.pop();typeof i=="function"&&i.call(null,r)}else{var a=Date.now()-s,c=Math.max(s-o,1),l=Math.min(c*1.2,100);a>=l?(yn("RETRY",t.name,n),t.apply(null,n.concat([o]))):ne[_e].push(e)}Po===void 0&&(Po=setTimeout(xi,0))}}});var Ce=V(Ot=>{"use strict";var Mu=fe().fromCallback,Te=qn(),gk=["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 Te[e]=="function");Object.assign(Ot,Te);gk.forEach(e=>{Ot[e]=Mu(Te[e])});Ot.exists=function(e,t){return typeof t=="function"?Te.exists(e,t):new Promise(n=>Te.exists(e,n))};Ot.read=function(e,t,n,r,o,s){return typeof s=="function"?Te.read(e,t,n,r,o,s):new Promise((i,a)=>{Te.read(e,t,n,r,o,(c,l,u)=>{if(c)return a(c);i({bytesRead:l,buffer:u})})})};Ot.write=function(e,t,...n){return typeof n[n.length-1]=="function"?Te.write(e,t,...n):new Promise((r,o)=>{Te.write(e,t,...n,(s,i,a)=>{if(s)return o(s);r({bytesWritten:i,buffer:a})})})};Ot.readv=function(e,t,...n){return typeof n[n.length-1]=="function"?Te.readv(e,t,...n):new Promise((r,o)=>{Te.readv(e,t,...n,(s,i,a)=>{if(s)return o(s);r({bytesRead:i,buffers:a})})})};Ot.writev=function(e,t,...n){return typeof n[n.length-1]=="function"?Te.writev(e,t,...n):new Promise((r,o)=>{Te.writev(e,t,...n,(s,i,a)=>{if(s)return o(s);r({bytesWritten:i,buffers:a})})})};typeof Te.realpath.native=="function"?Ot.realpath.native=Mu(Te.realpath.native):process.emitWarning("fs.realpath.native is not a function. Is fs being monkey-patched?","Warning","fs-extra-WARN0003")});var Uu=V((bI,Lu)=>{"use strict";var hk=require("path");Lu.exports.checkPath=function(t){if(process.platform==="win32"&&/[<>:"|?*]/.test(t.replace(hk.parse(t).root,""))){let r=new Error(`Path contains invalid characters: ${t}`);throw r.code="EINVAL",r}}});var Hu=V((EI,Ai)=>{"use strict";var Wu=Ce(),{checkPath:Bu}=Uu(),Gu=e=>{let t={mode:511};return typeof e=="number"?e:{...t,...e}.mode};Ai.exports.makeDir=async(e,t)=>(Bu(e),Wu.mkdir(e,{mode:Gu(t),recursive:!0}));Ai.exports.makeDirSync=(e,t)=>(Bu(e),Wu.mkdirSync(e,{mode:Gu(t),recursive:!0}))});var it=V((TI,qu)=>{"use strict";var yk=fe().fromPromise,{makeDir:wk,makeDirSync:Ii}=Hu(),Oi=yk(wk);qu.exports={mkdirs:Oi,mkdirsSync:Ii,mkdirp:Oi,mkdirpSync:Ii,ensureDir:Oi,ensureDirSync:Ii}});var Xt=V((CI,Yu)=>{"use strict";var _k=fe().fromPromise,Vu=Ce();function kk(e){return Vu.access(e).then(()=>!0).catch(()=>!1)}Yu.exports={pathExists:_k(kk),pathExistsSync:Vu.existsSync}});var $i=V((RI,Ku)=>{"use strict";var Vn=Ce(),Sk=fe().fromPromise;async function vk(e,t,n){let r=await Vn.open(e,"r+"),o=null;try{await Vn.futimes(r,t,n)}finally{try{await Vn.close(r)}catch(s){o=s}}if(o)throw o}function bk(e,t,n){let r=Vn.openSync(e,"r+");return Vn.futimesSync(r,t,n),Vn.closeSync(r)}Ku.exports={utimesMillis:Sk(vk),utimesMillisSync:bk}});var wn=V((xI,Xu)=>{"use strict";var Yn=Ce(),me=require("path"),Ju=fe().fromPromise;function Ek(e,t,n){let r=n.dereference?o=>Yn.stat(o,{bigint:!0}):o=>Yn.lstat(o,{bigint:!0});return Promise.all([r(e),r(t).catch(o=>{if(o.code==="ENOENT")return null;throw o})]).then(([o,s])=>({srcStat:o,destStat:s}))}function Tk(e,t,n){let r,o=n.dereference?i=>Yn.statSync(i,{bigint:!0}):i=>Yn.lstatSync(i,{bigint:!0}),s=o(e);try{r=o(t)}catch(i){if(i.code==="ENOENT")return{srcStat:s,destStat:null};throw i}return{srcStat:s,destStat:r}}async function Ck(e,t,n,r){let{srcStat:o,destStat:s}=await Ek(e,t,r);if(s){if($r(o,s)){let i=me.basename(e),a=me.basename(t);if(n==="move"&&i!==a&&i.toLowerCase()===a.toLowerCase())return{srcStat:o,destStat:s,isChangingCase:!0};throw new Error("Source and destination must not be the same.")}if(o.isDirectory()&&!s.isDirectory())throw new Error(`Cannot overwrite non-directory '${t}' with directory '${e}'.`);if(!o.isDirectory()&&s.isDirectory())throw new Error(`Cannot overwrite directory '${t}' with non-directory '${e}'.`)}if(o.isDirectory()&&Di(e,t))throw new Error(Io(e,t,n));return{srcStat:o,destStat:s}}function Rk(e,t,n,r){let{srcStat:o,destStat:s}=Tk(e,t,r);if(s){if($r(o,s)){let i=me.basename(e),a=me.basename(t);if(n==="move"&&i!==a&&i.toLowerCase()===a.toLowerCase())return{srcStat:o,destStat:s,isChangingCase:!0};throw new Error("Source and destination must not be the same.")}if(o.isDirectory()&&!s.isDirectory())throw new Error(`Cannot overwrite non-directory '${t}' with directory '${e}'.`);if(!o.isDirectory()&&s.isDirectory())throw new Error(`Cannot overwrite directory '${t}' with non-directory '${e}'.`)}if(o.isDirectory()&&Di(e,t))throw new Error(Io(e,t,n));return{srcStat:o,destStat:s}}async function zu(e,t,n,r){let o=me.resolve(me.dirname(e)),s=me.resolve(me.dirname(n));if(s===o||s===me.parse(s).root)return;let i;try{i=await Yn.stat(s,{bigint:!0})}catch(a){if(a.code==="ENOENT")return;throw a}if($r(t,i))throw new Error(Io(e,n,r));return zu(e,t,s,r)}function Qu(e,t,n,r){let o=me.resolve(me.dirname(e)),s=me.resolve(me.dirname(n));if(s===o||s===me.parse(s).root)return;let i;try{i=Yn.statSync(s,{bigint:!0})}catch(a){if(a.code==="ENOENT")return;throw a}if($r(t,i))throw new Error(Io(e,n,r));return Qu(e,t,s,r)}function $r(e,t){return t.ino!==void 0&&t.dev!==void 0&&t.ino===e.ino&&t.dev===e.dev}function Di(e,t){let n=me.resolve(e).split(me.sep).filter(o=>o),r=me.resolve(t).split(me.sep).filter(o=>o);return n.every((o,s)=>r[s]===o)}function Io(e,t,n){return`Cannot ${n} '${e}' to a subdirectory of itself, '${t}'.`}Xu.exports={checkPaths:Ju(Ck),checkPathsSync:Rk,checkParentPaths:Ju(zu),checkParentPathsSync:Qu,isSrcSubdir:Di,areIdentical:$r}});var ed=V((PI,Zu)=>{"use strict";async function xk(e,t){let n=[];for await(let r of e)n.push(t(r).then(()=>null,o=>o??new Error("unknown error")));await Promise.all(n.map(r=>r.then(o=>{if(o!==null)throw o})))}Zu.exports={asyncIteratorConcurrentProcess:xk}});var sd=V((AI,od)=>{"use strict";var Se=Ce(),Dr=require("path"),{mkdirs:Pk}=it(),{pathExists:Ak}=Xt(),{utimesMillis:Ik}=$i(),Nr=wn(),{asyncIteratorConcurrentProcess:Ok}=ed();async function $k(e,t,n={}){typeof n=="function"&&(n={filter:n}),n.clobber="clobber"in n?!!n.clobber:!0,n.overwrite="overwrite"in n?!!n.overwrite:n.clobber,n.preserveTimestamps&&process.arch==="ia32"&&process.emitWarning(`Using the preserveTimestamps option in 32-bit node is not recommended;
|
|
11
11
|
|
|
12
|
-
see https://github.com/jprichardson/node-fs-extra/issues/269`,"Warning","fs-extra-WARN0001");let{srcStat:r,destStat:o}=await
|
|
12
|
+
see https://github.com/jprichardson/node-fs-extra/issues/269`,"Warning","fs-extra-WARN0001");let{srcStat:r,destStat:o}=await Nr.checkPaths(e,t,"copy",n);if(await Nr.checkParentPaths(e,r,t,"copy"),!await nd(e,t,n))return;let i=Dr.dirname(t);await Ak(i)||await Pk(i),await rd(o,e,t,n)}async function nd(e,t,n){return n.filter?n.filter(e,t):!0}async function rd(e,t,n,r){let s=await(r.dereference?Se.stat:Se.lstat)(t);if(s.isDirectory())return Fk(s,e,t,n,r);if(s.isFile()||s.isCharacterDevice()||s.isBlockDevice())return Dk(s,e,t,n,r);if(s.isSymbolicLink())return Mk(e,t,n,r);throw s.isSocket()?new Error(`Cannot copy a socket file: ${t}`):s.isFIFO()?new Error(`Cannot copy a FIFO pipe: ${t}`):new Error(`Unknown file: ${t}`)}async function Dk(e,t,n,r,o){if(!t)return td(e,n,r,o);if(o.overwrite)return await Se.unlink(r),td(e,n,r,o);if(o.errorOnExist)throw new Error(`'${r}' already exists`)}async function td(e,t,n,r){if(await Se.copyFile(t,n),r.preserveTimestamps){Nk(e.mode)&&await jk(n,e.mode);let o=await Se.stat(t);await Ik(n,o.atime,o.mtime)}return Se.chmod(n,e.mode)}function Nk(e){return(e&128)===0}function jk(e,t){return Se.chmod(e,t|128)}async function Fk(e,t,n,r,o){t||await Se.mkdir(r),await Ok(await Se.opendir(n),async s=>{let i=Dr.join(n,s.name),a=Dr.join(r,s.name);if(await nd(i,a,o)){let{destStat:l}=await Nr.checkPaths(i,a,"copy",o);await rd(l,i,a,o)}}),t||await Se.chmod(r,e.mode)}async function Mk(e,t,n,r){let o=await Se.readlink(t);if(r.dereference&&(o=Dr.resolve(process.cwd(),o)),!e)return Se.symlink(o,n);let s=null;try{s=await Se.readlink(n)}catch(i){if(i.code==="EINVAL"||i.code==="UNKNOWN")return Se.symlink(o,n);throw i}if(r.dereference&&(s=Dr.resolve(process.cwd(),s)),o!==s){if(Nr.isSrcSubdir(o,s))throw new Error(`Cannot copy '${o}' to a subdirectory of itself, '${s}'.`);if(Nr.isSrcSubdir(s,o))throw new Error(`Cannot overwrite '${s}' with '${o}'.`)}return await Se.unlink(n),Se.symlink(o,n)}od.exports=$k});var ud=V((II,ld)=>{"use strict";var Re=qn(),jr=require("path"),Lk=it().mkdirsSync,Uk=$i().utimesMillisSync,Fr=wn();function Wk(e,t,n){typeof n=="function"&&(n={filter:n}),n=n||{},n.clobber="clobber"in n?!!n.clobber:!0,n.overwrite="overwrite"in n?!!n.overwrite:n.clobber,n.preserveTimestamps&&process.arch==="ia32"&&process.emitWarning(`Using the preserveTimestamps option in 32-bit node is not recommended;
|
|
13
13
|
|
|
14
|
-
see https://github.com/jprichardson/node-fs-extra/issues/269`,"Warning","fs-extra-WARN0002");let{srcStat:r,destStat:o}=
|
|
15
|
-
`,finalEOL:n=!0,replacer:r=null,spaces:o}={}){let s=n?t:"";return JSON.stringify(e,r,o).replace(/\n/g,t)+s}function xS(e){return Buffer.isBuffer(e)&&(e=e.toString("utf8")),e.replace(/^\uFEFF/,"")}Jd.exports={stringify:RS,stripBom:xS}});var Zd=V((WI,Xd)=>{var zn;try{zn=Yn()}catch{zn=require("fs")}var jo=fe(),{stringify:zd,stripBom:Qd}=No();async function PS(e,t={}){typeof t=="string"&&(t={encoding:t});let n=t.fs||zn,r="throws"in t?t.throws:!0,o=await jo.fromCallback(n.readFile)(e,t);o=Qd(o);let s;try{s=JSON.parse(o,t?t.reviver:null)}catch(i){if(r)throw i.message=`${e}: ${i.message}`,i;return null}return s}var AS=jo.fromPromise(PS);function IS(e,t={}){typeof t=="string"&&(t={encoding:t});let n=t.fs||zn,r="throws"in t?t.throws:!0;try{let o=n.readFileSync(e,t);return o=Qd(o),JSON.parse(o,t.reviver)}catch(o){if(r)throw o.message=`${e}: ${o.message}`,o;return null}}async function OS(e,t,n={}){let r=n.fs||zn,o=zd(t,n);await jo.fromCallback(r.writeFile)(e,o,n)}var $S=jo.fromPromise(OS);function DS(e,t,n={}){let r=n.fs||zn,o=zd(t,n);return r.writeFileSync(e,o,n)}Xd.exports={readFile:AS,readFileSync:IS,writeFile:$S,writeFileSync:DS}});var tp=V((BI,ep)=>{"use strict";var Fo=Zd();ep.exports={readJson:Fo.readFile,readJsonSync:Fo.readFileSync,writeJson:Fo.writeFile,writeJsonSync:Fo.writeFileSync}});var Mo=V((GI,op)=>{"use strict";var NS=fe().fromPromise,Fi=Re(),np=require("path"),rp=ct(),jS=en().pathExists;async function FS(e,t,n="utf-8"){let r=np.dirname(e);return await jS(r)||await rp.mkdirs(r),Fi.writeFile(e,t,n)}function MS(e,...t){let n=np.dirname(e);Fi.existsSync(n)||rp.mkdirsSync(n),Fi.writeFileSync(e,...t)}op.exports={outputFile:NS(FS),outputFileSync:MS}});var ip=V((HI,sp)=>{"use strict";var{stringify:LS}=No(),{outputFile:US}=Mo();async function WS(e,t,n={}){let r=LS(t,n);await US(e,r,n)}sp.exports=WS});var cp=V((qI,ap)=>{"use strict";var{stringify:BS}=No(),{outputFileSync:GS}=Mo();function HS(e,t,n){let r=BS(t,n);GS(e,r,n)}ap.exports=HS});var up=V((VI,lp)=>{"use strict";var qS=fe().fromPromise,Pe=tp();Pe.outputJson=qS(ip());Pe.outputJsonSync=cp();Pe.outputJSON=Pe.outputJson;Pe.outputJSONSync=Pe.outputJsonSync;Pe.writeJSON=Pe.writeJson;Pe.writeJSONSync=Pe.writeJsonSync;Pe.readJSON=Pe.readJson;Pe.readJSONSync=Pe.readJsonSync;lp.exports=Pe});var gp=V((YI,mp)=>{"use strict";var VS=Re(),dp=require("path"),{copy:YS}=Do(),{remove:fp}=Ur(),{mkdirp:KS}=ct(),{pathExists:JS}=en(),pp=kn();async function zS(e,t,n={}){let r=n.overwrite||n.clobber||!1,{srcStat:o,isChangingCase:s=!1}=await pp.checkPaths(e,t,"move",n);await pp.checkParentPaths(e,o,t,"move");let i=dp.dirname(t);return dp.parse(i).root!==i&&await KS(i),QS(e,t,r,s)}async function QS(e,t,n,r){if(!r){if(n)await fp(t);else if(await JS(t))throw new Error("dest already exists.")}try{await VS.rename(e,t)}catch(o){if(o.code!=="EXDEV")throw o;await XS(e,t,n)}}async function XS(e,t,n){return await YS(e,t,{overwrite:n,errorOnExist:!0,preserveTimestamps:!0}),fp(e)}mp.exports=zS});var kp=V((KI,_p)=>{"use strict";var yp=Yn(),Li=require("path"),ZS=Do().copySync,wp=Ur().removeSync,ev=ct().mkdirpSync,hp=kn();function tv(e,t,n){n=n||{};let r=n.overwrite||n.clobber||!1,{srcStat:o,isChangingCase:s=!1}=hp.checkPathsSync(e,t,"move",n);return hp.checkParentPathsSync(e,o,t,"move"),nv(t)||ev(Li.dirname(t)),rv(e,t,r,s)}function nv(e){let t=Li.dirname(e);return Li.parse(t).root===t}function rv(e,t,n,r){if(r)return Mi(e,t,n);if(n)return wp(t),Mi(e,t,n);if(yp.existsSync(t))throw new Error("dest already exists.");return Mi(e,t,n)}function Mi(e,t,n){try{yp.renameSync(e,t)}catch(r){if(r.code!=="EXDEV")throw r;return ov(e,t,n)}}function ov(e,t,n){return ZS(e,t,{overwrite:n,errorOnExist:!0,preserveTimestamps:!0}),wp(e)}_p.exports=tv});var vp=V((JI,Sp)=>{"use strict";var sv=fe().fromPromise;Sp.exports={move:sv(gp()),moveSync:kp()}});var X=V((zI,bp)=>{"use strict";bp.exports={...Re(),...Do(),...vd(),...Kd(),...up(),...ct(),...vp(),...Mo(),...en(),...Ur()}});var Bi={};he(Bi,{archiveWorkflow:()=>Wi,clearCache:()=>uv,deleteWorkflow:()=>dv,findActiveWorkflow:()=>pv,getResumePoint:()=>lv,invalidateCache:()=>jt,listWorkflows:()=>oe,loadCheckpoint:()=>A,saveCheckpoint:()=>P});function Ui(e,t){return`${e}:${t}`}function av(e){return Date.now()-e.timestamp<iv}function Ep(e){if(e.current_stage==="idea"&&(e.current_stage="intent"),e.construction_bolts===void 0&&(e.construction_bolts={}),e.active_bolt_id===void 0&&(e.active_bolt_id=null),e.active_bolt_stage===void 0&&(e.active_bolt_stage=null),e.construction_bolts)for(let t of Object.values(e.construction_bolts))t.requires_bolts===void 0&&(t.requires_bolts=[]),t.enables_bolts===void 0&&(t.enables_bolts=[]),t.requires_units===void 0&&(t.requires_units=[]),t.blocked===void 0&&(t.blocked=!1);if(!(!e.construction_units||Array.isArray(e.construction_units)))for(let t of Object.values(e.construction_units)){if(t.stages||(t.stages={}),!t.stages["test-generation"]){let n=t.code_generation_status==="completed";t.stages["test-generation"]={status:n?"skipped":"not_started",artifact_path:null,completed_at:null,failure_count:0,last_error:null}}for(let n of Object.values(t.stages))n.failure_count===void 0&&(n.failure_count=0),n.last_error===void 0&&(n.last_error=null);t.quality_validation_status===void 0&&(t.quality_validation_status="not_started"),t.mutation_validation_status===void 0&&(t.mutation_validation_status="not_started"),t.traceability_status===void 0&&(t.traceability_status="not_started"),t.contract_validation_status===void 0&&(t.contract_validation_status="not_started"),t.coverage_status===void 0&&(t.coverage_status="not_started"),t.coverage_percentage===void 0&&(t.coverage_percentage=null),t.critical_gap_count===void 0&&(t.critical_gap_count=0),t.security_scan_status===void 0&&(t.security_scan_status="not_started"),t.security_findings_critical===void 0&&(t.security_findings_critical=0),t.security_findings_warning===void 0&&(t.security_findings_warning=0),t.security_findings_info===void 0&&(t.security_findings_info=0),t.feature_doc_status===void 0&&(t.feature_doc_status="not_started"),t.feature_doc_path===void 0&&(t.feature_doc_path=null),t.recreation_readiness_score===void 0&&(t.recreation_readiness_score=null),t.recreation_readiness_dimensions===void 0&&(t.recreation_readiness_dimensions=null),t.adr_count===void 0&&(t.adr_count=0),t.impact_scan_status===void 0&&(t.impact_scan_status="not_started")}}function lv(e){let t=e.active_bolt_id;if(t==null)return null;if(e.active_bolt_stage!=null)return{boltId:t,stage:e.active_bolt_stage};let n=e.construction_bolts?.[t];if(!n)return null;for(let r of cv){let o=n.stages?.[r];if(!o)return{boltId:t,stage:r};if(o.status!=="completed"&&o.status!=="skipped")return{boltId:t,stage:r}}return null}function uv(){Br.clear()}function jt(e,t){let n=Ui(e,t);Br.delete(n)}async function P(e,t){let n=(0,Ge.join)(e,St,t.workflow_id),r=(0,Ge.join)(n,Gr);try{if(t.updated_at=new Date().toISOString(),t.schema_version="3.1.0",await re.default.ensureDir(n),JSON.stringify(t).length>1e4){let a=JSON.stringify(t);await re.default.writeFile(r,a,"utf-8")}else await re.default.writeJson(r,t,{spaces:2});let i=Ui(e,t.workflow_id);Br.set(i,{checkpoint:structuredClone(t),timestamp:Date.now(),dirty:!1})}catch(o){let s=o;throw s.code==="ENOSPC"?(console.error("[Checkpoint] Failed to save checkpoint: Disk full"),console.error("[Checkpoint] Please free up disk space and try again."),console.error(`[Checkpoint] Attempted path: ${r}`),new Error("Failed to save checkpoint: Disk is full. Please free up space and retry.")):s.code==="EACCES"||s.code==="EPERM"?(console.error("[Checkpoint] Failed to save checkpoint: Permission denied"),console.error(`[Checkpoint] Path: ${r}`),new Error(`Failed to save checkpoint: Permission denied for ${r}`)):s.code==="EROFS"?(console.error("[Checkpoint] Failed to save checkpoint: Read-only filesystem"),console.error(`[Checkpoint] Path: ${r}`),new Error("Failed to save checkpoint: Filesystem is read-only")):(console.error("[Checkpoint] Failed to save checkpoint:",s.message),console.error(`[Checkpoint] Workflow ID: ${t.workflow_id}`),console.error(`[Checkpoint] Path: ${r}`),new Error(`Failed to save checkpoint for workflow ${t.workflow_id}: ${s.message}`))}}async function A(e,t){let n=Ui(e,t),r=Br.get(n);if(r&&av(r)){let s=structuredClone(r.checkpoint);return Ep(s),s}let o=(0,Ge.join)(e,St,t,Gr);try{let s=await re.default.readFile(o,"utf-8"),i=JSON.parse(s);return i.schema_version?i.schema_version!=="3.0.0"&&i.schema_version!=="3.1.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}`),Ep(i),Br.set(n,{checkpoint:structuredClone(i),timestamp:Date.now(),dirty:!1}),i):(console.warn(`[Checkpoint] Checkpoint ${t} missing schema_version, treating as invalid`),console.warn("[Checkpoint] Checkpoint may be corrupt or from an older version"),console.warn(`[Checkpoint] Consider deleting: ${o}`),null)}catch(s){let i=s,a=i;return a.code==="ENOENT"?null:i.name==="SyntaxError"||i.message.includes("JSON")?(console.warn(`[Checkpoint] Corrupt checkpoint detected for workflow ${t}`),console.warn(`[Checkpoint] Path: ${o}`),console.warn(`[Checkpoint] Error: ${i.message}`),console.warn("[Checkpoint] To reset this workflow, delete the checkpoint file and start over"),null):a.code==="EACCES"||a.code==="EPERM"?(console.warn(`[Checkpoint] Permission denied reading checkpoint ${t}`),console.warn(`[Checkpoint] Path: ${o}`),null):(console.warn(`[Checkpoint] Failed to load checkpoint ${t}: ${i.message}`),console.warn(`[Checkpoint] Path: ${o}`),null)}}async function oe(e){let t=(0,Ge.join)(e,St);try{if(!await re.default.pathExists(t))return[];let r=await re.default.readdir(t,{withFileTypes:!0}),o=[];for(let s of r){if(!s.isDirectory()||s.name==="completed")continue;let i=(0,Ge.join)(t,s.name,Gr);if(await re.default.pathExists(i))try{let a=await re.default.readFile(i,"utf-8"),c=JSON.parse(a);c.workflow_id&&o.push(c.workflow_id)}catch{}}return o}catch(n){let r=n;return r.code==="EACCES"||r.code==="EPERM"?console.warn(`[Checkpoint] Permission denied reading ${t}`):console.warn(`[Checkpoint] Failed to list workflows: ${r.message}`),[]}}async function dv(e,t){let n=(0,Ge.join)(e,St,t);try{await re.default.remove(n)}catch(r){let o=r;if(o.code==="ENOENT")return;if(o.code==="EACCES"||o.code==="EPERM"){console.warn(`[Checkpoint] Permission denied deleting workflow ${t}`),console.warn(`[Checkpoint] Path: ${n}`),console.warn("[Checkpoint] Manual deletion may be required");return}console.warn(`[Checkpoint] Failed to delete workflow ${t}: ${o.message}`),console.warn(`[Checkpoint] Path: ${n}`)}}async function Wi(e,t){let n=await A(e,t);if(!n||n.status!=="complete")return;let r=(0,Ge.join)(e,St,t),o=(0,Ge.join)(e,St,"completed",t),s=(0,Ge.join)(o,Gr);if(await re.default.pathExists(s))try{let i=await re.default.readFile(s,"utf-8");if(JSON.parse(i).workflow_id===t){console.log(`[Checkpoint] Workflow ${t} already archived at ${o}`);return}}catch{await re.default.remove(o)}else await re.default.pathExists(o)&&await re.default.remove(o);n.archived_at=new Date().toISOString(),n.archived_path=`${St}/completed/${t}`,await P(e,n);try{await re.default.move(r,o,{overwrite:!1}),jt(e,t),console.log(`[Checkpoint] Workflow archived to ${St}/completed/${t}/`)}catch(i){let a=i,c=a.code==="EBUSY"&&process.platform==="win32"?" \u2014 try closing open files in the workflow directory":"";console.warn(`[Checkpoint] Failed to move workflow folder (non-fatal): ${a.message}${c}`)}try{let i=(0,Ge.join)(e,".olympus","plans",`${t}-plan.md`);if(await re.default.pathExists(i)){let a=`
|
|
14
|
+
see https://github.com/jprichardson/node-fs-extra/issues/269`,"Warning","fs-extra-WARN0002");let{srcStat:r,destStat:o}=Fr.checkPathsSync(e,t,"copy",n);if(Fr.checkParentPathsSync(e,r,t,"copy"),n.filter&&!n.filter(e,t))return;let s=jr.dirname(t);return Re.existsSync(s)||Lk(s),id(o,e,t,n)}function id(e,t,n,r){let s=(r.dereference?Re.statSync:Re.lstatSync)(t);if(s.isDirectory())return Kk(s,e,t,n,r);if(s.isFile()||s.isCharacterDevice()||s.isBlockDevice())return Bk(s,e,t,n,r);if(s.isSymbolicLink())return Qk(e,t,n,r);throw s.isSocket()?new Error(`Cannot copy a socket file: ${t}`):s.isFIFO()?new Error(`Cannot copy a FIFO pipe: ${t}`):new Error(`Unknown file: ${t}`)}function Bk(e,t,n,r,o){return t?Gk(e,n,r,o):ad(e,n,r,o)}function Gk(e,t,n,r){if(r.overwrite)return Re.unlinkSync(n),ad(e,t,n,r);if(r.errorOnExist)throw new Error(`'${n}' already exists`)}function ad(e,t,n,r){return Re.copyFileSync(t,n),r.preserveTimestamps&&Hk(e.mode,t,n),Ni(n,e.mode)}function Hk(e,t,n){return qk(e)&&Vk(n,e),Yk(t,n)}function qk(e){return(e&128)===0}function Vk(e,t){return Ni(e,t|128)}function Ni(e,t){return Re.chmodSync(e,t)}function Yk(e,t){let n=Re.statSync(e);return Uk(t,n.atime,n.mtime)}function Kk(e,t,n,r,o){return t?cd(n,r,o):Jk(e.mode,n,r,o)}function Jk(e,t,n,r){return Re.mkdirSync(n),cd(t,n,r),Ni(n,e)}function cd(e,t,n){let r=Re.opendirSync(e);try{let o;for(;(o=r.readSync())!==null;)zk(o.name,e,t,n)}finally{r.closeSync()}}function zk(e,t,n,r){let o=jr.join(t,e),s=jr.join(n,e);if(r.filter&&!r.filter(o,s))return;let{destStat:i}=Fr.checkPathsSync(o,s,"copy",r);return id(i,o,s,r)}function Qk(e,t,n,r){let o=Re.readlinkSync(t);if(r.dereference&&(o=jr.resolve(process.cwd(),o)),e){let s;try{s=Re.readlinkSync(n)}catch(i){if(i.code==="EINVAL"||i.code==="UNKNOWN")return Re.symlinkSync(o,n);throw i}if(r.dereference&&(s=jr.resolve(process.cwd(),s)),o!==s){if(Fr.isSrcSubdir(o,s))throw new Error(`Cannot copy '${o}' to a subdirectory of itself, '${s}'.`);if(Fr.isSrcSubdir(s,o))throw new Error(`Cannot overwrite '${s}' with '${o}'.`)}return Xk(o,n)}else return Re.symlinkSync(o,n)}function Xk(e,t){return Re.unlinkSync(t),Re.symlinkSync(e,t)}ld.exports=Wk});var Oo=V((OI,dd)=>{"use strict";var Zk=fe().fromPromise;dd.exports={copy:Zk(sd()),copySync:ud()}});var Mr=V(($I,fd)=>{"use strict";var pd=qn(),eS=fe().fromCallback;function tS(e,t){pd.rm(e,{recursive:!0,force:!0},t)}function nS(e){pd.rmSync(e,{recursive:!0,force:!0})}fd.exports={remove:eS(tS),removeSync:nS}});var Sd=V((DI,kd)=>{"use strict";var rS=fe().fromPromise,hd=Ce(),yd=require("path"),wd=it(),_d=Mr(),md=rS(async function(t){let n;try{n=await hd.readdir(t)}catch{return wd.mkdirs(t)}return Promise.all(n.map(r=>_d.remove(yd.join(t,r))))});function gd(e){let t;try{t=hd.readdirSync(e)}catch{return wd.mkdirsSync(e)}t.forEach(n=>{n=yd.join(e,n),_d.removeSync(n)})}kd.exports={emptyDirSync:gd,emptydirSync:gd,emptyDir:md,emptydir:md}});var Td=V((NI,Ed)=>{"use strict";var oS=fe().fromPromise,vd=require("path"),$t=Ce(),bd=it();async function sS(e){let t;try{t=await $t.stat(e)}catch{}if(t&&t.isFile())return;let n=vd.dirname(e),r=null;try{r=await $t.stat(n)}catch(o){if(o.code==="ENOENT"){await bd.mkdirs(n),await $t.writeFile(e,"");return}else throw o}r.isDirectory()?await $t.writeFile(e,""):await $t.readdir(n)}function iS(e){let t;try{t=$t.statSync(e)}catch{}if(t&&t.isFile())return;let n=vd.dirname(e);try{$t.statSync(n).isDirectory()||$t.readdirSync(n)}catch(r){if(r&&r.code==="ENOENT")bd.mkdirsSync(n);else throw r}$t.writeFileSync(e,"")}Ed.exports={createFile:oS(sS),createFileSync:iS}});var Ad=V((jI,Pd)=>{"use strict";var aS=fe().fromPromise,Cd=require("path"),Zt=Ce(),Rd=it(),{pathExists:cS}=Xt(),{areIdentical:xd}=wn();async function lS(e,t){let n;try{n=await Zt.lstat(t)}catch{}let r;try{r=await Zt.lstat(e)}catch(i){throw i.message=i.message.replace("lstat","ensureLink"),i}if(n&&xd(r,n))return;let o=Cd.dirname(t);await cS(o)||await Rd.mkdirs(o),await Zt.link(e,t)}function uS(e,t){let n;try{n=Zt.lstatSync(t)}catch{}try{let s=Zt.lstatSync(e);if(n&&xd(s,n))return}catch(s){throw s.message=s.message.replace("lstat","ensureLink"),s}let r=Cd.dirname(t);return Zt.existsSync(r)||Rd.mkdirsSync(r),Zt.linkSync(e,t)}Pd.exports={createLink:aS(lS),createLinkSync:uS}});var Od=V((FI,Id)=>{"use strict";var en=require("path"),Lr=Ce(),{pathExists:dS}=Xt(),pS=fe().fromPromise;async function fS(e,t){if(en.isAbsolute(e)){try{await Lr.lstat(e)}catch(s){throw s.message=s.message.replace("lstat","ensureSymlink"),s}return{toCwd:e,toDst:e}}let n=en.dirname(t),r=en.join(n,e);if(await dS(r))return{toCwd:r,toDst:e};try{await Lr.lstat(e)}catch(s){throw s.message=s.message.replace("lstat","ensureSymlink"),s}return{toCwd:e,toDst:en.relative(n,e)}}function mS(e,t){if(en.isAbsolute(e)){if(!Lr.existsSync(e))throw new Error("absolute srcpath does not exist");return{toCwd:e,toDst:e}}let n=en.dirname(t),r=en.join(n,e);if(Lr.existsSync(r))return{toCwd:r,toDst:e};if(!Lr.existsSync(e))throw new Error("relative srcpath does not exist");return{toCwd:e,toDst:en.relative(n,e)}}Id.exports={symlinkPaths:pS(fS),symlinkPathsSync:mS}});var Nd=V((MI,Dd)=>{"use strict";var $d=Ce(),gS=fe().fromPromise;async function hS(e,t){if(t)return t;let n;try{n=await $d.lstat(e)}catch{return"file"}return n&&n.isDirectory()?"dir":"file"}function yS(e,t){if(t)return t;let n;try{n=$d.lstatSync(e)}catch{return"file"}return n&&n.isDirectory()?"dir":"file"}Dd.exports={symlinkType:gS(hS),symlinkTypeSync:yS}});var Ld=V((LI,Md)=>{"use strict";var wS=fe().fromPromise,jd=require("path"),wt=Ce(),{mkdirs:_S,mkdirsSync:kS}=it(),{symlinkPaths:SS,symlinkPathsSync:vS}=Od(),{symlinkType:bS,symlinkTypeSync:ES}=Nd(),{pathExists:TS}=Xt(),{areIdentical:Fd}=wn();async function CS(e,t,n){let r;try{r=await wt.lstat(t)}catch{}if(r&&r.isSymbolicLink()){let[a,c]=await Promise.all([wt.stat(e),wt.stat(t)]);if(Fd(a,c))return}let o=await SS(e,t);e=o.toDst;let s=await bS(o.toCwd,n),i=jd.dirname(t);return await TS(i)||await _S(i),wt.symlink(e,t,s)}function RS(e,t,n){let r;try{r=wt.lstatSync(t)}catch{}if(r&&r.isSymbolicLink()){let a=wt.statSync(e),c=wt.statSync(t);if(Fd(a,c))return}let o=vS(e,t);e=o.toDst,n=ES(o.toCwd,n);let s=jd.dirname(t);return wt.existsSync(s)||kS(s),wt.symlinkSync(e,t,n)}Md.exports={createSymlink:wS(CS),createSymlinkSync:RS}});var Yd=V((UI,Vd)=>{"use strict";var{createFile:Ud,createFileSync:Wd}=Td(),{createLink:Bd,createLinkSync:Gd}=Ad(),{createSymlink:Hd,createSymlinkSync:qd}=Ld();Vd.exports={createFile:Ud,createFileSync:Wd,ensureFile:Ud,ensureFileSync:Wd,createLink:Bd,createLinkSync:Gd,ensureLink:Bd,ensureLinkSync:Gd,createSymlink:Hd,createSymlinkSync:qd,ensureSymlink:Hd,ensureSymlinkSync:qd}});var $o=V((WI,Kd)=>{function xS(e,{EOL:t=`
|
|
15
|
+
`,finalEOL:n=!0,replacer:r=null,spaces:o}={}){let s=n?t:"";return JSON.stringify(e,r,o).replace(/\n/g,t)+s}function PS(e){return Buffer.isBuffer(e)&&(e=e.toString("utf8")),e.replace(/^\uFEFF/,"")}Kd.exports={stringify:xS,stripBom:PS}});var Xd=V((BI,Qd)=>{var Kn;try{Kn=qn()}catch{Kn=require("fs")}var Do=fe(),{stringify:Jd,stripBom:zd}=$o();async function AS(e,t={}){typeof t=="string"&&(t={encoding:t});let n=t.fs||Kn,r="throws"in t?t.throws:!0,o=await Do.fromCallback(n.readFile)(e,t);o=zd(o);let s;try{s=JSON.parse(o,t?t.reviver:null)}catch(i){if(r)throw i.message=`${e}: ${i.message}`,i;return null}return s}var IS=Do.fromPromise(AS);function OS(e,t={}){typeof t=="string"&&(t={encoding:t});let n=t.fs||Kn,r="throws"in t?t.throws:!0;try{let o=n.readFileSync(e,t);return o=zd(o),JSON.parse(o,t.reviver)}catch(o){if(r)throw o.message=`${e}: ${o.message}`,o;return null}}async function $S(e,t,n={}){let r=n.fs||Kn,o=Jd(t,n);await Do.fromCallback(r.writeFile)(e,o,n)}var DS=Do.fromPromise($S);function NS(e,t,n={}){let r=n.fs||Kn,o=Jd(t,n);return r.writeFileSync(e,o,n)}Qd.exports={readFile:IS,readFileSync:OS,writeFile:DS,writeFileSync:NS}});var ep=V((GI,Zd)=>{"use strict";var No=Xd();Zd.exports={readJson:No.readFile,readJsonSync:No.readFileSync,writeJson:No.writeFile,writeJsonSync:No.writeFileSync}});var jo=V((HI,rp)=>{"use strict";var jS=fe().fromPromise,ji=Ce(),tp=require("path"),np=it(),FS=Xt().pathExists;async function MS(e,t,n="utf-8"){let r=tp.dirname(e);return await FS(r)||await np.mkdirs(r),ji.writeFile(e,t,n)}function LS(e,...t){let n=tp.dirname(e);ji.existsSync(n)||np.mkdirsSync(n),ji.writeFileSync(e,...t)}rp.exports={outputFile:jS(MS),outputFileSync:LS}});var sp=V((qI,op)=>{"use strict";var{stringify:US}=$o(),{outputFile:WS}=jo();async function BS(e,t,n={}){let r=US(t,n);await WS(e,r,n)}op.exports=BS});var ap=V((VI,ip)=>{"use strict";var{stringify:GS}=$o(),{outputFileSync:HS}=jo();function qS(e,t,n){let r=GS(t,n);HS(e,r,n)}ip.exports=qS});var lp=V((YI,cp)=>{"use strict";var VS=fe().fromPromise,xe=ep();xe.outputJson=VS(sp());xe.outputJsonSync=ap();xe.outputJSON=xe.outputJson;xe.outputJSONSync=xe.outputJsonSync;xe.writeJSON=xe.writeJson;xe.writeJSONSync=xe.writeJsonSync;xe.readJSON=xe.readJson;xe.readJSONSync=xe.readJsonSync;cp.exports=xe});var mp=V((KI,fp)=>{"use strict";var YS=Ce(),up=require("path"),{copy:KS}=Oo(),{remove:pp}=Mr(),{mkdirp:JS}=it(),{pathExists:zS}=Xt(),dp=wn();async function QS(e,t,n={}){let r=n.overwrite||n.clobber||!1,{srcStat:o,isChangingCase:s=!1}=await dp.checkPaths(e,t,"move",n);await dp.checkParentPaths(e,o,t,"move");let i=up.dirname(t);return up.parse(i).root!==i&&await JS(i),XS(e,t,r,s)}async function XS(e,t,n,r){if(!r){if(n)await pp(t);else if(await zS(t))throw new Error("dest already exists.")}try{await YS.rename(e,t)}catch(o){if(o.code!=="EXDEV")throw o;await ZS(e,t,n)}}async function ZS(e,t,n){return await KS(e,t,{overwrite:n,errorOnExist:!0,preserveTimestamps:!0}),pp(e)}fp.exports=QS});var _p=V((JI,wp)=>{"use strict";var hp=qn(),Mi=require("path"),ev=Oo().copySync,yp=Mr().removeSync,tv=it().mkdirpSync,gp=wn();function nv(e,t,n){n=n||{};let r=n.overwrite||n.clobber||!1,{srcStat:o,isChangingCase:s=!1}=gp.checkPathsSync(e,t,"move",n);return gp.checkParentPathsSync(e,o,t,"move"),rv(t)||tv(Mi.dirname(t)),ov(e,t,r,s)}function rv(e){let t=Mi.dirname(e);return Mi.parse(t).root===t}function ov(e,t,n,r){if(r)return Fi(e,t,n);if(n)return yp(t),Fi(e,t,n);if(hp.existsSync(t))throw new Error("dest already exists.");return Fi(e,t,n)}function Fi(e,t,n){try{hp.renameSync(e,t)}catch(r){if(r.code!=="EXDEV")throw r;return sv(e,t,n)}}function sv(e,t,n){return ev(e,t,{overwrite:n,errorOnExist:!0,preserveTimestamps:!0}),yp(e)}wp.exports=nv});var Sp=V((zI,kp)=>{"use strict";var iv=fe().fromPromise;kp.exports={move:iv(mp()),moveSync:_p()}});var X=V((QI,vp)=>{"use strict";vp.exports={...Ce(),...Oo(),...Sd(),...Yd(),...lp(),...it(),...Sp(),...jo(),...Xt(),...Mr()}});var Wi={};he(Wi,{archiveWorkflow:()=>Ui,clearCache:()=>dv,deleteWorkflow:()=>pv,findActiveWorkflow:()=>fv,getResumePoint:()=>uv,invalidateCache:()=>Dt,listWorkflows:()=>oe,loadCheckpoint:()=>A,saveCheckpoint:()=>P});function Li(e,t){return`${e}:${t}`}function cv(e){return Date.now()-e.timestamp<av}function bp(e){if(e.current_stage==="idea"&&(e.current_stage="intent"),e.construction_bolts===void 0&&(e.construction_bolts={}),e.active_bolt_id===void 0&&(e.active_bolt_id=null),e.active_bolt_stage===void 0&&(e.active_bolt_stage=null),e.construction_bolts)for(let t of Object.values(e.construction_bolts))t.requires_bolts===void 0&&(t.requires_bolts=[]),t.enables_bolts===void 0&&(t.enables_bolts=[]),t.requires_units===void 0&&(t.requires_units=[]),t.blocked===void 0&&(t.blocked=!1);if(!(!e.construction_units||Array.isArray(e.construction_units)))for(let t of Object.values(e.construction_units)){if(t.stages||(t.stages={}),!t.stages["test-generation"]){let n=t.code_generation_status==="completed";t.stages["test-generation"]={status:n?"skipped":"not_started",artifact_path:null,completed_at:null,failure_count:0,last_error:null}}for(let n of Object.values(t.stages))n.failure_count===void 0&&(n.failure_count=0),n.last_error===void 0&&(n.last_error=null);t.quality_validation_status===void 0&&(t.quality_validation_status="not_started"),t.mutation_validation_status===void 0&&(t.mutation_validation_status="not_started"),t.traceability_status===void 0&&(t.traceability_status="not_started"),t.contract_validation_status===void 0&&(t.contract_validation_status="not_started"),t.coverage_status===void 0&&(t.coverage_status="not_started"),t.coverage_percentage===void 0&&(t.coverage_percentage=null),t.critical_gap_count===void 0&&(t.critical_gap_count=0),t.security_scan_status===void 0&&(t.security_scan_status="not_started"),t.security_findings_critical===void 0&&(t.security_findings_critical=0),t.security_findings_warning===void 0&&(t.security_findings_warning=0),t.security_findings_info===void 0&&(t.security_findings_info=0),t.feature_doc_status===void 0&&(t.feature_doc_status="not_started"),t.feature_doc_path===void 0&&(t.feature_doc_path=null),t.recreation_readiness_score===void 0&&(t.recreation_readiness_score=null),t.recreation_readiness_dimensions===void 0&&(t.recreation_readiness_dimensions=null),t.adr_count===void 0&&(t.adr_count=0),t.impact_scan_status===void 0&&(t.impact_scan_status="not_started")}}function uv(e){let t=e.active_bolt_id;if(t==null)return null;if(e.active_bolt_stage!=null)return{boltId:t,stage:e.active_bolt_stage};let n=e.construction_bolts?.[t];if(!n)return null;for(let r of lv){let o=n.stages?.[r];if(!o)return{boltId:t,stage:r};if(o.status!=="completed"&&o.status!=="skipped")return{boltId:t,stage:r}}return null}function dv(){Ur.clear()}function Dt(e,t){let n=Li(e,t);Ur.delete(n)}async function P(e,t){let n=(0,We.join)(e,_t,t.workflow_id),r=(0,We.join)(n,Wr);try{if(t.updated_at=new Date().toISOString(),t.schema_version="3.1.0",await re.default.ensureDir(n),JSON.stringify(t).length>1e4){let a=JSON.stringify(t);await re.default.writeFile(r,a,"utf-8")}else await re.default.writeJson(r,t,{spaces:2});let i=Li(e,t.workflow_id);Ur.set(i,{checkpoint:structuredClone(t),timestamp:Date.now(),dirty:!1})}catch(o){let s=o;throw s.code==="ENOSPC"?(console.error("[Checkpoint] Failed to save checkpoint: Disk full"),console.error("[Checkpoint] Please free up disk space and try again."),console.error(`[Checkpoint] Attempted path: ${r}`),new Error("Failed to save checkpoint: Disk is full. Please free up space and retry.")):s.code==="EACCES"||s.code==="EPERM"?(console.error("[Checkpoint] Failed to save checkpoint: Permission denied"),console.error(`[Checkpoint] Path: ${r}`),new Error(`Failed to save checkpoint: Permission denied for ${r}`)):s.code==="EROFS"?(console.error("[Checkpoint] Failed to save checkpoint: Read-only filesystem"),console.error(`[Checkpoint] Path: ${r}`),new Error("Failed to save checkpoint: Filesystem is read-only")):(console.error("[Checkpoint] Failed to save checkpoint:",s.message),console.error(`[Checkpoint] Workflow ID: ${t.workflow_id}`),console.error(`[Checkpoint] Path: ${r}`),new Error(`Failed to save checkpoint for workflow ${t.workflow_id}: ${s.message}`))}}async function A(e,t){let n=Li(e,t),r=Ur.get(n);if(r&&cv(r)){let s=structuredClone(r.checkpoint);return bp(s),s}let o=(0,We.join)(e,_t,t,Wr);try{let s=await re.default.readFile(o,"utf-8"),i=JSON.parse(s);return i.schema_version?i.schema_version!=="3.0.0"&&i.schema_version!=="3.1.0"?(console.warn(`[Checkpoint] Unknown checkpoint schema version ${i.schema_version} for workflow ${t}`),console.warn("[Checkpoint] Expected 3.0.0"),null):(i.current_stage==="idea"&&console.warn(`[Checkpoint] Migrating legacy 'idea' stage to 'intent' for workflow ${t}`),bp(i),Ur.set(n,{checkpoint:structuredClone(i),timestamp:Date.now(),dirty:!1}),i):(console.warn(`[Checkpoint] Checkpoint ${t} missing schema_version, treating as invalid`),console.warn("[Checkpoint] Checkpoint may be corrupt or from an older version"),console.warn(`[Checkpoint] Consider deleting: ${o}`),null)}catch(s){let i=s,a=i;return a.code==="ENOENT"?null:i.name==="SyntaxError"||i.message.includes("JSON")?(console.warn(`[Checkpoint] Corrupt checkpoint detected for workflow ${t}`),console.warn(`[Checkpoint] Path: ${o}`),console.warn(`[Checkpoint] Error: ${i.message}`),console.warn("[Checkpoint] To reset this workflow, delete the checkpoint file and start over"),null):a.code==="EACCES"||a.code==="EPERM"?(console.warn(`[Checkpoint] Permission denied reading checkpoint ${t}`),console.warn(`[Checkpoint] Path: ${o}`),null):(console.warn(`[Checkpoint] Failed to load checkpoint ${t}: ${i.message}`),console.warn(`[Checkpoint] Path: ${o}`),null)}}async function oe(e){let t=(0,We.join)(e,_t);try{if(!await re.default.pathExists(t))return[];let r=await re.default.readdir(t,{withFileTypes:!0}),o=[];for(let s of r){if(!s.isDirectory()||s.name==="completed")continue;let i=(0,We.join)(t,s.name,Wr);if(await re.default.pathExists(i))try{let a=await re.default.readFile(i,"utf-8"),c=JSON.parse(a);c.workflow_id&&o.push(c.workflow_id)}catch{}}return o}catch(n){let r=n;return r.code==="EACCES"||r.code==="EPERM"?console.warn(`[Checkpoint] Permission denied reading ${t}`):console.warn(`[Checkpoint] Failed to list workflows: ${r.message}`),[]}}async function pv(e,t){let n=(0,We.join)(e,_t,t);try{await re.default.remove(n)}catch(r){let o=r;if(o.code==="ENOENT")return;if(o.code==="EACCES"||o.code==="EPERM"){console.warn(`[Checkpoint] Permission denied deleting workflow ${t}`),console.warn(`[Checkpoint] Path: ${n}`),console.warn("[Checkpoint] Manual deletion may be required");return}console.warn(`[Checkpoint] Failed to delete workflow ${t}: ${o.message}`),console.warn(`[Checkpoint] Path: ${n}`)}}async function Ui(e,t){let n=await A(e,t);if(!n||n.status!=="complete")return;let r=(0,We.join)(e,_t,t),o=(0,We.join)(e,_t,"completed",t),s=(0,We.join)(o,Wr);if(await re.default.pathExists(s))try{let i=await re.default.readFile(s,"utf-8");if(JSON.parse(i).workflow_id===t){console.log(`[Checkpoint] Workflow ${t} already archived at ${o}`);return}}catch{await re.default.remove(o)}else await re.default.pathExists(o)&&await re.default.remove(o);n.archived_at=new Date().toISOString(),n.archived_path=`${_t}/completed/${t}`,await P(e,n);try{await re.default.move(r,o,{overwrite:!1}),Dt(e,t),console.log(`[Checkpoint] Workflow archived to ${_t}/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,We.join)(e,".olympus","plans",`${t}-plan.md`);if(await re.default.pathExists(i)){let a=`
|
|
16
16
|
|
|
17
17
|
---
|
|
18
|
-
_This workflow was archived to \`${
|
|
19
|
-
`;await re.default.appendFile(i,a,"utf-8")}}catch{}}async function
|
|
18
|
+
_This workflow was archived to \`${_t}/completed/${t}/\` on ${n.archived_at}_
|
|
19
|
+
`;await re.default.appendFile(i,a,"utf-8")}}catch{}}async function fv(e){let t=(0,We.join)(e,_t);try{if(!await re.default.pathExists(t))return null;let r=await re.default.readdir(t,{withFileTypes:!0});for(let o of r){if(!o.isDirectory()||o.name==="completed")continue;let s=(0,We.join)(t,o.name,Wr);if(await re.default.pathExists(s))try{let i=await re.default.readFile(s,"utf-8"),a=JSON.parse(i);if((a.schema_version==="3.0.0"||a.schema_version==="3.1.0")&&a.status!=="complete"&&a.status!=="archived"&&a.status!=="deferred")return{workflowId:a.workflow_id,checkpoint:a}}catch{}}return null}catch{return null}}var re,We,_t,Wr,Ur,av,lv,ce=U(()=>{"use strict";re=v(X(),1),We=require("path"),_t="aidlc-docs",Wr="checkpoint.json",Ur=new Map,av=5e3;lv=["elaboration","code_generation","build_and_test","review"]});var Cp={};he(Cp,{computeVerification:()=>Fo,generateValidationQuestions:()=>Tp,getAdaptiveThreshold:()=>wv,getConformanceThreshold:()=>kv,recordAlignmentResult:()=>_v,runAlignmentCheck:()=>Gi,runDualValidation:()=>Jn});function hv(e){return e.replace(/^---\n[\s\S]*?\n---\n/,"")}function Bi(e){let t=new Map,n=e.split(`
|
|
20
20
|
`),r=null,o=[];for(let s of n){let i=s.match(/^##\s+(.+)$/);i?(r&&t.set(r,o.join(`
|
|
21
21
|
`)),r=i[1].trim(),o=[]):r&&o.push(s)}return r&&t.set(r,o.join(`
|
|
22
|
-
`)),t}function
|
|
23
|
-
`);for(let r of n){let o=r.match(/^\s*[-*+]\s+(?:\[[ x]\]\s+)?(.+)$/);o&&t.push(o[1].trim())}return t}function hv(e,t){let n=gv(e);if(t==="intent-to-unit"){let i=Gi(n),a=[],c=i.get("Business Requirements");c&&a.push(...Hr(c));let l=i.get("Implementation Plan");return l&&a.push(...Hr(l)),a}if(t==="unit-to-bolt"){let i=Gi(n),a=[],c=i.get("Acceptance Criteria");c&&a.push(...Hr(c));let l=i.get("Target Files");return l&&a.push(...Hr(l)),a}let r=Gi(n),o=mv[t],s=[];for(let i of o){let a=r.get(i);if(a){let c=Hr(a);s.push(...c)}}return s}function Lo(e,t,n){try{let r=hv(e,n);if(r.length===0)return{conformance_score:100,coverage_percentage:100,missing_items:[],passed:!0};let o=t.toLowerCase(),s=[],i=0;for(let d of r){let p=d.toLowerCase();o.includes(p)?i++:s.push(d)}let a=Math.round(i/r.length*100),c=a,l=Tp[n],u=a>=l;return{conformance_score:a,coverage_percentage:c,missing_items:s,passed:u}}catch(r){return console.error("[Alignment] Verification computation failed:",r),{conformance_score:0,coverage_percentage:0,missing_items:["Verification computation error"],passed:!1}}}function Cp(e){let t=fv[e];return[{question:t.verification,answer:null,answered_by:null,passed:null},{question:t.validation,answer:null,answered_by:null,passed:null}]}function Hi(e,t,n,r,o){try{let s=Lo(e,t,o),i=Cp(o),a=i.every(f=>f.answer!==null),c=i.every(f=>f.passed===!0),u={alignment_score:a&&c?100:0,alignment_questions:i,passed:c},d=s.passed&&u.passed;return{source_artifact_id:n,target_artifact_id:r,verification:s,validation:u,alignment_passed:d,checked_at:new Date().toISOString()}}catch(s){return console.error("[Alignment] Alignment check failed:",s),{source_artifact_id:n,target_artifact_id:r,verification:{conformance_score:0,coverage_percentage:0,missing_items:["Alignment check error"],passed:!1},validation:{alignment_score:0,alignment_questions:[],passed:!1},alignment_passed:!1,checked_at:new Date().toISOString()}}}function Qn(e,t,n,r,o,s,i,a){let c=Hi(t,e,s,i,r),l=Hi(n,e,a,i,o),u=c.alignment_passed&&l.alignment_passed;return{parentCheck:c,rootCheck:l,passed:u}}function yv(e,t){let n=0;t>=2&&(n+=10),t>=3&&(n+=10);let r=e-n;return Math.max(0,r)}function wv(e,t){try{let n=W(e);if(!n){console.error(`[Alignment] Manifest not found at ${e}`);return}n.alignment_checks.push(t),G(e,n)}catch(n){console.error("[Alignment] Failed to record alignment result:",n)}}function _v(e){return Tp[e]}var Tp,fv,mv,Uo=U(()=>{"use strict";Z();Tp={"intent-to-unit":95,"unit-to-bolt":100,"unit-to-intent":80,"bolt-to-intent":70},fv={"intent-to-unit":{verification:"Does the UNIT cover its assigned scope from the INTENT?",validation:"Will this UNIT produce a working module that contributes to the feature?"},"unit-to-bolt":{verification:"Does the BOLT cover all acceptance criteria from the UNIT?",validation:"Does this BOLT deliver meaningful, testable progress?"},"unit-to-intent":{verification:"Does this UNIT contribute to the INTENT's problem statement?",validation:"Does this UNIT help achieve the INTENT's success metrics?"},"bolt-to-intent":{verification:"Does this BOLT contribute to solving the INTENT's stated problem?",validation:"Is this BOLT still aligned with the original INTENT's goals?"}},mv={"intent-to-unit":["Business Requirements","Implementation Plan"],"unit-to-bolt":["Acceptance Criteria","Target Files"],"unit-to-intent":["Problem Statement","Success Criteria"],"bolt-to-intent":["Problem Statement","Success Criteria"]}});var vn={};he(vn,{addArtifactLink:()=>kv,addGateAuditEntry:()=>je,cascadeInvalidation:()=>vv,computeChecksum:()=>Wo,createManifest:()=>Vi,detectStaleArtifacts:()=>Sv,getArtifactById:()=>Tv,getArtifactsByPhase:()=>Cv,getBoltArtifacts:()=>Et,getBoltsByStatus:()=>Ki,getUnitArtifacts:()=>Sn,isWorkflowComplete:()=>Pp,linkArtifacts:()=>Yi,loadManifest:()=>W,normalizePath:()=>qi,recoverManifest:()=>Ev,registerArtifact:()=>Ne,revalidateStaleArtifacts:()=>xv,runAlignmentCheck:()=>bv,saveManifest:()=>G,transitionToActive:()=>Ji,transitionToDraft:()=>Ap,transitionToFulfilled:()=>zi,transitionToStale:()=>Op,transitionToViolated:()=>Ip,updateContractStatus:()=>bt,updatePhaseStatus:()=>Ft});function qi(e){return e.replace(/\\/g,"/")}function rn(){return{status:"not_started",started_at:null,completed_at:null,gate_result:null,gate_bypassed:!1,bypass_reason:null}}function Vi(e,t,n){let r=vt.join(n,"aidlc-docs",e),o=vt.join(r,"manifest.json");try{be.default.ensureDirSync(r);let s=new Date().toISOString(),i={schema_version:"2.0.0",workflow_id:e,feature_name:t,created_at:s,updated_at:s,phases:{discovery:rn(),inception:rn(),construction:rn(),operations:rn()},depth_assessment:null,artifacts:[],links:[],risks:[],gate_audit:[],metrics:null,alignment_checks:[],risk_tier:null};return be.default.writeFileSync(o,JSON.stringify(i,null,2),"utf-8"),o}catch(s){throw console.error(`Failed to create manifest at ${o}:`,s),s}}function W(e){try{if(!be.default.existsSync(e))return null;let t=be.default.readFileSync(e,"utf-8");return JSON.parse(t)}catch(t){return console.error(`Failed to load manifest at ${e}:`,t),null}}function G(e,t){try{t.updated_at=new Date().toISOString(),be.default.writeFileSync(e,JSON.stringify(t,null,2),"utf-8")}catch(n){throw console.error(`Failed to save manifest at ${e}:`,n),n}}function Wo(e){try{if(!be.default.existsSync(e))return null;let t=be.default.readFileSync(e),n=(0,xp.createHash)("sha256");return n.update(t),n.digest("hex")}catch(t){return console.error(`Failed to compute checksum for ${e}:`,t),null}}function Ne(e,t){try{let n=W(e);if(!n)throw new Error(`Manifest not found at ${e}`);let r=new Date().toISOString(),o=qi(t.path),s=n.artifacts.findIndex(a=>a.id===t.id),i=Wo(t.path);if(s>=0){let a=n.artifacts[s];n.artifacts[s]={...a,...t,path:o,updated_at:r,contract_version:a.contract_version+1,checksum:i}}else{let a={...t,path:o,created_at:r,updated_at:r,contract_version:1,contract_status:"draft",stale_reason:null,checksum:i};n.artifacts.push(a)}G(e,n)}catch(n){throw console.error(`Failed to register artifact in ${e}:`,n),n}}function Yi(e,t){try{let n=W(e);if(!n)throw new Error(`Manifest not found at ${e}`);let r=n.artifacts.some(i=>i.id===t.source_id),o=n.artifacts.some(i=>i.id===t.target_id);if(!r)throw new Error(`Source artifact not found: ${t.source_id}`);if(!o)throw new Error(`Target artifact not found: ${t.target_id}`);n.links.some(i=>i.source_id===t.source_id&&i.target_id===t.target_id&&i.link_type===t.link_type)||(n.links.push(t),G(e,n))}catch(n){throw console.error(`Failed to link artifacts in ${e}:`,n),n}}function kv(e,t,n,r){e.links.some(s=>s.source_id===t&&s.target_id===n&&s.link_type===r)||e.links.push({source_id:t,target_id:n,link_type:r})}function Sv(e){try{let t=W(e);if(!t)return[];let n=[];for(let r of t.artifacts)if(r.checksum&&r.write_complete){let o=Wo(r.path);o&&o!==r.checksum&&n.push(r.id)}return n}catch(t){return console.error(`Failed to detect stale artifacts in ${e}:`,t),[]}}function vv(e,t){try{let n=W(e);if(!n)return;let r=new Set,o=[t];for(;o.length>0;){let s=o.shift();if(r.has(s))continue;r.add(s);let i=n.artifacts.find(c=>c.id===s);if(i){let c=s===t?"Artifact content was modified":`Parent artifact ${s} was modified`;Rv(i,c)}let a=n.links.filter(c=>c.source_id===s);for(let c of a)r.has(c.target_id)||o.push(c.target_id)}G(e,n)}catch(n){console.error(`Failed to cascade invalidation in ${e}:`,n)}}function bv(e,t,n){try{let r=W(e);if(!r)return;let o=new Date().toISOString(),a={source_artifact_id:t,target_artifact_id:n,verification:{conformance_score:0,coverage_percentage:0,missing_items:[],passed:!1},validation:{alignment_score:0,alignment_questions:[],passed:!1},alignment_passed:!1,checked_at:o};r.alignment_checks.push(a),G(e,r)}catch(r){console.error(`Failed to run alignment check in ${e}:`,r)}}function Ev(e,t){try{let n=vt.join(e,"aidlc-docs",t);if(!be.default.existsSync(n))return null;let r=new Date().toISOString(),o={schema_version:"2.0.0",workflow_id:t,feature_name:"Recovered Workflow",created_at:r,updated_at:r,phases:{discovery:rn(),inception:rn(),construction:rn(),operations:rn()},depth_assessment:null,artifacts:[],links:[],risks:[],gate_audit:[],metrics:null,alignment_checks:[],risk_tier:null},s=be.default.readdirSync(n,{recursive:!0,withFileTypes:!0});for(let i of s)if(i.isFile()&&i.name!=="manifest.json"){let a=vt.join(i.path,i.name),c=vt.relative(n,a),l=qi(a),u={id:`recovered-${Date.now()}-${o.artifacts.length}`,type:vt.extname(i.name)||"unknown",phase:"inception",stage:"intent",path:l,created_at:r,updated_at:r,validation_passed:null,write_complete:!0,checksum:Wo(a),contract_status:"draft",contract_version:1,stale_reason:null};o.artifacts.push(u)}return o}catch(n){return console.error(`Failed to recover manifest for workflow ${t}:`,n),null}}function Ft(e,t,n,r,o){try{let s=W(e);if(!s)return;s.phases[t].status=n,r!==void 0&&(s.phases[t].started_at=r),o!==void 0&&(s.phases[t].completed_at=o),G(e,s)}catch(s){console.error(`Failed to update phase status in ${e}:`,s)}}function je(e,t){try{let n=W(e);if(!n)return;let r={...t,timestamp:new Date().toISOString()};n.gate_audit.push(r),G(e,n)}catch(n){console.error(`Failed to add gate audit entry in ${e}:`,n)}}function Tv(e,t){return e.artifacts.find(n=>n.id===t)}function Cv(e,t){return e.artifacts.filter(n=>n.phase===t)}function bt(e,t,n,r){try{switch(n){case"draft":Ap(e,t);break;case"active":Ji(e,t);break;case"fulfilled":zi(e,t);break;case"violated":Ip(e,t);break;case"stale":if(!r)throw new Error('staleReason is required when setting status to "stale"');Op(e,t,r);break}}catch(o){console.error(`Failed to update contract status in ${e}:`,o)}}function Sn(e){return e.artifacts.filter(t=>t.stage==="unit")}function Et(e,t){let n=e.artifacts.filter(r=>r.stage==="code-generation");if(t){let r=new Set(e.links.filter(o=>o.source_id===t&&(o.link_type==="derives"||o.link_type==="implements")).map(o=>o.target_id));return n.filter(o=>r.has(o.id))}return n}function Ki(e,t){return e.artifacts.filter(n=>n.stage==="code-generation"&&n.contract_status===t)}function Pp(e){let t=e.artifacts.filter(n=>n.stage==="code-generation");return t.length===0?!1:t.every(n=>n.contract_status==="fulfilled")}function Rv(e,t){return e.contract_status==="stale"||e.contract_status==="violated"?!1:(e.contract_status="stale",e.stale_reason=t,e.statusHistory||(e.statusHistory=[]),e.statusHistory.push({status:"stale",timestamp:new Date().toISOString()}),!0)}function Ap(e,t){let n=W(e);if(!n)throw new Error(`Manifest not found at ${e}`);let r=n.artifacts.find(o=>o.id===t);if(!r)throw new Error(`Artifact ${t} not found in manifest`);if(r.contract_status!=="violated"&&r.contract_status!=="stale")throw new Error(`Cannot transition from '${r.contract_status}' to 'draft'`);r.contract_status="draft",r.stale_reason=null,r.statusHistory||(r.statusHistory=[]),r.statusHistory.push({status:"draft",timestamp:new Date().toISOString()}),G(e,n)}function Ji(e,t){let n=W(e);if(!n)throw new Error(`Manifest not found at ${e}`);let r=n.artifacts.find(o=>o.id===t);if(!r)throw new Error(`Artifact ${t} not found in manifest`);if(r.contract_status!=="draft"&&r.contract_status!=="stale")throw new Error(`Cannot transition from '${r.contract_status}' to 'active'`);r.contract_status="active",r.stale_reason=null,r.statusHistory||(r.statusHistory=[]),r.statusHistory.push({status:"active",timestamp:new Date().toISOString()}),G(e,n)}function zi(e,t){let n=W(e);if(!n)throw new Error(`Manifest not found at ${e}`);let r=n.artifacts.find(o=>o.id===t);if(!r)throw new Error(`Artifact ${t} not found in manifest`);if(r.contract_status!=="active")throw new Error(`Cannot transition from '${r.contract_status}' to 'fulfilled'`);r.contract_status="fulfilled",r.stale_reason=null,r.statusHistory||(r.statusHistory=[]),r.statusHistory.push({status:"fulfilled",timestamp:new Date().toISOString()}),G(e,n)}function Ip(e,t){let n=W(e);if(!n)throw new Error(`Manifest not found at ${e}`);let r=n.artifacts.find(o=>o.id===t);if(!r)throw new Error(`Artifact ${t} not found in manifest`);if(r.contract_status!=="active")throw new Error(`Cannot transition from '${r.contract_status}' to 'violated'`);r.contract_status="violated",r.stale_reason=null,r.statusHistory||(r.statusHistory=[]),r.statusHistory.push({status:"violated",timestamp:new Date().toISOString()}),G(e,n)}function Op(e,t,n){let r=W(e);if(!r)throw new Error(`Manifest not found at ${e}`);let o=r.artifacts.find(s=>s.id===t);if(!o)throw new Error(`Artifact ${t} not found in manifest`);if(o.contract_status!=="active"&&o.contract_status!=="fulfilled")throw new Error(`Cannot transition from '${o.contract_status}' to 'stale'`);o.contract_status="stale",o.stale_reason=n,o.statusHistory||(o.statusHistory=[]),o.statusHistory.push({status:"stale",timestamp:new Date().toISOString()}),G(e,r)}async function xv(e,t){let n={restored:[],stillStale:[],errors:[]},r=vt.join(e,"aidlc-docs",t,"manifest.json"),o=W(r);if(!o)return n.errors.push("Manifest not found"),n;let s=o.artifacts.filter(i=>i.contract_status==="stale");for(let i of s)try{let a=o.links.find(w=>w.target_id===i.id);if(!a){n.stillStale.push(i.id);continue}let c=o.artifacts.find(w=>w.id===a.source_id);if(!c){n.stillStale.push(i.id);continue}let l=o.artifacts.find(w=>w.stage==="intent");if(!l){n.stillStale.push(i.id);continue}let u=be.default.existsSync(i.path)?be.default.readFileSync(i.path,"utf-8"):null,d=be.default.existsSync(c.path)?be.default.readFileSync(c.path,"utf-8"):null,p=be.default.existsSync(l.path)?be.default.readFileSync(l.path,"utf-8"):null;if(!u||!d||!p){n.stillStale.push(i.id);continue}let{runDualValidation:f}=await Promise.resolve().then(()=>(Uo(),Rp)),m,g;if(i.stage==="unit")m="intent-to-unit",g="unit-to-intent";else if(i.stage==="code-generation")m="unit-to-bolt",g="bolt-to-intent";else{n.stillStale.push(i.id);continue}f(u,d,p,m,g,c.id,i.id,l.id).passed?(i.contract_status="active",i.stale_reason=null,i.statusHistory||(i.statusHistory=[]),i.statusHistory.push({status:"active",timestamp:new Date().toISOString()}),n.restored.push(i.id)):n.stillStale.push(i.id)}catch(a){n.errors.push(`Error revalidating ${i.id}: ${a}`),n.stillStale.push(i.id)}return G(r,o),n}var be,vt,xp,Z=U(()=>{"use strict";be=v(X(),1),vt=v(require("path"),1),xp=require("crypto")});async function $p(e,t){let n=M.join(e,"aidlc-docs",t),r=M.join(n,"checkpoint.json");try{await ie.ensureDir(n),await ie.ensureDir(M.join(n,"inception")),await ie.ensureDir(M.join(n,"construction")),await ie.ensureDir(M.join(n,"construction","design")),await ie.ensureDir(M.join(n,"operations")),await ie.pathExists(r)||await ie.writeJson(r,{workflow_id:t,current_stage:"intent",created_at:new Date().toISOString(),updated_at:new Date().toISOString()},{spaces:2})}catch(o){let s=o;throw s.code==="ENOSPC"?(console.error("[Artifacts] Failed to create workflow directory: Disk full"),console.error("[Artifacts] Please free up disk space and try again."),console.error(`[Artifacts] Attempted path: ${n}`),new Error("Failed to create workflow directory: Disk is full. Please free up space and retry.")):s.code==="EACCES"||s.code==="EPERM"?(console.error("[Artifacts] Failed to create workflow directory: Permission denied"),console.error(`[Artifacts] Path: ${n}`),new Error(`Failed to create workflow directory: Permission denied for ${n}`)):s.code==="EROFS"?(console.error("[Artifacts] Failed to create workflow directory: Read-only filesystem"),console.error(`[Artifacts] Path: ${n}`),new Error("Failed to create workflow directory: Filesystem is read-only")):(console.error(`[Artifacts] Failed to create workflow directory: ${s.message}`),console.error(`[Artifacts] Workflow ID: ${t}`),console.error(`[Artifacts] Path: ${n}`),new Error(`Failed to create workflow directory for ${t}: ${s.message}`))}}function lt(e,t,n,r,o){let s=M.join(e,"aidlc-docs",t);switch(n){case"intent":return M.join(s,"inception","intent.md");case"nfr":return M.join(s,"inception","requirements","nfr.md");case"unit":if(!r)throw new Error("artifactId is required for unit artifacts");return M.join(s,"construction",r,"spec.md");case"code-generation":if(!r)throw new Error("artifactId is required for code-generation artifacts");if(!o)throw new Error("unitId is required for code-generation artifacts");return M.join(s,"construction",o,`${r}.md`);case"validation-report":if(!r)throw new Error("artifactId is required for validation-report artifacts");return M.join(s,"construction",r,"validation-report.md");case"interfaces":return M.join(s,"construction","design","interfaces.json");case"data-flow":return M.join(s,"construction","design","data-flow.json");case"components":return M.join(s,"construction","design","components.json");case"deploy-guide":return M.join(s,"operations","deploy-guide.md");case"runbook":return M.join(s,"operations","runbook.md");case"monitoring":return M.join(s,"operations","monitoring.json");case"release-notes":return M.join(s,"operations","release-notes.md");case"state":return M.join(s,"state.md");case"audit":return M.join(s,"audit.md");case"analysis-plan":return M.join(s,"discovery","analysis-plan.md");case"current-state-analysis":return M.join(s,"discovery","current-state-analysis.md");case"regression-baseline":return M.join(s,"discovery","regression-baseline.md");case"change-impact":return M.join(s,"discovery","change-impact.md");case"static-model":return M.join(s,"discovery","static-model.md");case"dynamic-model":return M.join(s,"discovery","dynamic-model.md");case"WORKFLOW_ROUTING":return M.join(s,"inception","plans","workflow-routing.md");case"requirements-qa":return M.join(s,"inception","requirements","requirements-analysis-questions.md");case"requirements":return M.join(s,"inception","requirements","requirements.md");case"personas":return M.join(s,"inception","user-stories","personas.md");case"user-stories":return M.join(s,"inception","user-stories","stories.md");case"execution-plan":return M.join(s,"inception","plans","execution-plan.md");case"units-generation":return M.join(s,"inception","units","unit-of-work.md");case"unit-dependency":return M.join(s,"inception","units","unit-of-work-dependency.md");case"unit-story-map":return M.join(s,"inception","units","unit-of-work-story-map.md");case"bolt-spec":if(!r)throw new Error("artifactId (boltId) is required for bolt-spec artifacts");if(!o)throw new Error("unitId is required for bolt-spec artifacts");return M.join(s,"construction",o,"bolts",r,"spec.md");case"bolt-review":if(!r)throw new Error("artifactId (boltId) is required for bolt-review artifacts");if(!o)throw new Error("unitId is required for bolt-review artifacts");return M.join(s,"construction",o,"bolts",r,"review.md");default:throw new Error(`Unknown artifact type: ${n}`)}}async function Xn(e,t,n,r,o,s){let i=lt(e,t,n,o,s),a=await ie.pathExists(i);try{await ie.ensureDir(M.dirname(i)),await ie.writeFile(i,r,"utf-8")}catch(c){let l=c;throw l.code==="ENOSPC"?(console.error(`[Artifacts] Failed to write ${n} artifact: Disk full`),console.error("[Artifacts] Please free up disk space and try again."),console.error(`[Artifacts] Path: ${i}`),new Error(`Failed to write ${n} artifact: Disk is full. Please free up space and retry.`)):l.code==="EACCES"||l.code==="EPERM"?(console.error(`[Artifacts] Failed to write ${n} artifact: Permission denied`),console.error(`[Artifacts] Path: ${i}`),new Error(`Failed to write ${n} artifact: Permission denied for ${i}`)):l.code==="EROFS"?(console.error(`[Artifacts] Failed to write ${n} artifact: Read-only filesystem`),console.error(`[Artifacts] Path: ${i}`),new Error(`Failed to write ${n} artifact: Filesystem is read-only`)):(console.error(`[Artifacts] Failed to write ${n} artifact: ${l.message}`),console.error(`[Artifacts] Path: ${i}`),new Error(`Failed to write ${n} artifact: ${l.message}`))}if(a)try{let c=M.join(e,"aidlc-docs",t,"manifest.json"),{cascadeInvalidation:l,loadManifest:u,saveManifest:d,computeChecksum:p}=await Promise.resolve().then(()=>(Z(),vn)),f=u(c);if(f){let m=i.replace(/\\/g,"/"),g=f.artifacts.find(y=>y.path===m||y.path.endsWith(M.basename(i)));if(g){let y=p(i);y&&(g.checksum=y,g.updated_at=new Date().toISOString(),d(c,f)),l(c,g.id)}}}catch(c){console.error("[Artifacts] Cascade invalidation after write failed:",c)}}async function Qi(e,t){let n=M.join(e,"aidlc-docs",t,"discovery");await ie.ensureDir(n)}async function Dp(e,t,n){let r=M.join(e,"aidlc-docs",t,"audit.md");await ie.ensureDir(M.dirname(r)),await ie.pathExists(r)?await ie.appendFile(r,`
|
|
22
|
+
`)),t}function Br(e){let t=[],n=e.split(`
|
|
23
|
+
`);for(let r of n){let o=r.match(/^\s*[-*+]\s+(?:\[[ x]\]\s+)?(.+)$/);o&&t.push(o[1].trim())}return t}function yv(e,t){let n=hv(e);if(t==="intent-to-unit"){let i=Bi(n),a=[],c=i.get("Business Requirements");c&&a.push(...Br(c));let l=i.get("Implementation Plan");return l&&a.push(...Br(l)),a}if(t==="unit-to-bolt"){let i=Bi(n),a=[],c=i.get("Acceptance Criteria");c&&a.push(...Br(c));let l=i.get("Target Files");return l&&a.push(...Br(l)),a}let r=Bi(n),o=gv[t],s=[];for(let i of o){let a=r.get(i);if(a){let c=Br(a);s.push(...c)}}return s}function Fo(e,t,n){try{let r=yv(e,n);if(r.length===0)return{conformance_score:100,coverage_percentage:100,missing_items:[],passed:!0};let o=t.toLowerCase(),s=[],i=0;for(let d of r){let p=d.toLowerCase();o.includes(p)?i++:s.push(d)}let a=Math.round(i/r.length*100),c=a,l=Ep[n],u=a>=l;return{conformance_score:a,coverage_percentage:c,missing_items:s,passed:u}}catch(r){return console.error("[Alignment] Verification computation failed:",r),{conformance_score:0,coverage_percentage:0,missing_items:["Verification computation error"],passed:!1}}}function Tp(e){let t=mv[e];return[{question:t.verification,answer:null,answered_by:null,passed:null},{question:t.validation,answer:null,answered_by:null,passed:null}]}function Gi(e,t,n,r,o){try{let s=Fo(e,t,o),i=Tp(o),a=i.every(f=>f.answer!==null),c=i.every(f=>f.passed===!0),u={alignment_score:a&&c?100:0,alignment_questions:i,passed:c},d=s.passed&&u.passed;return{source_artifact_id:n,target_artifact_id:r,verification:s,validation:u,alignment_passed:d,checked_at:new Date().toISOString()}}catch(s){return console.error("[Alignment] Alignment check failed:",s),{source_artifact_id:n,target_artifact_id:r,verification:{conformance_score:0,coverage_percentage:0,missing_items:["Alignment check error"],passed:!1},validation:{alignment_score:0,alignment_questions:[],passed:!1},alignment_passed:!1,checked_at:new Date().toISOString()}}}function Jn(e,t,n,r,o,s,i,a){let c=Gi(t,e,s,i,r),l=Gi(n,e,a,i,o),u=c.alignment_passed&&l.alignment_passed;return{parentCheck:c,rootCheck:l,passed:u}}function wv(e,t){let n=0;t>=2&&(n+=10),t>=3&&(n+=10);let r=e-n;return Math.max(0,r)}function _v(e,t){try{let n=W(e);if(!n){console.error(`[Alignment] Manifest not found at ${e}`);return}n.alignment_checks.push(t),G(e,n)}catch(n){console.error("[Alignment] Failed to record alignment result:",n)}}function kv(e){return Ep[e]}var Ep,mv,gv,Mo=U(()=>{"use strict";Z();Ep={"intent-to-unit":95,"unit-to-bolt":100,"unit-to-intent":80,"bolt-to-intent":70},mv={"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?"}},gv={"intent-to-unit":["Business Requirements","Implementation Plan"],"unit-to-bolt":["Acceptance Criteria","Target Files"],"unit-to-intent":["Problem Statement","Success Criteria"],"bolt-to-intent":["Problem Statement","Success Criteria"]}});var kn={};he(kn,{addArtifactLink:()=>Sv,addGateAuditEntry:()=>De,cascadeInvalidation:()=>bv,computeChecksum:()=>Lo,createManifest:()=>qi,detectStaleArtifacts:()=>vv,getArtifactById:()=>Cv,getArtifactsByPhase:()=>Rv,getBoltArtifacts:()=>vt,getBoltsByStatus:()=>Yi,getUnitArtifacts:()=>_n,isWorkflowComplete:()=>xp,linkArtifacts:()=>Vi,loadManifest:()=>W,normalizePath:()=>Hi,recoverManifest:()=>Tv,registerArtifact:()=>$e,revalidateStaleArtifacts:()=>Pv,runAlignmentCheck:()=>Ev,saveManifest:()=>G,transitionToActive:()=>Ki,transitionToDraft:()=>Pp,transitionToFulfilled:()=>Ji,transitionToStale:()=>Ip,transitionToViolated:()=>Ap,updateContractStatus:()=>St,updatePhaseStatus:()=>Nt});function Hi(e){return e.replace(/\\/g,"/")}function tn(){return{status:"not_started",started_at:null,completed_at:null,gate_result:null,gate_bypassed:!1,bypass_reason:null}}function qi(e,t,n){let r=kt.join(n,"aidlc-docs",e),o=kt.join(r,"manifest.json");try{ve.default.ensureDirSync(r);let s=new Date().toISOString(),i={schema_version:"2.0.0",workflow_id:e,feature_name:t,created_at:s,updated_at:s,phases:{discovery:tn(),inception:tn(),construction:tn(),operations:tn()},depth_assessment:null,artifacts:[],links:[],risks:[],gate_audit:[],metrics:null,alignment_checks:[],risk_tier:null};return ve.default.writeFileSync(o,JSON.stringify(i,null,2),"utf-8"),o}catch(s){throw console.error(`Failed to create manifest at ${o}:`,s),s}}function W(e){try{if(!ve.default.existsSync(e))return null;let t=ve.default.readFileSync(e,"utf-8");return JSON.parse(t)}catch(t){return console.error(`Failed to load manifest at ${e}:`,t),null}}function G(e,t){try{t.updated_at=new Date().toISOString(),ve.default.writeFileSync(e,JSON.stringify(t,null,2),"utf-8")}catch(n){throw console.error(`Failed to save manifest at ${e}:`,n),n}}function Lo(e){try{if(!ve.default.existsSync(e))return null;let t=ve.default.readFileSync(e),n=(0,Rp.createHash)("sha256");return n.update(t),n.digest("hex")}catch(t){return console.error(`Failed to compute checksum for ${e}:`,t),null}}function $e(e,t){try{let n=W(e);if(!n)throw new Error(`Manifest not found at ${e}`);let r=new Date().toISOString(),o=Hi(t.path),s=n.artifacts.findIndex(a=>a.id===t.id),i=Lo(t.path);if(s>=0){let a=n.artifacts[s];n.artifacts[s]={...a,...t,path:o,updated_at:r,contract_version:a.contract_version+1,checksum:i}}else{let a={...t,path:o,created_at:r,updated_at:r,contract_version:1,contract_status:"draft",stale_reason:null,checksum:i};n.artifacts.push(a)}G(e,n)}catch(n){throw console.error(`Failed to register artifact in ${e}:`,n),n}}function Vi(e,t){try{let n=W(e);if(!n)throw new Error(`Manifest not found at ${e}`);let r=n.artifacts.some(i=>i.id===t.source_id),o=n.artifacts.some(i=>i.id===t.target_id);if(!r)throw new Error(`Source artifact not found: ${t.source_id}`);if(!o)throw new Error(`Target artifact not found: ${t.target_id}`);n.links.some(i=>i.source_id===t.source_id&&i.target_id===t.target_id&&i.link_type===t.link_type)||(n.links.push(t),G(e,n))}catch(n){throw console.error(`Failed to link artifacts in ${e}:`,n),n}}function Sv(e,t,n,r){e.links.some(s=>s.source_id===t&&s.target_id===n&&s.link_type===r)||e.links.push({source_id:t,target_id:n,link_type:r})}function vv(e){try{let t=W(e);if(!t)return[];let n=[];for(let r of t.artifacts)if(r.checksum&&r.write_complete){let o=Lo(r.path);o&&o!==r.checksum&&n.push(r.id)}return n}catch(t){return console.error(`Failed to detect stale artifacts in ${e}:`,t),[]}}function bv(e,t){try{let n=W(e);if(!n)return;let r=new Set,o=[t];for(;o.length>0;){let s=o.shift();if(r.has(s))continue;r.add(s);let i=n.artifacts.find(c=>c.id===s);if(i){let c=s===t?"Artifact content was modified":`Parent artifact ${s} was modified`;xv(i,c)}let a=n.links.filter(c=>c.source_id===s);for(let c of a)r.has(c.target_id)||o.push(c.target_id)}G(e,n)}catch(n){console.error(`Failed to cascade invalidation in ${e}:`,n)}}function Ev(e,t,n){try{let r=W(e);if(!r)return;let o=new Date().toISOString(),a={source_artifact_id:t,target_artifact_id:n,verification:{conformance_score:0,coverage_percentage:0,missing_items:[],passed:!1},validation:{alignment_score:0,alignment_questions:[],passed:!1},alignment_passed:!1,checked_at:o};r.alignment_checks.push(a),G(e,r)}catch(r){console.error(`Failed to run alignment check in ${e}:`,r)}}function Tv(e,t){try{let n=kt.join(e,"aidlc-docs",t);if(!ve.default.existsSync(n))return null;let r=new Date().toISOString(),o={schema_version:"2.0.0",workflow_id:t,feature_name:"Recovered Workflow",created_at:r,updated_at:r,phases:{discovery:tn(),inception:tn(),construction:tn(),operations:tn()},depth_assessment:null,artifacts:[],links:[],risks:[],gate_audit:[],metrics:null,alignment_checks:[],risk_tier:null},s=ve.default.readdirSync(n,{recursive:!0,withFileTypes:!0});for(let i of s)if(i.isFile()&&i.name!=="manifest.json"){let a=kt.join(i.path,i.name),c=kt.relative(n,a),l=Hi(a),u={id:`recovered-${Date.now()}-${o.artifacts.length}`,type:kt.extname(i.name)||"unknown",phase:"inception",stage:"intent",path:l,created_at:r,updated_at:r,validation_passed:null,write_complete:!0,checksum:Lo(a),contract_status:"draft",contract_version:1,stale_reason:null};o.artifacts.push(u)}return o}catch(n){return console.error(`Failed to recover manifest for workflow ${t}:`,n),null}}function Nt(e,t,n,r,o){try{let s=W(e);if(!s)return;s.phases[t].status=n,r!==void 0&&(s.phases[t].started_at=r),o!==void 0&&(s.phases[t].completed_at=o),G(e,s)}catch(s){console.error(`Failed to update phase status in ${e}:`,s)}}function De(e,t){try{let n=W(e);if(!n)return;let r={...t,timestamp:new Date().toISOString()};n.gate_audit.push(r),G(e,n)}catch(n){console.error(`Failed to add gate audit entry in ${e}:`,n)}}function Cv(e,t){return e.artifacts.find(n=>n.id===t)}function Rv(e,t){return e.artifacts.filter(n=>n.phase===t)}function St(e,t,n,r){try{switch(n){case"draft":Pp(e,t);break;case"active":Ki(e,t);break;case"fulfilled":Ji(e,t);break;case"violated":Ap(e,t);break;case"stale":if(!r)throw new Error('staleReason is required when setting status to "stale"');Ip(e,t,r);break}}catch(o){console.error(`Failed to update contract status in ${e}:`,o)}}function _n(e){return e.artifacts.filter(t=>t.stage==="unit")}function vt(e,t){let n=e.artifacts.filter(r=>r.stage==="code-generation");if(t){let r=new Set(e.links.filter(o=>o.source_id===t&&(o.link_type==="derives"||o.link_type==="implements")).map(o=>o.target_id));return n.filter(o=>r.has(o.id))}return n}function Yi(e,t){return e.artifacts.filter(n=>n.stage==="code-generation"&&n.contract_status===t)}function xp(e){let t=e.artifacts.filter(n=>n.stage==="code-generation");return t.length===0?!1:t.every(n=>n.contract_status==="fulfilled")}function xv(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 Pp(e,t){let n=W(e);if(!n)throw new Error(`Manifest not found at ${e}`);let r=n.artifacts.find(o=>o.id===t);if(!r)throw new Error(`Artifact ${t} not found in manifest`);if(r.contract_status!=="violated"&&r.contract_status!=="stale")throw new Error(`Cannot transition from '${r.contract_status}' to 'draft'`);r.contract_status="draft",r.stale_reason=null,r.statusHistory||(r.statusHistory=[]),r.statusHistory.push({status:"draft",timestamp:new Date().toISOString()}),G(e,n)}function Ki(e,t){let n=W(e);if(!n)throw new Error(`Manifest not found at ${e}`);let r=n.artifacts.find(o=>o.id===t);if(!r)throw new Error(`Artifact ${t} not found in manifest`);if(r.contract_status!=="draft"&&r.contract_status!=="stale")throw new Error(`Cannot transition from '${r.contract_status}' to 'active'`);r.contract_status="active",r.stale_reason=null,r.statusHistory||(r.statusHistory=[]),r.statusHistory.push({status:"active",timestamp:new Date().toISOString()}),G(e,n)}function Ji(e,t){let n=W(e);if(!n)throw new Error(`Manifest not found at ${e}`);let r=n.artifacts.find(o=>o.id===t);if(!r)throw new Error(`Artifact ${t} not found in manifest`);if(r.contract_status!=="active")throw new Error(`Cannot transition from '${r.contract_status}' to 'fulfilled'`);r.contract_status="fulfilled",r.stale_reason=null,r.statusHistory||(r.statusHistory=[]),r.statusHistory.push({status:"fulfilled",timestamp:new Date().toISOString()}),G(e,n)}function Ap(e,t){let n=W(e);if(!n)throw new Error(`Manifest not found at ${e}`);let r=n.artifacts.find(o=>o.id===t);if(!r)throw new Error(`Artifact ${t} not found in manifest`);if(r.contract_status!=="active")throw new Error(`Cannot transition from '${r.contract_status}' to 'violated'`);r.contract_status="violated",r.stale_reason=null,r.statusHistory||(r.statusHistory=[]),r.statusHistory.push({status:"violated",timestamp:new Date().toISOString()}),G(e,n)}function Ip(e,t,n){let r=W(e);if(!r)throw new Error(`Manifest not found at ${e}`);let o=r.artifacts.find(s=>s.id===t);if(!o)throw new Error(`Artifact ${t} not found in manifest`);if(o.contract_status!=="active"&&o.contract_status!=="fulfilled")throw new Error(`Cannot transition from '${o.contract_status}' to 'stale'`);o.contract_status="stale",o.stale_reason=n,o.statusHistory||(o.statusHistory=[]),o.statusHistory.push({status:"stale",timestamp:new Date().toISOString()}),G(e,r)}async function Pv(e,t){let n={restored:[],stillStale:[],errors:[]},r=kt.join(e,"aidlc-docs",t,"manifest.json"),o=W(r);if(!o)return n.errors.push("Manifest not found"),n;let s=o.artifacts.filter(i=>i.contract_status==="stale");for(let i of s)try{let a=o.links.find(w=>w.target_id===i.id);if(!a){n.stillStale.push(i.id);continue}let c=o.artifacts.find(w=>w.id===a.source_id);if(!c){n.stillStale.push(i.id);continue}let l=o.artifacts.find(w=>w.stage==="intent");if(!l){n.stillStale.push(i.id);continue}let u=ve.default.existsSync(i.path)?ve.default.readFileSync(i.path,"utf-8"):null,d=ve.default.existsSync(c.path)?ve.default.readFileSync(c.path,"utf-8"):null,p=ve.default.existsSync(l.path)?ve.default.readFileSync(l.path,"utf-8"):null;if(!u||!d||!p){n.stillStale.push(i.id);continue}let{runDualValidation:f}=await Promise.resolve().then(()=>(Mo(),Cp)),m,g;if(i.stage==="unit")m="intent-to-unit",g="unit-to-intent";else if(i.stage==="code-generation")m="unit-to-bolt",g="bolt-to-intent";else{n.stillStale.push(i.id);continue}f(u,d,p,m,g,c.id,i.id,l.id).passed?(i.contract_status="active",i.stale_reason=null,i.statusHistory||(i.statusHistory=[]),i.statusHistory.push({status:"active",timestamp:new Date().toISOString()}),n.restored.push(i.id)):n.stillStale.push(i.id)}catch(a){n.errors.push(`Error revalidating ${i.id}: ${a}`),n.stillStale.push(i.id)}return G(r,o),n}var ve,kt,Rp,Z=U(()=>{"use strict";ve=v(X(),1),kt=v(require("path"),1),Rp=require("crypto")});async function Op(e,t){let n=M.join(e,"aidlc-docs",t),r=M.join(n,"checkpoint.json");try{await ie.ensureDir(n),await ie.ensureDir(M.join(n,"inception")),await ie.ensureDir(M.join(n,"construction")),await ie.ensureDir(M.join(n,"construction","design")),await ie.ensureDir(M.join(n,"operations")),await ie.pathExists(r)||await ie.writeJson(r,{workflow_id:t,current_stage:"intent",created_at:new Date().toISOString(),updated_at:new Date().toISOString()},{spaces:2})}catch(o){let s=o;throw s.code==="ENOSPC"?(console.error("[Artifacts] Failed to create workflow directory: Disk full"),console.error("[Artifacts] Please free up disk space and try again."),console.error(`[Artifacts] Attempted path: ${n}`),new Error("Failed to create workflow directory: Disk is full. Please free up space and retry.")):s.code==="EACCES"||s.code==="EPERM"?(console.error("[Artifacts] Failed to create workflow directory: Permission denied"),console.error(`[Artifacts] Path: ${n}`),new Error(`Failed to create workflow directory: Permission denied for ${n}`)):s.code==="EROFS"?(console.error("[Artifacts] Failed to create workflow directory: Read-only filesystem"),console.error(`[Artifacts] Path: ${n}`),new Error("Failed to create workflow directory: Filesystem is read-only")):(console.error(`[Artifacts] Failed to create workflow directory: ${s.message}`),console.error(`[Artifacts] Workflow ID: ${t}`),console.error(`[Artifacts] Path: ${n}`),new Error(`Failed to create workflow directory for ${t}: ${s.message}`))}}function at(e,t,n,r,o){let s=M.join(e,"aidlc-docs",t);switch(n){case"intent":return M.join(s,"inception","intent.md");case"nfr":return M.join(s,"inception","requirements","nfr.md");case"unit":if(!r)throw new Error("artifactId is required for unit artifacts");return M.join(s,"construction",r,"spec.md");case"code-generation":if(!r)throw new Error("artifactId is required for code-generation artifacts");if(!o)throw new Error("unitId is required for code-generation artifacts");return M.join(s,"construction",o,`${r}.md`);case"validation-report":if(!r)throw new Error("artifactId is required for validation-report artifacts");return M.join(s,"construction",r,"validation-report.md");case"interfaces":return M.join(s,"construction","design","interfaces.json");case"data-flow":return M.join(s,"construction","design","data-flow.json");case"components":return M.join(s,"construction","design","components.json");case"deploy-guide":return M.join(s,"operations","deploy-guide.md");case"runbook":return M.join(s,"operations","runbook.md");case"monitoring":return M.join(s,"operations","monitoring.json");case"release-notes":return M.join(s,"operations","release-notes.md");case"state":return M.join(s,"state.md");case"audit":return M.join(s,"audit.md");case"analysis-plan":return M.join(s,"discovery","analysis-plan.md");case"current-state-analysis":return M.join(s,"discovery","current-state-analysis.md");case"regression-baseline":return M.join(s,"discovery","regression-baseline.md");case"change-impact":return M.join(s,"discovery","change-impact.md");case"static-model":return M.join(s,"discovery","static-model.md");case"dynamic-model":return M.join(s,"discovery","dynamic-model.md");case"WORKFLOW_ROUTING":return M.join(s,"inception","plans","workflow-routing.md");case"requirements-qa":return M.join(s,"inception","requirements","requirements-analysis-questions.md");case"requirements":return M.join(s,"inception","requirements","requirements.md");case"personas":return M.join(s,"inception","user-stories","personas.md");case"user-stories":return M.join(s,"inception","user-stories","stories.md");case"execution-plan":return M.join(s,"inception","plans","execution-plan.md");case"units-generation":return M.join(s,"inception","units","unit-of-work.md");case"unit-dependency":return M.join(s,"inception","units","unit-of-work-dependency.md");case"unit-story-map":return M.join(s,"inception","units","unit-of-work-story-map.md");case"bolt-spec":if(!r)throw new Error("artifactId (boltId) is required for bolt-spec artifacts");if(!o)throw new Error("unitId is required for bolt-spec artifacts");return M.join(s,"construction",o,"bolts",r,"spec.md");case"bolt-review":if(!r)throw new Error("artifactId (boltId) is required for bolt-review artifacts");if(!o)throw new Error("unitId is required for bolt-review artifacts");return M.join(s,"construction",o,"bolts",r,"review.md");default:throw new Error(`Unknown artifact type: ${n}`)}}async function zn(e,t,n,r,o,s){let i=at(e,t,n,o,s),a=await ie.pathExists(i);try{await ie.ensureDir(M.dirname(i)),await ie.writeFile(i,r,"utf-8")}catch(c){let l=c;throw l.code==="ENOSPC"?(console.error(`[Artifacts] Failed to write ${n} artifact: Disk full`),console.error("[Artifacts] Please free up disk space and try again."),console.error(`[Artifacts] Path: ${i}`),new Error(`Failed to write ${n} artifact: Disk is full. Please free up space and retry.`)):l.code==="EACCES"||l.code==="EPERM"?(console.error(`[Artifacts] Failed to write ${n} artifact: Permission denied`),console.error(`[Artifacts] Path: ${i}`),new Error(`Failed to write ${n} artifact: Permission denied for ${i}`)):l.code==="EROFS"?(console.error(`[Artifacts] Failed to write ${n} artifact: Read-only filesystem`),console.error(`[Artifacts] Path: ${i}`),new Error(`Failed to write ${n} artifact: Filesystem is read-only`)):(console.error(`[Artifacts] Failed to write ${n} artifact: ${l.message}`),console.error(`[Artifacts] Path: ${i}`),new Error(`Failed to write ${n} artifact: ${l.message}`))}if(a)try{let c=M.join(e,"aidlc-docs",t,"manifest.json"),{cascadeInvalidation:l,loadManifest:u,saveManifest:d,computeChecksum:p}=await Promise.resolve().then(()=>(Z(),kn)),f=u(c);if(f){let m=i.replace(/\\/g,"/"),g=f.artifacts.find(y=>y.path===m||y.path.endsWith(M.basename(i)));if(g){let y=p(i);y&&(g.checksum=y,g.updated_at=new Date().toISOString(),d(c,f)),l(c,g.id)}}}catch(c){console.error("[Artifacts] Cascade invalidation after write failed:",c)}}async function zi(e,t){let n=M.join(e,"aidlc-docs",t,"discovery");await ie.ensureDir(n)}async function $p(e,t,n){let r=M.join(e,"aidlc-docs",t,"audit.md");await ie.ensureDir(M.dirname(r)),await ie.pathExists(r)?await ie.appendFile(r,`
|
|
24
24
|
`+n,"utf-8"):await ie.writeFile(r,`# Audit Log
|
|
25
25
|
|
|
26
|
-
${n}`,"utf-8")}var M,ie,
|
|
27
|
-
`,"utf-8"),t}function
|
|
28
|
-
`).filter(u=>u.trim()),c=!1,l=a.map(u=>{try{let d=JSON.parse(u);return d.id===e&&(c=!0,d.verification_count=(d.verification_count||0)+1,d.last_useful=new Date().toISOString()),JSON.stringify(d)}catch{return u}});if(c){let u=(0,
|
|
26
|
+
${n}`,"utf-8")}var M,ie,Qi=U(()=>{"use strict";M=v(require("path"),1),ie=v(X(),1)});function df(){return{current_level:0,total_transitions:0,rejection_count:0,rejection_rate:0,incident_count:0,last_level_change:null,level_history:[],consecutive_rejections:0,transition_history:[]}}function be(e){try{let t=e||process.cwd(),n=(0,Vo.join)(t,pf);if(!(0,Ft.existsSync)(n))return df();let r=(0,Ft.readFileSync)(n,"utf-8"),o=JSON.parse(r);return o.consecutive_rejections===void 0&&(o.consecutive_rejections=0),Array.isArray(o.transition_history)||(o.transition_history=[]),o}catch(t){return console.error("Error loading trust state:",t),df()}}function pa(e,t){try{let n=t||process.cwd(),r=(0,Vo.join)(n,".olympus"),o=(0,Vo.join)(n,pf);(0,Ft.existsSync)(r)||(0,Ft.mkdirSync)(r,{recursive:!0}),(0,Ft.writeFileSync)(o,JSON.stringify(e,null,2),"utf-8")}catch(n){console.error("Error saving trust state:",n)}}function Nb(e){return e.total_transitions>=50&&e.rejection_rate<.02&&e.incident_count===0?3:e.total_transitions>=20&&e.rejection_rate<.05?2:e.total_transitions>=10?1:0}function fa(e,t,n,r){let o=e.total_transitions+1,s=n?e.rejection_count+1:e.rejection_count,i=s/o,a=n?e.consecutive_rejections+1:0,c={success:t,rejected:n,metadata:r,timestamp:new Date().toISOString()},l=[...e.transition_history,c].slice(-100),u={...e,total_transitions:o,rejection_count:s,rejection_rate:i,consecutive_rejections:a,transition_history:l},d=Nb(u);if(d!==e.current_level){let p={from:e.current_level,to:d,reason:d>e.current_level?"Qualification threshold met":"Metrics degraded",timestamp:new Date().toISOString()};return{...u,current_level:d,last_level_change:p.timestamp,level_history:[...e.level_history,p]}}return u}function ff(e,t){return t>=e}var Ft,Vo,pf,rn=U(()=>{"use strict";Ft=require("fs"),Vo=require("path"),pf=".olympus/trust-state.json"});function ue(e){let t={...e,id:(0,gf.randomUUID)(),timestamp:new Date().toISOString(),verified:!1,verification_count:0,last_useful:new Date().toISOString()},n=t.scope==="global"?pe():yt(t.project_path);Bn(t.project_path);let r=(0,on.join)(n,"discoveries.jsonl");return Wn(r),(0,Be.appendFileSync)(r,JSON.stringify(t)+`
|
|
27
|
+
`,"utf-8"),t}function jb(e){let t=(0,on.join)(pe(),"discoveries.jsonl"),n=yt(e),r=(0,on.join)(n,"discoveries.jsonl"),o=mf(t),s=mf(r),i=[...o,...s],a={technical_insight:0,workaround:0,pattern:0,gotcha:0,performance:0,dependency:0,configuration:0,planning_insight:0,workflow_gate:0,retro_insight:0};for(let l of i)a[l.category]++;let c=[...i].sort((l,u)=>u.verification_count-l.verification_count);return{project_discoveries:s,global_discoveries:o,total_discoveries:i.length,categories:a,most_useful:c.slice(0,5)}}function hf(e,t){let n=(0,on.join)(pe(),"discoveries.jsonl"),r=(0,on.join)(t,".olympus","learning","discoveries.jsonl"),o=s=>{if(!(0,Be.existsSync)(s))return!1;let a=(0,Be.readFileSync)(s,"utf-8").trim().split(`
|
|
28
|
+
`).filter(u=>u.trim()),c=!1,l=a.map(u=>{try{let d=JSON.parse(u);return d.id===e&&(c=!0,d.verification_count=(d.verification_count||0)+1,d.last_useful=new Date().toISOString()),JSON.stringify(d)}catch{return u}});if(c){let u=(0,on.dirname)(s);(0,Be.existsSync)(u)||(0,Be.mkdirSync)(u,{recursive:!0}),(0,Be.writeFileSync)(s,l.join(`
|
|
29
29
|
`)+`
|
|
30
|
-
`,"utf-8")}return c};o(r)||o(n)}function
|
|
31
|
-
`).filter(n=>n.trim()).map(n=>JSON.parse(n))}catch(t){return console.error(`[Olympus Learning] Failed to read discoveries: ${t}`),[]}}var
|
|
32
|
-
`);u+=_.filter(h=>h.toLowerCase().includes("fail")).length}}}let p=(o.gate_audit||[]).length,f=a.length;return{workflowId:o.workflow_id||"",featureName:o.feature_name||"",gateRejections:a,cascadeEvents:c,trustDecreases:l,ciFailureCount:u,totalGates:p,totalRejections:f}}function
|
|
33
|
-
`)}async function
|
|
34
|
-
`);
|
|
35
|
-
`;
|
|
30
|
+
`,"utf-8")}return c};o(r)||o(n)}function Yo(e,t=10){let n=jb(e),r=[...n.project_discoveries,...n.global_discoveries],o=new Date,i=r.filter(a=>a.expires_at?new Date(a.expires_at)>o:!0).map(a=>{let c=(o.getTime()-new Date(a.timestamp).getTime())/864e5,l=Math.max(.1,1-c/90),u=(a.verification_count+1)*l*a.confidence;return{discovery:a,score:u}});return i.sort((a,c)=>c.score-a.score),i.slice(0,t).map(a=>a.discovery)}function mf(e){if(!(0,Be.existsSync)(e))return[];try{return(0,Be.readFileSync)(e,"utf-8").split(`
|
|
31
|
+
`).filter(n=>n.trim()).map(n=>JSON.parse(n))}catch(t){return console.error(`[Olympus Learning] Failed to read discoveries: ${t}`),[]}}var on,Be,gf,Mt=U(()=>{"use strict";on=require("path"),Be=require("fs"),gf=require("crypto");ye()});function yf(e,t){let n=t||"",r=n?(0,tr.join)(e,"aidlc-docs",n,"manifest.json"):(0,tr.join)(e,"aidlc-docs","manifest.json"),o=W(r),s=be(e),i={workflowId:"",featureName:"",gateRejections:[],cascadeEvents:[],trustDecreases:[],ciFailureCount:0,totalGates:0,totalRejections:0};if(!o)return i;let a=(o.gate_audit||[]).filter(m=>m.action==="rejected").map(m=>({phase:m.phase,timestamp:m.timestamp,reason:m.reason||null,actor:m.actor})),c=[];for(let m of o.artifacts||[])if(m.statusHistory)for(let g of m.statusHistory)(g.status.toLowerCase().includes("stale")||g.status.toLowerCase().includes("violated"))&&c.push({artifactId:m.id,status:g.status,timestamp:g.timestamp});let l=(s?.level_history||[]).filter(m=>m.to<m.from).map(m=>({from:m.from,to:m.to,reason:m.reason,timestamp:m.timestamp})),u=0,d=n?(0,tr.join)(e,"aidlc-docs",n,"construction"):(0,tr.join)(e,"aidlc-docs","construction");if((0,Lt.existsSync)(d)){let m=(0,Lt.readdirSync)(d,{withFileTypes:!0}).filter(g=>g.isDirectory()&&g.name.startsWith("UNIT-")).map(g=>g.name);for(let g of m){let y=(0,tr.join)(d,g,"validation-report.md");if((0,Lt.existsSync)(y)){let _=(0,Lt.readFileSync)(y,"utf-8").split(`
|
|
32
|
+
`);u+=_.filter(h=>h.toLowerCase().includes("fail")).length}}}let p=(o.gate_audit||[]).length,f=a.length;return{workflowId:o.workflow_id||"",featureName:o.feature_name||"",gateRejections:a,cascadeEvents:c,trustDecreases:l,ciFailureCount:u,totalGates:p,totalRejections:f}}function wf(e){let t=[],n=new Map;for(let r of e.gateRejections){let o=(r.reason||"unspecified").toLowerCase().trim();n.has(o)||n.set(o,[]),n.get(o).push(r)}for(let[r,o]of n.entries()){let s=o.length,i=s>=3?"High":s===2?"Medium":"Low",c=`Gate rejections in ${o.map(u=>u.phase).join(", ")} with reason: "${r}"`,l=s>1?`Review and address recurring gate rejection pattern: "${r}". Consider improving upstream validation or documentation.`:`Address gate rejection: "${r}". Ensure requirements are clear before implementation.`;t.push({description:`Gate rejection pattern: ${r}`,evidence:c,suggestion:l,confidence:i,occurrences:s})}if(e.trustDecreases.length>0){let r=e.trustDecreases.length,o=r>=3?"High":r===2?"Medium":"Low",s=e.trustDecreases.map(i=>`${i.from} \u2192 ${i.to} (${i.reason})`).join("; ");t.push({description:"Trust level decreases detected",evidence:`Trust trajectory: ${s}`,suggestion:"Improve code quality and validation processes to rebuild trust. Consider more thorough review before gate submissions.",confidence:o,occurrences:r})}if(e.cascadeEvents.length>0){let r=e.cascadeEvents.length,o=r>=3?"High":r===2?"Medium":"Low",s=[...new Set(e.cascadeEvents.map(i=>i.artifactId))].join(", ");t.push({description:"Cascade invalidation events",evidence:`${r} invalidation event(s) affecting: ${s}`,suggestion:"Strengthen contract verification and dependency validation to prevent cascading failures. Consider improving artifact stability.",confidence:o,occurrences:r})}return t}var Lt,tr,_f=U(()=>{"use strict";Lt=require("fs"),tr=require("path");Z();rn();Mt()});function Fb(e){return(e.gate_audit||[]).map(t=>({timestamp:t.timestamp,phase:t.phase,action:t.action,actor:t.actor,reason:t.reason??null})).sort((t,n)=>t.timestamp.localeCompare(n.timestamp))}function Mb(e){let t=e.artifacts||[],n=e.links||[];return t.filter(o=>o.stage==="intent").map(o=>{let s=n.filter(c=>c.source_id===o.id&&(c.link_type==="derives"||c.link_type==="implements")).map(c=>c.target_id).filter(c=>t.some(l=>l.id===c&&l.stage==="unit")),i=[];for(let c of s){let l=n.filter(u=>u.source_id===c&&(u.link_type==="derives"||u.link_type==="implements")).map(u=>u.target_id).filter(u=>t.some(d=>d.id===u&&d.stage==="code-generation"));i.push(...l)}let a=[...new Set(i.flatMap(c=>{let l=t.find(d=>d.id===c);if(!l)return[];let u=bt.extname(l.path).toLowerCase();return u&&u!==".md"&&u!==".json"?[l.path]:[]}))];return{intentId:o.id,unitIds:s,codeGenerationIds:[...new Set(i)],codeFiles:a}})}function Lb(e){return(e.level_history||[]).map(t=>({from:t.from,to:t.to,reason:t.reason,timestamp:t.timestamp}))}function Ub(e){let t=[];for(let n of e.artifacts||[]){if(!n.statusHistory||n.statusHistory.length<2)continue;let r=n.statusHistory;for(let o=1;o<r.length;o++){let s=r[o-1],i=r[o],a=i.status.toLowerCase();(a.includes("stale")||a.includes("violated"))&&t.push({artifactId:n.id,previousStatus:s.status,newStatus:i.status,reason:n.stale_reason??`Artifact transitioned to ${i.status}`,timestamp:i.timestamp})}}return t.sort((n,r)=>n.timestamp.localeCompare(r.timestamp))}function kf(e){return{workflowId:e,featureName:"",generatedAt:new Date().toISOString(),timeline:[],traceabilityMatrix:[],trustHistory:[],cascadeEvents:[],retroInsights:[]}}function Sf(e,t){try{let n=bt.join(e,"aidlc-docs",t,"manifest.json"),r=W(n);if(!r)return kf(t);let o=be(e),s=yf(e,t),a=wf(s).filter(c=>c.confidence==="High"||c.confidence==="Medium").map(c=>c.description);return{workflowId:r.workflow_id,featureName:r.feature_name,generatedAt:new Date().toISOString(),timeline:Fb(r),traceabilityMatrix:Mb(r),trustHistory:Lb(o),cascadeEvents:Ub(r),retroInsights:a}}catch(n){return console.error(`Failed to generate audit document for workflow ${t}:`,n),kf(t)}}function ma(e){let t=[];if(t.push(`# Audit Report: ${e.featureName}`),t.push(""),t.push(`Generated: ${e.generatedAt}`),t.push(`Workflow ID: ${e.workflowId}`),t.push(""),t.push("## Timeline"),t.push(""),e.timeline.length===0)t.push("_No gate decisions recorded._");else{t.push("| Timestamp | Phase | Action | Actor | Reason |"),t.push("|-----------|-------|--------|-------|--------|");for(let n of e.timeline)t.push(`| ${n.timestamp} | ${n.phase} | ${n.action} | ${n.actor} | ${n.reason??"\u2014"} |`)}if(t.push(""),t.push("## Traceability Matrix"),t.push(""),e.traceabilityMatrix.length===0)t.push("_No traceability data available._");else{t.push("| Intent | Units | Code Generation | Code Files |"),t.push("|--------|-------|-----------------|------------|");for(let n of e.traceabilityMatrix){let r=n.unitIds.length>0?n.unitIds.join(", "):"\u2014",o=n.codeGenerationIds.length>0?n.codeGenerationIds.join(", "):"\u2014",s=n.codeFiles.length>0?n.codeFiles.join(", "):"\u2014";t.push(`| ${n.intentId} | ${r} | ${o} | ${s} |`)}}if(t.push(""),t.push("## Trust History"),t.push(""),e.trustHistory.length===0)t.push("_No trust level changes recorded._");else{t.push("| From | To | Reason | Timestamp |"),t.push("|------|----|--------|-----------|");for(let n of e.trustHistory)t.push(`| ${n.from} | ${n.to} | ${n.reason} | ${n.timestamp} |`)}if(t.push(""),t.push("## Cascade Events"),t.push(""),e.cascadeEvents.length===0)t.push("_No cascade invalidation events recorded._");else for(let n of e.cascadeEvents)t.push(`- **${n.artifactId}**: \`${n.previousStatus}\` \u2192 \`${n.newStatus}\` \u2014 ${n.reason} _(${n.timestamp})_`);if(t.push(""),t.push("## Retrospective Insights"),t.push(""),e.retroInsights.length===0)t.push("_No retrospective insights available._");else for(let n of e.retroInsights)t.push(`- ${n}`);return t.push(""),t.join(`
|
|
33
|
+
`)}async function vf(e,t,n){let r=bt.join(e,"aidlc-docs",t),o=bt.join(r,"audit.md"),s=bt.join(r,"manifest.json");try{let i=ma(n);await ze.ensureDir(r),await ze.writeFile(o,i,"utf-8"),$e(s,{id:`audit-${t}`,type:"AUDIT",phase:"operations",stage:"complete",path:o,validation_passed:null,write_complete:!0,checksum:null})}catch(i){console.error(`Failed to write audit artifact for workflow ${t}:`,i)}return o}function Ko(e,t,n){try{let r=bt.join(e,"aidlc-docs",t,"audit.md");if(!ze.existsSync(r)){let s=["# Audit Report","",`Generated: ${new Date().toISOString()}`,`Workflow ID: ${t}`,"","## Timeline","","| Timestamp | Phase | Action | Actor | Reason |","|-----------|-------|--------|-------|--------|",""].join(`
|
|
34
|
+
`);ze.ensureDirSync(bt.dirname(r)),ze.writeFileSync(r,s,"utf-8")}let o=`| ${n.timestamp} | ${n.phase} | ${n.action} | ${n.actor} | ${n.reason??"\u2014"} |
|
|
35
|
+
`;ze.appendFileSync(r,o,"utf-8")}catch(r){console.error(`Failed to append to audit for workflow ${t}:`,r)}}var ze,bt,ga=U(()=>{"use strict";ze=v(X(),1),bt=v(require("path"),1);Z();rn();_f()});var ha={};he(ha,{captureBaseline:()=>Wb,compareAgainstBaseline:()=>Bb,writeRegressionReport:()=>Gb});async function Wb(e,t,n){let r=qr.default.join(e,"aidlc-docs",t,"construction");await Hr.default.ensureDir(r);let o=Hb(n),s="",i="";try{s=(0,Ef.execSync)(n,{cwd:e,encoding:"utf-8",stdio:"pipe"})}catch(m){let g=m;s=g.stdout??"",i=g.stderr??""}let c=qb(s||i,o),l=c.filter(m=>m.status==="passed").length,u=c.filter(m=>m.status==="failed").length,d=c.filter(m=>m.status==="skipped").length,p={tests:c.map(m=>({name:m.name,filePath:m.filePath,status:m.status,duration_ms:m.duration_ms})),captured_at:new Date().toISOString(),test_command:n,framework:o,total:c.length,passed:l,failed:u,skipped:d},f=qr.default.join(r,"regression-baseline.json");return await Hr.default.writeJson(f,p,{spaces:2}),p}function Bb(e,t){let n=new Map;for(let i of e.tests)n.set(i.name,i);let r=[],o=[],s=[];for(let i of t){let a=n.get(i.name);if(!a){i.status==="failed"&&r.push({name:i.name,filePath:i.filePath});continue}(a.status==="passed"||a.status==="skipped")&&i.status==="failed"&&r.push({name:i.name,filePath:i.filePath}),a.status==="failed"&&i.status==="passed"&&o.push({name:i.name,filePath:i.filePath});let c=Math.abs(i.duration_ms-a.duration_ms);c>100&&s.push({name:i.name,before_ms:a.duration_ms,after_ms:i.duration_ms,delta_ms:c})}return{new_failures:r,new_passes:o,timing_changes:s,computed_at:new Date().toISOString()}}async function Gb(e,t,n,r){let o=qr.default.join(e,"aidlc-docs",t,"construction",n,"testing");await Hr.default.ensureDir(o);let s=qr.default.join(o,"regression-report.md"),i=r.failures.map(c=>`| ${c.test_name} | ${c.file_path} | ${c.category} | ${c.rationale} |`).join(`
|
|
36
36
|
`),a=`# Regression Report
|
|
37
37
|
|
|
38
38
|
**Workflow ID**: ${r.workflow_id}
|
|
@@ -52,20 +52,20 @@ ${n}`,"utf-8")}var M,ie,Xi=U(()=>{"use strict";M=v(require("path"),1),ie=v(X(),1
|
|
|
52
52
|
| Test Name | File Path | Category | Rationale |
|
|
53
53
|
|---|---|---|---|
|
|
54
54
|
${i||"| _No failures_ | | | |"}
|
|
55
|
-
`;await
|
|
56
|
-
`),n=[],r="unknown";for(let o of t){let s=o.trim(),i=s.match(/^(?:FAIL|PASS)\s+(src\S+)/);if(i){r=i[1];continue}let a=[/^[✓√]\s+(.+?)(?:\s+\((\d+)ms\)|\s+(\d+)ms)?$/,/^ok\s+\d+\s+-\s+(.+?)(?:\s+#.*)?(?:\s+(\d+)ms)?$/],c=[/^[✗×]\s+(.+?)(?:\s+\((\d+)ms\)|\s+(\d+)ms)?$/,/^not ok\s+\d+\s+-\s+(.+?)(?:\s+#.*)?(?:\s+(\d+)ms)?$/],l=!1;for(let u of a){let d=s.match(u);if(d){n.push({name:d[1].trim(),filePath:r,status:"passed",duration_ms:
|
|
57
|
-
`);return d.length>
|
|
58
|
-
...(truncated)`),d}var
|
|
59
|
-
`).length}catch{return 0}}function
|
|
60
|
-
`),o=0;for(;o<r.length;){let s=r[o],i=/^##\s+(.+)$/.exec(s);if(i){let c=i[1].trim(),l=[];for(o++;o<r.length&&!/^##/.test(r[o]);){let u=r[o].trim();u.length>0&&l.push(u),o++}l.length>0&&n.push({path:c,description:l.join(" ")});continue}let a=/^[-*]\s+\*{0,2}([^*:]+)\*{0,2}:\s*(.+)$/.exec(s);if(a){let c=a[1].trim(),l=a[2].trim();c&&l&&n.push({path:c,description:l})}o++}return{relativeFilePath:t,pathDescriptionPairs:n}}async function
|
|
61
|
-
`).map(r=>r.trim()).filter(r=>r.length>0)}catch{return[]}}async function
|
|
55
|
+
`;await Hr.default.writeFile(s,a,"utf-8")}function Hb(e){return e.includes("vitest")?"vitest":e.includes("jest")?"jest":"unknown"}function qb(e,t){if(e.includes('"numPassedTests"'))try{let n=e.indexOf("{");if(n!==-1){let r=JSON.parse(e.slice(n)),o=[];if(Array.isArray(r.testResults))for(let s of r.testResults){let i=s.testFilePath??s.name??"unknown";for(let a of s.assertionResults??[])o.push({name:a.fullName??a.title??"unnamed",filePath:i,status:Vb(a.status),duration_ms:a.duration??0})}if(o.length>0)return o}}catch{}return Yb(e)}function Vb(e){return e==="passed"?"passed":e==="failed"?"failed":"skipped"}function Yb(e){let t=e.split(`
|
|
56
|
+
`),n=[],r="unknown";for(let o of t){let s=o.trim(),i=s.match(/^(?:FAIL|PASS)\s+(src\S+)/);if(i){r=i[1];continue}let a=[/^[✓√]\s+(.+?)(?:\s+\((\d+)ms\)|\s+(\d+)ms)?$/,/^ok\s+\d+\s+-\s+(.+?)(?:\s+#.*)?(?:\s+(\d+)ms)?$/],c=[/^[✗×]\s+(.+?)(?:\s+\((\d+)ms\)|\s+(\d+)ms)?$/,/^not ok\s+\d+\s+-\s+(.+?)(?:\s+#.*)?(?:\s+(\d+)ms)?$/],l=!1;for(let u of a){let d=s.match(u);if(d){n.push({name:d[1].trim(),filePath:r,status:"passed",duration_ms:bf(d[2]??d[3])}),l=!0;break}}if(!l)for(let u of c){let d=s.match(u);if(d){n.push({name:d[1].trim(),filePath:r,status:"failed",duration_ms:bf(d[2]??d[3])});break}}}return n}function bf(e){if(!e)return 0;let t=parseInt(e,10);return isNaN(t)?0:t}var Hr,qr,Ef,ya=U(()=>{"use strict";Hr=v(X(),1),qr=v(require("path"),1),Ef=require("child_process")});function Cf(e){let t={id:(0,Tf.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};zt(t)}function Rf(e){let t=Eo();return To(e,t)}var Tf,Jo=U(()=>{"use strict";Tf=require("crypto");ye()});var Qo={};he(Qo,{generateArchitectureModel:()=>wa,getArchitectureContext:()=>tE,initializeGreenfieldArchitectureModel:()=>Zb,loadArchitectureModel:()=>_a,saveArchitectureModel:()=>Vr,updateArchitectureModel:()=>eE});function Of(e,t){let n=[],r=/export\s+interface\s+(\w+)\s*(?:<[^{]*>)?\s*\{([^}]*)\}/g,o;for(;(o=r.exec(t))!==null;)n.push({name:o[1],path:e,fields:Pf(o[2]),exported:!0});let s=/export\s+type\s+(\w+)\s*(?:<[^=]*>)?\s*=\s*\{([^}]*)\}/g;for(;(o=s.exec(t))!==null;)n.push({name:o[1],path:e,fields:Pf(o[2]),exported:!0});return n}function Pf(e){let t=[],n=/(\w+)\??:\s*([^;,\n]+)/g,r;for(;(r=n.exec(e))!==null;)t.push({name:r[1].trim(),type:r[2].trim()});return t}function $f(e,t){let n=[],r=/export\s+(?:async\s+)?function\s+(\w+)\s*(<[^(]*)?\(([^)]*)\)\s*(?::\s*([^\n{]+))?/g,o;for(;(o=r.exec(t))!==null;){let s=o[1],i=o[3]?o[3].trim():"",a=o[4]?o[4].trim():"void",l=`${/export\s+async\s+function/.test(o[0])?"async ":""}function ${s}(${i}): ${a}`;n.push({name:s,path:e,signature:l,exported:!0,description:""})}return n}function Kb(e){let t="module";return e.name==="services"||e.name.endsWith("-service")?t="service":(e.name==="packages"||e.children.length>3)&&(t="package"),{name:e.name,path:e.path,description:`${e.name} module (${e.fileCount} files)`,type:t,fileCount:e.fileCount}}function Jb(e){let t=new Set,n=[];for(let r of e){let o=zo(r.sourceFile),s=zo(r.importedModule);if(!o||!s||o===s)continue;let i=`${o}\u2192${s}`;if(!t.has(i)){t.add(i);let a=s.includes("test")||s.includes("spec")?"dev":"import";n.push({source:o,target:s,type:a})}}return n}function zo(e){let r=e.replace(/\\/g,"/").split("/").filter(Boolean).filter(o=>o!=="."&&o!=="..");return r.length===0?"":r[0]==="src"&&r.length>1?r[1]:r[0]}function Df(e){let t=[];for(let n of e)t.push(n.name),t.push(...Df(n.children));return t}function Nf(e){let t=[];for(let n of e)t.push(n.path),t.push(...Nf(n.children));return t}function zb(e,t){let n=[],r=Df(e),o=Nf(e);return r.some(s=>s==="hooks"||s.endsWith("-hook")||s.endsWith("-hooks"))&&n.push({name:"Hook Pattern",description:"Functions/modules registered as hooks for lifecycle events.",locations:o.filter(s=>s.includes("hooks")).slice(0,5)}),r.some(s=>s==="middleware"||s==="middlewares")&&n.push({name:"Middleware Chain",description:"Layered middleware processing pipeline.",locations:o.filter(s=>s.includes("middleware")).slice(0,5)}),r.some(s=>s==="factories"||s==="factory")&&n.push({name:"Factory Pattern",description:"Factory functions or classes for object creation.",locations:o.filter(s=>s.includes("factor")).slice(0,5)}),r.some(s=>s==="plugins"||s==="registry"||s==="registries")&&n.push({name:"Registry / Plugin Pattern",description:"Central registry enabling pluggable extension points.",locations:o.filter(s=>s.includes("plugin")||s.includes("registr")).slice(0,5)}),t>50&&n.push({name:"Modular Architecture",description:"Code organized into distinct feature modules with clear boundaries.",locations:e.slice(0,3).map(s=>s.path)}),n}async function Qb(e,t,n){let r=[],o={".ts":"TypeScript",".tsx":"TypeScript (React)",".js":"JavaScript",".jsx":"JavaScript (React)",".py":"Python",".go":"Go",".rs":"Rust",".java":"Java",".cs":"C#",".rb":"Ruby",".swift":"Swift",".kt":"Kotlin"};for(let[s,i]of Object.entries(t))i>0&&o[s]&&r.push({category:"language",name:o[s]});if(n.some(s=>s.endsWith("package.json")))try{let s=await Ut.readFile(Ne.join(e,"package.json"),"utf-8"),i=JSON.parse(s),a={...i.dependencies??{},...i.devDependencies??{}},c={react:"React",vue:"Vue.js","@angular/core":"Angular",svelte:"Svelte",express:"Express",fastify:"Fastify",next:"Next.js",nuxt:"Nuxt.js"};for(let[d,p]of Object.entries(c))a[d]&&r.push({category:"framework",name:p,version:a[d]});let l={vitest:"Vitest",jest:"Jest",mocha:"Mocha",pytest:"Pytest"};for(let[d,p]of Object.entries(l))a[d]&&r.push({category:"test",name:p,version:a[d]});let u={typescript:"TypeScript Compiler",esbuild:"esbuild",webpack:"Webpack",vite:"Vite",rollup:"Rollup",turbo:"Turborepo"};for(let[d,p]of Object.entries(u))a[d]&&r.push({category:"tool",name:p,version:a[d]})}catch{}return n.some(s=>s.endsWith("Cargo.toml"))&&r.push({category:"tool",name:"Cargo"}),n.some(s=>s.endsWith("go.mod"))&&r.push({category:"tool",name:"Go Modules"}),r}async function Xb(e,t){let n=[],r=[],o=new Set;for(let i of t.entryPoints)o.add(i);for(let i of Object.values(t.largestFilesByDirectory))for(let a of i)o.add(a);let s=[...o].filter(i=>i.endsWith(".ts")||i.endsWith(".tsx")).slice(0,20);for(let i of s){let a=Ne.isAbsolute(i)?i:Ne.join(e,i);try{let c=await Ut.readFile(a,"utf-8");n.push(...Of(i,c)),r.push(...$f(i,c))}catch{}}return{dataModels:n,apiSurface:r}}async function Zb(e,t,n,r){let o=new Date().toISOString(),s={schemaVersion:Af,generatedAt:o,updatedAt:o,componentInventory:[],dataModels:[],apiSurface:[],dependencyGraph:[],designPatterns:[],technologyStack:n??[],designSystem:r};return await Vr(e,s),s}async function wa(e,t,n){let r=new Date().toISOString(),o=t.directoryTree.map(Kb),s=Jb(t.importGraph),i=await Qb(e,t.languageDistribution,t.configFiles),a=zb(t.directoryTree,t.sourceFiles),{dataModels:c,apiSurface:l}=await Xb(e,t);if(t.agentsMdEntries&&t.agentsMdEntries.length>0)for(let u of t.agentsMdEntries)for(let d of u.pathDescriptionPairs){let p=o.find(m=>d.path.startsWith(m.path)||m.path.includes(d.path));p&&d.description&&(p.description=d.description);let f=Ne.dirname(d.path);f!=="."&&!o.some(m=>m.path===f)&&o.push({name:Ne.basename(f),path:f,description:d.description||"Key file from AGENTS.md",type:"module",fileCount:1})}return{schemaVersion:Af,generatedAt:r,updatedAt:r,componentInventory:o,dataModels:c,apiSurface:l,dependencyGraph:s,designPatterns:a,technologyStack:i,designSystem:n}}async function Vr(e,t){await Ut.ensureDir(Ne.join(e,".olympus")),await Ut.writeFile(Ne.join(e,If),JSON.stringify(t,null,2),"utf-8")}async function _a(e){try{let t=await Ut.readFile(Ne.join(e,If),"utf-8");return JSON.parse(t)}catch{return null}}async function eE(e,t){let n=await _a(e);if(!n)return null;let r=[],o=[];for(let a of t){let c=Ne.isAbsolute(a)?a:Ne.join(e,a);try{let l=await Ut.readFile(c,"utf-8");r.push(...Of(a,l)),o.push(...$f(a,l))}catch{}}let s=new Set(t),i={...n,updatedAt:new Date().toISOString(),dataModels:[...n.dataModels.filter(a=>!s.has(a.path)),...r],apiSurface:[...n.apiSurface.filter(a=>!s.has(a.path)),...o]};return await Vr(e,i),i}async function tE(e,t){let n=await _a(e);if(!n||t.length===0)return"";let r=new Set(t.map(p=>p.toLowerCase())),o=new Set;for(let p of n.dependencyGraph)r.has(p.source.toLowerCase())&&o.add(p.target.toLowerCase());let s=new Set([...r,...o]),i=n.componentInventory.filter(p=>s.has(p.name.toLowerCase())),a=n.apiSurface.filter(p=>s.has(zo(p.path).toLowerCase())),c=n.dataModels.filter(p=>s.has(zo(p.path).toLowerCase())),l=n.dependencyGraph.filter(p=>s.has(p.source.toLowerCase())),u=["## Architecture Context",""];if(i.length>0){u.push("### Components");for(let p of i)u.push(`- **${p.name}** (${p.type}, ${p.fileCount} files): ${p.description}`);u.push("")}if(a.length>0){u.push("### API Surface");for(let p of a.slice(0,10))u.push(`- \`${p.signature}\` in \`${p.path}\``);u.push("")}if(c.length>0){u.push("### Data Models");for(let p of c.slice(0,10)){let f=p.fields.slice(0,3).map(m=>`${m.name}: ${m.type}`).join(", ");u.push(`- **${p.name}**: { ${f}${p.fields.length>3?", ...":""} }`)}u.push("")}if(l.length>0){u.push("### Dependencies");for(let p of l.slice(0,10))u.push(`- ${p.source} \u2192 ${p.target} (${p.type})`);u.push("")}if(n.designSystem&&n.designSystem.detected&&n.designSystem.systems.length>0){u.push("### Design System");for(let p of n.designSystem.systems)u.push(`- **${p.name}** (${p.type}): ${p.path}`);u.push("")}let d=u.join(`
|
|
57
|
+
`);return d.length>xf&&(d=d.slice(0,xf)+`
|
|
58
|
+
...(truncated)`),d}var Ne,Ut,Af,If,xf,Yr=U(()=>{"use strict";Ne=v(require("path"),1),Ut=v(X(),1),Af="1.0",If=".olympus/project-architecture.json",xf=2e3});function Ff(e){try{return(0,Xo.readFileSync)(e,"utf8").split(`
|
|
59
|
+
`).length}catch{return 0}}function oE(e,t){let n=[],r=e.split(`
|
|
60
|
+
`),o=0;for(;o<r.length;){let s=r[o],i=/^##\s+(.+)$/.exec(s);if(i){let c=i[1].trim(),l=[];for(o++;o<r.length&&!/^##/.test(r[o]);){let u=r[o].trim();u.length>0&&l.push(u),o++}l.length>0&&n.push({path:c,description:l.join(" ")});continue}let a=/^[-*]\s+\*{0,2}([^*:]+)\*{0,2}:\s*(.+)$/.exec(s);if(a){let c=a[1].trim(),l=a[2].trim();c&&l&&n.push({path:c,description:l})}o++}return{relativeFilePath:t,pathDescriptionPairs:n}}async function sE(e){let t=[];async function n(o,s){try{let i=await nr.readFile(o,"utf8"),a=oE(i,s);a.pathDescriptionPairs.length>0&&t.push(a)}catch{return}}await n(ct.join(e,"AGENTS.md"),"AGENTS.md");let r=[];try{r=await nr.readdir(e,{withFileTypes:!0})}catch{return t}for(let o of r)if(o.isDirectory()&&!o.name.startsWith(".")&&!ka.has(o.name)){let s=ct.join(e,o.name,"AGENTS.md");await n(s,ct.join(o.name,"AGENTS.md").replace(/\\/g,"/"))}return t}function Mf(e,t){let n=[],r;if(t===".ts"||t===".tsx"||t===".js"||t===".jsx"){let o=/import\s+(?:.*?\s+from\s+)?['"]([^'"]+)['"]/g;for(;(r=o.exec(e))!==null;)n.push(r[1]);let s=/export\s+(?:.*?\s+from\s+)?['"]([^'"]+)['"]/g;for(;(r=s.exec(e))!==null;)n.push(r[1])}else if(t===".py"){let o=/^import\s+([^\s;#]+)/gm;for(;(r=o.exec(e))!==null;)n.push(r[1]);let s=/^from\s+([^\s;#]+)\s+import/gm;for(;(r=s.exec(e))!==null;)n.push(r[1])}else if(t===".go"){let o=/import\s+"([^"]+)"/g;for(;(r=o.exec(e))!==null;)n.push(r[1]);let s=/^\s+"([^"]+)"/gm;for(;(r=s.exec(e))!==null;)n.push(r[1])}return n}async function bn(e){let t={value:0},n={value:0},r={},o=[],s=[],i={},a=[];async function c(f,m){let g={name:ct.basename(f),path:f,fileCount:0,children:[]},y;try{y=await nr.readdir(f,{withFileTypes:!0})}catch(w){return console.error(`[brownfield-scanner] Cannot read directory ${f}:`,w),g}for(let w of y){if(w.name.startsWith(".")||ka.has(w.name))continue;let _=ct.join(f,w.name);if(w.isDirectory()){let h=await c(_,m);g.fileCount+=h.fileCount,g.children.push(h)}else if(w.isFile()){t.value+=1,g.fileCount+=1;let h=ct.extname(w.name);if(Zo.includes(h)){n.value+=1,r[h]=(r[h]??0)+1,jf.has(w.name)&&s.push(_);let S=m??"(root)";i[S]||(i[S]=[]),i[S].push({file:_,lines:Ff(_)});try{let T=(0,Xo.readFileSync)(_,"utf8");for(let k of Mf(T,h))o.push({sourceFile:_,importedModule:k})}catch(T){console.error(`[brownfield-scanner] Cannot read file ${_}:`,T)}}}}return g}let l=[];try{l=await nr.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=ct.join(e,f.name);if(f.isDirectory()){if(ka.has(f.name))continue;let g=await c(m,f.name);u.push(g)}else if(f.isFile()){t.value+=1;let g=ct.extname(f.name);if(Zo.includes(g)){n.value+=1,r[g]=(r[g]??0)+1,jf.has(f.name)&&s.push(m),i["(root)"]||(i["(root)"]=[]),i["(root)"].push({file:m,lines:Ff(m)});try{let w=(0,Xo.readFileSync)(m,"utf8");for(let _ of Mf(w,g))o.push({sourceFile:m,importedModule:_})}catch(w){console.error(`[brownfield-scanner] Cannot read file ${m}:`,w)}}nE.has(f.name)&&a.push(f.name)}}let d={};for(let[f,m]of Object.entries(i)){let g=m.slice().sort((y,w)=>w.lines-y.lines);d[f]=g.slice(0,3).map(y=>y.file)}let p=await sE(e);return{totalFiles:t.value,sourceFiles:n.value,directoryTree:u,languageDistribution:r,importGraph:o,entryPoints:s,largestFilesByDirectory:d,configFiles:a,...p.length>0?{agentsMdEntries:p}:{}}}function Lf(e,t=20){let n=[],r=new Set;function o(i){r.has(i)||(r.add(i),n.push(i))}if(e.agentsMdEntries&&e.agentsMdEntries.length>0)for(let i of e.agentsMdEntries)for(let a of i.pathDescriptionPairs){let c=a.description.toLowerCase();iE.some(u=>c.includes(u))&&o(a.path)}for(let i of e.entryPoints.slice(0,5))o(i);let s=Object.keys(e.largestFilesByDirectory).slice(0,10);for(let i of s){let a=e.largestFilesByDirectory[i];a&&a.length>0&&o(a[0])}for(let i of e.configFiles.slice(0,5))o(i);return n.slice(0,t)}function Uf(e,t,n=15){let r=t.split(/\s+/).map(g=>g.toLowerCase().replace(/[^a-z0-9]/g,"")).filter(g=>g.length>=3&&!rE.has(g));if(r.length===0)return[];let o=new Set(e.importGraph.map(g=>g.sourceFile));for(let g of e.entryPoints)o.add(g);for(let g of Object.values(e.largestFilesByDirectory))for(let y of g)o.add(y);let s=new Map;if(e.agentsMdEntries&&e.agentsMdEntries.length>0)for(let g of e.agentsMdEntries)for(let y of g.pathDescriptionPairs)s.set(y.path,y.description.toLowerCase());let i=new Map;for(let g of e.importGraph){let y=i.get(g.sourceFile)??[];y.push(g.importedModule),i.set(g.sourceFile,y)}function a(g){let y=g.replace(/^\.+\//,"").replace(/\.js$/,"").toLowerCase();return y?Array.from(o).filter(w=>w.replace(/\\/g,"/").toLowerCase().includes(y)):[]}function c(g){let y=g.replace(/\\/g,"/");for(let[w,_]of s)if(y.includes(w)||w.includes(y))return r.filter(h=>_.includes(h)).length;return 0}let l=new Map;for(let g of o){let y=g.replace(/\\/g,"/").toLowerCase(),w=r.filter(h=>y.includes(h)).length,_=c(g)*2;(w>0||_>0)&&l.set(g,w+_)}let u=new Set(l.keys()),d=new Set(u);for(let g of u)for(let y of i.get(g)??[])for(let w of a(y))d.add(w);let p=Array.from(u).sort((g,y)=>(l.get(y)??0)-(l.get(g)??0)),f=[],m=new Set;for(let g of p)m.has(g)||(m.add(g),f.push(g));for(let g of d)m.has(g)||(m.add(g),f.push(g));return f.slice(0,n)}var ct,nr,Xo,ka,nE,jf,rE,iE,Sa=U(()=>{"use strict";ct=v(require("path"),1),nr=v(require("fs/promises"),1),Xo=require("fs");es();ka=new Set(["node_modules",".git","dist","build",".olympus","aidlc-docs",".next","__pycache__",".venv","vendor","target"]),nE=new Set(["package.json","tsconfig.json","tsconfig.base.json","pyproject.toml","setup.py","setup.cfg","requirements.txt","Cargo.toml","go.mod","go.sum","Makefile","makefile","Dockerfile","docker-compose.yml","docker-compose.yaml",".eslintrc.json",".eslintrc.js","jest.config.js","jest.config.ts","vite.config.ts","vite.config.js","webpack.config.js","webpack.config.ts","rollup.config.js","rollup.config.ts","babel.config.js","babel.config.json",".babelrc","vitest.config.ts","vitest.config.js","pom.xml","build.gradle","build.gradle.kts","CMakeLists.txt","Gemfile","composer.json"]),jf=new Set(["index.ts","index.tsx","index.js","index.jsx","main.ts","main.tsx","main.js","main.jsx","app.ts","app.tsx","app.js","app.jsx","server.ts","server.js"]),rE=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"]);iE=["core","entry","main","critical","primary","central"]});var Hf={};he(Hf,{getChangedFilesSince:()=>va,getFileLastModified:()=>Gf,getGitHeadSha:()=>Kr,isFileStale:()=>aE,isGitAvailable:()=>ba});async function Kr(e){try{let{stdout:t}=await ts("git",["rev-parse","HEAD"],{cwd:e,timeout:5e3}),n=t.trim();return n.length>0?n:null}catch{return null}}async function va(e,t){try{let{stdout:n}=await ts("git",["diff","--name-only",t],{cwd:e,timeout:1e4});return n.trim().split(`
|
|
61
|
+
`).map(r=>r.trim()).filter(r=>r.length>0)}catch{return[]}}async function ba(e){try{return await ts("git",["status","--porcelain"],{cwd:e,timeout:5e3}),!0}catch{return!1}}async function Gf(e,t){try{let{stdout:n}=await ts("git",["log","-1","--format=%at","--",t],{cwd:e,timeout:5e3}),r=parseInt(n.trim(),10);if(!isNaN(r)&&r>0)return r*1e3}catch(n){}try{let n=await import("fs/promises"),o=(await import("path")).join(e,t);return(await n.stat(o)).mtimeMs}catch{return null}}async function aE(e,t,n=30){let r=await Gf(e,t);if(r===null)return!1;let o=Date.now()-r,s=n*24*60*60*1e3;return o>s}var Wf,Bf,ts,ns=U(()=>{"use strict";Wf=require("node:child_process"),Bf=require("node:util"),ts=(0,Bf.promisify)(Wf.execFile)});function Yf(e){return Et.join(e,cE,lE)}async function Ea(e){let t=Yf(e);try{let n=await En.readFile(t,"utf-8"),r=JSON.parse(n);return!r.schemaVersion||!r.createdAt?(console.warn("[DiscoveryCache] Manifest missing required fields \u2014 treating as cache miss"),null):r}catch(n){return n instanceof Error&&"code"in n&&n.code==="ENOENT"||console.warn("[DiscoveryCache] Failed to read/parse cache manifest \u2014 treating as cache miss:",n),null}}async function Ta(e,t){let n=Yf(e);await En.ensureDir(Et.dirname(n)),await En.writeFile(n,JSON.stringify(t,null,2),"utf-8")}async function Kf(e,t,n){if(t.schemaVersion!==Vf)return{stale:!0,reason:"schema-version-mismatch"};if(n&&t.toolVersion&&t.toolVersion!==n)return{stale:!0,reason:"tool-version-mismatch"};let r=Date.now()-new Date(t.updatedAt).getTime(),o=uE*24*60*60*1e3;if(r>o)return{stale:!0,reason:"cache-too-old"};if(!await ba(e))return console.warn("[DiscoveryCache] Git unavailable \u2014 staleness check using file timestamps only"),qf(t);let i=await Kr(e);return i===null?(console.warn("[DiscoveryCache] Could not read HEAD SHA \u2014 falling back to timestamps"),qf(t)):t.gitSha===null?{stale:!0,reason:"no-cached-sha"}:i!==t.gitSha?{stale:!0,reason:"git-sha-changed",changedFiles:await va(e,t.gitSha)}:{stale:!1}}function qf(e){let t=e.fileTimestamps;if(!t||Object.keys(t).length===0)return{stale:!0,reason:"no-timestamps"};for(let[n,r]of Object.entries(t)){if(r===0)return{stale:!0,reason:`invalidated:${n}`};try{if(require("fs").statSync(n).mtimeMs!==r)return{stale:!0,reason:`timestamp-changed:${n}`}}catch{return{stale:!0,reason:`file-missing:${n}`}}}return{stale:!1}}async function Jf(e,t,n){if(t.length===0)return n;try{let r=new Set(t.map(a=>Et.dirname(Et.resolve(e,a)))),o=await bn(e),s={...n,totalFiles:o.totalFiles,sourceFiles:o.sourceFiles,largestFilesByDirectory:{...n.largestFilesByDirectory},importGraph:n.importGraph.filter(a=>!t.some(c=>a.sourceFile.endsWith(c)||a.importedModule.endsWith(c)))};for(let a of r){let c=Et.relative(e,a);o.largestFilesByDirectory[c]!==void 0?s.largestFilesByDirectory[c]=o.largestFilesByDirectory[c]:delete s.largestFilesByDirectory[c]}let i=o.importGraph.filter(a=>t.some(c=>a.sourceFile.endsWith(c)||a.importedModule.endsWith(c)));return s.importGraph=[...s.importGraph,...i],s}catch(r){return console.error("[DiscoveryCache] Incremental rescan failed \u2014 returning existing result:",r),n}}function zf(e,t,n,r,o){let s=new Date().toISOString();return{schemaVersion:Vf,toolVersion:o||"unknown",createdAt:s,updatedAt:s,gitSha:e,fileTimestamps:n,cachedArtifacts:["workspace-scan"],sourceFileCount:t.sourceFiles,agentsMdStatus:r}}var Et,En,Vf,cE,lE,uE,Qf=U(()=>{"use strict";Et=v(require("path"),1),En=v(X(),1);ns();Sa();Vf="1.0",cE=Et.join(".olympus","cache"),lE="discovery-cache.json",uE=7});function fE(e){let t=new Set;for(let n of Object.keys(e.languageDistribution)){let r=dE[n];r&&t.add(r)}for(let n of e.configFiles){let r=pE[n];r&&t.add(r)}return Array.from(t)}function mE(e){let t=[];for(let r of e.directoryTree){let o=r.name;o==="src"?t.push("Uses src/ directory for source code"):o==="__tests__"||o==="tests"?t.push("Has dedicated test directory"):o==="packages"?t.push("Monorepo with packages/ directory"):o==="docs"?t.push("Has documentation directory"):o==="lib"&&t.push("Uses lib/ directory for library code")}return Object.entries(e.languageDistribution).filter(([,r])=>r>5).length>1&&t.push("Multi-language project"),t}function Zf(e,t){try{Bn(e);let n=(0,Xf.join)(yt(e),"patterns.json"),r=we(n,null),o=fE(t),s=mE(t),i;r?i={...r,tech_stack:Array.from(new Set([...r.tech_stack,...o])),conventions:Array.from(new Set([...r.conventions,...s])),learned_rules:r.learned_rules||[],common_mistakes:r.common_mistakes||[],last_updated:new Date().toISOString()}:i={project_hash:lu(e),project_path:e,tech_stack:o,conventions:s,learned_rules:[],common_mistakes:[],last_updated:new Date().toISOString()},st(n,i)}catch(n){console.error("[Olympus Learning] Failed to write project patterns:",n)}}var Xf,dE,pE,em=U(()=>{"use strict";Xf=require("path");ye();ye();dE={".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"},pE={"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 hE(e,t){let n=e.split(`
|
|
62
62
|
`);return n.length<=t?e:n.slice(0,t).join(`
|
|
63
63
|
`)+`
|
|
64
|
-
... (truncated)`}function
|
|
65
|
-
`)}function
|
|
66
|
-
`),a=r.importGraph.slice(0,50).map(d=>` ${
|
|
64
|
+
... (truncated)`}function rm(e,t){let n=[],r=" ".repeat(t*2);for(let o of e)n.push(`${r}${o.name}/ (${o.fileCount} files)`),o.children.length>0&&n.push(rm(o.children,t+1));return n.join(`
|
|
65
|
+
`)}function yE(e){try{return(0,nm.readFileSync)(e,"utf8")}catch{return"(unable to read)"}}function wE(e,t){return Jr.isAbsolute(e)?e:Jr.resolve(t,e)}function tm(e){return e.replace(/\\/g,"/")}function om(e){let{projectPath:t,featureName:n,scanResult:r,keyFiles:o}=e,s=rm(r.directoryTree,0),i=Object.entries(r.languageDistribution).sort((d,p)=>p[1]-d[1]).map(([d,p])=>` ${d}: ${p} files`).join(`
|
|
66
|
+
`),a=r.importGraph.slice(0,50).map(d=>` ${tm(d.sourceFile)} -> ${d.importedModule}`).join(`
|
|
67
67
|
`),c=r.importGraph.length>50?`
|
|
68
|
-
... (${r.importGraph.length-50} more edges omitted)`:"",l=o.map(d=>{let p=
|
|
68
|
+
... (${r.importGraph.length-50} more edges omitted)`:"",l=o.map(d=>{let p=wE(d,t),f=yE(p),m=hE(f,200);return`### ${tm(d)}
|
|
69
69
|
\`\`\`
|
|
70
70
|
${m}
|
|
71
71
|
\`\`\``}).join(`
|
|
@@ -93,9 +93,9 @@ ${l||"(no key files provided)"}
|
|
|
93
93
|
|
|
94
94
|
Based on the above project structure and source files, produce a Static Code Model.
|
|
95
95
|
|
|
96
|
-
${
|
|
96
|
+
${gE}
|
|
97
97
|
|
|
98
|
-
Be precise and concise. Each module row should capture the real public exports or primary function signatures where visible. Use the actual file paths from the project.`}var
|
|
98
|
+
Be precise and concise. Each module row should capture the real public exports or primary function signatures where visible. Use the actual file paths from the project.`}var Jr,nm,gE,sm=U(()=>{"use strict";Jr=v(require("path"),1),nm=require("fs");Z();gE=`A Static Code Model must contain these markdown sections:
|
|
99
99
|
## Modules
|
|
100
100
|
| Name | Path | Responsibility | Public Interface |
|
|
101
101
|
|------|------|----------------|------------------|
|
|
@@ -111,7 +111,7 @@ Be precise and concise. Each module row should capture the real public exports o
|
|
|
111
111
|
(one row per data model)
|
|
112
112
|
|
|
113
113
|
## Configuration Summary
|
|
114
|
-
(paragraph describing configuration approach)`});async function
|
|
114
|
+
(paragraph describing configuration approach)`});async function im(e){let t=[];try{let n=Ca.join(e,"package.json"),r={};try{let s=await Ra.promises.readFile(n,"utf-8");r=JSON.parse(s)}catch{return{detected:!1,systems:[]}}let o={...r.dependencies,...r.devDependencies};if(Object.keys(o).length===0)return{detected:!1,systems:[]};for(let[s,i]of Object.entries(_E))if(s.endsWith("-*")){let a=s.slice(0,-2);for(let c of Object.keys(o))if(c.startsWith(a)){t.push({name:i,type:"component-library",path:`node_modules/${c}`,description:`Component library: ${i}`});break}}else s in o&&t.push({name:i,type:"component-library",path:`node_modules/${s}`,description:`Component library: ${i}`});for(let[s,i]of Object.entries(kE))s in o&&t.push({name:i,type:"css-framework",path:`node_modules/${s}`,description:`CSS framework: ${i}`});for(let s of SE)try{let i=Ca.join(e,s);if((await Ra.promises.stat(i)).isFile()){let c="theme-config",l="Theme configuration file";s.includes("tokens")?(c="token-file",l="Design tokens file"):s.includes("tailwind")&&(c="css-framework",l="Tailwind CSS configuration"),t.push({name:s,type:c,path:s,description:l})}}catch{}return t.length===0?{detected:!1,systems:[]}:{detected:!0,systems:t}}catch{return{detected:!1,systems:[]}}}var Ca,Ra,_E,kE,SE,am=U(()=>{"use strict";Ca=v(require("path"),1),Ra=require("node:fs"),_E={"@mui/material":"Material-UI (MUI)","@chakra-ui/react":"Chakra UI","@mantine/core":"Mantine",antd:"Ant Design","@radix-ui/react-*":"Radix UI",shadcn:"shadcn/ui"},kE={tailwindcss:"Tailwind CSS",bootstrap:"Bootstrap","styled-components":"styled-components","@emotion/react":"Emotion"},SE=["tailwind.config.ts","tailwind.config.js","tailwind.config.cjs","stitches.config.ts","stitches.config.js","theme.ts","theme.js","theme.config.ts","theme.config.js","tokens.json","design-tokens.json","design-tokens.ts","design-tokens.js"]});async function EE(e){try{let n=Qe.join(e,".olympus","config.json"),r=await lt.readFile(n,"utf-8");return JSON.parse(r).deepinit_threshold??50}catch{return 50}}function TE(){try{let e=Qe.resolve(__dirname,"../../../package.json");return JSON.parse(require("fs").readFileSync(e,"utf-8")).version||"unknown"}catch{return"unknown"}}async function cm(e){let t=0;try{let n=await lt.readdir(e,{withFileTypes:!0});for(let r of n){if(r.name.startsWith(".")||vE.has(r.name))continue;let o=Qe.join(e,r.name);if(r.isDirectory())t+=await cm(o);else if(r.isFile()){let s=Qe.extname(r.name);Zo.includes(s)&&t++}}}catch(n){console.error(`Error reading directory ${e}:`,n)}return t}async function Tn(e){let t=await cm(e);return{isBrownfield:t>=3,sourceFileCount:t}}function CE(e,t){return{"analysis-plan":`# Analysis Plan
|
|
115
115
|
|
|
116
116
|
## Feature: ${t}
|
|
117
117
|
|
|
@@ -226,11 +226,11 @@ Be precise and concise. Each module row should capture the real public exports o
|
|
|
226
226
|
|
|
227
227
|
## Error Handling Patterns
|
|
228
228
|
<!-- How errors propagate and are handled -->
|
|
229
|
-
`,"workspace-scan":""}[e]}async function
|
|
229
|
+
`,"workspace-scan":""}[e]}async function lm(e){let{projectPath:t,workflowId:n,featureName:r,manifestPath:o}=e;try{await zi(t,n);let s=new Date().toISOString();Nt(o,"discovery","in_progress",s);let i=[];for(let h of bE){if(h==="workspace-scan")continue;let b=CE(h,r),S=at(t,n,h);await zn(t,n,h,b),i.push(S),$e(o,{id:`DISCOVERY-${h}`,type:h,phase:"discovery",stage:"intent",path:S,validation_passed:null,write_complete:!0,checksum:null})}let{sourceFileCount:a,isBrownfield:c}=await Tn(t),l;if(c)try{let h,b=e.forceRescan===!0,S=b?null:await Ea(t),T=TE(),k=!1;if(S&&!b){let j=await Kf(t,S,T);if(j.stale)if(j.changedFiles&&j.changedFiles.length>0){let K=at(t,n,"workspace-scan");try{let q=await lt.readFile(K,"utf-8"),mn=JSON.parse(q),Oe=await Jf(t,j.changedFiles,mn);Oe===mn&&(k=!0),h=Oe}catch{h=await bn(t)}}else h=await bn(t);else{let K=at(t,n,"workspace-scan");try{let q=await lt.readFile(K,"utf-8");h=JSON.parse(q)}catch{h=await bn(t)}}}else h=await bn(t);let F=k&&S?S.gitSha:await Kr(t),R=h.agentsMdEntries&&h.agentsMdEntries.length>0?"present":"absent",O=zf(F,h,{},R,T);await Ta(t,O),Zf(t,h);let C=Lf(h);if(e.includeFiles&&e.includeFiles.length>0){let j=new Set(C);for(let K of e.includeFiles)j.has(K)||C.push(K)}let $=Uf(h,r),D=at(t,n,"workspace-scan");await zn(t,n,"workspace-scan",JSON.stringify(h,null,2)),i.push(D),$e(o,{id:"DISCOVERY-workspace-scan",type:"workspace-scan",phase:"discovery",stage:"intent",path:D,validation_passed:null,write_complete:!0,checksum:null});let E=om({projectPath:t,workflowId:n,featureName:r,scanResult:h,keyFiles:C,relevantFiles:$,intentText:r}),L=Qe.join(t,"aidlc-docs",n,"discovery","static-model-prompt.md");await zi(t,n),await lt.writeFile(L,E,"utf-8"),l={scanResult:h,keyFiles:C,relevantFiles:$,staticModelPrompt:E}}catch(h){console.error("[Discovery] Brownfield scanning failed (non-blocking):",h)}let u;try{u=await im(t)}catch{}let d;if(l)try{let h=await wa(t,l.scanResult,u);await Vr(t,h),d=!0}catch(h){console.error("[Discovery] Architecture model generation failed (non-blocking):",h),d=!1}let p=!1,f,m=!1,g=!1,y=await EE(t),w=!1;if(l)if(l.scanResult.agentsMdEntries&&l.scanResult.agentsMdEntries.length>0){p=!0,f=l.scanResult.agentsMdEntries.length,m=!1;try{let{isFileStale:h}=await Promise.resolve().then(()=>(ns(),Hf));for(let b of l.scanResult.agentsMdEntries)if(await h(t,b.relativeFilePath,30)){w=!0;break}}catch{}w&&(m=!0,g=!0);for(let h of l.scanResult.agentsMdEntries)$e(o,{id:`DISCOVERY-agents-md-${Qe.basename(Qe.dirname(h.relativeFilePath))||"root"}`,type:"structural-map",phase:"discovery",stage:"intent",path:h.relativeFilePath,validation_passed:null,write_complete:!0,checksum:null})}else m=a>=y;else c&&(m=a>=y);try{let h=at(t,n,"analysis-plan"),b=await lt.readFile(h,"utf-8"),S=p?`**Status**: Present (${f} file(s) found)${w?" \u2014 **Stale** (>30 days old)":""}
|
|
230
230
|
**Files**:
|
|
231
231
|
${l.scanResult.agentsMdEntries.map(k=>`- \`${k.relativeFilePath}\``).join(`
|
|
232
232
|
`)}`:"**Status**: Absent \u2014 no AGENTS.md files found in project",T=b.replace(/## AGENTS\.md Status\n<!-- Populated during brownfield scanning\. Indicates whether AGENTS\.md files were found\. -->/,`## AGENTS.md Status
|
|
233
|
-
${S}`);T!==b&&await
|
|
233
|
+
${S}`);T!==b&&await lt.writeFile(h,T,"utf-8")}catch{}if(w&&l)try{let h=await Ea(t);h&&(h.agentsMdStatus="stale",await Ta(t,h))}catch{}try{let h=p?"pre-existing":m?"suggested":"skipped",b=p?`AGENTS.md detected (${f} file(s), stale: ${w})`:"No AGENTS.md files found";await $p(t,n,`## Discovery \u2014 Deepinit Detection
|
|
234
234
|
**Timestamp**: ${new Date().toISOString()}
|
|
235
235
|
**Source file count**: ${a}
|
|
236
236
|
**Deepinit threshold**: ${y}
|
|
@@ -238,7 +238,7 @@ ${S}`);T!==b&&await dt.writeFile(h,T,"utf-8")}catch{}if(w&&l)try{let h=await Ta(
|
|
|
238
238
|
**AGENTS.md**: ${b}
|
|
239
239
|
|
|
240
240
|
---
|
|
241
|
-
`)}catch{}
|
|
241
|
+
`)}catch{}Nt(o,"discovery","blocked");let _=await A(t,n);return _&&(_.current_phase="discovery",_.phases.discovery.status="blocked",p&&g?_.deepinit_status="suggested":p?_.deepinit_status="pre-existing":m?_.deepinit_status="suggested":c?_.deepinit_status="skipped":_.deepinit_status="not_applicable",await P(t,_)),{completed:!1,gateRequired:!0,artifactsGenerated:i,sourceFileCount:a,agentsMdDetected:p,agentsMdFileCount:f,agentsMdStale:w,deepinitSuggested:m,deepinitUpdateMode:g,architectureModelGenerated:d,designSystem:u,brownfieldData:l}}catch(s){throw console.error("[Discovery] Error executing discovery phase:",s),new Error(`Discovery phase failed: ${s instanceof Error?s.message:String(s)}`)}}var Qe,lt,Zo,vE,bE,es=U(()=>{"use strict";Qe=v(require("path"),1),lt=v(X(),1);Qi();Z();ce();Sa();Qf();ns();em();sm();Yr();am();Zo=[".ts",".tsx",".js",".jsx",".py",".go",".rs",".java",".c",".cpp",".cs",".rb",".swift",".kt",".css",".scss",".html",".vue",".svelte"],vE=new Set(["node_modules",".git","dist","build",".olympus","aidlc-docs",".next","__pycache__",".venv","vendor","target"]),bE=["analysis-plan","current-state-analysis","regression-baseline","change-impact","static-model","dynamic-model","workspace-scan"]});var mm={};he(mm,{PATHWAY_DISPLAY_NAMES:()=>dm,WORKFLOW_ROUTING_FORMAT_INSTRUCTIONS:()=>LE,applyPathwayOverride:()=>pm,buildPathwayAnnouncement:()=>IE,detectPathway:()=>xa,generatePlanVisualization:()=>fm,generateWorkflowRouting:()=>Aa,getPathwayDisplayName:()=>Pa,isPhaseIncluded:()=>is,isStageIncluded:()=>Ia,loadPathwayBehaviors:()=>xE,loadWorkflowRouting:()=>zr,recordPathwayOverride:()=>OE,writeWorkflowRoutingArtifact:()=>ss});async function xE(e){if(!RE.includes(e))return null;let t=Wt.join(um.homedir(),".claude","olympus","rules","common","pathway-behaviors.json"),n=Wt.join(process.cwd(),"resources","rules","common","pathway-behaviors.json"),r=s=>rr.readFile(s,"utf-8").catch(()=>null),o=await r(t)??await r(n);if(o===null)return null;try{let i=JSON.parse(o)[e];return i?{rules:i.rules,qualityGateChecklist:i.quality_gate_checklist}:null}catch{return console.error("[PathwayBehaviors] Failed to parse pathway-behaviors.json"),null}}async function xa(e,t){let{isBrownfield:n}=await Tn(e);if(!n)return"greenfield";let r=t.toLowerCase();for(let{pathway:o,keywords:s}of PE)for(let i of s)if(r.includes(i))return o;return"brownfield-enhancement"}function Pa(e){return dm[e]??e}function IE(e,t,n){return{detectedPathway:e,displayName:Pa(e),depthScore:t,sourceFileCount:n,rationale:AE[e]}}function pm(e,t){let n=t.pathwayType??e.detectedPathway,r=t.depthScore??e.depthScore,o=t.pathwayType!=null||t.depthScore!=null?` (overridden by user: pathway=${t.pathwayType??"unchanged"}, depthScore=${t.depthScore??"unchanged"})`:"";return{detectedPathway:n,displayName:Pa(n),depthScore:r,sourceFileCount:e.sourceFileCount,rationale:e.rationale+o}}function OE(e,t,n){let r=pm(t,n);return{original_pathway_type:t.detectedPathway,original_depth_score:t.depthScore,pathway_override:n.pathwayType,depth_override:n.depthScore,pathway_type:r.detectedPathway,depth_score:r.depthScore}}function $E(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 rs(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 DE(e,t){switch(e){case"discovery":return["brownfield-scan","analysis"];case"inception":return["workspace-detection","reverse-engineering","requirements-analysis","workflow-planning","units-generation","user-stories","bolt-planning"];case"construction":return t==="bugfix"?["bolt-execution"]:["unit-decomposition","bolt-execution"];case"operations":return["deployment","monitoring"]}}function NE(e,t,n,r){return e==="construction"&&t==="unit-decomposition"&&r==="minimal"?"Skipped \u2014 minimal depth does not require unit decomposition":{"discovery:brownfield-scan":"Scan existing source files for architectural understanding","discovery:analysis":"Analyse change impact and regression risk","inception:intent":"Capture structured problem statement and success criteria","inception:depth-assessment":"Score 6 factors to determine workflow depth","inception:requirements":"Classify non-functional requirements and constraints","inception:workspace-detection":"Auto-detect greenfield/brownfield and determine pathway type","inception:reverse-engineering":"Reverse-engineer existing codebase architecture (brownfield only)","inception:requirements-analysis":"Structured Q&A to capture functional and non-functional requirements","inception:user-stories":"Generate user personas and stories with Given/When/Then acceptance criteria","inception:workflow-planning":"Generate execution plan with Mermaid visualization and live checkboxes","inception:units-generation":"Define units of work with inter-unit dependencies and story mapping","inception:bolt-planning":"Decompose units into executable bolts with dependency tracking","construction:unit-decomposition":"Break intent into implementable units","construction:bolt-execution":"Execute implementation bolts with validation gates","operations:deployment":"Generate deployment guide and release notes","operations:monitoring":"Configure monitoring, runbook, and observability"}[`${e}:${t}`]??"Standard stage for this phase"}async function Aa(e){let{pathwayType:t,depthAssessment:n,sourceFileCount:r}=e,{recommended_depth:o,total_score:s,risk_tier:i}=n,a=$E(t),c={discovery:{included:a.discovery,rationale:rs("discovery",t,a.discovery)},inception:{included:a.inception,rationale:rs("inception",t,a.inception)},construction:{included:a.construction,rationale:rs("construction",t,a.construction)},operations:{included:a.operations,rationale:rs("operations",t,a.operations)}},l=["discovery","inception","construction","operations"],u=[];for(let f of l)if(a[f])for(let m of DE(f,t)){let g=f==="construction"&&m==="unit-decomposition",y=f==="inception"&&m==="reverse-engineering",w=f==="inception"&&m==="user-stories",_=f==="inception"&&m==="units-generation",h=!0;g&&o==="minimal"&&(h=!1),y&&t==="greenfield"&&(h=!1),w&&(t==="bugfix"||t==="optimization")&&(h=!1),_&&o==="minimal"&&(h=!1),u.push({phase:f,stage:m,included:h,rationale:NE(f,m,t,o)})}let d;if(t==="bugfix")d=1;else switch(o){case"minimal":d=1;break;case"standard":d=Math.min(10,Math.max(1,Math.ceil(r/50)));break;case"comprehensive":d=Math.min(20,Math.max(2,Math.ceil(r/25)));break}let p=s<=10?"LOW":s<=20?"MEDIUM":"HIGH";return{pathway:t,risk_assessment:p,risk_tier:i.tier,phases:c,stages:u,estimated_bolts:d,estimated_depth:o,generated_at:new Date().toISOString(),approved_at:null,approved_by:null}}function jE(e,t){let r=["discovery","inception","construction","operations"].map(s=>{let{included:i,rationale:a}=t.phases[s];return`| ${s} | ${i?"yes":"no"} | ${a} |`}).join(`
|
|
242
242
|
`),o=t.stages.map((s,i)=>`| ${i+1} | ${s.phase} | ${s.stage} | ${s.included?"yes":"no"} | ${s.rationale} |`).join(`
|
|
243
243
|
`);return`# Workflow Routing: ${e}
|
|
244
244
|
|
|
@@ -261,25 +261,25 @@ ${r}
|
|
|
261
261
|
| # | Phase | Stage | Included | Rationale |
|
|
262
262
|
|---|-------|-------|----------|-----------|
|
|
263
263
|
${o}
|
|
264
|
-
`}async function
|
|
264
|
+
`}async function ss(e,t,n){let r=Wt.join(e,"aidlc-docs",t,"inception","plans"),o=Wt.join(r,"workflow-routing.md"),s=Wt.posix.join("aidlc-docs",t,"inception","plans","workflow-routing.md");try{await rr.mkdir(r,{recursive:!0});let a=jE(t,n),c=fm(n),l=a+`
|
|
265
265
|
## Execution Plan Visualization
|
|
266
266
|
|
|
267
267
|
`+c+`
|
|
268
|
-
`;await
|
|
269
|
-
`)){let o=r.split("|").map(s=>s.trim()).filter(Boolean);if(o.length>=3){let[s,i,...a]=o;t[s]={included:i.toLowerCase()==="yes",rationale:a.join(" | ")}}}return t}function
|
|
270
|
-
`)){let o=r.split("|").map(s=>s.trim()).filter(Boolean);if(o.length>=5){let[s,i,a,c,...l]=o;t.push({phase:i,stage:a,included:c.toLowerCase()==="yes",rationale:l.join(" | ")})}}return t}function
|
|
271
|
-
`)}var
|
|
268
|
+
`;await rr.writeFile(o,l,"utf-8")}catch(a){throw console.error("[WorkflowRouting] Failed to write artifact:",a),a}let i=Wt.join(e,"aidlc-docs",t,"manifest.json");return $e(i,{id:`WORKFLOW-ROUTING-${t}`,type:"WORKFLOW_ROUTING",phase:"inception",stage:"intent",path:s,validation_passed:!0,write_complete:!0,checksum:null}),s}function FE(e){let t={},n=e.match(/## Phase Overview[\s\S]*?\n\|[-| ]+\|\n([\s\S]*?)(?=\n## |\n# |$)/);if(!n)return t;for(let r of n[1].trim().split(`
|
|
269
|
+
`)){let o=r.split("|").map(s=>s.trim()).filter(Boolean);if(o.length>=3){let[s,i,...a]=o;t[s]={included:i.toLowerCase()==="yes",rationale:a.join(" | ")}}}return t}function ME(e){let t=[],n=e.match(/## Stage Details[\s\S]*?\n\|[-| ]+\|\n([\s\S]*?)(?=\n## |\n# |$)/);if(!n)return t;for(let r of n[1].trim().split(`
|
|
270
|
+
`)){let o=r.split("|").map(s=>s.trim()).filter(Boolean);if(o.length>=5){let[s,i,a,c,...l]=o;t.push({phase:i,stage:a,included:c.toLowerCase()==="yes",rationale:l.join(" | ")})}}return t}function zr(e,t){let n=Wt.join(e,"aidlc-docs",t,"inception","plans","workflow-routing.md");if(!(0,os.existsSync)(n))return null;let r;try{r=(0,os.readFileSync)(n,"utf-8")}catch(o){return console.error("[WorkflowRouting] Failed to read artifact:",o),null}try{let o=r.match(/\*\*Pathway:\*\*\s*(.+)/),s=r.match(/\*\*Risk Assessment:\*\*\s*(.+)/),i=r.match(/\*\*Risk Tier:\*\*\s*(.+)/),a=r.match(/\*\*Estimated (?:Bolts|Code Generations):\*\*\s*(\d+)/),c=r.match(/\*\*Estimated Depth:\*\*\s*(.+)/),l=r.match(/\*\*Generated:\*\*\s*(.+)/),u=r.match(/\*\*Approved:\*\*\s*(.+)/);if(!o||!s||!i||!a||!c||!l)return console.error("[WorkflowRouting] Missing required header fields"),null;let d=u?u[1].trim():"Pending",p=FE(r);return{pathway:o[1].trim(),risk_assessment:s[1].trim(),risk_tier:parseInt(i[1].trim(),10),estimated_bolts:parseInt(a[1].trim(),10),estimated_depth:c[1].trim(),generated_at:l[1].trim(),approved_at:d==="Pending"?null:d,approved_by:null,phases:{discovery:p.discovery??{included:!0,rationale:""},inception:p.inception??{included:!0,rationale:""},construction:p.construction??{included:!0,rationale:""},operations:p.operations??{included:!0,rationale:""}},stages:ME(r)}}catch(o){return console.error("[WorkflowRouting] Failed to parse artifact:",o),null}}function is(e,t){return e.phases[t]?.included??!0}function Ia(e,t,n){return e.stages.find(o=>o.phase===t&&o.stage===n)?.included??!0}function fm(e){let t=[];t.push("```mermaid"),t.push("flowchart TD"),t.push(""),t.push(" classDef execute fill:#4CAF50,color:#fff,stroke:#388E3C"),t.push(" classDef skip fill:#BDBDBD,color:#424242,stroke:#9E9E9E"),t.push(" classDef conditional fill:#FFA726,color:#fff,stroke:#F57C00"),t.push("");let n=["discovery","inception","construction","operations"];for(let r of n){let o=e.phases[r],s=r.charAt(0).toUpperCase()+r.slice(1);if(o.included){t.push(` subgraph ${s}["${s} Phase"]`);let i=e.stages.filter(c=>c.phase===r);for(let c of i){let l=`${r}_${c.stage.replace(/-/g,"_")}`,u=c.stage.replace(/-/g," ");c.included?(t.push(` ${l}["${u}"]`),t.push(` class ${l} execute`)):(t.push(` ${l}["${u} (SKIP)"]`),t.push(` class ${l} skip`))}let a=i.map(c=>`${r}_${c.stage.replace(/-/g,"_")}`);for(let c=0;c<a.length-1;c++)t.push(` ${a[c]} --> ${a[c+1]}`);t.push(" end")}else{let i=`${r}_skip`;t.push(` ${i}["${s} (SKIPPED)"]`),t.push(` class ${i} skip`)}t.push("")}for(let r=0;r<n.length-1;r++){let o=n[r],s=n[r+1],i=e.stages.filter(p=>p.phase===o),a=e.stages.filter(p=>p.phase===s),c=e.phases[o].included,l=e.phases[s].included,u,d;c&&i.length>0?u=`${o}_${i[i.length-1].stage.replace(/-/g,"_")}`:u=`${o}_skip`,l&&a.length>0?d=`${s}_${a[0].stage.replace(/-/g,"_")}`:d=`${s}_skip`,!c||!l?t.push(` ${u} -.-> ${d}`):t.push(` ${u} --> ${d}`)}return t.push("```"),t.join(`
|
|
271
|
+
`)}var Wt,rr,os,um,RE,PE,AE,dm,LE,as=U(()=>{"use strict";Wt=v(require("path"),1),rr=v(require("fs/promises"),1),os=require("fs"),um=v(require("os"),1);es();Z();RE=["bugfix","optimization"];PE=[{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"]}];AE={greenfield:"No existing source files detected \u2014 greenfield project.",bugfix:"Intent keywords matched 'fix', 'bug', 'broken', 'regression', 'error', 'crash', 'issue', 'defect', or 'patch' \u2192 bugfix pathway.",optimization:"Intent keywords matched 'optimize', 'performance', 'speed', 'cache', 'reduce', 'improve latency', 'memory', or 'bottleneck' \u2192 optimization pathway.","brownfield-refactor":"Intent keywords matched 'refactor', 'restructure', 'migrate', 'rewrite', 'reorganize', 'modernize', or 'upgrade' \u2192 brownfield-refactor pathway.","brownfield-enhancement":"Intent keywords matched 'add', 'new', 'feature', 'implement', 'integrate', 'extend', or 'support' (or no keywords matched \u2014 default brownfield pathway)."},dm={greenfield:"Greenfield","brownfield-enhancement":"Enhancement","brownfield-refactor":"Refactor",bugfix:"Bug Fix",optimization:"Optimization"};LE=`A Workflow Routing document must contain:
|
|
272
272
|
1. A header block with: Pathway, Risk Assessment, Risk Tier, Estimated Bolts, Estimated Depth, Generated date, Approved date
|
|
273
273
|
2. A "Phase Overview" table with columns: Phase | Included | Rationale \u2014 one row per phase (discovery, inception, construction, operations)
|
|
274
274
|
3. A "Stage Details" table with columns: # | Phase | Stage | Included | Rationale \u2014 one row per workflow stage
|
|
275
275
|
Pathway values: greenfield | brownfield-enhancement | brownfield-refactor | bugfix | optimization
|
|
276
276
|
Risk Assessment values: LOW | MEDIUM | HIGH
|
|
277
|
-
Estimated Depth values: minimal | standard | comprehensive`});var
|
|
277
|
+
Estimated Depth values: minimal | standard | comprehensive`});var cs={};he(cs,{CODE_PLAN_FORMAT_INSTRUCTIONS:()=>BE,buildCodeGenerationPrompt:()=>wm,buildCodePlanPath:()=>UE,dispatchCodeGeneration:()=>WE,extractSections:()=>Oa,extractTargetFiles:()=>$a,selectAgentForCodeGeneration:()=>ym});function UE(e,t,n){return(0,or.join)(e,"aidlc-docs",t,"construction",n,"code-plan.md")}function Oa(e,t){if(!e)return"";let n=[],r=e.split(`
|
|
278
278
|
`);for(let o=0;o<r.length;o++){let s=r[o],i=s.match(/^##\s+(.+)$/)||s.match(/^###\s+(.+)$/);if(i){let a=i[1].trim();if(t.some(c=>a.includes(c))){let c=[s],l=s.match(/^(#+)/)?.[1].length||2;for(let u=o+1;u<r.length;u++){let d=r[u],p=d.match(/^(#+)\s/);if(p&&p[1].length<=l)break;c.push(d)}n.push(c.join(`
|
|
279
279
|
`))}}}return n.length>0?n.join(`
|
|
280
280
|
|
|
281
|
-
`):e}function
|
|
282
|
-
`),r=!1;for(let o of n){if(o.match(/^##\s+Target Files/i)||o.match(/^###\s+Target Files/i)){r=!0;continue}if(r&&o.match(/^##\s+/))break;if(r){let s=o.match(/^-\s+(.+)$/);s&&t.push(s[1].trim())}}return t}function
|
|
281
|
+
`):e}function $a(e){let t=[],n=e.split(`
|
|
282
|
+
`),r=!1;for(let o of n){if(o.match(/^##\s+Target Files/i)||o.match(/^###\s+Target Files/i)){r=!0;continue}if(r&&o.match(/^##\s+/))break;if(r){let s=o.match(/^-\s+(.+)$/);s&&t.push(s[1].trim())}}return t}function ym(e){let t=$a(e),n=["olympian-low","frontend-engineer-low","oracle-low"];for(let r of n){let o=Rf(r);if(o&&o.success_rate>.8&&o.total_invocations>10)return gm(t,e)?r.startsWith("frontend")?r:"frontend-engineer-low":hm(e)?r.startsWith("oracle")?r:"oracle-low":r.startsWith("olympian")?r:"olympian-low"}return gm(t,e)?"frontend-engineer":hm(e)?"oracle":"olympian"}function gm(e,t){let n=[".tsx",".jsx",".css",".scss","/ui/","/component","/page","/layout"];for(let r of e){let o=r.toLowerCase();if(n.some(s=>o.includes(s)))return!0}return!1}function hm(e){let t=["debug","fix","investigate","diagnose"],n=e.toLowerCase();return t.some(r=>n.includes(r))}function wm(e,t,n,r,o){let s=r?`
|
|
283
283
|
## Execution Protocol (Two-Part Code Generation)
|
|
284
284
|
PART 1 - PLAN:
|
|
285
285
|
1. Create an execution plan in a markdown file with checkboxes for each step
|
|
@@ -309,50 +309,50 @@ Generate code for this unit according to the spec above.
|
|
|
309
309
|
- Create/modify files listed in "Target Files"
|
|
310
310
|
- Write tests per "Test Requirements"
|
|
311
311
|
- Meet all "Acceptance Criteria"
|
|
312
|
-
- Do NOT modify files outside the target list without justification`}async function
|
|
312
|
+
- Do NOT modify files outside the target list without justification`}async function WE(e,t,n){let r=(0,or.join)(e,"aidlc-docs",t),o=(0,or.join)(r,"construction"),s=(0,or.join)(o,n,"spec.md"),i=(0,sr.existsSync)(s)?(0,sr.readFileSync)(s,"utf-8"):"",a=(0,or.join)(r,"inception","intent.md"),c=(0,sr.existsSync)(a)?(0,sr.readFileSync)(a,"utf-8"):"",l=Oa(c,["Business Requirements","Technical Specification"]),u=Oa(c,["Problem Statement","Success Criteria"]),d=$a(i),p="";try{let{getArchitectureContext:_}=await Promise.resolve().then(()=>(Yr(),Qo)),h=[...new Set(d.map(b=>{let S=b.replace(/\\/g,"/").split("/").filter(Boolean);return S[0]==="src"&&S.length>1?S[1]:S[0]||""}).filter(Boolean))];h.length>0&&(p=await _(e,h))}catch(_){console.warn("[CodeGenExecutor] Architecture context loading failed:",_)}let f="";try{let{loadPathwayBehaviors:_}=await Promise.resolve().then(()=>(as(),mm)),{loadCheckpoint:h}=await Promise.resolve().then(()=>(ce(),Wi)),b=await h(e,t);if(b?.pathway_type){let S=await _(b.pathway_type);if(S){let T=S.rules.map(F=>`- **${F.name}**: ${F.description}`).join(`
|
|
313
313
|
`),k=S.qualityGateChecklist.map(F=>`- [ ] ${F}`).join(`
|
|
314
314
|
`);f=`
|
|
315
315
|
## Pathway Rules (${b.pathway_type})
|
|
316
316
|
${T}
|
|
317
317
|
|
|
318
318
|
### Quality Checklist
|
|
319
|
-
${k}`}}}catch(_){console.warn("[CodeGenExecutor] Pathway rules loading failed:",_)}let m="";try{let{loadArchitectureModel:_}=await Promise.resolve().then(()=>(
|
|
319
|
+
${k}`}}}catch(_){console.warn("[CodeGenExecutor] Pathway rules loading failed:",_)}let m="";try{let{loadArchitectureModel:_}=await Promise.resolve().then(()=>(Yr(),Qo)),h=await _(e);if(h?.designSystem?.detected&&h.designSystem.systems.length>0){let b=h.designSystem.systems.map(S=>S.name).join(", ");m=`
|
|
320
320
|
## Design System Enforcement
|
|
321
321
|
This project uses: ${b}. You MUST:
|
|
322
322
|
- Use existing components from the detected design system before creating new ones
|
|
323
323
|
- If you must create a new component, include a justification comment explaining why no existing component suffices
|
|
324
324
|
- Do NOT duplicate functionality already provided by ${b}`}}catch(_){console.warn("[CodeGenExecutor] Design system detection failed:",_)}let g=[p,f,m].filter(Boolean).join(`
|
|
325
325
|
|
|
326
|
-
`),y=
|
|
326
|
+
`),y=ym(i),w=wm(u,l,i,void 0,g||void 0);return{unitName:n,agentType:y,prompt:w,context:{unitSpec:i,intentSummary:l,intentSummary2:u,targetFiles:d,architectureContext:g||void 0}}}var sr,or,BE,ls=U(()=>{"use strict";sr=require("fs"),or=require("path");Jo();BE=`A code generation plan must contain:
|
|
327
327
|
1. A title line: "# Code Plan: {unitName}"
|
|
328
328
|
2. A checklist of implementation steps using markdown checkboxes (- [ ] step)
|
|
329
329
|
3. Each step should be specific and actionable
|
|
330
330
|
4. Steps should be ordered by dependency (prerequisites first)
|
|
331
331
|
5. Include a "## Verification" section with test/validation checkboxes
|
|
332
|
-
The plan file is saved at: aidlc-docs/{workflowId}/construction/{unitName}/code-plan.md`});var
|
|
333
|
-
`)){let r=n.trim();r&&(r.startsWith("//")||r[0]==="*"||/\bvi\.fn\b|\bjest\.fn\b|\bvi\.mock\b|\bjest\.mock\b|\bmockReturnValue\b|\bmockResolvedValue\b|\bmockImplementation\b|\bstub\b/.test(r)||/^\s*expect\s*\(|^\s*assert\s*[.(]/.test(n)||/\b\w+\s*\(/.test(r)&&t++)}return t}function
|
|
334
|
-
${o.body}`;
|
|
335
|
-
`)}function
|
|
336
|
-
`),{ratio:a,totalTests:c,negativeTests:l}=
|
|
337
|
-
`),r=[];for(let o=0;o<n.length&&!(r.length>=
|
|
338
|
-
`);let o=e.filter(i=>i.caught).length,s=e.filter(i=>!i.caught).length;if(r.push("## Summary",""),r.push("| Metric | Value |"),r.push("|--------|-------|"),r.push(`| Critical files analyzed | ${t.length} |`),r.push(`| Mutation points identified | ${e.length} |`),r.push(`| Caught by tests | ${o} |`),r.push(`| Uncaught (no test) | ${s} |`),r.push(""),t.length>0){r.push("## Critical Files","");for(let i of t)r.push(`- \`${
|
|
339
|
-
`)}async function
|
|
340
|
-
`);for(let o=0;o<r.length;o++){let s=r[o],i=s.match(/\b(AC-\d{3}\.\d+)\b/);if(!i)continue;let a=i[1];if(n.has(a))continue;n.add(a);let c=[],l=s.replace(/\*+/g,"").replace(/^[-*]\s*/,"").trim();c.push(l);for(let u=o+1;u<Math.min(o+10,r.length);u++){let d=r[u].trim();if(/^(Given|When|Then|And|But)\b/i.test(d))c.push(d);else{if(d===""&&u>o+1)break;if(/^\*\*(AC-|FR-)/.test(d)||/^#+\s/.test(d))break}}t.push({id:a,text:c.join(" ").trim(),source:"stories.md"})}if(t.length===0){let o=1,s=/###\s+(.+)/g,i;for(;(i=s.exec(e))!==null;)t.push({id:`AC-001.${o}`,text:i[1].trim(),source:"stories.md"}),o++}return t}function
|
|
341
|
-
`)){let o=r.match(/\b(FR-\d{3}\.\d+)\b/);if(!o)continue;let s=o[1];if(n.has(s))continue;n.add(s);let a=r.replace(/\*+/g,"").replace(/^[-*]\s*/,"").trim().replace(s,"").replace(/^[:\s-]+/,"").trim()||s;t.push({id:s,text:a,source:"requirements.md"})}return t}function
|
|
342
|
-
`)){let i=s.match(/^#{2,4}\s+(.+)/);if(i){let a=i[1].trim();a.length>3&&(r.push({id:`SPEC-${t.toUpperCase()}.${o}`,text:a,source:"spec.md"}),o++)}}return r}async function
|
|
343
|
-
`)){let m=f.match(/(?:^|\s)(?:it|test)\s*\(\s*['"`]([^'"`]+)['"`]/);if(!m)continue;let g=m[1],y=g.toLowerCase(),w=y.includes(o),_=s.some(h=>y.includes(h));(w||_||d)&&(r.some(b=>b.file===l&&b.testName===g)||r.push({file:l,testName:g}))}}let i=r.length>0?"Covered":"Gap";return{criterion:n,tests:r,status:i}})}function
|
|
344
|
-
`)}async function
|
|
332
|
+
The plan file is saved at: aidlc-docs/{workflowId}/construction/{unitName}/code-plan.md`});var _m={};he(_m,{buildRegressionSummary:()=>qE,categorizeFailure:()=>GE,checkFlakyThreshold:()=>HE});function GE(e,t,n){return t!==null&&t.status==="failed"?"pre_existing_failure":n.some(r=>r.status==="passed")?"flaky":t===null?"intentional_change":"legitimate_regression"}function HE(e,t=.2){let n=e.length;return n===0?!1:e.filter(o=>o==="flaky").length/n>t}function qE(e,t){let n=t.filter(o=>o==="legitimate_regression").length,r=t.filter(o=>o==="flaky").length;return{regressions_count:n,flaky_count:r}}var km=U(()=>{"use strict"});async function Sm(e,t){let n=[];for(let r of VE){let o=e.get(r);if(!o)continue;let s;try{let i=new Promise((a,c)=>setTimeout(()=>c(new Error("timeout")),t.timeoutBudgetMs));s=await Promise.race([o(t),i])}catch(i){let a=i instanceof Error&&i.message==="timeout",c={id:`${r}-error`,severity:"error",category:a?"timeout":"runtime-error",message:a?`Validator '${r}' exceeded timeout of ${t.timeoutBudgetMs}ms`:`Validator '${r}' threw an error: ${i instanceof Error?i.message:String(i)}`};console.error(`[ValidatorPipeline] ${r} validator failed:`,i),s={status:a?"timeout":"failed",findings:[c],artifactPath:""}}n.push({validator:r,result:s})}return{results:n}}function vm(e,t){if(e==="mutation"){let n=["auth","payment","security","encrypt","token","credential","password","session","permission"];if(!t.unitFiles.some(o=>n.some(s=>o.toLowerCase().includes(s))))return{skip:!0,reason:"No critical-path keywords found in unit files"}}return e==="contract"&&t.apiSurfaceFiles.length===0?{skip:!0,reason:"No API surface files in unit"}:{skip:!1}}function Ee(e){return{...e,status:"passed",findings:e.findings.map(t=>({...t,severity:"info"}))}}async function bm(e,t,n,r,o,s,i){let a=await A(e,t);if(!a||!a.construction_units)return;let c=a.construction_units[n];if(!c)return;let l=YE[r];c[l]=o,r==="coverage"&&s!==void 0&&(c.coverage_percentage=s),r==="coverage"&&i!==void 0&&(c.critical_gap_count=i),await P(e,a)}var VE,YE,Cn=U(()=>{"use strict";ce();VE=["quality","mutation","traceability","contract","coverage"],YE={quality:"quality_validation_status",mutation:"mutation_validation_status",traceability:"traceability_status",contract:"contract_validation_status",coverage:"coverage_status"}});function Em(e){let t=[],n=/(?:^|\n)\s*(?:it|test)\s*\(\s*(['"`])([\s\S]*?)\1/g,r;for(;(r=n.exec(e))!==null;){let o=r[2]??"",s=r.index+r[0].length,i=e.slice(s),a=i.search(/\{/);if(a===-1)continue;let c=0,l=s+a,u=l;for(let p=a;p<i.length;p++){let f=i[p];if(f==="{")c++;else if(f==="}"&&(c--,c===0)){u=s+p+1;break}}let d=e.slice(l,u);t.push({name:o,body:d})}return t}function Da(e){return/\bexpect\s*\(/.test(e)||/\bassert\s*\(/.test(e)||/\bassert\.\w+\s*\(/.test(e)}function tT(e){return!Da(e)||QE.test(e)?!1:XE.test(e)}function nT(e){return!Da(e)||!/\.toMatchSnapshot\s*\(|\.toMatchInlineSnapshot\s*\(/.test(e)?!1:!ZE.test(e)}function rT(e){let t=0;for(let n of eT){let r=e.match(n);r&&(t+=r.length)}return t}function oT(e){let t=0;for(let n of e.split(`
|
|
333
|
+
`)){let r=n.trim();r&&(r.startsWith("//")||r[0]==="*"||/\bvi\.fn\b|\bjest\.fn\b|\bvi\.mock\b|\bjest\.mock\b|\bmockReturnValue\b|\bmockResolvedValue\b|\bmockImplementation\b|\bstub\b/.test(r)||/^\s*expect\s*\(|^\s*assert\s*[.(]/.test(n)||/\b\w+\s*\(/.test(r)&&t++)}return t}function us(e,t,n){let r=[],o=Em(e);for(let s of o){let{name:i,body:a}=s,c={file:n,testName:i||t};if(!Da(a)){r.push({id:`empty-body:${n}:${i}`,severity:"error",category:"empty-body",message:`Test "${i}" has no assertions (empty test body)`,location:c});continue}for(let d of KE)if(d.pattern.test(a)){r.push({id:`${d.category}:${n}:${i}`,severity:d.severity,category:d.category,message:`Test "${i}": ${d.description}`,location:c});break}tT(a)&&r.push({id:`surface-assertion:${n}:${i}`,severity:"warning",category:"surface-assertion",message:`Test "${i}": ${JE.find(d=>d.category==="surface-assertion")?.description??"Only surface assertions found"}`,location:c}),nT(a)&&r.push({id:`snapshot-overuse:${n}:${i}`,severity:"warning",category:"snapshot-overuse",message:`Test "${i}": Test relies exclusively on snapshot assertions without behavioral checks`,location:c});let l=rT(a),u=oT(a);l>3&&l>u*2&&r.push({id:`excessive-mocking:${n}:${i}`,severity:"warning",category:"excessive-mocking",message:`Test "${i}": Excessive mocking detected (${l} mocks vs ${u} real calls)`,location:{...c,testName:i}})}return r}function ds(e){let t=Em(e),n=t.length;if(n===0)return{ratio:0,totalTests:0,negativeTests:0};let r=0;for(let o of t){let s=`${o.name}
|
|
334
|
+
${o.body}`;zE.some(i=>i.test(s))&&r++}return{ratio:r/n,totalTests:n,negativeTests:r}}var KE,JE,zE,QE,XE,ZE,eT,Na=U(()=>{"use strict";KE=[{category:"tautological",severity:"error",pattern:/mockReturnValue\((['"`]?)(\w+)\1\)[^]*?\.toBe\((['"`]?)\2\3\)/,description:"Mock return value is asserted against itself (tautological assertion)"},{category:"tautological",severity:"error",pattern:/mockResolvedValue\((['"`]?)(\w+)\1\)[^]*?\.resolves\.toBe\((['"`]?)\2\3\)/,description:"Mock resolved value is asserted against itself (tautological assertion)"},{category:"trivially-true",severity:"error",pattern:/expect\((true|false)\)\.toBe\(\1\)/,description:"Literal boolean asserted against itself (trivially true assertion)"},{category:"trivially-true",severity:"error",pattern:/expect\((true|1)\)\.toBeTruthy\(\)/,description:"Always-truthy literal asserted as truthy (trivially true assertion)"},{category:"trivially-true",severity:"error",pattern:/expect\((false|0)\)\.toBeFalsy\(\)/,description:"Always-falsy literal asserted as falsy (trivially true assertion)"},{category:"trivially-true",severity:"error",pattern:/expect\(null\)\.toBeNull\(\)/,description:"Null literal asserted as null (trivially true assertion)"},{category:"trivially-true",severity:"error",pattern:/expect\(undefined\)\.toBeUndefined\(\)/,description:"Undefined literal asserted as undefined (trivially true assertion)"}],JE=[{category:"surface-assertion",severity:"warning",pattern:/(?:expect\([^)]+\)\.(?:toBeInTheDocument|toBeDefined|toBeNull|toExist|toBeVisible)\(\)[\s;,]*)+/,description:"All assertions use only surface-level existence matchers without behavioral checks"},{category:"snapshot-overuse",severity:"warning",pattern:/expect\([^)]+\)\.toMatchSnapshot\(\)/,description:"Test relies exclusively on snapshot assertions without behavioral checks"},{category:"snapshot-overuse",severity:"warning",pattern:/expect\([^)]+\)\.toMatchInlineSnapshot\(/,description:"Test relies exclusively on inline snapshot assertions without behavioral checks"}],zE=[/\bthrow\b/i,/\breject\b/i,/\berror\b/i,/\binvalid\b/i,/\bfail\b/i,/\bboundary\b/i,/\bedge\b/i,/\bnegative\b/i,/\bmissing\b/i,/\bunauthorized\b/i,/\bforbidden\b/i,/\bnot.?found\b/i,/\.toThrow\b/,/\.rejects\b/,/\.toThrowError\b/],QE=/\.(?:toBe|toEqual|toStrictEqual|toMatchObject|toHaveBeenCalledWith|toHaveBeenCalled|toHaveReturnedWith|toThrow|toResolve|toReject|toHaveLength|toBeGreaterThan|toBeLessThan|toBeCloseTo)\s*\(/g,XE=/\.(?:toContain|toBeInTheDocument|toBeDefined|toBeNull|toExist|toBeVisible|toBeUndefined|toBeTruthy|toBeFalsy)\s*\(/g,ZE=/\.(?:toBe|toEqual|toStrictEqual|toMatchObject|toContain|toHaveBeenCalled|toHaveBeenCalledWith|toThrow|toReject|toBeInTheDocument|toBeDefined|toHaveLength|toBeGreaterThan|toBeLessThan)\s*\(/,eT=[/\bvi\.fn\s*\(/g,/\bjest\.fn\s*\(/g,/\bmock\s*\(/g,/\bstub\s*\(/g,/\.mockReturnValue\s*\(/g,/\.mockResolvedValue\s*\(/g,/\.mockImplementation\s*\(/g,/vi\.mock\s*\(/g,/jest\.mock\s*\(/g]});async function sT(e){if(!await sn.default.pathExists(e))return[];let n=(await sn.default.readdir(e)).filter(o=>o.endsWith(".test.ts")||o.endsWith(".test.js")||o.endsWith(".spec.ts")||o.endsWith(".spec.js")),r=[];for(let o of n){let s=Rn.default.join(e,o),i=await sn.default.readFile(s,"utf-8");r.push({filePath:s,content:i})}return r}function iT(e){let t=e.match(/(?:^|\n)\s*(?:it|test)\s*\(\s*['"`]/g);return t?t.length:0}function Tm(e,t,n,r,o,s){let i=e.filter(u=>u.severity==="error"),a=e.filter(u=>u.severity==="warning"),c=n-t,l=["# Quality Validation Report","","## Summary","","| Metric | Value |","|--------|-------|",`| Total tests | ${n} |`,`| Validated tests | ${t} |`,`| Rejected tests | ${c} |`,`| Warnings | ${a.length} |`,""];if(i.length>0){l.push("## Rejections",""),l.push("| Test | File | Reason |"),l.push("|------|------|--------|");for(let u of i){let d=u.location?.testName??"unknown",p=u.location?.file??"unknown";l.push(`| ${d} | ${p} | ${u.message} |`)}l.push("")}if(a.length>0){l.push("## Warnings",""),l.push("| Test | File | Warning | Details |"),l.push("|------|------|---------|---------|");for(let u of a){let d=u.location?.testName??"unknown",p=u.location?.file??"unknown";l.push(`| ${d} | ${p} | ${u.category} | ${u.message} |`)}l.push("")}return l.push("## Negative Case Coverage",""),l.push("| Metric | Value |"),l.push("|--------|-------|"),l.push(`| Total tests | ${o} |`),l.push(`| Negative tests | ${s} |`),l.push(`| Ratio | ${(r*100).toFixed(1)}% |`),l.push(`| Threshold | ${(ps*100).toFixed(1)}% |`),l.push(`| Status | ${r>=ps?"PASS":"BELOW THRESHOLD"} |`),l.push(""),l.join(`
|
|
335
|
+
`)}function Cm(){return async e=>{let t=Rn.default.join(e.projectPath,"aidlc-docs",e.workflowId,"construction",e.unitId,"testing"),n=Rn.default.join(t,"quality-validation.md"),r=await sT(t);if(r.length===0){let w={status:"passed",findings:[],artifactPath:n};return await sn.default.ensureDir(Rn.default.dirname(n)),await sn.default.writeFile(n,Tm([],0,0,0,0,0),"utf-8"),e.allowFailures?Ee(w):w}let o=[],s=0;for(let{filePath:w,content:_}of r){let h=Rn.default.basename(w),b=us(_,h,w);o.push(...b),s+=iT(_)}let i=r.map(w=>w.content).join(`
|
|
336
|
+
`),{ratio:a,totalTests:c,negativeTests:l}=ds(i),u=[];c>0&&a<ps&&u.push({id:`negative-case-ratio:${e.unitId}`,severity:"warning",category:"negative-case-ratio",message:`Negative case ratio is ${(a*100).toFixed(1)}% (${l}/${c}), below the ${(ps*100).toFixed(1)}% threshold`});let d=[...o,...u],p=d.filter(w=>w.severity==="error"),f=d.filter(w=>w.severity==="warning"),m=Math.max(0,s-p.length),g;p.length>0?g="failed":f.length>0?g="warned":g="passed",await sn.default.ensureDir(Rn.default.dirname(n)),await sn.default.writeFile(n,Tm(d,m,s,a,c,l),"utf-8");let y={status:g,findings:d,artifactPath:n};return e.allowFailures?Ee(y):y}}var sn,Rn,ps,Rm=U(()=>{"use strict";sn=v(X(),1),Rn=v(require("path"),1);Cn();Na();ps=.2});function aT(e){let t=[];for(let{filePath:n,content:r}of e){let o=Pe.default.basename(n).toLowerCase(),s=ja.some(a=>new RegExp(`\\b${a}\\b`,"i").test(o)),i=ja.some(a=>new RegExp(`\\b${a}`,"i").test(r));(s||i)&&t.push(n)}return t}function cT(e,t){let n=e.split(`
|
|
337
|
+
`),r=[];for(let o=0;o<n.length&&!(r.length>=fs);o++){let s=o+1,i=n[o].trim();if(/===/.test(i)){r.push({filePath:t,line:s,original:i,mutated:i.replace(/===/,"!=="),faultType:"conditional-negation",context:i});continue}if(/!==/.test(i)){r.push({filePath:t,line:s,original:i,mutated:i.replace(/!==/,"==="),faultType:"conditional-negation",context:i});continue}if(/\breturn\s+true\b/.test(i)){r.push({filePath:t,line:s,original:i,mutated:i.replace(/\breturn\s+true\b/,"return false"),faultType:"return-value",context:i});continue}if(/\breturn\s+false\b/.test(i)){r.push({filePath:t,line:s,original:i,mutated:i.replace(/\breturn\s+false\b/,"return true"),faultType:"return-value",context:i});continue}if(/\breturn\s+null\b/.test(i)){r.push({filePath:t,line:s,original:i,mutated:i.replace(/\breturn\s+null\b/,"return undefined"),faultType:"return-value",context:i});continue}if(/(?<!=)>=/.test(i)){r.push({filePath:t,line:s,original:i,mutated:i.replace(/(?<!=)>=/,">"),faultType:"comparison-boundary",context:i});continue}if(/<=(?!=)/.test(i)&&!i.includes("=>")){r.push({filePath:t,line:s,original:i,mutated:i.replace(/<=(?!=)/,"<"),faultType:"comparison-boundary",context:i});continue}if(/(?<![=!<>])>(?![>=])/.test(i)&&!/=>/.test(i)){r.push({filePath:t,line:s,original:i,mutated:i.replace(/(?<![=!<>])>(?![>=])/,">="),faultType:"comparison-boundary",context:i});continue}if(/(?<![=!<>])<(?![<=])/.test(i)&&!/=>/.test(i)){r.push({filePath:t,line:s,original:i,mutated:i.replace(/(?<![=!<>])<(?![<=])/,"<="),faultType:"comparison-boundary",context:i});continue}if(/\bif\s*\(!/.test(i)){r.push({filePath:t,line:s,original:i,mutated:i.replace(/\bif\s*\(!/,"if ("),faultType:"conditional-negation",context:i});continue}if(/\bif\s*\((?!!)/.test(i)){r.push({filePath:t,line:s,original:i,mutated:i.replace(/\bif\s*\((?!!)/,"if (!"),faultType:"conditional-negation",context:i});continue}}return r.slice(0,fs)}function lT(e,t){return e.map(n=>{let r=Pe.default.basename(n.filePath,Pe.default.extname(n.filePath));for(let{filePath:o,content:s}of t)if((s.includes(r)||s.includes(Pe.default.basename(n.filePath)))&&uT(n,s)){let a=s.match(/(?:it|test)\s*\(\s*['"`]([^'"`]+)['"`]/);return{point:n,caught:!0,testFile:o,testName:a?a[1]:void 0}}return{point:n,caught:!1}})}function uT(e,t){return/expect\s*\(/.test(t)?e.faultType==="conditional-negation"?/\b(false|null|undefined|throws?|rejects?|denied|unauthorized|forbidden|invalid)\b/i.test(t)||/toBe\s*\(\s*false\s*\)/.test(t)||/toBeFalsy/.test(t)||/toThrow/.test(t)||/toReject/.test(t)||/status.*4\d\d/.test(t):e.faultType==="comparison-boundary"?/\b(0|1|limit|max|min|boundary|threshold|exactly|equal)\b/i.test(t)||/toBe\s*\(\s*\d+\s*\)/.test(t)||/toEqual/.test(t):e.faultType==="return-value"?/toBe\s*\(\s*(true|false|null|undefined)\s*\)/.test(t)||/toBeTruthy/.test(t)||/toBeFalsy/.test(t)||/toBeNull/.test(t)||/toBeUndefined/.test(t):!1:!1}function xm(e,t,n){let r=["# Mutation Validation Report",""];if(n)return r.push("## Status: Skipped",""),r.push("No critical-path files were identified in this unit."),r.push("Mutation spot-check requires files containing keywords: "+ja.join(", ")+"."),r.push(""),r.join(`
|
|
338
|
+
`);let o=e.filter(i=>i.caught).length,s=e.filter(i=>!i.caught).length;if(r.push("## Summary",""),r.push("| Metric | Value |"),r.push("|--------|-------|"),r.push(`| Critical files analyzed | ${t.length} |`),r.push(`| Mutation points identified | ${e.length} |`),r.push(`| Caught by tests | ${o} |`),r.push(`| Uncaught (no test) | ${s} |`),r.push(""),t.length>0){r.push("## Critical Files","");for(let i of t)r.push(`- \`${Pe.default.basename(i)}\``);r.push("")}if(e.length>0){r.push("## Mutation Points",""),r.push("| File | Line | Fault Type | Original | Mutated | Status | Test Reference |"),r.push("|------|------|------------|----------|---------|--------|----------------|");for(let i of e){let a=i.caught?"CAUGHT":"UNCAUGHT",c=i.caught?i.testName?`\`${i.testName}\``:Pe.default.basename(i.testFile??""):"\u2014",l=i.point.original.length>40?i.point.original.slice(0,37)+"...":i.point.original,u=i.point.mutated.length>40?i.point.mutated.slice(0,37)+"...":i.point.mutated;r.push(`| ${Pe.default.basename(i.point.filePath)} | ${i.point.line} | ${i.point.faultType} | ${l} | ${u} | ${a} | ${c} |`)}r.push("")}return r.join(`
|
|
339
|
+
`)}async function dT(e){let t=[];for(let n of e)try{if(await Tt.default.pathExists(n)){let r=await Tt.default.readFile(n,"utf-8");t.push({filePath:n,content:r})}}catch{}return t}async function pT(e){if(!await Tt.default.pathExists(e))return[];let n=(await Tt.default.readdir(e)).filter(o=>o.endsWith(".test.ts")||o.endsWith(".test.js")||o.endsWith(".spec.ts")||o.endsWith(".spec.js")),r=[];for(let o of n){let s=Pe.default.join(e,o),i=await Tt.default.readFile(s,"utf-8");r.push({filePath:s,content:i})}return r}function Pm(){return async e=>{let t=Pe.default.join(e.projectPath,"aidlc-docs",e.workflowId,"construction",e.unitId,"testing"),n=Pe.default.join(t,"mutation-validation.md"),r=await dT(e.unitFiles),o=aT(r);if(o.length===0){await Tt.default.ensureDir(Pe.default.dirname(n)),await Tt.default.writeFile(n,xm([],[],!0),"utf-8");let p={status:"skipped",findings:[],artifactPath:n};return e.allowFailures?Ee(p):p}let s=[];for(let p of r)if(o.includes(p.filePath)&&(s.push(...cT(p.content,p.filePath)),s.length>=fs))break;let i=s.slice(0,fs),a=await pT(t),c=lT(i,a),l=[];for(let p of c)p.caught||l.push({id:`mutation-uncaught:${Pe.default.basename(p.point.filePath)}:${p.point.line}`,severity:"warning",category:"uncaught-mutation",message:`Uncaught ${p.point.faultType} mutation at ${Pe.default.basename(p.point.filePath)}:${p.point.line} \u2014 \`${p.point.original}\` \u2192 \`${p.point.mutated}\``,location:{file:p.point.filePath,line:p.point.line}});let u=l.length===0?"passed":"warned";await Tt.default.ensureDir(Pe.default.dirname(n)),await Tt.default.writeFile(n,xm(c,o,!1),"utf-8");let d={status:u,findings:l,artifactPath:n};return e.allowFailures?Ee(d):d}}var Tt,Pe,ja,fs,Am=U(()=>{"use strict";Tt=v(X(),1),Pe=v(require("path"),1);Cn();ja=["auth","payment","security","encrypt","token","credential","password","session","permission"],fs=10});function fT(e){let t=e.toLowerCase();return Im.some(n=>t.includes(n))}function mT(e){let t=e.toLowerCase();for(let n of Im)if(t.includes(n))return`Criterion contains "${n}" \u2014 inherently untestable`;return"Inherently untestable"}function gT(e){let t=[],n=new Set,r=e.split(`
|
|
340
|
+
`);for(let o=0;o<r.length;o++){let s=r[o],i=s.match(/\b(AC-\d{3}\.\d+)\b/);if(!i)continue;let a=i[1];if(n.has(a))continue;n.add(a);let c=[],l=s.replace(/\*+/g,"").replace(/^[-*]\s*/,"").trim();c.push(l);for(let u=o+1;u<Math.min(o+10,r.length);u++){let d=r[u].trim();if(/^(Given|When|Then|And|But)\b/i.test(d))c.push(d);else{if(d===""&&u>o+1)break;if(/^\*\*(AC-|FR-)/.test(d)||/^#+\s/.test(d))break}}t.push({id:a,text:c.join(" ").trim(),source:"stories.md"})}if(t.length===0){let o=1,s=/###\s+(.+)/g,i;for(;(i=s.exec(e))!==null;)t.push({id:`AC-001.${o}`,text:i[1].trim(),source:"stories.md"}),o++}return t}function Om(e){let t=[],n=new Set;for(let r of e.split(`
|
|
341
|
+
`)){let o=r.match(/\b(FR-\d{3}\.\d+)\b/);if(!o)continue;let s=o[1];if(n.has(s))continue;n.add(s);let a=r.replace(/\*+/g,"").replace(/^[-*]\s*/,"").trim().replace(s,"").replace(/^[:\s-]+/,"").trim()||s;t.push({id:s,text:a,source:"requirements.md"})}return t}function hT(e,t){let n=Om(e);if(n.length>0)return n.map(s=>({...s,source:"spec.md"}));let r=[],o=1;for(let s of e.split(`
|
|
342
|
+
`)){let i=s.match(/^#{2,4}\s+(.+)/);if(i){let a=i[1].trim();a.length>3&&(r.push({id:`SPEC-${t.toUpperCase()}.${o}`,text:a,source:"spec.md"}),o++)}}return r}async function yT(e){let t=Ct.default.join(e.projectPath,"aidlc-docs",e.workflowId,"inception"),n=Ct.default.join(t,"user-stories","stories.md");if(await Xe.default.pathExists(n)){let s=await Xe.default.readFile(n,"utf-8"),i=gT(s);if(i.length>0)return{type:"user-stories",criteria:i}}let r=Ct.default.join(t,"requirements","requirements.md");if(await Xe.default.pathExists(r)){let s=await Xe.default.readFile(r,"utf-8"),i=Om(s);if(i.length>0)return{type:"requirements",criteria:i}}let o=Ct.default.join(e.projectPath,"aidlc-docs",e.workflowId,"construction",e.unitId,"spec.md");if(await Xe.default.pathExists(o)){let s=await Xe.default.readFile(o,"utf-8"),i=hT(s,e.unitId);if(i.length>0)return{type:"unit-spec",criteria:i}}return null}function wT(e,t){return e.map(n=>{if(fT(n.text))return{criterion:n,tests:[],status:"Not Testable",notTestableReason:mT(n.text)};let r=[],o=n.id.toLowerCase(),s=n.text.toLowerCase().split(/\W+/).filter(a=>a.length>4);for(let{filePath:a,content:c}of t){let l=Ct.default.basename(a),u=c.toLowerCase(),d=u.includes(o),p=s.length>0&&s.some(f=>u.includes(f));if(!(!d&&!p))for(let f of c.split(`
|
|
343
|
+
`)){let m=f.match(/(?:^|\s)(?:it|test)\s*\(\s*['"`]([^'"`]+)['"`]/);if(!m)continue;let g=m[1],y=g.toLowerCase(),w=y.includes(o),_=s.some(h=>y.includes(h));(w||_||d)&&(r.some(b=>b.file===l&&b.testName===g)||r.push({file:l,testName:g}))}}let i=r.length>0?"Covered":"Gap";return{criterion:n,tests:r,status:i}})}function _T(e,t){let n=t==="user-stories"?"User Stories (Gherkin AC)":t==="requirements"?"Requirements (FR sub-requirements)":"Unit Spec",r=e.filter(c=>c.status==="Covered").length,o=e.filter(c=>c.status==="Gap").length,s=e.filter(c=>c.status==="Not Testable").length,i=e.length,a=["# Requirement-Test Traceability Map","",`**Source**: ${n}`,"","## Summary","","| Metric | Value |","|--------|-------|",`| Total criteria | ${i} |`,`| Covered | ${r} |`,`| Gaps | ${o} |`,`| Not Testable | ${s} |`,"","## Traceability Table","","| Requirement/Criterion | Test(s) | Status |","|-----------------------|---------|--------|"];for(let c of e){let l=c.criterion.text,u=l.length>60?l.slice(0,60)+"...":l,d=`${c.criterion.id}: ${u}`,p;c.status==="Not Testable"?p=`\u2014 (${c.notTestableReason??"Not Testable"})`:c.tests.length===0?p="\u2014":p=c.tests.map(f=>`${f.file}: ${f.testName}`).join("<br>"),a.push(`| ${d} | ${p} | ${c.status} |`)}return a.push(""),a.join(`
|
|
344
|
+
`)}async function kT(e){if(!await Xe.default.pathExists(e))return[];let n=(await Xe.default.readdir(e)).filter(o=>o.endsWith(".test.ts")||o.endsWith(".test.js")||o.endsWith(".spec.ts")||o.endsWith(".spec.js")),r=[];for(let o of n){let s=Ct.default.join(e,o),i=await Xe.default.readFile(s,"utf-8");r.push({filePath:s,content:i})}return r}function $m(){return async e=>{let t=Ct.default.join(e.projectPath,"aidlc-docs",e.workflowId,"construction",e.unitId,"testing"),n=Ct.default.join(t,"requirement-test-map.md"),r=await yT(e);if(r===null){let d={status:"skipped",findings:[{id:`traceability:no-source:${e.unitId}`,severity:"info",category:"no-traceability-source",message:"No traceability source found (user stories, requirements, or unit spec). Traceability skipped."}],artifactPath:n};return e.allowFailures?Ee(d):d}let{criteria:o}=r;if(e.workflowDepth===0){let d=["reproduce","fix","verify"];o=o.filter(p=>{let f=p.text.toLowerCase();return d.some(m=>f.includes(m))})}let s=await kT(t),i=wT(o,s),a=i.filter(d=>d.status==="Gap"),c=[];for(let d of a){let p=e.workflowDepth>=2?"error":"warning";c.push({id:`traceability:gap:${d.criterion.id}`,severity:p,category:"traceability-gap",message:`No test covers criterion ${d.criterion.id}: "${d.criterion.text.slice(0,80)}"`})}let l;a.length===0?l="passed":e.workflowDepth>=2?l="failed":(e.workflowDepth,l="warned"),await Xe.default.ensureDir(Ct.default.dirname(n)),await Xe.default.writeFile(n,_T(i,r.type),"utf-8");let u={status:l,findings:c,artifactPath:n};return e.allowFailures?Ee(u):u}}var Xe,Ct,Im,Dm=U(()=>{"use strict";Xe=v(X(),1),Ct=v(require("path"),1);Cn();Im=["deployment","infrastructure","manual review","visual inspection","ui style","not testable"]});function bT(e){let t=[],n=[];for(let r of e){let o=Rt.default.extname(r).toLowerCase();if(!ST.has(o)){n.push(r),console.warn(`[ContractValidator] Skipping non-JS/TS file: ${r}`);continue}(vT.some(i=>i.test(r))||Rt.default.basename(r)==="index.ts"||Rt.default.basename(r)==="index.js")&&t.push(r)}return{surfaces:t,nonJsFiles:n}}function Nm(e,t){let n=[],r=[],o=[],s=/export\s+(?:async\s+)?function\s+(\w+)\s*\(([^)]*)\)\s*(?::\s*([^\s{;]+(?:\s*<[^>]*>)?(?:\[\])?(?:\s*\|\s*[^\s{;]+)*))?/g,i;for(;(i=s.exec(e))!==null;){let d=i[1],p=i[2].trim(),f=(i[3]??"void").trim(),m=p===""?0:p.split(",").length;n.push({name:d,parameterCount:m,returnType:f})}let a=/export\s+const\s+(\w+)\s*=\s*(?:async\s*)?\(([^)]*)\)\s*(?::\s*([^\s=>]+))?\s*=>/g;for(;(i=a.exec(e))!==null;){let d=i[1],p=i[2].trim(),f=(i[3]??"void").trim(),m=p===""?0:p.split(",").length;n.push({name:d,parameterCount:m,returnType:f})}let c=/(?:app|router|server|fastify)\s*\.\s*(get|post|put|patch|delete|head|options)\s*\(\s*['"`]([^'"`]+)['"`]/gi;for(;(i=c.exec(e))!==null;){let d=i[1].toUpperCase(),p=i[2],f=ET(e,i.index);r.push({method:d,path:p,statusCodes:f})}let l=/export\s+(?:interface|type)\s+(\w+)\s*(?:<[^>]*>)?\s*([=\{][^}]*\}?)/gs;for(;(i=l.exec(e))!==null;){let d=i[1],p=i[2].slice(0,200).replace(/\s+/g," ").trim();o.push({name:d,definition:p})}let u=/export\s+(?:const\s+)?enum\s+(\w+)\s*\{([^}]*)\}/gs;for(;(i=u.exec(e))!==null;){let d=i[1],p=i[2].split(",").map(f=>f.trim().split("=")[0].trim()).filter(f=>f.length>0);o.push({name:`enum:${d}`,definition:p.join(",")})}return{exports:n,endpoints:r,types:o}}function ET(e,t){let n=e.slice(t,t+500),r=/\.status\s*\(\s*(\d{3})\s*\)/g,o=[],s;for(;(s=r.exec(n))!==null;){let i=parseInt(s[1],10);o.includes(i)||o.push(i)}return o}function TT(e,t){let n=[];for(let r of e.exports){let o=t.exports.find(s=>s.name===r.name);if(!o){n.push({category:"removed-export",name:r.name,before:`${r.name}(${r.parameterCount} params): ${r.returnType}`,after:"(removed)"});continue}o.parameterCount!==r.parameterCount&&n.push({category:"changed-params",name:r.name,before:`${r.parameterCount} params`,after:`${o.parameterCount} params`}),o.returnType!==r.returnType&&r.returnType!=="void"&&r.returnType!==""&&n.push({category:"changed-return-type",name:r.name,before:r.returnType,after:o.returnType})}for(let r of e.endpoints)t.endpoints.find(s=>s.method===r.method&&s.path===r.path)||n.push({category:"removed-endpoint",name:`${r.method} ${r.path}`,before:`${r.method} ${r.path}`,after:"(removed)"});for(let r of e.types){if(!r.name.startsWith("enum:"))continue;let o=t.types.find(c=>c.name===r.name);if(!o){n.push({category:"narrowed-enum",name:r.name.replace("enum:",""),before:r.definition,after:"(removed)"});continue}let s=r.definition.split(",").map(c=>c.trim()).filter(Boolean),i=o.definition.split(",").map(c=>c.trim()).filter(Boolean);s.filter(c=>!i.includes(c)).length>0&&n.push({category:"narrowed-enum",name:r.name.replace("enum:",""),before:s.join(", "),after:i.join(", ")})}return n}function jm(e,t,n,r){if(n)return["# Contract Validation Report","","## Result","","No API surfaces affected. Contract validation skipped.",""].join(`
|
|
345
345
|
`);let o=["# Contract Validation Report","","## Summary","","| Metric | Value |","|--------|-------|",`| Exports analyzed | ${t.exports.length} |`,`| Endpoints analyzed | ${t.endpoints.length} |`,`| Breaking changes found | ${e.length} |`,"| Contract source | inferred from source code |",""];if(e.length>0){o.push("## Breaking Changes",""),o.push("| Category | Name | Before | After |"),o.push("|----------|------|--------|-------|");for(let s of e)o.push(`| ${s.category} | ${s.name} | ${s.before} | ${s.after} |`);o.push(""),o.push("> **Human Approval Required**: Breaking changes detected. Review before proceeding.","")}if(r.length>0){o.push("## Non-JS/TS Files Skipped",""),o.push("The following files were skipped (contract validation supports JS/TS only):","");for(let s of r)o.push(`- \`${s}\``);o.push("")}if(t.exports.length>0){o.push("## Exports",""),o.push("| Name | Parameters | Return Type |"),o.push("|------|-----------|-------------|");for(let s of t.exports)o.push(`| ${s.name} | ${s.parameterCount} | ${s.returnType} |`);o.push("")}if(t.endpoints.length>0){o.push("## Endpoints",""),o.push("| Method | Path | Status Codes |"),o.push("|--------|------|-------------|");for(let s of t.endpoints){let i=s.statusCodes.length>0?s.statusCodes.join(", "):"N/A";o.push(`| ${s.method} | ${s.path} | ${i} |`)}o.push("")}if(t.types.length>0){o.push("## Types",""),o.push("| Name | Definition |"),o.push("|------|-----------|");for(let s of t.types){let i=s.name.startsWith("enum:")?`enum ${s.name.slice(5)}`:s.name;o.push(`| ${i} | ${s.definition} |`)}o.push("")}return o.join(`
|
|
346
|
-
`)}function
|
|
347
|
-
${t.toLowerCase()}`;for(let o of n.critical)if(new RegExp(`\\b${o}\\b`,"i").test(r))return"critical";for(let o of n.moderate)if(new RegExp(`\\b${o}\\b`,"i").test(r))return"moderate";return"low"}async function
|
|
348
|
-
`)}function
|
|
349
|
-
`)}function
|
|
350
|
-
`)[0].trim();o&&(t==="bugfix"?n.fixed.push(o):/(?:add|create|implement|introduce|new)/i.test(o)?n.added.push(o):/(?:fix|repair|resolve|patch|correct)/i.test(o)?n.fixed.push(o):/(?:update|change|modify|refactor|improve|enhance)/i.test(o)?n.changed.push(o):n.added.push(o))}return n}function
|
|
351
|
-
`)}function
|
|
352
|
-
`+s)}else
|
|
353
|
-
`+t)}function
|
|
354
|
-
`);
|
|
355
|
-
`);
|
|
346
|
+
`)}function Fm(){return async e=>{let t=Rt.default.join(e.projectPath,"aidlc-docs",e.workflowId,"construction",e.unitId,"testing"),n=Rt.default.join(t,"contract-validation.md"),r=[...new Set([...e.unitFiles,...e.apiSurfaceFiles])],{surfaces:o,nonJsFiles:s}=bT(r);if(o.length===0){let f={status:"skipped",findings:[{id:"contract:no-api-surfaces",severity:"info",category:"skip",message:"No API surfaces detected in unit files. Contract validation skipped."}],artifactPath:n};return await xn.default.ensureDir(t),await xn.default.writeFile(n,jm([],{exports:[],endpoints:[],types:[]},!0,s),"utf-8"),e.allowFailures?Ee(f):f}let i=[],a={exports:[],endpoints:[],types:[]},c=[];for(let f of s)c.push({id:`contract:non-js-ts:${Rt.default.basename(f)}`,severity:"warning",category:"non-js-ts-file",message:`File skipped (non-JS/TS): ${f}`,location:{file:f}});for(let f of o){let m;try{m=await xn.default.readFile(f,"utf-8")}catch{c.push({id:`contract:read-error:${Rt.default.basename(f)}`,severity:"warning",category:"read-error",message:`Could not read API surface file: ${f}`,location:{file:f}});continue}let g=Nm(m,f);if(a.exports.push(...g.exports),a.endpoints.push(...g.endpoints),a.types.push(...g.types),e.apiSurfaceFiles.includes(f)){for(let y of e.unitFiles)if(Rt.default.basename(y)===Rt.default.basename(f)){let w;try{w=await xn.default.readFile(y,"utf-8")}catch{continue}let _=Nm(w,y);i.push(...TT(g,_))}}}for(let f of i)c.push({id:`contract:breaking:${f.category}:${f.name}`,severity:"error",category:f.category,message:`Breaking change detected (${f.category}): ${f.name} \u2014 before: ${f.before}, after: ${f.after}`});let l=c.filter(f=>f.severity==="error"),u=c.filter(f=>f.severity==="warning"),d;l.length>0?d="failed":u.length>0?d="warned":d="passed",await xn.default.ensureDir(t),await xn.default.writeFile(n,jm(i,a,!1,s),"utf-8");let p={status:d,findings:c,artifactPath:n};return e.allowFailures?Ee(p):p}}var xn,Rt,ST,vT,Mm=U(()=>{"use strict";xn=v(X(),1),Rt=v(require("path"),1);Cn();ST=new Set([".ts",".tsx",".js",".jsx"]),vT=[/[/\\]routes[/\\]/,/[/\\]controllers[/\\]/,/[/\\]api[/\\]/,/[/\\]handlers[/\\]/]});function RT(e){let t=CT;try{let r=[Ge.default.resolve(Ge.default.dirname(new URL(NT.url).pathname),"../../../../resources/config/risk-keywords.json"),Ge.default.resolve(process.cwd(),"resources/config/risk-keywords.json")];for(let o of r){let s=o.startsWith("/")&&o[2]===":"?o.slice(1):o;if(Ae.default.existsSync(s)){t=JSON.parse(Ae.default.readFileSync(s,"utf-8"));break}}}catch(r){}let n=Ge.default.join(e,".olympus","config.json");if(Ae.default.existsSync(n))try{let o=JSON.parse(Ae.default.readFileSync(n,"utf-8"))["risk-keywords"];if(o)return{critical:o.critical??t.critical,moderate:o.moderate??t.moderate,low:o.low??t.low}}catch(r){}return t}function xT(e,t,n){let r=`${e.toLowerCase()}
|
|
347
|
+
${t.toLowerCase()}`;for(let o of n.critical)if(new RegExp(`\\b${o}\\b`,"i").test(r))return"critical";for(let o of n.moderate)if(new RegExp(`\\b${o}\\b`,"i").test(r))return"moderate";return"low"}async function PT(e,t){let n=Ge.default.join(e,"coverage","coverage-summary.json");if(await Ae.default.pathExists(n))try{let o=JSON.parse(await Ae.default.readFile(n,"utf-8")),s=[];for(let[i,a]of Object.entries(o))i!=="total"&&s.push({filePath:i,lineCoverage:a.lines?.pct,branchCoverage:a.branches?.pct,functionCoverage:a.functions?.pct});return{source:"instrumentation",files:s}}catch(o){}let r=[];for(let o of t){let s=Ge.default.parse(o),i=[Ge.default.join(s.dir,`${s.name}.test${s.ext}`),Ge.default.join(s.dir,`${s.name}.spec${s.ext}`),o.replace(/src\//,"src/__tests__/").replace(/\.(ts|js)$/,".test.$1")],a=!1;for(let c of i)if(await Ae.default.pathExists(c)){a=!0;break}r.push({filePath:o,lineCoverage:a?100:0,branchCoverage:a?100:0,functionCoverage:a?100:0})}return{source:"static-analysis",files:r}}function AT(e){return e>=90?"Exemplary":e>=75?"Commendable":e>=60?"Acceptable":""}function IT(e){let t=Ge.default.join(e,".olympus","config.json");if(Ae.default.existsSync(t))try{let r=JSON.parse(Ae.default.readFileSync(t,"utf-8"))["coverage-thresholds"];if(r)return{critical:r.critical??ms.critical,moderate:r.moderate??ms.moderate,low:r.low??ms.low}}catch(n){}return{...ms}}function OT(e,t,n=""){let r=IT(n);return["critical","moderate","low"].map(o=>{let s=e[o],i=r[o],a=s>=i,c;return a?c="info":t>=3?c="block":t===2?c="warn":c="info",{tier:o,coverage:s,threshold:i,met:a,enforcement:c}})}function $T(e,t,n,r,o,s){let i=e.files,a=i.length,c=a>0?i.reduce((f,m)=>f+(m.lineCoverage??0),0)/a:0,l=a>0?i.reduce((f,m)=>f+(m.branchCoverage??0),0)/a:0,u=a>0?i.reduce((f,m)=>f+(m.functionCoverage??0),0)/a:0,d=[`| Source | ${e.source} |`,`| Total files | ${a} |`,`| Line coverage | ${c.toFixed(1)}% |`,`| Branch coverage | ${l.toFixed(1)}% |`,`| Function coverage | ${u.toFixed(1)}% |`];o&&d.push(`| Quality label | ${o} |`);let p=["# Coverage Report","","## Summary","","| Metric | Value |","|--------|-------|",...d,"","## Threshold Results","","| Tier | Coverage | Threshold | Met | Enforcement |","|------|----------|-----------|-----|-------------|",...n.map(f=>`| ${f.tier} | ${f.coverage.toFixed(1)}% | ${f.threshold}% | ${f.met?"yes":"no"} | ${f.met?"n/a":f.enforcement} |`),""];for(let f of["critical","moderate","low"]){let m=i.filter(_=>s.get(_.filePath)===f&&(_.lineCoverage??0)<100);if(m.length===0)continue;let g=m.slice(0,20),y=m.length>20,w=f.charAt(0).toUpperCase()+f.slice(1);p.push(`## Uncovered Files \u2014 ${w} Tier`,""),y&&p.push(`> Showing top 20 of ${m.length} files. Full list in \`coverage-detail.md\`.`,""),p.push("| File | Line % | Branch % | Function % |"),p.push("|------|--------|----------|------------|");for(let _ of g){let h=_.filePath.length>60?`...${_.filePath.slice(-57)}`:_.filePath;p.push(`| ${h} | ${(_.lineCoverage??0).toFixed(1)}% | ${(_.branchCoverage??0).toFixed(1)}% | ${(_.functionCoverage??0).toFixed(1)}% |`)}p.push("")}return p.join(`
|
|
348
|
+
`)}function DT(e,t){let n=["# Coverage Detail","",`Source: ${e.source}`,"","## All Files","","| File | Tier | Line % | Branch % | Function % |","|------|------|--------|----------|------------|"];for(let r of e.files){let o=t.get(r.filePath)??"low",s=r.filePath.length>70?`...${r.filePath.slice(-67)}`:r.filePath;n.push(`| ${s} | ${o} | ${(r.lineCoverage??0).toFixed(1)}% | ${(r.branchCoverage??0).toFixed(1)}% | ${(r.functionCoverage??0).toFixed(1)}% |`)}return n.push(""),n.join(`
|
|
349
|
+
`)}function Lm(){return async e=>{let t=RT(e.projectPath),n=await PT(e.projectPath,e.unitFiles),r=new Map;for(let h of n.files){let b="";try{await Ae.default.pathExists(h.filePath)&&(b=await Ae.default.readFile(h.filePath,"utf-8"))}catch(S){}r.set(h.filePath,xT(h.filePath,b,t))}let o={critical:[],moderate:[],low:[]};for(let h of n.files){let b=r.get(h.filePath)??"low";o[b].push(h)}function s(h){return h.length===0?100:h.reduce((b,S)=>b+(S.lineCoverage??0),0)/h.length}let i={critical:s(o.critical),moderate:s(o.moderate),low:s(o.low)},a=OT(i,e.workflowDepth,e.projectPath),c=[];for(let h of a)if(!h.met){let b=h.enforcement==="block"?"error":h.enforcement==="warn"?"warning":"info";c.push({id:`coverage-threshold:${h.tier}`,severity:b,category:"coverage-threshold",message:`${h.tier.charAt(0).toUpperCase()+h.tier.slice(1)} tier coverage is ${h.coverage.toFixed(1)}% (threshold: ${h.threshold}%)`})}for(let h of o.critical)(h.lineCoverage??0)===0&&c.push({id:`uncovered-critical:${h.filePath}`,severity:"warning",category:"uncovered-critical-file",message:`Critical-tier file has 0% coverage: ${h.filePath}`,location:{file:h.filePath}});let l=c.some(h=>h.severity==="error"),u=c.some(h=>h.severity==="warning"),d;l?d="failed":u?d="warned":d="passed";let p=n.files,f=p.length>0?p.reduce((h,b)=>h+(b.lineCoverage??0),0)/p.length:100,m=AT(f),g=Ge.default.join(e.projectPath,"aidlc-docs",e.workflowId,"construction",e.unitId,"testing");await Ae.default.ensureDir(g);let y=Ge.default.join(g,"coverage-report.md");await Ae.default.writeFile(y,$T(n,i,a,t,m,r),"utf-8"),(["critical","moderate","low"].some(h=>o[h].filter(b=>(b.lineCoverage??0)<100).length>20)||n.files.length>20)&&await Ae.default.writeFile(Ge.default.join(g,"coverage-detail.md"),DT(n,r),"utf-8");let _={status:d,findings:c,artifactPath:y,coverage_percentage:Math.round(f*10)/10};return e.allowFailures?Ee(_):_}}var Ae,Ge,NT,ms,CT,Um=U(()=>{"use strict";Ae=v(X(),1),Ge=v(require("path"),1);Cn();NT={},ms={critical:80,moderate:60,low:40},CT={critical:["auth","payment","security","encrypt","token","credential","password","session","permission"],moderate:["validate","transform","process","persist","database","query","transaction","migrate","cache"],low:["log","format","display","util","helper","config","constant","mock","fixture"]}});var Wm={};he(Wm,{applyAllowFailures:()=>Ee,calculateNegativeCaseRatio:()=>ds,createContractValidator:()=>Fm,createCoverageValidator:()=>Lm,createMutationValidator:()=>Pm,createQualityValidator:()=>Cm,createTraceabilityValidator:()=>$m,detectAntiPatterns:()=>us,runValidationPipeline:()=>Sm,shouldSkipValidator:()=>vm,updateCheckpointForValidator:()=>bm});var Bm=U(()=>{"use strict";Cn();Rm();Am();Dm();Na();Mm();Um()});var Qm={};he(Qm,{appendOlympusSection:()=>Jm,categorizeChanges:()=>qm,createNewChangelog:()=>zm,detectExistingChangelogTool:()=>Gm,formatChangelogEntry:()=>Vm,generateChangelogEntry:()=>jT,isKeepAChangelogFormat:()=>Ym,prependToChangelog:()=>Km,readFeatureDocSummaries:()=>Hm});function Gm(e){let t=[{files:[".versionrc",".versionrc.json",".versionrc.js"],tool:"conventional-changelog"},{files:[".changeset"],tool:"changesets"},{files:["cliff.toml"],tool:"git-cliff"}];for(let{files:n,tool:r}of t)for(let o of n){let s=Qr.join(e,o);if(je.existsSync(s))return r}return null}function Hm(e,t){let n=[];for(let r of t){let o=Qr.join(e,"construction",r,"documentation","feature-doc.md");if(!je.existsSync(o))continue;let i=je.readFileSync(o,"utf-8").match(/## Summary\n\n([\s\S]*?)(?=\n## |\n---|\Z)/);i&&i[1].trim()&&n.push({unitId:r,summary:i[1].trim()})}return n}function qm(e,t){let n={added:[],changed:[],fixed:[]};for(let{summary:r}of e){let o=r.split(`
|
|
350
|
+
`)[0].trim();o&&(t==="bugfix"?n.fixed.push(o):/(?:add|create|implement|introduce|new)/i.test(o)?n.added.push(o):/(?:fix|repair|resolve|patch|correct)/i.test(o)?n.fixed.push(o):/(?:update|change|modify|refactor|improve|enhance)/i.test(o)?n.changed.push(o):n.added.push(o))}return n}function Vm(e,t,n){let r=[`## [${e}] - ${t}`,""];if(n.added.length>0){r.push("### Added","");for(let o of n.added)r.push(`- ${o}`);r.push("")}if(n.changed.length>0){r.push("### Changed","");for(let o of n.changed)r.push(`- ${o}`);r.push("")}if(n.fixed.length>0){r.push("### Fixed","");for(let o of n.fixed)r.push(`- ${o}`);r.push("")}return r.join(`
|
|
351
|
+
`)}function Ym(e){return/^# (?:Changelog|Change\s*Log)/im.test(e)||/^## \[/m.test(e)}function Km(e,t){let n=je.readFileSync(e,"utf-8"),r=n.match(/^## \[/m);if(r&&r.index!==void 0){let o=n.substring(0,r.index),s=n.substring(r.index);je.writeFileSync(e,o+t+`
|
|
352
|
+
`+s)}else je.writeFileSync(e,n+`
|
|
353
|
+
`+t)}function Jm(e,t){let n=je.readFileSync(e,"utf-8"),r=["","<!-- Olympus AI-DLC Generated -->",t,"<!-- End Olympus AI-DLC Generated -->",""].join(`
|
|
354
|
+
`);je.writeFileSync(e,n+r)}function zm(e,t){let n=["# Changelog","","All notable changes to this project will be documented in this file.","","The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).",""].join(`
|
|
355
|
+
`);je.writeFileSync(e,n+t)}function jT(e){let t=Gm(e.projectPath);if(t)return{status:"skipped",path:null,entriesAdded:0,skipReason:`Changelog managed by ${t}`};let n=Qr.join(e.projectPath,"aidlc-docs",e.workflowId),r=Hm(n,e.unitIds);if(r.length===0)return{status:"skipped",path:null,entriesAdded:0,skipReason:"No feature doc summaries found"};let o=qm(r,e.pathway),s=new Date().toISOString().split("T")[0],i=Vm(e.workflowId,s,o),a=Qr.join(e.projectPath,"CHANGELOG.md");if(je.existsSync(a)){let l=je.readFileSync(a,"utf-8");Ym(l)?Km(a,i):Jm(a,i)}else zm(a,i);let c=o.added.length+o.changed.length+o.fixed.length;return{status:"completed",path:a,entriesAdded:c}}var je,Qr,Xm=U(()=>{"use strict";je=v(require("fs"),1),Qr=v(require("path"),1)});async function Zm(e,t,n){let r=ir.default.join(e,"aidlc-docs",t,"inception","requirements","nfr.md"),o=ir.default.join(e,"aidlc-docs",t,"construction",n,"spec.md"),s=ir.default.join(e,"aidlc-docs",t,"construction",n,"nfr-requirements.md"),i="";try{await Pn.default.pathExists(r)&&(i=await Pn.default.readFile(r,"utf-8"))}catch{}let a="";try{await Pn.default.pathExists(o)&&(a=await Pn.default.readFile(o,"utf-8"))}catch{}let c=a.match(/^title:\s*(.+)$/m),l=c?c[1].trim().replace(/^["']|["']$/g,""):n,u=FT(i,a,l),d=new Date().toISOString(),p=`---
|
|
356
356
|
id: ${n}-nfr-requirements
|
|
357
357
|
parent_unit: ${n}
|
|
358
358
|
generated_at: ${d}
|
|
@@ -369,8 +369,8 @@ ${u||"_No specific NFRs identified for this unit. Inherit project-level defaults
|
|
|
369
369
|
|
|
370
370
|
## Unit Context
|
|
371
371
|
${l}
|
|
372
|
-
`;await
|
|
373
|
-
`)}function
|
|
372
|
+
`;await Pn.default.ensureDir(ir.default.dirname(s)),await Pn.default.writeFile(s,p,"utf-8");try{let f=ir.default.join(e,"aidlc-docs",t,"manifest.json");$e(f,{id:`${n}-nfr-requirements`,type:"NFR_REQUIREMENTS",phase:"construction",stage:"unit",path:s,validation_passed:null,write_complete:!0,checksum:null})}catch(f){console.error(`[NFRRequirements] Failed to register artifact for ${n}:`,f)}return{artifactPath:s,nfrContent:u}}function FT(e,t,n){if(!e.trim())return"";let r=e.split(/(?=^## )/m).filter(a=>a.trim());if(r.length===0)return e;let o=MT(t+" "+n);if(o.length===0)return e;let i=r.map(a=>{let c=a.toLowerCase(),l=o.filter(u=>c.includes(u)).length;return{section:a,score:l}}).filter(a=>a.score>0);return i.length===0?e:i.map(a=>a.section).join(`
|
|
373
|
+
`)}function MT(e){let t=new Set(["the","a","an","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","shall","can","need","must","ought","and","or","but","if","then","else","when","at","from","by","on","off","for","in","out","over","to","into","with","not","no","nor","as","of","this","that","these","those","it","its","all","each","any","both","few","more","most","other","some","such","than","too","very"]);return e.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(n=>n.length>3&&!t.has(n)).filter((n,r,o)=>o.indexOf(n)===r).slice(0,30)}var Pn,ir,eg=U(()=>{"use strict";Pn=v(X(),1),ir=v(require("path"),1);Z()});var tg={};he(tg,{UnitStageRunner:()=>Fa});var Fe,Bt,LT,Fa,ng=U(()=>{"use strict";Fe=v(X(),1),Bt=v(require("path"),1);eg();LT={SHALLOW:[],MEDIUM:["functional-design","nfr-requirements"],DEEP:["functional-design","nfr-requirements","nfr-design","infrastructure-design"]},Fa=class{projectPath;workflowId;constructor(t,n){this.projectPath=t,this.workflowId=n}async executeForUnit(t,n,r,o,s){let i=LT[n],a=Bt.default.join(this.projectPath,"aidlc-docs",this.workflowId,"construction",t),c=["functional-design","nfr-requirements","nfr-design","infrastructure-design","code-generation","test-generation"],l={unitId:t,stages:{},code_plan_path:null,code_generation_status:"not_started"};for(let d of c)l.stages[d]={status:i.includes(d)?"not_started":"skipped",artifact_path:null,completed_at:null,failure_count:0,last_error:null};if(i.length===0)return console.log(`[UnitStageRunner] SHALLOW depth: skipping all design stages for ${t}`),l;console.log(`[UnitStageRunner] Running ${i.length} design stages for ${t} (${n})`);let u="";try{let d=Bt.default.join(a,"spec.md");await Fe.default.pathExists(d)&&(u=await Fe.default.readFile(d,"utf-8"))}catch{}for(let d of i){l.stages[d].status="in_progress";try{let p=await this.executeStage(d,t,a,u,r,o);if(l.stages[d].status="completed",l.stages[d].artifact_path=p,l.stages[d].completed_at=new Date().toISOString(),console.log(`[UnitStageRunner] ${t}/${d} completed -> ${p}`),s)try{await s(t,l)}catch{}}catch(p){if(l.stages[d].failure_count+=1,l.stages[d].last_error=p instanceof Error?p.message:String(p),l.stages[d].failure_count>=2){if(l.stages[d].status="failed",console.error(`[UnitStageRunner] ${t}/${d} failed after ${l.stages[d].failure_count} attempts \u2014 escalating`),s)try{await s(t,l)}catch{}break}else l.stages[d].status="not_started",console.warn(`[UnitStageRunner] ${t}/${d} failed (attempt ${l.stages[d].failure_count}/2), will retry`)}}return await this.appendAudit(t,i,l),l}async executeStage(t,n,r,o,s,i){switch(await Fe.default.ensureDir(r),t){case"functional-design":{let a=Bt.default.join(r,"functional-design.md"),c=this.buildFunctionalDesignContent(n,o,s);return await Fe.default.writeFile(a,c,"utf-8"),a}case"nfr-requirements":return(await Zm(this.projectPath,this.workflowId,n)).artifactPath;case"nfr-design":{let a=Bt.default.join(r,"nfr-design.md"),c=Bt.default.join(r,"nfr-requirements.md"),l=i||"";try{await Fe.default.pathExists(c)&&(l=await Fe.default.readFile(c,"utf-8"))}catch{}let u=this.buildNFRDesignContent(n,o,l);return await Fe.default.writeFile(a,u,"utf-8"),a}case"infrastructure-design":{let a=Bt.default.join(r,"infrastructure-design.md"),c=Bt.default.join(r,"nfr-design.md"),l="";try{await Fe.default.pathExists(c)&&(l=await Fe.default.readFile(c,"utf-8"))}catch{}let u=this.buildInfrastructureDesignContent(n,o,l);return await Fe.default.writeFile(a,u,"utf-8"),a}default:throw new Error(`Stage '${t}' not handled by UnitStageRunner`)}}buildFunctionalDesignContent(t,n,r){let o=n.match(/^title:\s*(.+)$/m),s=o?o[1].trim().replace(/^["']|["']$/g,""):t,i=new Date().toISOString();return`---
|
|
374
374
|
id: ${t}-functional-design
|
|
375
375
|
parent_unit: ${t}
|
|
376
376
|
stage: functional-design
|
|
@@ -427,17 +427,17 @@ Infrastructure resource mapping for this unit.
|
|
|
427
427
|
|
|
428
428
|
## Deployment Architecture
|
|
429
429
|
Deployment topology and environment configuration.
|
|
430
|
-
`}extractSection(t,n){try{let r=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`##\\s+${r}\\s*\\n([\\s\\S]*?)(?=\\n##|$)`,"i").exec(t);return o?o[1].trim():""}catch{return""}}async appendAudit(t,n,r){try{let o=
|
|
430
|
+
`}extractSection(t,n){try{let r=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`##\\s+${r}\\s*\\n([\\s\\S]*?)(?=\\n##|$)`,"i").exec(t);return o?o[1].trim():""}catch{return""}}async appendAudit(t,n,r){try{let o=Bt.default.join(this.projectPath,"aidlc-docs",this.workflowId,"audit.md"),s=new Date().toISOString(),i=n.filter(c=>r.stages[c]?.status==="completed"),a=`
|
|
431
431
|
## ${t} Design Stages \u2014 ${s}
|
|
432
432
|
|
|
433
433
|
`+i.map(c=>`- [x] ${c}: ${r.stages[c].artifact_path}`).join(`
|
|
434
434
|
`)+`
|
|
435
|
-
`;await
|
|
436
|
-
${a}`,"utf-8")}catch(o){console.error(`[UnitStageRunner] Failed to update audit for ${t}:`,o)}}}});function
|
|
437
|
-
`)}function
|
|
435
|
+
`;await Fe.default.pathExists(o)?await Fe.default.appendFile(o,a,"utf-8"):await Fe.default.writeFile(o,`# Audit Trail
|
|
436
|
+
${a}`,"utf-8")}catch(o){console.error(`[UnitStageRunner] Failed to update audit for ${t}:`,o)}}}});function iC(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function aC(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 cC(e){let{inception_stages:t,current_inception_stage:n}=e;if(!t)return[];let r=[];for(let o of sC){let s=t[o];if(!s)continue;let i=iC(o),a=n===o,c,l;s.status==="completed"?(c="[x]",l=s.completed_at?`(completed ${s.completed_at})`:"(completed)"):s.status==="skipped"?(c="[ ]",l=s.skip_reason?`(skipped -- ${s.skip_reason})`:"(skipped)"):(c="[ ]",l="");let u=` - ${c} ${i} ${l}`.trimEnd();a&&(u+=" <- CURRENT"),r.push(u)}return r}function lC(e){let t=["## Progress"];for(let n of oC){let r=e.phases[n],o,s;r?.completed_at?(o="[x]",s=`(completed ${r.completed_at})`):e.current_phase===n?(o="[ ]",s="(in progress)"):(o="[ ]",s="");let i=n.charAt(0).toUpperCase()+n.slice(1);if(t.push(`- ${o} ${i} ${s}`.trimEnd()),n==="inception"&&e.inception_stages){let a=cC(e);t.push(...a)}}return t.join(`
|
|
437
|
+
`)}function uC(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(`
|
|
438
438
|
`);t.push(""),t.push("| Unit | Status |"),t.push("|------|--------|");for(let[n,r]of Object.entries(e.construction_units)){let o=r.code_generation_status;r.recreation_readiness_score!=null&&r.recreation_readiness_score>0&&(o+=` | Readiness: ${r.recreation_readiness_score}/5.0`),t.push(`| ${n} | ${o} |`)}return t.join(`
|
|
439
|
-
`)}function
|
|
440
|
-
`)}function
|
|
439
|
+
`)}function dC(e,t){let n=["## Key Artifacts",""];n.push("| Artifact | Path | Status |"),n.push("|----------|------|--------|");let r=lr.join(e,Xr,t),o=[{name:"Intent Analysis",path:"inception/intent.md"},{name:"Requirements",path:"inception/requirements/requirements.md"},{name:"NFR",path:"inception/requirements/nfr.md"},{name:"User Stories",path:"inception/user-stories/stories.md"},{name:"Personas",path:"inception/user-stories/personas.md"},{name:"Workflow Plan",path:"inception/workflow-plan.md"},{name:"Unit Definitions",path:"inception/units/unit-of-work.md"},{name:"Dependency Matrix",path:"inception/units/unit-of-work-dependency.md"}];for(let s of o){let i=Gt.existsSync(lr.join(r,s.path));n.push(`| ${s.name} | ${s.path} | ${i?"created":"pending"} |`)}return n.join(`
|
|
440
|
+
`)}function Ua(e,t,n){let r=lr.join(e,Xr,t,cg);try{let o=aC(n.feature_name),s=lC(n),i=uC(n),a=dC(e,t),c=`# ${o}
|
|
441
441
|
|
|
442
442
|
| Field | Value |
|
|
443
443
|
|-------|-------|
|
|
@@ -464,8 +464,8 @@ ${a}
|
|
|
464
464
|
## Code Location
|
|
465
465
|
|
|
466
466
|
Application Code: ${e} (NEVER in aidlc-docs/)
|
|
467
|
-
Documentation: ${
|
|
468
|
-
`;
|
|
467
|
+
Documentation: ${Xr}/${t}/
|
|
468
|
+
`;Gt.ensureDirSync(lr.join(e,Xr,t)),Gt.writeFileSync(r,c,"utf-8")}catch(o){console.error(`[StateFile] Failed to generate state file for workflow ${t}:`,o.message)}return r}function ws(e,t,n,r){let o=lr.join(e,Xr,t,cg);try{let s=Gt.readFileSync(o,"utf-8"),i=new RegExp(`^(- \\[[ x\\-]\\] ${n}.*)$`,"im"),a=s;r==="completed"?a=a.replace(i,(u,d)=>`${d.replace(/\[[ x\-]\]/,"[x]").replace(/\s*\(.*?\)\s*$/,"").replace(/\s*← CURRENT\s*$/,"")} (completed ${new Date().toISOString()})`):r==="in_progress"?a=a.replace(i,(u,d)=>`${d.replace(/\[[ x\-]\]/,"[ ]").replace(/\s*\(.*?\)\s*$/,"").replace(/\s*← CURRENT\s*$/,"")} \u2190 CURRENT`):r==="skipped"&&(a=a.replace(i,(u,d)=>`${d.replace(/\[[ x\-]\]/,"[-]").replace(/\s*\(.*?\)\s*$/,"").replace(/\s*← CURRENT\s*$/,"")} (skipped)`));let c=/\| \*\*Last Updated\*\* \| .+? \|/,l=/^\*\*Last Updated\*\*: .+$/m;c.test(a)?a=a.replace(c,`| **Last Updated** | ${new Date().toISOString()} |`):a=a.replace(l,`**Last Updated**: ${new Date().toISOString()}`),Gt.writeFileSync(o,a,"utf-8")}catch(s){console.error(`[StateFile] Failed to update state file for workflow ${t}:`,s.message)}}var lr,Gt,Xr,cg,oC,sC,Wa=U(()=>{"use strict";lr=v(require("path"),1),Gt=v(X(),1),Xr="aidlc-docs",cg="aidlc-state.md",oC=["discovery","inception","construction","operations"],sC=["workspace-detection","reverse-engineering","requirements-analysis","workflow-planning","units-generation","user-stories","bolt-planning"]});var mg={};he(mg,{InceptionOrchestrator:()=>qa,registerStageHandler:()=>pC});function pC(e,t){Ha[e]=t}function lg(e,t,n=null){return{stage:e,status:t,started_at:null,completed_at:null,skip_reason:n,artifacts_generated:[],questions_file:null,answers_received:!1}}function Ba(e,t,n){return n&&!Ia(n,"inception",e)?{status:"skipped",skipReason:"Excluded by workflow routing plan"}:t==="greenfield"&&e==="reverse-engineering"?{status:"skipped",skipReason:"Greenfield project \u2014 no existing codebase to reverse-engineer"}:(t==="bugfix"||t==="optimization")&&e==="user-stories"?{status:"skipped",skipReason:`${t} pathway does not require ${e}`}:{status:"not_started",skipReason:null}}function ug(e){for(let t of xt){let n=e[t];if(n&&(n.status==="not_started"||n.status==="in_progress"))return t}return null}function fC(e,t){let n=xt.indexOf(e);for(let r=n+1;r<xt.length;r++){let o=xt[r],s=t[o];if(s&&(s.status==="not_started"||s.status==="in_progress"))return o}}async function mC(e,t,n){if(!n.trust_state_path)return 0;try{let r=(0,fg.join)(e,"aidlc-docs",t,n.trust_state_path),o=await pg.readFile(r,"utf-8");return JSON.parse(o).current_level??0}catch{return 0}}function gC(e,t,n){let r=e==="workspace-detection",o=t.status==="awaiting_answers";return!(n>=3||n>=2&&!o||n>=1&&r&&!o)}function dg(e){return xt.every(t=>{let n=e[t];return n&&(n.status==="completed"||n.status==="skipped")})}function hC(e){let t=e.phases?.discovery;if(!t)return!1;let n=t.status;return n==="complete"||n==="completed"}function Ga(e,t=null){let n=t!==null,r=new Date().toISOString();return{stage:e,status:n?"skipped":"completed",started_at:n?null:r,completed_at:r,skip_reason:t,artifacts_generated:[],questions_file:null,answers_received:!1}}var pg,fg,Ha,xt,qa,gg=U(()=>{"use strict";pg=v(X(),1),fg=require("path");ce();Wa();ga();as();Ha={};xt=["workspace-detection","reverse-engineering","requirements-analysis","workflow-planning","units-generation","user-stories","bolt-planning"];qa=class{async migrateCheckpoint(t,n){let r=await A(t,n);if(!r)throw new Error(`[InceptionOrchestrator] Checkpoint not found for workflow ${n}`);if(r.inception_stages)return{migrated:!1,case:"no_migration_needed"};let o=r.pathway_type??"brownfield-enhancement";if(r.current_stage!=="intent"){let a={};for(let c of xt){let{skipReason:l}=Ba(c,o,null);a[c]=Ga(c,l)}return r.inception_stages=a,r.current_inception_stage=void 0,await P(t,r),Dt(t,n),{migrated:!0,case:"already_past_inception"}}let s={};for(let a of xt){let{status:c,skipReason:l}=Ba(a,o,null);s[a]=lg(a,c,l)}s["workspace-detection"].status!=="skipped"&&(s["workspace-detection"]=Ga("workspace-detection")),s["reverse-engineering"].status!=="skipped"&&hC(r)&&(s["reverse-engineering"]=Ga("reverse-engineering")),r.inception_stages=s;let i=ug(s);return r.current_inception_stage=i??void 0,await P(t,r),Dt(t,n),{migrated:!0,case:"paused_at_intent"}}async initialize(t,n,r,o){let s=await A(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 xt){let{status:l,skipReason:u}=Ba(c,r,o);i[c]=lg(c,l,u),!a&&l==="not_started"&&(a=c)}s.inception_stages=i,s.current_inception_stage=a??void 0,await P(t,s),Dt(t,n)}async executeNextStage(t,n){let r=await A(t,n);if(!r)throw new Error(`[InceptionOrchestrator] Checkpoint not found for workflow ${n}`);let o=r.inception_stages;if(!o)throw new Error(`[InceptionOrchestrator] inception_stages not initialized for workflow ${n}. Call initialize() first.`);let s=ug(o);if(!s)return{stage:"units-generation",status:"completed",requires_approval:!1,artifacts_generated:[],whats_next:"Inception is complete. Proceed to construction phase."};o[s].status="in_progress",o[s].started_at=new Date().toISOString(),r.current_inception_stage=s,await P(t,r),Dt(t,n);let i=Ha[s],a;if(i)try{a=await i(t,n,r)}catch(c){let l=c;console.error(`[InceptionOrchestrator] Stage '${s}' handler threw:`,l.message);let u=await A(t,n);return u?.inception_stages&&(u.inception_stages[s].status="not_started",u.inception_stages[s].started_at=null,await P(t,u),Dt(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 has no registered handler \u2014 skipping to next stage."};return await this._postStage(t,n,s,a),a}async processAnswers(t,n,r){let o=await A(t,n);if(!o)throw new Error(`[InceptionOrchestrator] Checkpoint not found for workflow ${n}`);let s=o.inception_stages;if(!s)throw new Error(`[InceptionOrchestrator] inception_stages not initialized for workflow ${n}`);let i=s[r];if(!i||i.status!=="in_progress")throw new Error(`[InceptionOrchestrator] Stage '${r}' is not in_progress (status: ${i?.status??"unknown"})`);let a=Ha[r],c;if(a)try{c=await a(t,n,o)}catch(l){let u=l;return console.error(`[InceptionOrchestrator] processAnswers for '${r}' threw:`,u.message),{stage:r,status:"review_required",requires_approval:!0,artifacts_generated:[],review_summary:`Stage '${r}' answer processing failed: ${u.message}`}}else c={stage:r,status:"completed",requires_approval:!0,artifacts_generated:[],review_summary:`Stage '${r}' has no handler registered yet.`,whats_next:"This stage has no registered handler \u2014 skipping to next stage."};return await this._postStage(t,n,r,c),c}async getProgress(t,n){let r=await A(t,n);if(!r)throw new Error(`[InceptionOrchestrator] Checkpoint not found for workflow ${n}`);let o=r.inception_stages??{},s=xt.length,i=0,a=0;for(let c of xt){let l=o[c];l&&(l.status==="completed"&&i++,l.status==="skipped"&&a++)}return{total_stages:s,completed_stages:i,skipped_stages:a,current_stage:r.current_inception_stage??null,stages:o}}async isComplete(t,n){let r=await A(t,n);return r?.inception_stages?dg(r.inception_stages):!1}async _postStage(t,n,r,o){let s=await A(t,n);if(!s?.inception_stages)return;let i=s.inception_stages,a=new Date().toISOString();o.status==="completed"?(i[r].status="completed",i[r].completed_at=a,i[r].artifacts_generated=o.artifacts_generated):o.status==="awaiting_answers"?(i[r].status="in_progress",i[r].questions_file=o.questions_file??null):o.status==="skipped"&&(i[r].status="skipped",i[r].completed_at=a),(o.status==="completed"||o.status==="skipped")&&(s.current_inception_stage=fC(r,i)),await P(t,s),Dt(t,n);try{o.status==="completed"?ws(t,n,r,"completed"):o.status==="awaiting_answers"?ws(t,n,r,"in_progress"):o.status==="skipped"&&ws(t,n,r,"skipped")}catch(u){console.error(`[InceptionOrchestrator] Failed to update state file for stage ${r}:`,u.message)}try{let u={timestamp:a,phase:"inception",action:`Stage '${r}' ${o.status}`,actor:"ai",reason:o.review_summary??null};Ko(t,n,u)}catch(u){console.error(`[InceptionOrchestrator] Failed to append to audit for stage ${r}:`,u.message)}if(dg(i))try{let u=Sf(t,n);ma(u),await vf(t,n,u)}catch(u){console.error("[InceptionOrchestrator] Failed to generate final audit document:",u.message)}try{let u=await mC(t,n,s);o.requires_approval=gC(r,o,u)}catch(u){console.error("[InceptionOrchestrator] Failed to compute trust level:",u.message),o.requires_approval=!0}let l=await A(t,n);l?.current_inception_stage&&(o.next_stage=l.current_inception_stage)}}});var Sg={};he(Sg,{generateCostAnalysis:()=>kg,generateDeployGuide:()=>hg,generateMonitoringConfig:()=>wg,generateOperationsArtifacts:()=>yC,generateReleaseNotes:()=>_g,generateRunbook:()=>yg});function hg(e){let{featureName:t,workflowId:n,manifest:r}=e,o=new Date().toISOString(),s=r?.artifacts?.length??0,i=r?.artifacts?.filter(c=>c.phase==="inception").length??0,a=r?.artifacts?.filter(c=>c.phase==="construction").length??0;return`---
|
|
469
469
|
id: DEPLOY-GUIDE-001
|
|
470
470
|
feature: ${n}
|
|
471
471
|
created: ${o}
|
|
@@ -531,7 +531,7 @@ Generated from ${s} artifacts (${i} Inception, ${a} Construction).
|
|
|
531
531
|
|
|
532
532
|
---
|
|
533
533
|
*Generated by Operations Phase Templates*
|
|
534
|
-
`}function
|
|
534
|
+
`}function yg(e){let{featureName:t,workflowId:n}=e,r=new Date().toISOString();return`---
|
|
535
535
|
id: RUNBOOK-001
|
|
536
536
|
feature: ${n}
|
|
537
537
|
created: ${r}
|
|
@@ -615,7 +615,7 @@ grep -i error /var/log/service/${n}.log | tail -20
|
|
|
615
615
|
|
|
616
616
|
---
|
|
617
617
|
*Generated by Operations Phase Templates*
|
|
618
|
-
`}function
|
|
618
|
+
`}function wg(e){let{featureName:t,workflowId:n,manifest:r}=e,o=new Date().toISOString(),s=r?.risk_tier?.tier??2,i=s===3?.5:s===2?1:2,a=s===3?500:s===2?1e3:2e3,l={id:"MONITORING-001",feature:n,feature_name:t,created:o,phase:"operations",stage:"monitor",risk_tier:s,health_checks:{endpoint:"/health",interval_seconds:s===3?30:s===2?60:120,timeout_seconds:5,unhealthy_threshold:3},alerts:[{name:`${n}-error-rate`,metric:"error_rate_percent",threshold:i,window_seconds:300,severity:"critical",notification_channels:["pagerduty","slack"]},{name:`${n}-latency-p99`,metric:"latency_p99_ms",threshold:a,window_seconds:300,severity:"warning",notification_channels:["slack"]},{name:`${n}-availability`,metric:"availability_percent",threshold:99.9,comparison:"less_than",window_seconds:3600,severity:"critical",notification_channels:["pagerduty","slack"]}],dashboards:{overview:{panels:[{title:"Request Rate",metric:"request_rate",type:"timeseries"},{title:"Error Rate",metric:"error_rate_percent",type:"timeseries"},{title:"Latency (p50/p95/p99)",metric:"latency_percentiles",type:"timeseries"},{title:"Availability",metric:"availability_percent",type:"stat"}]}},logging:{level:s===3?"debug":"info",retention_days:s===3?90:s===2?60:30,structured:!0}};return JSON.stringify(l,null,2)}function _g(e){let{featureName:t,workflowId:n,manifest:r}=e,o=new Date().toISOString(),s=r?.artifacts??[],i=s.filter(m=>m.phase==="inception"),a=s.filter(m=>m.phase==="construction"),c=r?.risks??[],l=c.filter(m=>m.status==="open"),u=c.filter(m=>m.status==="mitigated"),p=(r?.gate_audit??[]).filter(m=>m.action==="approved"),f=s.map(m=>`- **${m.id}** (${m.phase}/${m.stage}): ${m.contract_status}`).join(`
|
|
619
619
|
`);return`---
|
|
620
620
|
id: RELEASE-NOTES-001
|
|
621
621
|
feature: ${n}
|
|
@@ -681,7 +681,7 @@ This is a new feature deployment. No migration from previous versions required.
|
|
|
681
681
|
|
|
682
682
|
---
|
|
683
683
|
*Generated by Operations Phase Templates*
|
|
684
|
-
`}function
|
|
684
|
+
`}function kg(e){let{featureName:t,workflowId:n,manifest:r}=e,o=new Date().toISOString(),s=r?.artifacts??[],i=s.filter(d=>d.stage==="code-generation"),a=s.filter(d=>d.stage==="unit"),l=(r?.gate_audit??[]).filter(d=>d.action==="rejected"),u=r?.metrics??null;return`---
|
|
685
685
|
id: COST-001
|
|
686
686
|
feature: ${n}
|
|
687
687
|
created: ${o}
|
|
@@ -728,27 +728,27 @@ ${l.length>2?"- High rejection rate suggests specification clarity could be impr
|
|
|
728
728
|
|
|
729
729
|
---
|
|
730
730
|
*Generated by Operations Phase Templates*
|
|
731
|
-
`}async function
|
|
732
|
-
`)){let a=i.indexOf(":");if(a===-1)continue;let c=i.slice(0,a).trim(),l=i.slice(a+1).trim();(l.startsWith('"')&&l.endsWith('"')||l.startsWith("'")&&l.endsWith("'"))&&(l=l.slice(1,-1)),s[c]=l}return{data:s,body:o}}function
|
|
731
|
+
`}async function yC(e,t){let n=An.join(t,"aidlc-docs",e.workflowId,"operations");await an.ensureDir(n);let r=[],o=e.depthLevel||"MEDIUM";return await an.writeFile(An.join(n,"release-notes.md"),_g(e),"utf-8"),r.push("release-notes.md"),o==="SHALLOW"?{artifactsGenerated:r,operationsDir:n}:(await an.writeFile(An.join(n,"deploy-guide.md"),hg(e),"utf-8"),r.push("deploy-guide.md"),await an.writeFile(An.join(n,"runbook.md"),yg(e),"utf-8"),r.push("runbook.md"),await an.writeFile(An.join(n,"monitoring.json"),wg(e),"utf-8"),r.push("monitoring.json"),await an.writeFile(An.join(n,"cost.md"),kg(e),"utf-8"),r.push("cost.md"),{artifactsGenerated:r,operationsDir:n})}var an,An,vg=U(()=>{"use strict";an=v(X(),1),An=v(require("path"),1)});var Qy={};he(Qy,{formatSessionSummaryLine:()=>Rx});function Rx(e){let t;e.agents_used.length===0?t="(none)":e.agents_used.length<=4?t=e.agents_used.join(", "):t=e.agents_used.slice(0,3).join(", ")+", ...";let n=e.duration_seconds,r=Math.floor(n/60),o=n%60,s;r>0?s=`${r}m ${o}s`:s=`${o}s`;let i=e.total_tokens.toLocaleString("en-US"),a=`$${e.estimated_cost.toFixed(e.estimated_cost>=.01?2:3)}`,c=e.agents_used.length,u=`[Olympus] Session: ${c} ${c===1?"agent":"agents"} (${t}) | ${i} tokens | ${a} | ${s}`;return u.length>200&&(u=u.substring(0,197)+"..."),u}var Xy=U(()=>{"use strict"});function iw(e){if(!e)return[];let t=e.toLowerCase(),n=[];for(let[r,o]of Object.entries(Px))for(let s of o)if(t.includes(s)){n.push(r);break}return n}var Px,aw=U(()=>{"use strict";Px={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 uw={};he(uw,{COLD_START_FALLBACK_RATE:()=>ol,getRoutingRecommendation:()=>$x});function Ax(){let e=(0,lw.join)(pe(),"routing-config.json"),t=we(e,null);if(t)return t;try{st(e,cw)}catch{}return cw}function Ix(e,t){for(let[n,r]of Object.entries(t)){let o=r.indexOf(e);if(o>=0)return{family:n,tierList:r,index:o}}return null}function Ox(e,t){return!e||t===0?ol:t*e.success_rate+(1-t)*ol}function $x(e,t,n){try{let r=Ax();if(!r.preferLowerTier)return null;let o=Ix(e,r.agentTiers);if(!o||o.index===0)return null;let s=Gn(n),i=o.tierList.slice(0,o.index);for(let a of i){let c=s[a],l=c?.total_invocations??0,u=Math.min(1,l/5),d=Ox(c,u);if(d<r.minSuccessRate||u>=1&&l<r.minDataPoints)continue;let p="";if(c?.task_patterns&&c.task_patterns.length>0){let g=iw(t);for(let y of c.task_patterns)if(g.includes(y.pattern)&&y.successfulAgents.includes(a)&&y.confidence>=.7){p=` (especially for ${y.pattern.replace(/_/g," ")} tasks)`;break}}let f=(d*100).toFixed(0);return`Based on ${l} data points, ${a} handles this type of task with ${f}% success rate${p}. Consider using ${a} instead of ${e} to save tokens.`}return null}catch{return null}}var lw,ol,cw,dw=U(()=>{"use strict";lw=require("path");ye();aw();ol=.5,cw={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 wA={};he(wA,{main:()=>y_});module.exports=R_(wA);var ai=new Map;function I(e){let t=ai.get(e.event)||[];t.push(e),t.sort((n,r)=>(n.priority??100)-(r.priority??100)),ai.set(e.event,t)}function vl(e){return ai.get(e)||[]}var x_={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},P_=["ultrawork","ultrathink","olympus","search","analyze"];function bl(e){let t=e.replace(/```[\s\S]*?```/g,"");return t=t.replace(/~~~[\s\S]*?~~~/g,""),t=t.replace(/`[^`]+`/g,""),t}function El(e,t){let n=[];for(let r of P_){let o=x_[r],s=e.match(o);s&&s.index!==void 0&&n.push({type:r,keyword:s[0],position:s.index})}return n}var Tl="auto-slash-command",ko="<auto-slash-command>",So="</auto-slash-command>",Cl=/^\/([a-zA-Z][\w-]*)\s*(.*)/,Rl=new Set(["ascent","cancel-ascent","help","clear","history","exit","quit"]);var A_=/```[\s\S]*?```/g;function xl(e){return e.replace(A_,"")}function Pl(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.match(Cl);if(!n)return null;let[r,o,s]=n;return{command:o.toLowerCase(),args:s.trim(),raw:r}}function Al(e){return Rl.has(e.toLowerCase())}function ci(e){let n=xl(e).trim();if(!n.startsWith("/"))return null;let r=Pl(n);return!r||Al(r.command)?null:r}function li(e){return e.filter(t=>t.type==="text").map(t=>t.text||"").join(" ")}var gt=require("fs"),It=require("path"),$l=require("os"),Il=(0,It.join)((0,$l.homedir)(),".claude");function Dl(e){let t=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,n=e.match(t);if(!n)return{data:{},body:e};let[,r,o]=n,s={};for(let i of r.split(`
|
|
732
|
+
`)){let a=i.indexOf(":");if(a===-1)continue;let c=i.slice(0,a).trim(),l=i.slice(a+1).trim();(l.startsWith('"')&&l.endsWith('"')||l.startsWith("'")&&l.endsWith("'"))&&(l=l.slice(1,-1)),s[c]=l}return{data:s,body:o}}function Ol(e,t){if(!(0,gt.existsSync)(e))return[];let n;try{n=(0,gt.readdirSync)(e,{withFileTypes:!0})}catch{return[]}let r=[];for(let o of n){if(!o.isFile()||!o.name.endsWith(".md"))continue;let s=(0,It.join)(e,o.name),i=(0,It.basename)(o.name,".md");try{let a=(0,gt.readFileSync)(s,"utf-8"),{data:c,body:l}=Dl(a),u={name:i,description:c.description||"",argumentHint:c["argument-hint"],model:c.model,agent:c.agent};r.push({name:i,path:s,metadata:u,content:l,scope:t})}catch{continue}}return r}function ui(){let e=(0,It.join)(Il,"commands"),t=(0,It.join)(process.cwd(),".claude","commands"),n=(0,It.join)(Il,"skills"),r=Ol(e,"user"),o=Ol(t,"project"),s=[];if((0,gt.existsSync)(n))try{let i=(0,gt.readdirSync)(n,{withFileTypes:!0});for(let a of i){if(!a.isDirectory())continue;let c=(0,It.join)(n,a.name,"SKILL.md");if((0,gt.existsSync)(c))try{let l=(0,gt.readFileSync)(c,"utf-8"),{data:u,body:d}=Dl(l),p={name:u.name||a.name,description:u.description||"",argumentHint:u["argument-hint"],model:u.model,agent:u.agent};s.push({name:u.name||a.name,path:c,metadata:p,content:d,scope:"skill"})}catch{continue}}}catch{}return[...o,...r,...s]}function vo(e){return ui().find(n=>n.name.toLowerCase()===e.toLowerCase())??null}function I_(e,t){return e.replace(/\$ARGUMENTS/g,t||"(no arguments provided)")}function O_(e,t){let n=[];n.push(`<command-name>/${e.name}</command-name>
|
|
733
733
|
`),e.metadata.description&&n.push(`**Description**: ${e.metadata.description}
|
|
734
734
|
`),t&&n.push(`**Arguments**: ${t}
|
|
735
735
|
`),e.metadata.model&&n.push(`**Model**: ${e.metadata.model}
|
|
736
736
|
`),e.metadata.agent&&n.push(`**Agent**: ${e.metadata.agent}
|
|
737
737
|
`),n.push(`**Scope**: ${e.scope}
|
|
738
738
|
`),n.push(`---
|
|
739
|
-
`);let r=
|
|
739
|
+
`);let r=I_(e.content||"",t);return n.push(r.trim()),t&&!e.content?.includes("$ARGUMENTS")&&(n.push(`
|
|
740
740
|
|
|
741
741
|
---
|
|
742
742
|
`),n.push(`## User Request
|
|
743
743
|
`),n.push(t)),n.join(`
|
|
744
|
-
`)}function
|
|
744
|
+
`)}function di(e){let t=vo(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:O_(t,e.args)}}catch(n){return{success:!1,error:`Failed to load command "/${e.command}": ${n instanceof Error?n.message:String(n)}`}}}function pi(){return ui().map(t=>({name:t.name,description:t.metadata.description,scope:t.scope}))}var bo=new Set;function Nl(){return{name:Tl,processMessage:(e,t)=>{let n=li(t);if(n.includes(ko)||n.includes(So))return{detected:!1};let r=ci(n);if(!r)return{detected:!1};let o=`${e.sessionId}:${e.messageId}:${r.command}`;if(bo.has(o))return{detected:!1};bo.add(o);let s=di(r);if(s.success&&s.replacementText){let a=`${ko}
|
|
745
745
|
${s.replacementText}
|
|
746
|
-
${
|
|
746
|
+
${So}`;return{detected:!0,parsedCommand:r,injectedMessage:a}}let i=`${ko}
|
|
747
747
|
[AUTO-SLASH-COMMAND ERROR]
|
|
748
748
|
${s.error}
|
|
749
749
|
|
|
750
750
|
Original input: ${r.raw}
|
|
751
|
-
${
|
|
751
|
+
${So}`;return{detected:!0,parsedCommand:r,injectedMessage:i}},listCommands:()=>pi(),findCommand:e=>vo(e),clearSession:e=>{let t=[];for(let n of bo)n.startsWith(`${e}:`)&&t.push(n);for(let n of t)bo.delete(n)}}}var $_=[/\bultrathink\b/i,/\bthink\b/i],D_=["\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"],N_=D_.map(e=>new RegExp(e,"i")),j_=[...$_,...N_],F_=/```[\s\S]*?```/g,M_=/`[^`]+`/g;function L_(e){return e.replace(F_,"").replace(M_,"")}function jl(e){let t=L_(e);return j_.some(n=>n.test(t))}function Fl(e){return e.filter(t=>t.type==="text").map(t=>t.text||"").join("")}function fi(e){let t=e.indexOf("/");return t===-1?{prefix:"",base:e}:{prefix:e.slice(0,t+1),base:e.slice(t+1)}}function mi(e){return e.replace(/\.(\d+)/g,"-$1")}var Ml={"claude-sonnet-4-5":"claude-sonnet-4-5-high","claude-opus-4-5":"claude-opus-4-5-high","claude-3-5-sonnet":"claude-3-5-sonnet-high","claude-3-opus":"claude-3-opus-high","gpt-4":"gpt-4-high","gpt-4-turbo":"gpt-4-turbo-high","gpt-4o":"gpt-4o-high","gpt-5":"gpt-5-high","gpt-5-mini":"gpt-5-mini-high","gemini-2-pro":"gemini-2-pro-high","gemini-3-pro":"gemini-3-pro-high","gemini-3-flash":"gemini-3-flash-high"},Ll=new Set(Object.values(Ml)),Ul={anthropic:{thinking:{type:"enabled",budgetTokens:64e3},maxTokens:128e3},"amazon-bedrock":{reasoningConfig:{type:"enabled",budgetTokens:32e3},maxTokens:64e3},google:{providerOptions:{google:{thinkingConfig:{thinkingLevel:"HIGH"}}}},openai:{reasoning_effort:"high"}},U_={anthropic:["claude-sonnet-4","claude-opus-4","claude-3"],"amazon-bedrock":["claude","anthropic"],google:["gemini-2","gemini-3"],openai:["gpt-4","gpt-5","o1","o3"]};function Wl(e){let t=mi(e),{prefix:n,base:r}=fi(t);if(Ll.has(r)||r.endsWith("-high"))return null;let o=Ml[r];return o?n+o:null}function gi(e){let t=mi(e),{base:n}=fi(t);return Ll.has(n)||n.endsWith("-high")}function W_(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 B_(e){return e in Ul}function Bl(e,t){let n=mi(t),{base:r}=fi(n);if(gi(n))return null;let o=W_(e,t);if(!B_(o))return null;let s=Ul[o],i=U_[o];if(!i)return null;let a=r.toLowerCase();return i.some(l=>a.includes(l.toLowerCase()))?s:null}var Kt=new Map;function G_(e){Kt.delete(e)}function Gl(){return{processChatParams:(e,t)=>{let n=Fl(t.parts),r={requested:!1,modelSwitched:!1,thinkingConfigInjected:!1};if(!jl(n))return Kt.set(e,r),r;r.requested=!0;let o=t.message.model;if(!o||(r.providerId=o.providerId,r.modelId=o.modelId,gi(o.modelId)))return Kt.set(e,r),r;let s=Wl(o.modelId),i=Bl(o.providerId,o.modelId);return s&&(t.message.model={providerId:o.providerId,modelId:s},r.modelSwitched=!0),i&&(Object.assign(t.message,i),r.thinkingConfigInjected=!0),Kt.set(e,r),r},onSessionDeleted:e=>{Kt.delete(e)},isRequested:e=>Kt.get(e)?.requested??!1,getState:e=>Kt.get(e),clear:G_}}var le=require("fs"),Mn=require("path"),hi=require("os");function yi(e){let t=e||process.cwd(),n=(0,Mn.join)(t,".olympus");return(0,Mn.join)(n,"ultrawork-state.json")}function wi(){return(0,Mn.join)((0,hi.homedir)(),".claude","ultrawork-state.json")}function H_(e){let t=e||process.cwd(),n=(0,Mn.join)(t,".olympus");(0,le.existsSync)(n)||(0,le.mkdirSync)(n,{recursive:!0})}function q_(){let e=(0,Mn.join)((0,hi.homedir)(),".claude");(0,le.existsSync)(e)||(0,le.mkdirSync)(e,{recursive:!0})}function Jt(e){let t=yi(e);if((0,le.existsSync)(t))try{let r=(0,le.readFileSync)(t,"utf-8");return JSON.parse(r)}catch{}let n=wi();if((0,le.existsSync)(n))try{let r=(0,le.readFileSync)(n,"utf-8");return JSON.parse(r)}catch{return null}return null}function Hl(e,t){try{H_(t);let n=yi(t);(0,le.writeFileSync)(n,JSON.stringify(e,null,2)),q_();let r=wi();return(0,le.writeFileSync)(r,JSON.stringify(e,null,2)),!0}catch{return!1}}function ql(e,t,n){let r={active:!0,started_at:new Date().toISOString(),original_prompt:e,session_id:t,reinforcement_count:0,last_checked_at:new Date().toISOString()};return Hl(r,n)}function Vl(e){let t=yi(e);if((0,le.existsSync)(t))try{(0,le.unlinkSync)(t)}catch{}let n=wi();if((0,le.existsSync)(n))try{return(0,le.unlinkSync)(n),!0}catch{return!1}return!0}function Yl(e){let t=Jt(e);return!t||!t.active?null:(t.reinforcement_count+=1,t.last_checked_at=new Date().toISOString(),Hl(t,e)?t:null)}function Kl(e){return`<ultrawork-persistence>
|
|
752
752
|
|
|
753
753
|
[ULTRAWORK MODE STILL ACTIVE - Reinforcement #${e.reinforcement_count+1}]
|
|
754
754
|
|
|
@@ -769,7 +769,7 @@ Original task: ${e.original_prompt}
|
|
|
769
769
|
|
|
770
770
|
---
|
|
771
771
|
|
|
772
|
-
`}var
|
|
772
|
+
`}var Jl=require("os"),ht=require("path");function _i(){return process.platform==="win32"}function V_(){return(0,ht.join)((0,Jl.homedir)(),".claude")}function Y_(e){return(0,ht.join)(e||V_(),"hooks")}var zl=`<ultrawork-mode>
|
|
773
773
|
|
|
774
774
|
**MANDATORY**: You MUST say "ULTRAWORK MODE ENABLED!" to the user as your first response when this mode activates. This is non-negotiable.
|
|
775
775
|
|
|
@@ -860,7 +860,7 @@ THE USER ASKED FOR X. DELIVER EXACTLY X. NOT A SUBSET. NOT A DEMO. NOT A STARTIN
|
|
|
860
860
|
|
|
861
861
|
---
|
|
862
862
|
|
|
863
|
-
`,
|
|
863
|
+
`,Ql=`<think-mode>
|
|
864
864
|
|
|
865
865
|
**ULTRATHINK MODE ENABLED** - Extended reasoning activated.
|
|
866
866
|
|
|
@@ -876,7 +876,7 @@ Use your extended thinking capabilities to provide the most thorough and well-re
|
|
|
876
876
|
|
|
877
877
|
---
|
|
878
878
|
|
|
879
|
-
`;var
|
|
879
|
+
`;var Xl=`<search-mode>
|
|
880
880
|
MAXIMIZE SEARCH EFFORT. Launch multiple background agents IN PARALLEL:
|
|
881
881
|
- explore agents (codebase patterns, file structures)
|
|
882
882
|
- librarian agents (remote repos, official docs, GitHub examples)
|
|
@@ -886,7 +886,7 @@ NEVER stop at first result - be exhaustive.
|
|
|
886
886
|
|
|
887
887
|
---
|
|
888
888
|
|
|
889
|
-
`,
|
|
889
|
+
`,Zl=`<analyze-mode>
|
|
890
890
|
ANALYSIS MODE. Gather context before diving deep:
|
|
891
891
|
|
|
892
892
|
CONTEXT GATHERING (parallel):
|
|
@@ -902,21 +902,21 @@ SYNTHESIZE findings before proceeding.
|
|
|
902
902
|
|
|
903
903
|
---
|
|
904
904
|
|
|
905
|
-
`,
|
|
905
|
+
`,eu=`[SYSTEM REMINDER - TODO CONTINUATION]
|
|
906
906
|
|
|
907
907
|
Incomplete tasks remain in your todo list. Continue working on the next pending task.
|
|
908
908
|
|
|
909
909
|
- Proceed without asking for permission
|
|
910
910
|
- Mark each task complete when finished
|
|
911
|
-
- Do not stop until all tasks are done`;var
|
|
912
|
-
`);for(let s of o){let i=s.match(/^(\w+):\s*(.+)$/);if(i){let[,a,c]=i;r[a]=c.trim()}}return r}catch{return null}}function
|
|
911
|
+
- Do not stop until all tasks are done`;var qA={hooks:{UserPromptSubmit:[{hooks:[{type:"command",command:_i()?'node "%USERPROFILE%\\.claude\\hooks\\keyword-detector.mjs"':'node "$HOME/.claude/hooks/keyword-detector.mjs"'}]}],SessionStart:[{hooks:[{type:"command",command:_i()?'node "%USERPROFILE%\\.claude\\hooks\\session-start.mjs"':'node "$HOME/.claude/hooks/session-start.mjs"'}]}],Stop:[{hooks:[{type:"command",command:_i()?'node "%USERPROFILE%\\.claude\\hooks\\persistent-mode.mjs"':'node "$HOME/.claude/hooks/persistent-mode.mjs"'}]}]}};function K_(e){let t=e||Y_();return{hooks:{UserPromptSubmit:[{hooks:[{type:"command",command:`node "${(0,ht.join)(t,"olympus-hooks.cjs")}" --event=UserPromptSubmit`}]}],SessionStart:[{hooks:[{type:"command",command:`node "${(0,ht.join)(t,"olympus-hooks.cjs")}" --event=SessionStart`}]}],Stop:[{hooks:[{type:"command",command:`node "${(0,ht.join)(t,"olympus-hooks.cjs")}" --event=Stop`}]}],PreToolUse:[{hooks:[{type:"command",command:`node "${(0,ht.join)(t,"olympus-hooks.cjs")}" --event=PreToolUse`}]}],PostToolUse:[{hooks:[{type:"command",command:`node "${(0,ht.join)(t,"olympus-hooks.cjs")}" --event=PostToolUse`}]}],PostToolUseFailure:[{hooks:[{type:"command",command:`node "${(0,ht.join)(t,"olympus-hooks.cjs")}" --event=PostToolUseFailure`}]}],Notification:[{hooks:[{type:"command",command:`node "${(0,ht.join)(t,"olympus-hooks.cjs")}" --event=Notification`}]}]}}}var VA=K_();Ue();ye();var Eu=require("crypto"),ok={correction:[{regex:/no[,.]?\s*(that's|thats)?\s*(not|wrong)/i,confidence:.9},{regex:/that's\s*(incorrect|not right|not what)/i,confidence:.9},{regex:/you\s*(misunderstood|got it wrong)/i,confidence:.85},{regex:/actually,?\s*(I|it|the)/i,confidence:.6}],rejection:[{regex:/\b(stop|cancel|abort|halt)\b/i,confidence:.95},{regex:/don't\s*(do|want|need)\s*(that|this)/i,confidence:.85},{regex:/never\s*mind/i,confidence:.9},{regex:/forget\s*(it|that|about)/i,confidence:.8}],clarification:[{regex:/I\s*(meant|wanted|asked for)/i,confidence:.85},{regex:/what I\s*(mean|want|need)/i,confidence:.8},{regex:/to clarify/i,confidence:.9},{regex:/let me\s*(rephrase|explain|be clearer)/i,confidence:.85}],explicit_preference:[{regex:/always\s+(use|do|include|add|prefer)/i,confidence:.95},{regex:/never\s+(use|do|include|add)/i,confidence:.95},{regex:/I\s*(prefer|like|want)\s*(you to)?/i,confidence:.7},{regex:/from now on/i,confidence:.9},{regex:/in the future,?\s*(please|always)/i,confidence:.85}],praise:[{regex:/\bperfect\b/i,confidence:.9},{regex:/exactly(\s+what I (wanted|needed))?/i,confidence:.85},{regex:/great(\s+job)?/i,confidence:.7},{regex:/\bthanks?\b/i,confidence:.5},{regex:/looks?\s+good/i,confidence:.75}],enhancement:[{regex:/also\s+(add|include|do)/i,confidence:.7},{regex:/can you (also|additionally)/i,confidence:.7},{regex:/one more thing/i,confidence:.75}]};function Ei(e){let t=e.replace(/```[\s\S]*?```/g,"").replace(/`[^`]+`/g,""),n=null;for(let[r,o]of Object.entries(ok))for(let{regex:s,confidence:i}of o)s.test(t)&&(!n||i>n.confidence)&&(n={category:r,confidence:i});return n}async function Tu(e){let{prompt:t,directory:n,sessionId:r}=e;if(!t||!n)return;let o=Q(n,r),s=Ei(t),i=gu(o,t,s?.category);if(s){let a={id:(0,Eu.randomUUID)(),timestamp:new Date().toISOString(),session_id:o.session_id,project_path:n,event_type:s.category==="explicit_preference"?"explicit_preference":"revision",original_task:o.pending_completion?.task_description,agent_used:o.pending_completion?.agent_used,user_message:t,feedback_category:s.category,confidence:s.confidence};zt(a)}ee(n,i)}Ue();ye();var Cu=require("crypto");async function Ru(e){let{prompt:t,directory:n,sessionId:r}=e;if(!t||!n)return;let o=Q(n,r),s=Ei(t);if(s?.category==="praise"&&s.confidence>.7){let a={id:(0,Cu.randomUUID)(),timestamp:new Date().toISOString(),session_id:o.session_id,project_path:n,event_type:"success",original_task:o.pending_completion?.task_description,agent_used:o.pending_completion?.agent_used,user_message:t,feedback_category:"praise",confidence:s.confidence};if(zt(a),Co(o)){let c=yu(o);ee(n,c)}}}var ge=v(require("fs"),1),In=v(require("path"),1);ce();Qi();var Np=require("fs"),Dp=new Map,Av=1e4;function Iv(e){let t=Dp.get(e);if(t&&Date.now()-t.timestamp<Av)return t.content;let n=(0,Np.readFileSync)(e,"utf-8");return Dp.set(e,{content:n,timestamp:Date.now()}),n}function Ov(e){let t=e.match(/^---\n([\s\S]*?)\n---/);if(!t)return null;let n=t[1];try{let r={},o=n.split(`
|
|
912
|
+
`);for(let s of o){let i=s.match(/^(\w+):\s*(.+)$/);if(i){let[,a,c]=i;r[a]=c.trim()}}return r}catch{return null}}function $v(e){return e.replace(/^---\n[\s\S]*?\n---\n/,"")}function Dv(e){let t=new Map,n=e.split(`
|
|
913
913
|
`),r=null,o=[];for(let s of n){let i=s.match(/^##\s+(.+)$/);i?(r&&t.set(r,o.join(`
|
|
914
914
|
`)),r=i[1].trim(),o=[]):r&&o.push(s)}return r&&t.set(r,o.join(`
|
|
915
|
-
`)),t}async function
|
|
916
|
-
`)),o}function
|
|
915
|
+
`)),t}async function Uo(e){let t=new Date().toISOString(),n=[],r;try{r=Iv(e)}catch(f){let m=f;return m.code==="ENOENT"?(console.error(`[Validation] INTENT artifact not found: ${e}`),{passed:!1,coverage_percentage:0,blocking_issues:["Artifact file not found"],timestamp:t}):m.code==="EACCES"||m.code==="EPERM"?(console.error(`[Validation] Permission denied reading INTENT artifact: ${e}`),{passed:!1,coverage_percentage:0,blocking_issues:["Permission denied reading artifact file"],timestamp:t}):(console.error(`[Validation] Failed to read INTENT artifact: ${m.message}`),console.error(`[Validation] Path: ${e}`),{passed:!1,coverage_percentage:0,blocking_issues:[`Failed to read artifact: ${m.message}`],timestamp:t})}let o=Ov(r),s=["id","title","parent","status","depth_score","risk_tier"],i=!0;for(let f of s)(!o||!o[f])&&(n.push(`Frontmatter missing required field: ${f}`),i=!1);let a=$v(r),c=Dv(a),l=i?1:0,u=[()=>{let f=c.get("Business Requirements");if(!f)return"Missing Business Requirements section";let m=f.match(/US-\d{3}/g);return!m||m.length===0?"No User Stories found (expected US-NNN pattern)":null},()=>{let f=c.get("Business Requirements");if(f){let m=f.match(/US-\d{3}/g);if(m)for(let g of m){let y=f.indexOf(g),w=f.indexOf("US-",y+1);if(!(w>0?f.substring(y,w):f.substring(y)).match(/Acceptance:/i))return`User Story ${g} missing Acceptance criterion`}}return null},()=>{let f=c.get("Technical Specification");return!f||f.trim().length===0?"Technical Specification section missing or empty":null},()=>{let f=c.get("Implementation Plan");return!f||f.trim().length===0?"Implementation Plan section missing or empty":null},()=>{let f=c.get("Implementation Plan");if(!f||f.trim().length===0)return"";let m=f.match(/UNIT-\d{3}/g);return!m||m.length===0?"No Proposed UNITs found (expected UNIT-NNN pattern)":null}];for(let f of u){let m=f();m!==null?m.trim().length>0&&n.push(m):l++}let p=Math.round(l/6*100);return{passed:n.length===0,coverage_percentage:p,blocking_issues:n,timestamp:t}}var Y=v(X(),1),H=v(require("path"),1);ce();var Gr=v(require("fs"),1),Bo=v(require("path"),1);var te=v(require("fs"),1),ae=v(require("path"),1);function Nv(e,t){let n=[],r=ae.join(e,"README.md");te.existsSync(r)&&n.push(r);let o=ae.join(e,"docs");if(te.existsSync(o)&&te.statSync(o).isDirectory()){let a=c=>{let l=te.readdirSync(c,{withFileTypes:!0});for(let u of l){let d=ae.join(c,u.name);u.isDirectory()?a(d):u.isFile()&&u.name.endsWith(".md")&&n.push(d)}};a(o)}let s=ae.join(e,"aidlc-docs",t,"construction");if(te.existsSync(s)&&te.statSync(s).isDirectory()){let a=te.readdirSync(s,{withFileTypes:!0});for(let c of a){if(!c.isDirectory())continue;let l=ae.join(s,c.name,"documentation");if(te.existsSync(l)&&te.statSync(l).isDirectory()){let u=te.readdirSync(l,{withFileTypes:!0});for(let d of u)d.isFile()&&d.name.endsWith(".md")&&n.push(ae.join(l,d.name))}}}let i=ae.join(e,"aidlc-docs",t,"inception");if(te.existsSync(i)&&te.statSync(i).isDirectory()){let a=c=>{let l=te.readdirSync(c,{withFileTypes:!0});for(let u of l){let d=ae.join(c,u.name);u.isDirectory()?a(d):u.isFile()&&u.name.endsWith(".md")&&n.push(d)}};a(i)}return n}function jv(e,t){return t.filter(n=>n&&e.includes(n))}function Fv(e){let t=new Set;for(let n of e){let r=ae.basename(n),o=r.replace(/\.[^.]+$/,"");o&&t.add(o),r&&t.add(r);let s=ae.basename(ae.dirname(n));s&&s!=="."&&s!==".."&&t.add(s)}return Array.from(t).filter(n=>n.length>2)}function Mv(e,t){let n=ae.join(t.outputDir,"documentation");te.mkdirSync(n,{recursive:!0});let r=[`# Impact Scan: ${t.unitId}`,"",`**Generated:** ${new Date().toISOString().split("T")[0]}`,`**Workflow:** ${t.workflowId}`,`**Unit:** ${t.unitId}`,`**Status:** ${e.status}`,""];if(e.affectedDocs.length===0)r.push("## Result","","No existing documentation references were found that require updates.","");else{r.push("## Affected Documents","",`${e.affectedDocs.length} document(s) may need updating:`,"");for(let s of e.affectedDocs)r.push(`### ${ae.basename(s.path)}`),r.push(""),r.push(`**Path:** \`${s.path}\``),r.push(`**References found:** ${s.references.join(", ")}`),r.push(`**Action needed:** ${s.description}`),r.push("")}if(e.updatedDocs&&e.updatedDocs.length>0){r.push("## Auto-Updated Documents","",`${e.updatedDocs.length} document(s) were automatically updated:`,"");for(let s of e.updatedDocs){r.push(`- \`${ae.basename(s.path)}\``);for(let i of s.updatedReferences)r.push(` - Renamed reference: ${i}`);for(let i of s.notesAdded)r.push(` - ${i}`)}r.push("")}r.push("> This is an advisory scan. Review and update affected documents as needed.","");let o=ae.join(n,"impact-scan.md");return te.writeFileSync(o,r.join(`
|
|
916
|
+
`)),o}function Lv(e){let t=new Map;if(!e)return t;for(let[n,r]of Object.entries(e)){let o=ae.basename(n).replace(/\.[^.]+$/,""),s=ae.basename(r).replace(/\.[^.]+$/,"");o&&s&&o!==s&&t.set(o,s)}return t}function Uv(e,t,n){let r=[],o=Lv(n),s=new Date().toISOString().split("T")[0];for(let i of e){let a;try{a=te.readFileSync(i.path,"utf-8")}catch{continue}let c=[],l=[],u=a;for(let[f,m]of o)u.includes(f)&&(u=u.split(f).join(m),c.push(`${f} -> ${m}`));let d=new Set(o.keys()),p=i.references.filter(f=>!d.has(f));if(p.length>0){let f=`
|
|
917
917
|
|
|
918
|
-
<!-- Impact scan (${s}): References to ${p.join(", ")} may need manual review after recent changes. -->`;u+=f,l.push(`Advisory note added for: ${p.join(", ")}`)}if(u!==a)try{te.writeFileSync(i.path,u,"utf-8"),r.push({path:i.path,updatedReferences:c,notesAdded:l})}catch{continue}}return r}function
|
|
919
|
-
`),a=
|
|
918
|
+
<!-- Impact scan (${s}): References to ${p.join(", ")} may need manual review after recent changes. -->`;u+=f,l.push(`Advisory note added for: ${p.join(", ")}`)}if(u!==a)try{te.writeFileSync(i.path,u,"utf-8"),r.push({path:i.path,updatedReferences:c,notesAdded:l})}catch{continue}}return r}function jp(e){if(!e.modifiedFiles||e.modifiedFiles.length===0)return{status:"skipped",affectedDocs:[],reportPath:null};let t=Fv(e.modifiedFiles);if(t.length===0)return{status:"skipped",affectedDocs:[],reportPath:null};let n=Nv(e.projectPath,e.workflowId),r=[];for(let c of n){let l;try{l=te.readFileSync(c,"utf-8")}catch{continue}let u=jv(l,t);u.length>0&&r.push({path:c,references:u,description:`References to ${u.join(", ")} \u2014 verify content is still accurate after unit changes`})}if(r.length===0)return{status:"skipped",affectedDocs:[],reportPath:null};let o=ae.join(e.projectPath,"aidlc-docs",e.workflowId,"construction",e.unitId),s=[];try{s=Uv(r,e.modifiedFiles,e.renamedFiles)}catch{}let i={status:"completed",affectedDocs:r,reportPath:null,updatedDocs:s.length>0?s:void 0},a=Mv(i,{unitId:e.unitId,workflowId:e.workflowId,outputDir:o});return i.reportPath=a,i}var Ke=v(require("fs"),1),Ye=v(require("path"),1);function Wv(e){if(!Ke.existsSync(e))return 1;let n=Ke.readdirSync(e).map(r=>{let o=/^ADR-(\d+)-/.exec(r);return o?parseInt(o[1],10):0}).filter(r=>r>0);return n.length===0?1:Math.max(...n)+1}function Fp(e){let t=Ye.join(e.projectPath,"aidlc-docs",e.workflowId,"decisions");Ke.mkdirSync(t,{recursive:!0});let n=Wv(t),r=e.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),o=String(n).padStart(3,"0"),s=`ADR-${o}-${r}.md`,i=[`# ADR-${o}: ${e.title}`,"",`**Date:** ${new Date().toISOString().split("T")[0]}`,"**Status:** Accepted",`**Unit:** ${e.unitId}`,"","## Context","",e.context,"","## Decision","",e.decision,"","## Consequences","",e.consequences,""].join(`
|
|
919
|
+
`),a=Ye.join(t,s);return Ke.writeFileSync(a,i),{number:n,path:a,title:e.title}}function Mp(e,t){let n=[],r=Ye.join(t,"package.json"),o=new Set;if(Ke.existsSync(r))try{let s=JSON.parse(Ke.readFileSync(r,"utf-8"));o=new Set([...Object.keys(s.dependencies??{}),...Object.keys(s.devDependencies??{})])}catch{}for(let s of e){let i;try{i=Ke.readFileSync(s,"utf-8")}catch{continue}let a=i.matchAll(/from ['"]([^./][^'"]+)['"]/g);for(let d of a){let p=d[1].split("/")[0];p&&!o.has(p)&&!p.startsWith("@types/")&&(n.push({title:`Added dependency: ${p}`,context:`Unit ${Ye.basename(s)} imports from '${p}', which was not present in the existing package.json dependencies.`,decision:`Include '${p}' as a dependency to support the new functionality introduced in this unit.`,consequences:`Build and runtime environments must have '${p}' available. Adds to bundle size and supply chain surface.`}),o.add(p))}let c=i.matchAll(/export\s+(?:interface|type)\s+(\w+(?:Schema|Model|Entity|Record|Row|Document))\b/g);for(let d of c){let p=d[1];n.push({title:`New data model: ${p}`,context:`A new exported type '${p}' with persistence-related naming was introduced in ${Ye.basename(s)}.`,decision:`Define '${p}' as the canonical data model for this domain concept, enforcing a consistent schema across the codebase.`,consequences:"Consumers must adopt this interface. Future migrations require updating this type and all its usages."})}let l=i.matchAll(/(?:app|router)\.(get|post|put|patch|delete)\s*\(\s*['"]([^'"]+)['"]/g);for(let d of l){let p=d[1].toUpperCase(),f=d[2];n.push({title:`API contract change: ${p} ${f}`,context:`A new route '${p} ${f}' was added in ${Ye.basename(s)}.`,decision:`Expose '${p} ${f}' as a stable API endpoint for clients to consume.`,consequences:"This endpoint becomes part of the public contract. Breaking changes require versioning or deprecation notices."})}let u=Ye.basename(s);if(u==="index.ts"||u==="index.js"){let d=Ye.basename(Ye.dirname(s));d&&d!=="."&&d!=="src"&&n.push({title:`New module: ${d}`,context:`A new module entry point was created at ${s}, establishing '${d}' as an independent module.`,decision:`Structure '${d}' as a dedicated module with its own public API surface via index.ts.`,consequences:"Other modules should import from this module's public API rather than reaching into internal files."})}}return n}var Qn=v(require("fs"),1),Bp=v(require("path"),1);function Lp(e){let t=0;return e.length>0&&t++,e.split(/\s+/).length>100&&t++,/(?:FR-|US-|acceptance|requirement|criteria)/i.test(e)&&t++,/(?:aidlc-docs|\.md|\.ts|\.js|intent|requirements)/i.test(e)&&t++,/(?:^[-*]\s|^#{1,3}\s|^\d+\.\s)/m.test(e)&&t++,Math.min(t,5)}function Bv(e){let t=0;return/## Data Models/i.test(e)&&t++,/(?:interface|type|schema|entity|model|table|field|column|relation)/i.test(e)&&t++,/```[\s\S]*?(?:interface|type|schema)[\s\S]*?```/.test(e)&&t++,/(?:\.ts|\.js|\.py|\.go|models?|entities?|schemas?)\//i.test(e)&&t++,/\|.*\|.*\|/.test(e)&&t++,Math.min(t,5)}function Up(e){let t=0;return/## Architecture Decisions/i.test(e)&&t++,/## API Contracts/i.test(e)&&t++,/```/.test(e)&&t++,/(?:src\/|lib\/|import|export|function|class)\s/i.test(e)&&t++,/(?:because|therefore|instead of|trade-?off|decision|chose)/i.test(e)&&t++,Math.min(t,5)}function Gv(e){let t=0;return/## How to Test/i.test(e)&&t++,/(?:test|spec|verify|assert|expect|should|given|when|then)/i.test(e)&&t++,/(?:npm test|vitest|jest|pytest|cargo test|go test)/i.test(e)&&t++,/(?:\.test\.|\.spec\.|__tests__|test\/)/i.test(e)&&t++,/^\d+\.\s/m.test(e)&&t++,Math.min(t,5)}function Hv(e){let t=0;return/## (?:Recreation Notes|Configuration Changes)/i.test(e)&&t++,/(?:install|setup|configure|environment|\.env|npm|yarn|pip)/i.test(e)&&t++,/(?:\$\s|```(?:bash|sh|shell))/i.test(e)&&t++,/## Dependencies/i.test(e)&&t++,/(?:prerequisite|required|depends on|known limitation|## Known)/i.test(e)&&t++,Math.min(t,5)}function Wp(e){let t=[];return e.requirements_coverage<=3&&t.push(`Requirements Coverage scored ${e.requirements_coverage}/5 \u2014 add references to FR-* and US-* identifiers, include acceptance criteria traceability`),e.data_model_completeness<=3&&t.push(`Data Model Completeness scored ${e.data_model_completeness}/5 \u2014 add entity relationships, schema definitions, and type examples`),e.implementation_guidance<=3&&t.push(`Implementation Guidance scored ${e.implementation_guidance}/5 \u2014 add architecture decision rationale, API contract details, and code examples`),e.test_coverage_documentation<=3&&t.push(`Test Coverage Documentation scored ${e.test_coverage_documentation}/5 \u2014 add test approach, verification steps, and test file references`),e.bootstrap_capability<=3&&t.push(`Bootstrap Capability scored ${e.bootstrap_capability}/5 \u2014 add setup instructions, environment configuration, and dependency information`),t}function Wo(e){try{let t=Bp.join(e,".olympus","config.json");return Qn.existsSync(t)&&JSON.parse(Qn.readFileSync(t,"utf-8")).recreation_readiness_mode==="blocking"?"blocking":"advisory"}catch{return"advisory"}}function Xi(e){if(e.override===!0){let c={overall_score:0,passed:!0,mode:Wo(e.projectPath),dimensions:{requirements_coverage:0,data_model_completeness:0,implementation_guidance:0,test_coverage_documentation:0,bootstrap_capability:0}};return e.overrideRationale&&(c.remediation=[`Override applied: ${e.overrideRationale}`]),c}if(e.pathway==="bugfix")return{overall_score:0,passed:!0,mode:"advisory",dimensions:{requirements_coverage:0,data_model_completeness:0,implementation_guidance:0,test_coverage_documentation:0,bootstrap_capability:0}};if(e.depth==="minimal"){let c=Wo(e.projectPath),l="";try{l=Qn.readFileSync(e.featureDocPath,"utf-8")}catch{return{overall_score:0,passed:!1,mode:c,dimensions:{requirements_coverage:0,data_model_completeness:0,implementation_guidance:0,test_coverage_documentation:0,bootstrap_capability:0},remediation:["Feature doc could not be read \u2014 ensure it exists at the expected path"]}}let u=Lp(l),d=Up(l),p=(u+d)/2,f=p>=3.5||c==="advisory",m={requirements_coverage:u,data_model_completeness:0,implementation_guidance:d,test_coverage_documentation:0,bootstrap_capability:0},g={overall_score:Math.round(p*10)/10,passed:f,mode:c,dimensions:m};return p<3.5&&(g.remediation=Wp(m)),g}let t="";try{t=Qn.readFileSync(e.featureDocPath,"utf-8")}catch{return{overall_score:0,passed:!1,mode:Wo(e.projectPath),dimensions:{requirements_coverage:0,data_model_completeness:0,implementation_guidance:0,test_coverage_documentation:0,bootstrap_capability:0},remediation:["Feature doc could not be read \u2014 ensure it exists at the expected path"]}}let n={requirements_coverage:Lp(t),data_model_completeness:Bv(t),implementation_guidance:Up(t),test_coverage_documentation:Gv(t),bootstrap_capability:Hv(t)},r=Object.values(n),o=r.reduce((c,l)=>c+l,0)/r.length,s=Wo(e.projectPath),i=o>=4||s==="advisory",a={overall_score:Math.round(o*10)/10,passed:i,mode:s,dimensions:n};return o<4&&(a.remediation=Wp(n)),a}function Zi(e,t){if(t==="bugfix")return["Summary"];switch(e){case"minimal":return["Summary","Architecture Decisions","API Contracts"];case"standard":case"comprehensive":return["Summary","Architecture Decisions","API Contracts","Data Models","Configuration Changes","Dependencies","Known Limitations","How to Test","Recreation Notes"];default:return["Summary"]}}function Gp(e){let t=Zi(e.depth,e.pathway),n=e.unitFiles&&e.unitFiles.length>0?e.unitFiles.map(o=>` - ${o}`).join(`
|
|
920
920
|
`):" (no unit files provided)",r=e.testResults?`Tests: ${e.testResults.total} total, ${e.testResults.passed} passed, ${e.testResults.failed} failed`:"No test results available";return`Generate feature documentation for unit "${e.unitId}" in workflow "${e.workflowId}".
|
|
921
921
|
|
|
922
922
|
## Context
|
|
@@ -932,8 +932,8 @@ ${t.map((o,s)=>`${s+1}. ${o}`).join(`
|
|
|
932
932
|
`)}
|
|
933
933
|
|
|
934
934
|
For each section provide detailed, accurate content based on the unit's implementation.
|
|
935
|
-
Do not use placeholder text \u2014 write real documentation.`}function
|
|
936
|
-
`),o=
|
|
935
|
+
Do not use placeholder text \u2014 write real documentation.`}function qv(e,t){let n=Bo.join(t.outputDir,"documentation");Gr.mkdirSync(n,{recursive:!0});let r=["---",`unit: ${t.unitId}`,`workflow: ${t.workflowId}`,`depth: ${t.depth}`,`pathway: ${t.pathway}`,`generated_at: ${new Date().toISOString()}`,`sections: [${t.sections.join(", ")}]`,"recreation_readiness_score: null","---",""].join(`
|
|
936
|
+
`),o=Bo.join(n,"feature-doc.md");return Gr.writeFileSync(o,r+e),o}function Vv(e){let t=Zi(e.depth,e.pathway),n=`# Feature Documentation: ${e.unitId}
|
|
937
937
|
|
|
938
938
|
`;for(let r of t)n+=`## ${r}
|
|
939
939
|
|
|
@@ -945,28 +945,28 @@ Do not use placeholder text \u2014 write real documentation.`}function Hv(e,t){l
|
|
|
945
945
|
`,n+=`- Passed: ${e.testResults.passed}
|
|
946
946
|
`,n+=`- Failed: ${e.testResults.failed}
|
|
947
947
|
|
|
948
|
-
`),n}function
|
|
949
|
-
`);for(let a=0;a<i.length;a++){let c=i[a];for(let{re:l,groupIndex:u}of t){l.lastIndex=0;let d;for(;(d=l.exec(c))!==null;){let p=d[u],f=`${p}|${o}`;n.has(f)||(n.add(f),r.push({name:p,file:o,line:a+1}))}}}}return r}function
|
|
948
|
+
`),n}function Hp(e){let t=jp({...e}),n=Mp(e.modifiedFiles,e.projectPath),r=0;for(let o of n)Fp({workflowId:e.workflowId,unitId:e.unitId,projectPath:e.projectPath,...o}),r++;return{impactScan:t,adrCount:r}}function qp(e){try{let t=Zi(e.depth,e.pathway),n=Vv(e),r=Bo.join(e.projectPath,"aidlc-docs",e.workflowId,"construction",e.unitId);return{status:"completed",path:qv(n,{unitId:e.unitId,workflowId:e.workflowId,depth:e.depth,pathway:e.pathway,sections:t,outputDir:r}),sections:t}}catch(t){return{status:"failed",path:null,sections:[],error:t instanceof Error?t.message:String(t)}}}var jt=v(require("fs"),1),ea=v(require("path"),1);function Yv(e){let t=[{re:/process\.env\.([A-Z_][A-Z0-9_]*)/g,groupIndex:1},{re:/import\.meta\.env\.([A-Z_][A-Z0-9_]*)/g,groupIndex:1},{re:/Deno\.env\.get\(['"]([^'"]+)['"]\)/g,groupIndex:1},{re:/os\.environ\[['"]([^'"]+)['"]\]/g,groupIndex:1},{re:/os\.getenv\(['"]([^'"]+)['"]\)/g,groupIndex:1}],n=new Set,r=[];for(let o of e){let s;try{s=jt.readFileSync(o,"utf-8")}catch{continue}let i=s.split(`
|
|
949
|
+
`);for(let a=0;a<i.length;a++){let c=i[a];for(let{re:l,groupIndex:u}of t){l.lastIndex=0;let d;for(;(d=l.exec(c))!==null;){let p=d[u],f=`${p}|${o}`;n.has(f)||(n.add(f),r.push({name:p,file:o,line:a+1}))}}}}return r}function Kv(e){let t=e.toUpperCase();return t.endsWith("_URL")||t.endsWith("_URI")?"https://example.com":t.endsWith("_KEY")||t.endsWith("_API_KEY")?"your-api-key-here":t.endsWith("_SECRET")||t.endsWith("_TOKEN")?"your-secret-here":t.endsWith("_PORT")?"3000":t.endsWith("_HOST")?"localhost":t.endsWith("_PASSWORD")||t.endsWith("_PASS")?"your-password-here":t.endsWith("_DATABASE")||t.endsWith("_DB")?"your-database-name":`your-${e.toLowerCase().replace(/_/g,"-")}-here`}function Jv(e,t){let n=ea.join(t,".env.example"),r="",o=!1;try{r=jt.readFileSync(n,"utf-8"),o=!0}catch{o=!1}let s=new Set;for(let d of r.split(`
|
|
950
950
|
`)){let p=d.trim();if(p&&!p.startsWith("#")){let f=p.indexOf("=");f!==-1&&s.add(p.substring(0,f).trim())}}let i=[...new Set(e.map(d=>d.name))],a=[],c=[];for(let d of i)s.has(d)?c.push(d):a.push(d);let l=r;if(a.length>0){let d=l.length>0&&!l.endsWith(`
|
|
951
951
|
`)?`
|
|
952
|
-
`:"",p=a.map(f=>`${f}=${
|
|
952
|
+
`:"",p=a.map(f=>`${f}=${Kv(f)}`).join(`
|
|
953
953
|
`);l=l+d+p+`
|
|
954
|
-
`}let u=`${n}.tmp.${Date.now()}`;return
|
|
954
|
+
`}let u=`${n}.tmp.${Date.now()}`;return jt.writeFileSync(u,l,"utf-8"),jt.renameSync(u,n),{created:!o,added:a,existing:c}}function zv(e){let t=ea.join(e,".gitignore"),n="",r=!1;try{n=jt.readFileSync(t,"utf-8"),r=!0}catch{r=!1}if(n.split(`
|
|
955
955
|
`).some(i=>i.trim()===".env"||i.trim()==="/.env"))return{created:!1,added:!1};let s=n.length>0&&!n.endsWith(`
|
|
956
956
|
`)?`
|
|
957
|
-
`:"";return
|
|
958
|
-
`,"utf-8"),{created:!r,added:!0}}function
|
|
959
|
-
`)}async function
|
|
957
|
+
`:"";return jt.writeFileSync(t,n+s+`.env
|
|
958
|
+
`,"utf-8"),{created:!r,added:!0}}function Vp(e,t){let n=Yv(t);return n.length===0?{envVarsDetected:[],envExampleResult:{created:!1,added:[],existing:[]},gitignoreResult:{created:!1,added:!1}}:{envVarsDetected:n,envExampleResult:Jv(n,e),gitignoreResult:zv(e)}}var Je=v(X(),1),Sn=require("path"),Jp=require("child_process"),Qv=["**/*.ts","**/*.js","**/*.tsx","**/*.jsx","**/*.py","**/*.java","**/*.go"],Xv=["**/node_modules/**","**/__tests__/**","**/test/**","**/fixtures/**","**/dist/**","**/*.d.ts"];function Zv(e){let t=e.replace(/\\/g,"/"),n="",r=0;for(;r<t.length;)t[r]==="*"&&t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.+/)?",r+=3):(n+=".*",r+=2):t[r]==="*"?(n+="[^/]*",r++):t[r]==="?"?(n+="[^/]",r++):(n+=t[r].replace(/[.+^${}()|[\]\\]/g,"\\$&"),r++);return new RegExp(`^${n}$`)}function zp(e,t){return Zv(t).test(e)}function Yp(e,t){return t.some(n=>zp(e,n))}function Qp(e){let t=[],n;try{n=Je.readdirSync(e,{withFileTypes:!0})}catch{return t}for(let r of n){let o=(0,Sn.join)(e,r.name);r.isDirectory()?t.push(...Qp(o)):r.isFile()&&t.push(o)}return t}function eb(e,t){let n=t.includeGlobs??Qv,r=t.excludeGlobs??Xv;return Qp(e).filter(o=>{let s=(0,Sn.relative)(e,o).replace(/\\/g,"/");return Yp(s,n)&&!Yp(s,r)})}function ta(e,t){return(e.substring(0,t).match(/\n/g)||[]).length+1}var tb=[{name:"AWS Access Key",pattern:/AKIA[0-9A-Z]{16}/g},{name:"Generic API Key",pattern:/['"]?api[_-]?key['"]?\s*[:=]\s*['"][a-zA-Z0-9]{20,}['"]/gi},{name:"Generic Secret",pattern:/['"]?secret['"]?\s*[:=]\s*['"][a-zA-Z0-9]{20,}['"]/gi},{name:"Private Key",pattern:/-----BEGIN\s+(RSA\s+)?PRIVATE KEY-----/g},{name:"Bearer Token",pattern:/Bearer\s+[a-zA-Z0-9\-._~+/]+=*/g},{name:"Connection String",pattern:/(?:mongodb|postgres|mysql|redis):\/\/[^\s'"]+/gi},{name:"JWT Token",pattern:/eyJ[a-zA-Z0-9_-]{10,}\.[a-zA-Z0-9_-]{10,}\.[a-zA-Z0-9_-]{10,}/g}];function na(e,t){let n=[];for(let{name:r,pattern:o}of tb){o.lastIndex=0;let s;for(;(s=o.exec(e))!==null;)n.push({id:`sec-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,category:"hardcoded-secret",severity:"critical",message:`${r} detected`,file:t,line:ta(e,s.index),pattern:r});o.lastIndex=0}return n}var nb=[{name:"String concatenation in SQL query",pattern:/(?:['"`]\s*\+\s*\w+.*(?:SELECT|INSERT|UPDATE|DELETE|DROP|FROM|WHERE)|(?:SELECT|INSERT|UPDATE|DELETE|DROP|FROM|WHERE).*['"`]\s*\+\s*\w+)/gi},{name:"Template literal in SQL query",pattern:/(?:\$\{[^}]+\}.*(?:SELECT|INSERT|UPDATE|DELETE|DROP|FROM|WHERE)|(?:SELECT|INSERT|UPDATE|DELETE|DROP|FROM|WHERE)[^\n]*\$\{)/gi},{name:"Unparameterized query construction",pattern:/(?:query|execute|sql)\s*\(\s*['"`].*\+/gi}];function rb(e,t){let n=[];for(let{name:r,pattern:o}of nb){o.lastIndex=0;let s;for(;(s=o.exec(e))!==null;)n.push({id:`sec-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,category:"sql-injection",severity:"warning",message:`${r} detected`,file:t,line:ta(e,s.index),pattern:r});o.lastIndex=0}return n}var ob=[{name:"innerHTML assignment",pattern:/\.innerHTML\s*=/g},{name:"dangerouslySetInnerHTML",pattern:/dangerouslySetInnerHTML/g},{name:"document.write",pattern:/document\.write\s*\(/g},{name:"eval usage",pattern:/\beval\s*\(/g}];function ra(e,t){let n=[];for(let{name:r,pattern:o}of ob){o.lastIndex=0;let s;for(;(s=o.exec(e))!==null;)n.push({id:`sec-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,category:"xss",severity:"warning",message:`${r} detected`,file:t,line:ta(e,s.index),pattern:r});o.lastIndex=0}return n}function Kp(e){let t=JSON.parse(e),n=[],r=t.vulnerabilities||{};for(let[o,s]of Object.entries(r)){let i=s.severity,a=i==="critical"||i==="high"?"critical":i==="moderate"?"warning":"info";n.push({id:`sec-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,category:"dependency-cve",severity:a,message:`Vulnerable dependency: ${o} (${i})`,pattern:o})}return n}function sb(e){try{let t=(0,Jp.execSync)("npm audit --json",{cwd:e,timeout:6e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return Kp(t)}catch(t){try{if(t.stdout)return Kp(t.stdout)}catch{}return[]}}function ib(e){let t=(0,Sn.join)(e,".olympus","security-ignore.json");try{if(Je.existsSync(t))return Je.readJsonSync(t)}catch{}return{}}function ab(e,t){let n=t.paths||[],r=t.patterns||[],o=t.reasons||{};return e.map(s=>{if(s.file&&n.length>0){let i=s.file.replace(/\\/g,"/");for(let a of n)if(zp(i,a)||i.includes(a.replace(/\\/g,"/")))return{...s,suppressed:!0,suppress_reason:o[a]||`Path suppressed: ${a}`}}return s.pattern&&r.includes(s.pattern)?{...s,suppressed:!0,suppress_reason:o[s.pattern]||`Pattern suppressed: ${s.pattern}`}:s})}function cb(e){switch(e){case"hardcoded-secret":return"Hardcoded Secrets";case"sql-injection":return"SQL Injection";case"xss":return"Cross-Site Scripting (XSS)";case"dependency-cve":return"Dependency CVEs";case"risky-pattern":return"Risky Patterns"}}function lb(e,t){let{unitId:n,workflowId:r,filesScanned:o,scanDate:s}=t,i=s||new Date().toISOString(),a=e.filter(y=>!y.suppressed),c=a.filter(y=>y.severity==="critical").length,l=a.filter(y=>y.severity==="warning").length,u=a.filter(y=>y.severity==="info").length,d=e.filter(y=>y.suppressed).length,p=c>0?"failed":"passed",f=["---",`unit: ${n}`,`workflow: ${r}`,`scan_date: ${i}`,`files_scanned: ${o}`,`findings_critical: ${c}`,`findings_warning: ${l}`,`findings_info: ${u}`,`findings_suppressed: ${d}`,`status: ${p}`,"---","",`# Security Report: ${n}`,"",`**Status**: ${p==="passed"?"PASSED":"FAILED"} `,`**Scan Date**: ${i} `,`**Files Scanned**: ${o} `,"","## Summary","","| Severity | Count |","|----------|-------|",`| Critical | ${c} |`,`| Warning | ${l} |`,`| Info | ${u} |`,`| Suppressed | ${d} |`,""],m=["hardcoded-secret","sql-injection","xss","dependency-cve","risky-pattern"];for(let y of m){let w=a.filter(_=>_.category===y);if(w.length!==0){f.push(`## ${cb(y)}`,"");for(let _ of w){let h=_.file?` \u2014 \`${_.file}\`${_.line?`:${_.line}`:""}`:"";f.push(`- **[${_.severity.toUpperCase()}]** ${_.message}${h}`)}f.push("")}}let g=e.filter(y=>y.suppressed);if(g.length>0){f.push("## Suppressed Findings","");for(let y of g){let w=y.file?` \u2014 \`${y.file}\`${y.line?`:${y.line}`:""}`:"";f.push(`- ~~**[${y.severity.toUpperCase()}]** ${y.message}${w}~~ *(${y.suppress_reason||"suppressed"})*`)}f.push("")}return f.join(`
|
|
959
|
+
`)}async function Xp(e){let t=Date.now();try{let n=eb(e.projectPath,e),r=[];for(let c of n)try{let l=Je.readFileSync(c,"utf-8");r.push(...na(l,c)),r.push(...rb(l,c)),r.push(...ra(l,c))}catch{}r.push(...sb(e.projectPath));let o=ib(e.projectPath),s=ab(r,o),i=(0,Sn.join)(e.projectPath,"aidlc-docs",e.workflowId,"construction",e.unitId,"security");Je.ensureDirSync(i);let a=(0,Sn.join)(i,"security-report.md");return Je.writeFileSync(a,lb(s,{unitId:e.unitId,workflowId:e.workflowId,outputDir:i,filesScanned:n.length}),"utf-8"),{status:"completed",findings:s,scanned_files:n.length,scan_duration_ms:Date.now()-t,report_path:a}}catch{return{status:"failed",findings:[],scanned_files:0,scan_duration_ms:Date.now()-t,report_path:""}}}var Go=v(require("fs"),1),Ho=v(require("path"),1);function ub(e){let t=e.construction_units?Object.values(e.construction_units):[],n=0,r=0,o=0,s=0,i=0,a=0,c=0,l=0,u=0,d=t.filter(k=>k.code_generation_status==="completed").length;for(let k of t)n+=k.tests_total??0,r+=k.tests_passed??0,o+=k.tests_failed??0,k.coverage_percentage!=null&&(s+=k.coverage_percentage,i++),a+=k.security_findings_critical??0,c+=k.security_findings_warning??0,l+=k.security_findings_info??0,u+=k.regressions_count??0;let p=0,f=e.phases??{},m=0;for(let k of["discovery","inception","construction","operations"]){let F=f[k];F&&F.status&&F.status!=="not_started"&&m++}let g=e.metrics,y={inception_ms:g?.inception_duration_ms??0,construction_ms:g?.construction_duration_ms??0,operations_ms:g?.operations_duration_ms??0},w=g?.validation_pass_rate??0,_=g?.rework_count??0,h=0;for(let k of t){let F=k.regressions_count??0,R=k.tests_failed??0;F>0&&R===0&&(h+=F)}let b=0,S=0;for(let k of t)k.recreation_readiness_score!=null&&(b+=k.recreation_readiness_score,S++);let T=S>0?Math.round(b/S*10)/10:null;return{tests_total:n,tests_passed:r,tests_failed:o,coverage_percentage:i>0?Math.round(s/i*10)/10:null,security_findings:{critical:a,warning:c,info:l},units_completed:d,units_total:t.length,regressions_count:u,gate_bypass_count:p,data_sources:db(t),phases_completed:m,time_per_phase:y,validation_pass_rate:w,rework_count:_,regressions_fixed:h,average_recreation_readiness_score:T}}function db(e){let t=e.some(i=>(i.tests_total??0)>0),n=e.some(i=>i.coverage_percentage!=null),r=e.some(i=>i.security_scan_status==="completed"),o=e.some(i=>i.feature_doc_status==="completed"),s=e.some(i=>i.recreation_readiness_score!=null);return{tests:t?"connected":"pending",coverage:n?"connected":"pending",security:r?"connected":"pending",documentation:o?"connected":"pending",recreation_readiness:s?"connected":"pending"}}function pb(e,t){let n=Ho.join(t.projectPath,"aidlc-docs",t.workflowId,"quality-scorecard.md"),r=["---",`workflow: ${t.workflowId}`,`feature: "${t.featureName}"`,`generated_at: ${new Date().toISOString()}`,`tests_total: ${e.tests_total}`,`tests_passed: ${e.tests_passed}`,`tests_failed: ${e.tests_failed}`,`coverage_percentage: ${e.coverage_percentage??"null"}`,`security_critical: ${e.security_findings.critical}`,`security_warning: ${e.security_findings.warning}`,`security_info: ${e.security_findings.info}`,`units_completed: ${e.units_completed}`,`units_total: ${e.units_total}`,`regressions_count: ${e.regressions_count}`,`gate_bypass_count: ${e.gate_bypass_count}`,`phases_completed: ${e.phases_completed??0}`,`validation_pass_rate: ${e.validation_pass_rate??0}`,`rework_count: ${e.rework_count??0}`,`regressions_fixed: ${e.regressions_fixed??0}`,`average_recreation_readiness_score: ${e.average_recreation_readiness_score??"null"}`,"---",""].join(`
|
|
960
960
|
`),o=e.tests_total>0?Math.round(e.tests_passed/e.tests_total*100):0,s=[`# Quality Scorecard: ${t.featureName}`,"","## Test Results","","| Metric | Value |","|--------|-------|",`| Tests Total | ${e.tests_total} |`,`| Tests Passed | ${e.tests_passed} |`,`| Tests Failed | ${e.tests_failed} |`,`| Pass Rate | ${o}% |`,`| Coverage | ${e.coverage_percentage!=null?e.coverage_percentage+"%":"pending"} |`,`| Regressions | ${e.regressions_count} |`,"","## Security","","| Severity | Count |","|----------|-------|",`| Critical | ${e.security_findings.critical} |`,`| Warning | ${e.security_findings.warning} |`,`| Info | ${e.security_findings.info} |`,"","## Unit Completion","","| Metric | Value |","|--------|-------|",`| Units Completed | ${e.units_completed} |`,`| Units Total | ${e.units_total} |`,`| Gate Bypasses | ${e.gate_bypass_count} |`,"","## Methodology Metrics","","| Metric | Value |","|--------|-------|",`| Phases Completed | ${e.phases_completed??0} |`,`| Inception Time | ${e.time_per_phase?.inception_ms??0}ms |`,`| Construction Time | ${e.time_per_phase?.construction_ms??0}ms |`,`| Operations Time | ${e.time_per_phase?.operations_ms??0}ms |`,`| Validation Pass Rate | ${e.validation_pass_rate??0}% |`,`| Rework Count | ${e.rework_count??0} |`,`| Regressions Fixed | ${e.regressions_fixed??0} |`,"","## Recreation Readiness","","| Metric | Value |","|--------|-------|",`| Average Score | ${e.average_recreation_readiness_score!=null?e.average_recreation_readiness_score:"pending"} |`,"","## Data Sources","","| Source | Status |","|--------|--------|",...Object.entries(e.data_sources).map(([i,a])=>`| ${i} | ${a} |`),""].join(`
|
|
961
|
-
`);return
|
|
962
|
-
`),d={};for(let f of u){let m=f.match(/^(\w+):\s*(.+)$/);if(m){let[,g,y]=m;y.startsWith("[")?d[g]=JSON.parse(y.replace(/'/g,'"')):isNaN(Number(y))?d[g]=y.trim():d[g]=Number(y)}}let p={id:d.id||s.replace(".md",""),type:"intent",title:d.title||"Untitled Intent",parent_id:null,children_ids:[],status:d.status||"pending",assigned_agent:d.assigned_agent||null,estimated_effort:d.estimated_effort||0};o.push(p)}catch(i){console.error(`Failed to parse ${s}:`,i)}return o}catch(t){return console.error(`Failed to read intents from ${e}:`,t),[]}}async function
|
|
961
|
+
`);return Go.mkdirSync(Ho.dirname(n),{recursive:!0}),Go.writeFileSync(n,r+s),n}function Zp(e,t){let n=ub(e),r=pb(n,t);return{data:n,reportPath:r}}var Xn=v(X(),1),ef=v(require("path"),1),fb=10;function tf(e,t){let n=`UNIT-${String(t).padStart(3,"0")}`;if(!e||!e.trim())return`${n}-untitled`;let r=e.toLowerCase().replace(/[_\s]+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"");return r?r.length>60?`${n}-${r.substring(0,60).replace(/-$/,"")}`:`${n}-${r}`:`${n}-untitled`}function oa(e,t){let n=`BOLT-${String(t).padStart(3,"0")}`;if(!e||!e.trim())return`${n}-untitled`;let r=e.toLowerCase().replace(/[_\s]+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"");return r?r.length>60?`${n}-${r.substring(0,60).replace(/-$/,"")}`:`${n}-${r}`:`${n}-untitled`}async function sa(e){try{if(!await Xn.default.pathExists(e))return[];let r=(await Xn.default.readdir(e)).filter(s=>s.startsWith("INTENT-")&&s.endsWith(".md")),o=[];for(let s of r)try{let i=ef.default.join(e,s),c=(await Xn.default.readFile(i,"utf-8")).match(/^---\n([\s\S]*?)\n---/);if(!c){console.error(`No frontmatter found in ${s}`);continue}let u=c[1].split(`
|
|
962
|
+
`),d={};for(let f of u){let m=f.match(/^(\w+):\s*(.+)$/);if(m){let[,g,y]=m;y.startsWith("[")?d[g]=JSON.parse(y.replace(/'/g,'"')):isNaN(Number(y))?d[g]=y.trim():d[g]=Number(y)}}let p={id:d.id||s.replace(".md",""),type:"intent",title:d.title||"Untitled Intent",parent_id:null,children_ids:[],status:d.status||"pending",assigned_agent:d.assigned_agent||null,estimated_effort:d.estimated_effort||0};o.push(p)}catch(i){console.error(`Failed to parse ${s}:`,i)}return o}catch(t){return console.error(`Failed to read intents from ${e}:`,t),[]}}async function ia(e){try{if(!await Xn.default.pathExists(e))return null;let n=await Xn.default.readFile(e,"utf-8"),r=[],o=n.match(/### Proposed UNITs\s*\n([\s\S]*?)(?=\n##[^#]|\n---|\Z|$)/);if(o){let s=o[1],i=/^-\s+\*\*([^*]+)\*\*:\s*(.+)$/gm,a,c=0;for(;(a=i.exec(s))!==null;){let l=a[1].trim(),u=a[2].trim(),d=tf(l,c+1);r.push({id:d,title:l,description:u}),c++}}return{content:n,proposedUnits:r}}catch(t){return console.error(`Failed to parse intent from ${e}:`,t),null}}function aa(e,t,n=fb){let r=t;r.length>n&&(console.warn(`[decomposition] Unit specs (${r.length}) exceed maxUnits limit (${n}). Truncating to ${n}.`),r=r.slice(0,n));let o=[];for(let s=0;s<r.length;s++){let i=r[s],a=tf(i.title,s+1),c={id:a,type:"unit",title:i.title,parent_id:e.id,children_ids:[],status:"pending",assigned_agent:null,estimated_effort:i.estimated_effort};o.push(c),e.children_ids.push(a)}return o}function ca(e){let t=new Map;function n(r,o){t.set(r.id,r);for(let s of r.children_ids){let i=o.find(a=>a.id===s);i&&n(i,o)}}for(let r of e)t.set(r.id,r);return{roots:e,nodes:t}}var Zn=v(X(),1),er=v(require("path"),1);function rf(e,t){let n=[],r=1;for(let o of e){let s=nn(o.title),i=mb(t,s),a=nf(i,"input"),c=nf(i,"output"),l=gb(o,e);n.push({id:`IFACE-${String(r++).padStart(3,"0")}`,unit_id:o.id,name:hb(o.title),inputs:a,outputs:c,dependencies:l,description:`Interface contract for ${o.title}`})}return n}function of(e,t){let n=[],r=1;for(let o of e){let s=t.filter(c=>c.unit_id===o.id),i=[],a=[];for(let c of s){i.push({id:`COMP-${c.id}`,name:c.name,type:"interface"});for(let l of c.dependencies){let u=t.find(d=>d.id===l);u&&a.push({from:`COMP-${u.id}`,to:`COMP-${c.id}`,data:`Data from ${u.name}`,direction:"unidirectional"})}if(wb(c)){let l=`STORE-${c.id}`;i.push({id:l,name:`${c.name}Store`,type:"store"}),a.push({from:`COMP-${c.id}`,to:l,data:"Persisted data",direction:"bidirectional"})}}n.push({id:`DFD-${String(r++).padStart(3,"0")}`,unit_id:o.id,components:i,flows:a,description:`Data flow diagram for ${o.title}`})}return n}function sf(e,t,n){let r=[],o=1;for(let s of e){let i=t.filter(u=>u.unit_id===s.id),a=n.find(u=>u.unit_id===s.id),c=a?a.components.filter(u=>u.type==="store").map(u=>u.name):[],l=_b(s,i);r.push({id:`COMP-${String(o++).padStart(3,"0")}`,unit_id:s.id,name:yb(s.title),responsibilities:l,interfaces_used:i.map(u=>u.id),data_stores:c,description:`Component design for ${s.title}`})}return r}function la(e,t){let n=[];for(let a of e.interfaces)a.inputs.length===0&&a.outputs.length===0&&n.push(`Interface ${a.id} (${a.name}) has no inputs or outputs`);for(let a of e.dataFlows){let c=new Set(a.components.map(l=>l.id));for(let l of a.flows)c.has(l.from)||n.push(`DFD ${a.id}: Flow references invalid source component ${l.from}`),c.has(l.to)||n.push(`DFD ${a.id}: Flow references invalid target component ${l.to}`)}let r=new Set(e.interfaces.map(a=>a.id));for(let a of e.components)for(let c of a.interfaces_used)r.has(c)||n.push(`Component ${a.id} (${a.name}) references invalid interface ${c}`);for(let a of e.components)a.responsibilities.length===0&&n.push(`Component ${a.id} (${a.name}) has no defined responsibilities`);let o=kb(t),s=Sb(e),i=vb(o,s);return{passed:n.length===0,coverage_percentage:i,blocking_issues:n,reviewer:"design-validator",timestamp:new Date().toISOString()}}async function af(e,t,n){let r=er.default.join(e,"aidlc-docs",t,"construction","design");try{await Zn.default.ensureDir(r),await Zn.default.writeJson(er.default.join(r,"interfaces.json"),n.interfaces,{spaces:2}),await Zn.default.writeJson(er.default.join(r,"data-flow.json"),n.dataFlows,{spaces:2}),await Zn.default.writeJson(er.default.join(r,"components.json"),n.components,{spaces:2});let o=la(n,"");await Zn.default.writeJson(er.default.join(r,"validation.json"),o,{spaces:2})}catch(o){throw console.error("Failed to write design artifacts:",o),o}}function nn(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 mb(e,t){let n=e.split(`
|
|
963
963
|
`),r=[];for(let o of n){let s=o.toLowerCase();t.some(i=>s.includes(i))&&r.push(o)}return r.join(`
|
|
964
|
-
`)}function
|
|
965
|
-
`);for(let s of o){let i=s.match(/^(\w+):\s*(.+)$/);if(i){let[,a,c]=i;r[a]=c.trim()}}return r}catch{return null}}function
|
|
964
|
+
`)}function nf(e,t){let n=[],r=/(\w+):\s*(\w+)/g,o;for(;(o=r.exec(e))!==null;)n.push({name:o[1],type:o[2],required:!0,description:`${t} field ${o[1]}`});return n}function gb(e,t){let n=new Set(nn(e.title)),r=[];for(let o of t){if(o.id===e.id)continue;nn(o.title).filter(a=>n.has(a)).length>0&&r.push(o.id)}return r}function hb(e){return e.split(/\s+/).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")+"Interface"}function yb(e){return e.split(/\s+/).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")+"Component"}function wb(e){let t=["store","save","persist","database","repository"],n=e.name.toLowerCase();return t.some(r=>n.includes(r))}function _b(e,t){let n=[];n.push(`Implement ${e.title}`);for(let r of t)r.inputs.length>0&&n.push(`Process inputs for ${r.name}`),r.outputs.length>0&&n.push(`Generate outputs for ${r.name}`);return n}function kb(e){return new Set(nn(e))}function Sb(e){let t=new Set;for(let n of e.interfaces)nn(n.name).forEach(r=>t.add(r)),nn(n.description).forEach(r=>t.add(r));for(let n of e.components)nn(n.name).forEach(r=>t.add(r)),nn(n.description).forEach(r=>t.add(r));return t}function vb(e,t){if(e.size===0)return 100;let n=0;for(let r of e)t.has(r)&&n++;return Math.round(n/e.size*100)}var vn=require("fs"),ua=require("path"),bb=[1,2,4,8,16];function Eb(e){let t=e.match(/^---\n([\s\S]*?)\n---/);if(!t)return null;let n=t[1];try{let r={},o=n.split(`
|
|
965
|
+
`);for(let s of o){let i=s.match(/^(\w+):\s*(.+)$/);if(i){let[,a,c]=i;r[a]=c.trim()}}return r}catch{return null}}function Tb(e){return e.replace(/^---\n[\s\S]*?\n---\n/,"")}function Cb(e){let t=new Map,n=e.split(`
|
|
966
966
|
`),r=null,o=[];for(let s of n){let i=s.match(/^##\s+(.+)$/);i?(r&&t.set(r,o.join(`
|
|
967
967
|
`)),r=i[1].trim(),o=[]):r&&o.push(s)}return r&&t.set(r,o.join(`
|
|
968
|
-
`)),t}function
|
|
969
|
-
`),n=0;for(let r of t)r.trim().match(/^[-*+]\s+/)&&n++;return n}function Rb(e,t,n){let r=[],o=null,s=bb(e);if(!s)return r.push(`${t}: Missing frontmatter`),{isValid:!1,blockingIssues:r,parentIntent:o};let i=["id","title","parent_intent","status","estimated_effort"],a=[];for(let y of i)s[y]||a.push(y);if(a.length>0)return r.push(`${t}: Missing frontmatter fields: ${a.join(", ")}`),{isValid:!1,blockingIssues:r,parentIntent:o};if(o=s.parent_intent,!n.has(o)&&!o.startsWith("intent-"))return r.push(`${t}: References non-existent parent intent: ${o}`),{isValid:!1,blockingIssues:r,parentIntent:o};let c=parseInt(s.estimated_effort,10);if(isNaN(c)||!vb.includes(c))return r.push(`${t}: Invalid effort estimate ${s.estimated_effort} (must be 1, 2, 4, 8, or 16)`),{isValid:!1,blockingIssues:r,parentIntent:o};let l=Eb(e),u=Tb(l),d=["Scope & Responsibility","Interface Contracts","Dependencies","Acceptance Criteria"],p=["Goal","Acceptance Criteria","Implementation Notes"],f=d.every(y=>u.has(y)),m=p.every(y=>u.has(y));if(!f&&!m){let y=d.filter(w=>!u.has(w));return r.push(`${t}: Missing sections: ${y.join(", ")}`),{isValid:!1,blockingIssues:r,parentIntent:o}}let g=u.get("Acceptance Criteria");if(g){if(Cb(g)===0)return r.push(`${t}: No acceptance criteria found`),{isValid:!1,blockingIssues:r,parentIntent:o}}else return r.push(`${t}: Acceptance Criteria section is empty`),{isValid:!1,blockingIssues:r,parentIntent:o};return{isValid:!0,blockingIssues:r,parentIntent:o}}async function pa(e,t){let n=new Date().toISOString(),r=[],o;try{o=(0,En.readdirSync)(e,{withFileTypes:!0})}catch(m){let g=m;return console.error(`[Validation] Failed to read construction directory: ${g.message}`),console.error(`[Validation] Path: ${e}`),{passed:!1,coverage_percentage:0,blocking_issues:[g.code==="ENOENT"?"Units directory not found":g.code==="EACCES"||g.code==="EPERM"?"Permission denied reading units directory":`Failed to read units directory: ${g.message}`],timestamp:n}}let s=o.filter(m=>m.isDirectory()&&m.name!=="design"),i=o.filter(m=>m.isFile()&&m.name.endsWith(".md")&&m.name!=="design.md"),a=new Set,c=[];for(let m of s){let g=m.name,y=(0,da.join)(e,m.name,"spec.md");(0,En.existsSync)(y)&&(a.add(g),c.push({unitId:g,filePath:y}))}for(let m of i){let g=m.name.replace(".md","");a.has(g)||(a.add(g),c.push({unitId:g,filePath:(0,da.join)(e,m.name)}))}if(c.length===0)return{passed:!1,coverage_percentage:0,blocking_issues:["No unit files found in units directory"],timestamp:n};let l=new Set;try{let m=(0,En.readdirSync)(t).filter(g=>g.startsWith("INTENT-")&&g.endsWith(".md"));l=new Set(m.map(g=>g.replace(".md","")))}catch(m){let g=m;return console.error(`[Validation] Failed to read intents directory: ${g.message}`),console.error(`[Validation] Path: ${t}`),{passed:!1,coverage_percentage:0,blocking_issues:[g.code==="ENOENT"?"Intents directory not found":g.code==="EACCES"||g.code==="EPERM"?"Permission denied reading intents directory":`Failed to read intents directory: ${g.message}`],timestamp:n}}let u=new Set,d=0,p=c.length;for(let{unitId:m,filePath:g}of c){let y;try{y=(0,En.readFileSync)(g,"utf-8")}catch(_){let h=_;console.error(`[Validation] Failed to read unit file: ${h.message}`),console.error(`[Validation] Path: ${g}`);let b=h.code==="ENOENT"?`Unit file not found: ${m}`:h.code==="EACCES"||h.code==="EPERM"?`Permission denied reading unit file: ${m}`:`Failed to read unit file ${m}: ${h.message}`;r.push(b);continue}let w=Rb(y,m,l);r.push(...w.blockingIssues),w.parentIntent&&l.has(w.parentIntent)&&u.add(w.parentIntent),w.isValid&&d++}for(let m of l)u.has(m)||r.push(`Intent ${m} has no unit children`);let f=Math.round(d/p*100);return{passed:r.length===0&&d===p,coverage_percentage:f,blocking_issues:r,timestamp:n}}Uo();Z();function lf(e,t,n){let o=(n.construction_bolts?Object.keys(n.construction_bolts).length:0)+1,s=sa(e.title,o),i=e,a=Array.isArray(i.acceptance_criteria)&&i.acceptance_criteria.length>0?i.acceptance_criteria:["Implement as described in intent"],c=Array.isArray(i.target_files)?i.target_files:[];return{id:s,type:"bolt",title:e.title,parent_id:e.id,children_ids:[],status:"pending",assigned_agent:null,estimated_effort:e.estimated_effort,parent_unit_id:e.id,sequence:1,scope:t.substring(0,500)||e.title,acceptance_criteria:a,target_files:c,dependencies:[],requires_bolts:[],enables_bolts:[],requires_units:[],blocked:!1,depth_target:1,express_mode:!0,estimated_effort_hours:e.estimated_effort,requirements:[],stories:[],docs_impact:["none"]}}var xb=v(require("path"),1);function Yo(){return{status:"not_started",started_at:null,completed_at:null,failure_count:0,last_error:null,artifact_path:null}}function uf(e,t){t.construction_bolts||(t.construction_bolts={});for(let n of e){let r={bolt_id:n.id,parent_unit_id:n.parent_unit_id,status:"planned",stages:{elaboration:Yo(),code_generation:Yo(),build_and_test:Yo(),review:Yo()},failure_count:0,last_error:null,review_score:null,acknowledged_by:null,acknowledged_at:null,requires_bolts:n.requires_bolts??[],enables_bolts:n.enables_bolts??[],requires_units:n.requires_units??[],blocked:n.blocked??!1};t.construction_bolts[n.id]=r}}ce();var Pb=["elaboration","code_generation","build_and_test","review"],Ab={elaboration:"onElaboration",code_generation:"onCodeGeneration",build_and_test:"onBuildAndTest",review:"onReview"},Ib={build_and_test:"built",review:"done"};async function Ob(e,t,n,r){let o=Ab[t];return t==="build_and_test"?e.onBuildAndTest(n,r,n.target_files??[]):e[o](n,r)}async function $b(e,t,n,r,o){let s=t.construction_bolts[e.id];if(t.active_bolt_id=e.id,s.blocked)return t.active_bolt_id=null,await P(n,t),{status:s.status,stages:{...s.stages}};s.status="in_progress",await P(n,t);for(let i of Pb){let a=s.stages[i];if(e.express_mode&&i==="elaboration"){a.status="skipped",a.completed_at=new Date().toISOString(),await P(n,t);continue}i==="review"&&(s.status="in_review",await P(n,t)),t.active_bolt_stage=i,a.status="in_progress",a.started_at=new Date().toISOString(),await P(n,t);let c=await Ob(o,i,e,n);if(c.success){a.status="completed",a.completed_at=new Date().toISOString(),c.artifact_path&&(a.artifact_path=c.artifact_path);let l=Ib[i];l&&(s.status=l),await P(n,t)}else{if(a.failure_count+=1,a.last_error=c.error??"Unknown error",s.failure_count+=1,s.last_error=a.last_error,a.failure_count>=2){a.status="failed",s.status="failed",await P(n,t);break}a.status="not_started",await P(n,t);break}}if(t.active_bolt_id=null,s.status==="done"&&t.construction_bolts){let i=e.id;for(let a of Object.values(t.construction_bolts))if(a.requires_bolts?.includes(i)){let c=a.requires_bolts.every(u=>{let d=t.construction_bolts[u];return d&&d.status==="done"}),l=(a.requires_units??[]).every(u=>{let d=t.construction_units?.[u];return d?Object.values(d.stages).every(p=>p.status==="completed"||p.status==="skipped"):!1});c&&l&&(a.blocked=!1)}}return t.active_bolt_stage=null,await P(n,t),{status:s.status,stages:{...s.stages}}}var df={execute:$b};ha();var LT={unit:"olympian","code-generation":"olympian",design:"olympian"},ys=class{projectPath;workflowId;tree=null;currentStage="unit";totalUnits=0;totalCodeGenerations=0;totalEffort=0;constructor(t,n){this.projectPath=t,this.workflowId=n}async execute(t,n={}){let{depth:r="MEDIUM",max_units:o=10,max_code_gen_per_unit:s=8,max_total_code_gen:i=50,checkpointStatus:a,onCheckpointSave:c}=n;if(a==="awaiting_dev_review")return{passed:!1,coverage_percentage:0,blocking_issues:["Construction blocked: developer review of technical specification required (Risk Tier 3)."],reviewer:"construction-executor",timestamp:new Date().toISOString()};if(console.log(`[ConstructionExecutor] Starting Construction phase execution (depth: ${r})`),(n.pathwayType==="brownfield-enhancement"||n.pathwayType==="brownfield-refactor"||n.pathwayType==="bugfix")&&n.testCommand)try{let{captureBaseline:p}=await Promise.resolve().then(()=>(wa(),ya));await p(this.projectPath,this.workflowId,n.testCommand),console.log("[ConstructionExecutor] Regression baseline captured")}catch(p){console.error("[ConstructionExecutor] Baseline capture failed (non-fatal):",p)}if(r==="SHALLOW")return this.executeShallowViaBolt();this.currentStage="unit";let u=await this.executeDecompositionPhase(o,s,i,r);if(!u.passed)return console.error("[ConstructionExecutor] Decomposition phase failed"),u;if(console.log("[ConstructionExecutor] Decomposition phase complete"),c)try{await c()}catch(p){console.error("[ConstructionExecutor] Checkpoint save callback failed:",p)}this.currentStage="design";let d=await this.executeDesignStage(t);return d.passed?(console.log("[ConstructionExecutor] Design stage complete"),{passed:!0,coverage_percentage:100,blocking_issues:[],reviewer:"construction-executor",timestamp:new Date().toISOString()}):(console.error("[ConstructionExecutor] Design stage failed validation"),d)}getProgress(){let t=0,n=0;if(this.tree)for(let i of this.tree.nodes.values())i.type==="unit"&&(t++,i.status==="complete"&&n++);let r=this.totalCodeGenerations,o=0,s=0;return this.currentStage==="unit"?s=t>0?Math.round(n/t*50):0:this.currentStage==="code-generation"?s=50+(r>0?Math.round(o/r*25):0):this.currentStage==="design"&&(s=100),{current_stage:this.currentStage,units_total:t,units_complete:n,code_gen_total:r,code_gen_complete:o,design_complete:this.currentStage==="design",overall_percentage:s}}getDecompositionSummary(){return{units:this.totalUnits,codeGenerations:this.totalCodeGenerations,totalEffort:this.totalEffort}}async handleZeroBoltUnit(t,n={}){let r=n.projectPath||this.projectPath,o=n.workflowId||this.workflowId,s=await A(r,o);return!s||Object.values(s.construction_bolts??{}).filter(a=>a.parent_unit_id===t).length>0?!1:(s.construction_units||(s.construction_units={}),s.construction_units[t]&&(s.construction_units[t].code_generation_status="completed"),zo(r,o,{timestamp:new Date().toISOString(),phase:"construction",action:`Unit ${t} auto-fulfilled (zero bolts)`,actor:"construction-executor",reason:null}),await P(r,s),console.log(`[ConstructionExecutor] Unit ${t} auto-fulfilled: 0 bolts registered`),!0)}async executeCodeGenerationWithPlanApproval(t,n={}){let r=n.projectPath||this.projectPath,o=n.workflowId||this.workflowId,{buildCodePlanPath:s,dispatchCodeGeneration:i,buildCodeGenerationPrompt:a}=await Promise.resolve().then(()=>(ds(),us)),c=s(r,o,t),l=await i(r,o,t),u=a(l.context.intentSummary2,l.context.intentSummary,l.context.unitSpec,c,l.context.architectureContext);return{status:"awaiting_code_plan_approval",codePlanPath:c,prompt:u}}async approveCodePlan(t,n){let{buildCodePlanPath:r,dispatchCodeGeneration:o,buildCodeGenerationPrompt:s}=await Promise.resolve().then(()=>(ds(),us)),{addGateAuditEntry:i}=await Promise.resolve().then(()=>(Z(),vn)),a=r(this.projectPath,this.workflowId,t);if(!await Y.default.pathExists(a))throw new Error(`Code plan file not found at ${a}. The agent must create the plan before it can be approved.`);let l=H.default.join(this.projectPath,"aidlc-docs",this.workflowId,"manifest.json");try{i(l,{phase:"construction",action:"approved",actor:"human",reason:n||`Code plan for ${t} approved by developer`})}catch(p){console.error(`[ConstructionExecutor] Failed to record gate audit for ${t}:`,p)}let u=await o(this.projectPath,this.workflowId,t);return{status:"executing_code_plan",prompt:s(u.context.intentSummary2,u.context.intentSummary,u.context.unitSpec,void 0,u.context.architectureContext)}}async autoApproveCodePlan(t,n){let{addGateAuditEntry:r}=await Promise.resolve().then(()=>(Z(),vn)),o=H.default.join(this.projectPath,"aidlc-docs",this.workflowId,"manifest.json"),s=n>=3;try{r(o,{phase:"construction",action:"approved",actor:"trust",reason:s?`Code plan for ${t} auto-approved silently (trust level ${n})`:`Code plan for ${t} auto-approved with notification (trust level ${n})`})}catch(u){console.error(`[ConstructionExecutor] Failed to record gate audit for ${t}:`,u)}s||console.log(`[ConstructionExecutor] Code plan for ${t} auto-approved (trust level ${n})`);let{dispatchCodeGeneration:i,buildCodeGenerationPrompt:a}=await Promise.resolve().then(()=>(ds(),us)),c=await i(this.projectPath,this.workflowId,t);return{status:"executing_code_plan",prompt:a(c.context.intentSummary2,c.context.intentSummary,c.context.unitSpec,void 0,c.context.architectureContext)}}async executeTestGeneration(t,n={}){let r=n.projectPath||this.projectPath,o=n.workflowId||this.workflowId,i=await A(r,o)??{schema_version:"3.0.0",workflow_id:o,feature_name:"",current_phase:"construction",current_stage:"code-generation",status:"in_progress",phases:{},manifest_path:"",trust_state_path:"",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),construction_units:{}};i.construction_units||(i.construction_units={});let a=i.construction_units[t]??{unitId:t,stages:{"functional-design":{status:"not_started",artifact_path:null,completed_at:null,failure_count:0,last_error:null},"nfr-requirements":{status:"not_started",artifact_path:null,completed_at:null,failure_count:0,last_error:null},"nfr-design":{status:"not_started",artifact_path:null,completed_at:null,failure_count:0,last_error:null},"infrastructure-design":{status:"not_started",artifact_path:null,completed_at:null,failure_count:0,last_error:null},"code-generation":{status:"not_started",artifact_path:null,completed_at:null,failure_count:0,last_error:null},"test-generation":{status:"not_started",artifact_path:null,completed_at:null,failure_count:0,last_error:null}},code_plan_path:null,code_generation_status:"not_started",tests_total:0,tests_passed:0,tests_failed:0,test_framework:"unknown",test_generation_status:"not_started"};a.stages["test-generation"].status="in_progress",a.test_generation_status="in_progress",i.construction_units[t]=a,await P(r,i);let c=H.default.join(r,"aidlc-docs",o,"construction",t,"testing");await Y.default.ensureDir(c);let l=H.default.join(c,"test-report.md"),u="",d=H.default.join(r,"aidlc-docs",o,"construction",t,"code","code-summary.md");try{await Y.default.pathExists(d)&&(u=await Y.default.readFile(d,"utf-8"))}catch{}let p=await this.detectTestFramework(r),f=new Date().toISOString(),m=this.buildTestReportScaffold(t,p,u,f);await Y.default.writeFile(l,m,"utf-8");let g=0,y=0,w=0,_=0,h=0;n.currentResults&&n.currentResults.length>0&&(g=n.currentResults.length,y=n.currentResults.filter(C=>C.status==="passed").length,w=n.currentResults.filter(C=>C.status==="failed").length);let b=!1,S=0,T=H.default.join(r,"aidlc-docs",o,"construction","regression-baseline.json");if(n.currentResults&&w>0&&await Y.default.pathExists(T))try{let{compareAgainstBaseline:C,writeRegressionReport:$}=await Promise.resolve().then(()=>(wa(),ya)),{categorizeFailure:D,buildRegressionSummary:x}=await Promise.resolve().then(()=>(Sm(),km)),E=await Y.default.readJson(T);b=!0;let L=C(E,n.currentResults),j=[],K=[];for(let $e of L.new_failures){let Dr=E.tests.find(Jt=>Jt.name===$e.name)??null,Ke=D($e.name,Dr,[]);j.push(Ke),K.push({test_name:$e.name,file_path:$e.filePath,category:Ke,rationale:Ke==="legitimate_regression"?"Test was passing in baseline, now fails":Ke==="flaky"?"Test passed on re-run without code changes":Ke==="intentional_change"?"New test not present in baseline":"Test was already failing in baseline"})}let q=x(K.map($e=>({test_name:$e.test_name,file_path:$e.file_path})),j);_=q.regressions_count,h=q.flaky_count,S=q.regressions_count;let hn={workflow_id:o,unit_id:t,baseline_captured_at:E.captured_at,compared_at:new Date().toISOString(),failures:K,total_regressions:j.filter($e=>$e!=="pre_existing_failure").length,legitimate_regressions:q.regressions_count};await $(r,o,t,hn)}catch(C){console.error(`[ConstructionExecutor] Regression analysis failed for ${t} (non-fatal):`,C)}let k="completed",F;if(n.allowFailures!==!0&&(g===0?(k="blocked",F=`No tests detected for unit ${t}. Set allowFailures: true to override.`):b&&S>0?(k="blocked",F=`${S} legitimate regression(s) for unit ${t}. Flaky: ${h} (non-blocking). Fix regressions before proceeding.`):!b&&w>0&&(k="blocked",F=`${w} test(s) failed for unit ${t}. Set allowFailures: true to override.`)),a.stages["test-generation"].status=k==="completed"?"completed":"in_progress",a.stages["test-generation"].artifact_path=l,k==="completed"&&(a.stages["test-generation"].completed_at=f),a.tests_total=g,a.tests_passed=y,a.tests_failed=w,a.test_framework=p,a.test_generation_status=k==="completed"?"completed":"in_progress",a.regressions_count=_,a.flaky_count=h,i.construction_units[t]=a,await P(r,i),k==="completed")try{let{updateArchitectureModel:C}=await Promise.resolve().then(()=>(Jr(),Zo)),$=await this.discoverUnitFiles(r,o,t);$.length>0&&(await C(r,$),a.architecture_model_status="updated",i.construction_units[t]=a,await P(r,i))}catch(C){console.error(`[ConstructionExecutor] Architecture model update failed for ${t} (non-blocking):`,C),a.architecture_model_status="failed",i.construction_units[t]=a;try{await P(r,i)}catch($){console.warn("[ConstructionExecutor] Failed to save checkpoint after architecture model failure:",$)}}let R;if(k==="completed")try{let{runValidationPipeline:C,shouldSkipValidator:$,updateCheckpointForValidator:D,createQualityValidator:x,createMutationValidator:E,createTraceabilityValidator:L,createContractValidator:j,createCoverageValidator:K}=await Promise.resolve().then(()=>(Gm(),Bm)),q=await this.discoverUnitFiles(r,o,t),hn=this.detectApiSurfaceFiles(q),$e=this.deriveWorkflowDepth(i),Dr={timeoutBudgetMs:3e4,allowFailures:n.allowFailures??!1,workflowDepth:$e,unitId:t,unitFiles:q,apiSurfaceFiles:hn,projectPath:r,workflowId:o},Ke=new Map;Ke.set("quality",x()),$("mutation",Dr).skip||Ke.set("mutation",E()),Ke.set("traceability",L()),$("contract",Dr).skip||Ke.set("contract",j()),Ke.set("coverage",K()),R=await C(Ke,Dr);for(let{validator:Jt,result:Ot}of R.results){let __=Ot.status==="passed"||Ot.status==="warned"?"completed":Ot.status==="skipped"?"skipped":"in_progress",k_=Jt==="coverage"?Ot.coverage_percentage:void 0,S_=Jt==="coverage"?Ot.findings.filter(v_=>v_.category==="uncovered-critical-file").length:void 0;await D(r,o,t,Jt,__,k_,S_)}if(!n.allowFailures){let Jt=R.results.filter(Ot=>Ot.result.status==="failed");Jt.length>0&&(k="blocked",F=`Validation blocked: ${Jt.map(Ot=>Ot.validator).join(", ")}`,a.stages["test-generation"].status="in_progress",a.test_generation_status="in_progress",i.construction_units[t]=a,await P(r,i))}}catch(C){console.error(`[ConstructionExecutor] Validation pipeline failed for ${t} (non-fatal):`,C)}return{status:k,unitId:t,tests_total:g,tests_passed:y,tests_failed:w,test_framework:p,reportPath:l,blockingReason:F,regressions_count:_,flaky_count:h,validationPipeline:R}}async validateBugfixTestRequirement(t,n={}){try{let r=n.projectPath||this.projectPath,o=n.workflowId||this.workflowId,s=await A(r,o);if(!s)return{valid:!1,reason:"checkpoint not found"};if(s.pathway_type!=="bugfix")return{valid:!0};let i=s.construction_units?.[t];return i?i.stages?.["test-generation"]?.status!=="completed"?{valid:!1,reason:"test-generation stage not completed for bugfix unit"}:(i.tests_total??0)===0?{valid:!1,reason:"bugfix unit must have at least one test (tests_total === 0)"}:{valid:!0}:{valid:!1,reason:`no unit progress found for unit ${t}`}}catch(r){let o=r instanceof Error?r.message:String(r);return console.error(`[ConstructionExecutor] validateBugfixTestRequirement error for ${t}:`,r),{valid:!1,reason:`validation error: ${o}`}}}async executeDocumentationGeneration(t,n={}){let r=n.projectPath||this.projectPath,o=n.workflowId||this.workflowId,s=await A(r,o),i=s?.depth_score?s.depth_score<=12?"minimal":s.depth_score<=20?"standard":"comprehensive":"standard",a=s?.pathway_type||"brownfield-enhancement",c=await this.discoverUnitFiles(r,o,t),l={unitId:t,workflowId:o,projectPath:r,depth:i,pathway:a,unitFiles:c},u=Vp(l),d,p=0,f=[],m;if(u.status==="completed"){try{let g=qp({projectPath:r,workflowId:o,unitId:t,modifiedFiles:l.unitFiles||[]});d={status:g.impactScan.status,path:g.impactScan.reportPath},p=g.adrCount,g.adrEntries&&(f=g.adrEntries)}catch{}if(u.path&&a!=="bugfix"&&i!=="minimal")try{let g=s?.construction_units?.[t];m=Zi({featureDocPath:u.path,projectPath:r,depth:i,pathway:a,override:g?.recreation_readiness_override,overrideRationale:g?.recreation_readiness_override_rationale??void 0})}catch{}}if(s?.construction_units?.[t]){let g=s.construction_units[t];g.feature_doc_status=u.status==="completed"?"completed":"not_started",g.feature_doc_path=u.path,g.impact_scan_status=d?.status==="completed"?"completed":"not_started",g.impact_scan_report_path=d?.path??null,g.adr_count=p,g.adr_entries=f.length>0?f:void 0,m&&(g.recreation_readiness_score=m.overall_score,g.recreation_readiness_dimensions=m.dimensions??null),u.status==="completed"&&(g.doc_generation_agent=LT["code-generation"],g.doc_generation_prompt=Hp(l)),await P(r,s)}return{featureDoc:u,impactScan:d,adrCount:p,recreationReadiness:m}}async executeUnitCompletion(t,n={}){let r=n.projectPath||this.projectPath,o=n.workflowId||this.workflowId,s=await this.executeTestGeneration(t,n);if(s.status==="completed"){try{let i=await this.discoverUnitFiles(r,o,t);i.length>0&&Yp(r,i)}catch(i){console.error(`[ConstructionExecutor] Secrets management failed for ${t} (non-blocking):`,i)}try{let i=await this.discoverUnitFiles(r,o,t),a=await Zp({projectPath:r,workflowId:o,unitId:t,includeGlobs:i.length>0?i:void 0}),c=await A(r,o);if(c?.construction_units?.[t]){let l=c.construction_units[t];l.security_scan_status=a.status==="completed"?"completed":a.status==="failed"?"in_progress":"not_started",l.security_findings_critical=a.findings.filter(u=>u.severity==="critical").length,l.security_findings_warning=a.findings.filter(u=>u.severity==="warning").length,l.security_findings_info=a.findings.filter(u=>u.severity==="info").length,await P(r,c)}}catch(i){console.error(`[ConstructionExecutor] Security scan failed for ${t} (non-blocking):`,i)}if(!n.skipDocumentation){let i=await this.executeDocumentationGeneration(t,{projectPath:r,workflowId:o});return{testGeneration:s,documentation:i}}}return{testGeneration:s}}async executeSmokeTest(t={}){let n=t.projectPath||this.projectPath,r=t.workflowId||this.workflowId,o=await A(n,r);if(!o||!o.construction_units)return{status:"not_run",reportPath:null};let s=o.construction_units,i=Object.keys(s);if(i.length===0)return{status:"not_run",reportPath:null};let a=0,c=0,l=0,u=0,d=0,p=0,f=0,m=0,g=[];for(let T of i){let k=s[T],F=k.tests_total??0,R=k.tests_passed??0,O=k.tests_failed??0,C=F-R-O,$=k.regressions_count??0,D=k.flaky_count??0;F>0&&(f++,O===0&&m++),a+=F,c+=R,l+=O,u+=Math.max(0,C),d+=$,p+=D;let x=F===0?"\u26A0\uFE0F":O===0?"\u2705":"\u274C";g.push(`| ${T} | ${F} | ${R} | ${O} | ${$} | ${D} | ${x} |`)}let y=a===0?"not_run":l===0?"passed":"failed",w=H.default.join(n,"aidlc-docs",r,"construction","build-and-test");await Y.default.ensureDir(w);let _=H.default.join(w,"test-report.md"),h=new Date().toISOString(),b=`# Build-Level Test Report
|
|
968
|
+
`)),t}function Rb(e){let t=e.split(`
|
|
969
|
+
`),n=0;for(let r of t)r.trim().match(/^[-*+]\s+/)&&n++;return n}function xb(e,t,n){let r=[],o=null,s=Eb(e);if(!s)return r.push(`${t}: Missing frontmatter`),{isValid:!1,blockingIssues:r,parentIntent:o};let i=["id","title","parent_intent","status","estimated_effort"],a=[];for(let y of i)s[y]||a.push(y);if(a.length>0)return r.push(`${t}: Missing frontmatter fields: ${a.join(", ")}`),{isValid:!1,blockingIssues:r,parentIntent:o};if(o=s.parent_intent,!n.has(o)&&!o.startsWith("intent-"))return r.push(`${t}: References non-existent parent intent: ${o}`),{isValid:!1,blockingIssues:r,parentIntent:o};let c=parseInt(s.estimated_effort,10);if(isNaN(c)||!bb.includes(c))return r.push(`${t}: Invalid effort estimate ${s.estimated_effort} (must be 1, 2, 4, 8, or 16)`),{isValid:!1,blockingIssues:r,parentIntent:o};let l=Tb(e),u=Cb(l),d=["Scope & Responsibility","Interface Contracts","Dependencies","Acceptance Criteria"],p=["Goal","Acceptance Criteria","Implementation Notes"],f=d.every(y=>u.has(y)),m=p.every(y=>u.has(y));if(!f&&!m){let y=d.filter(w=>!u.has(w));return r.push(`${t}: Missing sections: ${y.join(", ")}`),{isValid:!1,blockingIssues:r,parentIntent:o}}let g=u.get("Acceptance Criteria");if(g){if(Rb(g)===0)return r.push(`${t}: No acceptance criteria found`),{isValid:!1,blockingIssues:r,parentIntent:o}}else return r.push(`${t}: Acceptance Criteria section is empty`),{isValid:!1,blockingIssues:r,parentIntent:o};return{isValid:!0,blockingIssues:r,parentIntent:o}}async function da(e,t){let n=new Date().toISOString(),r=[],o;try{o=(0,vn.readdirSync)(e,{withFileTypes:!0})}catch(m){let g=m;return console.error(`[Validation] Failed to read construction directory: ${g.message}`),console.error(`[Validation] Path: ${e}`),{passed:!1,coverage_percentage:0,blocking_issues:[g.code==="ENOENT"?"Units directory not found":g.code==="EACCES"||g.code==="EPERM"?"Permission denied reading units directory":`Failed to read units directory: ${g.message}`],timestamp:n}}let s=o.filter(m=>m.isDirectory()&&m.name!=="design"),i=o.filter(m=>m.isFile()&&m.name.endsWith(".md")&&m.name!=="design.md"),a=new Set,c=[];for(let m of s){let g=m.name,y=(0,ua.join)(e,m.name,"spec.md");(0,vn.existsSync)(y)&&(a.add(g),c.push({unitId:g,filePath:y}))}for(let m of i){let g=m.name.replace(".md","");a.has(g)||(a.add(g),c.push({unitId:g,filePath:(0,ua.join)(e,m.name)}))}if(c.length===0)return{passed:!1,coverage_percentage:0,blocking_issues:["No unit files found in units directory"],timestamp:n};let l=new Set;try{let m=(0,vn.readdirSync)(t).filter(g=>g.startsWith("INTENT-")&&g.endsWith(".md"));l=new Set(m.map(g=>g.replace(".md","")))}catch(m){let g=m;return console.error(`[Validation] Failed to read intents directory: ${g.message}`),console.error(`[Validation] Path: ${t}`),{passed:!1,coverage_percentage:0,blocking_issues:[g.code==="ENOENT"?"Intents directory not found":g.code==="EACCES"||g.code==="EPERM"?"Permission denied reading intents directory":`Failed to read intents directory: ${g.message}`],timestamp:n}}let u=new Set,d=0,p=c.length;for(let{unitId:m,filePath:g}of c){let y;try{y=(0,vn.readFileSync)(g,"utf-8")}catch(_){let h=_;console.error(`[Validation] Failed to read unit file: ${h.message}`),console.error(`[Validation] Path: ${g}`);let b=h.code==="ENOENT"?`Unit file not found: ${m}`:h.code==="EACCES"||h.code==="EPERM"?`Permission denied reading unit file: ${m}`:`Failed to read unit file ${m}: ${h.message}`;r.push(b);continue}let w=xb(y,m,l);r.push(...w.blockingIssues),w.parentIntent&&l.has(w.parentIntent)&&u.add(w.parentIntent),w.isValid&&d++}for(let m of l)u.has(m)||r.push(`Intent ${m} has no unit children`);let f=Math.round(d/p*100);return{passed:r.length===0&&d===p,coverage_percentage:f,blocking_issues:r,timestamp:n}}Mo();Z();function cf(e,t,n){let o=(n.construction_bolts?Object.keys(n.construction_bolts).length:0)+1,s=oa(e.title,o),i=e,a=Array.isArray(i.acceptance_criteria)&&i.acceptance_criteria.length>0?i.acceptance_criteria:["Implement as described in intent"],c=Array.isArray(i.target_files)?i.target_files:[];return{id:s,type:"bolt",title:e.title,parent_id:e.id,children_ids:[],status:"pending",assigned_agent:null,estimated_effort:e.estimated_effort,parent_unit_id:e.id,sequence:1,scope:t.substring(0,500)||e.title,acceptance_criteria:a,target_files:c,dependencies:[],requires_bolts:[],enables_bolts:[],requires_units:[],blocked:!1,depth_target:1,express_mode:!0,estimated_effort_hours:e.estimated_effort,requirements:[],stories:[],docs_impact:["none"]}}var Pb=v(require("path"),1);function qo(){return{status:"not_started",started_at:null,completed_at:null,failure_count:0,last_error:null,artifact_path:null}}function lf(e,t){t.construction_bolts||(t.construction_bolts={});for(let n of e){let r={bolt_id:n.id,parent_unit_id:n.parent_unit_id,status:"planned",stages:{elaboration:qo(),code_generation:qo(),build_and_test:qo(),review:qo()},failure_count:0,last_error:null,review_score:null,acknowledged_by:null,acknowledged_at:null,requires_bolts:n.requires_bolts??[],enables_bolts:n.enables_bolts??[],requires_units:n.requires_units??[],blocked:n.blocked??!1};t.construction_bolts[n.id]=r}}ce();var Ab=["elaboration","code_generation","build_and_test","review"],Ib={elaboration:"onElaboration",code_generation:"onCodeGeneration",build_and_test:"onBuildAndTest",review:"onReview"},Ob={build_and_test:"built",review:"done"};async function $b(e,t,n,r){let o=Ib[t];return t==="build_and_test"?e.onBuildAndTest(n,r,n.target_files??[]):e[o](n,r)}async function Db(e,t,n,r,o){let s=t.construction_bolts[e.id];if(t.active_bolt_id=e.id,s.blocked)return t.active_bolt_id=null,await P(n,t),{status:s.status,stages:{...s.stages}};s.status="in_progress",await P(n,t);for(let i of Ab){let a=s.stages[i];if(e.express_mode&&i==="elaboration"){a.status="skipped",a.completed_at=new Date().toISOString(),await P(n,t);continue}i==="review"&&(s.status="in_review",await P(n,t)),t.active_bolt_stage=i,a.status="in_progress",a.started_at=new Date().toISOString(),await P(n,t);let c=await $b(o,i,e,n);if(c.success){a.status="completed",a.completed_at=new Date().toISOString(),c.artifact_path&&(a.artifact_path=c.artifact_path);let l=Ob[i];l&&(s.status=l),await P(n,t)}else{if(a.failure_count+=1,a.last_error=c.error??"Unknown error",s.failure_count+=1,s.last_error=a.last_error,a.failure_count>=2){a.status="failed",s.status="failed",await P(n,t);break}a.status="not_started",await P(n,t);break}}if(t.active_bolt_id=null,s.status==="done"&&t.construction_bolts){let i=e.id;for(let a of Object.values(t.construction_bolts))if(a.requires_bolts?.includes(i)){let c=a.requires_bolts.every(u=>{let d=t.construction_bolts[u];return d&&d.status==="done"}),l=(a.requires_units??[]).every(u=>{let d=t.construction_units?.[u];return d?Object.values(d.stages).every(p=>p.status==="completed"||p.status==="skipped"):!1});c&&l&&(a.blocked=!1)}}return t.active_bolt_stage=null,await P(n,t),{status:s.status,stages:{...s.stages}}}var uf={execute:Db};ga();var UT={unit:"olympian","code-generation":"olympian",design:"olympian"},gs=class{projectPath;workflowId;tree=null;currentStage="unit";totalUnits=0;totalCodeGenerations=0;totalEffort=0;constructor(t,n){this.projectPath=t,this.workflowId=n}async execute(t,n={}){let{depth:r="MEDIUM",max_units:o=10,max_code_gen_per_unit:s=8,max_total_code_gen:i=50,checkpointStatus:a,onCheckpointSave:c}=n;if(a==="awaiting_dev_review")return{passed:!1,coverage_percentage:0,blocking_issues:["Construction blocked: developer review of technical specification required (Risk Tier 3)."],reviewer:"construction-executor",timestamp:new Date().toISOString()};if(console.log(`[ConstructionExecutor] Starting Construction phase execution (depth: ${r})`),(n.pathwayType==="brownfield-enhancement"||n.pathwayType==="brownfield-refactor"||n.pathwayType==="bugfix")&&n.testCommand)try{let{captureBaseline:p}=await Promise.resolve().then(()=>(ya(),ha));await p(this.projectPath,this.workflowId,n.testCommand),console.log("[ConstructionExecutor] Regression baseline captured")}catch(p){console.error("[ConstructionExecutor] Baseline capture failed (non-fatal):",p)}if(r==="SHALLOW")return this.executeShallowViaBolt();this.currentStage="unit";let u=await this.executeDecompositionPhase(o,s,i,r);if(!u.passed)return console.error("[ConstructionExecutor] Decomposition phase failed"),u;if(console.log("[ConstructionExecutor] Decomposition phase complete"),c)try{await c()}catch(p){console.error("[ConstructionExecutor] Checkpoint save callback failed:",p)}this.currentStage="design";let d=await this.executeDesignStage(t);return d.passed?(console.log("[ConstructionExecutor] Design stage complete"),{passed:!0,coverage_percentage:100,blocking_issues:[],reviewer:"construction-executor",timestamp:new Date().toISOString()}):(console.error("[ConstructionExecutor] Design stage failed validation"),d)}getProgress(){let t=0,n=0;if(this.tree)for(let i of this.tree.nodes.values())i.type==="unit"&&(t++,i.status==="complete"&&n++);let r=this.totalCodeGenerations,o=0,s=0;return this.currentStage==="unit"?s=t>0?Math.round(n/t*50):0:this.currentStage==="code-generation"?s=50+(r>0?Math.round(o/r*25):0):this.currentStage==="design"&&(s=100),{current_stage:this.currentStage,units_total:t,units_complete:n,code_gen_total:r,code_gen_complete:o,design_complete:this.currentStage==="design",overall_percentage:s}}getDecompositionSummary(){return{units:this.totalUnits,codeGenerations:this.totalCodeGenerations,totalEffort:this.totalEffort}}async handleZeroBoltUnit(t,n={}){let r=n.projectPath||this.projectPath,o=n.workflowId||this.workflowId,s=await A(r,o);return!s||Object.values(s.construction_bolts??{}).filter(a=>a.parent_unit_id===t).length>0?!1:(s.construction_units||(s.construction_units={}),s.construction_units[t]&&(s.construction_units[t].code_generation_status="completed"),Ko(r,o,{timestamp:new Date().toISOString(),phase:"construction",action:`Unit ${t} auto-fulfilled (zero bolts)`,actor:"construction-executor",reason:null}),await P(r,s),console.log(`[ConstructionExecutor] Unit ${t} auto-fulfilled: 0 bolts registered`),!0)}async executeCodeGenerationWithPlanApproval(t,n={}){let r=n.projectPath||this.projectPath,o=n.workflowId||this.workflowId,{buildCodePlanPath:s,dispatchCodeGeneration:i,buildCodeGenerationPrompt:a}=await Promise.resolve().then(()=>(ls(),cs)),c=s(r,o,t),l=await i(r,o,t),u=a(l.context.intentSummary2,l.context.intentSummary,l.context.unitSpec,c,l.context.architectureContext);return{status:"awaiting_code_plan_approval",codePlanPath:c,prompt:u}}async approveCodePlan(t,n){let{buildCodePlanPath:r,dispatchCodeGeneration:o,buildCodeGenerationPrompt:s}=await Promise.resolve().then(()=>(ls(),cs)),{addGateAuditEntry:i}=await Promise.resolve().then(()=>(Z(),kn)),a=r(this.projectPath,this.workflowId,t);if(!await Y.default.pathExists(a))throw new Error(`Code plan file not found at ${a}. The agent must create the plan before it can be approved.`);let l=H.default.join(this.projectPath,"aidlc-docs",this.workflowId,"manifest.json");try{i(l,{phase:"construction",action:"approved",actor:"human",reason:n||`Code plan for ${t} approved by developer`})}catch(p){console.error(`[ConstructionExecutor] Failed to record gate audit for ${t}:`,p)}let u=await o(this.projectPath,this.workflowId,t);return{status:"executing_code_plan",prompt:s(u.context.intentSummary2,u.context.intentSummary,u.context.unitSpec,void 0,u.context.architectureContext)}}async autoApproveCodePlan(t,n){let{addGateAuditEntry:r}=await Promise.resolve().then(()=>(Z(),kn)),o=H.default.join(this.projectPath,"aidlc-docs",this.workflowId,"manifest.json"),s=n>=3;try{r(o,{phase:"construction",action:"approved",actor:"trust",reason:s?`Code plan for ${t} auto-approved silently (trust level ${n})`:`Code plan for ${t} auto-approved with notification (trust level ${n})`})}catch(u){console.error(`[ConstructionExecutor] Failed to record gate audit for ${t}:`,u)}s||console.log(`[ConstructionExecutor] Code plan for ${t} auto-approved (trust level ${n})`);let{dispatchCodeGeneration:i,buildCodeGenerationPrompt:a}=await Promise.resolve().then(()=>(ls(),cs)),c=await i(this.projectPath,this.workflowId,t);return{status:"executing_code_plan",prompt:a(c.context.intentSummary2,c.context.intentSummary,c.context.unitSpec,void 0,c.context.architectureContext)}}async executeTestGeneration(t,n={}){let r=n.projectPath||this.projectPath,o=n.workflowId||this.workflowId,i=await A(r,o)??{schema_version:"3.0.0",workflow_id:o,feature_name:"",current_phase:"construction",current_stage:"code-generation",status:"in_progress",phases:{},manifest_path:"",trust_state_path:"",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),construction_units:{}};i.construction_units||(i.construction_units={});let a=i.construction_units[t]??{unitId:t,stages:{"functional-design":{status:"not_started",artifact_path:null,completed_at:null,failure_count:0,last_error:null},"nfr-requirements":{status:"not_started",artifact_path:null,completed_at:null,failure_count:0,last_error:null},"nfr-design":{status:"not_started",artifact_path:null,completed_at:null,failure_count:0,last_error:null},"infrastructure-design":{status:"not_started",artifact_path:null,completed_at:null,failure_count:0,last_error:null},"code-generation":{status:"not_started",artifact_path:null,completed_at:null,failure_count:0,last_error:null},"test-generation":{status:"not_started",artifact_path:null,completed_at:null,failure_count:0,last_error:null}},code_plan_path:null,code_generation_status:"not_started",tests_total:0,tests_passed:0,tests_failed:0,test_framework:"unknown",test_generation_status:"not_started"};a.stages["test-generation"].status="in_progress",a.test_generation_status="in_progress",i.construction_units[t]=a,await P(r,i);let c=H.default.join(r,"aidlc-docs",o,"construction",t,"testing");await Y.default.ensureDir(c);let l=H.default.join(c,"test-report.md"),u="",d=H.default.join(r,"aidlc-docs",o,"construction",t,"code","code-summary.md");try{await Y.default.pathExists(d)&&(u=await Y.default.readFile(d,"utf-8"))}catch{}let p=await this.detectTestFramework(r),f=new Date().toISOString(),m=this.buildTestReportScaffold(t,p,u,f);await Y.default.writeFile(l,m,"utf-8");let g=0,y=0,w=0,_=0,h=0;n.currentResults&&n.currentResults.length>0&&(g=n.currentResults.length,y=n.currentResults.filter(C=>C.status==="passed").length,w=n.currentResults.filter(C=>C.status==="failed").length);let b=!1,S=0,T=H.default.join(r,"aidlc-docs",o,"construction","regression-baseline.json");if(n.currentResults&&w>0&&await Y.default.pathExists(T))try{let{compareAgainstBaseline:C,writeRegressionReport:$}=await Promise.resolve().then(()=>(ya(),ha)),{categorizeFailure:D,buildRegressionSummary:x}=await Promise.resolve().then(()=>(km(),_m)),E=await Y.default.readJson(T);b=!0;let L=C(E,n.currentResults),j=[],K=[];for(let Oe of L.new_failures){let Or=E.tests.find(Yt=>Yt.name===Oe.name)??null,Ve=D(Oe.name,Or,[]);j.push(Ve),K.push({test_name:Oe.name,file_path:Oe.filePath,category:Ve,rationale:Ve==="legitimate_regression"?"Test was passing in baseline, now fails":Ve==="flaky"?"Test passed on re-run without code changes":Ve==="intentional_change"?"New test not present in baseline":"Test was already failing in baseline"})}let q=x(K.map(Oe=>({test_name:Oe.test_name,file_path:Oe.file_path})),j);_=q.regressions_count,h=q.flaky_count,S=q.regressions_count;let mn={workflow_id:o,unit_id:t,baseline_captured_at:E.captured_at,compared_at:new Date().toISOString(),failures:K,total_regressions:j.filter(Oe=>Oe!=="pre_existing_failure").length,legitimate_regressions:q.regressions_count};await $(r,o,t,mn)}catch(C){console.error(`[ConstructionExecutor] Regression analysis failed for ${t} (non-fatal):`,C)}let k="completed",F;if(n.allowFailures!==!0&&(g===0?(k="blocked",F=`No tests detected for unit ${t}. Set allowFailures: true to override.`):b&&S>0?(k="blocked",F=`${S} legitimate regression(s) for unit ${t}. Flaky: ${h} (non-blocking). Fix regressions before proceeding.`):!b&&w>0&&(k="blocked",F=`${w} test(s) failed for unit ${t}. Set allowFailures: true to override.`)),a.stages["test-generation"].status=k==="completed"?"completed":"in_progress",a.stages["test-generation"].artifact_path=l,k==="completed"&&(a.stages["test-generation"].completed_at=f),a.tests_total=g,a.tests_passed=y,a.tests_failed=w,a.test_framework=p,a.test_generation_status=k==="completed"?"completed":"in_progress",a.regressions_count=_,a.flaky_count=h,i.construction_units[t]=a,await P(r,i),k==="completed")try{let{updateArchitectureModel:C}=await Promise.resolve().then(()=>(Yr(),Qo)),$=await this.discoverUnitFiles(r,o,t);$.length>0&&(await C(r,$),a.architecture_model_status="updated",i.construction_units[t]=a,await P(r,i))}catch(C){console.error(`[ConstructionExecutor] Architecture model update failed for ${t} (non-blocking):`,C),a.architecture_model_status="failed",i.construction_units[t]=a;try{await P(r,i)}catch($){console.warn("[ConstructionExecutor] Failed to save checkpoint after architecture model failure:",$)}}let R;if(k==="completed")try{let{runValidationPipeline:C,shouldSkipValidator:$,updateCheckpointForValidator:D,createQualityValidator:x,createMutationValidator:E,createTraceabilityValidator:L,createContractValidator:j,createCoverageValidator:K}=await Promise.resolve().then(()=>(Bm(),Wm)),q=await this.discoverUnitFiles(r,o,t),mn=this.detectApiSurfaceFiles(q),Oe=this.deriveWorkflowDepth(i),Or={timeoutBudgetMs:3e4,allowFailures:n.allowFailures??!1,workflowDepth:Oe,unitId:t,unitFiles:q,apiSurfaceFiles:mn,projectPath:r,workflowId:o},Ve=new Map;Ve.set("quality",x()),$("mutation",Or).skip||Ve.set("mutation",E()),Ve.set("traceability",L()),$("contract",Or).skip||Ve.set("contract",j()),Ve.set("coverage",K()),R=await C(Ve,Or);for(let{validator:Yt,result:At}of R.results){let w_=At.status==="passed"||At.status==="warned"?"completed":At.status==="skipped"?"skipped":"in_progress",__=Yt==="coverage"?At.coverage_percentage:void 0,k_=Yt==="coverage"?At.findings.filter(S_=>S_.category==="uncovered-critical-file").length:void 0;await D(r,o,t,Yt,w_,__,k_)}if(!n.allowFailures){let Yt=R.results.filter(At=>At.result.status==="failed");Yt.length>0&&(k="blocked",F=`Validation blocked: ${Yt.map(At=>At.validator).join(", ")}`,a.stages["test-generation"].status="in_progress",a.test_generation_status="in_progress",i.construction_units[t]=a,await P(r,i))}}catch(C){console.error(`[ConstructionExecutor] Validation pipeline failed for ${t} (non-fatal):`,C)}return{status:k,unitId:t,tests_total:g,tests_passed:y,tests_failed:w,test_framework:p,reportPath:l,blockingReason:F,regressions_count:_,flaky_count:h,validationPipeline:R}}async validateBugfixTestRequirement(t,n={}){try{let r=n.projectPath||this.projectPath,o=n.workflowId||this.workflowId,s=await A(r,o);if(!s)return{valid:!1,reason:"checkpoint not found"};if(s.pathway_type!=="bugfix")return{valid:!0};let i=s.construction_units?.[t];return i?i.stages?.["test-generation"]?.status!=="completed"?{valid:!1,reason:"test-generation stage not completed for bugfix unit"}:(i.tests_total??0)===0?{valid:!1,reason:"bugfix unit must have at least one test (tests_total === 0)"}:{valid:!0}:{valid:!1,reason:`no unit progress found for unit ${t}`}}catch(r){let o=r instanceof Error?r.message:String(r);return console.error(`[ConstructionExecutor] validateBugfixTestRequirement error for ${t}:`,r),{valid:!1,reason:`validation error: ${o}`}}}async executeDocumentationGeneration(t,n={}){let r=n.projectPath||this.projectPath,o=n.workflowId||this.workflowId,s=await A(r,o),i=s?.depth_score?s.depth_score<=12?"minimal":s.depth_score<=20?"standard":"comprehensive":"standard",a=s?.pathway_type||"brownfield-enhancement",c=await this.discoverUnitFiles(r,o,t),l={unitId:t,workflowId:o,projectPath:r,depth:i,pathway:a,unitFiles:c},u=qp(l),d,p=0,f=[],m;if(u.status==="completed"){try{let g=Hp({projectPath:r,workflowId:o,unitId:t,modifiedFiles:l.unitFiles||[]});d={status:g.impactScan.status,path:g.impactScan.reportPath},p=g.adrCount,g.adrEntries&&(f=g.adrEntries)}catch{}if(u.path&&a!=="bugfix"&&i!=="minimal")try{let g=s?.construction_units?.[t];m=Xi({featureDocPath:u.path,projectPath:r,depth:i,pathway:a,override:g?.recreation_readiness_override,overrideRationale:g?.recreation_readiness_override_rationale??void 0})}catch{}}if(s?.construction_units?.[t]){let g=s.construction_units[t];g.feature_doc_status=u.status==="completed"?"completed":"not_started",g.feature_doc_path=u.path,g.impact_scan_status=d?.status==="completed"?"completed":"not_started",g.impact_scan_report_path=d?.path??null,g.adr_count=p,g.adr_entries=f.length>0?f:void 0,m&&(g.recreation_readiness_score=m.overall_score,g.recreation_readiness_dimensions=m.dimensions??null),u.status==="completed"&&(g.doc_generation_agent=UT["code-generation"],g.doc_generation_prompt=Gp(l)),await P(r,s)}return{featureDoc:u,impactScan:d,adrCount:p,recreationReadiness:m}}async executeUnitCompletion(t,n={}){let r=n.projectPath||this.projectPath,o=n.workflowId||this.workflowId,s=await this.executeTestGeneration(t,n);if(s.status==="completed"){try{let i=await this.discoverUnitFiles(r,o,t);i.length>0&&Vp(r,i)}catch(i){console.error(`[ConstructionExecutor] Secrets management failed for ${t} (non-blocking):`,i)}try{let i=await this.discoverUnitFiles(r,o,t),a=await Xp({projectPath:r,workflowId:o,unitId:t,includeGlobs:i.length>0?i:void 0}),c=await A(r,o);if(c?.construction_units?.[t]){let l=c.construction_units[t];l.security_scan_status=a.status==="completed"?"completed":a.status==="failed"?"in_progress":"not_started",l.security_findings_critical=a.findings.filter(u=>u.severity==="critical").length,l.security_findings_warning=a.findings.filter(u=>u.severity==="warning").length,l.security_findings_info=a.findings.filter(u=>u.severity==="info").length,await P(r,c)}}catch(i){console.error(`[ConstructionExecutor] Security scan failed for ${t} (non-blocking):`,i)}if(!n.skipDocumentation){let i=await this.executeDocumentationGeneration(t,{projectPath:r,workflowId:o});return{testGeneration:s,documentation:i}}}return{testGeneration:s}}async executeSmokeTest(t={}){let n=t.projectPath||this.projectPath,r=t.workflowId||this.workflowId,o=await A(n,r);if(!o||!o.construction_units)return{status:"not_run",reportPath:null};let s=o.construction_units,i=Object.keys(s);if(i.length===0)return{status:"not_run",reportPath:null};let a=0,c=0,l=0,u=0,d=0,p=0,f=0,m=0,g=[];for(let T of i){let k=s[T],F=k.tests_total??0,R=k.tests_passed??0,O=k.tests_failed??0,C=F-R-O,$=k.regressions_count??0,D=k.flaky_count??0;F>0&&(f++,O===0&&m++),a+=F,c+=R,l+=O,u+=Math.max(0,C),d+=$,p+=D;let x=F===0?"\u26A0\uFE0F":O===0?"\u2705":"\u274C";g.push(`| ${T} | ${F} | ${R} | ${O} | ${$} | ${D} | ${x} |`)}let y=a===0?"not_run":l===0?"passed":"failed",w=H.default.join(n,"aidlc-docs",r,"construction","build-and-test");await Y.default.ensureDir(w);let _=H.default.join(w,"test-report.md"),h=new Date().toISOString(),b=`# Build-Level Test Report
|
|
970
970
|
|
|
971
971
|
**Workflow ID**: ${r}
|
|
972
972
|
**Generated At**: ${h}
|
|
@@ -1010,7 +1010,7 @@ ${g.join(`
|
|
|
1010
1010
|
|------|----------|---------------|------|
|
|
1011
1011
|
${T.join(`
|
|
1012
1012
|
`)}
|
|
1013
|
-
`,$=H.default.join(w,"coverage-report.md");await Y.default.writeFile($,C,"utf-8")}catch(T){console.error("[ConstructionExecutor] Workflow-level coverage report failed (non-fatal):",T)}let S={status:y,tests_total:a,tests_passed:c,tests_failed:l,tests_skipped:u,regressions_total:d,flaky_total:p,units_tested:f,units_passed:m,report_path:_,completed_at:h};o.smoke_test=S,o.updated_at=h,await P(n,o);try{let{generateChangelogEntry:T}=await Promise.resolve().then(()=>(
|
|
1013
|
+
`,$=H.default.join(w,"coverage-report.md");await Y.default.writeFile($,C,"utf-8")}catch(T){console.error("[ConstructionExecutor] Workflow-level coverage report failed (non-fatal):",T)}let S={status:y,tests_total:a,tests_passed:c,tests_failed:l,tests_skipped:u,regressions_total:d,flaky_total:p,units_tested:f,units_passed:m,report_path:_,completed_at:h};o.smoke_test=S,o.updated_at=h,await P(n,o);try{let{generateChangelogEntry:T}=await Promise.resolve().then(()=>(Xm(),Qm)),k=Object.keys(s);T({projectPath:n,workflowId:r,featureName:o.feature_name??r,unitIds:k,pathway:o.pathway_type??void 0})}catch(T){console.error("[ConstructionExecutor] Changelog generation failed (non-fatal):",T)}try{let T=await A(n,r);T&&Zp(T,{projectPath:n,workflowId:r,featureName:T.feature_name??r})}catch(T){console.error("[ConstructionExecutor] Quality scorecard generation failed (non-fatal):",T)}return{status:y,reportPath:_}}async captureBugDescription(t,n){try{let r=n?.projectPath||this.projectPath,o=n?.workflowId||this.workflowId,i=await A(r,o)??{schema_version:"3.0.0",workflow_id:o,feature_name:"",current_phase:"construction",current_stage:"code-generation",status:"in_progress",phases:{},manifest_path:"",trust_state_path:"",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),construction_units:{}};i.bug_description=t,i.updated_at=new Date().toISOString(),await P(r,i)}catch(r){console.error("[ConstructionExecutor] captureBugDescription error:",r)}}async discoverUnitFiles(t,n,r){let o=H.default.join(t,"aidlc-docs",n,"construction",r,"code","code-summary.md");try{if(!await Y.default.pathExists(o))return[];let s=await Y.default.readFile(o,"utf-8"),i=[],a=[/[`|]\s*([\w/.\\-]+\.\w{1,5})\s*[`|]/g,/^[-*]\s+`?([\w/.\\-]+\.\w{1,5})`?\s*$/gm];for(let c of a){let l;for(;(l=c.exec(s))!==null;){let u=l[1];i.includes(u)||i.push(u)}}return i}catch{return[]}}detectApiSurfaceFiles(t){let n=[/route/i,/controller/i,/handler/i,/endpoint/i,/api\//i,/server/i,/middleware/i,/graphql/i];return t.filter(r=>n.some(o=>o.test(r)))}deriveWorkflowDepth(t){return t.pathway_type==="bugfix"?0:(t.depth_score??3)<=2?1:2}async detectTestFramework(t){let n=H.default.join(t,"package.json");try{if(!await Y.default.pathExists(n))return"unknown";let r=await Y.default.readFile(n,"utf-8"),o=JSON.parse(r),s={...o.dependencies,...o.devDependencies};return s.vitest?"vitest":s.jest?"jest":s.mocha?"mocha":"unknown"}catch{return"unknown"}}buildTestReportScaffold(t,n,r,o){let s="_No code-summary.md found \u2014 files in scope unknown._";if(r){let i=r.match(/## Files (?:created|modified|created\/modified)[^\n]*\n([\s\S]*?)(?=\n##|$)/i);i&&i[1].trim()&&(s=i[1].trim())}return`---
|
|
1014
1014
|
unit_id: ${t}
|
|
1015
1015
|
framework: ${n}
|
|
1016
1016
|
generated_at: ${o}
|
|
@@ -1043,7 +1043,7 @@ _No failures recorded._
|
|
|
1043
1043
|
## Override
|
|
1044
1044
|
|
|
1045
1045
|
_allowFailures was not set._
|
|
1046
|
-
`}async executeShallowViaBolt(){let t=H.default.join(this.projectPath,"aidlc-docs",this.workflowId,"inception","intent.md"),n="Shallow Implementation",r=2,o="",s=await
|
|
1046
|
+
`}async executeShallowViaBolt(){let t=H.default.join(this.projectPath,"aidlc-docs",this.workflowId,"inception","intent.md"),n="Shallow Implementation",r=2,o="",s=await ia(t);if(s){o=s.content;let d=o.match(/^title:\s*(.+)$/m);d&&(n=d[1].trim().replace(/^["']|["']$/g,""));let p=o.match(/^estimated_effort:\s*(\d+)/m);p&&(r=Number(p[1]))}else{let d=H.default.join(this.projectPath,"aidlc-docs",this.workflowId,"inception"),p=await sa(d);if(p.length===0)return{passed:!1,coverage_percentage:0,blocking_issues:["No intent found for SHALLOW construction"],reviewer:"construction-executor",timestamp:new Date().toISOString()};n=p[0].title,r=p[0].estimated_effort}let i={id:"shallow-impl",type:"unit",title:n,parent_id:null,children_ids:[],status:"pending",assigned_agent:null,estimated_effort:r},a=await A(this.projectPath,this.workflowId);if(!a)return{passed:!1,coverage_percentage:0,blocking_issues:["No checkpoint found for SHALLOW construction"],reviewer:"construction-executor",timestamp:new Date().toISOString()};let c=cf(i,o,a);lf([c],a);let l={onElaboration:async()=>({success:!0}),onCodeGeneration:async()=>({success:!0}),onBuildAndTest:async()=>({success:!0}),onReview:async()=>({success:!0})},u=await uf.execute(c,a,this.projectPath,this.workflowId,l);return console.log(`[ConstructionExecutor] SHALLOW express bolt completed with status: ${u.status}`),{passed:u.status==="done",coverage_percentage:u.status==="done"?100:0,blocking_issues:u.status==="done"?[]:[`Express bolt failed with status: ${u.status}`],reviewer:"construction-executor",timestamp:new Date().toISOString()}}async executeDecompositionPhase(t,n,r,o="MEDIUM"){let s=H.default.join(this.projectPath,"aidlc-docs",this.workflowId,"inception"),i=H.default.join(this.projectPath,"aidlc-docs",this.workflowId,"construction");await Y.default.ensureDir(i);let a=H.default.join(s,"intent.md"),c=await ia(a),l=H.default.join(s,"intent.md"),u="";try{await Y.default.pathExists(l)&&(u=await Y.default.readFile(l,"utf-8"))}catch{}return c?this.executeDecompositionFromIntent(c,s,i,t,n,r,u,o):this.executeDecompositionFromLegacyIntents(s,i,t,n,r,u)}async executeDecompositionFromIntent(t,n,r,o,s,i,a,c="MEDIUM"){let l=t.content,u=l.match(/^title:\s*(.+)$/m),d=l.match(/^estimated_effort:\s*(\d+)/m),p=u?u[1].trim().replace(/^["']|["']$/g,""):"Untitled Intent",f=d?Number(d[1]):0,m="INTENT-001",g={id:m,type:"intent",title:p,parent_id:null,children_ids:[],status:"pending",assigned_agent:null,estimated_effort:f},y=`---
|
|
1047
1047
|
id: ${m}
|
|
1048
1048
|
title: ${p}
|
|
1049
1049
|
status: pending
|
|
@@ -1067,7 +1067,7 @@ Auto-generated
|
|
|
1067
1067
|
|
|
1068
1068
|
## Technical Notes
|
|
1069
1069
|
Generated from inception/intent.md
|
|
1070
|
-
`;await Y.default.writeFile(H.default.join(n,`${m}.md`),y,"utf-8");let w=t.proposedUnits.map(S=>({title:S.title,estimated_effort:Math.ceil(f/Math.max(t.proposedUnits.length,1)),description:S.description}));w.length===0&&w.push({title:p,estimated_effort:f,description:`Implementation unit for ${p}`});let _=
|
|
1070
|
+
`;await Y.default.writeFile(H.default.join(n,`${m}.md`),y,"utf-8");let w=t.proposedUnits.map(S=>({title:S.title,estimated_effort:Math.ceil(f/Math.max(t.proposedUnits.length,1)),description:S.description}));w.length===0&&w.push({title:p,estimated_effort:f,description:`Implementation unit for ${p}`});let _=aa(g,w,o),h=[];for(let S of _){let T=H.default.join(r,S.id);await Y.default.ensureDir(T);let k=this.formatUnitMarkdown(S,g.id,l);await Y.default.writeFile(H.default.join(T,"spec.md"),k,"utf-8"),await Y.default.writeFile(H.default.join(r,`${S.id}.md`),k,"utf-8"),this.registerConstructionArtifact(S.id,"unit","unit",H.default.join(T,"spec.md")),this.linkConstructionArtifacts(m,S.id,"derives"),this.runUnitValidation(k,l,a,g.id,S.id);try{let{UnitStageRunner:F}=await Promise.resolve().then(()=>(ng(),tg)),{loadCheckpoint:R,saveCheckpoint:O}=await Promise.resolve().then(()=>(ce(),Wi));await new F(this.projectPath,this.workflowId).executeForUnit(S.id,c,a,void 0,async($,D)=>{let x=await R(this.projectPath,this.workflowId);x&&(x.construction_units||(x.construction_units={}),x.construction_units[$]=D,await O(this.projectPath,x))})}catch(F){console.error(`[ConstructionExecutor] Unit stage runner failed for ${S.id}:`,F)}}this.tree=ca([g]);for(let S of _)this.tree.nodes.set(S.id,S);this.totalUnits=_.length,this.totalCodeGenerations=_.length,this.totalEffort=_.reduce((S,T)=>S+T.estimated_effort,0),console.log(`[ConstructionExecutor] Created ${_.length} units for code generation`);let b=await da(r,n);return b.passed?h.length>0?{passed:!1,coverage_percentage:0,blocking_issues:h,reviewer:"construction-executor",timestamp:new Date().toISOString()}:{passed:!0,coverage_percentage:100,blocking_issues:[],reviewer:"construction-executor",timestamp:new Date().toISOString()}:b}async executeDecompositionFromLegacyIntents(t,n,r,o,s,i){let a=await sa(t);if(a.length===0)return{passed:!1,coverage_percentage:0,blocking_issues:["No intents found in Inception phase"],reviewer:"construction-executor",timestamp:new Date().toISOString()};console.log(`[ConstructionExecutor] Found ${a.length} intents to decompose (legacy mode)`);let c="";try{let f=(await Y.default.readdir(t)).find(m=>m.startsWith("INTENT-")&&m.endsWith(".md"));f&&(c=await Y.default.readFile(H.default.join(t,f),"utf-8"))}catch{}let l=[],u=[];for(let p of a){let f=[{title:p.title,estimated_effort:p.estimated_effort,description:`Implementation unit for ${p.title}`}],m=aa(p,f,r);l.push(...m);for(let g of m){let y=H.default.join(n,`${g.id}.md`),w=this.formatUnitMarkdown(g,p.id);await Y.default.writeFile(y,w,"utf-8");let _=H.default.join(n,g.id);await Y.default.ensureDir(_),await Y.default.writeFile(H.default.join(_,"spec.md"),w,"utf-8"),this.registerConstructionArtifact(g.id,"unit","unit",H.default.join(_,"spec.md")),this.linkConstructionArtifacts(p.id,g.id,"derives"),this.runUnitValidation(w,c,i,p.id,g.id)}}console.log(`[ConstructionExecutor] Created ${l.length} units for code generation`),this.tree=ca(a);for(let p of l)this.tree.nodes.set(p.id,p);this.totalUnits=l.length,this.totalCodeGenerations=l.length,this.totalEffort=l.reduce((p,f)=>p+f.estimated_effort,0);let d=await da(n,t);return d.passed?u.length>0?{passed:!1,coverage_percentage:0,blocking_issues:u,reviewer:"construction-executor",timestamp:new Date().toISOString()}:{passed:!0,coverage_percentage:100,blocking_issues:[],reviewer:"construction-executor",timestamp:new Date().toISOString()}:d}async executeDesignStage(t){let n=H.default.join(this.projectPath,"aidlc-docs",this.workflowId,"construction"),r=await Y.default.readdir(n,{withFileTypes:!0}),o=[];for(let l of r)if(l.isDirectory()&&l.name!=="design"){let u=H.default.join(n,l.name,"spec.md");if(await Y.default.pathExists(u)){let d=await Y.default.readFile(u,"utf-8"),p=this.parseUnitFromMarkdown(d,l.name);p&&o.push(p)}}else if(l.isFile()&&l.name.endsWith(".md")&&l.name!=="design"){let u=H.default.join(n,l.name),d=await Y.default.readFile(u,"utf-8"),p=this.parseUnitFromMarkdown(d,l.name.replace(".md",""));p&&o.push(p)}if(o.length===0)return{passed:!1,coverage_percentage:0,blocking_issues:["No units found to generate design artifacts"],reviewer:"construction-executor",timestamp:new Date().toISOString()};console.log(`[ConstructionExecutor] Generating design artifacts for ${o.length} units`);let s=rf(o,t||""),i=of(o,s),a=sf(o,s,i);await af(this.projectPath,this.workflowId,{interfaces:s,dataFlows:i,components:a});let c=H.default.join(this.projectPath,"aidlc-docs",this.workflowId,"construction","design");return this.registerConstructionArtifact("design-interfaces","interface-contracts","unit",H.default.join(c,"interfaces.json")),this.registerConstructionArtifact("design-data-flow","data-flow-diagram","unit",H.default.join(c,"data-flow.json")),this.registerConstructionArtifact("design-components","component-design","unit",H.default.join(c,"components.json")),t?la({interfaces:s,dataFlows:i,components:a},t):{passed:!0,coverage_percentage:100,blocking_issues:[],reviewer:"construction-executor",timestamp:new Date().toISOString()}}runUnitValidation(t,n,r,o,s){if(!(!n||!r))try{let i=Jn(t,n,r,"intent-to-unit","unit-to-intent",o,s,`intent-${this.workflowId}`);i.passed||console.warn(`[ConstructionExecutor] Dual validation warning for ${s}: parent=${i.parentCheck.alignment_passed}, root=${i.rootCheck.alignment_passed}`)}catch(i){console.error(`[ConstructionExecutor] Dual validation error for ${s}:`,i)}}registerConstructionArtifact(t,n,r,o){try{let s=H.default.join(this.projectPath,"aidlc-docs",this.workflowId,"manifest.json");$e(s,{id:t,type:n,phase:"construction",stage:r,path:o,validation_passed:null,write_complete:!0,checksum:null})}catch(s){console.error(`[ConstructionExecutor] Failed to register artifact ${t}:`,s)}}linkConstructionArtifacts(t,n,r){try{let o=H.default.join(this.projectPath,"aidlc-docs",this.workflowId,"manifest.json");Vi(o,{source_id:t,target_id:n,link_type:r})}catch(o){console.error(`[ConstructionExecutor] Failed to link ${t} -> ${n}:`,o)}}formatUnitMarkdown(t,n,r){let o=new Date().toISOString();return`---
|
|
1071
1071
|
id: ${t.id}
|
|
1072
1072
|
title: ${t.title}
|
|
1073
1073
|
parent_intent: ${n}
|
|
@@ -1118,16 +1118,16 @@ Implementation details for ${t.title}.
|
|
|
1118
1118
|
- Parent INTENT: ${n} (inception/intent.md)
|
|
1119
1119
|
- Root INTENT: intent-${this.workflowId} (inception/intent.md)
|
|
1120
1120
|
`}parseUnitFromMarkdown(t,n){try{let r=t.match(/^---\n([\s\S]*?)\n---/);if(!r)return null;let s=r[1].split(`
|
|
1121
|
-
`),i={};for(let a of s){let c=a.match(/^(\w+):\s*(.+)$/);if(c){let[,l,u]=c,d=u.trim().replace(/^["']|["']$/g,"");isNaN(Number(d))?i[l]=d:i[l]=Number(d)}}return{id:n,type:"unit",title:i.title||"Untitled Unit",parent_id:i.parent_intent||null,children_ids:[],status:i.status||"pending",assigned_agent:i.assigned_agent||null,estimated_effort:i.estimated_effort||0}}catch(r){return console.error("Failed to parse unit from markdown:",r),null}}};
|
|
1122
|
-
`)}
|
|
1121
|
+
`),i={};for(let a of s){let c=a.match(/^(\w+):\s*(.+)$/);if(c){let[,l,u]=c,d=u.trim().replace(/^["']|["']$/g,"");isNaN(Number(d))?i[l]=d:i[l]=Number(d)}}return{id:n,type:"unit",title:i.title||"Untitled Unit",parent_id:i.parent_intent||null,children_ids:[],status:i.status||"pending",assigned_agent:i.assigned_agent||null,estimated_effort:i.estimated_effort||0}}catch(r){return console.error("Failed to parse unit from markdown:",r),null}}};es();var rg=require("crypto"),WT={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 He(e,t){let n=WT[e.type],r=e.timestamp??new Date().toISOString(),o=BT(e.type),s=GT(e).slice(0,100),i=HT(e,t);return{id:(0,rg.randomUUID)(),timestamp:r,session_id:t.sessionId,project_path:t.projectPath,category:n,summary:s,details:i,agent_name:e.agentName??"workflow-engine",task_context:`${t.featureName} (${e.phase}${e.stage?"/"+e.stage:""})`,files_involved:e.artifactId?[`${e.artifactId}`]:[],confidence:o,verified:e.type==="gate_approval"||e.type==="phase_complete"||e.type==="bolt_execution_complete",verification_count:0,scope:"project",last_useful:r}}function BT(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 GT(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 HT(e,t){let n=[`Event: ${e.type}`,`Workflow: ${t.workflowId} (${t.featureName})`,`Phase: ${e.phase}${e.stage?" / Stage: "+e.stage:""}`,`Details: ${e.details}`];return e.artifactId&&n.push(`Artifact: ${e.artifactId}`),e.agentName&&n.push(`Agent: ${e.agentName}`),t.riskTier&&n.push(`Risk Tier: ${t.riskTier.tier}`),t.depthScore!==void 0&&n.push(`Depth Score: ${t.depthScore}`),n.join(`
|
|
1122
|
+
`)}Mt();as();function ar(e){return Math.max(1,Math.min(5,Math.round(e)))}function qT(e){let t=ar(e.clarity),n=ar(e.complexity),r=ar(e.scope),o=ar(e.risk),s=ar(e.context),i=ar(e.preferences),a=t+n+r+o+s+i,c;a<=10?c="minimal":a<=20?c="standard":c="comprehensive";let l=a<=10,u=VT(o,n,r),d=og(u);return{clarity:t,complexity:n,scope:r,risk:o,context:s,preferences:i,total_score:a,recommended_depth:c,skip_units:l,risk_tier:d}}function VT(e,t,n){let r;e>=4?r="difficult":e>=3?r="moderate":r="easy";let o;n>=4?o="system-wide":n>=3?o="cross-cutting":o="isolated";let s;e>=4&&t>=3?s="user-facing":e>=3?s="internal":s="none";let i;return e>=5?i="major":e>=4?i="minor":i="none",{reversibility:r,blast_radius:o,data_sensitivity:s,compliance_impact:i}}function og(e){let t=e.reversibility==="easy"?1:e.reversibility==="moderate"?2:3,n=e.blast_radius==="isolated"?1:e.blast_radius==="cross-cutting"?2:3,r=e.data_sensitivity==="none"?1:e.data_sensitivity==="internal"?2:3,o=e.compliance_impact==="none"?1:e.compliance_impact==="minor"?2:3,s=t+n+r+o,i;s<=6?i=1:s<=9?i=2:i=3;let a=YT(i,e);return{tier:i,rationale:a,factors:e,override_reason:null}}function YT(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 hs(e){let t=KT(e),n=JT(t),r=zT(t),o=QT(t),s=XT(t),i=ZT(t),a=eC(t),c=tC(e,t),u=qT({clarity:n,complexity:r,scope:o,risk:s,context:i,preferences:a}),d=og(c);return u.risk_tier=d,u}function KT(e){let t={problemStatement:"",userPersonas:"",businessConstraints:"",successMetrics:"",outOfScope:""},n=/^## (.+)$/gm,r=[],o=0,s;for(;(s=n.exec(e))!==null;)r.length>0&&(r[r.length-1].content=e.substring(o,s.index).trim()),r.push({title:s[1].trim(),content:""}),o=s.index+s[0].length;r.length>0&&(r[r.length-1].content=e.substring(o).trim());for(let i of r){let a=i.title.toLowerCase();a.includes("problem")||a.includes("statement")?t.problemStatement=i.content:a.includes("persona")||a.includes("user persona")?t.userPersonas=i.content:a.includes("business constraint")||a.includes("constraint")?t.businessConstraints=i.content:a.includes("success")||a.includes("metric")?t.successMetrics=i.content:(a.includes("out of scope")||a.includes("scope"))&&(t.outOfScope=i.content)}return t}function JT(e){let t=e.problemStatement.length+e.userPersonas.length;return t>1e3?1:t>500?2:t>250?3:t>100?4:5}function zT(e){let t=(e.userPersonas.match(/^[-*+]\s/gm)||[]).length,r=["component","service","module","layer","system","integration","api"].filter(s=>e.userPersonas.toLowerCase().includes(s)).length,o=t+r;return o>=10?5:o>=7?4:o>=4?3:o>=2?2:1}function QT(e){let t=(e.businessConstraints.match(/^[-*+]\s/gm)||[]).length,n=(e.successMetrics.match(/^[-*+]\s/gm)||[]).length,r=t+n;return r>=10?5:r>=7?4:r>=4?3:r>=2?2:1}function XT(e){let t=["security","compliance","data","migration","breaking","irreversible","pii","gdpr","authentication","payment","infrastructure","system-wide","critical"],r=(e.businessConstraints+e.userPersonas).toLowerCase(),o=t.filter(s=>r.includes(s)).length;return o>=5?5:o>=3?4:o>=2?3:o>=1?2:1}function ZT(e){let t=e.outOfScope.length;return t>500?1:t>300?2:t>150?3:t>50?4:5}function eC(e){let t=["must","should","could","prefer","optional","required","nice to have"],r=(e.businessConstraints+e.userPersonas).toLowerCase(),o=t.filter(s=>r.includes(s)).length;return o>=8?5:o>=5?4:o>=3?3:o>=2?2:1}function tC(e,t){let n=e.toLowerCase(),r="moderate";n.includes("irreversible")||n.includes("migration")||n.includes("data loss")||n.includes("breaking change")?r="difficult":(n.includes("refactor")||n.includes("new feature")||n.includes("additive"))&&(r="easy");let o="isolated";n.includes("system-wide")||n.includes("all users")||n.includes("infrastructure")||n.includes("platform")?o="system-wide":(n.includes("cross-cutting")||n.includes("multiple")||n.includes("shared"))&&(o="cross-cutting");let s="none";n.includes("pii")||n.includes("personal")||n.includes("authentication")||n.includes("payment")||n.includes("user data")||n.includes("sensitive")?s="user-facing":(n.includes("internal")||n.includes("logging")||n.includes("metrics")||n.includes("telemetry"))&&(s="internal");let i="none";return n.includes("gdpr")||n.includes("soc")||n.includes("hipaa")||n.includes("compliance")||n.includes("regulatory")?i="major":(n.includes("audit")||n.includes("policy"))&&(i="minor"),{reversibility:r,blast_radius:o,data_sensitivity:s,compliance_impact:i}}Z();var sg=require("fs"),nC=require("path"),rC=require("os"),ys="<!-- AIDLC-RULES-START -->",cr="<!-- AIDLC-RULES-END -->";function ig(e){return e.includes(ys)&&e.includes(cr)}function Ma(e,t){let n=`${ys}
|
|
1123
1123
|
${t}
|
|
1124
|
-
${
|
|
1124
|
+
${cr}`;if(ig(e)){let o=e.indexOf(ys),s=e.indexOf(cr)+cr.length,i=e.slice(0,o).replace(/\s+$/,""),a=e.slice(s).replace(/^\s+/,"");return a?`${n}
|
|
1125
1125
|
|
|
1126
1126
|
${a}`:n}let r=e.replace(/^\s+/,"");return r?`${n}
|
|
1127
1127
|
|
|
1128
|
-
${r}`:n}function
|
|
1128
|
+
${r}`:n}function ag(e){if(!ig(e))return e;let t=e.indexOf(ys),n=e.indexOf(cr)+cr.length,r=e.slice(0,t).replace(/\s+$/,""),o=e.slice(n).replace(/^\s+/,"");return r&&o?`${r}
|
|
1129
1129
|
|
|
1130
|
-
${o}`:r||o||""}function
|
|
1130
|
+
${o}`:r||o||""}function La(e,t){return`# AI-DLC Workflow Rules (Olympus-Native)
|
|
1131
1131
|
|
|
1132
1132
|
## Active Workflow
|
|
1133
1133
|
- **Workflow ID**: \`${e}\`
|
|
@@ -1138,7 +1138,7 @@ ${o}`:r||o||""}function Ua(e,t){return`# AI-DLC Workflow Rules (Olympus-Native)
|
|
|
1138
1138
|
|
|
1139
1139
|
All workflow stages, agent delegation, directory layout, and rules are defined in the
|
|
1140
1140
|
global \`~/.claude/CLAUDE.md\` (installed by Olympus). This block only tracks the active
|
|
1141
|
-
workflow identity \u2014 do NOT search for a separate core-workflow.md file.`}var yC=["set up","build out","roll out","hook up","wire up","spin up","build","create","add","implement","design","make","develop","configure","integrate","fix","update","refactor","migrate","deploy","setup","establish","introduce","enable","write","construct","generate","define","prepare"];function Ka(e){let t=e.trim();(t.includes("/")||t.includes("\\"))&&(t=t.split(/[/\\]/).pop()||t),t=t.replace(/\.[a-z]{1,4}$/i,"");let n=[...yC].sort((s,i)=>i.length-s.length);for(let s of n){let i=new RegExp(`^${s}\\s+`,"i");if(i.test(t)){t=t.replace(i,"");break}}t=t.replace(/^(?:a|an|the)\s+/i,"");let r=t.replace(/\s+(?:for|with|using|via|in|to|on|at|from|into|across|through|about|of)\s+.+$/i,"").trim();r.length>0&&(t=r);let o=t.toLowerCase().replace(/[_\s]+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"");if(o.length>40){let s=o.substring(0,40),i=s.lastIndexOf("-");o=i>0?s.substring(0,i):s,o=o.replace(/-$/,"")}if(!o)throw new Error("Feature name produced an empty workflow ID after sanitization");if(o==="completed")throw new Error("'completed' is a reserved directory name and cannot be used as a workflow ID");return o}var Ya=["intent","unit","code-generation","complete"];function wC(e){let t=Ya.indexOf(e);return t===-1||t>=Ya.length-1?"complete":Ya[t+1]}var Ss=class{projectPath;featureName;workflowId;interruptHandler=null;constructor(t,n){this.projectPath=t,this.featureName=n,this.workflowId=Ka(n)}async start(t){let n={schema_version:"3.0.0",workflow_id:this.workflowId,feature_name:this.featureName,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),current_phase:"inception",current_stage:"intent",status:"in_progress",origin:"hook-init",phases:{discovery:{status:"not_started",started_at:null,completed_at:null,gate_result:null,gate_bypassed:!1,bypass_reason:null},inception:{status:"in_progress",started_at:new Date().toISOString(),completed_at:null,gate_result:null,gate_bypassed:!1,bypass_reason:null},construction:{status:"not_started",started_at:null,completed_at:null,gate_result:null,gate_bypassed:!1,bypass_reason:null},operations:{status:"not_started",started_at:null,completed_at:null,gate_result:null,gate_bypassed:!1,bypass_reason:null}},manifest_path:`aidlc-docs/${this.workflowId}/manifest.json`,trust_state_path:".olympus/trust-state.json",resume_context:{initial_prompt:t}};try{await $p(this.projectPath,this.workflowId)}catch(o){let s=o;throw console.error(`[WorkflowEngine] Failed to initialize workflow directory: ${s.message}`),new Error(`Failed to start workflow: Could not create directory structure - ${s.message}`)}let r=$n.join(this.projectPath,"aidlc-docs",this.workflowId,"manifest.json");if(!ge.existsSync(r))try{Vi(this.workflowId,this.featureName,this.projectPath)}catch(o){console.warn(`[WorkflowEngine] Failed to create manifest: ${o.message}`)}try{await P(this.projectPath,n)}catch(o){let s=o;throw console.error(`[WorkflowEngine] Failed to save initial checkpoint: ${s.message}`),new Error(`Failed to start workflow: Could not save checkpoint - ${s.message}`)}try{let s=(await Rn(this.projectPath)).sourceFileCount??0,i=await Pa(this.projectPath,t),a=ws(t),c=await Ia({projectPath:this.projectPath,workflowId:this.workflowId,intentText:t,depthAssessment:a,pathwayType:i,sourceFileCount:s}),l=await as(this.projectPath,this.workflowId,c),u=await A(this.projectPath,this.workflowId);if(u){u.workflow_routing_path=l,u.pathway_type=i,u.depth_score=a.total_score;let d=["discovery","inception","construction","operations"];u.skipped_phases=d.filter(p=>!cs(c,p)),await P(this.projectPath,u)}if(console.log(`[WorkflowEngine] Generated Workflow Routing: pathway=${i}, depth=${c.estimated_depth}, bolts=${c.estimated_bolts}`),c.stages.some(d=>!d.included)){let d=c.stages.filter(p=>!p.included).map(p=>`${p.phase}/${p.stage}`);console.log(`[WorkflowEngine] Stages excluded by plan: ${d.join(", ")}`)}}catch(o){console.warn(`[WorkflowEngine] Failed to generate Workflow Routing: ${o.message}`),console.warn("[WorkflowEngine] Workflow will proceed without adaptive phase selection")}try{let s=(await A(this.projectPath,this.workflowId))?.pathway_type;if(!s){let{isBrownfield:u}=await Rn(this.projectPath);s=u?"brownfield-enhancement":"greenfield"}let i=$n.join(this.projectPath,".claude","CLAUDE.md"),a=ge.existsSync(i)?ge.readFileSync(i,"utf-8"):"",c=Ua(this.workflowId,s),l=La(a,c);ge.mkdirSync($n.join(this.projectPath,".claude"),{recursive:!0}),ge.writeFileSync(i,l,"utf-8"),console.log("[WorkflowEngine] Injected AI-DLC rules into .claude/CLAUDE.md")}catch(o){console.error("[WorkflowEngine] Failed to inject AI-DLC rules into CLAUDE.md:",o)}}async resume(){let t;try{t=await A(this.projectPath,this.workflowId)}catch(r){let o=r;throw console.error(`[WorkflowEngine] Failed to load checkpoint for resume: ${o.message}`),new Error(`Failed to resume workflow: Could not load checkpoint - ${o.message}`)}if(!t)throw console.error(`[WorkflowEngine] No checkpoint found for workflow: ${this.workflowId}`),console.error("[WorkflowEngine] Available workflows: Run 'olympus workflow list' to see workflows"),new Error(`No checkpoint found for workflow: ${this.workflowId}`);if(t.status==="complete")return"Workflow already complete";if(t.status==="paused"){t.status="in_progress";try{await P(this.projectPath,t)}catch(r){let o=r;throw console.error(`[WorkflowEngine] Failed to update checkpoint status: ${o.message}`),new Error(`Failed to resume workflow: Could not save checkpoint - ${o.message}`)}}try{let r=t.pathway_type;if(!r){let{isBrownfield:c}=await Rn(this.projectPath);r=c?"brownfield-enhancement":"greenfield"}let o=$n.join(this.projectPath,".claude","CLAUDE.md"),s=ge.existsSync(o)?ge.readFileSync(o,"utf-8"):"",i=Ua(this.workflowId,r),a=La(s,i);ge.mkdirSync($n.join(this.projectPath,".claude"),{recursive:!0}),ge.writeFileSync(o,a,"utf-8"),console.log("[WorkflowEngine] Injected AI-DLC rules into .claude/CLAUDE.md")}catch(r){console.error("[WorkflowEngine] Failed to inject AI-DLC rules into CLAUDE.md:",r)}this.setupInterruptHandler();let n=t.current_stage;try{await this.executeStage(n)}catch(r){let o=r;console.error(`[WorkflowEngine] Failed to execute ${n} stage: ${o.message}`);try{let s=await A(this.projectPath,this.workflowId);s&&(s.status="paused",s.resume_context={...s.resume_context,error_message:o.message,failed_stage:n},await P(this.projectPath,s),console.log("[WorkflowEngine] Workflow saved as paused. Fix the issue and resume with `/continue`"))}catch(s){console.warn("[WorkflowEngine] Failed to save error checkpoint:",s.message)}throw new Error(`Failed to execute ${n} stage: ${o.message}`)}finally{this.cleanupInterruptHandler()}return`Resumed workflow from stage: ${n}`}async pause(){let t;try{t=await A(this.projectPath,this.workflowId)}catch(n){let r=n;throw console.error(`[WorkflowEngine] Failed to load checkpoint for pause: ${r.message}`),new Error(`Failed to pause workflow: Could not load checkpoint - ${r.message}`)}if(!t)throw console.error(`[WorkflowEngine] No checkpoint found for workflow: ${this.workflowId}`),new Error(`No checkpoint found for workflow: ${this.workflowId}`);t.status="paused";try{await P(this.projectPath,t)}catch(n){let r=n;throw console.error(`[WorkflowEngine] Failed to save paused checkpoint: ${r.message}`),new Error(`Failed to pause workflow: Could not save checkpoint - ${r.message}`)}return`aidlc-docs/${this.workflowId}/checkpoint.json`}async executeStage(t){if(t==="complete")throw new Error("No execution for complete stage");let n=await A(this.projectPath,this.workflowId);if(!n)throw new Error(`No checkpoint found for workflow: ${this.workflowId}`);switch(t){case"intent":await this.executeIntentStage(n);break;case"unit":await this.executeUnitStage(n);break;case"code-generation":await this.executeCodeGenerationStage(n);break}let r=wC(t);n.current_stage=r,r==="complete"?await this.completeWorkflow(n):await P(this.projectPath,n)}async getStatus(){let t;try{t=await A(this.projectPath,this.workflowId)}catch(r){let o=r;throw console.error(`[WorkflowEngine] Failed to load checkpoint for status: ${o.message}`),new Error(`Failed to get workflow status: Could not load checkpoint - ${o.message}`)}if(!t)throw console.error(`[WorkflowEngine] No checkpoint found for workflow: ${this.workflowId}`),new Error(`No checkpoint found for workflow: ${this.workflowId}`);let n=[];return{workflow_id:t.workflow_id,feature_name:t.feature_name,current_stage:t.current_stage,status:t.status,artifacts:n,updated_at:t.updated_at}}async executePhase(t){let n=Xr(this.projectPath,this.workflowId);if(n&&!cs(n,t)){console.log(`[WorkflowEngine] Skipping ${t} phase (excluded by Workflow Routing: ${n.phases[t]?.rationale||"no rationale"})`);let r=await A(this.projectPath,this.workflowId);if(r){let s=r;s.phases&&s.phases[t]&&(s.phases[t].status="complete",s.phases[t].completed_at=new Date().toISOString(),s.phases[t].gate_bypassed=!0,s.phases[t].bypass_reason="Excluded by Workflow Routing"),await P(this.projectPath,r)}let o=`${this.projectPath}/aidlc-docs/${this.workflowId}/manifest.json`;try{je(o,{phase:t,action:"bypassed",actor:"config",reason:`Excluded by Workflow Routing (pathway: ${n.pathway})`})}catch{}return}switch(t){case"discovery":{let r=`${this.projectPath}/aidlc-docs/${this.workflowId}/manifest.json`,o=await um({projectPath:this.projectPath,workflowId:this.workflowId,featureName:this.featureName,manifestPath:r});o.gateRequired&&(console.log(`[WorkflowEngine] Discovery phase: ${o.artifactsGenerated.length} artifacts generated (${o.sourceFileCount} source files detected)`),console.log(`[WorkflowEngine] Discovery Gate: Review findings in aidlc-docs/${this.workflowId}/discovery/ before proceeding to Inception`));try{let s=await A(this.projectPath,this.workflowId);s&&(s.phases.discovery.status="complete",s.phases.discovery.completed_at=new Date().toISOString(),await P(this.projectPath,s))}catch(s){console.error("[WorkflowEngine] Failed to persist discovery phase completion:",s)}try{let s={type:"phase_complete",phase:"discovery",details:`${o.artifactsGenerated.length} artifacts generated, ${o.sourceFileCount} source files`},i={workflowId:this.workflowId,featureName:this.featureName,projectPath:this.projectPath,sessionId:"engine",phase:"discovery"},a=Ve(s,i);ue(a)}catch(s){console.error("[WorkflowEngine] Failed to capture discovery phase discovery:",s)}break}case"inception":{let{InceptionOrchestrator:r}=await Promise.resolve().then(()=>(hg(),gg)),o=new r,s=await A(this.projectPath,this.workflowId);if(!s)throw new Error(`No checkpoint found for workflow: ${this.workflowId}`);if(s.current_stage!=="intent"){console.log(`[WorkflowEngine] Skipping inception orchestrator \u2014 checkpoint already at stage '${s.current_stage}'`);break}if(!s.inception_stages){let i=Xr(this.projectPath,this.workflowId),a=s;await o.initialize(this.projectPath,this.workflowId,a.pathway_type||"greenfield",i)}for(;!await o.isComplete(this.projectPath,this.workflowId);){let i=await o.executeNextStage(this.projectPath,this.workflowId);if(i.status==="awaiting_answers"||i.status==="review_required")break}if(await o.isComplete(this.projectPath,this.workflowId))try{let i=await A(this.projectPath,this.workflowId);i&&(i.phases.inception.status="complete",i.phases.inception.completed_at=new Date().toISOString(),await P(this.projectPath,i))}catch(i){console.error("[WorkflowEngine] Failed to persist inception phase completion:",i)}try{let i={type:"phase_complete",phase:"inception",details:"Inception stages completed"},a={workflowId:this.workflowId,featureName:this.featureName,projectPath:this.projectPath,sessionId:"engine",phase:"inception"},c=Ve(i,a);ue(c)}catch(i){console.error("[WorkflowEngine] Failed to capture inception phase discovery:",i)}break}case"construction":{let r=await A(this.projectPath,this.workflowId);if(r&&r.status==="awaiting_dev_review"){console.log("[WorkflowEngine] Waiting for developer review of technical specification (Risk Tier 3).");return}let o=lt(this.projectPath,this.workflowId,"intent"),s;try{s=ge.readFileSync(o,"utf-8")}catch{}let a=await new ys(this.projectPath,this.workflowId).execute(s);if(!a.passed)throw console.error("[WorkflowEngine] Construction phase validation failed:",a.blocking_issues),new Error(`Construction phase validation failed: ${a.blocking_issues.join(", ")}`);try{let c=await A(this.projectPath,this.workflowId);c&&(c.phases.construction.status="complete",c.phases.construction.completed_at=new Date().toISOString(),await P(this.projectPath,c))}catch(c){console.error("[WorkflowEngine] Failed to persist construction phase completion:",c)}try{let c={type:"phase_complete",phase:"construction",details:"Construction phase completed"},l={workflowId:this.workflowId,featureName:this.featureName,projectPath:this.projectPath,sessionId:"engine",phase:"construction"},u=Ve(c,l);ue(u)}catch(c){console.error("[WorkflowEngine] Failed to capture construction phase discovery:",c)}break}case"operations":{let{generateOperationsArtifacts:r}=await Promise.resolve().then(()=>(bg(),vg)),{loadManifest:o,registerArtifact:s,updatePhaseStatus:i}=await Promise.resolve().then(()=>(Z(),vn)),a=`${this.projectPath}/aidlc-docs/${this.workflowId}/manifest.json`,c=o(a),l=null;try{l=ge.readFileSync(lt(this.projectPath,this.workflowId,"intent"),"utf-8")}catch{}let u=await A(this.projectPath,this.workflowId),d="MEDIUM";if(c?.depth_assessment){let m=c.depth_assessment.total_score;m<=10?d="SHALLOW":m>=21&&(d="DEEP")}let p={workflowId:this.workflowId,featureName:this.featureName,manifest:c,specContent:l,buildLogContent:null,depthLevel:d},f=await r(p,this.projectPath);if(c){i(a,"operations","complete");for(let m of f.artifactsGenerated){let g=`aidlc-docs/${this.workflowId}/operations/${m}`,y=m.replace(/\.(md|json)$/,"").toUpperCase().replace(/-/g,"_");s(a,{id:`OPS-${y}`,type:y,phase:"operations",stage:"code-generation",path:g,validation_passed:!0,write_complete:!0,checksum:null})}}u&&(u.current_phase="operations",u.phases.operations.status="complete",u.phases.operations.completed_at=new Date().toISOString(),u.updated_at=new Date().toISOString(),await P(this.projectPath,u)),console.log(`[WorkflowEngine] Operations phase: Generated ${f.artifactsGenerated.length} artifacts (depth: ${d})`),console.log(`[WorkflowEngine] Operations artifacts: ${f.artifactsGenerated.join(", ")}`);try{let m={type:"phase_complete",phase:"operations",details:`${f.artifactsGenerated.length} artifacts generated (depth: ${d})`},g={workflowId:this.workflowId,featureName:this.featureName,projectPath:this.projectPath,sessionId:"engine",phase:"operations"},y=Ve(m,g);ue(y)}catch(m){console.error("[WorkflowEngine] Failed to capture operations phase discovery:",m)}break}}}async completeWorkflow(t){t.status="complete";try{let n=$n.join(this.projectPath,".claude","CLAUDE.md");if(ge.existsSync(n)){let r=ge.readFileSync(n,"utf-8"),o=cg(r);ge.writeFileSync(n,o,"utf-8"),console.log("[WorkflowEngine] Removed AI-DLC rules from .claude/CLAUDE.md (workflow complete)")}}catch(n){console.error("[WorkflowEngine] Failed to remove AI-DLC rules from CLAUDE.md:",n)}await P(this.projectPath,t),await Wi(this.projectPath,this.workflowId)}async approveWorkflowRouting(t){let n=Xr(this.projectPath,this.workflowId);if(!n)throw new Error(`No Workflow Routing found for workflow: ${this.workflowId}`);n.approved_at=new Date().toISOString(),n.approved_by="human",await as(this.projectPath,this.workflowId,n);let r=await A(this.projectPath,this.workflowId);if(r){let s=r;if(s.inception_stages?.["workflow-planning"]){let i=s.inception_stages["workflow-planning"];i.status!=="completed"&&i.status!=="skipped"&&(i.status="completed",i.completed_at=new Date().toISOString(),await P(this.projectPath,r))}}let o=`${this.projectPath}/aidlc-docs/${this.workflowId}/manifest.json`;try{je(o,{phase:"inception",action:"approved",actor:"human",reason:t||"Workflow Routing approved"})}catch{}console.log("[WorkflowEngine] Workflow Routing approved")}setupInterruptHandler(){this.interruptHandler=async()=>{console.log(`
|
|
1141
|
+
workflow identity \u2014 do NOT search for a separate core-workflow.md file.`}var wC=["set up","build out","roll out","hook up","wire up","spin up","build","create","add","implement","design","make","develop","configure","integrate","fix","update","refactor","migrate","deploy","setup","establish","introduce","enable","write","construct","generate","define","prepare"];function Ya(e){let t=e.trim();(t.includes("/")||t.includes("\\"))&&(t=t.split(/[/\\]/).pop()||t),t=t.replace(/\.[a-z]{1,4}$/i,"");let n=[...wC].sort((s,i)=>i.length-s.length);for(let s of n){let i=new RegExp(`^${s}\\s+`,"i");if(i.test(t)){t=t.replace(i,"");break}}t=t.replace(/^(?:a|an|the)\s+/i,"");let r=t.replace(/\s+(?:for|with|using|via|in|to|on|at|from|into|across|through|about|of)\s+.+$/i,"").trim();r.length>0&&(t=r);let o=t.toLowerCase().replace(/[_\s]+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"");if(o.length>40){let s=o.substring(0,40),i=s.lastIndexOf("-");o=i>0?s.substring(0,i):s,o=o.replace(/-$/,"")}if(!o)throw new Error("Feature name produced an empty workflow ID after sanitization");if(o==="completed")throw new Error("'completed' is a reserved directory name and cannot be used as a workflow ID");return o}var Va=["intent","unit","code-generation","complete"];function _C(e){let t=Va.indexOf(e);return t===-1||t>=Va.length-1?"complete":Va[t+1]}var _s=class{projectPath;featureName;workflowId;interruptHandler=null;constructor(t,n){this.projectPath=t,this.featureName=n,this.workflowId=Ya(n)}async start(t){let n={schema_version:"3.0.0",workflow_id:this.workflowId,feature_name:this.featureName,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),current_phase:"inception",current_stage:"intent",status:"in_progress",origin:"hook-init",phases:{discovery:{status:"not_started",started_at:null,completed_at:null,gate_result:null,gate_bypassed:!1,bypass_reason:null},inception:{status:"in_progress",started_at:new Date().toISOString(),completed_at:null,gate_result:null,gate_bypassed:!1,bypass_reason:null},construction:{status:"not_started",started_at:null,completed_at:null,gate_result:null,gate_bypassed:!1,bypass_reason:null},operations:{status:"not_started",started_at:null,completed_at:null,gate_result:null,gate_bypassed:!1,bypass_reason:null}},manifest_path:`aidlc-docs/${this.workflowId}/manifest.json`,trust_state_path:".olympus/trust-state.json",resume_context:{initial_prompt:t}};try{await Op(this.projectPath,this.workflowId)}catch(o){let s=o;throw console.error(`[WorkflowEngine] Failed to initialize workflow directory: ${s.message}`),new Error(`Failed to start workflow: Could not create directory structure - ${s.message}`)}let r=In.join(this.projectPath,"aidlc-docs",this.workflowId,"manifest.json");if(!ge.existsSync(r))try{qi(this.workflowId,this.featureName,this.projectPath)}catch(o){console.warn(`[WorkflowEngine] Failed to create manifest: ${o.message}`)}try{await P(this.projectPath,n)}catch(o){let s=o;throw console.error(`[WorkflowEngine] Failed to save initial checkpoint: ${s.message}`),new Error(`Failed to start workflow: Could not save checkpoint - ${s.message}`)}try{let s=(await Tn(this.projectPath)).sourceFileCount??0,i=await xa(this.projectPath,t),a=hs(t),c=await Aa({projectPath:this.projectPath,workflowId:this.workflowId,intentText:t,depthAssessment:a,pathwayType:i,sourceFileCount:s}),l=await ss(this.projectPath,this.workflowId,c),u=await A(this.projectPath,this.workflowId);if(u){u.workflow_routing_path=l,u.pathway_type=i,u.depth_score=a.total_score;let d=["discovery","inception","construction","operations"];u.skipped_phases=d.filter(p=>!is(c,p)),await P(this.projectPath,u)}if(console.log(`[WorkflowEngine] Generated Workflow Routing: pathway=${i}, depth=${c.estimated_depth}, bolts=${c.estimated_bolts}`),c.stages.some(d=>!d.included)){let d=c.stages.filter(p=>!p.included).map(p=>`${p.phase}/${p.stage}`);console.log(`[WorkflowEngine] Stages excluded by plan: ${d.join(", ")}`)}}catch(o){console.warn(`[WorkflowEngine] Failed to generate Workflow Routing: ${o.message}`),console.warn("[WorkflowEngine] Workflow will proceed without adaptive phase selection")}try{let s=(await A(this.projectPath,this.workflowId))?.pathway_type;if(!s){let{isBrownfield:u}=await Tn(this.projectPath);s=u?"brownfield-enhancement":"greenfield"}let i=In.join(this.projectPath,".claude","CLAUDE.md"),a=ge.existsSync(i)?ge.readFileSync(i,"utf-8"):"",c=La(this.workflowId,s),l=Ma(a,c);ge.mkdirSync(In.join(this.projectPath,".claude"),{recursive:!0}),ge.writeFileSync(i,l,"utf-8"),console.log("[WorkflowEngine] Injected AI-DLC rules into .claude/CLAUDE.md")}catch(o){console.error("[WorkflowEngine] Failed to inject AI-DLC rules into CLAUDE.md:",o)}}async resume(){let t;try{t=await A(this.projectPath,this.workflowId)}catch(r){let o=r;throw console.error(`[WorkflowEngine] Failed to load checkpoint for resume: ${o.message}`),new Error(`Failed to resume workflow: Could not load checkpoint - ${o.message}`)}if(!t)throw console.error(`[WorkflowEngine] No checkpoint found for workflow: ${this.workflowId}`),console.error("[WorkflowEngine] Available workflows: Run 'olympus workflow list' to see workflows"),new Error(`No checkpoint found for workflow: ${this.workflowId}`);if(t.status==="complete")return"Workflow already complete";if(t.status==="paused"){t.status="in_progress";try{await P(this.projectPath,t)}catch(r){let o=r;throw console.error(`[WorkflowEngine] Failed to update checkpoint status: ${o.message}`),new Error(`Failed to resume workflow: Could not save checkpoint - ${o.message}`)}}try{let r=t.pathway_type;if(!r){let{isBrownfield:c}=await Tn(this.projectPath);r=c?"brownfield-enhancement":"greenfield"}let o=In.join(this.projectPath,".claude","CLAUDE.md"),s=ge.existsSync(o)?ge.readFileSync(o,"utf-8"):"",i=La(this.workflowId,r),a=Ma(s,i);ge.mkdirSync(In.join(this.projectPath,".claude"),{recursive:!0}),ge.writeFileSync(o,a,"utf-8"),console.log("[WorkflowEngine] Injected AI-DLC rules into .claude/CLAUDE.md")}catch(r){console.error("[WorkflowEngine] Failed to inject AI-DLC rules into CLAUDE.md:",r)}this.setupInterruptHandler();let n=t.current_stage;try{await this.executeStage(n)}catch(r){let o=r;console.error(`[WorkflowEngine] Failed to execute ${n} stage: ${o.message}`);try{let s=await A(this.projectPath,this.workflowId);s&&(s.status="paused",s.resume_context={...s.resume_context,error_message:o.message,failed_stage:n},await P(this.projectPath,s),console.log("[WorkflowEngine] Workflow saved as paused. Fix the issue and resume with `/continue`"))}catch(s){console.warn("[WorkflowEngine] Failed to save error checkpoint:",s.message)}throw new Error(`Failed to execute ${n} stage: ${o.message}`)}finally{this.cleanupInterruptHandler()}return`Resumed workflow from stage: ${n}`}async pause(){let t;try{t=await A(this.projectPath,this.workflowId)}catch(n){let r=n;throw console.error(`[WorkflowEngine] Failed to load checkpoint for pause: ${r.message}`),new Error(`Failed to pause workflow: Could not load checkpoint - ${r.message}`)}if(!t)throw console.error(`[WorkflowEngine] No checkpoint found for workflow: ${this.workflowId}`),new Error(`No checkpoint found for workflow: ${this.workflowId}`);t.status="paused";try{await P(this.projectPath,t)}catch(n){let r=n;throw console.error(`[WorkflowEngine] Failed to save paused checkpoint: ${r.message}`),new Error(`Failed to pause workflow: Could not save checkpoint - ${r.message}`)}return`aidlc-docs/${this.workflowId}/checkpoint.json`}async executeStage(t){if(t==="complete")throw new Error("No execution for complete stage");let n=await A(this.projectPath,this.workflowId);if(!n)throw new Error(`No checkpoint found for workflow: ${this.workflowId}`);switch(t){case"intent":await this.executeIntentStage(n);break;case"unit":await this.executeUnitStage(n);break;case"code-generation":await this.executeCodeGenerationStage(n);break}let r=_C(t);n.current_stage=r,r==="complete"?await this.completeWorkflow(n):await P(this.projectPath,n)}async getStatus(){let t;try{t=await A(this.projectPath,this.workflowId)}catch(r){let o=r;throw console.error(`[WorkflowEngine] Failed to load checkpoint for status: ${o.message}`),new Error(`Failed to get workflow status: Could not load checkpoint - ${o.message}`)}if(!t)throw console.error(`[WorkflowEngine] No checkpoint found for workflow: ${this.workflowId}`),new Error(`No checkpoint found for workflow: ${this.workflowId}`);let n=[];return{workflow_id:t.workflow_id,feature_name:t.feature_name,current_stage:t.current_stage,status:t.status,artifacts:n,updated_at:t.updated_at}}async executePhase(t){let n=zr(this.projectPath,this.workflowId);if(n&&!is(n,t)){console.log(`[WorkflowEngine] Skipping ${t} phase (excluded by Workflow Routing: ${n.phases[t]?.rationale||"no rationale"})`);let r=await A(this.projectPath,this.workflowId);if(r){let s=r;s.phases&&s.phases[t]&&(s.phases[t].status="complete",s.phases[t].completed_at=new Date().toISOString(),s.phases[t].gate_bypassed=!0,s.phases[t].bypass_reason="Excluded by Workflow Routing"),await P(this.projectPath,r)}let o=`${this.projectPath}/aidlc-docs/${this.workflowId}/manifest.json`;try{De(o,{phase:t,action:"bypassed",actor:"config",reason:`Excluded by Workflow Routing (pathway: ${n.pathway})`})}catch{}return}switch(t){case"discovery":{let r=`${this.projectPath}/aidlc-docs/${this.workflowId}/manifest.json`,o=await lm({projectPath:this.projectPath,workflowId:this.workflowId,featureName:this.featureName,manifestPath:r});o.gateRequired&&(console.log(`[WorkflowEngine] Discovery phase: ${o.artifactsGenerated.length} artifacts generated (${o.sourceFileCount} source files detected)`),console.log(`[WorkflowEngine] Discovery Gate: Review findings in aidlc-docs/${this.workflowId}/discovery/ before proceeding to Inception`));try{let s=await A(this.projectPath,this.workflowId);s&&(s.phases.discovery.status="complete",s.phases.discovery.completed_at=new Date().toISOString(),await P(this.projectPath,s))}catch(s){console.error("[WorkflowEngine] Failed to persist discovery phase completion:",s)}try{let s={type:"phase_complete",phase:"discovery",details:`${o.artifactsGenerated.length} artifacts generated, ${o.sourceFileCount} source files`},i={workflowId:this.workflowId,featureName:this.featureName,projectPath:this.projectPath,sessionId:"engine",phase:"discovery"},a=He(s,i);ue(a)}catch(s){console.error("[WorkflowEngine] Failed to capture discovery phase discovery:",s)}break}case"inception":{let{InceptionOrchestrator:r}=await Promise.resolve().then(()=>(gg(),mg)),o=new r,s=await A(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=zr(this.projectPath,this.workflowId),a=s;await o.initialize(this.projectPath,this.workflowId,a.pathway_type||"greenfield",i)}for(;!await o.isComplete(this.projectPath,this.workflowId);){let i=await o.executeNextStage(this.projectPath,this.workflowId);if(i.status==="awaiting_answers"||i.status==="review_required")break}if(await o.isComplete(this.projectPath,this.workflowId))try{let i=await A(this.projectPath,this.workflowId);i&&(i.phases.inception.status="complete",i.phases.inception.completed_at=new Date().toISOString(),await P(this.projectPath,i))}catch(i){console.error("[WorkflowEngine] Failed to persist inception phase completion:",i)}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=He(i,a);ue(c)}catch(i){console.error("[WorkflowEngine] Failed to capture inception phase discovery:",i)}break}case"construction":{let r=await A(this.projectPath,this.workflowId);if(r&&r.status==="awaiting_dev_review"){console.log("[WorkflowEngine] Waiting for developer review of technical specification (Risk Tier 3).");return}let o=at(this.projectPath,this.workflowId,"intent"),s;try{s=ge.readFileSync(o,"utf-8")}catch{}let a=await new gs(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=await A(this.projectPath,this.workflowId);c&&(c.phases.construction.status="complete",c.phases.construction.completed_at=new Date().toISOString(),await P(this.projectPath,c))}catch(c){console.error("[WorkflowEngine] Failed to persist construction phase completion:",c)}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=He(c,l);ue(u)}catch(c){console.error("[WorkflowEngine] Failed to capture construction phase discovery:",c)}break}case"operations":{let{generateOperationsArtifacts:r}=await Promise.resolve().then(()=>(vg(),Sg)),{loadManifest:o,registerArtifact:s,updatePhaseStatus:i}=await Promise.resolve().then(()=>(Z(),kn)),a=`${this.projectPath}/aidlc-docs/${this.workflowId}/manifest.json`,c=o(a),l=null;try{l=ge.readFileSync(at(this.projectPath,this.workflowId,"intent"),"utf-8")}catch{}let u=await A(this.projectPath,this.workflowId),d="MEDIUM";if(c?.depth_assessment){let m=c.depth_assessment.total_score;m<=10?d="SHALLOW":m>=21&&(d="DEEP")}let p={workflowId:this.workflowId,featureName:this.featureName,manifest:c,specContent:l,buildLogContent:null,depthLevel:d},f=await r(p,this.projectPath);if(c){i(a,"operations","complete");for(let m of f.artifactsGenerated){let g=`aidlc-docs/${this.workflowId}/operations/${m}`,y=m.replace(/\.(md|json)$/,"").toUpperCase().replace(/-/g,"_");s(a,{id:`OPS-${y}`,type:y,phase:"operations",stage:"code-generation",path:g,validation_passed:!0,write_complete:!0,checksum:null})}}u&&(u.current_phase="operations",u.phases.operations.status="complete",u.phases.operations.completed_at=new Date().toISOString(),u.updated_at=new Date().toISOString(),await P(this.projectPath,u)),console.log(`[WorkflowEngine] Operations phase: Generated ${f.artifactsGenerated.length} artifacts (depth: ${d})`),console.log(`[WorkflowEngine] Operations artifacts: ${f.artifactsGenerated.join(", ")}`);try{let m={type:"phase_complete",phase:"operations",details:`${f.artifactsGenerated.length} artifacts generated (depth: ${d})`},g={workflowId:this.workflowId,featureName:this.featureName,projectPath:this.projectPath,sessionId:"engine",phase:"operations"},y=He(m,g);ue(y)}catch(m){console.error("[WorkflowEngine] Failed to capture operations phase discovery:",m)}break}}}async completeWorkflow(t){t.status="complete";try{let n=In.join(this.projectPath,".claude","CLAUDE.md");if(ge.existsSync(n)){let r=ge.readFileSync(n,"utf-8"),o=ag(r);ge.writeFileSync(n,o,"utf-8"),console.log("[WorkflowEngine] Removed AI-DLC rules from .claude/CLAUDE.md (workflow complete)")}}catch(n){console.error("[WorkflowEngine] Failed to remove AI-DLC rules from CLAUDE.md:",n)}await P(this.projectPath,t),await Ui(this.projectPath,this.workflowId)}async approveWorkflowRouting(t){let n=zr(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 ss(this.projectPath,this.workflowId,n);let r=await A(this.projectPath,this.workflowId);if(r){let s=r;if(s.inception_stages?.["workflow-planning"]){let i=s.inception_stages["workflow-planning"];i.status!=="completed"&&i.status!=="skipped"&&(i.status="completed",i.completed_at=new Date().toISOString(),await P(this.projectPath,r))}}let o=`${this.projectPath}/aidlc-docs/${this.workflowId}/manifest.json`;try{De(o,{phase:"inception",action:"approved",actor:"human",reason:t||"Workflow Routing approved"})}catch{}console.log("[WorkflowEngine] Workflow Routing approved")}setupInterruptHandler(){this.interruptHandler=async()=>{console.log(`
|
|
1142
1142
|
[WorkflowEngine] Workflow interrupted - saving checkpoint...`);try{let t=await A(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 P(this.projectPath,t),console.log("[WorkflowEngine] Checkpoint saved. Resume with `/continue`"))}catch(t){console.error("[WorkflowEngine] Failed to save checkpoint on interrupt:",t)}process.exit(0)},process.on("SIGINT",this.interruptHandler)}cleanupInterruptHandler(){this.interruptHandler&&(process.off("SIGINT",this.interruptHandler),this.interruptHandler=null)}async executeIntentStage(t){let n=t.resume_context?.initial_prompt||"No initial prompt provided";console.log(`[WorkflowEngine] Executing INTENT stage for feature: ${this.featureName}`),console.log(`[WorkflowEngine] Initial prompt: ${n}`),console.log("[WorkflowEngine] Generating merged INTENT artifact with full inception content");let r=`intent-${this.workflowId}`,o=new Date().toISOString(),s=`---
|
|
1143
1143
|
id: ${r}
|
|
1144
1144
|
title: ${this.featureName}
|
|
@@ -1290,7 +1290,7 @@ The implementation follows the existing system architecture patterns. Core funct
|
|
|
1290
1290
|
|
|
1291
1291
|
---
|
|
1292
1292
|
*Generated by WorkflowEngine based on ${r}*
|
|
1293
|
-
`;await
|
|
1293
|
+
`;await zn(this.projectPath,this.workflowId,"intent",s);let a=`---
|
|
1294
1294
|
id: ${`nfr-${this.workflowId}`}
|
|
1295
1295
|
parent: "${r}"
|
|
1296
1296
|
status: draft
|
|
@@ -1340,7 +1340,7 @@ created: ${o}
|
|
|
1340
1340
|
|
|
1341
1341
|
---
|
|
1342
1342
|
*Generated by WorkflowEngine based on ${r}*
|
|
1343
|
-
`;await
|
|
1343
|
+
`;await zn(this.projectPath,this.workflowId,"nfr",a),console.log("[WorkflowEngine] Generated NFR artifact at inception/requirements/nfr.md");let c=at(this.projectPath,this.workflowId,"intent");console.log(`[WorkflowEngine] Validating INTENT artifact at: ${c}`);let l=await Uo(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 A(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 P(this.projectPath,u)}}async executeUnitStage(t){console.log("[WorkflowEngine] UNIT stage delegated to construction phase executor"),await this.executePhase("construction")}async executeCodeGenerationStage(t){console.log("[WorkflowEngine] CODE-GENERATION stage delegated to construction phase executor"),await this.executePhase("construction")}};ce();var bg={intent:null,unit:null,"code-generation":null,complete:null};function Eg(e){switch(e){case"intent":return"capture the problem statement, personas, success metrics, constraints, and define business requirements, technical approach, and proposed UNITs";case"unit":return"decompose into module-scoped UNITs with interface contracts";case"code-generation":return"generate code from the approved code plan";case"complete":return"finalize and validate all workflow artifacts";default:return"proceed with the next stage"}}function Tg(e,t,n=!1){let r=t.current_stage,o=bg[r],s=Eg(r),i=`You are beginning a structured workflow for feature: ${e}
|
|
1344
1344
|
|
|
1345
1345
|
`;return i+=`Current stage: ${r}
|
|
1346
1346
|
`,i+=`Status: ${t.status}
|
|
@@ -1351,7 +1351,7 @@ created: ${o}
|
|
|
1351
1351
|
`):i+=`Next step: ${s}
|
|
1352
1352
|
`,n&&(i+=`
|
|
1353
1353
|
IMPORTANT: This is a BRAND NEW workflow just initialized. `,i+="Do NOT treat this as a resumed or existing workflow. ",i+=`Proceed with workspace detection as the first step.
|
|
1354
|
-
`),i}function
|
|
1354
|
+
`),i}function Cg(e,t){let n=t.current_stage,r=bg[n],o=Eg(n),s=`Resuming workflow for feature: ${e}
|
|
1355
1355
|
|
|
1356
1356
|
`;return s+=`You were interrupted during: ${n}
|
|
1357
1357
|
`,s+=`Last update: ${t.updated_at}
|
|
@@ -1364,17 +1364,17 @@ IMPORTANT: This is a BRAND NEW workflow just initialized. `,i+="Do NOT treat thi
|
|
|
1364
1364
|
|
|
1365
1365
|
`,s+=`Use: Task(subagent_type="${r}", prompt="...")
|
|
1366
1366
|
`):s+=`Continue from where you left off: ${o}
|
|
1367
|
-
`,s}function
|
|
1367
|
+
`,s}function Ka(e){return e.prompt?e.prompt:e.message?.content?e.message.content:e.parts?e.parts.filter(t=>t.type==="text"&&t.text).map(t=>t.text).join(" "):""}function Rg(){I({name:"structuredWorkflowDetector",event:"UserPromptSubmit",priority:8,handler:async e=>{let t=Ka(e);if(!t||!e.directory)return{continue:!0};let n=t.match(/^\/plan\s+(?!continue\b|--)([\s\S]+?)$/i),r=t.match(/^\/plan\s+continue$/i);if(n){let o=n[1].trim();o=o.replace(/\s+--structured\s*/i,"").trim();let s,i=o.match(/\s+--depth\s+(shallow|medium|deep)\s*$/i);i&&(s=i[1].toLowerCase(),o=o.replace(i[0],"").trim());let a,c=o.match(/\s+--(brownfield|greenfield)\s*$/i);if(c&&(a=c[1].toLowerCase(),o=o.replace(c[0],"").trim()),o.length>120)return console.error("[Structured Workflow] Feature name too long, likely not a real feature name:",o.substring(0,50)+"..."),{continue:!0};if(/\b(lets|let's|please|proceed|creating|we should|i want to|i need to|going to)\b/i.test(o))return console.error("[Structured Workflow] Feature name looks like conversational text, skipping:",o.substring(0,50)+"..."),{continue:!0};try{await new _s(e.directory,o).start(o);let d=Ya(o),p=await A(e.directory,d);if(!p)return{continue:!0};let f=Tg(o,p,!0),g=`${`[Workflow: ${d} | Phase: ${p.current_phase||"inception"} | Stage: ${p.current_stage||"intent"}]`}
|
|
1368
1368
|
|
|
1369
1369
|
${f}`;return s&&(g+=`
|
|
1370
1370
|
|
|
1371
1371
|
Depth override: ${s}`),a&&(g+=`
|
|
1372
1372
|
|
|
1373
|
-
Project type: ${a}`),{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:g}}}catch(u){return console.error("[Structured Workflow]",u),{continue:!0}}}if(r)try{let o=await oe(e.directory);if(o.length===0)return{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:"No active workflows found. Use `/plan {feature}` to start a new workflow."}};let s=o[0],i=await A(e.directory,s);if(!i)return{continue:!0};let a=
|
|
1373
|
+
Project type: ${a}`),{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:g}}}catch(u){return console.error("[Structured Workflow]",u),{continue:!0}}}if(r)try{let o=await oe(e.directory);if(o.length===0)return{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:"No active workflows found. Use `/plan {feature}` to start a new workflow."}};let s=o[0],i=await A(e.directory,s);if(!i)return{continue:!0};let a=Cg(i.feature_name,i);return{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:`[TIP: For full AIDLC resume with behavioral rules, use /continue instead of /plan continue]
|
|
1374
1374
|
|
|
1375
1375
|
${`[Workflow: ${s} | Phase: ${i.current_phase||"inception"} | Stage: ${i.current_stage||"intent"}]`}
|
|
1376
1376
|
|
|
1377
|
-
${a}`}}}catch(o){return console.error("[Workflow Resume]",o),{continue:!0}}return{continue:!0}}}),I({name:"keywordDetector",event:"UserPromptSubmit",priority:10,handler:e=>{let t=
|
|
1377
|
+
${a}`}}}catch(o){return console.error("[Workflow Resume]",o),{continue:!0}}return{continue:!0}}}),I({name:"keywordDetector",event:"UserPromptSubmit",priority:10,handler:e=>{let t=Ka(e);if(!t)return{continue:!0};let n=bl(t),r=El(n);if(r.length===0)return{continue:!0};let o=r.some(c=>c.type==="ultrawork"),s=r.some(c=>c.type==="ultrathink"),i=r.some(c=>c.type==="search"),a=r.some(c=>c.type==="analyze");return o?(ql(t,e.sessionId,e.directory||process.cwd()),{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:zl}}):s?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:Ql}}:i?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:Xl}}:a?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:Zl}}:{continue:!0}}}),I({name:"autoSlashCommand",event:"UserPromptSubmit",priority:20,handler:e=>{if(!e.parts)return{continue:!0};let n=Nl().processMessage({sessionId:e.sessionId||""},e.parts);return n.detected&&n.injectedMessage?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:n.injectedMessage}}:{continue:!0}}}),I({name:"thinkMode",event:"UserPromptSubmit",priority:30,handler:e=>{if(!e.message||!e.parts)return{continue:!0};let t=Gl(),n=e.sessionId||"default",r={parts:e.parts,message:{model:e.message.model&&e.message.model.providerId&&e.message.model.modelId?{providerId:e.message.model.providerId,modelId:e.message.model.modelId}:void 0}},o=t.processChatParams(n,r);return o.requested&&o.modelSwitched?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:"[Think Mode Activated] Switched to high-reasoning model variant."}}:{continue:!0}}}),I({name:"learningFeedbackCapture",event:"UserPromptSubmit",priority:100,handler:async e=>{let t=Ka(e);return!t||!e.directory?{continue:!0}:(Promise.resolve().then(async()=>{try{await Tu({prompt:t,directory:e.directory,sessionId:e.sessionId}),await Ru({prompt:t,directory:e.directory,sessionId:e.sessionId})}catch(n){console.error("[Olympus Learning]",n)}}),{continue:!0})}})}var Ja=require("child_process");var kC="mcpProcessCleanup",SC=/mcp/i;function vC(e){return e?SC.test(e):!1}function bC(e,t){return e.filter(n=>vC(n.CommandLine)?!t.has(n.ParentProcessId):!1)}function EC(e){let t=0;for(let n of e)try{(0,Ja.execSync)(`taskkill /T /F /PID ${n.ProcessId}`,{encoding:"utf8",timeout:5e3,stdio:"pipe"}),t++}catch{}return t}function TC(){if(process.platform!=="win32")return 0;try{let e=`
|
|
1378
1378
|
$nodeProcs = Get-CimInstance Win32_Process -Filter "Name='node.exe'" |
|
|
1379
1379
|
Select-Object ProcessId, ParentProcessId, CommandLine;
|
|
1380
1380
|
$allPids = (Get-Process -ErrorAction SilentlyContinue).Id;
|
|
@@ -1382,7 +1382,7 @@ ${a}`}}}catch(o){return console.error("[Workflow Resume]",o),{continue:!0}}retur
|
|
|
1382
1382
|
nodeProcesses = @($nodeProcs | ForEach-Object { @{ ProcessId=$_.ProcessId; ParentProcessId=$_.ParentProcessId; CommandLine=$_.CommandLine } });
|
|
1383
1383
|
allPids = @($allPids)
|
|
1384
1384
|
} | ConvertTo-Json -Depth 3
|
|
1385
|
-
`.replace(/\n/g," "),t=(0,
|
|
1385
|
+
`.replace(/\n/g," "),t=(0,Ja.execSync)(`powershell -NoProfile -Command "${e}"`,{encoding:"utf8",timeout:15e3,stdio:["pipe","pipe","pipe"]}),n=JSON.parse(t),r=Array.isArray(n.nodeProcesses)?n.nodeProcesses:n.nodeProcesses?[n.nodeProcesses]:[],o=new Set(Array.isArray(n.allPids)?n.allPids:n.allPids?[n.allPids]:[]),s=bC(r,o);return s.length===0?0:EC(s)}catch(e){return console.error("[Olympus MCP Cleanup] Error:",e),0}}function xg(){I({name:kC,event:"SessionStart",priority:1,handler:e=>{let t=TC();return t>0?{continue:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:`[MCP Cleanup] Removed ${t} orphaned MCP server process${t===1?"":"es"} from previous session(s).`}}:{continue:!0}}})}var On=require("fs"),cn=require("path"),Pg=require("os");function CC(e,t){let n=(0,cn.join)((0,Pg.homedir)(),".claude"),r=[];e&&(r.push((0,cn.join)(n,"sessions",e,"todos.json")),r.push((0,cn.join)(n,"todos",`${e}.json`))),t&&(r.push((0,cn.join)(t,".olympus","todos.json")),r.push((0,cn.join)(t,".claude","todos.json")));let o=(0,cn.join)(n,"todos");if((0,On.existsSync)(o))try{let s=(0,On.readdirSync)(o);for(let i of s)i.endsWith(".json")&&r.push((0,cn.join)(o,i))}catch{}return r}function RC(e){try{let t=(0,On.readFileSync)(e,"utf-8"),n=JSON.parse(t);return Array.isArray(n)?n.filter(r=>r&&typeof r.content=="string"&&typeof r.status=="string"):n.todos&&Array.isArray(n.todos)?n.todos.filter(r=>{let o=r;return o&&typeof o.content=="string"&&typeof o.status=="string"}):[]}catch{return[]}}function xC(e){return e.status!=="completed"&&e.status!=="cancelled"}async function Zr(e,t){let n=CC(e,t),r=new Set,o=[],s=[];for(let i of n){if(!(0,On.existsSync)(i))continue;let a=RC(i);for(let c of a){let l=`${c.content}:${c.status}`;r.has(l)||(r.add(l),o.push(c),xC(c)&&s.push(c))}}return{count:s.length,todos:s,total:o.length}}function Ag(e){let t=e.todos.find(n=>n.status==="in_progress");return t||(e.todos.find(n=>n.status==="pending")??null)}var za=require("path");ye();Jo();ye();function Ig(e,t=5){return(e.token_efficiency?.invocation_count??0)>=t}bi();var Og=500;function $g(e){let t=we((0,za.join)(pe(),"user-preferences.json"),null),n=we((0,za.join)(yt(e),"patterns.json"),null),r=Gn(),o=Gn(e),s={...r,...o},i=[];if(t&&PC(t)){let u=t.explicit_rules.filter(p=>!p.project_path||p.project_path===e),d={...t,explicit_rules:u};i.push(AC(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(IC(n)),t?.recurring_corrections&&t.recurring_corrections.length>0&&i.push(OC(t.recurring_corrections.slice(0,5)));let a=Object.values(s).filter(u=>u.weak_areas.length>0);a.length>0&&i.push($C(a));let c=DC(s);if(c&&i.push(c),i.length===0)return"";let l=`<learned-context>
|
|
1386
1386
|
|
|
1387
1387
|
${i.join(`
|
|
1388
1388
|
|
|
@@ -1392,21 +1392,21 @@ ${i.join(`
|
|
|
1392
1392
|
|
|
1393
1393
|
---
|
|
1394
1394
|
|
|
1395
|
-
`;return l.length
|
|
1395
|
+
`;return l.length>Og*4?l.substring(0,Og*4)+`
|
|
1396
1396
|
...</learned-context>
|
|
1397
1397
|
|
|
1398
1398
|
---
|
|
1399
1399
|
|
|
1400
|
-
`:l}function
|
|
1401
|
-
`)}function
|
|
1402
|
-
`)}function
|
|
1403
|
-
`)}function
|
|
1404
|
-
`)}function
|
|
1405
|
-
`)}function
|
|
1406
|
-
`)}
|
|
1407
|
-
`);for(let o of r){let s=o.trim();if(s.startsWith("# "))return s.slice(2).trim()}return t}catch{return t}}function
|
|
1408
|
-
`)}catch(t){return console.error("[WorkflowBridge] Failed to generate workflow summary:",t),""}}async function
|
|
1409
|
-
`)}catch(t){return console.error("[WorkflowBridge] Failed to generate bolt execution plan:",t),""}}async function
|
|
1400
|
+
`:l}function PC(e){return e.verbosity!=="unknown"||e.autonomy!=="unknown"||e.explicit_rules.length>0||e.inferred_preferences.length>0}function AC(e){let t=["## User Preferences"];e.verbosity!=="unknown"&&t.push(`- Verbosity: ${e.verbosity}`),e.autonomy!=="unknown"&&t.push(`- Autonomy: ${e.autonomy}`);for(let n of e.explicit_rules.slice(0,5)){let r=typeof n=="string"?n:n.rule;t.push(`- ${r}`)}return t.join(`
|
|
1401
|
+
`)}function IC(e){let t=["## Project Conventions"];for(let n of e.conventions.slice(0,5))t.push(`- ${n}`);if(e.tech_stack.length>0&&t.push(`- Tech: ${e.tech_stack.join(", ")}`),e.learned_rules&&e.learned_rules.length>0)for(let n of e.learned_rules.slice(0,3))t.push(`- Rule: ${n}`);if(e.common_mistakes&&e.common_mistakes.length>0)for(let n of e.common_mistakes.slice(0,3))t.push(`- Watch out: ${n}`);return t.join(`
|
|
1402
|
+
`)}function OC(e){let t=["## Avoid These Mistakes"];for(let n of e)t.push(`- ${n.pattern} (${n.count}x)`);return t.join(`
|
|
1403
|
+
`)}function $C(e){let t=["## Agent Notes"];for(let n of e.slice(0,3))t.push(`- ${n.agent_name}: struggles with ${n.weak_areas.join(", ")}`);return t.join(`
|
|
1404
|
+
`)}function DC(e){let t=Object.values(e).filter(a=>a.token_efficiency&&Ig(a)).sort((a,c)=>{let l=a.token_efficiency?.efficiency_score??0;return(c.token_efficiency?.efficiency_score??0)-l});if(t.length===0)return"";let n=[];n.push("<olympus-efficiency>"),n.push("AGENT EFFICIENCY (success%/avg tokens):");for(let a of t.slice(0,3)){let c=Math.round(a.success_rate*100),l=a.token_efficiency.avg_tokens_per_success,u=l>=1e3?`${(l/1e3).toFixed(1)}k`:`${Math.round(l)}`,p=a.success_rate>=.9&&a.token_efficiency.efficiency_score>.8?" [PREFERRED]":"";n.push(`- ${a.agent_name}: ${c}%/${u}${p}`)}let r=hn(),o=r>=1e3?`${(r/1e3).toFixed(0)}k`:r.toString(),s=Math.round(r*1.5),i=s>=1e3?`${(s/1e3).toFixed(0)}k`:s.toString();return n.push(""),n.push(`SESSION BUDGET: ~${o} baseline | warn at ${i}`),n.push("PATTERNS: Parallel reads save 40%"),n.push(""),n.push("Quality remains priority. Use efficiency as tiebreaker."),n.push("</olympus-efficiency>"),n.join(`
|
|
1405
|
+
`)}function Dg(e){if(e.length===0)return"";let t=["## Agent Discoveries"];t.push(""),t.push("These insights were discovered during previous work:"),t.push("");for(let n of e.slice(0,5))t.push(`- **${n.category}**: ${n.summary}`),t.push(` ${n.details.substring(0,200)}`);return t.join(`
|
|
1406
|
+
`)}Mt();Ue();var Fg=v(require("path"),1);ce();Z();var ut=v(require("path"),1),Ss=v(X(),1);Z();ce();rn();async function vs(e){try{let t=await oe(e);if(t.length===0)return null;let n=t[0],r=ut.join(e,"aidlc-docs",n,"manifest.json"),o=W(r);if(!o)return null;let s=await A(e,n);if(!s)return null;let i=be(e),a=NC(o),l=Yi(o,"fulfilled").map(p=>p.id),d=_n(o).filter(p=>p.contract_status!=="fulfilled").map(p=>p.id);return{workflowId:s.workflow_id,featureName:s.feature_name,currentPhase:s.current_phase,currentStage:s.current_stage,manifest:o,checkpoint:s,trustLevel:i.current_level,riskTier:s.risk_tier??0,depthScore:s.depth_score??0,pendingBolts:a,completedBolts:l,pendingUnits:d,executionMode:s.execution_mode??"manual"}}catch(t){return console.error("[WorkflowBridge] Failed to detect active workflow:",t),null}}function NC(e){return vt(e).filter(n=>n.contract_status!=="fulfilled").map(n=>n.id)}function jC(e){let t=_n(e),n=vt(e),r=[...t].sort((a,c)=>a.id.localeCompare(c.id)),o=[],s=new Set;for(let a of r){let l=[...vt(e,a.id)].sort((u,d)=>u.id.localeCompare(d.id));for(let u of l)o.push(u.id),s.add(u.id)}let i=n.filter(a=>!s.has(a.id)).sort((a,c)=>a.id.localeCompare(c.id));for(let a of i)o.push(a.id);return o}function to(e){let t=vt(e),n=t.length;if(n===0)return{completed:0,total:0,percentage:0};let r=t.filter(s=>s.contract_status==="fulfilled").length,o=Math.round(r/n*100);return{completed:r,total:n,percentage:o}}function eo(e,t){try{if(!Ss.existsSync(e))return t;let r=Ss.readFileSync(e,"utf-8").split(`
|
|
1407
|
+
`);for(let o of r){let s=o.trim();if(s.startsWith("# "))return s.slice(2).trim()}return t}catch{return t}}function ks(e,t){return e.links.find(r=>r.target_id===t&&(r.link_type==="derives"||r.link_type==="implements"))?.source_id??null}function FC(e){let t=e.toLowerCase(),n=["ui","component","frontend","style","css","layout","page","view"];for(let r of n)if(t.includes(r))return"frontend-engineer";return"olympian"}async function Ng(e){try{let t=await vs(e);if(!t)return"";let n=to(t.manifest),r=vt(t.manifest),o=[];for(let a of t.pendingBolts){if(!r.find(f=>f.id===a))continue;let l=ks(t.manifest,a),u=l?ut.join(e,"aidlc-docs",t.workflowId,"construction",l,`${a}.md`):ut.join(e,"aidlc-docs",t.workflowId,"construction",`${a}.md`),d=eo(u,a),p=l?` (${l})`:"";o.push(`- ${a} "${d}"${p}`)}let s=[];for(let a of t.completedBolts){if(!r.find(p=>p.id===a))continue;let l=ks(t.manifest,a),u=l?ut.join(e,"aidlc-docs",t.workflowId,"construction",l,`${a}.md`):ut.join(e,"aidlc-docs",t.workflowId,"construction",`${a}.md`),d=eo(u,a);s.push(`- ${a} "${d}" done`)}let i=["## Active Workflow",`Workflow: ${t.featureName} (${t.workflowId})`,`Phase: ${t.currentPhase} | Stage: ${t.currentStage}`,`Trust: Level ${t.trustLevel} | Risk: Tier ${t.riskTier} | Depth: ${t.depthScore}`,`Mode: ${t.executionMode}`,"","### Progress",`BOLTs: ${n.completed}/${n.total} (${n.percentage}%)`];return o.length>0&&(i.push("","### Pending BOLTs:"),i.push(...o)),s.length>0&&(i.push("","### Completed BOLTs:"),i.push(...s)),i.join(`
|
|
1408
|
+
`)}catch(t){return console.error("[WorkflowBridge] Failed to generate workflow summary:",t),""}}async function jg(e){try{let t=await vs(e);if(!t)return"";let n=vt(t.manifest),r=jC(t.manifest),o=new Set(t.pendingBolts),s=_n(t.manifest),i=[],a=1;for(let u of r){if(!o.has(u))continue;let d=n.find(w=>w.id===u);if(!d)continue;let p=ks(t.manifest,u),f=p?ut.join(e,"aidlc-docs",t.workflowId,"construction",p,`${u}.md`):ut.join(e,"aidlc-docs",t.workflowId,"construction",`${u}.md`),m=eo(f,u),g=FC(d.path),y="";if(p){let w=s.find(b=>b.id===p),_=ut.join(e,"aidlc-docs",t.workflowId,"construction",p,"spec.md"),h=eo(_,p);y=` (${p}: ${h})`}i.push(`${a}. ${u} "${m}"${y}`),i.push(` Agent: ${g} | Files: ${d.path}`),a++}let c=[];for(let u of t.completedBolts){if(!n.find(g=>g.id===u))continue;let p=ks(t.manifest,u),f=p?ut.join(e,"aidlc-docs",t.workflowId,"construction",p,`${u}.md`):ut.join(e,"aidlc-docs",t.workflowId,"construction",`${u}.md`),m=eo(f,u);c.push(`- ${u} "${m}" done (fulfilled)`)}let l=["## Workflow Execution Plan",`Workflow: ${t.featureName} (${t.workflowId})`,`Phase: ${t.currentPhase} | Trust: Level ${t.trustLevel} | Risk: Tier ${t.riskTier}`];return i.length>0&&(l.push("","### Pending BOLTs (execute in this order):"),l.push(...i)),c.length>0&&(l.push("","### Completed BOLTs:"),l.push(...c)),l.push("","### Instructions:"),l.push("For each pending BOLT: read its spec file, dispatch to the listed agent, then present Gate 4 review."),l.join(`
|
|
1409
|
+
`)}catch(t){return console.error("[WorkflowBridge] Failed to generate bolt execution plan:",t),""}}async function Mg(e){let t=[];try{let n=await oe(e);for(let r of n){let o=await A(e,r);if(!o||o.status==="complete"||o.status==="archived")continue;let s=Fg.join(e,"aidlc-docs",r,"manifest.json"),i=W(s),a={completed:0,total:0};i&&(a=to(i)),t.push({workflowId:o.workflow_id,featureName:o.feature_name,currentPhase:o.current_phase,currentStage:o.current_stage,progress:a,lastActivity:o.updated_at,status:o.status,interviewProgress:o.interview_progress})}}catch(n){console.error("[ResumeDetector] Error checking aidlc-docs:",n)}return t}rn();function Lg(){xg(),I({name:"learnedContextInjection",event:"SessionStart",priority:5,handler:e=>{if(!e.directory)return{continue:!0};try{let t=$g(e.directory),n=Yo(e.directory,5),r=Dg(n),o=new Date,s=new Date(o.getTime()-1440*60*1e3);for(let c of n)try{new Date(c.last_useful)<s&&hf(c.id,e.directory)}catch(l){console.error("[Olympus Learning] Failed to mark discovery as useful:",l)}return{continue:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:`<olympus-mode>
|
|
1410
1410
|
[OLYMPUS MODE ACTIVE]
|
|
1411
1411
|
You are operating as an Olympus orchestrator. MANDATORY behaviors:
|
|
1412
1412
|
- DELEGATE multi-file changes to subagents (olympian, oracle, frontend-engineer, etc.) via the Task tool
|
|
@@ -1418,11 +1418,11 @@ You are operating as an Olympus orchestrator. MANDATORY behaviors:
|
|
|
1418
1418
|
|
|
1419
1419
|
`+t+(r?`
|
|
1420
1420
|
|
|
1421
|
-
`+r:"")}}}catch(t){console.error("[Olympus Learning]",t)}return{continue:!0}}}),I({name:"workflowResumeDetection",event:"SessionStart",priority:8,handler:async e=>{try{let t=e.directory||process.cwd(),n=await
|
|
1421
|
+
`+r:"")}}}catch(t){console.error("[Olympus Learning]",t)}return{continue:!0}}}),I({name:"workflowResumeDetection",event:"SessionStart",priority:8,handler:async e=>{try{let t=e.directory||process.cwd(),n=await Mg(t);if(n.length===0)return{continue:!0};let r=[];for(let a of n)if(a.status==="awaiting_mode_selection")r.push(`[Active workflow: '${a.featureName}' \u2014 awaiting execution mode selection.
|
|
1422
1422
|
Choose: /ascent, /olympus, or /ultrawork to begin Construction]`);else if(a.status==="awaiting_dev_review")r.push(`[Active workflow: '${a.featureName}' \u2014 awaiting developer review (Risk Tier 3).
|
|
1423
1423
|
Review the INTENT technical specification before proceeding to Construction.]`);else{let c=a.progress.total>0?`, ${a.progress.completed}/${a.progress.total} BOLTs complete`:"";r.push(`[Active workflow: '${a.featureName}' \u2014 ${a.currentPhase} phase${c}.
|
|
1424
|
-
Resume with /continue or check status with /workflow-status]`)}let o=
|
|
1425
|
-
`)}}}catch(t){console.error("[Olympus Resume Detection] Error:",t)}return{continue:!0}}}),I({name:"sessionStart",event:"SessionStart",priority:10,handler:async e=>{let t=e.sessionId,n=e.directory||process.cwd(),r=[];try{let i=Q(n,t);i.token_budget||(
|
|
1424
|
+
Resume with /continue or check status with /workflow-status]`)}let o=be(t);r.push(`[Trust Level: ${o.current_level}]`);let s=await Ng(t);s&&r.push(s);let i=await jg(t);i&&r.push(i);for(let a of n)a.interviewProgress&&r.push(`[Interview in progress: ${a.interviewProgress.stage} stage, ${a.interviewProgress.questions_asked} questions asked${a.interviewProgress.draft_artifact_path?". Draft artifact exists.":""}]`);if(r.length>0)return{continue:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:r.join(`
|
|
1425
|
+
`)}}}catch(t){console.error("[Olympus Resume Detection] Error:",t)}return{continue:!0}}}),I({name:"sessionStart",event:"SessionStart",priority:10,handler:async e=>{let t=e.sessionId,n=e.directory||process.cwd(),r=[];try{let i=Q(n,t);i.token_budget||(wu(i,n),ee(n,i))}catch(i){console.error("[Olympus Learning] Failed to initialize token budget:",i)}let o=Jt(n);o?.active&&r.push(`<session-restore>
|
|
1426
1426
|
|
|
1427
1427
|
[ULTRAWORK MODE RESTORED]
|
|
1428
1428
|
|
|
@@ -1435,7 +1435,7 @@ Continue working in ultrawork mode until all tasks are complete.
|
|
|
1435
1435
|
|
|
1436
1436
|
---
|
|
1437
1437
|
|
|
1438
|
-
`);let s=await
|
|
1438
|
+
`);let s=await Zr(t,n);return s.count>0&&r.push(`<session-restore>
|
|
1439
1439
|
|
|
1440
1440
|
[PENDING TASKS DETECTED]
|
|
1441
1441
|
|
|
@@ -1447,7 +1447,7 @@ Please continue working on these tasks.
|
|
|
1447
1447
|
---
|
|
1448
1448
|
|
|
1449
1449
|
`),r.length>0?{continue:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:r.join(`
|
|
1450
|
-
`)}}:{continue:!0}}})}var
|
|
1450
|
+
`)}}:{continue:!0}}})}var pr=require("fs"),Ht=require("path"),sc=require("os");var Me=require("fs"),ln=require("path"),Ug=require("os");function Qa(e){let t=(0,ln.join)(e,".olympus");return(0,ln.join)(t,"ascent-state.json")}function MC(e){let t=(0,ln.join)(e,".olympus");(0,Me.existsSync)(t)||(0,Me.mkdirSync)(t,{recursive:!0})}function ur(e){let t=Qa(e);if(!(0,Me.existsSync)(t))return null;try{let n=(0,Me.readFileSync)(t,"utf-8");return JSON.parse(n)}catch{return null}}function LC(e,t){try{MC(e);let n=Qa(e);return(0,Me.writeFileSync)(n,JSON.stringify(t,null,2)),!0}catch{return!1}}function bs(e){let t=Qa(e);if(!(0,Me.existsSync)(t))return!0;try{return(0,Me.unlinkSync)(t),!0}catch{return!1}}function Wg(e){let t=ur(e);return!t||!t.active?null:(t.iteration+=1,LC(e,t)?t:null)}function Bg(e,t){let n=(0,ln.join)((0,Ug.homedir)(),".claude"),r=[(0,ln.join)(n,"sessions",e,"transcript.md"),(0,ln.join)(n,"sessions",e,"messages.json"),(0,ln.join)(n,"transcripts",`${e}.md`)];for(let o of r)if((0,Me.existsSync)(o))try{let s=(0,Me.readFileSync)(o,"utf-8");if(new RegExp(`<promise>\\s*${UC(t)}\\s*</promise>`,"is").test(s))return!0}catch{continue}return!1}function UC(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Ze=require("fs"),Xa=require("path"),WC=3;function Za(e){return(0,Xa.join)(e,".olympus","ascent-verification.json")}function ro(e){let t=Za(e);if(!(0,Ze.existsSync)(t))return null;try{return JSON.parse((0,Ze.readFileSync)(t,"utf-8"))}catch{return null}}function Gg(e,t){let n=Za(e),r=(0,Xa.join)(e,".olympus");if(!(0,Ze.existsSync)(r))try{(0,Ze.mkdirSync)(r,{recursive:!0})}catch{return!1}try{return(0,Ze.writeFileSync)(n,JSON.stringify(t,null,2)),!0}catch{return!1}}function no(e){let t=Za(e);if((0,Ze.existsSync)(t))try{return(0,Ze.unlinkSync)(t),!0}catch{return!1}return!0}function Hg(e,t,n){let r={pending:!0,completion_claim:t,verification_attempts:0,max_verification_attempts:WC,requested_at:new Date().toISOString(),original_task:n};return Gg(e,r),r}function qg(e,t,n){let r=ro(e);return r?(r.verification_attempts+=1,r.oracle_approved=t,r.oracle_feedback=n,t?(no(e),{...r,pending:!1}):r.verification_attempts>=r.max_verification_attempts?(no(e),{...r,pending:!1}):(Gg(e,r),r)):null}function ec(e){return`<ascent-verification>
|
|
1451
1451
|
|
|
1452
1452
|
[ORACLE VERIFICATION REQUIRED - Attempt ${e.verification_attempts+1}/${e.max_verification_attempts}]
|
|
1453
1453
|
|
|
@@ -1487,7 +1487,7 @@ DO NOT output the completion promise again until Oracle approves.
|
|
|
1487
1487
|
|
|
1488
1488
|
---
|
|
1489
1489
|
|
|
1490
|
-
`}function
|
|
1490
|
+
`}function Vg(e){return`<ascent-continuation-after-rejection>
|
|
1491
1491
|
|
|
1492
1492
|
[ORACLE REJECTED - Continue Working]
|
|
1493
1493
|
|
|
@@ -1512,7 +1512,7 @@ Continue working now.
|
|
|
1512
1512
|
|
|
1513
1513
|
---
|
|
1514
1514
|
|
|
1515
|
-
`}function
|
|
1515
|
+
`}function Yg(e){return/<oracle-approved>.*?VERIFIED_COMPLETE.*?<\/oracle-approved>/is.test(e)}function Kg(e){let t=[/oracle.*?(rejected|found issues|not complete|incomplete)/i,/issues? (found|identified|detected)/i,/not yet complete/i,/missing.*?(implementation|feature|test)/i,/bug.*?(found|detected|identified)/i,/error.*?(found|detected|identified)/i];for(let n of t)if(n.test(e)){let r=e.match(/(?:oracle|feedback|issue|problem|error|bug)[:\s]+([^.]+\.)/i);return{rejected:!0,feedback:r?r[1]:"Oracle found issues with the implementation."}}return{rejected:!1,feedback:""}}var de=require("fs"),dr=require("path"),tc=require("os");function nc(e){let t=e||process.cwd(),n=(0,dr.join)(t,".olympus");return(0,dr.join)(n,"olympus-state.json")}function rc(){return(0,dr.join)((0,tc.homedir)(),".claude","olympus-state.json")}function BC(e){let t=e||process.cwd(),n=(0,dr.join)(t,".olympus");(0,de.existsSync)(n)||(0,de.mkdirSync)(n,{recursive:!0})}function GC(){let e=(0,dr.join)((0,tc.homedir)(),".claude");(0,de.existsSync)(e)||(0,de.mkdirSync)(e,{recursive:!0})}function $n(e){let t=nc(e);if((0,de.existsSync)(t))try{let r=(0,de.readFileSync)(t,"utf-8");return JSON.parse(r)}catch{}let n=rc();if((0,de.existsSync)(n))try{let r=(0,de.readFileSync)(n,"utf-8");return JSON.parse(r)}catch{return null}return null}function Jg(e,t){try{BC(t);let n=nc(t);(0,de.writeFileSync)(n,JSON.stringify(e,null,2)),GC();let r=rc();return(0,de.writeFileSync)(r,JSON.stringify(e,null,2)),!0}catch{return!1}}function oc(e){let t=nc(e);if((0,de.existsSync)(t))try{(0,de.unlinkSync)(t)}catch{}let n=rc();if((0,de.existsSync)(n))try{return(0,de.unlinkSync)(n),!0}catch{return!1}return!0}function zg(e){let t=$n(e);return!t||!t.active?null:(t.reinforcement_count+=1,t.last_checked_at=new Date().toISOString(),Jg(t,e)?t:null)}function Qg(e){let t=$n(e);return!t||!t.active?!1:(t.oracle_approved=!0,t.last_checked_at=new Date().toISOString(),Jg(t,e))}function Xg(e){let t=e.requires_oracle_verification&&!e.oracle_approved?`
|
|
1516
1516
|
|
|
1517
1517
|
**ORACLE VERIFICATION REQUIRED**: Before declaring complete, you MUST get Oracle approval.`:"";return`<olympus-persistence>
|
|
1518
1518
|
|
|
@@ -1534,7 +1534,7 @@ Original task: ${e.original_prompt}
|
|
|
1534
1534
|
|
|
1535
1535
|
---
|
|
1536
1536
|
|
|
1537
|
-
`}ce();function
|
|
1537
|
+
`}ce();function Zg(e){let t=(0,Ht.join)((0,sc.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 r of n)if((0,pr.existsSync)(r))try{let o=(0,pr.readFileSync)(r,"utf-8");if(Yg(o))return!0}catch{continue}return!1}function HC(e){let t=(0,Ht.join)((0,sc.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 r of n)if((0,pr.existsSync)(r))try{let o=(0,pr.readFileSync)(r,"utf-8"),s=Kg(o);if(s.rejected)return s}catch{continue}return{rejected:!1,feedback:""}}async function qC(e,t){let n=t||process.cwd(),r=ur(n);if(!r||!r.active||r.session_id&&e&&r.session_id!==e)return null;let o=ro(n);if(o?.pending){if(e){if(Zg(e))return no(n),bs(n),{shouldBlock:!1,message:`[ASCENT LOOP VERIFIED COMPLETE] Oracle verified task completion after ${r.iteration} iteration(s). Excellent work!`,mode:"none"};let l=HC(e);if(l.rejected){qg(n,!1,l.feedback);let u=ro(n);if(u)return{shouldBlock:!0,message:Vg(u),mode:"ascent",metadata:{iteration:r.iteration,maxIterations:r.max_iterations}}}}return{shouldBlock:!0,message:ec(o),mode:"ascent",metadata:{iteration:r.iteration,maxIterations:r.max_iterations}}}if(Bg(e||"",r.completion_promise)){Hg(n,r.completion_promise,r.prompt);let c=ro(n);return c?{shouldBlock:!0,message:ec(c),mode:"ascent",metadata:{iteration:r.iteration,maxIterations:r.max_iterations}}:(bs(n),{shouldBlock:!1,message:`[ASCENT LOOP COMPLETE] Task completed after ${r.iteration} iteration(s). Great work!`,mode:"none"})}if(r.iteration>=r.max_iterations)return bs(n),no(n),{shouldBlock:!1,message:`[ASCENT LOOP STOPPED] Max iterations (${r.max_iterations}) reached without completion promise. Consider reviewing the task requirements.`,mode:"none"};let i=Wg(n);return i?{shouldBlock:!0,message:`<ascent-continuation>
|
|
1538
1538
|
|
|
1539
1539
|
[ASCENT LOOP - ITERATION ${i.iteration}/${i.max_iterations}]
|
|
1540
1540
|
|
|
@@ -1553,7 +1553,7 @@ ${i.prompt?`Original task: ${i.prompt}`:""}
|
|
|
1553
1553
|
|
|
1554
1554
|
---
|
|
1555
1555
|
|
|
1556
|
-
`,mode:"ascent",metadata:{iteration:i.iteration,maxIterations:i.max_iterations}}:null}async function
|
|
1556
|
+
`,mode:"ascent",metadata:{iteration:i.iteration,maxIterations:i.max_iterations}}:null}async function VC(e,t,n){let r=Jt(t);if(!r||!r.active||r.session_id&&e&&r.session_id!==e)return null;if(!n)return Vl(t),{shouldBlock:!1,message:"[ULTRAWORK COMPLETE] All tasks finished. Ultrawork mode deactivated. Well done!",mode:"none"};let o=Yl(t);return o?{shouldBlock:!0,message:Kl(o),mode:"ultrawork",metadata:{reinforcementCount:o.reinforcement_count}}:null}async function YC(e,t,n){let r=$n(t);if(!r||!r.active||r.session_id&&e&&r.session_id!==e)return null;if(!n&&r.oracle_approved)return oc(t),{shouldBlock:!1,message:"[OLYMPUS COMPLETE] All tasks finished and Oracle verified. Orchestration mode deactivated. Excellent work!",mode:"none"};if(!n&&!r.oracle_approved&&r.requires_oracle_verification)return e&&Zg(e)?(Qg(t),oc(t),{shouldBlock:!1,message:"[OLYMPUS VERIFIED COMPLETE] Oracle approved. Orchestration mode deactivated. Excellent work!",mode:"none"}):{shouldBlock:!0,message:`<olympus-verification-required>
|
|
1557
1557
|
|
|
1558
1558
|
[OLYMPUS MODE - ORACLE VERIFICATION REQUIRED]
|
|
1559
1559
|
|
|
@@ -1576,11 +1576,11 @@ DO NOT stop until Oracle has approved.
|
|
|
1576
1576
|
|
|
1577
1577
|
---
|
|
1578
1578
|
|
|
1579
|
-
`,mode:"olympus",metadata:{reinforcementCount:r.reinforcement_count}};let o=
|
|
1579
|
+
`,mode:"olympus",metadata:{reinforcementCount:r.reinforcement_count}};let o=zg(t);return o?{shouldBlock:!0,message:Xg(o),mode:"olympus",metadata:{reinforcementCount:o.reinforcement_count}}:null}async function KC(e,t){let n=await Zr(e,t);if(n.count===0)return null;let r=Ag(n),o=r?`
|
|
1580
1580
|
|
|
1581
1581
|
Next task: "${r.content}" (${r.status})`:"";return{shouldBlock:!0,message:`<todo-continuation>
|
|
1582
1582
|
|
|
1583
|
-
${
|
|
1583
|
+
${eu}
|
|
1584
1584
|
|
|
1585
1585
|
[Status: ${n.count} of ${n.total} tasks remaining]${o}
|
|
1586
1586
|
|
|
@@ -1588,11 +1588,11 @@ ${tu}
|
|
|
1588
1588
|
|
|
1589
1589
|
---
|
|
1590
1590
|
|
|
1591
|
-
`,mode:"todo-continuation",metadata:{todoCount:n.count}}}async function
|
|
1591
|
+
`,mode:"todo-continuation",metadata:{todoCount:n.count}}}async function JC(e,t,n){let r=t||process.cwd();try{let o=await vs(r);if(!o)return null;let s=to(o.manifest),i=o.pendingBolts.length>0,a=`
|
|
1592
1592
|
Workflow '${o.featureName}': ${s.completed}/${s.total} BOLTs complete (${s.percentage}%)`;if(o.pendingBolts.length>0){let l=o.pendingBolts[0];a+=`
|
|
1593
|
-
Next: ${l}`}try{await P(r,o.checkpoint)}catch{}return{progressMessage:a,shouldBlock:i&&(n==="ascent"||n==="ultrawork"||n==="olympus")}}catch{return null}}async function
|
|
1594
|
-
${l.progressMessage}`),u;let d=await
|
|
1595
|
-
${l.progressMessage}`),d;let p=await
|
|
1593
|
+
Next: ${l}`}try{await P(r,o.checkpoint)}catch{}return{progressMessage:a,shouldBlock:i&&(n==="ascent"||n==="ultrawork"||n==="olympus")}}catch{return null}}async function eh(e,t){let n=t||process.cwd(),o=(await Zr(e,n)).count>0,s=ur(n),i=Jt(n),a=$n(n),c=null;s?.active?c="ascent":i?.active?c="ultrawork":a?.active&&(c="olympus");let l=await JC(e,n,c),u=await qC(e,n);if(u?.shouldBlock)return l&&(u.message=u.message+`
|
|
1594
|
+
${l.progressMessage}`),u;let d=await VC(e,n,o);if(d?.shouldBlock)return l&&(d.message=d.message+`
|
|
1595
|
+
${l.progressMessage}`),d;let p=await YC(e,n,o);if(p?.shouldBlock)return l&&(p.message=p.message+`
|
|
1596
1596
|
${l.progressMessage}`),p;if(l?.shouldBlock)return{shouldBlock:!0,message:`<workflow-continuation>
|
|
1597
1597
|
|
|
1598
1598
|
[WORKFLOW IN PROGRESS - DO NOT STOP]
|
|
@@ -1605,21 +1605,21 @@ You are in ${c} mode with pending BOLTs. Continue executing the remaining BOLTs.
|
|
|
1605
1605
|
|
|
1606
1606
|
---
|
|
1607
1607
|
|
|
1608
|
-
`,mode:c||"none",metadata:{}};if(o){let f=await
|
|
1609
|
-
${l.progressMessage}`),f}return l?{shouldBlock:!1,message:l.progressMessage,mode:"none"}:{shouldBlock:!1,message:"",mode:"none"}}function
|
|
1610
|
-
`),n={},r=0;for(;r<t.length;){let o=t[r],s=o.indexOf(":");if(s===-1){r++;continue}let i=o.slice(0,s).trim(),a=o.slice(s+1).trim();if(i==="description")n.description=
|
|
1608
|
+
`,mode:c||"none",metadata:{}};if(o){let f=await KC(e,n);if(f?.shouldBlock)return l&&(f.message=f.message+`
|
|
1609
|
+
${l.progressMessage}`),f}return l?{shouldBlock:!1,message:l.progressMessage,mode:"none"}:{shouldBlock:!1,message:"",mode:"none"}}function th(e){return e.shouldBlock?{continue:!1,stopReason:e.message}:{continue:!0,message:e.message||void 0}}var fr=require("fs"),ic=require("path"),nh=require("os");Ue();ye();var rh=require("crypto");function zC(){let e=(0,ic.join)((0,nh.homedir)(),".claude","todos");if(!(0,fr.existsSync)(e))return 0;let t=0;try{let n=(0,fr.readdirSync)(e).filter(r=>r.endsWith(".json"));for(let r of n)try{let o=(0,fr.readFileSync)((0,ic.join)(e,r),"utf-8"),s=JSON.parse(o);Array.isArray(s)&&(t+=s.filter(i=>i.status!=="completed"&&i.status!=="cancelled").length)}catch{}}catch{}return t}async function oh(e){let{directory:t,sessionId:n}=e;if(!t)return;let r=Q(t,n),o=zC();if(o>0&&r.pending_completion){let s={id:(0,rh.randomUUID)(),timestamp:new Date().toISOString(),session_id:r.session_id,project_path:t,event_type:"cancellation",original_task:r.pending_completion.task_description,agent_used:r.pending_completion.agent_used,user_message:`[Stopped with ${o} incomplete todos]`,feedback_category:"rejection",confidence:.7};zt(s)}r.pending_completion=null,r.todo_snapshot={total:0,completed:0,pending:o},ee(t,r)}function sh(){I({name:"persistentMode",event:"Stop",priority:10,handler:async e=>{let t=e.sessionId,n=e.directory||process.cwd(),r=await eh(t,n),o=th(r);return{continue:o.continue,message:o.message,stopReason:o.stopReason}}}),I({name:"learningCancellationCapture",event:"Stop",priority:100,handler:async e=>e.directory?(Promise.resolve().then(async()=>{try{await oh({directory:e.directory,sessionId:e.sessionId})}catch(t){console.error("[Olympus Learning]",t)}}),{continue:!0}):{continue:!0}})}var hc=require("fs"),yc=require("os"),so=require("path");var dt=require("fs"),qe=require("path");var ac=require("path"),ih=require("os"),QC=(0,ac.join)((0,ih.homedir)(),".olympus"),Es=(0,ac.join)(QC,"rules-injector"),ah=[".git","pyproject.toml","package.json","Cargo.toml","go.mod",".venv"],ch=[[".github","instructions"],[".cursor","rules"],[".claude","rules"]],lh=[".github/copilot-instructions.md"],uh=/\.instructions\.md$/,dh=".claude/rules",ph=[".md",".mdc"],cc=["read","write","edit","multiedit"];function XC(e){return e.includes(".github/instructions")||e.endsWith(".github/instructions")}function ZC(e,t){return XC(t)?uh.test(e):ph.some(n=>e.endsWith(n))}function dc(e){let t;try{t=(0,dt.statSync)(e).isDirectory()?e:(0,qe.dirname)(e)}catch{t=(0,qe.dirname)(e)}for(;;){for(let r of ah){let o=(0,qe.join)(t,r);if((0,dt.existsSync)(o))return t}let n=(0,qe.dirname)(t);if(n===t)return null;t=n}}function uc(e,t){if((0,dt.existsSync)(e))try{let n=(0,dt.readdirSync)(e,{withFileTypes:!0});for(let r of n){let o=(0,qe.join)(e,r.name);r.isDirectory()?uc(o,t):r.isFile()&&ZC(r.name,e)&&t.push(o)}}catch{}}function lc(e){try{return(0,dt.realpathSync)(e)}catch{return e}}function pc(e,t,n){let r=[],o=new Set,s=(0,qe.dirname)(n),i=0;for(;;){for(let[u,d]of ch){let p=(0,qe.join)(s,u,d),f=[];uc(p,f);for(let m of f){let g=lc(m);o.has(g)||(o.add(g),r.push({path:m,realPath:g,isGlobal:!1,distance:i}))}}if(e&&s===e)break;let l=(0,qe.dirname)(s);if(l===s)break;s=l,i++}if(e)for(let l of lh){let u=(0,qe.join)(e,l);if((0,dt.existsSync)(u))try{if((0,dt.statSync)(u).isFile()){let p=lc(u);o.has(p)||(o.add(p),r.push({path:u,realPath:p,isGlobal:!1,distance:0,isSingleFile:!0}))}}catch{}}let a=(0,qe.join)(t,dh),c=[];uc(a,c);for(let l of c){let u=lc(l);o.has(u)||(o.add(u),r.push({path:l,realPath:u,isGlobal:!0,distance:9999}))}return r.sort((l,u)=>l.isGlobal!==u.isGlobal?l.isGlobal?1:-1:l.distance-u.distance),r}var fh=require("crypto"),mh=require("path");function eR(e,t){let n=e.replace(/\./g,"\\.").replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/<<<GLOBSTAR>>>/g,".*").replace(/\?/g,".");return new RegExp(`^${n}$`).test(t)}function fc(e,t,n){if(e.alwaysApply===!0)return{applies:!0,reason:"alwaysApply"};let r=e.globs;if(!r)return{applies:!1};let o=Array.isArray(r)?r:[r];if(o.length===0)return{applies:!1};let i=(n?(0,mh.relative)(n,t):t).replace(/\\/g,"/");for(let a of o)if(eR(a,i))return{applies:!0,reason:`glob: ${a}`};return{applies:!1}}function gh(e,t){return t.has(e)}function hh(e){return(0,fh.createHash)("sha256").update(e).digest("hex").slice(0,16)}function yh(e,t){return t.has(e)}function mc(e){let t=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,n=e.match(t);if(!n)return{metadata:{},body:e};let r=n[1],o=n[2];try{return{metadata:tR(r),body:o}}catch{return{metadata:{},body:e}}}function tR(e){let t=e.split(`
|
|
1610
|
+
`),n={},r=0;for(;r<t.length;){let o=t[r],s=o.indexOf(":");if(s===-1){r++;continue}let i=o.slice(0,s).trim(),a=o.slice(s+1).trim();if(i==="description")n.description=oo(a);else if(i==="alwaysApply")n.alwaysApply=a==="true";else if(i==="globs"||i==="paths"||i==="applyTo"){let{value:c,consumed:l}=nR(a,t,r);n.globs=oR(n.globs,c),r+=l;continue}r++}return n}function oo(e){return e?e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e:""}function nR(e,t,n){if(e.startsWith("["))return{value:rR(e),consumed:1};if(!e||e===""){let o=[],s=1;for(let i=n+1;i<t.length;i++){let a=t[i],c=a.match(/^\s+-\s*(.*)$/);if(c){let l=oo(c[1].trim());l&&o.push(l),s++}else if(a.trim()==="")s++;else break}if(o.length>0)return{value:o,consumed:s}}let r=oo(e);return r.includes(",")?{value:r.split(",").map(s=>s.trim()).filter(s=>s.length>0),consumed:1}:{value:r,consumed:1}}function rR(e){let t=e.slice(1,e.lastIndexOf("]")).trim();if(!t)return[];let n=[],r="",o=!1,s="";for(let a=0;a<t.length;a++){let c=t[a];if(!o&&(c==='"'||c==="'"))o=!0,s=c;else if(o&&c===s)o=!1,s="";else if(!o&&c===","){let l=r.trim();l&&n.push(oo(l)),r=""}else r+=c}let i=r.trim();return i&&n.push(oo(i)),n}function oR(e,t){if(!e)return t;let n=Array.isArray(e)?e:[e],r=Array.isArray(t)?t:[t];return[...n,...r]}var et=require("fs"),wh=require("path");function gc(e){return(0,wh.join)(Es,`${e}.json`)}function _h(e){let t=gc(e);if(!(0,et.existsSync)(t))return{contentHashes:new Set,realPaths:new Set};try{let n=(0,et.readFileSync)(t,"utf-8"),r=JSON.parse(n);return{contentHashes:new Set(r.injectedHashes),realPaths:new Set(r.injectedRealPaths??[])}}catch{return{contentHashes:new Set,realPaths:new Set}}}function kh(e,t){(0,et.existsSync)(Es)||(0,et.mkdirSync)(Es,{recursive:!0});let n={sessionId:e,injectedHashes:[...t.contentHashes],injectedRealPaths:[...t.realPaths],updatedAt:Date.now()};(0,et.writeFileSync)(gc(e),JSON.stringify(n,null,2))}function Sh(e){let t=gc(e);(0,et.existsSync)(t)&&(0,et.unlinkSync)(t)}function vh(e){let t=new Map;function n(i){return t.has(i)||t.set(i,_h(i)),t.get(i)}function r(i){return i?i.startsWith("/")?i:(0,so.resolve)(e,i):null}function o(i,a){let c=r(i);if(!c)return[];let l=dc(c),u=n(a),d=(0,yc.homedir)(),p=pc(l,d,c),f=[];for(let m of p)if(!gh(m.realPath,u.realPaths))try{let g=(0,hc.readFileSync)(m.path,"utf-8"),{metadata:y,body:w}=mc(g),_;if(m.isSingleFile)_="copilot-instructions (always apply)";else{let S=fc(y,c,l);if(!S.applies)continue;_=S.reason??"matched"}let h=hh(w);if(yh(h,u.contentHashes))continue;let b=l?(0,so.relative)(l,m.path):m.path;f.push({relativePath:b,matchReason:_,content:w,distance:m.distance}),u.realPaths.add(m.realPath),u.contentHashes.add(h)}catch{}return f.length>0&&(f.sort((m,g)=>m.distance-g.distance),kh(a,u)),f}function s(i){if(i.length===0)return"";let a="";for(let c of i)a+=`
|
|
1611
1611
|
|
|
1612
1612
|
[Rule: ${c.relativePath}]
|
|
1613
1613
|
[Match: ${c.matchReason}]
|
|
1614
|
-
${c.content}`;return a}return{processToolExecution:(i,a,c)=>{if(!
|
|
1614
|
+
${c.content}`;return a}return{processToolExecution:(i,a,c)=>{if(!cc.includes(i.toLowerCase()))return"";let l=o(a,c);return s(l)},getRulesForFile:i=>{let a=r(i);if(!a)return[];let c=dc(a),l=(0,yc.homedir)(),u=pc(c,l,a),d=[];for(let p of u)try{let f=(0,hc.readFileSync)(p.path,"utf-8"),{metadata:m,body:g}=mc(f),y;if(p.isSingleFile)y="copilot-instructions (always apply)";else{let _=fc(m,a,c);if(!_.applies)continue;y=_.reason??"matched"}let w=c?(0,so.relative)(c,p.path):p.path;d.push({relativePath:w,matchReason:y,content:g,distance:p.distance})}catch{}return d.sort((p,f)=>p.distance-f.distance)},clearSession:i=>{t.delete(i),Sh(i)},isTrackedTool:i=>cc.includes(i.toLowerCase())}}var Cs=require("node:fs"),qt=require("node:path");var tt=require("node:fs"),Th=require("node:path");var wc=require("node:path"),bh=require("node:os"),sR=(0,wc.join)((0,bh.homedir)(),".olympus"),Ts=(0,wc.join)(sR,"directory-readme"),Eh="README.md",_c=["read","write","edit","multiedit"];function kc(e){return(0,Th.join)(Ts,`${e}.json`)}function Ch(e){let t=kc(e);if(!(0,tt.existsSync)(t))return new Set;try{let n=(0,tt.readFileSync)(t,"utf-8"),r=JSON.parse(n);return new Set(r.injectedPaths)}catch{return new Set}}function Rh(e,t){(0,tt.existsSync)(Ts)||(0,tt.mkdirSync)(Ts,{recursive:!0});let n={sessionID:e,injectedPaths:Array.from(t),updatedAt:Date.now()};(0,tt.writeFileSync)(kc(e),JSON.stringify(n,null,2))}function xh(e){let t=kc(e);(0,tt.existsSync)(t)&&(0,tt.unlinkSync)(t)}var Ph=4,iR=5e3;function aR(e,t=iR){if(Math.ceil(e.length/Ph)<=t)return{result:e,truncated:!1};let r=t*Ph;return{result:e.slice(0,r),truncated:!0}}function Ah(e){let t=new Map;function n(i){return t.has(i)||t.set(i,Ch(i)),t.get(i)}function r(i){return i?i.startsWith("/")?i:(0,qt.resolve)(e,i):null}function o(i){let a=[],c=i;for(;;){let l=(0,qt.join)(c,Eh);if((0,Cs.existsSync)(l)&&a.push(l),c===e)break;let u=(0,qt.dirname)(c);if(u===c||!u.startsWith(e))break;c=u}return a.reverse()}function s(i,a){let c=r(i);if(!c)return"";let l=(0,qt.dirname)(c),u=n(a),d=o(l),p="";for(let f of d){let m=(0,qt.dirname)(f);if(!u.has(m))try{let g=(0,Cs.readFileSync)(f,"utf-8"),{result:y,truncated:w}=aR(g),_=w?`
|
|
1615
1615
|
|
|
1616
1616
|
[Note: Content was truncated to save context window space. For full context, please read the file directly: ${f}]`:"";p+=`
|
|
1617
1617
|
|
|
1618
1618
|
[Project README: ${f}]
|
|
1619
|
-
${y}${_}`,u.add(m)}catch{}}return p&&
|
|
1619
|
+
${y}${_}`,u.add(m)}catch{}}return p&&Rh(a,u),p}return{processToolExecution:(i,a,c)=>_c.includes(i.toLowerCase())?s(a,c):"",getReadmesForFile:i=>{let a=r(i);if(!a)return[];let c=(0,qt.dirname)(a);return o(c)},clearSession:i=>{t.delete(i),xh(i)},isTrackedTool:i=>_c.includes(i.toLowerCase())}}var Ih="non-interactive-env",Oh={CI:"true",DEBIAN_FRONTEND:"noninteractive",GIT_TERMINAL_PROMPT:"0",GCM_INTERACTIVE:"never",HOMEBREW_NO_AUTO_UPDATE:"1",GIT_EDITOR:":",EDITOR:":",VISUAL:"",GIT_SEQUENCE_EDITOR:":",GIT_MERGE_AUTOEDIT:"no",GIT_PAGER:"cat",PAGER:"cat",npm_config_yes:"true",PIP_NO_INPUT:"1",YARN_ENABLE_IMMUTABLE_INSTALLS:"false"},Sc={npm:{bad:["npm init","npm install (prompts)"],good:["npm init -y","npm install --yes"]},apt:{bad:["apt-get install pkg"],good:["apt-get install -y pkg","DEBIAN_FRONTEND=noninteractive apt-get install pkg"]},pip:{bad:["pip install pkg (with prompts)"],good:["pip install --no-input pkg","PIP_NO_INPUT=1 pip install pkg"]},git:{bad:["git commit","git merge branch","git add -p","git rebase -i"],good:["git commit -m 'msg'","git merge --no-edit branch","git add .","git rebase --no-edit"]},system:{bad:["rm file (prompts)","cp a b (prompts)","ssh host"],good:["rm -f file","cp -f a b","ssh -o BatchMode=yes host","unzip -o file.zip"]},banned:["vim","nano","vi","emacs","less","more","man","python (REPL)","node (REPL)","git add -p","git rebase -i"],workarounds:{yesPipe:"yes | ./script.sh",heredoc:`./script.sh <<EOF
|
|
1620
1620
|
option1
|
|
1621
1621
|
option2
|
|
1622
|
-
EOF`,expectAlternative:"Use environment variables or config files instead of expect"}};var
|
|
1622
|
+
EOF`,expectAlternative:"Use environment variables or config files instead of expect"}};var $h=Sc.banned.filter(e=>!e.includes("(")).map(e=>new RegExp(`\\b${e}\\b`));function cR(e){for(let t=0;t<$h.length;t++)if($h[t].test(e))return Sc.banned[t]}function lR(e){return e===""?"''":/[^a-zA-Z0-9_\-.:\/]/.test(e)?`'${e.replace(/'/g,"'\\''")}'`:e}function uR(e){return`export ${Object.entries(e).map(([n,r])=>`${n}=${lR(r)}`).join(" ")};`}var vc={name:Ih,async beforeCommand(e){let t=cR(e),n=t?`Warning: '${t}' is an interactive command that may hang in non-interactive environments.`:void 0;return/\bgit\b/.test(e)?{command:`${uR(Oh)} ${e}`,warning:n}:{command:e,warning:n}}};var Ec=require("child_process");var Dh="olympus-orchestrator",Nh=".olympus/",jh=["Write","Edit","write","edit"],Fh=`
|
|
1623
1623
|
|
|
1624
1624
|
---
|
|
1625
1625
|
|
|
@@ -1645,7 +1645,7 @@ You should NOT:
|
|
|
1645
1645
|
3. Verify the subagent's work after completion
|
|
1646
1646
|
|
|
1647
1647
|
---
|
|
1648
|
-
`;var
|
|
1648
|
+
`;var Mh=`[SYSTEM REMINDER - QUEST CONTINUATION]
|
|
1649
1649
|
|
|
1650
1650
|
You have an active work plan with incomplete tasks. Continue working.
|
|
1651
1651
|
|
|
@@ -1654,7 +1654,7 @@ RULES:
|
|
|
1654
1654
|
- Mark each checkbox [x] in the plan file when done
|
|
1655
1655
|
- Learnings are automatically captured in .olympus/learning/discoveries.jsonl
|
|
1656
1656
|
- Do not stop until all tasks are complete
|
|
1657
|
-
- If blocked, document the blocker and move to the next task`,
|
|
1657
|
+
- If blocked, document the blocker and move to the next task`,Lh=`**MANDATORY VERIFICATION - SUBAGENTS LIE**
|
|
1658
1658
|
|
|
1659
1659
|
Subagents FREQUENTLY claim completion when:
|
|
1660
1660
|
- Tests are actually FAILING
|
|
@@ -1669,7 +1669,7 @@ Subagents FREQUENTLY claim completion when:
|
|
|
1669
1669
|
3. Check build/typecheck - Must succeed
|
|
1670
1670
|
|
|
1671
1671
|
DO NOT TRUST THE AGENT'S SELF-REPORT.
|
|
1672
|
-
VERIFY EACH CLAIM WITH YOUR OWN TOOL CALLS.`,
|
|
1672
|
+
VERIFY EACH CLAIM WITH YOUR OWN TOOL CALLS.`,Uh=`
|
|
1673
1673
|
|
|
1674
1674
|
[SYSTEM DIRECTIVE - SINGLE TASK ONLY]
|
|
1675
1675
|
|
|
@@ -1692,7 +1692,7 @@ If you were NOT given **exactly ONE atomic task**, you MUST:
|
|
|
1692
1692
|
- Batch delegation = sloppy work = rework = wasted tokens
|
|
1693
1693
|
|
|
1694
1694
|
**REFUSE multi-task requests. DEMAND single-task clarity.**
|
|
1695
|
-
`,
|
|
1695
|
+
`,Wh=`
|
|
1696
1696
|
|
|
1697
1697
|
================================================================================
|
|
1698
1698
|
HARD BLOCK: DELEGATION REQUIRED
|
|
@@ -1731,41 +1731,41 @@ This is a HARD BLOCK. The operation will NOT be executed.
|
|
|
1731
1731
|
Delegate to a subagent to proceed.
|
|
1732
1732
|
|
|
1733
1733
|
================================================================================
|
|
1734
|
-
`;var
|
|
1735
|
-
`;(0,
|
|
1734
|
+
`;var io=".olympus",Rs="quest.json",dR=`${io}/${Rs}`,Bh="notepads",pR=`${io}/${Bh}`;var pt=require("fs"),xs=require("path");function Gh(e){return(0,xs.join)(e,io,Rs)}function Ps(e){let t=Gh(e);if(!(0,pt.existsSync)(t))return null;try{let n=(0,pt.readFileSync)(t,"utf-8");return JSON.parse(n)}catch{return null}}function As(e){if(!(0,pt.existsSync)(e))return{total:0,completed:0,isComplete:!0};try{let t=(0,pt.readFileSync)(e,"utf-8"),n=t.match(/^[-*]\s*\[\s*\]/gm)||[],r=t.match(/^[-*]\s*\[[xX]\]/gm)||[],o=n.length+r.length,s=r.length;return{total:o,completed:s,isComplete:o===0||s===o}}catch{return{total:0,completed:0,isComplete:!0}}}var ao=class{recentTasks=[];maxTracked=3;recordTaskCompletion(t){this.recentTasks.unshift(t),this.recentTasks.length>this.maxTracked&&this.recentTasks.pop()}isVerificationEdit(t,n){return this.recentTasks.some(o=>o.filesModified.includes(t))&&n<10}getRecentTaskFiles(){let t=this.recentTasks.flatMap(n=>n.filesModified);return Array.from(new Set(t))}getRecentTasks(){return[...this.recentTasks]}clear(){this.recentTasks=[]}get trackedCount(){return this.recentTasks.length}},PN=new ao;var Dn=require("fs"),bc=require("path");function co(e,t){let n=t||process.cwd(),r=(0,bc.join)(n,".olympus","logs"),o=(0,bc.join)(r,"hook-violations.jsonl");try{(0,Dn.existsSync)(r)||(0,Dn.mkdirSync)(r,{recursive:!0});let s=JSON.stringify(e)+`
|
|
1735
|
+
`;(0,Dn.appendFileSync)(o,s,"utf-8")}catch(s){console.error("[Hook Logging] Failed to log violation:",s)}}var Hh=new ao;function qh(e){return e?e.replace(/\\/g,"/").includes(Nh):!0}function gR(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 hR(e,t){if(!t)return 0;if(e==="Edit"||e==="edit"){let n=t.old_string??"",r=t.new_string??"";if(!n&&!r)return 0;let o=n.split(`
|
|
1736
1736
|
`).length,s=r.split(`
|
|
1737
1737
|
`).length;return Math.abs(s-o)}if(e==="Write"||e==="write"){let n=t.content??"";return n?n.split(`
|
|
1738
|
-
`).length:0}return 0}function
|
|
1738
|
+
`).length:0}return 0}function Vh(e){return jh.includes(e)}function yR(e){try{let t=(0,Ec.execSync)("git diff --numstat HEAD",{cwd:e,encoding:"utf-8",timeout:5e3}).trim();if(!t)return[];let n=(0,Ec.execSync)("git status --porcelain",{cwd:e,encoding:"utf-8",timeout:5e3}).trim(),r=new Map;for(let s of n.split(`
|
|
1739
1739
|
`)){if(!s)continue;let i=s.substring(0,2).trim(),a=s.substring(3);i==="A"||i==="??"?r.set(a,"added"):i==="D"?r.set(a,"deleted"):r.set(a,"modified")}let o=[];for(let s of t.split(`
|
|
1740
|
-
`)){let i=s.split(" ");if(i.length<3)continue;let[a,c,l]=i,u=a==="-"?0:parseInt(a,10),d=c==="-"?0:parseInt(c,10);o.push({path:l,added:u,removed:d,status:r.get(l)??"modified"})}return o}catch{return[]}}function
|
|
1740
|
+
`)){let i=s.split(" ");if(i.length<3)continue;let[a,c,l]=i,u=a==="-"?0:parseInt(a,10),d=c==="-"?0:parseInt(c,10);o.push({path:l,added:u,removed:d,status:r.get(l)??"modified"})}return o}catch{return[]}}function wR(e){if(e.length===0)return`[FILE CHANGES SUMMARY]
|
|
1741
1741
|
No file changes detected.
|
|
1742
1742
|
`;let t=e.filter(s=>s.status==="modified"),n=e.filter(s=>s.status==="added"),r=e.filter(s=>s.status==="deleted"),o=["[FILE CHANGES SUMMARY]"];if(t.length>0){o.push("Modified files:");for(let s of t)o.push(` ${s.path} (+${s.added}, -${s.removed})`);o.push("")}if(n.length>0){o.push("Created files:");for(let s of n)o.push(` ${s.path} (+${s.added})`);o.push("")}if(r.length>0){o.push("Deleted files:");for(let s of r)o.push(` ${s.path} (-${s.removed})`);o.push("")}return o.join(`
|
|
1743
|
-
`)}function
|
|
1743
|
+
`)}function Yh(e){let t=Lh;return e&&(t+=`
|
|
1744
1744
|
|
|
1745
1745
|
---
|
|
1746
1746
|
|
|
1747
1747
|
**If ANY verification fails, resume the subagent with the fix:**
|
|
1748
|
-
Task tool with resume="${e}", prompt="fix: [describe the specific failure]"`),t}function
|
|
1748
|
+
Task tool with resume="${e}", prompt="fix: [describe the specific failure]"`),t}function _R(e,t,n){let r=t.total-t.completed;return`
|
|
1749
1749
|
---
|
|
1750
1750
|
|
|
1751
1751
|
**State:** Plan: ${e} | ${t.completed}/${t.total} done, ${r} left
|
|
1752
1752
|
|
|
1753
1753
|
---
|
|
1754
1754
|
|
|
1755
|
-
${
|
|
1755
|
+
${Yh(n)}
|
|
1756
1756
|
|
|
1757
|
-
ALL pass? \u2192 commit atomic unit, mark \`[x]\`, next task.`}function
|
|
1757
|
+
ALL pass? \u2192 commit atomic unit, mark \`[x]\`, next task.`}function kR(e,t,n){return Mh.replace(/{PLAN_NAME}/g,e)+`
|
|
1758
1758
|
|
|
1759
|
-
[Status: ${n-t}/${n} completed, ${t} remaining]`}function
|
|
1759
|
+
[Status: ${n-t}/${n} completed, ${t} remaining]`}function SR(e){let{toolName:t,toolInput:n,directory:r}=e,o=r||process.cwd();if(!Vh(t))return{continue:!0};let s=n?.filePath??n?.path??n?.file;if(!s)return{continue:!0};let i=s.replace(/\\/g,"/");if(qh(i))return co({timestamp:new Date().toISOString(),filePath:i,toolName:t,wasBlocked:!1,reason:"Allowed: .olympus/ path"},o),{continue:!0};if(gR(i))return co({timestamp:new Date().toISOString(),filePath:i,toolName:t,wasBlocked:!1,reason:"Allowed: Test file"},o),{continue:!0};let a=hR(t,n);return Hh.isVerificationEdit(i,a)?(co({timestamp:new Date().toISOString(),filePath:i,toolName:t,linesChanged:a,wasBlocked:!1,reason:`Allowed: Verification edit (${a} lines on recent task file)`},o),{continue:!0}):(co({timestamp:new Date().toISOString(),filePath:i,toolName:t,linesChanged:a,wasBlocked:!0,reason:"Blocked: Direct source file modification (delegation required)"},o),{continue:!1,message:Wh})}function vR(e,t){let{toolName:n,toolInput:r,directory:o,sessionId:s}=e,i=o||process.cwd();if(Vh(n)){let a=r?.filePath??r?.path??r?.file;if(a&&!qh(a))return{continue:!0,modifiedOutput:t+Fh}}if(n==="Task"||n==="task"){if(t.includes("Background task launched")||t.includes("Background task resumed"))return{continue:!0};let c=yR(i),l=c.map(p=>p.path);Hh.recordTaskCompletion({timestamp:Date.now(),filesModified:l,taskId:s||`task-${Date.now()}`});let u=wR(c),d=Ps(i);if(d){let p=As(d.active_plan);return{continue:!0,modifiedOutput:`
|
|
1760
1760
|
## SUBAGENT WORK COMPLETED
|
|
1761
1761
|
|
|
1762
1762
|
${u}
|
|
1763
1763
|
<system-reminder>
|
|
1764
|
-
${
|
|
1764
|
+
${_R(d.plan_name,p,s)}
|
|
1765
1765
|
</system-reminder>`}}return{continue:!0,modifiedOutput:t+`
|
|
1766
1766
|
<system-reminder>
|
|
1767
|
-
${
|
|
1768
|
-
</system-reminder>`}}return{continue:!0}}function
|
|
1767
|
+
${Yh(s)}
|
|
1768
|
+
</system-reminder>`}}return{continue:!0}}function bR(e){let t=Ps(e);if(!t)return{shouldContinue:!1};let n=As(t.active_plan);if(n.isComplete)return{shouldContinue:!1};let r=n.total-n.completed;return{shouldContinue:!0,message:kR(t.plan_name,r,n.total)}}function Is(e){return{name:Dh,preTool:(t,n)=>SR({toolName:t,toolInput:n,directory:e}),postTool:(t,n,r)=>vR({toolName:t,toolInput:n,directory:e},r),checkContinuation:()=>bR(e),getSingleTaskDirective:()=>Uh}}function Kh(e){if(!e||typeof e!="object")return null;let t=e;return t.file_path||t.filePath||t.path||t.file}function Jh(){I({name:"rulesInjector",event:"PreToolUse",priority:10,matcher:/^(read|edit|write|glob|grep)$/i,handler:e=>{let t=vh(e.directory||process.cwd()),n=Kh(e.toolInput);if(!n)return{continue:!0};let r=t.processToolExecution(e.toolName,n,e.sessionId||"default");return{continue:!0,hookSpecificOutput:r?{hookEventName:"PreToolUse",additionalContext:r}:void 0}}}),I({name:"directoryReadmeInjector",event:"PreToolUse",priority:20,matcher:/^(read|edit|write|glob|grep|bash)$/i,handler:e=>{let t=Ah(e.directory||process.cwd()),n=Kh(e.toolInput);if(!n)return{continue:!0};let r=t.processToolExecution(e.toolName,n,e.sessionId||"default");return{continue:!0,hookSpecificOutput:r?{hookEventName:"PreToolUse",additionalContext:r}:void 0}}}),I({name:"nonInteractiveEnv",event:"PreToolUse",priority:30,matcher:/^bash$/i,handler:async e=>{let t=e.toolInput;if(!t?.command)return{continue:!0};try{if(!vc.beforeCommand)return{continue:!0};let n=await vc.beforeCommand(t.command);return{continue:!0,hookSpecificOutput:n.warning?{hookEventName:"PreToolUse",additionalContext:n.warning}:void 0,modifiedInput:n.command!==t.command?{...t,command:n.command}:void 0}}catch(n){return console.error("[nonInteractiveEnv] Error:",n),{continue:!0}}}}),I({name:"olympusOrchestratorPre",event:"PreToolUse",priority:40,matcher:/^(write|edit|bash|task)$/i,handler:e=>Is(e.directory||process.cwd()).preTool(e.toolName,e.toolInput)})}var ER=["oldString and newString must be different","oldString not found","oldString found multiple times","old_string not found","old_string and new_string must be different"],TR=`
|
|
1769
1769
|
[EDIT ERROR - IMMEDIATE ACTION REQUIRED]
|
|
1770
1770
|
|
|
1771
1771
|
You made an Edit mistake. STOP and do this NOW:
|
|
@@ -1776,7 +1776,7 @@ You made an Edit mistake. STOP and do this NOW:
|
|
|
1776
1776
|
4. CONTINUE with corrected action based on the real file content
|
|
1777
1777
|
|
|
1778
1778
|
DO NOT attempt another edit until you've read and verified the file state.
|
|
1779
|
-
`;function
|
|
1779
|
+
`;function CR(e){let t=e.toLowerCase();return ER.some(n=>t.includes(n.toLowerCase()))}function zh(){return{afterToolExecute:(e,t)=>e.tool.toLowerCase()!=="edit"?t:CR(t.output)?{...t,output:t.output+TR}:t}}var Zh=v(require("fs"),1),$s=v(require("path"),1),ey=require("os");var Os=new Set(["given","when","then","arrange","act","assert","when & then","when&then"]),Tc=["type:","noqa","pyright:","ruff:","mypy:","pylint:","flake8:","pyre:","pytype:","eslint-disable","eslint-enable","eslint-ignore","prettier-ignore","ts-ignore","ts-expect-error","ts-nocheck","@ts-ignore","@ts-expect-error","@ts-nocheck","clippy::","allow(","deny(","warn(","forbid(","nolint","go:generate","go:build","go:embed","coverage:","c8 ignore","istanbul ignore","biome-ignore","region","endregion","#region","#endregion"],Cc=`COMMENT/DOCSTRING DETECTED - IMMEDIATE ACTION REQUIRED
|
|
1780
1780
|
|
|
1781
1781
|
Your recent changes contain comments or docstrings, which triggered this hook.
|
|
1782
1782
|
You need to take immediate action. You must follow the conditions below.
|
|
@@ -1814,13 +1814,13 @@ MANDATORY REQUIREMENT: You must acknowledge this hook message and take one of th
|
|
|
1814
1814
|
Review in the above priority order and take the corresponding action EVERY TIME this appears.
|
|
1815
1815
|
|
|
1816
1816
|
Detected comments/docstrings:
|
|
1817
|
-
`,
|
|
1818
|
-
`;
|
|
1817
|
+
`,Rc={js:/\/\/.*$|\/\*[\s\S]*?\*\//gm,ts:/\/\/.*$|\/\*[\s\S]*?\*\//gm,jsx:/\/\/.*$|\/\*[\s\S]*?\*\//gm,tsx:/\/\/.*$|\/\*[\s\S]*?\*\//gm,java:/\/\/.*$|\/\*[\s\S]*?\*\//gm,c:/\/\/.*$|\/\*[\s\S]*?\*\//gm,cpp:/\/\/.*$|\/\*[\s\S]*?\*\//gm,cs:/\/\/.*$|\/\*[\s\S]*?\*\//gm,go:/\/\/.*$/gm,rust:/\/\/.*$|\/\*[\s\S]*?\*\//gm,swift:/\/\/.*$|\/\*[\s\S]*?\*\//gm,kotlin:/\/\/.*$|\/\*[\s\S]*?\*\//gm,py:/#.*$|'''[\s\S]*?'''|"""[\s\S]*?"""/gm,rb:/#.*$|=begin[\s\S]*?=end/gm,sh:/#.*$/gm,bash:/#.*$/gm,zsh:/#.*$/gm,yaml:/#.*$/gm,yml:/#.*$/gm,toml:/#.*$/gm,html:/<!--[\s\S]*?-->/gm,xml:/<!--[\s\S]*?-->/gm,vue:/<!--[\s\S]*?-->|\/\/.*$|\/\*[\s\S]*?\*\//gm,svelte:/<!--[\s\S]*?-->|\/\/.*$|\/\*[\s\S]*?\*\//gm,sql:/--.*$/gm,lua:/--.*$|--\[\[[\s\S]*?\]\]/gm},xc={".js":"js",".mjs":"js",".cjs":"js",".ts":"ts",".mts":"ts",".cts":"ts",".jsx":"jsx",".tsx":"tsx",".java":"java",".c":"c",".h":"c",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".hpp":"cpp",".cs":"cs",".go":"go",".rs":"rust",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".py":"py",".pyi":"py",".rb":"rb",".sh":"sh",".bash":"bash",".zsh":"zsh",".yaml":"yaml",".yml":"yml",".toml":"toml",".html":"html",".htm":"html",".xml":"xml",".vue":"vue",".svelte":"svelte",".sql":"sql",".lua":"lua"};function RR(e){return e.text.trim().startsWith("#!")&&e.lineNumber===1?{shouldSkip:!0,reason:"shebang"}:{shouldSkip:!1}}function xR(e){if(e.isDocstring)return{shouldSkip:!1};let t=e.text.toLowerCase().trim();for(let n of Os){if(t.startsWith(`#${n}`)||t.startsWith(`// ${n}`))return{shouldSkip:!0,reason:`BDD keyword: ${n}`};if(t.includes(n)&&t.split(/\s+/).some(o=>Os.has(o.replace(/[^a-z&]/g,""))))return{shouldSkip:!0,reason:"BDD keyword detected"}}return{shouldSkip:!1}}function PR(e){let t=e.text.toLowerCase().trim();for(let n of Tc)if(t.includes(n.toLowerCase()))return{shouldSkip:!0,reason:`directive: ${n}`};return{shouldSkip:!1}}function AR(e){return{shouldSkip:!1}}function IR(e){let t=e.text.toLowerCase(),n=["copyright","license","licensed under","spdx-license-identifier","all rights reserved","mit license","apache license","gnu general public","bsd license"];for(let r of n)if(t.includes(r))return{shouldSkip:!0,reason:"copyright/license"};return{shouldSkip:!1}}function OR(e){let t=e.text.toUpperCase(),n=["TODO","FIXME","HACK","XXX","NOTE","REVIEW"];for(let r of n)if(t.includes(r))return{shouldSkip:!0,reason:`todo marker: ${r}`};return{shouldSkip:!1}}var $R=[RR,xR,PR,IR,OR,AR];function Pc(e){return e.filter(t=>{for(let n of $R)if(n(t).shouldSkip)return!1;return!0})}var DR=process.env.COMMENT_CHECKER_DEBUG==="1",NR=$s.join((0,ey.tmpdir)(),"comment-checker-debug.log");function Nn(...e){if(DR){let t=`[${new Date().toISOString()}] [comment-checker] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
|
|
1818
|
+
`;Zh.appendFileSync(NR,t)}}function jR(e){let t=$s.extname(e).toLowerCase();return xc[t]}function Ac(e,t){let n=jR(t);if(!n)return Nn("unsupported language for:",t),[];let r=Rc[n];if(!r)return Nn("no pattern for language:",n),[];let o=[],s=e.split(`
|
|
1819
1819
|
`);r.lastIndex=0;let i;for(;(i=r.exec(e))!==null;){let a=i.index,c=i[0],u=e.substring(0,a).split(`
|
|
1820
|
-
`).length,d="line",p=!1;c.startsWith("/*")||c.startsWith("<!--")?d="block":(c.startsWith("'''")||c.startsWith('"""')||c.startsWith("=begin"))&&(d="docstring",p=!0),o.push({text:c.trim(),lineNumber:u,filePath:t,commentType:d,isDocstring:p})}return o}function
|
|
1820
|
+
`).length,d="line",p=!1;c.startsWith("/*")||c.startsWith("<!--")?d="block":(c.startsWith("'''")||c.startsWith('"""')||c.startsWith("=begin"))&&(d="docstring",p=!0),o.push({text:c.trim(),lineNumber:u,filePath:t,commentType:d,isDocstring:p})}return o}function FR(e,t){return Ac(e,t)}function Qh(e,t,n){let r=Ac(e,t);if(n){let o=Ac(n,t),s=new Set(o.map(i=>i.text));return r.filter(i=>!s.has(i.text))}return r}function MR(e){if(e.length===0)return"";let t=new Map;for(let r of e){let o=t.get(r.filePath)||[];o.push(r),t.set(r.filePath,o)}let n=Cc;for(let[r,o]of t){n+=`
|
|
1821
1821
|
File: ${r}
|
|
1822
1822
|
`;for(let s of o){let i=s.isDocstring?"docstring":s.commentType;n+=` Line ${s.lineNumber} (${i}): ${s.text.substring(0,100)}${s.text.length>100?"...":""}
|
|
1823
|
-
`}}return n}function
|
|
1823
|
+
`}}return n}function LR(e,t,n,r,o){let s=[];if(t)s=FR(t,e);else if(r)s=Qh(r,e,n);else if(o&&o.length>0)for(let a of o){let c=Qh(a.new_string,e,a.old_string);s.push(...c)}let i=Pc(s);return Nn(`found ${s.length} comments, ${i.length} flagged after filtering`),i.length===0?{hasComments:!1,count:0,comments:[]}:{hasComments:!0,count:i.length,message:MR(i),comments:i}}var lo=new Map,UR=6e4;function WR(){let e=Date.now();for(let[t,n]of lo)e-n.timestamp>UR&&lo.delete(t)}var Xh=!1;function ty(e){return Nn("createCommentCheckerHook called",{config:e}),Xh||(Xh=!0,setInterval(WR,1e4)),{preToolUse:t=>{let n=t.tool_name.toLowerCase();if(n!=="write"&&n!=="edit"&&n!=="multiedit")return null;let r=t.tool_input.file_path??t.tool_input.filePath??t.tool_input.path,o=t.tool_input.content,s=t.tool_input.old_string??t.tool_input.oldString,i=t.tool_input.new_string??t.tool_input.newString,a=t.tool_input.edits;if(!r)return null;let c=`${t.session_id}-${Date.now()}-${Math.random().toString(36).slice(2)}`;return Nn("registering pendingCall:",{callId:c,filePath:r,tool:n}),lo.set(c,{filePath:r,content:o,oldString:s,newString:i,edits:a,tool:n,sessionId:t.session_id,timestamp:Date.now()}),null},postToolUse:t=>{let n=t.tool_name.toLowerCase();if(n!=="write"&&n!=="edit"&&n!=="multiedit")return null;let r,o;for(let[i,a]of lo)if(a.sessionId===t.session_id&&a.tool===n){r=a,o=i;break}if(!r){let i=t.tool_input.file_path??t.tool_input.filePath??t.tool_input.path;if(!i)return null;r={filePath:i,content:t.tool_input.content,oldString:t.tool_input.old_string??t.tool_input.oldString,newString:t.tool_input.new_string??t.tool_input.newString,edits:t.tool_input.edits,tool:n,sessionId:t.session_id,timestamp:Date.now()}}if(o&&lo.delete(o),t.tool_response){let i=t.tool_response.toLowerCase();if(i.includes("error:")||i.includes("failed to")||i.includes("could not")||i.startsWith("error"))return Nn("skipping due to tool failure in response"),null}let s=LR(r.filePath,r.content,r.oldString,r.newString,r.edits);return s.hasComments&&s.message?(Nn("detected comments, returning message"),e?.customPrompt||s.message):null}}}var cy=v(require("fs"),1),ly=v(require("path"),1),uy=require("os");var ry=[/(\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],oy=["prompt is too long","is too long","context_length_exceeded","max_tokens","token limit","context length","too many tokens","non-empty content"],BR=[/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],GR=/messages\.(\d+)/;function HR(e){return BR.some(t=>t.test(e))}function Ic(e){for(let t of ry){let n=e.match(t);if(n){let r=parseInt(n[1],10),o=parseInt(n[2],10);return r>o?{current:r,max:o}:{current:o,max:r}}}return null}function ny(e){let t=e.match(GR);if(t)return parseInt(t[1],10)}function mr(e){if(HR(e))return!1;let t=e.toLowerCase();return oy.some(n=>t.includes(n.toLowerCase()))}function Ds(e){if(typeof e=="string"){if(e.toLowerCase().includes("non-empty content"))return{currentTokens:0,maxTokens:0,errorType:"non-empty content",messageIndex:ny(e)};if(mr(e)){let l=Ic(e);return{currentTokens:l?.current??0,maxTokens:l?.max??0,errorType:"token_limit_exceeded_string"}}return null}if(!e||typeof e!="object")return null;let t=e,n=[],r=t.data,o=r?.responseBody,s=t.message,i=t.error,a=i?.error;if(typeof o=="string"&&n.push(o),typeof s=="string"&&n.push(s),typeof i?.message=="string"&&n.push(i.message),typeof t.body=="string"&&n.push(t.body),typeof t.details=="string"&&n.push(t.details),typeof t.reason=="string"&&n.push(t.reason),typeof t.description=="string"&&n.push(t.description),typeof a?.message=="string"&&n.push(a.message),typeof r?.message=="string"&&n.push(r.message),typeof r?.error=="string"&&n.push(r.error),n.length===0)try{let l=JSON.stringify(t);mr(l)&&n.push(l)}catch{}let c=n.join(" ");if(!mr(c))return null;if(typeof o=="string")try{let l=[/data:\s*(\{[\s\S]*\})\s*$/m,/(\{"type"\s*:\s*"error"[\s\S]*\})/,/(\{[\s\S]*"error"[\s\S]*\})/];for(let d of l){let p=o.match(d);if(p)try{let f=JSON.parse(p[1]),m=f.error?.message||"",g=Ic(m);if(g)return{currentTokens:g.current,maxTokens:g.max,requestId:f.request_id,errorType:f.error?.type||"token_limit_exceeded"}}catch{}}let u=JSON.parse(o);if(typeof u.message=="string"&&mr(u.message))return{currentTokens:0,maxTokens:0,errorType:"bedrock_input_too_long"}}catch{}for(let l of n){let u=Ic(l);if(u)return{currentTokens:u.current,maxTokens:u.max,errorType:"token_limit_exceeded"}}return c.toLowerCase().includes("non-empty content")?{currentTokens:0,maxTokens:0,errorType:"non-empty content",messageIndex:ny(c)}:mr(c)?{currentTokens:0,maxTokens:0,errorType:"token_limit_exceeded_unknown"}:null}function Oc(e){return mr(e)}var $c=`CONTEXT WINDOW LIMIT REACHED - IMMEDIATE ACTION REQUIRED
|
|
1824
1824
|
|
|
1825
1825
|
The conversation has exceeded the model's context window limit. To continue working effectively, you must take one of these actions:
|
|
1826
1826
|
|
|
@@ -1845,7 +1845,7 @@ Current Status:
|
|
|
1845
1845
|
- Context limit exceeded
|
|
1846
1846
|
- Further API calls will fail until context is reduced
|
|
1847
1847
|
- Action required before continuing
|
|
1848
|
-
`,
|
|
1848
|
+
`,Dc="Context window limit reached. Please use /compact to summarize the conversation or start a new session.",Nc=`API ERROR: Non-empty content validation failed.
|
|
1849
1849
|
|
|
1850
1850
|
This error typically occurs when:
|
|
1851
1851
|
- A message has empty text content
|
|
@@ -1856,7 +1856,7 @@ Suggested actions:
|
|
|
1856
1856
|
2. If the error persists, start a new session
|
|
1857
1857
|
|
|
1858
1858
|
The system will attempt automatic recovery.
|
|
1859
|
-
`;var
|
|
1859
|
+
`;var jc=`CONTEXT RECOVERY FAILED
|
|
1860
1860
|
|
|
1861
1861
|
All automatic recovery attempts have been exhausted.
|
|
1862
1862
|
Please start a new session to continue.
|
|
@@ -1867,13 +1867,13 @@ Before starting a new session:
|
|
|
1867
1867
|
3. Document the current state of the task
|
|
1868
1868
|
|
|
1869
1869
|
You can copy this conversation summary to continue in a new session.
|
|
1870
|
-
`;var
|
|
1871
|
-
`;
|
|
1870
|
+
`;var Fc={maxAttempts:2,initialDelayMs:2e3,backoffFactor:2,maxDelayMs:3e4};var qR=process.env.CONTEXT_LIMIT_RECOVERY_DEBUG==="1",VR=ly.join((0,uy.tmpdir)(),"context-limit-recovery-debug.log");function Ns(...e){if(qR){let t=`[${new Date().toISOString()}] [context-limit-recovery] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
|
|
1871
|
+
`;cy.appendFileSync(VR,t)}}var js=new Map,dy=3e5;function sy(e){let t=js.get(e),n=Date.now();return t&&n-t.lastErrorTime>dy&&(t=void 0),t||(t={retryState:{attempt:0,lastAttemptTime:0},truncateState:{truncateAttempt:0},lastErrorTime:n,errorCount:0},js.set(e,t)),t}function YR(){let e=Date.now();for(let[t,n]of js)e-n.lastErrorTime>dy&&js.delete(t)}var iy=!1;function py(e){return Ns("createContextLimitRecoveryHook called",{config:e}),iy||(iy=!0,setInterval(YR,6e4)),{postToolUse:t=>{if(!t.tool_response)return null;let n=Ds(t.tool_response);if(!n&&!Oc(t.tool_response))return null;Ns("detected token limit error",{tool:t.tool_name,sessionId:t.session_id,parsed:n});let r=sy(t.session_id);r.lastErrorTime=Date.now(),r.errorCount++;let o=ay(n,r,e);return o.message?(Ns("injecting recovery message",{errorType:o.errorType,attempt:r.retryState.attempt}),o.message):null},onError:t=>{let n=Ds(t.error);if(!n)return{attempted:!1,success:!1};Ns("error notification contains token limit error",{sessionId:t.session_id,parsed:n});let r=sy(t.session_id);r.lastErrorTime=Date.now(),r.errorCount++;let o=ay(n,r,e);return{attempted:!0,success:!!o.message,message:o.message,errorType:o.errorType}}}}function ay(e,t,n){if(n?.customMessage)return{message:n.customMessage,errorType:e?.errorType};if(e?.errorType?.includes("non-empty content"))return{message:Nc,errorType:"non-empty content"};if(t.retryState.attempt++,t.retryState.lastAttemptTime=Date.now(),t.retryState.attempt>Fc.maxAttempts)return{message:jc,errorType:"recovery_exhausted"};if(n?.detailed!==!1){let r=$c;return e?.currentTokens&&e?.maxTokens&&(r+=`
|
|
1872
1872
|
Token Details:
|
|
1873
1873
|
- Current: ${e.currentTokens.toLocaleString()} tokens
|
|
1874
1874
|
- Maximum: ${e.maxTokens.toLocaleString()} tokens
|
|
1875
1875
|
- Over limit by: ${(e.currentTokens-e.maxTokens).toLocaleString()} tokens
|
|
1876
|
-
`),{message:r,errorType:e?.errorType||"token_limit_exceeded"}}return{message:
|
|
1876
|
+
`),{message:r,errorType:e?.errorType||"token_limit_exceeded"}}return{message:Dc,errorType:e?.errorType||"token_limit_exceeded"}}var fy=/File content \((\d+) tokens\) exceeds maximum allowed tokens \((\d+)\)/i,KR=/exceeds maximum allowed tokens/i;function JR(e){let t=e.match(fy);return t?{current:parseInt(t[1],10),max:parseInt(t[2],10)}:null}function zR(e,t){return e.toLowerCase()==="read"&&(fy.test(t)||KR.test(t))}function QR(e,t){return`[SYSTEM RECOVERY - READ TOOL FILE SIZE LIMIT]
|
|
1877
1877
|
|
|
1878
1878
|
${t?`The file contains ${t.current} tokens, exceeding the ${t.max} token limit.`:"The file is too large to read in one operation."}
|
|
1879
1879
|
|
|
@@ -1903,7 +1903,7 @@ ${t?`The file contains ${t.current} tokens, exceeding the ${t.max} token limit.`
|
|
|
1903
1903
|
- Need overview/summary? \u2192 Use multimodal-looker agent
|
|
1904
1904
|
- Need specific section? \u2192 Grep to find it, then Read that portion
|
|
1905
1905
|
|
|
1906
|
-
Proceed with one of these strategies.`.trim()}function
|
|
1906
|
+
Proceed with one of these strategies.`.trim()}function my(){return{postToolUse:e=>{if(!e.tool_response||!zR(e.tool_name,e.tool_response))return null;let t=e.tool_input?.file_path||"<unknown file>",n=JR(e.tool_response);return QR(t,n||void 0)}}}var ky=v(require("fs"),1),Sy=v(require("path"),1),vy=require("os");var Mc=process.env.ANTHROPIC_1M_CONTEXT==="true"||process.env.VERTEX_ANTHROPIC_1M_CONTEXT==="true"?1e6:2e5,Fs=4,Lc=`CONTEXT WINDOW WARNING - APPROACHING LIMIT
|
|
1907
1907
|
|
|
1908
1908
|
Your context usage is getting high. Consider these actions to prevent hitting the limit:
|
|
1909
1909
|
|
|
@@ -1923,7 +1923,7 @@ Your context usage is getting high. Consider these actions to prevent hitting th
|
|
|
1923
1923
|
|
|
1924
1924
|
Current Status: Context usage is high but recoverable.
|
|
1925
1925
|
Action recommended: Use /compact when convenient.
|
|
1926
|
-
`,
|
|
1926
|
+
`,Uc=`CRITICAL: CONTEXT WINDOW ALMOST FULL
|
|
1927
1927
|
|
|
1928
1928
|
Your context usage is critically high. Immediate action required:
|
|
1929
1929
|
|
|
@@ -1942,8 +1942,8 @@ Your context usage is critically high. Immediate action required:
|
|
|
1942
1942
|
|
|
1943
1943
|
WARNING: Further messages may fail if context is not reduced.
|
|
1944
1944
|
Action required: Run /compact now.
|
|
1945
|
-
`;var
|
|
1946
|
-
`;
|
|
1945
|
+
`;var XR=process.env.PREEMPTIVE_COMPACTION_DEBUG==="1",ZR=Sy.join((0,vy.tmpdir)(),"preemptive-compaction-debug.log");function gr(...e){if(XR){let t=`[${new Date().toISOString()}] [preemptive-compaction] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
|
|
1946
|
+
`;ky.appendFileSync(ZR,t)}}var Ms=new Map;function ex(){let e=Date.now(),t=1800*1e3;for(let[n,r]of Ms)e-r.lastWarningTime>t&&Ms.delete(n)}var gy=!1;function by(e){return Math.ceil(e.length/Fs)}function tx(e,t){let n=t?.warningThreshold??.85,r=t?.criticalThreshold??.95,o=Mc,s=by(e),i=s/o,a=i>=n,c=i>=r,l="none";return c?l="compact":a&&(l="warn"),{totalTokens:s,usageRatio:i,isWarning:a,isCritical:c,action:l}}function Ls(e){let t=Ms.get(e);return t||(t={lastWarningTime:0,warningCount:0,estimatedTokens:0},Ms.set(e,t)),t}function nx(e,t){let n=Ls(e),r=t?.cooldownMs??6e4,o=t?.maxWarnings??3,s=Date.now();return s-n.lastWarningTime<r?(gr("skipping warning - cooldown active",{sessionId:e,elapsed:s-n.lastWarningTime,cooldown:r}),!1):n.warningCount>=o?(gr("skipping warning - max reached",{sessionId:e,warningCount:n.warningCount,maxWarnings:o}),!1):!0}function rx(e){let t=Ls(e);t.lastWarningTime=Date.now(),t.warningCount++}function Ey(e){return gr("createPreemptiveCompactionHook called",{config:e}),e?.enabled===!1?{postToolUse:()=>null,stop:()=>null}:(gy||(gy=!0,setInterval(ex,300*1e3)),{postToolUse:t=>{if(!t.tool_response)return null;let n=t.tool_name.toLowerCase();if(!["read","grep","glob","bash","webfetch"].includes(n))return null;let o=by(t.tool_response),s=Ls(t.session_id);s.estimatedTokens+=o,gr("tracking tool output",{tool:n,responseTokens:o,cumulativeTokens:s.estimatedTokens});let i=tx("x".repeat(s.estimatedTokens*Fs),e);return!i.isWarning||!nx(t.session_id,e)?null:(rx(t.session_id),gr("injecting context warning",{sessionId:t.session_id,usageRatio:i.usageRatio,isCritical:i.isCritical}),e?.customMessage?e.customMessage:i.isCritical?Uc:Lc)},stop:t=>{let n=Ls(t.session_id);return n.warningCount>0&&(gr("resetting warning count on stop",{sessionId:t.session_id,previousCount:n.warningCount}),n.warningCount=0),null}})}var nt=require("fs"),Cy=require("path");var Wc=require("path"),Ty=require("os"),ox=(0,Wc.join)((0,Ty.homedir)(),".olympus"),Us=(0,Wc.join)(ox,"agent-usage-reminder"),Bc=new Set(["grep","safe_grep","glob","safe_glob","webfetch","context7_resolve-library-id","context7_query-docs","websearch_web_search_exa","context7_get-library-docs","grep_app_searchgithub"]),Gc=new Set(["task","call_omo_agent","olympus_task"]),Hc=`
|
|
1947
1947
|
[Agent Usage Reminder]
|
|
1948
1948
|
|
|
1949
1949
|
You called a search/fetch tool directly without leveraging specialized agents.
|
|
@@ -1967,7 +1967,7 @@ WHY:
|
|
|
1967
1967
|
- Reduces context window usage in main session
|
|
1968
1968
|
|
|
1969
1969
|
ALWAYS prefer: Multiple parallel Task calls > Direct tool calls
|
|
1970
|
-
`;function
|
|
1970
|
+
`;function qc(e){return(0,Cy.join)(Us,`${e}.json`)}function Vc(e){let t=qc(e);if(!(0,nt.existsSync)(t))return null;try{let n=(0,nt.readFileSync)(t,"utf-8");return JSON.parse(n)}catch{return null}}function Ws(e){(0,nt.existsSync)(Us)||(0,nt.mkdirSync)(Us,{recursive:!0});let t=qc(e.sessionID);(0,nt.writeFileSync)(t,JSON.stringify(e,null,2))}function Yc(e){let t=qc(e);(0,nt.existsSync)(t)&&(0,nt.unlinkSync)(t)}function sx(e){let t=e||process.cwd();return ur(t)?.active?{active:!0,mode:"ascent"}:$n(t)?.active?{active:!0,mode:"olympus"}:Jt(t)?.active?{active:!0,mode:"ultrawork"}:{active:!1,mode:"none"}}function ix(e){if(!e||typeof e!="object")return null;let t=e;return t.file_path||t.filePath||t.path}function ax(e,t){if(e<3)return null;let n=e>=5?"CRITICAL":"WARNING";return`<conductor-violation severity="${n}">
|
|
1971
1971
|
|
|
1972
1972
|
[${n}: CONDUCTOR MODE VIOLATION - ${t.toUpperCase()} ACTIVE]
|
|
1973
1973
|
|
|
@@ -1993,36 +1993,36 @@ ${e>=5?"**CRITICAL**: Too many direct operations. Your next action MUST be deleg
|
|
|
1993
1993
|
|
|
1994
1994
|
---
|
|
1995
1995
|
|
|
1996
|
-
`}function
|
|
1997
|
-
`;(0,Wy.appendFileSync)($y,t)}}function By(e){if(!e)return"";if(typeof e=="string")return e.toLowerCase();let t=e,n=[t.data,t.error,t,t.data?.error];for(let r of n)if(r&&typeof r=="object"){let o=r.message;if(typeof o=="string"&&o.length>0)return o.toLowerCase()}try{return JSON.stringify(e).toLowerCase()}catch{return""}}function Gy(e){let n=By(e).match(/messages\.(\d+)/);return n?parseInt(n[1],10):null}function Hy(e){let t=By(e);return t.includes("tool_use")&&t.includes("tool_result")?"tool_result_missing":t.includes("thinking")&&(t.includes("first block")||t.includes("must start with")||t.includes("preceeding")||t.includes("final block")||t.includes("cannot be thinking")||t.includes("expected")&&t.includes("found"))?"thinking_block_order":t.includes("thinking is disabled")&&t.includes("cannot contain")?"thinking_disabled_violation":t.includes("empty")&&(t.includes("content")||t.includes("message"))?"empty_content":null}function px(e){return Hy(e)!==null}function fx(e){return e.filter(t=>t.type==="tool_use"&&!!t.id).map(t=>t.id)}async function mx(e,t){Se("recoverToolResultMissing",{sessionID:e,msgId:t.info?.id});let n=t.parts||[];n.length===0&&t.info?.id&&(n=It(t.info.id).map(s=>({type:s.type==="tool"?"tool_use":s.type,id:"callID"in s?s.callID:s.id,name:"tool"in s?s.tool:void 0,input:"state"in s?s.state?.input:void 0})));let r=fx(n);return r.length===0?(Se("No tool_use IDs found"),!1):(Se("Found tool_use IDs to inject results for",r),!0)}async function gx(e,t,n){Se("recoverThinkingBlockOrder",{sessionID:e});let r=Gy(n);if(r!==null){let i=Uy(e,r);if(i)return Se("Found target message by index",{targetIndex:r,targetMessageID:i}),Xc(e,i)}let o=Qc(e);if(o.length===0)return Se("No orphan thinking messages found"),!1;Se("Found orphan thinking messages",o);let s=!1;for(let i of o)Xc(e,i)&&(s=!0);return s}async function hx(e,t){Se("recoverThinkingDisabledViolation",{sessionID:e});let n=zc(e);if(n.length===0)return Se("No messages with thinking blocks found"),!1;Se("Found messages with thinking blocks",n);let r=!1;for(let o of n)My(o)&&(r=!0);return r}async function yx(e,t,n){Se("recoverEmptyContentMessage",{sessionID:e});let r=Gy(n),o=t.info?.id,s=!1,i=Ly(e);for(let l of i)go(l,st)&&(s=!0);let a=Fy(e);for(let l of a)mo(e,l,st)&&(s=!0);if(r!==null){let l=jy(e,r);if(l&&(go(l,st)||mo(e,l,st)))return!0}if(o&&(go(o,st)||mo(e,o,st)))return!0;let c=Jc(e);for(let l of c)go(l,st)&&(s=!0),mo(e,l,st)&&(s=!0);return s}async function wx(e,t,n,r){Se("handleSessionRecovery",{sessionID:e,error:t});let o=Hy(t);if(!o)return Se("Not a recoverable error"),{attempted:!1,success:!1};Se("Detected recoverable error type",o);try{let s=!1,i=n||{info:{},parts:[]};switch(o){case"tool_result_missing":s=await mx(e,i);break;case"thinking_block_order":s=await gx(e,i,t);break;case"thinking_disabled_violation":s=await hx(e,i);break;case"empty_content":s=await yx(e,i,t);break}Se("Recovery result",{errorType:o,success:s});let a=r?.customMessages?.[o]||qs[o]?.message||`Session recovery attempted for ${o}`;return{attempted:!0,success:s,message:s?a:void 0,errorType:o}}catch(s){return Se("Recovery failed with error",s),{attempted:!0,success:!1,errorType:o}}}function qy(e){return Se("createSessionRecoveryHook",{config:e}),{onError:async t=>wx(t.session_id,t.error,t.message,e),isRecoverable:t=>px(t),getRecoveryMessage:t=>{if(t)return e?.customMessages?.[t]||qs[t]?.message}}}function Vy(){let e=qy();I({name:"sessionRecovery",event:"PostToolUseFailure",priority:10,handler:async t=>{let n=t.error||t.toolOutput;if(!n)return{continue:!0};if(!e.isRecoverable(n))return{continue:!0};let r=await e.onError({session_id:t.sessionId||"default",error:n,message:void 0});return r.attempted&&r.success?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:r.message||`[session-recovery] Recovered from ${r.errorType} error. Please retry.`}}:r.attempted&&!r.success?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:`[session-recovery] Attempted recovery for ${r.errorType} but could not fix automatically. You may need to restart the session.`}}:{continue:!0}}})}var it=require("fs"),Vs=require("path"),Yy=require("os");var ho=class{config;counts=new Map;queues=new Map;constructor(t){this.config=t}getConcurrencyLimit(t){let n=this.config?.modelConcurrency?.[t];if(n!==void 0)return n===0?1/0:n;let r=t.split("/")[0],o=this.config?.providerConcurrency?.[r];if(o!==void 0)return o===0?1/0:o;let s=this.config?.defaultConcurrency;return s!==void 0?s===0?1/0:s:5}async acquire(t){let n=this.getConcurrencyLimit(t);if(n===1/0)return;let r=this.counts.get(t)??0;if(r<n){this.counts.set(t,r+1);return}return new Promise(o=>{let s=this.queues.get(t)??[];s.push(o),this.queues.set(t,s)})}release(t){if(this.getConcurrencyLimit(t)===1/0)return;let r=this.queues.get(t);if(r&&r.length>0)r.shift()();else{let o=this.counts.get(t)??0;o>0&&this.counts.set(t,o-1)}}getCount(t){return this.counts.get(t)??0}getQueueLength(t){return this.queues.get(t)?.length??0}isAtCapacity(t){let n=this.getConcurrencyLimit(t);return n===1/0?!1:(this.counts.get(t)??0)>=n}getActiveCounts(){return new Map(this.counts)}clear(){this.counts.clear(),this.queues.clear()}};var _x=1800*1e3,kr=(0,Vs.join)((0,Yy.homedir)(),".claude",".olympus","background-tasks"),Ys=class{tasks=new Map;notifications=new Map;concurrencyManager;config;pruneInterval;constructor(t){this.config=t??{},this.concurrencyManager=new ho(t),this.ensureStorageDir(),this.loadPersistedTasks(),this.startPruning()}ensureStorageDir(){(0,it.existsSync)(kr)||(0,it.mkdirSync)(kr,{recursive:!0})}generateTaskId(){let t=Date.now().toString(36),n=Math.random().toString(36).substring(2,8);return`bg_${t}${n}`}getTaskPath(t){return(0,Vs.join)(kr,`${t}.json`)}persistTask(t){let n=this.getTaskPath(t.id);(0,it.writeFileSync)(n,JSON.stringify(t,null,2))}unpersistTask(t){let n=this.getTaskPath(t);(0,it.existsSync)(n)&&(0,it.unlinkSync)(n)}loadPersistedTasks(){if((0,it.existsSync)(kr))try{let{readdirSync:t}=require("fs"),n=t(kr);for(let r of n)if(r.endsWith(".json"))try{let o=(0,Vs.join)(kr,r),s=(0,it.readFileSync)(o,"utf-8"),i=JSON.parse(s);i.startedAt=new Date(i.startedAt),i.completedAt&&(i.completedAt=new Date(i.completedAt)),i.progress?.lastUpdate&&(i.progress.lastUpdate=new Date(i.progress.lastUpdate)),i.progress?.lastMessageAt&&(i.progress.lastMessageAt=new Date(i.progress.lastMessageAt)),this.tasks.set(i.id,i)}catch{}}catch{}}startPruning(){this.pruneInterval||(this.pruneInterval=setInterval(()=>{this.pruneStaleTasksAndNotifications()},6e4),this.pruneInterval.unref&&this.pruneInterval.unref())}stopPruning(){this.pruneInterval&&(clearInterval(this.pruneInterval),this.pruneInterval=void 0)}pruneStaleTasksAndNotifications(){let t=Date.now(),n=this.config.taskTimeoutMs??_x;for(let[r,o]of this.tasks.entries())t-o.startedAt.getTime()>n&&o.status==="running"&&(o.status="error",o.error=`Task timed out after ${Math.round(n/6e4)} minutes`,o.completedAt=new Date,o.concurrencyKey&&this.concurrencyManager.release(o.concurrencyKey),this.clearNotificationsForTask(r),this.unpersistTask(r),this.tasks.delete(r));for(let[r,o]of this.notifications.entries()){let s=o.filter(i=>t-i.startedAt.getTime()<=n);s.length===0?this.notifications.delete(r):s.length!==o.length&&this.notifications.set(r,s)}}async launch(t){let n=t.agent,r=this.config.maxTotalTasks??10;if(Array.from(this.tasks.values()).filter(c=>c.status==="running").length>=r)throw new Error(`Maximum concurrent background tasks (${r}) reached. Wait for some tasks to complete.`);await this.concurrencyManager.acquire(n);let s=this.generateTaskId(),i=`ses_${this.generateTaskId()}`,a={id:s,sessionId:i,parentSessionId:t.parentSessionId,description:t.description,prompt:t.prompt,agent:t.agent,status:"running",startedAt:new Date,progress:{toolCalls:0,lastUpdate:new Date},concurrencyKey:n};return this.tasks.set(s,a),this.persistTask(a),a}async resume(t){let n=this.findBySession(t.sessionId);if(!n)throw new Error(`Task not found for session: ${t.sessionId}`);return n.status="running",n.completedAt=void 0,n.error=void 0,n.parentSessionId=t.parentSessionId,n.progress||(n.progress={toolCalls:0,lastUpdate:new Date}),n.progress.lastUpdate=new Date,this.persistTask(n),n}getTask(t){return this.tasks.get(t)}findBySession(t){for(let n of this.tasks.values())if(n.sessionId===t)return n}getTasksByParentSession(t){let n=[];for(let r of this.tasks.values())r.parentSessionId===t&&n.push(r);return n}getAllTasks(){return Array.from(this.tasks.values())}getRunningTasks(){return Array.from(this.tasks.values()).filter(t=>t.status==="running")}updateTaskStatus(t,n,r,o){let s=this.tasks.get(t);s&&(s.status=n,r&&(s.result=r),o&&(s.error=o),(n==="completed"||n==="error"||n==="cancelled")&&(s.completedAt=new Date,s.concurrencyKey&&this.concurrencyManager.release(s.concurrencyKey),this.markForNotification(s)),this.persistTask(s))}updateTaskProgress(t,n){let r=this.tasks.get(t);r&&(r.progress||(r.progress={toolCalls:0,lastUpdate:new Date}),Object.assign(r.progress,n,{lastUpdate:new Date}),this.persistTask(r))}markForNotification(t){let n=this.notifications.get(t.parentSessionId)??[];n.push(t),this.notifications.set(t.parentSessionId,n)}getPendingNotifications(t){return this.notifications.get(t)??[]}clearNotifications(t){this.notifications.delete(t)}clearNotificationsForTask(t){for(let[n,r]of this.notifications.entries()){let o=r.filter(s=>s.id!==t);o.length===0?this.notifications.delete(n):this.notifications.set(n,o)}}removeTask(t){let n=this.tasks.get(t);n?.concurrencyKey&&this.concurrencyManager.release(n.concurrencyKey),this.clearNotificationsForTask(t),this.unpersistTask(t),this.tasks.delete(t)}formatDuration(t,n){let r=(n??new Date).getTime()-t.getTime(),o=Math.floor(r/1e3),s=Math.floor(o/60),i=Math.floor(s/60);return i>0?`${i}h ${s%60}m ${o%60}s`:s>0?`${s}m ${o%60}s`:`${o}s`}getStatusSummary(){let t=this.getRunningTasks(),n=this.getAllTasks();if(n.length===0)return"No background tasks.";let r=[`Background Tasks: ${t.length} running, ${n.length} total`,""];for(let o of n){let s=this.formatDuration(o.startedAt,o.completedAt),i=o.status.toUpperCase(),a=o.progress?` (${o.progress.toolCalls} tools)`:"";r.push(` [${i}] ${o.description} - ${s}${a}`),o.error&&r.push(` Error: ${o.error}`)}return r.join(`
|
|
1998
|
-
`)}cleanup(){this.stopPruning(),this.tasks.clear(),this.notifications.clear()}},
|
|
1999
|
-
`)}function
|
|
1996
|
+
`}function Ry(){let e=new Map,t=new Map;function n(c){if(!e.has(c)){let u=Vc(c)??{sessionID:c,agentUsed:!1,reminderCount:0,updatedAt:Date.now()};e.set(c,u)}return e.get(c)}function r(c){let l=n(c);l.agentUsed=!0,l.updatedAt=Date.now(),Ws(l)}function o(c){e.delete(c),Yc(c),t.delete(c)}function s(c,l,u){let d=t.get(c)||{consecutiveCount:0,lastToolName:"",lastFilePath:"",sessionId:c};return l.toLowerCase()==="task"?(d.consecutiveCount=0,t.set(c,d),0):(["edit","write","multiedit"].includes(l.toLowerCase())&&(d.consecutiveCount++,d.lastToolName=l,d.lastFilePath=u,t.set(c,d)),d.consecutiveCount)}return{"tool.execute.after":async(c,l)=>{let{tool:u,sessionID:d}=c,p=u.toLowerCase();if(Gc.has(p)){r(d),s(d,p,"");return}let f=c.properties||{},m=ix(f),g=s(d,p,m||""),y=sx();if(y.active){let _=ax(g,y.mode);if(_){l.output=_+l.output;return}}if(!Bc.has(p))return;let w=n(d);w.agentUsed||(l.output+=Hc,w.reminderCount++,w.updatedAt=Date.now(),Ws(w))},event:async({event:c})=>{let l=c.properties;if(c.type==="session.deleted"){let u=l?.info;u?.id&&o(u.id)}if(c.type==="session.compacted"){let u=l?.sessionID??l?.info?.id;u&&o(u)}}}}function xy(){let e=process.cwd(),t=zh();I({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=ty();I({name:"commentChecker",event:"PostToolUse",matcher:/^(write|edit|multiedit)$/i,priority:20,handler:async c=>{if(!c.toolName)return{continue:!0};let l=n.postToolUse({tool_name:c.toolName,session_id:c.sessionId||"",tool_input:c.toolInput||{},tool_response:c.toolOutput?String(c.toolOutput):void 0});return l?{continue:!0,message:l}:{continue:!0}}});let r=py();I({name:"contextWindowLimitRecovery",event:"PostToolUse",priority:30,handler:async c=>{if(!c.toolName)return{continue:!0};let l=r.postToolUse({tool_name:c.toolName,session_id:c.sessionId||"",tool_input:c.toolInput||{},tool_response:c.toolOutput?String(c.toolOutput):void 0});return l?{continue:!0,message:l}:{continue:!0}}});let o=my();I({name:"readToolLimitRecovery",event:"PostToolUse",matcher:/^read$/i,priority:35,handler:async c=>{if(!c.toolName||c.toolName.toLowerCase()!=="read")return{continue:!0};let l=o.postToolUse({tool_name:c.toolName,session_id:c.sessionId||"",tool_input:c.toolInput||{},tool_response:c.toolOutput?String(c.toolOutput):void 0});return l?{continue:!0,message:l}:{continue:!0}}});let s=Ey();I({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=Ry();I({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=Is(e);I({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 Uy=require("node:fs");var J=require("node:fs"),Le=require("node:path");var hr=require("node:path"),Bs=require("node:os");function cx(){return process.env.XDG_DATA_HOME??(0,hr.join)((0,Bs.homedir)(),".local","share")}function lx(){return(0,hr.join)(cx(),"claude-code","storage")}var Py=lx(),uo=(0,hr.join)(Py,"message"),yr=(0,hr.join)(Py,"part"),un=new Set(["thinking","redacted_thinking","reasoning"]),Ay=new Set(["step-start","step-finish"]);var rt="[user interrupted]",Gs={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 Iy=process.env.SESSION_RECOVERY_DEBUG==="1",Oy=(0,hr.join)((0,Bs.tmpdir)(),"session-recovery-debug.log");function ux(){let e=Date.now().toString(16),t=Math.random().toString(36).substring(2,10);return`prt_${e}${t}`}function dx(e){if(!(0,J.existsSync)(uo))return"";let t=(0,Le.join)(uo,e);if((0,J.existsSync)(t))return t;for(let n of(0,J.readdirSync)(uo)){let r=(0,Le.join)(uo,n,e);if((0,J.existsSync)(r))return r}return""}function Vt(e){let t=dx(e);if(!t||!(0,J.existsSync)(t))return[];let n=[];for(let r of(0,J.readdirSync)(t))if(r.endsWith(".json"))try{let o=(0,J.readFileSync)((0,Le.join)(t,r),"utf-8");n.push(JSON.parse(o))}catch{continue}return n.sort((r,o)=>{let s=r.time?.created??0,i=o.time?.created??0;return s!==i?s-i:r.id.localeCompare(o.id)})}function Pt(e){let t=(0,Le.join)(yr,e);if(!(0,J.existsSync)(t))return[];let n=[];for(let r of(0,J.readdirSync)(t))if(r.endsWith(".json"))try{let o=(0,J.readFileSync)((0,Le.join)(t,r),"utf-8");n.push(JSON.parse(o))}catch{continue}return n}function $y(e){return un.has(e.type)||Ay.has(e.type)?!1:e.type==="text"?!!e.text?.trim():e.type==="tool"||e.type==="tool_use"||e.type==="tool_result"}function Dy(e){return Pt(e).some($y)}function po(e,t,n){let r=(0,Le.join)(yr,t);(0,J.existsSync)(r)||(0,J.mkdirSync)(r,{recursive:!0});let o=ux(),s={id:o,sessionID:e,messageID:t,type:"text",text:n,synthetic:!0};try{return(0,J.writeFileSync)((0,Le.join)(r,`${o}.json`),JSON.stringify(s,null,2)),!0}catch{return!1}}function Kc(e){let t=Vt(e),n=[];for(let r of t)Dy(r.id)||n.push(r.id);return n}function Ny(e,t){let n=Vt(e),r=[t,t-1,t+1,t-2,t+2,t-3,t-4,t-5];for(let o of r){if(o<0||o>=n.length)continue;let s=n[o];if(!Dy(s.id))return s.id}return null}function Jc(e){let t=Vt(e),n=[];for(let r of t){if(r.role!=="assistant")continue;Pt(r.id).some(i=>un.has(i.type))&&n.push(r.id)}return n}function jy(e){let t=Vt(e),n=[];for(let r of t){if(r.role!=="assistant")continue;let o=Pt(r.id);if(o.length===0)continue;let s=o.some(a=>un.has(a.type)),i=o.some($y);s&&!i&&n.push(r.id)}return n}function zc(e){let t=Vt(e),n=[];for(let r of t){if(r.role!=="assistant")continue;let o=Pt(r.id);if(o.length===0)continue;let i=[...o].sort((c,l)=>c.id.localeCompare(l.id))[0];un.has(i.type)||n.push(r.id)}return n}function px(e,t){let n=Vt(e),r=n.findIndex(o=>o.id===t);if(r===-1)return"";for(let o=r-1;o>=0;o--){let s=n[o];if(s.role!=="assistant")continue;let i=Pt(s.id);for(let a of i)if(un.has(a.type)){let c=a.thinking,l=a.text,u=c||l;if(u&&u.trim().length>0)return u}}return""}function Qc(e,t){let n=(0,Le.join)(yr,t);(0,J.existsSync)(n)||(0,J.mkdirSync)(n,{recursive:!0});let r=px(e,t),o="prt_0000000000_thinking",s={id:o,sessionID:e,messageID:t,type:"thinking",thinking:r||"[Continuing from previous reasoning]",synthetic:!0};try{return(0,J.writeFileSync)((0,Le.join)(n,`${o}.json`),JSON.stringify(s,null,2)),!0}catch{return!1}}function Fy(e){let t=(0,Le.join)(yr,e);if(!(0,J.existsSync)(t))return!1;let n=!1;for(let r of(0,J.readdirSync)(t))if(r.endsWith(".json"))try{let o=(0,Le.join)(t,r),s=(0,J.readFileSync)(o,"utf-8"),i=JSON.parse(s);un.has(i.type)&&((0,J.unlinkSync)(o),n=!0)}catch{continue}return n}function fo(e,t=rt){let n=(0,Le.join)(yr,e);if(!(0,J.existsSync)(n))return!1;let r=!1;for(let o of(0,J.readdirSync)(n))if(o.endsWith(".json"))try{let s=(0,Le.join)(n,o),i=(0,J.readFileSync)(s,"utf-8"),a=JSON.parse(i);if(a.type==="text"){let c=a;c.text?.trim()||(c.text=t,c.synthetic=!0,(0,J.writeFileSync)(s,JSON.stringify(c,null,2)),r=!0)}}catch{continue}return r}function My(e){let t=Vt(e),n=[];for(let r of t)Pt(r.id).some(i=>i.type!=="text"?!1:!i.text?.trim())&&n.push(r.id);return n}function Ly(e,t){let n=Vt(e);if(t<0||t>=n.length)return null;let r=n[t];if(r.role!=="assistant")return null;let o=Pt(r.id);if(o.length===0)return null;let i=[...o].sort((c,l)=>c.id.localeCompare(l.id))[0];return un.has(i.type)?null:r.id}function ke(...e){if(Iy){let t=`[${new Date().toISOString()}] [session-recovery] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
|
|
1997
|
+
`;(0,Uy.appendFileSync)(Oy,t)}}function Wy(e){if(!e)return"";if(typeof e=="string")return e.toLowerCase();let t=e,n=[t.data,t.error,t,t.data?.error];for(let r of n)if(r&&typeof r=="object"){let o=r.message;if(typeof o=="string"&&o.length>0)return o.toLowerCase()}try{return JSON.stringify(e).toLowerCase()}catch{return""}}function By(e){let n=Wy(e).match(/messages\.(\d+)/);return n?parseInt(n[1],10):null}function Gy(e){let t=Wy(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 fx(e){return Gy(e)!==null}function mx(e){return e.filter(t=>t.type==="tool_use"&&!!t.id).map(t=>t.id)}async function gx(e,t){ke("recoverToolResultMissing",{sessionID:e,msgId:t.info?.id});let n=t.parts||[];n.length===0&&t.info?.id&&(n=Pt(t.info.id).map(s=>({type:s.type==="tool"?"tool_use":s.type,id:"callID"in s?s.callID:s.id,name:"tool"in s?s.tool:void 0,input:"state"in s?s.state?.input:void 0})));let r=mx(n);return r.length===0?(ke("No tool_use IDs found"),!1):(ke("Found tool_use IDs to inject results for",r),!0)}async function hx(e,t,n){ke("recoverThinkingBlockOrder",{sessionID:e});let r=By(n);if(r!==null){let i=Ly(e,r);if(i)return ke("Found target message by index",{targetIndex:r,targetMessageID:i}),Qc(e,i)}let o=zc(e);if(o.length===0)return ke("No orphan thinking messages found"),!1;ke("Found orphan thinking messages",o);let s=!1;for(let i of o)Qc(e,i)&&(s=!0);return s}async function yx(e,t){ke("recoverThinkingDisabledViolation",{sessionID:e});let n=Jc(e);if(n.length===0)return ke("No messages with thinking blocks found"),!1;ke("Found messages with thinking blocks",n);let r=!1;for(let o of n)Fy(o)&&(r=!0);return r}async function wx(e,t,n){ke("recoverEmptyContentMessage",{sessionID:e});let r=By(n),o=t.info?.id,s=!1,i=My(e);for(let l of i)fo(l,rt)&&(s=!0);let a=jy(e);for(let l of a)po(e,l,rt)&&(s=!0);if(r!==null){let l=Ny(e,r);if(l&&(fo(l,rt)||po(e,l,rt)))return!0}if(o&&(fo(o,rt)||po(e,o,rt)))return!0;let c=Kc(e);for(let l of c)fo(l,rt)&&(s=!0),po(e,l,rt)&&(s=!0);return s}async function _x(e,t,n,r){ke("handleSessionRecovery",{sessionID:e,error:t});let o=Gy(t);if(!o)return ke("Not a recoverable error"),{attempted:!1,success:!1};ke("Detected recoverable error type",o);try{let s=!1,i=n||{info:{},parts:[]};switch(o){case"tool_result_missing":s=await gx(e,i);break;case"thinking_block_order":s=await hx(e,i,t);break;case"thinking_disabled_violation":s=await yx(e,i);break;case"empty_content":s=await wx(e,i,t);break}ke("Recovery result",{errorType:o,success:s});let a=r?.customMessages?.[o]||Gs[o]?.message||`Session recovery attempted for ${o}`;return{attempted:!0,success:s,message:s?a:void 0,errorType:o}}catch(s){return ke("Recovery failed with error",s),{attempted:!0,success:!1,errorType:o}}}function Hy(e){return ke("createSessionRecoveryHook",{config:e}),{onError:async t=>_x(t.session_id,t.error,t.message,e),isRecoverable:t=>fx(t),getRecoveryMessage:t=>{if(t)return e?.customMessages?.[t]||Gs[t]?.message}}}function qy(){let e=Hy();I({name:"sessionRecovery",event:"PostToolUseFailure",priority:10,handler:async t=>{let n=t.error||t.toolOutput;if(!n)return{continue:!0};if(!e.isRecoverable(n))return{continue:!0};let r=await e.onError({session_id:t.sessionId||"default",error:n,message:void 0});return r.attempted&&r.success?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:r.message||`[session-recovery] Recovered from ${r.errorType} error. Please retry.`}}:r.attempted&&!r.success?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:`[session-recovery] Attempted recovery for ${r.errorType} but could not fix automatically. You may need to restart the session.`}}:{continue:!0}}})}var ot=require("fs"),Hs=require("path"),Vy=require("os");var mo=class{config;counts=new Map;queues=new Map;constructor(t){this.config=t}getConcurrencyLimit(t){let n=this.config?.modelConcurrency?.[t];if(n!==void 0)return n===0?1/0:n;let r=t.split("/")[0],o=this.config?.providerConcurrency?.[r];if(o!==void 0)return o===0?1/0:o;let s=this.config?.defaultConcurrency;return s!==void 0?s===0?1/0:s:5}async acquire(t){let n=this.getConcurrencyLimit(t);if(n===1/0)return;let r=this.counts.get(t)??0;if(r<n){this.counts.set(t,r+1);return}return new Promise(o=>{let s=this.queues.get(t)??[];s.push(o),this.queues.set(t,s)})}release(t){if(this.getConcurrencyLimit(t)===1/0)return;let r=this.queues.get(t);if(r&&r.length>0)r.shift()();else{let o=this.counts.get(t)??0;o>0&&this.counts.set(t,o-1)}}getCount(t){return this.counts.get(t)??0}getQueueLength(t){return this.queues.get(t)?.length??0}isAtCapacity(t){let n=this.getConcurrencyLimit(t);return n===1/0?!1:(this.counts.get(t)??0)>=n}getActiveCounts(){return new Map(this.counts)}clear(){this.counts.clear(),this.queues.clear()}};var kx=1800*1e3,wr=(0,Hs.join)((0,Vy.homedir)(),".claude",".olympus","background-tasks"),qs=class{tasks=new Map;notifications=new Map;concurrencyManager;config;pruneInterval;constructor(t){this.config=t??{},this.concurrencyManager=new mo(t),this.ensureStorageDir(),this.loadPersistedTasks(),this.startPruning()}ensureStorageDir(){(0,ot.existsSync)(wr)||(0,ot.mkdirSync)(wr,{recursive:!0})}generateTaskId(){let t=Date.now().toString(36),n=Math.random().toString(36).substring(2,8);return`bg_${t}${n}`}getTaskPath(t){return(0,Hs.join)(wr,`${t}.json`)}persistTask(t){let n=this.getTaskPath(t.id);(0,ot.writeFileSync)(n,JSON.stringify(t,null,2))}unpersistTask(t){let n=this.getTaskPath(t);(0,ot.existsSync)(n)&&(0,ot.unlinkSync)(n)}loadPersistedTasks(){if((0,ot.existsSync)(wr))try{let{readdirSync:t}=require("fs"),n=t(wr);for(let r of n)if(r.endsWith(".json"))try{let o=(0,Hs.join)(wr,r),s=(0,ot.readFileSync)(o,"utf-8"),i=JSON.parse(s);i.startedAt=new Date(i.startedAt),i.completedAt&&(i.completedAt=new Date(i.completedAt)),i.progress?.lastUpdate&&(i.progress.lastUpdate=new Date(i.progress.lastUpdate)),i.progress?.lastMessageAt&&(i.progress.lastMessageAt=new Date(i.progress.lastMessageAt)),this.tasks.set(i.id,i)}catch{}}catch{}}startPruning(){this.pruneInterval||(this.pruneInterval=setInterval(()=>{this.pruneStaleTasksAndNotifications()},6e4),this.pruneInterval.unref&&this.pruneInterval.unref())}stopPruning(){this.pruneInterval&&(clearInterval(this.pruneInterval),this.pruneInterval=void 0)}pruneStaleTasksAndNotifications(){let t=Date.now(),n=this.config.taskTimeoutMs??kx;for(let[r,o]of this.tasks.entries())t-o.startedAt.getTime()>n&&o.status==="running"&&(o.status="error",o.error=`Task timed out after ${Math.round(n/6e4)} minutes`,o.completedAt=new Date,o.concurrencyKey&&this.concurrencyManager.release(o.concurrencyKey),this.clearNotificationsForTask(r),this.unpersistTask(r),this.tasks.delete(r));for(let[r,o]of this.notifications.entries()){let s=o.filter(i=>t-i.startedAt.getTime()<=n);s.length===0?this.notifications.delete(r):s.length!==o.length&&this.notifications.set(r,s)}}async launch(t){let n=t.agent,r=this.config.maxTotalTasks??10;if(Array.from(this.tasks.values()).filter(c=>c.status==="running").length>=r)throw new Error(`Maximum concurrent background tasks (${r}) reached. Wait for some tasks to complete.`);await this.concurrencyManager.acquire(n);let s=this.generateTaskId(),i=`ses_${this.generateTaskId()}`,a={id:s,sessionId:i,parentSessionId:t.parentSessionId,description:t.description,prompt:t.prompt,agent:t.agent,status:"running",startedAt:new Date,progress:{toolCalls:0,lastUpdate:new Date},concurrencyKey:n};return this.tasks.set(s,a),this.persistTask(a),a}async resume(t){let n=this.findBySession(t.sessionId);if(!n)throw new Error(`Task not found for session: ${t.sessionId}`);return n.status="running",n.completedAt=void 0,n.error=void 0,n.parentSessionId=t.parentSessionId,n.progress||(n.progress={toolCalls:0,lastUpdate:new Date}),n.progress.lastUpdate=new Date,this.persistTask(n),n}getTask(t){return this.tasks.get(t)}findBySession(t){for(let n of this.tasks.values())if(n.sessionId===t)return n}getTasksByParentSession(t){let n=[];for(let r of this.tasks.values())r.parentSessionId===t&&n.push(r);return n}getAllTasks(){return Array.from(this.tasks.values())}getRunningTasks(){return Array.from(this.tasks.values()).filter(t=>t.status==="running")}updateTaskStatus(t,n,r,o){let s=this.tasks.get(t);s&&(s.status=n,r&&(s.result=r),o&&(s.error=o),(n==="completed"||n==="error"||n==="cancelled")&&(s.completedAt=new Date,s.concurrencyKey&&this.concurrencyManager.release(s.concurrencyKey),this.markForNotification(s)),this.persistTask(s))}updateTaskProgress(t,n){let r=this.tasks.get(t);r&&(r.progress||(r.progress={toolCalls:0,lastUpdate:new Date}),Object.assign(r.progress,n,{lastUpdate:new Date}),this.persistTask(r))}markForNotification(t){let n=this.notifications.get(t.parentSessionId)??[];n.push(t),this.notifications.set(t.parentSessionId,n)}getPendingNotifications(t){return this.notifications.get(t)??[]}clearNotifications(t){this.notifications.delete(t)}clearNotificationsForTask(t){for(let[n,r]of this.notifications.entries()){let o=r.filter(s=>s.id!==t);o.length===0?this.notifications.delete(n):this.notifications.set(n,o)}}removeTask(t){let n=this.tasks.get(t);n?.concurrencyKey&&this.concurrencyManager.release(n.concurrencyKey),this.clearNotificationsForTask(t),this.unpersistTask(t),this.tasks.delete(t)}formatDuration(t,n){let r=(n??new Date).getTime()-t.getTime(),o=Math.floor(r/1e3),s=Math.floor(o/60),i=Math.floor(s/60);return i>0?`${i}h ${s%60}m ${o%60}s`:s>0?`${s}m ${o%60}s`:`${o}s`}getStatusSummary(){let t=this.getRunningTasks(),n=this.getAllTasks();if(n.length===0)return"No background tasks.";let r=[`Background Tasks: ${t.length} running, ${n.length} total`,""];for(let o of n){let s=this.formatDuration(o.startedAt,o.completedAt),i=o.status.toUpperCase(),a=o.progress?` (${o.progress.toolCalls} tools)`:"";r.push(` [${i}] ${o.description} - ${s}${a}`),o.error&&r.push(` Error: ${o.error}`)}return r.join(`
|
|
1998
|
+
`)}cleanup(){this.stopPruning(),this.tasks.clear(),this.notifications.clear()}},Xc;function Zc(e){return Xc||(Xc=new qs(e)),Xc}function Sx(e){let t=e.status.toUpperCase(),n=vx(e.startedAt,e.completedAt),o=[`${e.status==="completed"?"\u2713":e.status==="error"?"\u2717":"\u25CB"} [${t}] ${e.description}`,` Agent: ${e.agent}`,` Duration: ${n}`];if(e.progress?.toolCalls&&o.push(` Tool calls: ${e.progress.toolCalls}`),e.result){let s=e.result.substring(0,200),i=e.result.length>200?"...":"";o.push(` Result: ${s}${i}`)}return e.error&&o.push(` Error: ${e.error}`),o.join(`
|
|
1999
|
+
`)}function vx(e,t){let n=(t??new Date).getTime()-e.getTime(),r=Math.floor(n/1e3),o=Math.floor(r/60),s=Math.floor(o/60);return s>0?`${s}h ${o%60}m ${r%60}s`:o>0?`${o}m ${r%60}s`:`${r}s`}function bx(e){if(e.length===0)return"";let t=e.length===1?`
|
|
2000
2000
|
[BACKGROUND TASK COMPLETED]
|
|
2001
2001
|
`:`
|
|
2002
2002
|
[${e.length} BACKGROUND TASKS COMPLETED]
|
|
2003
|
-
`,n=e.map(r=>
|
|
2003
|
+
`,n=e.map(r=>Sx(r)).join(`
|
|
2004
2004
|
|
|
2005
2005
|
`);return`${t}
|
|
2006
2006
|
${n}
|
|
2007
|
-
`}function
|
|
2007
|
+
`}function Ex(e,t,n){let r=t.getPendingNotifications(e);if(r.length===0)return{hasNotifications:!1,tasks:[]};let s=(n?.formatNotification??bx)(r);return{hasNotifications:!0,tasks:r,message:s}}function Yy(e,t){let n=e.sessionId;if(!n)return{continue:!0};let r=Zc(),o=Ex(n,r,t);return o.hasNotifications?((t?.autoClear??!0)&&r.clearNotifications(n),{continue:!0,message:o.message,notificationCount:o.tasks.length}):{continue:!0}}function Ky(){I({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 Yy(t);return{continue:n.continue,hookSpecificOutput:n.message?{hookEventName:"Notification",additionalContext:n.message}:void 0}}})}var tl=null,el=!1;async function Tx(){if(!el)try{let{encode:e}=await import("gpt-tokenizer");tl=e,el=!0}catch{el=!0}}function Cx(e){return Math.ceil(e.length/4)}async function jn(e){if(!e||e.length===0)return 0;await Tx();try{if(tl)return tl(e).length}catch{}return Cx(e)}async function Jy(e){if(!e)return 0;if(typeof e=="object"&&e!==null){let n=e;if("content"in n&&typeof n.content=="string")return jn(n.content);if("output"in n&&typeof n.output=="string")return jn(n.output);if("text"in n&&typeof n.text=="string")return jn(n.text);if("result"in n&&typeof n.result=="string")return jn(n.result)}let t=typeof e=="string"?e:JSON.stringify(e);return jn(t)}var nl=[{model_pattern:"claude-opus",input_per_million:15,output_per_million:75,effective_date:"2025-01-01"},{model_pattern:"claude-sonnet",input_per_million:3,output_per_million:15,effective_date:"2025-01-01"},{model_pattern:"claude-haiku",input_per_million:.25,output_per_million:1.25,effective_date:"2025-01-01"}];function zy(e,t,n,r=nl){let o=r.find(a=>new RegExp(a.model_pattern,"i").test(n));if(!o){let a=r.find(u=>u.model_pattern==="claude-sonnet")||{input_per_million:3,output_per_million:15,effective_date:"2025-01-01"},c=e/1e6*a.input_per_million,l=t/1e6*a.output_per_million;return{inputCost:c,outputCost:l,totalCost:c+l,pricingVersion:a.effective_date}}let s=e/1e6*o.input_per_million,i=t/1e6*o.output_per_million;return{inputCost:s,outputCost:i,totalCost:s+i,pricingVersion:o.effective_date}}Ue();ye();var _r=v(require("fs"),1),Vs=v(require("path"),1),nw=v(require("os"),1),rw=process.env.OLYMPUS_DEBUG_HOOKS==="1",Zy=Vs.join(nw.homedir(),".claude","olympus","learning","hooks-debug.log");function N(e,t,n){if(rw)try{let o=`[${new Date().toISOString()}] [${e}] ${t}`;n!==void 0&&(typeof n=="object"?o+=`
|
|
2008
2008
|
${JSON.stringify(n,null,2)}`:o+=` ${n}`),o+=`
|
|
2009
|
-
`;let s=
|
|
2009
|
+
`;let s=Vs.dirname(Zy);_r.existsSync(s)||_r.mkdirSync(s,{recursive:!0}),_r.appendFileSync(Zy,o,"utf8")}catch(r){console.error("[Olympus Debug] Failed to write debug log:",r)}}function rl(e,t){rw&&N(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 xx(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 ew(e){if(e.message?.model){let{providerId:t,modelId:n}=e.message.model;if(t&&n)return`${t}/${n}`;if(n)return n}}function tw(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 ow(){I({name:"learningCapturePrompt",event:"UserPromptSubmit",priority:110,handler:async e=>{N("learningCapturePrompt","Hook fired"),rl("learningCapturePrompt",e);try{if(!e.directory)return N("learningCapturePrompt","No directory in context - skipping"),{continue:!0};N("learningCapturePrompt","Extracting prompt text");let t=xx(e);if(!t)return N("learningCapturePrompt","No prompt text extracted - skipping"),{continue:!0};N("learningCapturePrompt",`Prompt text extracted (${t.length} chars)`),N("learningCapturePrompt","Estimating input tokens");let n=await jn(t);N("learningCapturePrompt",`Estimated tokens: ${n}`),N("learningCapturePrompt","Loading session state",{directory:e.directory,sessionId:e.sessionId});let r=Q(e.directory,e.sessionId);N("learningCapturePrompt","Session state loaded",{hasTokenBudget:!!r.token_budget,currentUsage:r.token_budget?.current_usage,inputTokens:r.token_budget?.input_tokens,outputTokens:r.token_budget?.output_tokens}),tw(r),N("learningCapturePrompt","Token budget ensured");let o=ew(e);if(N("learningCapturePrompt",`Model identifier: ${o||"none"}`),o&&r.token_budget&&(r.token_budget.current_model=o,N("learningCapturePrompt",`Model set in token budget: ${o}`)),r.token_budget){let s=r.token_budget.input_tokens,i=r.token_budget.current_usage;r.token_budget.input_tokens+=n,r.token_budget.current_usage+=n,N("learningCapturePrompt","Tokens accumulated",{addedTokens:n,inputTokens:{before:s,after:r.token_budget.input_tokens},currentUsage:{before:i,after:r.token_budget.current_usage}}),N("learningCapturePrompt","Saving session state"),ee(e.directory,r),N("learningCapturePrompt","Session state saved successfully")}else N("learningCapturePrompt","WARNING: No token budget after ensure - this should not happen")}catch(t){N("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 N("learningCapturePrompt","Hook completed"),{continue:!0}}}),I({name:"learningCaptureTool",event:"PostToolUse",priority:70,handler:async e=>{N("learningCaptureTool","Hook fired"),rl("learningCaptureTool",e);try{if(!e.directory||!e.toolName)return N("learningCaptureTool","Missing directory or toolName - skipping",{hasDirectory:!!e.directory,hasToolName:!!e.toolName}),{continue:!0};N("learningCaptureTool",`Processing tool: ${e.toolName}`),N("learningCaptureTool","Estimating output tokens from tool result");let t=e.toolOutput?await Jy(e.toolOutput):0;N("learningCaptureTool",`Estimated output tokens: ${t}`),N("learningCaptureTool","Loading session state",{directory:e.directory,sessionId:e.sessionId});let n=Q(e.directory,e.sessionId);N("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}),tw(n),N("learningCaptureTool","Token budget ensured");let r=ew(e);if(N("learningCaptureTool",`Model identifier: ${r||"none"}`),r&&n.token_budget&&(n.token_budget.current_model=r,N("learningCaptureTool",`Model set in token budget: ${r}`)),n.token_budget){let o=n.token_budget.output_tokens,s=n.token_budget.current_usage;n.token_budget.output_tokens+=t,n.token_budget.current_usage+=t,N("learningCaptureTool","Tokens accumulated",{addedTokens:t,outputTokens:{before:o,after:n.token_budget.output_tokens},currentUsage:{before:s,after:n.token_budget.current_usage}}),N("learningCaptureTool","Saving session state"),ee(e.directory,n),N("learningCaptureTool","Session state saved successfully")}else N("learningCaptureTool","WARNING: No token budget after ensure - this should not happen")}catch(t){N("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 N("learningCaptureTool","Hook completed"),{continue:!0}}}),I({name:"learningCaptureStop",event:"Stop",priority:90,handler:async e=>{N("learningCaptureStop","Hook fired"),rl("learningCaptureStop",e);try{if(!e.directory)return N("learningCaptureStop","No directory in context - skipping"),{continue:!0};N("learningCaptureStop","Loading session state",{directory:e.directory,sessionId:e.sessionId});let t=Q(e.directory,e.sessionId);if(N("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 N("learningCaptureStop","No token budget in session state - skipping (backward compatibility)"),{continue:!0};let n=t.token_budget.current_usage,r=t.token_budget.input_tokens||0,o=t.token_budget.output_tokens||0;if(N("learningCaptureStop","Token totals",{totalTokens:n,inputTokens:r,outputTokens:o}),n===0)return N("learningCaptureStop","No token usage recorded - skipping feedback entry creation"),{continue:!0};let s=t.token_budget.current_model||"unknown";N("learningCaptureStop",`Using model identifier: ${s}`),N("learningCaptureStop","Token usage object created",{input_tokens:r,output_tokens:o,total_tokens:n,estimated:!0,model:s}),N("learningCaptureStop","Calculating cost estimate");let a={input_cost:0,output_cost:0,total_cost:0,pricing_version:"2025-01-01"};try{let l=zy(r,o,s);a.input_cost=l.inputCost,a.output_cost=l.outputCost,a.total_cost=l.totalCost,a.pricing_version=l.pricingVersion,N("learningCaptureStop","Cost calculated successfully",{inputCost:l.inputCost,outputCost:l.outputCost,totalCost:l.totalCost})}catch(l){N("learningCaptureStop","Cost calculation failed (not critical)",{error:l instanceof Error?l.message:String(l)})}let c={session_id:t.session_id,project_path:e.directory,started_at:t.token_budget.started_at,ended_at:new Date().toISOString(),duration_seconds:Math.round((Date.now()-new Date(t.token_budget.started_at).getTime())/1e3),agents_used:t.token_budget.agents_used||[],total_input_tokens:r,total_output_tokens:o,total_tokens:n,estimated_cost:a.total_cost,model:s,outcome:"success"};N("learningCaptureStop","Session summary created",{sessionId:c.session_id,duration:c.duration_seconds,agentsUsed:c.agents_used,totalTokens:c.total_tokens,cost:c.estimated_cost});try{uu(c),N("learningCaptureStop","Session summary saved successfully")}catch(l){N("learningCaptureStop","Failed to save session summary (non-critical)",{error:l instanceof Error?l.message:String(l)})}try{let{formatSessionSummaryLine:l}=await Promise.resolve().then(()=>(Xy(),Qy)),u=l(c);console.error(u)}catch{}N("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,N("learningCaptureStop","Saving reset session state"),ee(e.directory,t),N("learningCaptureStop","Session state saved successfully")}catch(t){N("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 N("learningCaptureStop","Hook completed"),{continue:!0}}})}Ue();function sw(){I({name:"budgetWarning",event:"PostToolUse",priority:90,handler:e=>{if(!e.directory)return{continue:!0};try{let t=Q(e.directory,e.sessionId),n=0;if(e.toolOutput&&typeof e.toolOutput=="object"){let r=e.toolOutput;r.token_usage&&typeof r.token_usage=="object"&&(n=r.token_usage.total_tokens??0)}if(n>0&&_u(t,n),Su(t)){let r=t.token_budget,o=(r.current_usage/1e3).toFixed(1),s=(r.session_baseline/1e3).toFixed(0),i=(r.current_usage/r.session_baseline).toFixed(2);return ku(t),ee(e.directory,t),{continue:!0,message:`[TOKEN AWARENESS] Session at ${o}k tokens (${i}x baseline of ${s}k).
|
|
2010
2010
|
This is informational - continue if task requires it.
|
|
2011
|
-
Consider: delegate to subagent, break into smaller tasks.`}}return ee(e.directory,t),{continue:!0}}catch(t){return console.error("[Olympus Learning] Budget warning error:",t),{continue:!0}}}})}
|
|
2011
|
+
Consider: delegate to subagent, break into smaller tasks.`}}return ee(e.directory,t),{continue:!0}}catch(t){return console.error("[Olympus Learning] Budget warning error:",t),{continue:!0}}}})}Ue();ce();Z();Jo();Mt();var kr=v(require("fs"),1),go=v(require("path"),1),fw=v(require("os"),1),Dx=process.env.OLYMPUS_DEBUG_HOOKS==="1",pw=go.join(fw.homedir(),".claude","olympus","learning","hooks-debug.log");function B(e,t,n){if(Dx)try{let o=`[${new Date().toISOString()}] [${e}] ${t}`;n!==void 0&&(typeof n=="object"?o+=`
|
|
2012
2012
|
${JSON.stringify(n,null,2)}`:o+=` ${n}`),o+=`
|
|
2013
|
-
`;let s=
|
|
2014
|
-
`),o=e.length;n&&n[0].length<=t&&(o=Math.min(o,n[0].length)),r>0&&r<=t&&(o=Math.min(o,r)),o=Math.min(o,t);let s=e.substring(0,o).trim();return s.length<e.length&&!s.endsWith(".")?
|
|
2015
|
-
`).filter(i=>i.trim()).map(i=>{try{return JSON.parse(i)}catch{return null}}).filter(i=>i?new Date(i.timestamp)>=s:!1)}catch{return[]}}
|
|
2013
|
+
`;let s=go.dirname(pw);kr.existsSync(s)||kr.mkdirSync(s,{recursive:!0}),kr.appendFileSync(pw,o,"utf8")}catch(r){console.error("[Olympus Debug] Failed to write debug log:",r)}}async function Nx(e,t){try{let n=e.includes("executing a coding task as part of a structured workflow"),r=e.match(/BOLT-(\d+)/i);if(!n&&!r)return null;let o=await oe(t);if(o.length===0)return null;let s=await A(t,o[0]);return s?s.active_code_plan_path?{boltId:s.active_code_plan_path,workflowId:s.workflow_id}:r&&n?{boltId:`BOLT-${r[1].padStart(3,"0")}`,workflowId:s.workflow_id}:null:null}catch(n){return B("agentTracking","Error detecting BOLT execution",{error:n instanceof Error?n.message:String(n)}),null}}function mw(){I({name:"agentTracking",event:"PreToolUse",priority:50,handler:async e=>{B("agentTracking","Hook fired"),B("agentTracking","Context received",{directory:e.directory,sessionId:e.sessionId,toolName:e.toolName,hasToolInput:!!e.toolInput});let t=null;try{if(e.toolName!=="Task")return B("agentTracking",`Skipping non-Task tool: ${e.toolName}`),{continue:!0};if(B("agentTracking","Task tool detected - processing"),!e.directory)return B("agentTracking","No directory in context - skipping"),{continue:!0};if(!e.sessionId)return B("agentTracking","No sessionId in context - skipping"),{continue:!0};if(!e.toolInput)return B("agentTracking","No toolInput in context - skipping"),{continue:!0};let n=e.toolInput,r=n.subagent_type,o=n.prompt;if(B("agentTracking","Tool input extracted",{subagentType:r,hasPrompt:!!o,promptLength:typeof o=="string"?o.length:0}),!r||typeof r!="string")return B("agentTracking","Missing or invalid subagent_type - skipping"),{continue:!0};if(!o||typeof o!="string")return B("agentTracking","Missing or invalid prompt - skipping"),{continue:!0};B("agentTracking","Loading session state",{directory:e.directory,sessionId:e.sessionId});let s=Q(e.directory,e.sessionId);B("agentTracking","Session state loaded",{sessionId:s.session_id,hasPendingCompletion:!!s.pending_completion});try{let{getRoutingRecommendation:a}=await Promise.resolve().then(()=>(dw(),uw));t=a(r,o),t&&B("agentTracking","Routing recommendation generated",{recommendation:t})}catch{}let i=await Nx(o,e.directory);if(B("agentTracking","BOLT detection result",{isBoltExecution:!!i,boltId:i?.boltId,workflowId:i?.workflowId}),B("agentTracking","Marking completion claim",{agent:r,taskLength:o.length,hasBoltMetadata:!!i}),hu(s,o,r),i&&s.pending_completion){s.pending_completion.bolt_id=i.boltId,s.pending_completion.workflow_id=i.workflowId,B("agentTracking","BOLT metadata added to pending_completion",{bolt_id:i.boltId,workflow_id:i.workflowId});try{let a=await oe(e.directory),c=null;for(let l of a){let u=await A(e.directory,l);if(u&&u.status!=="complete"&&u.status!=="archived"&&u.status!=="deferred"){c=l;break}}if(!c)B("agentTracking","No active workflow found for manifest update");else{let l=go.join(e.directory,"aidlc-docs",c,"manifest.json"),u=W(l);if(u){let d=u.artifacts.find(p=>p.id===i.boltId);d&&(d.executedBy=r,G(l,u),B("agentTracking","Set executedBy on BOLT artifact",{boltId:i.boltId,executedBy:r}))}}}catch(a){B("agentTracking","Error setting executedBy on manifest",{error:a instanceof Error?a.message:String(a)})}}B("agentTracking","Completion claim marked",{claimedAt:s.pending_completion?.claimed_at,agentUsed:s.pending_completion?.agent_used,bolt_id:s.pending_completion?.bolt_id,workflow_id:s.pending_completion?.workflow_id}),s.token_budget&&(s.token_budget.agents_used||(s.token_budget.agents_used=[]),s.token_budget.agents_used.includes(r)||s.token_budget.agents_used.push(r),B("agentTracking","Agents accumulated",{agents_used:s.token_budget.agents_used})),B("agentTracking","Saving session state"),ee(e.directory,s),B("agentTracking","Session state saved successfully")}catch(n){B("agentTracking","ERROR in handler",{error:n instanceof Error?n.message:String(n),stack:n instanceof Error?n.stack:void 0}),console.error("[Olympus Agent Tracking] Error in handler:",n)}return B("agentTracking","Hook completed"),t?{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:t}}:{continue:!0}}}),I({name:"agentTrackingBoltCompletion",event:"PostToolUse",priority:51,handler:async e=>{B("agentTrackingBoltCompletion","Hook fired");try{if(e.toolName!=="Task")return B("agentTrackingBoltCompletion",`Skipping non-Task tool: ${e.toolName}`),{continue:!0};if(!e.directory||!e.sessionId)return B("agentTrackingBoltCompletion","Missing directory or sessionId - skipping"),{continue:!0};let t=Q(e.directory,e.sessionId);if(B("agentTrackingBoltCompletion","Session state loaded",{hasPendingCompletion:!!t.pending_completion,bolt_id:t.pending_completion?.bolt_id}),!t.pending_completion||!t.pending_completion.bolt_id)return B("agentTrackingBoltCompletion","No BOLT execution detected - skipping"),{continue:!0};let{bolt_id:n,workflow_id:r,agent_used:o,task_description:s}=t.pending_completion;if(!o)return B("agentTrackingBoltCompletion","No agent_used in pending_completion - skipping"),{continue:!0};B("agentTrackingBoltCompletion","Recording BOLT execution",{boltId:n,agentName:o,workflowId:r}),Cf({boltId:n,agentName:o,success:!0,sessionId:e.sessionId,projectPath:e.directory,taskDescription:s}),B("agentTrackingBoltCompletion","BOLT execution recorded successfully");try{let i={type:"bolt_execution_complete",phase:"construction",stage:"code-generation",details:`BOLT ${n} executed by ${o}`,artifactId:n,agentName:o},a={workflowId:r||"unknown",featureName:r||"unknown",projectPath:e.directory,sessionId:e.sessionId,phase:"construction"},c=He(i,a);ue(c),B("agentTrackingBoltCompletion","BOLT completion discovery recorded",{boltId:n,discoveryId:c.id})}catch(i){console.error("[Olympus Agent Tracking] Failed to capture BOLT completion discovery:",i),B("agentTrackingBoltCompletion","Failed to capture BOLT completion discovery",{error:i instanceof Error?i.message:String(i)})}}catch(t){B("agentTrackingBoltCompletion","ERROR in handler",{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0}),console.error("[Olympus Agent Tracking BOLT Completion] Error in handler:",t)}return B("agentTrackingBoltCompletion","Hook completed"),{continue:!0}}})}Ue();var sl=require("path"),gw=require("os");ye();var jx={enabled:!0,minConfidence:.6,maxPerSession:5,maxPerDay:20,deduplicationWindowDays:7};function Sr(e){let t=(0,sl.join)((0,gw.homedir)(),".claude","olympus","config.json"),n=we(t,{}),r={};if(e){let s=(0,sl.join)(e,".olympus","config.json");r=we(s,{})}let o={...jx,...n.autoDiscovery||{},...r.autoDiscovery||{}};return o.minConfidence=Math.max(0,Math.min(1,o.minConfidence)),o.maxPerSession=Math.max(1,Math.min(50,o.maxPerSession)),o.maxPerDay=Math.max(1,Math.min(200,o.maxPerDay)),o.deduplicationWindowDays=Math.max(1,Math.min(90,o.deduplicationWindowDays)),o}var Ys=require("fs"),hw=require("path");ye();var Fx={praise:.85,problem_solved:.7,topic_change:.6},Mx=[{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 yw(e,t){if(!e.pending_completion?.task_description)return null;let n=e.pending_completion.task_description,r=e.pending_completion.agent_used||"unknown",o=Gx(n),s=Hx(n),i=Lx(n,r),a=Fx[t]??.6;return{session_id:e.session_id,category:i,summary:o,details:s,agent_name:r,task_context:n.substring(0,200),confidence:a,scope:"project"}}function ww(e,t,n=7){let r=qx(t,n);if(r.length===0)return!1;let o=e.summary||"",s=e.details||"";for(let i of r)if(i.details===s&&s.length>0||o.length>0&&i.summary&&Ux(o,i.summary)>.7)return!0;return!1}function Lx(e,t){for(let{pattern:n,category:r}of Mx)if(n.test(e))return r;return"technical_insight"}function Ux(e,t){let n=a=>new Set(a.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter(c=>c.length>3)),r=n(e),o=n(t);if(r.size===0&&o.size===0)return 1;if(r.size===0||o.size===0)return 0;let s=new Set([...r].filter(a=>o.has(a))),i=new Set([...r,...o]);return i.size>0?s.size/i.size:0}function vr(e,t){if(e.length<=t)return e;let n=e.substring(0,t),r=n.lastIndexOf(" ");return r>t*.5?n.substring(0,r)+"...":n+"..."}function Wx(e,t=100){if(!e||e.length===0)return"";let n=e.match(/^[^.]+\./),r=e.indexOf(`
|
|
2014
|
+
`),o=e.length;n&&n[0].length<=t&&(o=Math.min(o,n[0].length)),r>0&&r<=t&&(o=Math.min(o,r)),o=Math.min(o,t);let s=e.substring(0,o).trim();return s.length<e.length&&!s.endsWith(".")?vr(s,t):s}function Bx(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 Gx(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=Bx(e),r=Wx(n,150);for(let[s,i]of Object.entries(t)){let a=new RegExp(`^${s}\\b`,"i");if(a.test(r)){let c=r.replace(a,i);return vr(c.trim(),100)}}let o=n.match(/^In the .+? project,\s*(.+)/i);if(o){let s=o[1].trim();if(s.toLowerCase().startsWith("i need to")){let i=s.replace(/^i need to\s+/i,"");return vr(i.charAt(0).toUpperCase()+i.slice(1),100)}return vr(s,100)}return vr(r,100)}function Hx(e){if(!e||e.length===0)return"";let t=e;t=t.replace(/```[\s\S]*?```/g,"[code block]"),t=t.replace(/`[^`]+`/g,"");let n=t.match(/^(.*?)(?=\n##|\n\n##|$)/s);n&&(t=n[1].trim());let r=t.match(/^\d+\.\s+(.+)/gm);return r&&r.length>0&&(t=r.slice(0,3).map(i=>i.replace(/^\d+\.\s+/,"").trim()).join("; ")),t=t.split(/\n\n/)[0]||t,t=t.replace(/\s+/g," ").trim(),t.length>500?vr(t,500):t}function qx(e,t){let n=yt(e),r=(0,hw.join)(n,"discoveries.jsonl");if(!(0,Ys.existsSync)(r))return[];try{let o=(0,Ys.readFileSync)(r,"utf-8"),s=new Date(Date.now()-t*24*60*60*1e3);return o.split(`
|
|
2015
|
+
`).filter(i=>i.trim()).map(i=>{try{return JSON.parse(i)}catch{return null}}).filter(i=>i?new Date(i.timestamp)>=s:!1)}catch{return[]}}Mt();function _w(){I({name:"discoveryCapture",event:"Stop",priority:92,handler:async e=>{try{if(!e.directory)return{continue:!0};let t=Sr(e.directory);if(!t.enabled)return{continue:!0};let n=Q(e.directory,e.sessionId);if(bu(n,t))return{continue:!0};if(!Co(n))return{continue:!0};let r=Vx(n);if(!r)return{continue:!0};let o=yw(n,r);if(!o)return{continue:!0};if((o.confidence||0)<t.minConfidence)return{continue:!0};if(ww(o,e.directory,t.deduplicationWindowDays))return{continue:!0};ue({...o,project_path:e.directory,session_id:n.session_id,category:o.category||"technical_insight",summary:o.summary||"",details:o.details||"",agent_name:o.agent_name||"unknown",confidence:o.confidence||.6,scope:"project"}),vu(n),ee(e.directory,n)}catch(t){console.error("[Olympus Discovery Capture] Error:",t)}return{continue:!0}}})}function Vx(e){let t=e.recent_prompts||[];if(t.length===0)return null;let n=t[0];return n?.detected_feedback==="praise"?"praise":n?.prompt&&e.pending_completion?.task_description&&Yx(n.prompt,e.pending_completion.task_description)<.2?"topic_change":null}function Yx(e,t){let n=a=>new Set(a.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter(c=>c.length>3)),r=n(e),o=n(t);if(r.size===0&&o.size===0)return 1;if(r.size===0||o.size===0)return 0;let s=new Set([...r].filter(a=>o.has(a))),i=new Set([...r,...o]);return i.size>0?s.size/i.size:0}Ue();var br=require("fs"),vw=require("path"),kw=new Map;function bw(e,t,n){try{if(!(0,br.existsSync)(t))return null;let r=(0,vw.relative)(e,t),o=(0,br.readFileSync)(t,"utf-8"),i=(0,br.statSync)(t).mtimeMs,a=kw.get(t),c=a===void 0;if(kw.set(t,i),!c&&a===i)return null;let l=Kx(o);if(c)return{event_type:"plan_created",plan_path:r,plan_summary:l,revision_count:0,session_id:n,timestamp:new Date().toISOString()};let u=zx(t);return{event_type:"plan_revised",plan_path:r,plan_summary:l,revision_count:u,session_id:n,timestamp:new Date().toISOString()}}catch{return null}}function Ew(e){let t=typeof e=="string"?e:String(e||"");if(!t)return{passed:!1,issues:["Empty review output"]};let n=t.toUpperCase(),o=["APPROVED","LOOKS GOOD","NO CRITICAL ISSUES","PLAN IS SOLID"].some(c=>n.includes(c)),i=["CRITICAL","REVISE","REJECT","MAJOR ISSUE","MISSING","INCOMPLETE"].some(c=>n.includes(c)),a=Jx(t);return o&&!i?{passed:!0,issues:a}:i?{passed:!1,issues:a.length>0?a:["Plan requires revision"]}:{passed:!0,issues:a}}function il(e,t,n){let r=e.plan_path.split("/").pop()||e.plan_path,o=t.length,s=e.event_type==="plan_review_failed"?`Plan '${r}' failed review: ${o} issue${o!==1?"s":""}`:`Plan '${r}' failed: ${o} issue${o!==1?"s":""}`,i=t.map(c=>`- ${c}`).join(`
|
|
2016
2016
|
`).substring(0,500),a=[e.reviewer?`Issues found by ${e.reviewer}:`:"Issues:",i].join(`
|
|
2017
|
-
`);return{session_id:e.session_id,project_path:n,category:"planning_insight",summary:s,details:a,agent_name:"prometheus",task_context:`Plan lifecycle: ${e.event_type}`,files_involved:[e.plan_path],confidence:.9,scope:"project"}}function
|
|
2017
|
+
`);return{session_id:e.session_id,project_path:n,category:"planning_insight",summary:s,details:a,agent_name:"prometheus",task_context:`Plan lifecycle: ${e.event_type}`,files_involved:[e.plan_path],confidence:.9,scope:"project"}}function Tw(e){if(e.length===0)return"";let t=["<plan-learnings>","## Planning Insights (from previous sessions)",""],n=[],r=[];for(let s of e.slice(0,5))s.summary.includes("failed")?n.push(`- ${s.summary}`):r.push(`- ${s.summary}`);n.length>0&&(t.push("**Common Planning Mistakes:**"),t.push(...n),t.push("")),r.length>0&&(t.push("**Required Considerations:**"),t.push(...r),t.push("")),t.push("</plan-learnings>");let o=t.join(`
|
|
2018
2018
|
`);return o.length>1200?o.substring(0,1200)+`
|
|
2019
|
-
</plan-learnings>`:o}function
|
|
2020
|
-
`);for(let r of n){let o=r.trim();/^[-*]\s+(CRITICAL|ISSUE|PROBLEM|MISSING|BUG|CONCERN):/i.test(o)&&t.push(o.replace(/^[-*]\s+/,"")),/\b(CRITICAL|MAJOR)\s+(ISSUE|PROBLEM|BUG|GAP)/i.test(o)&&o.length<200&&(t.includes(o)||t.push(o))}return t.slice(0,10)}var
|
|
2019
|
+
</plan-learnings>`:o}function Kx(e){let t=e;if(t.startsWith("---")){let r=t.indexOf("---",3);r>0&&(t=t.substring(r+3).trim())}return t.replace(/^#+\s*/gm,"").replace(/\n+/g," ").trim().substring(0,200)}function Jx(e){let t=[],n=e.split(`
|
|
2020
|
+
`);for(let r of n){let o=r.trim();/^[-*]\s+(CRITICAL|ISSUE|PROBLEM|MISSING|BUG|CONCERN):/i.test(o)&&t.push(o.replace(/^[-*]\s+/,"")),/\b(CRITICAL|MAJOR)\s+(ISSUE|PROBLEM|BUG|GAP)/i.test(o)&&o.length<200&&(t.includes(o)||t.push(o))}return t.slice(0,10)}var Sw=new Map;function zx(e){let n=(Sw.get(e)||0)+1;return Sw.set(e,n),n}Mt();Mt();Z();ce();Wa();var Cw=v(require("path"),1);function Rw(){I({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(!Sr(e.directory).enabled)return{continue:!0};let r=e.toolInput?.file_path;if(!r)return{continue:!0};let o=r.replace(/\\/g,"/");if(!o.includes(".olympus/plans/")||!o.endsWith(".md"))return{continue:!0};let s=bw(e.directory,r,e.sessionId);if(!s)return{continue:!0};if(s.event_type==="plan_revised"&&s.revision_count&&s.revision_count>=2){let i=il(s,[`Plan revised ${s.revision_count} times - may indicate unclear requirements`],e.directory);i.summary&&i.details&&ue({...i,project_path:e.directory,session_id:e.sessionId,category:i.category||"planning_insight",summary:i.summary,details:i.details,agent_name:i.agent_name||"prometheus",confidence:i.confidence||.7,scope:"project"})}}catch(t){console.error("[Olympus Plan Lifecycle] Error in plan file monitor:",t)}return{continue:!0}}}),I({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(!Sr(e.directory).enabled)return{continue:!0};let n=e.toolInput;if(n?.subagent_type!=="momus")return{continue:!0};let o=e.toolOutput,s=typeof o=="string"?o:JSON.stringify(o||""),i=Ew(s);if(!i.passed&&i.issues.length>0){if(!i.issues.some(m=>m!=="Plan requires revision"&&m.length>10))return{continue:!0};let l=(n?.prompt||"").match(/\.olympus\/plans\/([\w-]+\.md)/),u=l?l[0]:"unknown-plan",d=l?l[1]:"unknown-plan",p={event_type:"plan_review_failed",plan_path:u,plan_summary:`Momus review failed with ${i.issues.length} issues`,failure_reasons:i.issues,reviewer:"momus",session_id:e.sessionId,timestamp:new Date().toISOString()},f=il(p,i.issues,e.directory);f.summary&&f.details&&ue({...f,project_path:e.directory,session_id:e.sessionId,category:"planning_insight",summary:f.summary,details:f.details,agent_name:"momus",confidence:.9,scope:"project"})}}catch(t){console.error("[Olympus Plan Lifecycle] Error in Momus review tracker:",t)}return{continue:!0}}}),I({name:"completePlanTracker",event:"UserPromptSubmit",priority:115,handler:async e=>{try{if(!e.directory||!e.sessionId)return{continue:!0};if(!Sr(e.directory).enabled)return{continue:!0};let n=e.prompt||"";if(!((e.parts||[]).map(a=>a.text||"").join(" ")||n).includes("[PLAN COMPLETION MODE - VERIFICATION REQUIRED]"))return{continue:!0};let i=Q(e.directory,e.sessionId);i.pending_completion||(i.pending_completion={claimed_at:new Date().toISOString(),task_description:"plan_completion_verification",agent_used:"complete-plan"},ee(e.directory,i))}catch(t){console.error("[Olympus Plan Lifecycle] Error in complete-plan tracker:",t)}return{continue:!0}}}),I({name:"prometheusLearningsInjection",event:"PreToolUse",priority:55,handler:async e=>{try{if(e.toolName!=="Task")return{continue:!0};if(!e.directory)return{continue:!0};if(e.toolInput?.subagent_type!=="prometheus")return{continue:!0};let o=Yo(e.directory,20).filter(i=>i.category==="planning_insight");if(o.length===0)return{continue:!0};let s=Tw(o.slice(0,5));if(s)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:s}}}catch(t){console.error("[Olympus Plan Lifecycle] Error in Prometheus learnings injection:",t)}return{continue:!0}}}),I({name:"workflowPhaseTransitionTracker",event:"PostToolUse",priority:83,handler:async e=>{try{if(e.toolName!=="Write"&&e.toolName!=="Task")return{continue:!0};if(!e.directory||!e.sessionId)return{continue:!0};let t=e.directory,n=await oe(t),r=null,o=null;for(let u of n){let d=await A(t,u);if(d&&d.status!=="complete"&&d.status!=="archived"&&d.status!=="deferred"){r=u,o=d;break}}if(!r||!o)return{continue:!0};let s=Cw.join(t,"aidlc-docs",r,"manifest.json"),i=W(s);if(!i)return{continue:!0};let a=Q(t,e.sessionId),c=o.current_phase,l=a.last_tracked_phase;if(l&&l!==c){let u=new Date().toISOString();i.gate_audit.push({phase:c,timestamp:u,action:"approved",actor:"trust",reason:`Phase transition: ${l} -> ${c}`});let d=l;i.phases[d]&&(i.phases[d].status="complete",i.phases[d].completed_at=u),i.phases[c]&&i.phases[c].status==="not_started"&&(i.phases[c].status="in_progress",i.phases[c].started_at=u),G(s,i),Ua(t,r,o),(o.status==="complete"||o.current_stage==="complete")&&(i.phases.operations.status="complete",i.phases.operations.completed_at=u,G(s,i)),a.last_tracked_phase=c,ee(t,a);let p={discovery:"Discovery",inception:"Inception",construction:"Construction",operations:"Operations"},f=p[l]||l,m=p[c]||c,g=`Phase transition: ${f} \u2192 ${m}`;return c==="operations"&&(g+=`
|
|
2021
2021
|
\u2192 Generating deployment artifacts...`),{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`<phase-transition>
|
|
2022
2022
|
${g}
|
|
2023
|
-
</phase-transition>`}}}if(l||(a.last_tracked_phase=c,ee(t,a)),o.status==="complete"&&i.phases.operations.status!=="complete"){let u=new Date().toISOString();return i.phases.operations.status="complete",i.phases.operations.completed_at=u,G(s,i),
|
|
2023
|
+
</phase-transition>`}}}if(l||(a.last_tracked_phase=c,ee(t,a)),o.status==="complete"&&i.phases.operations.status!=="complete"){let u=new Date().toISOString();return i.phases.operations.status="complete",i.phases.operations.completed_at=u,G(s,i),Ua(t,r,o),{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`<phase-transition>
|
|
2024
2024
|
\u2713 Workflow complete! All phases finished.
|
|
2025
|
-
</phase-transition>`}}}}catch(t){console.error("[Olympus Plan Lifecycle] Error in phase transition tracker:",t)}return{continue:!0}}})}ce();Z();
|
|
2025
|
+
</phase-transition>`}}}}catch(t){console.error("[Olympus Plan Lifecycle] Error in phase transition tracker:",t)}return{continue:!0}}})}ce();Z();rn();Mo();function al(e,t){return t===3||e<=1?"blocking":"auto-advance"}function cl(e,t){return t===3||e<=1?"blocking":e===2?"summary-review":"notification-only"}function ll(e,t){let n=e.links.find(r=>r.target_id===t&&r.link_type==="derives");return n?n.source_id:null}function xw(e,t){let n=e.artifacts.filter(o=>o.stage==="unit"),r=e.risk_tier?.tier??null;return n.map(o=>{let s=e.links.filter(c=>c.source_id===o.id&&c.link_type==="derives").map(c=>e.artifacts.find(l=>l.id===c.target_id)).filter(c=>c!==void 0),i=s.length>0?`
|
|
2026
2026
|
|
|
2027
2027
|
Child BOLTs:
|
|
2028
2028
|
${s.map(c=>` - ${c.id} (${c.path})`).join(`
|
|
@@ -2031,7 +2031,7 @@ ${s.map(c=>` - ${c.id} (${c.path})`).join(`
|
|
|
2031
2031
|
No child BOLTs found.`,a=`UNIT Artifact: ${o.path}
|
|
2032
2032
|
Contract Status: ${o.contract_status}${i}`;return r===3&&(a+=`
|
|
2033
2033
|
|
|
2034
|
-
NOTE: Risk Tier 3 - Momus review mandatory for architecture decisions.`),{gateNumber:3,gateType:"architecture-review",artifactId:o.id,summary:`Architecture review for ${o.id}`,reviewContent:a,trustLevel:t,trustBehavior:
|
|
2034
|
+
NOTE: Risk Tier 3 - Momus review mandatory for architecture decisions.`),{gateNumber:3,gateType:"architecture-review",artifactId:o.id,summary:`Architecture review for ${o.id}`,reviewContent:a,trustLevel:t,trustBehavior:al(t,r)}})}function Pw(e,t,n,r){let o=e.artifacts.find(c=>c.id===t);if(!o)throw new Error(`BOLT artifact not found: ${t}`);let s=cl(n,r),i="";n<=1?i=`
|
|
2035
2035
|
|
|
2036
2036
|
Review Instructions: Full code review required.`:n===2?i=`
|
|
2037
2037
|
|
|
@@ -2040,7 +2040,7 @@ Review Instructions: Summary review - verify major changes only.`:i=`
|
|
|
2040
2040
|
Review Instructions: Notification only - AI proceeds automatically.`;let a=`BOLT Spec: ${o.path}
|
|
2041
2041
|
Contract Status: ${o.contract_status}${i}`;return r===3&&(a+=`
|
|
2042
2042
|
|
|
2043
|
-
NOTE: Risk Tier 3 - Developer review mandatory for every BOLT.`),{gateNumber:4,gateType:"code-review",artifactId:t,summary:`Code review for ${t}`,reviewContent:a,trustLevel:n,trustBehavior:s}}function
|
|
2043
|
+
NOTE: Risk Tier 3 - Developer review mandatory for every BOLT.`),{gateNumber:4,gateType:"code-review",artifactId:t,summary:`Code review for ${t}`,reviewContent:a,trustLevel:n,trustBehavior:s}}function Aw(e,t){let n=e.artifacts.length,r=e.artifacts.filter(c=>c.stage==="code-generation"),o=e.gate_audit.filter(c=>c.action==="approved").length,s=e.gate_audit.filter(c=>c.action==="rejected").length,i=r.length>0?r.map(c=>` - ${c.id}: ${c.contract_status}`).join(`
|
|
2044
2044
|
`):" No BOLTs found.",a=`Release Approval Review
|
|
2045
2045
|
|
|
2046
2046
|
Feature: ${e.feature_name}
|
|
@@ -2053,7 +2053,7 @@ Gate Audit Summary:
|
|
|
2053
2053
|
BOLT Artifacts:
|
|
2054
2054
|
${i}
|
|
2055
2055
|
|
|
2056
|
-
NOTE: Gate 5 is always blocking - final release approval required.`;return{gateNumber:5,gateType:"release-review",artifactId:e.workflow_id,summary:`Release approval for ${e.feature_name}`,reviewContent:a,trustLevel:t,trustBehavior:"blocking"}}var
|
|
2056
|
+
NOTE: Gate 5 is always blocking - final release approval required.`;return{gateNumber:5,gateType:"release-review",artifactId:e.workflow_id,summary:`Release approval for ${e.feature_name}`,reviewContent:a,trustLevel:t,trustBehavior:"blocking"}}var dn=v(X(),1),Ks=require("path");function ul(e,t,n){dn.ensureDirSync((0,Ks.dirname)(e));let r="";dn.existsSync(e)?r=dn.readFileSync(e,"utf-8"):r=`# Validation Report: ${t}
|
|
2057
2057
|
|
|
2058
2058
|
`;let o=n.commandsExecuted.length>0?n.commandsExecuted.map(d=>`- \`${d.command}\` -> exit ${d.exitCode} (${d.result})`).join(`
|
|
2059
2059
|
`):"- No commands recorded",s=`| Suite | Pass | Fail | Skip |
|
|
@@ -2080,22 +2080,22 @@ ${a}
|
|
|
2080
2080
|
|
|
2081
2081
|
---
|
|
2082
2082
|
|
|
2083
|
-
`,u=r+l;
|
|
2083
|
+
`,u=r+l;dn.writeFileSync(e,u,"utf-8")}function dl(e,t,n){return(0,Ks.join)(e,"aidlc-docs",t,"construction",n,"validation-report.md")}function Qx(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 Iw(e,t,n,r=5){try{let o=n.attemptNumber>=r,s=Qx(n.gateNumber),i;switch(n.gateNumber){case 1:i=`Revise the INTENT based on this feedback: ${n.rejectionReason}`;break;case 2:i=`Update the INTENT based on this feedback: ${n.rejectionReason}`;break;case 3:i=`Regenerate UNITs based on this feedback: ${n.rejectionReason}`;break;case 4:i=`Re-implement this BOLT based on this feedback: ${n.rejectionReason}`;break;case 5:i=`Revise operations artifacts based on this feedback: ${n.rejectionReason}`;break;default:i=`Address this feedback: ${n.rejectionReason}`}let a=o?`Maximum revision attempts reached for ${n.artifactId}. Consider manual intervention or scope change.`:`${i}
|
|
2084
2084
|
|
|
2085
2085
|
Artifact ID: ${n.artifactId}
|
|
2086
2086
|
Workflow ID: ${t}
|
|
2087
2087
|
Attempt Number: ${n.attemptNumber}
|
|
2088
2088
|
Rejected By: ${n.rejectedBy}
|
|
2089
2089
|
|
|
2090
|
-
Please revise the artifact to address the feedback above and re-submit for approval.`;return{agentType:s,prompt:a,maxRetriesReached:o,contractStatusUpdate:{from:"violated",to:"draft"}}}catch(o){throw console.error("Error in dispatchRejection:",o),o}}var
|
|
2090
|
+
Please revise the artifact to address the feedback above and re-submit for approval.`;return{agentType:s,prompt:a,maxRetriesReached:o,contractStatusUpdate:{from:"violated",to:"draft"}}}catch(o){throw console.error("Error in dispatchRejection:",o),o}}var ho=v(require("fs"),1),mt=v(require("path"),1);function ft(e,t){try{return t()}catch(n){return{name:e,passed:!0,severity:"info",remediation:`Check error: ${n instanceof Error?n.message:String(n)}`}}}function pl(e){for(let t of e)if(ho.existsSync(t))return ho.readFileSync(t,"utf-8");return null}function Xx(e){let t="user-stories-criteria",n=pl([mt.join(e,"inception","user-stories","stories.md"),mt.join(e,"inception","stories.md")]);return n===null?{name:t,passed:!0,severity:"info",remediation:"User stories stage was skipped \u2014 no stories.md artifact found."}:/acceptance\s+criteria/i.test(n)||/given\s+.+when\s+.+then/is.test(n)||/\bGiven\b.+\bWhen\b/s.test(n)?{name:t,passed:!0,severity:"info"}:{name:t,passed:!1,severity:"warning",remediation:'User stories are missing acceptance criteria. Add "Acceptance Criteria" sections or Given/When/Then scenarios to each story.'}}function Zx(e){let t="app-design-concrete",n=pl([mt.join(e,"inception","application-design","components.md"),mt.join(e,"inception","application-design.md"),mt.join(e,"inception","application-design","design.md")]);return n===null?{name:t,passed:!0,severity:"info",remediation:"Application design stage was skipped \u2014 no design artifact found."}:/\b(TBD|TODO|placeholder|to be determined|to be decided|N\/A)\b/i.test(n)?{name:t,passed:!1,severity:"warning",remediation:"Application design contains placeholder text (TBD/TODO/placeholder). Replace with concrete technology choices before proceeding to construction."}:{name:t,passed:!0,severity:"info"}}function eP(e){let t="units-have-descriptions",n=pl([mt.join(e,"inception","unit-of-work.md"),mt.join(e,"inception","units-generation","unit-of-work.md")]);return n===null?{name:t,passed:!0,severity:"info",remediation:"Units generation stage was skipped \u2014 no unit-of-work.md artifact found."}:/^Scope\s*:\s*$/im.test(n)||/^Scope\s*:\s*(TBD|TODO|placeholder|N\/A)\s*$/im.test(n)?{name:t,passed:!1,severity:"error",remediation:"One or more units have an empty or placeholder Scope field. All units must have a concrete scope description before construction begins."}:{name:t,passed:!0,severity:"info"}}function Ow(e){return[ft("user-stories-criteria",()=>Xx(e)),ft("app-design-concrete",()=>Zx(e)),ft("units-have-descriptions",()=>eP(e))]}function tP(e){let t="tests-pass",n=e.test_generation_status;if(!n||n==="skipped"||n==="not_started")return{name:t,passed:!0,severity:"info",remediation:"Test generation was skipped or not started \u2014 no test results to evaluate."};let r=e.tests_total??0,o=e.tests_failed??0;return r===0?{name:t,passed:!1,severity:"warning",remediation:"No tests found for this unit. Add tests before marking the unit complete."}:o>0?{name:t,passed:!1,severity:"error",remediation:`${o} test(s) are failing. All tests must pass before Gate 4 approval.`}:{name:t,passed:!0,severity:"info"}}function nP(e){let t="security-clean";if(!e.security_scan_status||e.security_scan_status==="not_started")return{name:t,passed:!0,severity:"info",remediation:"Security scanner not configured or not started."};if(e.security_scan_status==="skipped")return{name:t,passed:!0,severity:"info",remediation:"Security scan was skipped."};let n=e.security_findings_critical??0,r=n>0;return{name:t,passed:!r,severity:r?"error":"info",remediation:r?`${n} critical security finding(s) must be resolved before Gate 4 approval.`:void 0}}function rP(e){let t="feature-doc-exists",n=e.feature_doc_status;return!n||n==="not_started"?{name:t,passed:!1,severity:"error",remediation:"Feature documentation has not been generated. Feature docs are mandatory for unit completion (FR-DOC-003). Run the documentation generator before approving this unit."}:n==="skipped"||n==="in_progress"?{name:t,passed:!0,severity:"info",remediation:n==="in_progress"?"Feature documentation is still in progress.":"Feature documentation was skipped."}:e.feature_doc_path?{name:t,passed:!0,severity:"info"}:{name:t,passed:!1,severity:"error",remediation:"Feature documentation status is completed but no artifact path was recorded. Re-run the documentation generator."}}function oP(e){let t="architecture-model-updated",n=e.architecture_model_status;return!n||n==="not_started"?{name:t,passed:!0,severity:"warning",remediation:"Architecture model has not been updated for this unit. Consider running the architecture model updater."}:n==="updated"||n==="completed"?{name:t,passed:!0,severity:"info"}:{name:t,passed:!0,severity:"warning",remediation:`Architecture model status is "${n}". Verify the model reflects this unit's changes.`}}function fl(e,t){return[ft("tests-pass",()=>tP(e)),ft("security-clean",()=>nP(e)),ft("feature-doc-exists",()=>rP(e)),ft("architecture-model-updated",()=>oP(e))]}function sP(e){let t="all-units-complete",n=e.construction_units;if(!n||Object.keys(n).length===0)return{name:t,passed:!0,severity:"info",remediation:"No construction units tracked in checkpoint."};let r=Object.values(n).filter(o=>o.code_generation_status!=="completed");if(r.length>0){let o=r.map(s=>s.unitId).join(", ");return{name:t,passed:!1,severity:"error",remediation:`${r.length} unit(s) have not completed code generation: ${o}. All units must be completed before Gate 5.`}}return{name:t,passed:!0,severity:"info"}}function iP(e){let t="smoke-test-passed",n=e.smoke_test;return!n||n.status==="not_run"?{name:t,passed:!0,severity:"warning",remediation:"No smoke test result recorded. Run the smoke test build before proceeding to operations."}:n.status==="failed"?{name:t,passed:!1,severity:"error",remediation:`Smoke test failed (${n.tests_failed} failure(s) of ${n.tests_total} total). Fix failing tests before Gate 5 approval.`}:{name:t,passed:!0,severity:"info"}}function aP(e){let t="security-report-clean",n=e.construction_units;if(!n||Object.keys(n).length===0)return{name:t,passed:!0,severity:"info",remediation:"No construction units with security data found."};let r=Object.values(n).filter(s=>s.security_scan_status==="completed");if(r.length===0)return{name:t,passed:!0,severity:"info",remediation:"No units have completed security scans."};let o=r.reduce((s,i)=>s+(i.security_findings_critical??0),0);if(o>0){let s=r.filter(i=>(i.security_findings_critical??0)>0).map(i=>i.unitId).join(", ");return{name:t,passed:!1,severity:"error",remediation:`${o} critical security finding(s) across units: ${s}. Resolve all critical findings before Gate 5 approval.`}}return{name:t,passed:!0,severity:"info"}}function cP(e){let t="test-report-exists",n=[mt.join(e,"construction","build-and-test","test-report.md"),mt.join(e,"construction","build-and-test","report.md"),mt.join(e,"construction","build-and-test","validation-report.md")];for(let r of n)if(ho.existsSync(r))return{name:t,passed:!0,severity:"info"};return{name:t,passed:!1,severity:"warning",remediation:"No test report found in build-and-test directory. Generate a test report before Gate 5 approval."}}function $w(e,t){return[ft("all-units-complete",()=>sP(e)),ft("smoke-test-passed",()=>iP(e)),ft("security-report-clean",()=>aP(e)),ft("test-report-exists",()=>cP(t))]}Mt();var zs=v(X(),1),Ie=require("path"),Tr=require("fs");function ml(e){if(!e)return"";let t=e.filter(r=>!r.passed);return t.length===0?"":`
|
|
2091
2091
|
|
|
2092
2092
|
**Content Check Failures:**
|
|
2093
2093
|
${t.map(r=>`- ${r.name}: ${r.remediation??"No remediation provided."}`).join(`
|
|
2094
|
-
`)}`}var
|
|
2094
|
+
`)}`}var Er={inception:[{question:"Does the INTENT address all stated constraints?",answer:null,answered_by:null,passed:null},{question:"Does the INTENT solve the actual business problem?",answer:null,answered_by:null,passed:null},{question:"Are NFRs properly derived from INTENT constraints?",answer:null,answered_by:null,passed:null}],construction:[{question:"Do UNITS cover all INTENT acceptance criteria?",answer:null,answered_by:null,passed:null},{question:"Does DESIGN address all UNIT requirements?",answer:null,answered_by:null,passed:null},{question:"Does BUILD satisfy DESIGN contracts?",answer:null,answered_by:null,passed:null}],operations:[{question:"Does the deployment guide cover all components?",answer:null,answered_by:null,passed:null},{question:"Does the monitoring config capture key metrics?",answer:null,answered_by:null,passed:null}],gate3:[{question:"Do UNITs cover all INTENT acceptance criteria?",answer:null,answered_by:null,passed:null},{question:"Is the decomposition granularity appropriate?",answer:null,answered_by:null,passed:null}],gate4:[{question:"Does the BOLT implementation satisfy its acceptance criteria?",answer:null,answered_by:null,passed:null},{question:"Are all tests passing?",answer:null,answered_by:null,passed:null}]};async function Js(e){try{let t=await oe(e);if(t.length===0)return null;let n=null;for(let r of t){let o=await A(e,r);if(!o||o.status==="complete")continue;let s=o.manifest_path||(0,Ie.join)(e,".olympus","workflow",r,"manifest.json");(!n||o.updated_at>n.updatedAt)&&(n={workflowId:r,checkpoint:o,manifestPath:s,updatedAt:o.updated_at})}return n?{workflowId:n.workflowId,checkpoint:n.checkpoint,manifestPath:n.manifestPath}:null}catch(t){return console.error("[Olympus Quality Gate] Failed to find active workflow:",t),null}}function lP(e,t){let n=e.current_phase;if(!n)return e.current_stage==="intent"||e.current_stage==="complete"?"inception":null;if(t){let r=t.phases[n];if(r&&r.status==="in_progress"&&(!r.gate_result||r.gate_result&&!r.gate_result.passed&&r.gate_result.approved_by===null))return r.gate_result&&r.gate_result.approved_by===null?null:n}return n==="inception"&&(e.current_stage==="intent"||e.current_stage==="complete")?"inception":n==="construction"&&e.current_stage==="unit"||n==="construction"&&e.current_stage==="code-generation"&&e.active_code_plan_path?"construction":n==="operations"?"operations":null}function uP(e){try{let t=(0,Ie.join)(e,".olympus","config.json");if(zs.existsSync(t)){let n=zs.readJsonSync(t);if(n?.workflow?.qualityGates?.enabled===!1||n?.hooks?.qualityGate?.enabled===!1)return!0}}catch{}return!1}function gl(e){for(let t of["discovery","inception","construction","operations"]){let n=e.phases[t];if(n.gate_result&&!n.gate_result.passed&&n.gate_result.approved_by===null)return t}return null}function dP(e,t){return e==="inception"?t==="intent"?2:1:e==="construction"?t==="code-generation"?4:3:e==="operations"?5:1}function pP(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 fP(e){try{if(e.toolName!=="Task")return{continue:!0};if(!e.directory||!e.sessionId)return{continue:!0};let t=await Js(e.directory);if(!t)return{continue:!0};let{workflowId:n,checkpoint:r,manifestPath:o}=t,s=W(o);if(!s)return console.error("[Olympus Quality Gate] Manifest corrupted or missing - failing open"),{continue:!0};let i=lP(r,s);if(!i)return{continue:!0};let a=be(e.directory),c=(typeof r.risk_tier=="number"?r.risk_tier:r.risk_tier?.tier)||s.risk_tier?.tier||2;if(c===3&&i==="inception"&&!s.artifacts.some(_=>_.type?.toLowerCase().includes("momus")||_.type?.toLowerCase()==="momus-review"))return s.phases[i].gate_result={passed:!1,approved_by:null,approved_at:null,feedback:"Momus review required for Risk Tier 3",verification:{conformance_score:0,coverage_percentage:0,missing_items:["Momus review artifact missing"],passed:!1},validation:{alignment_score:0,alignment_questions:[],passed:!1}},G(o,s),await P(e.directory,r),{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`[BLOCKING - Acknowledgment Required] BLOCKED: Risk Tier 3 requires Momus review before INTENT approval. Run /review to invoke Momus.
|
|
2095
2095
|
|
|
2096
|
-
[GATE_PENDING]`}};if(i==="construction"&&r.current_stage==="unit"){if(
|
|
2096
|
+
[GATE_PENDING]`}};if(i==="construction"&&r.current_stage==="unit"){if(al(a.current_level,c)==="auto-advance"&&c!==3){De(o,{phase:"construction",action:"approved",actor:"trust",reason:`Gate 3 auto-advanced by Trust Level ${a.current_level} for Tier ${c}`});let R=new Date().toISOString();s.phases.construction.gate_result={passed:!0,approved_by:"trust",approved_at:R,feedback:null,verification:{conformance_score:100,coverage_percentage:100,missing_items:[],passed:!0},validation:{alignment_score:100,alignment_questions:[],passed:!0}};for(let O of s.artifacts)O.stage==="unit"&&(O.reviewedBy="auto-approved");G(o,s),await P(e.directory,r);try{let O={type:"gate_approval",phase:"construction",stage:"unit",details:`Gate 3 auto-advanced by Trust Level ${a.current_level} for Tier ${c}`},C={workflowId:n,featureName:r.feature_name||n,projectPath:e.directory,sessionId:e.sessionId||"unknown",phase:"construction"},$=He(O,C);ue($)}catch(O){console.error("[Olympus Quality Gate] Failed to capture Gate 3 auto-advance discovery:",O)}return{continue:!0}}let _;try{let R=(0,Ie.join)(e.directory,"aidlc-docs",n,"inception"),O=(0,Tr.readFileSync)((0,Ie.join)(R,"intent.md"),"utf-8"),C=s.artifacts.filter(x=>x.stage==="unit"),$=C.length>0?(0,Tr.readFileSync)((0,Ie.join)(e.directory,C[0].path),"utf-8"):"",D=Jn($,O,O,"intent-to-unit","unit-to-intent","intent",C[0]?.id||"unit","intent");_={conformance_score:D.parentCheck.verification.conformance_score,coverage_percentage:D.parentCheck.verification.coverage_percentage,missing_items:D.parentCheck.verification.missing_items,passed:D.passed}}catch{_={conformance_score:0,coverage_percentage:0,missing_items:["Could not read construction artifacts for alignment check"],passed:!1}}let h=Er.gate3||[],b={alignment_score:0,alignment_questions:h,passed:!1},T=xw(s,a.current_level).map(R=>R.reviewContent).join(`
|
|
2097
2097
|
|
|
2098
|
-
`);return s.phases.construction.gate_result={passed:!1,approved_by:null,approved_at:null,feedback:null,verification:_,validation:b},
|
|
2098
|
+
`);return s.phases.construction.gate_result={passed:!1,approved_by:null,approved_at:null,feedback:null,verification:_,validation:b},De(o,{phase:"construction",action:"approved",actor:"trust",reason:"Gate 3 pending review"}),G(o,s),await P(e.directory,r),{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`${c===3?"[BLOCKING - Acknowledgment Required] ":""}STOP: Gate 3 (UNIT decomposition review) requires approval.
|
|
2099
2099
|
|
|
2100
2100
|
${T}
|
|
2101
2101
|
|
|
@@ -2108,7 +2108,7 @@ ${h.map((R,O)=>`${O+1}. ${R.question}`).join(`
|
|
|
2108
2108
|
|
|
2109
2109
|
Type "approve" to proceed or "reject <reason>" to block.
|
|
2110
2110
|
|
|
2111
|
-
[GATE_PENDING]`}}}if(i==="construction"&&r.current_stage==="code-generation"&&r.active_code_plan_path){let w=r.active_code_plan_path,_=
|
|
2111
|
+
[GATE_PENDING]`}}}if(i==="construction"&&r.current_stage==="code-generation"&&r.active_code_plan_path){let w=r.active_code_plan_path,_=cl(a.current_level,c),h;try{let C=(0,Ie.join)(e.directory,"aidlc-docs",n,"inception"),$=(0,Tr.readFileSync)((0,Ie.join)(C,"intent.md"),"utf-8"),D=s.artifacts.find(L=>L.id===w),x=D?(0,Tr.readFileSync)((0,Ie.join)(e.directory,D.path),"utf-8"):"",E=Jn(x,$,$,"unit-to-bolt","bolt-to-intent","intent",w,"intent");h={conformance_score:E.parentCheck.verification.conformance_score,coverage_percentage:E.parentCheck.verification.coverage_percentage,missing_items:E.parentCheck.verification.missing_items,passed:E.passed}}catch{h={conformance_score:0,coverage_percentage:0,missing_items:["Could not read BOLT artifacts for alignment check"],passed:!1}}let b=Er.gate4||[],S={alignment_score:0,alignment_questions:b,passed:!1};if(_==="notification-only"&&c!==3){De(o,{phase:"construction",action:"approved",actor:"trust",reason:`Gate 4 notification-only for BOLT ${w} at Trust Level ${a.current_level}`});let $={passed:!0,approved_by:"trust",approved_at:new Date().toISOString(),feedback:null,verification:h,validation:S};try{let E=r.construction_units?.[w];if(E){let L=fl(E,(0,Ie.join)(e.directory,"aidlc-docs",n));$.content_checks=L,L.some(j=>!j.passed&&j.severity==="error")&&($.passed=!1)}}catch(E){console.error("[quality-gate] Gate 4 content check error:",E)}s.phases.construction.gate_result=$;let D=s.artifacts.find(E=>E.id===w);D&&(D.reviewedBy="auto-approved"),St(o,w,"fulfilled");try{let E=ll(s,w);if(E&&e.directory){let L=dl(e.directory,n,E);ul(L,E,{boltId:w,boltTitle:D?.type||"auto-approved",commandsExecuted:[],testResults:[],filesChanged:[],gateApprovedBy:"auto-approved",dualValidation:{parentConformance:h.conformance_score,rootConformance:0},riskTier:c})}}catch(E){console.error("[Olympus Quality Gate] Failed to generate validation report:",E)}G(o,s),await P(e.directory,r);try{let E={type:"gate_approval",phase:"construction",stage:"code-generation",details:`Gate 4 notification-only for BOLT ${w} at Trust Level ${a.current_level}`,artifactId:w},L={workflowId:n,featureName:r.feature_name||n,projectPath:e.directory,sessionId:e.sessionId||"unknown",phase:"construction"},j=He(E,L);ue(j)}catch(E){console.error("[Olympus Quality Gate] Failed to capture Gate 4 auto-advance discovery:",E)}let x="";try{let{isWorkflowComplete:E}=await Promise.resolve().then(()=>(Z(),kn)),L=W(o);L&&E(L)&&(r.current_phase="operations",r.current_stage="code-generation",Nt(o,"construction","complete"),Nt(o,"operations","in_progress"),await P(e.directory,r),x=" All BOLTs fulfilled \u2014 auto-transitioning to Operations phase.",console.log("[Olympus Quality Gate] All BOLTs fulfilled \u2014 auto-transitioning to Operations phase"))}catch(E){console.error("[Olympus Quality Gate] Failed to check workflow completion:",E)}return{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`Gate 4 (BOLT ${w} review): Auto-approved at Trust Level ${a.current_level}. Notification only.${x}`}}}let T;try{T=Pw(s,w,a.current_level,c)}catch{return{continue:!0}}let k={passed:!1,approved_by:null,approved_at:null,feedback:null,verification:h,validation:S};try{let C=r.construction_units?.[w];if(C){let $=fl(C,(0,Ie.join)(e.directory,"aidlc-docs",n));k.content_checks=$,$.some(D=>!D.passed&&D.severity==="error")&&(k.passed=!1)}}catch(C){console.error("[quality-gate] Gate 4 content check error:",C)}return s.phases.construction.gate_result=k,De(o,{phase:"construction",action:"approved",actor:"trust",reason:`Gate 4 pending review for BOLT ${w}`,content_checks:k.content_checks}),G(o,s),await P(e.directory,r),{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`${c===3?"[BLOCKING - Acknowledgment Required] ":""}STOP: Gate 4 (BOLT ${w} review)${_==="summary-review"?" (Summary Review)":""} requires approval.
|
|
2112
2112
|
|
|
2113
2113
|
${T.reviewContent}
|
|
2114
2114
|
|
|
@@ -2119,9 +2119,9 @@ VALIDATION: Review alignment questions:
|
|
|
2119
2119
|
${b.map((C,$)=>`${$+1}. ${C.question}`).join(`
|
|
2120
2120
|
`)}
|
|
2121
2121
|
|
|
2122
|
-
Type "approve" to proceed or "reject <reason>" to block.${
|
|
2122
|
+
Type "approve" to proceed or "reject <reason>" to block.${ml(k.content_checks)}
|
|
2123
2123
|
|
|
2124
|
-
[GATE_PENDING]`}}}if(i==="operations"){let w;try{w=
|
|
2124
|
+
[GATE_PENDING]`}}}if(i==="operations"){let w;try{w=Aw(s,a.current_level)}catch{return{continue:!0}}let _=Er.operations||[],S={passed:!1,approved_by:null,approved_at:null,feedback:null,verification:{conformance_score:0,coverage_percentage:0,missing_items:["Release review pending"],passed:!1},validation:{alignment_score:0,alignment_questions:_,passed:!1}};try{let k=$w(r,(0,Ie.join)(e.directory,"aidlc-docs",n));S.content_checks=k,k.some(F=>!F.passed&&F.severity==="error")&&(S.passed=!1)}catch(k){console.error("[quality-gate] Gate 5 content check error:",k)}return s.phases.operations.gate_result=S,G(o,s),await P(e.directory,r),{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`[BLOCKING - Acknowledgment Required] STOP: Gate 5 (Release review) requires approval.
|
|
2125
2125
|
|
|
2126
2126
|
${w.reviewContent}
|
|
2127
2127
|
|
|
@@ -2129,11 +2129,11 @@ VALIDATION: Review alignment questions:
|
|
|
2129
2129
|
${_.map((k,F)=>`${F+1}. ${k.question}`).join(`
|
|
2130
2130
|
`)}
|
|
2131
2131
|
|
|
2132
|
-
Type "approve" to proceed or "reject <reason>" to block.${
|
|
2132
|
+
Type "approve" to proceed or "reject <reason>" to block.${ml(S.content_checks)}
|
|
2133
2133
|
|
|
2134
|
-
[GATE_PENDING]`}}}if(
|
|
2134
|
+
[GATE_PENDING]`}}}if(ff(c,a.current_level)){De(o,{phase:i,action:"approved",actor:"trust",reason:`Auto-advanced by Trust Level ${a.current_level} for Tier ${c}`});let w=new Date().toISOString();s.phases[i].gate_result={passed:!0,approved_by:"trust",approved_at:w,feedback:null,verification:{conformance_score:100,coverage_percentage:100,missing_items:[],passed:!0},validation:{alignment_score:100,alignment_questions:[],passed:!0}},G(o,s),await P(e.directory,r);try{let _={type:"gate_approval",phase:i,stage:r.current_stage,details:`Auto-advanced by Trust Level ${a.current_level} for Tier ${c}`},h={workflowId:n,featureName:r.feature_name||n,projectPath:e.directory,sessionId:e.sessionId||"unknown",phase:i},b=He(_,h);ue(b)}catch(_){console.error("[Olympus Quality Gate] Failed to capture auto-advance discovery:",_)}return{continue:!0}}let l,u;if(i==="inception")try{let w=(0,Ie.join)(e.directory,"aidlc-docs",n,"inception"),_=(0,Tr.readFileSync)((0,Ie.join)(w,"intent.md"),"utf-8");l=Fo(_,_,"intent-to-unit"),u=Er[i]||[]}catch{l={conformance_score:0,coverage_percentage:0,missing_items:["Could not read inception artifacts for alignment check"],passed:!1},u=Er[i]||[]}else l={conformance_score:0,coverage_percentage:0,missing_items:["Alignment check not yet implemented for this phase"],passed:!1},u=Er[i]||[];let d={alignment_score:0,alignment_questions:u,passed:!1},p="";if(i==="inception"){let w=r.depth_score||s.depth_assessment?.total_score;w&&w>=21&&(s.artifacts.some(h=>h.type?.toLowerCase().includes("metis"))||(p=`
|
|
2135
2135
|
|
|
2136
|
-
WARNING: DEEP workflow without Metis consultation detected. Metis blind-spot analysis is strongly recommended for complex workflows.`))}let f={passed:!1,approved_by:null,approved_at:null,feedback:null,verification:l,validation:d};try{let w=(0,
|
|
2136
|
+
WARNING: DEEP workflow without Metis consultation detected. Metis blind-spot analysis is strongly recommended for complex workflows.`))}let f={passed:!1,approved_by:null,approved_at:null,feedback:null,verification:l,validation:d};try{let w=(0,Ie.join)(e.directory,"aidlc-docs",n),_=Ow(w);f.content_checks=_,_.some(h=>!h.passed&&h.severity==="error")&&(f.passed=!1)}catch(w){console.error("[quality-gate] Gate 1 content check error:",w)}s.phases[i].gate_result=f,G(o,s),await P(e.directory,r);let m=c===3?"[BLOCKING - Acknowledgment Required] ":"",g=r.current_stage==="intent"?"Gate 1 (INTENT review)":r.current_stage==="complete"?"Gate 2 (INTENT review)":`${i} transition`;return{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`${m}STOP: ${g} requires approval.
|
|
2137
2137
|
|
|
2138
2138
|
VERIFICATION: ${l.conformance_score}% conformance, ${l.coverage_percentage}% coverage.
|
|
2139
2139
|
Missing: ${l.missing_items.join(", ")}
|
|
@@ -2142,13 +2142,13 @@ VALIDATION: Review alignment questions:
|
|
|
2142
2142
|
${u.map((w,_)=>`${_+1}. ${w.question}`).join(`
|
|
2143
2143
|
`)}
|
|
2144
2144
|
|
|
2145
|
-
Type "approve" to proceed or "reject <reason>" to block.${p}${
|
|
2145
|
+
Type "approve" to proceed or "reject <reason>" to block.${p}${ml(f.content_checks)}
|
|
2146
2146
|
|
|
2147
|
-
[GATE_PENDING]`}}}catch(t){return console.error("[Olympus Quality Gate] Error in qualityGateBlocker:",t),{continue:!0}}}async function
|
|
2147
|
+
[GATE_PENDING]`}}}catch(t){return console.error("[Olympus Quality Gate] Error in qualityGateBlocker:",t),{continue:!0}}}async function mP(e){try{let t=pP(e);if(!e.directory)return{continue:!0};if(t.includes("--no-gates")||uP(e.directory)){let n=await Js(e.directory);if(n){let{manifestPath:r}=n,o=W(r);if(o){let s=gl(o);if(s){let i=t.includes("--no-gates")?"flag":"config";De(r,{phase:s,action:"bypassed",actor:i,reason:i==="flag"?"--no-gates flag detected":"Quality gates disabled in config"}),o.phases[s].gate_result=null,o.phases[s].gate_bypassed=!0,o.phases[s].bypass_reason=i==="flag"?"--no-gates flag":"Config disabled",G(r,o),await P(e.directory,n.checkpoint)}}}return{continue:!0}}if(t.trim().toLowerCase().startsWith("approve")){let n=await Js(e.directory);if(!n)return{continue:!0};let{manifestPath:r}=n,o=W(r);if(!o)return{continue:!0};let s=gl(o);if(!s)return{continue:!0};let i=new Date().toISOString();o.phases[s].gate_result&&(o.phases[s].gate_result.passed=!0,o.phases[s].gate_result.approved_by="human",o.phases[s].gate_result.approved_at=i);let{checkpoint:a}=n;if(s==="construction"){if(a.current_stage==="code-generation"&&a.active_code_plan_path){let p=a.active_code_plan_path;St(r,p,"fulfilled");let f=o.artifacts.find(m=>m.id===p);f&&(f.reviewedBy="human");try{let m=ll(o,p);if(m){let g=dl(e.directory,n.workflowId,m),y=(typeof a.risk_tier=="number"?a.risk_tier:a.risk_tier?.tier)||o.risk_tier?.tier||2;ul(g,m,{boltId:p,boltTitle:f?.type||p,commandsExecuted:[],testResults:[],filesChanged:[],gateApprovedBy:"human",dualValidation:{parentConformance:o.phases.construction.gate_result?.verification?.conformance_score??0,rootConformance:0},riskTier:y})}}catch(m){console.error("[Olympus Quality Gate] Failed to generate validation report:",m)}try{let{isWorkflowComplete:m}=await Promise.resolve().then(()=>(Z(),kn)),g=W(r);g&&m(g)&&(a.current_phase="operations",a.current_stage="code-generation",Nt(r,"construction","complete"),Nt(r,"operations","in_progress"),await P(e.directory,a),console.log("[Olympus Quality Gate] All BOLTs fulfilled \u2014 auto-transitioning to Operations phase"))}catch(m){console.error("[Olympus Quality Gate] Failed to check workflow completion:",m)}}else if(a.current_stage==="unit"){let p=o.artifacts.filter(f=>f.stage==="unit");for(let f of p)St(r,f.id,"active"),f.reviewedBy="human"}}else{let p=o.artifacts.filter(f=>f.phase===s);for(let f of p)St(r,f.id,"active")}De(r,{phase:s,action:"approved",actor:"human",reason:null,content_checks:o.phases[s].gate_result?.content_checks});try{let p={type:"gate_approval",phase:s,stage:a.current_stage,details:`Gate approved for ${s} phase`},f={workflowId:n.workflowId,featureName:a.feature_name||n.workflowId,projectPath:e.directory,sessionId:e.sessionId||"unknown",phase:s},m=He(p,f);ue(m)}catch(p){console.error("[Olympus Quality Gate] Failed to capture gate approval discovery:",p)}let c=be(e.directory),l=fa(c,!0,!1);pa(l,e.directory),G(r,o),await P(e.directory,n.checkpoint),o.phases[s].gate_result?.passed&&(o.phases[s].gate_result=null,G(r,o));let u="",d=n.checkpoint.depth_score;return d&&d<=10?u=" SHALLOW depth: Skip UNIT decomposition, proceed directly to single BOLT generation.":d&&d>=21&&(u=" DEEP depth: Full UNIT + BOLT decomposition with design artifacts required."),{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:`Gate approved. Phase ${s} transition approved. Proceeding to next phase.${u}`}}}if(t.trim().toLowerCase().startsWith("reject")){let n=await Js(e.directory);if(!n)return{continue:!0};let{manifestPath:r}=n,o=W(r);if(!o)return{continue:!0};let s=gl(o);if(!s)return{continue:!0};let i=t.trim().substring(6).trim()||"No reason provided";o.phases[s].gate_result&&(o.phases[s].gate_result.passed=!1,o.phases[s].gate_result.feedback=i);let{checkpoint:a}=n,c="";if(s==="construction")if(a.current_stage==="code-generation"&&a.active_code_plan_path){let g=a.active_code_plan_path;St(r,g,"violated",i),c=`The reviewer rejected ${g}: ${i}. Revise and re-submit.`}else if(a.current_stage==="unit"){let g=o.artifacts.filter(y=>y.stage==="unit");for(let y of g)St(r,y.id,"violated",i);c=`The reviewer rejected UNIT decomposition: ${i}. Revise and re-submit.`}else{let g=o.artifacts.filter(y=>y.phase===s);for(let y of g)St(r,y.id,"violated",i)}else{let g=o.artifacts.filter(y=>y.phase===s);for(let y of g)St(r,y.id,"violated",i)}De(r,{phase:s,action:"rejected",actor:"human",reason:i,content_checks:o.phases[s].gate_result?.content_checks});try{let g={type:"gate_rejection",phase:s,stage:a.current_stage,details:i},y={workflowId:n.workflowId,featureName:a.feature_name||n.workflowId,projectPath:e.directory,sessionId:e.sessionId||"unknown",phase:s},w=He(g,y);ue(w)}catch(g){console.error("[Olympus Quality Gate] Failed to capture gate rejection discovery:",g)}let l=be(e.directory),u=fa(l,!1,!0);pa(u,e.directory),G(r,o),await P(e.directory,n.checkpoint);let d=dP(s,a.current_stage),p=s==="construction"&&a.current_stage==="code-generation"&&a.active_code_plan_path?a.active_code_plan_path:o.artifacts.find(g=>g.phase===s)?.id??`${s}-artifact`,f=o.gate_audit.filter(g=>g.phase===s&&g.action==="rejected").length,m;try{let g=await Iw(e.directory,o.workflow_id,{gateNumber:d,artifactId:p,rejectionReason:i,rejectedBy:"human",attemptNumber:f+1});m=`Gate ${d} rejected ${p}: ${i}.
|
|
2148
2148
|
|
|
2149
|
-
${g.prompt}`}catch{m=c||`Gate rejected. Reason: ${i}. Revise artifacts before retrying.`}return{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:m}}}return{continue:!0}}catch(t){return console.error("[Olympus Quality Gate] Error in qualityGateApprover:",t),{continue:!0}}}function
|
|
2150
|
-
`)[0];if(s)return s}catch{}return null}function
|
|
2151
|
-
... (truncated)`:
|
|
2149
|
+
${g.prompt}`}catch{m=c||`Gate rejected. Reason: ${i}. Revise artifacts before retrying.`}return{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:m}}}return{continue:!0}}catch(t){return console.error("[Olympus Quality Gate] Error in qualityGateApprover:",t),{continue:!0}}}function Dw(){I({name:"qualityGateBlocker",event:"PostToolUse",priority:80,matcher:"task",handler:fP}),I({name:"qualityGateApprover",event:"UserPromptSubmit",priority:12,handler:mP})}var gP=["explore","explore-medium","librarian","librarian-low","oracle","oracle-low","oracle-medium","momus","metis","multimodal-looker"];function Nw(e){return gP.includes(e)}var jw=/(?:^|\s|&&|\|\||;)(?:>|>>|rm\s|mv\s|cp\s|mkdir\s|rmdir\s|touch\s|npm\s+install|pip\s+install|cargo\s+add|tee\s|dd\s|install\s|sed\s+-i|awk\s+-i|chmod\s|chown\s)/,Qs={debounceMs:1e4,mode:"soft",enabled:!0};Ue();function Fw(){I({name:"agentRoleGuard",event:"PreToolUse",priority:5,matcher:"write|edit|multiedit|bash",handler:async e=>{try{if(!e.directory||!e.sessionId)return{continue:!0};let n=Q(e.directory,e.sessionId).pending_completion?.agent_used;if(!n)return{continue:!0};if(!Nw(n))return{continue:!0};let r=e.toolName;if(r==="write"||r==="edit"||r==="multiedit")return{continue:!1,stopReason:`Agent "${n}" is read-only and cannot perform ${r} operations. Use an agent like "olympian" or "frontend-engineer" for file modifications.`};if(r==="bash"){let s=e.toolInput?.command;if(typeof s=="string"&&jw.test(s))return{continue:!1,stopReason:`Agent "${n}" is read-only and cannot execute bash commands that modify files. Detected write operation in: ${s.substring(0,100)}${s.length>100?"...":""}`}}return{continue:!0}}catch(t){return console.error("[Olympus Agent Role Guard] Error in handler:",t),{continue:!0}}}})}var Xs=require("child_process"),Zs=require("path"),Cr=require("fs"),Mw=0,pn=null,fn=null;function Lw(e){let t=(0,Zs.join)(e,".olympus","config.json"),n={enabled:Qs.enabled,mode:Qs.mode,debounceMs:Qs.debounceMs};try{if((0,Cr.existsSync)(t)){let r=(0,Cr.readFileSync)(t,"utf8"),o=JSON.parse(r);if(o.hooks?.buildCheck){let s=o.hooks.buildCheck;typeof s.enabled=="boolean"&&(n.enabled=s.enabled),(s.mode==="soft"||s.mode==="strict")&&(n.mode=s.mode),typeof s.debounceMs=="number"&&s.debounceMs>0&&(n.debounceMs=s.debounceMs)}}}catch(r){console.error("[Olympus Build Check] Failed to load config:",r)}return n}function hP(e){let t=(0,Zs.join)(e,"node_modules",".bin","tsc"),n=process.platform==="win32"?`${t}.cmd`:t;if((0,Cr.existsSync)(n))return n;try{let r=process.platform==="win32"?"where":"which",s=require("child_process").execSync(`${r} tsc`,{encoding:"utf8"}).trim().split(`
|
|
2150
|
+
`)[0];if(s)return s}catch{}return null}function yP(){if(!fn||!fn.pid)return;let e=fn.pid;try{fn.kill("SIGTERM")}catch{if(process.platform==="win32")try{(0,Xs.exec)(`taskkill /PID ${e} /F`,n=>{n&&console.error("[Olympus Build Check] Failed to kill process with taskkill:",n)})}catch{}}fn=null}function Uw(){I({name:"buildCheckTrigger",event:"PostToolUse",priority:65,matcher:/write|edit|multiedit/i,handler:async e=>{try{if(!e.directory)return{continue:!0};let t=Lw(e.directory);if(!t.enabled)return{continue:!0};let n=Date.now();if(n-Mw<t.debounceMs)return{continue:!0};let r=(0,Zs.join)(e.directory,"tsconfig.json");if(!(0,Cr.existsSync)(r))return{continue:!0};let o=hP(e.directory);if(!o)return{continue:!0};yP();try{let s=(0,Xs.spawn)(o,["--noEmit"],{cwd:e.directory,detached:!0,stdio:"pipe"});fn=s,Mw=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();pn={passed:c===0,output:l,timestamp:Date.now()},fn=null}),s.on("error",c=>{console.error("[Olympus Build Check] tsc spawn error:",c),fn=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}}}),I({name:"buildCheckInjector",event:"PostToolUse",priority:66,handler:async e=>{try{if(!pn)return{continue:!0};let t=e.directory?Lw(e.directory):{mode:"soft"};if(pn.passed)return pn=null,{continue:!0};let n=pn.output.length>500?pn.output.substring(0,500)+`
|
|
2151
|
+
... (truncated)`:pn.output,r=t.mode==="strict"?`[BUILD CHECK FAILED - BLOCKING]
|
|
2152
2152
|
|
|
2153
2153
|
TypeScript compilation failed:
|
|
2154
2154
|
|
|
@@ -2160,16 +2160,16 @@ TypeScript compilation failed:
|
|
|
2160
2160
|
|
|
2161
2161
|
${n}
|
|
2162
2162
|
|
|
2163
|
-
Consider fixing these errors.`;return
|
|
2163
|
+
Consider fixing these errors.`;return pn=null,t.mode==="strict"?{continue:!1,stopReason:"Build check failed (strict mode)",hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:r}}:{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:r}}}catch(t){console.error("[Olympus Build Check] Error in buildCheckInjector:",t)}return{continue:!0}}})}Ue();ce();Z();var Rr=require("path"),xr=require("fs"),wP={prometheus:"inception"};async function _P(e){try{let t=await oe(e);if(t.length===0)return null;let n=null;for(let r of t){let o=await A(e,r);!o||o.status==="complete"||(!n||o.updated_at>n.updatedAt)&&(n={workflowId:r,checkpoint:o,updatedAt:o.updated_at})}return n?{workflowId:n.workflowId,checkpoint:n.checkpoint}:null}catch(t){return console.error("[Olympus Artifact Gate] Failed to find active workflow:",t),null}}function kP(e,t){let n=(0,Rr.join)(e,"inception"),r=e;switch(t){case"intent":{let o=(0,Rr.join)(n,"intent.md"),s=(0,Rr.join)(r,"intent.md"),i=(0,xr.existsSync)(o)?o:s;return(0,xr.existsSync)(i)?{artifactPath:i,referencePaths:[]}:null}default:return null}}async function SP(e,t,n){try{switch(e){case"intent":return await Uo(t);default:return null}}catch(r){return console.error(`[Olympus Artifact Gate] Validation error for ${e}:`,r),null}}function vP(e,t){let n=e.toUpperCase();if(t.passed)return`[Artifact Validation] ${n} validation PASSED (${t.coverage_percentage}% coverage). Good work!`;let r=t.blocking_issues.map((o,s)=>` ${s+1}. ${o}`).join(`
|
|
2164
2164
|
`);return`[Artifact Validation] WARNING: ${n} validation FAILED (${t.coverage_percentage}% coverage)
|
|
2165
2165
|
|
|
2166
2166
|
Blocking issues:
|
|
2167
2167
|
${r}
|
|
2168
2168
|
|
|
2169
2169
|
${t.reviewer?`Reviewer: ${t.reviewer}
|
|
2170
|
-
`:""}Please review and address these issues before proceeding to the next stage.`}async function
|
|
2170
|
+
`:""}Please review and address these issues before proceeding to the next stage.`}async function bP(e){try{if(e.toolName!=="Task")return{continue:!0};if(!e.directory||!e.sessionId)return{continue:!0};let n=Q(e.directory,e.sessionId).pending_completion?.agent_used;if(!n)return{continue:!0};if(!wP[n])return{continue:!0};let o=await _P(e.directory);if(!o)return{continue:!0};let{workflowId:s,checkpoint:i}=o,a="intent",c=(0,Rr.join)(e.directory,"aidlc-docs",s);if(!(0,xr.existsSync)(c))return console.error("[Olympus Artifact Gate] Workflow directory not found:",c),{continue:!0};let l=kP(c,a);if(!l)return console.error(`[Olympus Artifact Gate] Could not find artifact paths for ${a} in ${c}`),{continue:!0};let u=await SP(a,l.artifactPath,l.referencePaths);if(!u)return console.error(`[Olympus Artifact Gate] Validation failed to run for ${a}`),{continue:!0};let d=vP(a,u);if(a==="intent"&&u.passed)try{let p=(0,xr.readFileSync)(l.artifactPath,"utf-8"),f=hs(p),m=i.manifest_path||(0,Rr.join)(e.directory,"aidlc-docs",s,"manifest.json"),g=W(m);g&&(g.depth_assessment=f,g.risk_tier=f.risk_tier,G(m,g)),i.depth_score=f.total_score,i.risk_tier=f.risk_tier.tier,await P(e.directory,i);let y=f.recommended_depth==="minimal"?"SHALLOW":f.recommended_depth==="standard"?"MEDIUM":"DEEP";d+=`
|
|
2171
2171
|
|
|
2172
|
-
[Depth Assessment] Score: ${f.total_score}/30 \u2192 ${y} | Risk Tier: ${f.risk_tier.tier}`}catch(p){console.error("[Olympus Artifact Gate] Failed to assess depth after INTENT validation:",p)}return{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:d}}}catch(t){return console.error("[Olympus Artifact Gate] Error in workflowArtifactGateHandler:",t),{continue:!0}}}function
|
|
2172
|
+
[Depth Assessment] Score: ${f.total_score}/30 \u2192 ${y} | Risk Tier: ${f.risk_tier.tier}`}catch(p){console.error("[Olympus Artifact Gate] Failed to assess depth after INTENT validation:",p)}return{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:d}}}catch(t){return console.error("[Olympus Artifact Gate] Error in workflowArtifactGateHandler:",t),{continue:!0}}}function Ww(){I({name:"workflowArtifactGate",event:"PostToolUse",priority:78,matcher:"task",handler:bP})}ce();Z();var Fn=v(X(),1),ei=require("path"),Bw=require("child_process");function Gw(e){let t=(0,ei.join)(e,".olympus","config.json");try{if(Fn.existsSync(t)){let n=Fn.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 EP()}function EP(){return{staticQuality:{enabled:!0},security:{enabled:!0,auditLevel:"moderate"},complexity:{enabled:!0,agent:"oracle-low"},customChecks:[]}}function TP(e){let t=[];try{let n=(0,ei.join)(e,"package.json");if(Fn.existsSync(n)){let o=Fn.readJsonSync(n)?.scripts||{};o.lint&&t.push("npm run lint"),o.typecheck&&t.push("npm run typecheck"),o.test&&t.push("npm test"),!o.typecheck&&Fn.existsSync((0,ei.join)(e,"tsconfig.json"))&&t.push("npx tsc --noEmit")}}catch{}return t}function hl(e,t,n,r){let o=Date.now();try{let s=(0,Bw.execSync)(e,{cwd:t,timeout:12e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return{name:n,layer:r,passed:!0,command:e,exitCode:0,stdout:(s||"").substring(0,2e3),stderr:"",duration_ms:Date.now()-o}}catch(s){return{name:n,layer:r,passed:!1,command:e,exitCode:s.status||1,stdout:(s.stdout||"").substring(0,2e3),stderr:(s.stderr||"").substring(0,2e3),duration_ms:Date.now()-o}}}function Hw(e,t){let n=[],r=Date.now();if(t.staticQuality.enabled){let s=t.staticQuality.commands||TP(e);for(let i of s)n.push(hl(i,e,`Static: ${i}`,"static-quality"))}if(t.security.enabled){let s=t.security.auditLevel||"moderate";n.push(hl(`npm audit --audit-level=${s}`,e,"Security: npm audit","security"))}if(t.complexity.enabled&&n.push({name:"Complexity: AI review",layer:"complexity",passed:!0,command:`dispatch ${t.complexity.agent||"oracle-low"}`,exitCode:0,stdout:"AI complexity review dispatched",stderr:"",duration_ms:0}),t.customChecks)for(let s of t.customChecks)n.push(hl(s.command,e,`Custom: ${s.name}`,"custom"));let o=n.filter(s=>!s.passed).map(s=>s.name);return{allPassed:o.length===0,results:n,totalDuration_ms:Date.now()-r,failedChecks:o}}function qw(e){let t=e.allPassed?"CI Review Pipeline: ALL CHECKS PASSED":`CI Review Pipeline: ${e.failedChecks.length} CHECK(S) FAILED`,n=e.results.map(r=>{let s=`[${r.passed?"PASS":"FAIL"}] ${r.name}`;return r.passed||(s+=`
|
|
2173
2173
|
Command: ${r.command}`,s+=`
|
|
2174
2174
|
Exit code: ${r.exitCode}`,r.stderr&&(s+=`
|
|
2175
2175
|
Error: ${r.stderr.substring(0,500)}`)),s}).join(`
|
|
@@ -2177,7 +2177,7 @@ ${t.reviewer?`Reviewer: ${t.reviewer}
|
|
|
2177
2177
|
|
|
2178
2178
|
${n}
|
|
2179
2179
|
|
|
2180
|
-
Total duration: ${e.totalDuration_ms}ms`}var
|
|
2180
|
+
Total duration: ${e.totalDuration_ms}ms`}var Vw=require("fs");async function CP(e){try{if(e.toolName!=="Task")return{continue:!0};if(!e.directory||!e.sessionId)return{continue:!0};let t=await oe(e.directory);if(t.length===0)return{continue:!0};let n=null,r="";for(let f of t){let m=await A(e.directory,f);if(m&&m.status!=="complete"){n=m,r=m.manifest_path||"";break}}if(!n)return{continue:!0};if(n.current_phase!=="construction"||n.current_stage!=="code-generation"||!n.active_code_plan_path)return{continue:!0};let o=n.active_code_plan_path,s=W(r);if(!s)return{continue:!0};let i=Gw(e.directory),a=Hw(e.directory,i),c=s.artifacts.find(f=>f.id===o),l=[],u=[];if(c)try{let f=(0,Vw.readFileSync)(c.path,"utf-8");l=na(f,c.path).map(m=>m.message),u=ra(f,c.path).map(m=>m.message)}catch{}let d=qw(a),p="";return l.length>0&&(p=`
|
|
2181
2181
|
|
|
2182
2182
|
SECURITY FINDINGS:
|
|
2183
2183
|
${l.map(f=>` - ${f}`).join(`
|
|
@@ -2189,22 +2189,22 @@ ${u.map(f=>` - ${f}`).join(`
|
|
|
2189
2189
|
|
|
2190
2190
|
${d}${p}
|
|
2191
2191
|
|
|
2192
|
-
Fix the failing checks and re-run the BOLT execution.`}}}catch(t){return console.error("[Olympus CI Review] Error in ciReviewPipeline:",t),{continue:!0}}}function
|
|
2193
|
-
`);return{summary:d,phaseProgress:r,artifactTree:o,riskSummary:s,gateSummary:i,trustDisplay:a,alignmentSummary:c,fullReport:m}}function
|
|
2194
|
-
`)}function
|
|
2195
|
-
`)}function
|
|
2196
|
-
`)}function
|
|
2197
|
-
`)}function
|
|
2198
|
-
`)}function
|
|
2199
|
-
`)}Z();
|
|
2192
|
+
Fix the failing checks and re-run the BOLT execution.`}}}catch(t){return console.error("[Olympus CI Review] Error in ciReviewPipeline:",t),{continue:!0}}}function Yw(){I({name:"ciReviewPipeline",event:"PostToolUse",priority:79,matcher:"task",handler:CP})}ye();function Kw(e,t=2){let r=e.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter(s=>s.length>0);if(r.length<t)return new Set(r);let o=new Set;for(let s=0;s<=r.length-t;s++)o.add(r.slice(s,s+t).join(" "));return o}function yl(e,t){let n=Kw(e),r=Kw(t),o=new Set([...n].filter(i=>r.has(i))),s=new Set([...n,...r]);return s.size>0?o.size/s.size:0}function RP(e,t=.4){let n=[],r=new Set;for(let o of e){if(r.has(o.id))continue;let s=[o];r.add(o.id);for(let i of e){if(r.has(i.id))continue;yl(o.user_message,i.user_message)>=t&&(s.push(i),r.add(i.id))}n.push(s)}return n}function Jw(e,t=3,n=1e3,r){let i=(r?e.filter(c=>c.project_path===r):e).slice(-n).filter(c=>c.feedback_category==="correction"||c.feedback_category==="clarification"||c.feedback_category==="explicit_preference");return RP(i).filter(c=>c.length>=t).map(c=>{let l=c.sort((m,g)=>new Date(g.timestamp).getTime()-new Date(m.timestamp).getTime())[0],u=c.reduce((m,g)=>m+g.confidence,0)/c.length,p=new Set(c.map(m=>m.project_path)).size===1?"project":"global",f=PP(c);return{pattern:xP(c),confidence:u,evidence_count:c.length,evidence_examples:c.slice(0,3).map(m=>m.user_message.substring(0,150)),scope:p,category:f}})}function xP(e){let t=new Map;for(let o of e){let s=o.user_message.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter(i=>i.length>3);for(let i of s)t.set(i,(t.get(i)||0)+1)}let n=[...t.entries()].sort((o,s)=>s[1]-o[1]).slice(0,3).map(([o])=>o);return e[0].user_message.substring(0,100)+(n.length>0?` [themes: ${n.join(", ")}]`:"")}function PP(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 AP={verbosity:"unknown",autonomy:"unknown",explanation_depth:"unknown",explicit_rules:[],inferred_preferences:[],recurring_corrections:[],last_updated:new Date().toISOString()},IP=30;function OP(e){let t=e.filter(r=>r.feedback_category==="explicit_preference"),n=[];for(let r of t){let o=r.user_message.match(/always\s+(.+?)(?:\.|$)/i),s=r.user_message.match(/never\s+(.+?)(?:\.|$)/i);o&&n.push(`Always: ${o[1].trim()}`),s&&n.push(`Never: ${s[1].trim()}`)}return[...new Set(n)]}function $P(e){let t=e.filter(r=>/too (long|verbose|much|wordy)/i.test(r.user_message)).length,n=e.filter(r=>/more (detail|info|explanation)|too (brief|short)/i.test(r.user_message)).length;return t>=3&&t>n?"concise":n>=3&&n>t?"detailed":"unknown"}function DP(e){let t=e.filter(r=>/ask (me )?(first|before)|don't assume|confirm/i.test(r.user_message)).length,n=e.filter(r=>/just (do|make|fix)|don't ask|stop asking/i.test(r.user_message)).length;return t>=3&&t>n?"ask_first":n>=3&&n>t?"just_do_it":t>=2&&n>=2?"balanced":"unknown"}function zw(e,t,n,r){let o={...e},s=r??t.find(f=>f.project_path)?.project_path,i=OP(t),a=new Set(o.explicit_rules.map(f=>f.rule)),c=i.filter(f=>!a.has(f)).map(f=>({rule:f,created_at:new Date().toISOString(),...s?{project_path:s}:{}}));o.explicit_rules=[...o.explicit_rules,...c];let l=$P(t);l!=="unknown"&&(o.verbosity=l);let u=DP(t);u!=="unknown"&&(o.autonomy=u);let d=n.filter(f=>f.confidence>.7&&f.scope==="global").map(f=>f.pattern);o.inferred_preferences=[...new Set([...o.inferred_preferences,...d])];for(let f of n){let m=o.recurring_corrections.find(g=>yl(g.pattern,f.pattern)>.5);m?(m.count=f.evidence_count,m.last_seen=new Date().toISOString(),m.examples=f.evidence_examples):o.recurring_corrections.push({pattern:f.pattern,count:f.evidence_count,last_seen:new Date().toISOString(),examples:f.evidence_examples})}let p=Date.now();if(o.recurring_corrections=o.recurring_corrections.filter(f=>{if(!f.last_seen)return!0;let m=Date.parse(f.last_seen);return isNaN(m)?!0:p-m<=IP*864e5}),n.length>0){let f=new Set(n.map(m=>m.pattern));o.inferred_preferences=o.inferred_preferences.filter(m=>f.has(m))}return o.last_updated=new Date().toISOString(),o}function Qw(){return{...AP,last_updated:new Date().toISOString()}}var yo=require("path"),Pr=require("fs"),NP=3,jP=10;function FP(e){let t=(0,yo.join)(e,"feedback-log.jsonl"),n=(0,yo.join)(e,"agent-performance.json");if(!(0,Pr.existsSync)(t))return!1;if(!(0,Pr.existsSync)(n))return!0;try{let r=(0,Pr.statSync)(t),o=(0,Pr.statSync)(n);return r.mtime>o.mtime}catch(r){return console.error("[Olympus Learning Aggregation] Failed to check file times:",r),!0}}function Xw(){I({name:"learningAggregation",event:"Stop",priority:95,handler:async e=>{try{if(!e.directory)return{continue:!0};let t=pe();if(!FP(t))return{continue:!0};let n=Eo();if(n.length<NP)return{continue:!0};let r=new Set;for(let d of n)d.agent_used&&r.add(d.agent_used);let o=Array.from(r);if(o.length===0)return{continue:!0};let s={};for(let d of o){let p=To(d,n);p&&(s[d]=p)}let i=(0,yo.join)(t,"agent-performance.json");st(i,s);let a=(0,yo.join)(t,"user-preferences.json"),c=we(a,Qw()),l=[];if(n.length>=jP)try{l=Jw(n)}catch(d){console.error("[Olympus Learning Aggregation] Pattern extraction failed:",d)}let u=zw(c,n,l);st(a,u)}catch(t){console.error("[Olympus Learning Aggregation] Error in aggregation handler:",t)}return{continue:!0}}})}var _l=["discovery","inception","construction","operations"],MP={draft:"o",active:"+",fulfilled:"++",violated:"X",stale:"!"},LP={0:"Baseline",1:"Earned",2:"Extended",3:"Trusted"};function Zw(e,t=null,n=null){let r=UP(e),o=BP(e),s=GP(e.risks),i=HP(e.gate_audit),a=qP(t),c=VP(e.alignment_checks),l=YP(e.depth_assessment),u=KP(e.risk_tier),d=zP(e,r),p=JP(e),f=n?.inception_stages?XP(n.inception_stages,n.current_inception_stage):null,m=[`# Workflow Status: ${e.feature_name}`,`ID: ${e.workflow_id}`,"",d,"","## Phase Progress",...r.map(g=>WP(g)),"",...f?[f,""]:[],p,l,u,a,"","## Artifacts",o,"","## Alignment",c,"","## Risk Summary",s,"","## Gate Audit",i].filter(g=>g!==null).join(`
|
|
2193
|
+
`);return{summary:d,phaseProgress:r,artifactTree:o,riskSummary:s,gateSummary:i,trustDisplay:a,alignmentSummary:c,fullReport:m}}function UP(e){return _l.map(t=>{let n=e.phases[t],r=e.artifacts.filter(a=>a.phase===t),o=r.length;if(o===0)return{phase:t,percentage:n.status==="complete"?100:0,status:n.status,artifactCount:0};let s=r.filter(a=>a.contract_status==="active"||a.contract_status==="fulfilled").length,i=Math.round(s/o*100);return{phase:t,percentage:i,status:n.status,artifactCount:o}})}function WP(e){let n=Math.round(e.percentage/100*20),r=20-n,o="=".repeat(n)+"-".repeat(r);return`${(e.phase.charAt(0).toUpperCase()+e.phase.slice(1)).padEnd(8)} [${o}] ${String(e.percentage).padStart(3)}% (${e.status}) ${e.artifactCount} artifacts`}function BP(e){let t=[];for(let n of _l){let r=e.artifacts.filter(i=>i.phase===n);if(r.length===0)continue;let o=n.charAt(0).toUpperCase()+n.slice(1);t.push(`[${o}]`);let s=new Map;for(let i of r){let a=i.stage;s.has(a)||s.set(a,[]),s.get(a).push(i)}for(let[i,a]of s){t.push(` ${i}/`);for(let c of a){let l=MP[c.contract_status]??"?",u=c.validation_passed===!0?"v":c.validation_passed===!1?"x":"-";t.push(` [${l}] ${c.id} (${c.type}) [${u}]`)}}}return t.join(`
|
|
2194
|
+
`)}function GP(e){if(e.length===0)return"No risks registered";let t=e.filter(a=>a.status==="open").length,n=e.filter(a=>a.status==="mitigated").length,r=e.filter(a=>a.status==="accepted").length,o=e.filter(a=>a.status==="closed").length,s=[`Total: ${e.length} | Open: ${t} | Mitigated: ${n} | Accepted: ${r} | Closed: ${o}`],i=e.filter(a=>a.status==="open");for(let a of i)s.push(` [OPEN] ${a.id}: ${a.description} (${a.likelihood}/${a.impact})`);return s.join(`
|
|
2195
|
+
`)}function HP(e){if(e.length===0)return"No gate transitions recorded";let t=e.filter(s=>s.action==="approved").length,n=e.filter(s=>s.action==="rejected").length,r=e.filter(s=>s.action==="bypassed").length,o=[`Total: ${e.length} | Approved: ${t} | Rejected: ${n} | Bypassed: ${r}`];for(let s of e){let i=s.phase.charAt(0).toUpperCase()+s.phase.slice(1);o.push(` [${s.action.toUpperCase()}] ${i} by ${s.actor}${s.reason?": "+s.reason:""}`)}return o.join(`
|
|
2196
|
+
`)}function qP(e){if(!e)return"Trust: Not initialized";let t=LP[e.current_level]??"Unknown";return[`Trust Level ${e.current_level}: ${t}`,` Transitions: ${e.total_transitions} | Rejections: ${e.rejection_count} (${(e.rejection_rate*100).toFixed(1)}%) | Incidents: ${e.incident_count}`].join(`
|
|
2197
|
+
`)}function VP(e){if(e.length===0)return"No alignment checks recorded";let t=e.filter(o=>o.alignment_passed).length,n=e.filter(o=>!o.alignment_passed).length,r=[`Total: ${e.length} | Passed: ${t} | Failed: ${n}`];for(let o of e){let s=o.alignment_passed?"PASS":"FAIL",i=o.verification.conformance_score,a=o.verification.passed?"v":"x",c=o.validation.passed?"v":"x";r.push(` [${s}] ${o.source_artifact_id} -> ${o.target_artifact_id}: verification=${i}% [${a}] validation [${c}]`)}return r.join(`
|
|
2198
|
+
`)}function YP(e){return e?`Depth: ${e.recommended_depth} (score: ${e.total_score}/30)${e.skip_units?" [skip-units]":""}`:"Depth: Not assessed"}function KP(e){return e?`Risk Tier: ${e.tier} (${e.rationale})`:"Risk Tier: Not classified"}function JP(e){let t=e.artifacts.filter(o=>o.stage==="code-generation"),n=t.length;return n===0?"Bolts: 0/0":`Bolts: ${t.filter(o=>o.contract_status==="active"||o.contract_status==="fulfilled").length}/${n} complete`}function zP(e,t){let n=e.artifacts.length,r=t.filter(s=>s.status!=="not_started");return`${t.filter(s=>s.percentage===100&&s.status==="complete").length}/${_l.length} phases complete | ${n} artifacts total`}var wl=["workspace-detection","reverse-engineering","requirements-analysis","workflow-planning","units-generation","user-stories","bolt-planning"],QP={"workspace-detection":"Workspace Detection","reverse-engineering":"Reverse Engineering","requirements-analysis":"Requirements Analysis","workflow-planning":"Workflow Planning","units-generation":"Units Generation","user-stories":"User Stories","bolt-planning":"Bolt Planning"};function XP(e,t){let n=wl.length,r=wl.filter(l=>e[l]?.status==="completed").length,o=Math.round(r/n*100),s=10,i=Math.round(o/100*s),c=[`Inception [${i>=s?"=".repeat(s):"=".repeat(i)+">"+"-".repeat(s-i-1)}] ${o}% (${r}/${n} stages)`];for(let l of wl){let u=e[l],d=QP[l];if(!u){c.push(` [ ] ${d}`);continue}if(u.status==="completed")c.push(` [x] ${d}`);else if(u.status==="skipped"){let p=u.skip_reason?` (${u.skip_reason})`:" (skipped)";c.push(` [-] ${d}${p}`)}else u.status==="in_progress"||l===t?c.push(` [ ] ${d} <- current`):c.push(` [ ] ${d}`)}return c.join(`
|
|
2199
|
+
`)}Z();rn();ce();var e_=v(require("path"),1);function t_(){I({name:"workflowStatusReporter",event:"UserPromptSubmit",priority:6,handler:async e=>{try{let t=e.directory||process.cwd(),n=e.prompt||"",o=(e.parts||[]).map(f=>f.text||"").join(" ")||n;if(!(o.includes("Show status of all active structured workflows")||o.includes("workflow-status")))return{continue:!0};let i=await oe(t),a=null;for(let f of i){let m=await A(t,f);if(m&&m.status!=="complete"&&m.status!=="archived"&&m.status!=="deferred"){a=f;break}}if(!a)return{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:"<workflow-status>\nNo active workflows found. Start one with `/plan <description>`\n</workflow-status>"}};let c=e_.join(t,"aidlc-docs",a,"manifest.json"),l=W(c);if(!l){let f=await A(t,a),m=f?.current_phase||"unknown",g=f?.current_stage||"unknown";return{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:`<workflow-status>
|
|
2200
2200
|
# Workflow Status: ${a}
|
|
2201
2201
|
|
|
2202
2202
|
Phase: ${m} | Stage: ${g}
|
|
2203
2203
|
|
|
2204
2204
|
Note: manifest.json not found. Detailed artifact tracking unavailable. The workflow is active and can proceed normally.
|
|
2205
|
-
</workflow-status>`}}}let u=
|
|
2206
|
-
${
|
|
2207
|
-
</workflow-status>`}}}catch(t){return console.error("[Olympus Workflow Status] Error generating report:",t),{continue:!0}}}})}Z();
|
|
2205
|
+
</workflow-status>`}}}let u=be(t),d=await A(t,a);return{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:`<workflow-status>
|
|
2206
|
+
${Zw(l,u,d).fullReport}
|
|
2207
|
+
</workflow-status>`}}}catch(t){return console.error("[Olympus Workflow Status] Error generating report:",t),{continue:!0}}}})}Z();rn();ce();var n_=v(require("path"),1);function r_(){I({name:"workflowTransitionMessages",event:"PostToolUse",priority:82,handler:async e=>{try{let t=e.directory||process.cwd();if(e.toolName!=="Write"&&e.toolName!=="Task")return{continue:!0};let n=await oe(t),r=null,o=null;for(let m of n){let g=await A(t,m);if(g&&g.status!=="complete"&&g.status!=="archived"&&g.status!=="deferred"){r=m,o=g;break}}if(!r||!o)return{continue:!0};let s=n_.join(t,"aidlc-docs",r,"manifest.json"),i=W(s);if(!i)return{continue:!0};let a=be(t),c=i.gate_audit.length>0?i.gate_audit[i.gate_audit.length-1]:null,l=null,u=vt(i),d=u.filter(m=>m.contract_status==="fulfilled"),p=_n(i),f=i.artifacts.filter(m=>m.stage==="intent");if(u.length>0&&d.length===u.length&&o.current_stage==="code-generation"&&i.phases.construction.status==="complete")l=`\u2713 All ${u.length} BOLTs executed and reviewed
|
|
2208
2208
|
\u2192 Next: Operations phase. Generating deployment guide and release notes...`;else if(d.length>0&&d.length<u.length&&c?.phase==="construction"&&c?.action==="approved"){let m=u.length-d.length,g=d[d.length-1];l=`\u2713 BOLT ${d.length}/${u.length} complete \u2014 '${g.id}'
|
|
2209
2209
|
Gate 4: Dev review of ${g.id} code
|
|
2210
2210
|
\u2192 Current: ${m} remaining`}else if(p.length>0&&i.phases.construction.status==="in_progress"&&o.current_stage==="unit"&&c?.phase==="inception"&&c?.action==="approved"){let m=p.map(g=>g.id).join(", ");l=`\u2713 ${p.length} UNITs created: ${m}
|
|
@@ -2216,14 +2216,14 @@ ${p.length} UNITs decomposed | ${u.length} BOLTs queued
|
|
|
2216
2216
|
\u2192 Ready: /ascent, /olympus, or /ultrawork to begin Construction${g}`}if(!l&&o.inception_stages&&o.current_inception_stage){let m=o.inception_stages,g=o.current_inception_stage;if(m[g]?.status==="completed"){let _=Object.values(m).filter(h=>h.status==="completed").length;l=`Inception stage '${g}' complete (${_}/7)
|
|
2217
2217
|
\u2192 Next: continue inception pipeline`}}if(l)return{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:`<workflow-transition>
|
|
2218
2218
|
${l}
|
|
2219
|
-
</workflow-transition>`}}}catch(t){console.error("[Olympus Workflow Transition] Error:",t)}return{continue:!0}}})}var
|
|
2220
|
-
`;break;case 114:h+="\r";break;case 116:h+=" ";break;case 117:let k=p(4,!0);k>=0?h+=String.fromCharCode(k):d=4;break;default:d=5}b=r;continue}if(S>=0&&S<=31)if(
|
|
2221
|
-
`),a++,l=r,i=14;switch(h){case 123:return r++,i=1;case 125:return r++,i=2;case 91:return r++,i=3;case 93:return r++,i=4;case 58:return r++,i=6;case 44:return r++,i=5;case 34:return r++,o=g(),i=10;case 47:let b=r-1;if(e.charCodeAt(r+1)===47){for(r+=2;r<n&&!
|
|
2222
|
-
`+" ".repeat(t)),"\r":new Array(
|
|
2223
|
-
`+" ".repeat(t))}," ":{"\n":new Array(
|
|
2224
|
-
`+" ".repeat(t)),"\r":new Array(
|
|
2225
|
-
`+" ".repeat(t))}};var oi;(function(e){e.DEFAULT={allowTrailingComma:!1}})(oi||(oi={}));function c_(e,t=[],n=oi.DEFAULT){let r=null,o=[],s=[];function i(c){Array.isArray(o)?o.push(c):r!==null&&(o[r]=c)}return l_(e,{onObjectBegin:()=>{let c={};i(c),s.push(o),o=c,r=null},onObjectProperty:c=>{r=c},onObjectEnd:()=>{o=s.pop()},onArrayBegin:()=>{let c=[];i(c),s.push(o),o=c,r=null},onArrayEnd:()=>{o=s.pop()},onLiteralValue:i,onError:(c,l,u)=>{t.push({error:c,offset:l,length:u})}},n),o[0]}function l_(e,t,n=oi.DEFAULT){let r=ri(e,!1),o=[],s=0;function i(x){return x?()=>s===0&&x(r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter()):()=>!0}function a(x){return x?E=>s===0&&x(E,r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter()):()=>!0}function c(x){return x?E=>s===0&&x(E,r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter(),()=>o.slice()):()=>!0}function l(x){return x?()=>{s>0?s++:x(r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter(),()=>o.slice())===!1&&(s=1)}:()=>!0}function u(x){return x?()=>{s>0&&s--,s===0&&x(r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter())}:()=>!0}let d=l(t.onObjectBegin),p=c(t.onObjectProperty),f=u(t.onObjectEnd),m=l(t.onArrayBegin),g=u(t.onArrayEnd),y=c(t.onLiteralValue),w=a(t.onSeparator),_=i(t.onComment),h=a(t.onError),b=n&&n.disallowComments,S=n&&n.allowTrailingComma;function T(){for(;;){let x=r.scan();switch(r.getTokenError()){case 4:k(14);break;case 5:k(15);break;case 3:k(13);break;case 1:b||k(11);break;case 2:k(12);break;case 6:k(16);break}switch(x){case 12:case 13:b?k(10):_();break;case 16:k(1);break;case 15:case 14:break;default:return x}}}function k(x,E=[],L=[]){if(h(x),E.length+L.length>0){let j=r.getToken();for(;j!==17;){if(E.indexOf(j)!==-1){T();break}else if(L.indexOf(j)!==-1)break;j=T()}}}function F(x){let E=r.getTokenValue();return x?y(E):(p(E),o.push(E)),T(),!0}function R(){switch(r.getToken()){case 11:let x=r.getTokenValue(),E=Number(x);isNaN(E)&&(k(2),E=0),y(E);break;case 7:y(null);break;case 8:y(!0);break;case 9:y(!1);break;default:return!1}return T(),!0}function O(){return r.getToken()!==10?(k(3,[],[2,5]),!1):(F(!1),r.getToken()===6?(w(":"),T(),D()||k(4,[],[2,5])):k(5,[],[2,5]),o.pop(),!0)}function C(){d(),T();let x=!1;for(;r.getToken()!==2&&r.getToken()!==17;){if(r.getToken()===5){if(x||k(4,[],[]),w(","),T(),r.getToken()===2&&S)break}else x&&k(6,[],[]);O()||k(4,[],[2,5]),x=!0}return f(),r.getToken()!==2?k(7,[2],[]):T(),!0}function $(){m(),T();let x=!0,E=!1;for(;r.getToken()!==4&&r.getToken()!==17;){if(r.getToken()===5){if(E||k(4,[],[]),w(","),T(),r.getToken()===4&&S)break}else E&&k(6,[],[]);x?(o.push(0),x=!1):o[o.length-1]++,D()||k(4,[],[4,5]),E=!0}return g(),x||o.pop(),r.getToken()!==4?k(8,[4],[]):T(),!0}function D(){switch(r.getToken()){case 3:return $();case 1:return C();case 10:return F(!0);default:return R()}}return T(),r.getToken()===17?n.allowEmptyContent?!0:(k(4,[],[]),!1):D()?(r.getToken()!==17&&k(9,[],[]),!0):(k(4,[],[]),!1)}var u_;(function(e){e[e.None=0]="None",e[e.UnexpectedEndOfComment=1]="UnexpectedEndOfComment",e[e.UnexpectedEndOfString=2]="UnexpectedEndOfString",e[e.UnexpectedEndOfNumber=3]="UnexpectedEndOfNumber",e[e.InvalidUnicode=4]="InvalidUnicode",e[e.InvalidEscapeCharacter=5]="InvalidEscapeCharacter",e[e.InvalidCharacter=6]="InvalidCharacter"})(u_||(u_={}));var d_;(function(e){e[e.OpenBraceToken=1]="OpenBraceToken",e[e.CloseBraceToken=2]="CloseBraceToken",e[e.OpenBracketToken=3]="OpenBracketToken",e[e.CloseBracketToken=4]="CloseBracketToken",e[e.CommaToken=5]="CommaToken",e[e.ColonToken=6]="ColonToken",e[e.NullKeyword=7]="NullKeyword",e[e.TrueKeyword=8]="TrueKeyword",e[e.FalseKeyword=9]="FalseKeyword",e[e.StringLiteral=10]="StringLiteral",e[e.NumericLiteral=11]="NumericLiteral",e[e.LineCommentTrivia=12]="LineCommentTrivia",e[e.BlockCommentTrivia=13]="BlockCommentTrivia",e[e.LineBreakTrivia=14]="LineBreakTrivia",e[e.Trivia=15]="Trivia",e[e.Unknown=16]="Unknown",e[e.EOF=17]="EOF"})(d_||(d_={}));var f_=c_;var p_;(function(e){e[e.InvalidSymbol=1]="InvalidSymbol",e[e.InvalidNumberFormat=2]="InvalidNumberFormat",e[e.PropertyNameExpected=3]="PropertyNameExpected",e[e.ValueExpected=4]="ValueExpected",e[e.ColonExpected=5]="ColonExpected",e[e.CommaExpected=6]="CommaExpected",e[e.CloseBraceExpected=7]="CloseBraceExpected",e[e.CloseBracketExpected=8]="CloseBracketExpected",e[e.EndOfFileExpected=9]="EndOfFileExpected",e[e.InvalidCommentToken=10]="InvalidCommentToken",e[e.UnexpectedEndOfComment=11]="UnexpectedEndOfComment",e[e.UnexpectedEndOfString=12]="UnexpectedEndOfString",e[e.UnexpectedEndOfNumber=13]="UnexpectedEndOfNumber",e[e.InvalidUnicode=14]="InvalidUnicode",e[e.InvalidEscapeCharacter=15]="InvalidEscapeCharacter",e[e.InvalidCharacter=16]="InvalidCharacter"})(p_||(p_={}));var cA={agents:{olympus:{model:"claude-opus-4-5-20251101"},oracle:{model:"claude-opus-4-5-20251101",enabled:!0},librarian:{model:"claude-sonnet-4-5-20250929"},explore:{model:"claude-haiku-4-5-20251001"},frontendEngineer:{model:"claude-sonnet-4-5-20250929",enabled:!0},documentWriter:{model:"claude-haiku-4-5-20251001",enabled:!0},multimodalLooker:{model:"claude-sonnet-4-5-20250929",enabled:!0},momus:{model:"claude-opus-4-5-20251101",enabled:!0},metis:{model:"claude-opus-4-5-20251101",enabled:!0},orchestratorOlympus:{model:"claude-sonnet-4-5-20250929",enabled:!0},olympusJunior:{model:"claude-sonnet-4-5-20250929",enabled:!0},prometheus:{model:"claude-opus-4-5-20251101",enabled:!0}},features:{parallelExecution:!0,lspTools:!0,astTools:!0,continuationEnforcement:!0,autoContextInjection:!0},mcpServers:{exa:{enabled:!0},context7:{enabled:!0},grepApp:{enabled:!0}},permissions:{allowBash:!0,allowEdit:!0,allowWrite:!0,maxBackgroundTasks:5},magicKeywords:{ultrawork:["ultrawork","ulw","uw"],search:["search","find","locate"],analyze:["analyze","investigate","examine"],ultrathink:["ultrathink","think","reason","ponder"]},routing:{enabled:!0,defaultTier:"MEDIUM",escalationEnabled:!0,maxEscalations:2,tierModels:{LOW:"claude-haiku-4-5-20251001",MEDIUM:"claude-sonnet-4-5-20250929",HIGH:"claude-opus-4-5-20251101"},agentOverrides:{oracle:{tier:"HIGH",reason:"Advisory agent requires deep reasoning"},prometheus:{tier:"HIGH",reason:"Strategic planning requires deep reasoning"},momus:{tier:"HIGH",reason:"Critical review requires deep reasoning"},metis:{tier:"HIGH",reason:"Pre-planning analysis requires deep reasoning"},explore:{tier:"LOW",reason:"Exploration is search-focused"},"document-writer":{tier:"LOW",reason:"Documentation is straightforward"}},escalationKeywords:["critical","production","urgent","security","breaking","architecture","refactor","redesign","root cause"],simplificationKeywords:["find","list","show","where","search","locate","grep"]},ascent:{maxIterations:100},learning:{tokenMetrics:{enabled:!0,warningThreshold:1.5,minimumSamples:5,injectionTokenBudget:150,sessionBaseline:1e4}},pricing:{models:rl,customPricing:[]}};function lA(){return{user:(0,ii.join)((0,g_.homedir)(),".claude","olympus","config.jsonc"),project:(0,ii.join)(process.cwd(),".claude","olympus.jsonc")}}function m_(e){if(!(0,ai.existsSync)(e))return null;try{let t=(0,ai.readFileSync)(e,"utf-8"),n=[],r=f_(t,n,{allowTrailingComma:!0,allowEmptyContent:!0});return n.length>0&&console.warn(`Warning: Parse errors in ${e}:`,n),r}catch(t){return console.error(`Error loading config from ${e}:`,t),null}}function si(e,t){let n={...e};for(let r of Object.keys(t)){let o=t[r],s=n[r];o!==void 0&&typeof o=="object"&&o!==null&&!Array.isArray(o)&&typeof s=="object"&&s!==null&&!Array.isArray(s)?n[r]=si(s,o):o!==void 0&&(n[r]=o)}return n}function uA(){let e={};if(process.env.EXA_API_KEY&&(e.mcpServers={...e.mcpServers,exa:{enabled:!0,apiKey:process.env.EXA_API_KEY}}),process.env.OLYMPUS_PARALLEL_EXECUTION!==void 0&&(e.features={...e.features,parallelExecution:process.env.OLYMPUS_PARALLEL_EXECUTION==="true"}),process.env.OLYMPUS_LSP_TOOLS!==void 0&&(e.features={...e.features,lspTools:process.env.OLYMPUS_LSP_TOOLS==="true"}),process.env.OLYMPUS_MAX_BACKGROUND_TASKS){let t=parseInt(process.env.OLYMPUS_MAX_BACKGROUND_TASKS,10);isNaN(t)||(e.permissions={...e.permissions,maxBackgroundTasks:t})}if(process.env.OLYMPUS_ROUTING_ENABLED!==void 0&&(e.routing={...e.routing,enabled:process.env.OLYMPUS_ROUTING_ENABLED==="true"}),process.env.OLYMPUS_ROUTING_DEFAULT_TIER){let t=process.env.OLYMPUS_ROUTING_DEFAULT_TIER.toUpperCase();(t==="LOW"||t==="MEDIUM"||t==="HIGH")&&(e.routing={...e.routing,defaultTier:t})}if(process.env.OLYMPUS_ESCALATION_ENABLED!==void 0&&(e.routing={...e.routing,escalationEnabled:process.env.OLYMPUS_ESCALATION_ENABLED==="true"}),process.env.OLYMPUS_MAX_ASCENT_ITERATIONS){let t=parseInt(process.env.OLYMPUS_MAX_ASCENT_ITERATIONS,10);!isNaN(t)&&t>=10&&t<=1e3?e.ascent={...e.ascent,maxIterations:t}:isNaN(t)||console.warn(`Warning: OLYMPUS_MAX_ASCENT_ITERATIONS must be between 10 and 1000. Got: ${t}`)}return e}function h_(){let e=lA(),t={...cA},n=m_(e.user);n&&(t=si(t,n));let r=m_(e.project);r&&(t=si(t,r));let o=uA();return t=si(t,o),t}function dA(e){let t=e.hooks;return t&&typeof t.timeoutMs=="number"?t.timeoutMs:5e3}function pA(e,t){let n=e.hooks;if(n&&typeof n.enabled=="boolean"&&!n.enabled)return!1;if(n&&t in n){let r=n[t];if(typeof r=="object"&&r!==null){let o=r.enabled;if(typeof o=="boolean")return o}}return!0}async function fA(e,t){return Promise.race([Promise.resolve(e()),new Promise(n=>setTimeout(()=>n(null),t))])}function mA(e,t){return!e||!t?!0:(typeof e=="string"?new RegExp(e,"i"):e).test(t)}async function y_(e,t){let n=h_(),r=bl(e),o=dA(n),s=!0,i=[],a,c=t.toolInput,l=t.messages;for(let u of r)if(pA(n,u.name)&&mA(u.matcher,t.toolName))try{let d=await fA(()=>u.handler({...t,toolInput:c,messages:l}),o);if(d===null){console.error(`[hook-router] ${u.name} timed out after ${o}ms`);continue}d.continue||(s=!1,a=d.stopReason),d.message&&i.push(d.message),d.hookSpecificOutput?.additionalContext&&i.push(d.hookSpecificOutput.additionalContext),d.modifiedInput!==void 0&&(c=d.modifiedInput),d.modifiedMessages!==void 0&&(l=d.modifiedMessages)}catch(d){console.error(`[hook-router] ${u.name} error:`,d)}return{continue:s,message:i.length>0?i.join(`
|
|
2219
|
+
</workflow-transition>`}}}catch(t){console.error("[Olympus Workflow Transition] Error:",t)}return{continue:!0}}})}var o_=!1;function s_(){o_||(Fw(),t_(),Rg(),Lg(),sh(),Jh(),xy(),qy(),Ky(),ow(),sw(),mw(),_w(),Rw(),Uw(),Ww(),Yw(),Dw(),r_(),Xw(),o_=!0)}var si=require("fs"),m_=require("os"),oi=require("path");function ti(e,t=!1){let n=e.length,r=0,o="",s=0,i=16,a=0,c=0,l=0,u=0,d=0;function p(h,b){let S=0,T=0;for(;S<h||!b;){let k=e.charCodeAt(r);if(k>=48&&k<=57)T=T*16+k-48;else if(k>=65&&k<=70)T=T*16+k-65+10;else if(k>=97&&k<=102)T=T*16+k-97+10;else break;r++,S++}return S<h&&(T=-1),T}function f(h){r=h,o="",s=0,i=16,d=0}function m(){let h=r;if(e.charCodeAt(r)===48)r++;else for(r++;r<e.length&&Ar(e.charCodeAt(r));)r++;if(r<e.length&&e.charCodeAt(r)===46)if(r++,r<e.length&&Ar(e.charCodeAt(r)))for(r++;r<e.length&&Ar(e.charCodeAt(r));)r++;else return d=3,e.substring(h,r);let b=r;if(r<e.length&&(e.charCodeAt(r)===69||e.charCodeAt(r)===101))if(r++,(r<e.length&&e.charCodeAt(r)===43||e.charCodeAt(r)===45)&&r++,r<e.length&&Ar(e.charCodeAt(r))){for(r++;r<e.length&&Ar(e.charCodeAt(r));)r++;b=r}else d=3;return e.substring(h,b)}function g(){let h="",b=r;for(;;){if(r>=n){h+=e.substring(b,r),d=2;break}let S=e.charCodeAt(r);if(S===34){h+=e.substring(b,r),r++;break}if(S===92){if(h+=e.substring(b,r),r++,r>=n){d=2;break}switch(e.charCodeAt(r++)){case 34:h+='"';break;case 92:h+="\\";break;case 47:h+="/";break;case 98:h+="\b";break;case 102:h+="\f";break;case 110:h+=`
|
|
2220
|
+
`;break;case 114:h+="\r";break;case 116:h+=" ";break;case 117:let k=p(4,!0);k>=0?h+=String.fromCharCode(k):d=4;break;default:d=5}b=r;continue}if(S>=0&&S<=31)if(wo(S)){h+=e.substring(b,r),d=2;break}else d=6;r++}return h}function y(){if(o="",d=0,s=r,c=a,u=l,r>=n)return s=n,i=17;let h=e.charCodeAt(r);if(kl(h)){do r++,o+=String.fromCharCode(h),h=e.charCodeAt(r);while(kl(h));return i=15}if(wo(h))return r++,o+=String.fromCharCode(h),h===13&&e.charCodeAt(r)===10&&(r++,o+=`
|
|
2221
|
+
`),a++,l=r,i=14;switch(h){case 123:return r++,i=1;case 125:return r++,i=2;case 91:return r++,i=3;case 93:return r++,i=4;case 58:return r++,i=6;case 44:return r++,i=5;case 34:return r++,o=g(),i=10;case 47:let b=r-1;if(e.charCodeAt(r+1)===47){for(r+=2;r<n&&!wo(e.charCodeAt(r));)r++;return o=e.substring(b,r),i=12}if(e.charCodeAt(r+1)===42){r+=2;let S=n-1,T=!1;for(;r<S;){let k=e.charCodeAt(r);if(k===42&&e.charCodeAt(r+1)===47){r+=2,T=!0;break}r++,wo(k)&&(k===13&&e.charCodeAt(r)===10&&r++,a++,l=r)}return T||(r++,d=1),o=e.substring(b,r),i=13}return o+=String.fromCharCode(h),r++,i=16;case 45:if(o+=String.fromCharCode(h),r++,r===n||!Ar(e.charCodeAt(r)))return i=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return o+=m(),i=11;default:for(;r<n&&w(h);)r++,h=e.charCodeAt(r);if(s!==r){switch(o=e.substring(s,r),o){case"true":return i=8;case"false":return i=9;case"null":return i=7}return i=16}return o+=String.fromCharCode(h),r++,i=16}}function w(h){if(kl(h)||wo(h))return!1;switch(h){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}function _(){let h;do h=y();while(h>=12&&h<=15);return h}return{setPosition:f,getPosition:()=>r,scan:t?_:y,getToken:()=>i,getTokenValue:()=>o,getTokenOffset:()=>s,getTokenLength:()=>r-s,getTokenStartLine:()=>c,getTokenStartCharacter:()=>s-u,getTokenError:()=>d}}function kl(e){return e===32||e===9}function wo(e){return e===10||e===13}function Ar(e){return e>=48&&e<=57}var i_;(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"})(i_||(i_={}));var eA=new Array(20).fill(0).map((e,t)=>" ".repeat(t)),Ir=200,tA={" ":{"\n":new Array(Ir).fill(0).map((e,t)=>`
|
|
2222
|
+
`+" ".repeat(t)),"\r":new Array(Ir).fill(0).map((e,t)=>"\r"+" ".repeat(t)),"\r\n":new Array(Ir).fill(0).map((e,t)=>`\r
|
|
2223
|
+
`+" ".repeat(t))}," ":{"\n":new Array(Ir).fill(0).map((e,t)=>`
|
|
2224
|
+
`+" ".repeat(t)),"\r":new Array(Ir).fill(0).map((e,t)=>"\r"+" ".repeat(t)),"\r\n":new Array(Ir).fill(0).map((e,t)=>`\r
|
|
2225
|
+
`+" ".repeat(t))}};var ni;(function(e){e.DEFAULT={allowTrailingComma:!1}})(ni||(ni={}));function a_(e,t=[],n=ni.DEFAULT){let r=null,o=[],s=[];function i(c){Array.isArray(o)?o.push(c):r!==null&&(o[r]=c)}return c_(e,{onObjectBegin:()=>{let c={};i(c),s.push(o),o=c,r=null},onObjectProperty:c=>{r=c},onObjectEnd:()=>{o=s.pop()},onArrayBegin:()=>{let c=[];i(c),s.push(o),o=c,r=null},onArrayEnd:()=>{o=s.pop()},onLiteralValue:i,onError:(c,l,u)=>{t.push({error:c,offset:l,length:u})}},n),o[0]}function c_(e,t,n=ni.DEFAULT){let r=ti(e,!1),o=[],s=0;function i(x){return x?()=>s===0&&x(r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter()):()=>!0}function a(x){return x?E=>s===0&&x(E,r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter()):()=>!0}function c(x){return x?E=>s===0&&x(E,r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter(),()=>o.slice()):()=>!0}function l(x){return x?()=>{s>0?s++:x(r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter(),()=>o.slice())===!1&&(s=1)}:()=>!0}function u(x){return x?()=>{s>0&&s--,s===0&&x(r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter())}:()=>!0}let d=l(t.onObjectBegin),p=c(t.onObjectProperty),f=u(t.onObjectEnd),m=l(t.onArrayBegin),g=u(t.onArrayEnd),y=c(t.onLiteralValue),w=a(t.onSeparator),_=i(t.onComment),h=a(t.onError),b=n&&n.disallowComments,S=n&&n.allowTrailingComma;function T(){for(;;){let x=r.scan();switch(r.getTokenError()){case 4:k(14);break;case 5:k(15);break;case 3:k(13);break;case 1:b||k(11);break;case 2:k(12);break;case 6:k(16);break}switch(x){case 12:case 13:b?k(10):_();break;case 16:k(1);break;case 15:case 14:break;default:return x}}}function k(x,E=[],L=[]){if(h(x),E.length+L.length>0){let j=r.getToken();for(;j!==17;){if(E.indexOf(j)!==-1){T();break}else if(L.indexOf(j)!==-1)break;j=T()}}}function F(x){let E=r.getTokenValue();return x?y(E):(p(E),o.push(E)),T(),!0}function R(){switch(r.getToken()){case 11:let x=r.getTokenValue(),E=Number(x);isNaN(E)&&(k(2),E=0),y(E);break;case 7:y(null);break;case 8:y(!0);break;case 9:y(!1);break;default:return!1}return T(),!0}function O(){return r.getToken()!==10?(k(3,[],[2,5]),!1):(F(!1),r.getToken()===6?(w(":"),T(),D()||k(4,[],[2,5])):k(5,[],[2,5]),o.pop(),!0)}function C(){d(),T();let x=!1;for(;r.getToken()!==2&&r.getToken()!==17;){if(r.getToken()===5){if(x||k(4,[],[]),w(","),T(),r.getToken()===2&&S)break}else x&&k(6,[],[]);O()||k(4,[],[2,5]),x=!0}return f(),r.getToken()!==2?k(7,[2],[]):T(),!0}function $(){m(),T();let x=!0,E=!1;for(;r.getToken()!==4&&r.getToken()!==17;){if(r.getToken()===5){if(E||k(4,[],[]),w(","),T(),r.getToken()===4&&S)break}else E&&k(6,[],[]);x?(o.push(0),x=!1):o[o.length-1]++,D()||k(4,[],[4,5]),E=!0}return g(),x||o.pop(),r.getToken()!==4?k(8,[4],[]):T(),!0}function D(){switch(r.getToken()){case 3:return $();case 1:return C();case 10:return F(!0);default:return R()}}return T(),r.getToken()===17?n.allowEmptyContent?!0:(k(4,[],[]),!1):D()?(r.getToken()!==17&&k(9,[],[]),!0):(k(4,[],[]),!1)}var l_;(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"})(l_||(l_={}));var u_;(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"})(u_||(u_={}));var p_=a_;var d_;(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"})(d_||(d_={}));var lA={agents:{olympus:{model:"claude-opus-4-5-20251101"},oracle:{model:"claude-opus-4-5-20251101",enabled:!0},librarian:{model:"claude-sonnet-4-5-20250929"},explore:{model:"claude-haiku-4-5-20251001"},frontendEngineer:{model:"claude-sonnet-4-5-20250929",enabled:!0},documentWriter:{model:"claude-haiku-4-5-20251001",enabled:!0},multimodalLooker:{model:"claude-sonnet-4-5-20250929",enabled:!0},momus:{model:"claude-opus-4-5-20251101",enabled:!0},metis:{model:"claude-opus-4-5-20251101",enabled:!0},orchestratorOlympus:{model:"claude-sonnet-4-5-20250929",enabled:!0},olympusJunior:{model:"claude-sonnet-4-5-20250929",enabled:!0},prometheus:{model:"claude-opus-4-5-20251101",enabled:!0}},features:{parallelExecution:!0,lspTools:!0,astTools:!0,continuationEnforcement:!0,autoContextInjection:!0},mcpServers:{exa:{enabled:!0},context7:{enabled:!0},grepApp:{enabled:!0}},permissions:{allowBash:!0,allowEdit:!0,allowWrite:!0,maxBackgroundTasks:5},magicKeywords:{ultrawork:["ultrawork","ulw","uw"],search:["search","find","locate"],analyze:["analyze","investigate","examine"],ultrathink:["ultrathink","think","reason","ponder"]},routing:{enabled:!0,defaultTier:"MEDIUM",escalationEnabled:!0,maxEscalations:2,tierModels:{LOW:"claude-haiku-4-5-20251001",MEDIUM:"claude-sonnet-4-5-20250929",HIGH:"claude-opus-4-5-20251101"},agentOverrides:{oracle:{tier:"HIGH",reason:"Advisory agent requires deep reasoning"},prometheus:{tier:"HIGH",reason:"Strategic planning requires deep reasoning"},momus:{tier:"HIGH",reason:"Critical review requires deep reasoning"},metis:{tier:"HIGH",reason:"Pre-planning analysis requires deep reasoning"},explore:{tier:"LOW",reason:"Exploration is search-focused"},"document-writer":{tier:"LOW",reason:"Documentation is straightforward"}},escalationKeywords:["critical","production","urgent","security","breaking","architecture","refactor","redesign","root cause"],simplificationKeywords:["find","list","show","where","search","locate","grep"]},ascent:{maxIterations:100},learning:{tokenMetrics:{enabled:!0,warningThreshold:1.5,minimumSamples:5,injectionTokenBudget:150,sessionBaseline:1e4}},pricing:{models:nl,customPricing:[]}};function uA(){return{user:(0,oi.join)((0,m_.homedir)(),".claude","olympus","config.jsonc"),project:(0,oi.join)(process.cwd(),".claude","olympus.jsonc")}}function f_(e){if(!(0,si.existsSync)(e))return null;try{let t=(0,si.readFileSync)(e,"utf-8"),n=[],r=p_(t,n,{allowTrailingComma:!0,allowEmptyContent:!0});return n.length>0&&console.warn(`Warning: Parse errors in ${e}:`,n),r}catch(t){return console.error(`Error loading config from ${e}:`,t),null}}function ri(e,t){let n={...e};for(let r of Object.keys(t)){let o=t[r],s=n[r];o!==void 0&&typeof o=="object"&&o!==null&&!Array.isArray(o)&&typeof s=="object"&&s!==null&&!Array.isArray(s)?n[r]=ri(s,o):o!==void 0&&(n[r]=o)}return n}function dA(){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 g_(){let e=uA(),t={...lA},n=f_(e.user);n&&(t=ri(t,n));let r=f_(e.project);r&&(t=ri(t,r));let o=dA();return t=ri(t,o),t}function pA(e){let t=e.hooks;return t&&typeof t.timeoutMs=="number"?t.timeoutMs:5e3}function fA(e,t){let n=e.hooks;if(n&&typeof n.enabled=="boolean"&&!n.enabled)return!1;if(n&&t in n){let r=n[t];if(typeof r=="object"&&r!==null){let o=r.enabled;if(typeof o=="boolean")return o}}return!0}async function mA(e,t){return Promise.race([Promise.resolve(e()),new Promise(n=>setTimeout(()=>n(null),t))])}function gA(e,t){return!e||!t?!0:(typeof e=="string"?new RegExp(e,"i"):e).test(t)}async function h_(e,t){let n=g_(),r=vl(e),o=pA(n),s=!0,i=[],a,c=t.toolInput,l=t.messages;for(let u of r)if(fA(n,u.name)&&gA(u.matcher,t.toolName))try{let d=await mA(()=>u.handler({...t,toolInput:c,messages:l}),o);if(d===null){console.error(`[hook-router] ${u.name} timed out after ${o}ms`);continue}d.continue||(s=!1,a=d.stopReason),d.message&&i.push(d.message),d.hookSpecificOutput?.additionalContext&&i.push(d.hookSpecificOutput.additionalContext),d.modifiedInput!==void 0&&(c=d.modifiedInput),d.modifiedMessages!==void 0&&(l=d.modifiedMessages)}catch(d){console.error(`[hook-router] ${u.name} error:`,d)}return{continue:s,message:i.length>0?i.join(`
|
|
2226
2226
|
|
|
2227
2227
|
---
|
|
2228
2228
|
|
|
2229
|
-
`):void 0,stopReason:a,modifiedInput:c!==t.toolInput?c:void 0,modifiedMessages:l!==t.messages?l:void 0}}
|
|
2229
|
+
`):void 0,stopReason:a,modifiedInput:c!==t.toolInput?c:void 0,modifiedMessages:l!==t.messages?l:void 0}}s_();async function hA(){return process.stdin.isTTY?"{}":new Promise(e=>{let t=[],n=!1,r=setTimeout(()=>{process.stdin.pause(),process.stdin.destroy(),e(n?Buffer.concat(t).toString("utf-8"):"{}")},1e3);process.stdin.on("data",o=>{n=!0,t.push(o)}),process.stdin.on("end",()=>{clearTimeout(r),e(n?Buffer.concat(t).toString("utf-8"):"{}")}),process.stdin.on("error",()=>{clearTimeout(r),e("{}")}),process.stdin.resume()})}async function y_(){let t=process.argv.slice(2).find(a=>a.startsWith("--event="));t||(console.error("Usage: node olympus-hooks.mjs --event=<event-type>"),process.exit(1));let n=t.split("=")[1],r=await hA(),o;try{let a=JSON.parse(r);o={...a,directory:a.cwd||a.directory,sessionId:a.session_id||a.sessionId,toolName:a.tool_name||a.toolName,toolInput:a.tool_input||a.toolInput,toolOutput:a.tool_response||a.toolOutput}}catch{o={}}let s=await h_(n,o),i={continue:s.continue};s.stopReason&&(i.stopReason=s.stopReason),s.message&&(n==="PreToolUse"||n==="UserPromptSubmit"||n==="PostToolUse"?i.hookSpecificOutput={hookEventName:n,additionalContext:s.message}:i.reason=s.message),console.log(JSON.stringify(i)),process.exit(0)}var ii=process.argv[1]||"",yA=ii.endsWith("entry.ts")||ii.endsWith("entry.js")||ii.endsWith("olympus-hooks.mjs")||ii.includes("olympus-hooks");yA&&y_().catch(e=>{console.error("[olympus-hooks] Fatal error:",e),process.exit(1)});0&&(module.exports={main});
|