olympus-ai 3.4.1 → 3.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +640 -630
- package/dist/__tests__/workflow-engine/checkpoint.test.d.ts +7 -0
- package/dist/__tests__/workflow-engine/checkpoint.test.d.ts.map +1 -0
- package/dist/__tests__/workflow-engine/checkpoint.test.js +373 -0
- package/dist/__tests__/workflow-engine/checkpoint.test.js.map +1 -0
- package/dist/agents/definitions.d.ts.map +1 -1
- package/dist/agents/definitions.js +8 -0
- package/dist/agents/definitions.js.map +1 -1
- package/dist/agents/idea-intake.d.ts +20 -0
- package/dist/agents/idea-intake.d.ts.map +1 -0
- package/dist/agents/idea-intake.js +255 -0
- package/dist/agents/idea-intake.js.map +1 -0
- package/dist/agents/index.d.ts +4 -0
- package/dist/agents/index.d.ts.map +1 -1
- package/dist/agents/index.js +4 -0
- package/dist/agents/index.js.map +1 -1
- package/dist/agents/intent-generator.d.ts +19 -0
- package/dist/agents/intent-generator.d.ts.map +1 -0
- package/dist/agents/intent-generator.js +303 -0
- package/dist/agents/intent-generator.js.map +1 -0
- package/dist/agents/prd-writer.d.ts +19 -0
- package/dist/agents/prd-writer.d.ts.map +1 -0
- package/dist/agents/prd-writer.js +236 -0
- package/dist/agents/prd-writer.js.map +1 -0
- package/dist/agents/prometheus.d.ts.map +1 -1
- package/dist/agents/prometheus.js +96 -2
- package/dist/agents/prometheus.js.map +1 -1
- package/dist/agents/spec-writer.d.ts +19 -0
- package/dist/agents/spec-writer.d.ts.map +1 -0
- package/dist/agents/spec-writer.js +528 -0
- package/dist/agents/spec-writer.js.map +1 -0
- package/dist/config/loader.d.ts +1 -1
- package/dist/config/loader.d.ts.map +1 -1
- package/dist/config/loader.js +2 -3
- package/dist/config/loader.js.map +1 -1
- package/dist/features/index.d.ts +1 -0
- package/dist/features/index.d.ts.map +1 -1
- package/dist/features/index.js +6 -0
- package/dist/features/index.js.map +1 -1
- package/dist/features/workflow-engine/artifacts.d.ts +96 -0
- package/dist/features/workflow-engine/artifacts.d.ts.map +1 -0
- package/dist/features/workflow-engine/artifacts.js +399 -0
- package/dist/features/workflow-engine/artifacts.js.map +1 -0
- package/dist/features/workflow-engine/checkpoint.d.ts +67 -0
- package/dist/features/workflow-engine/checkpoint.d.ts.map +1 -0
- package/dist/features/workflow-engine/checkpoint.js +249 -0
- package/dist/features/workflow-engine/checkpoint.js.map +1 -0
- package/dist/features/workflow-engine/engine.d.ts +125 -0
- package/dist/features/workflow-engine/engine.d.ts.map +1 -0
- package/dist/features/workflow-engine/engine.js +1354 -0
- package/dist/features/workflow-engine/engine.js.map +1 -0
- package/dist/features/workflow-engine/execution.d.ts +99 -0
- package/dist/features/workflow-engine/execution.d.ts.map +1 -0
- package/dist/features/workflow-engine/execution.js +493 -0
- package/dist/features/workflow-engine/execution.js.map +1 -0
- package/dist/features/workflow-engine/hooks.d.ts +78 -0
- package/dist/features/workflow-engine/hooks.d.ts.map +1 -0
- package/dist/features/workflow-engine/hooks.js +188 -0
- package/dist/features/workflow-engine/hooks.js.map +1 -0
- package/dist/features/workflow-engine/index.d.ts +17 -0
- package/dist/features/workflow-engine/index.d.ts.map +1 -0
- package/dist/features/workflow-engine/index.js +19 -0
- package/dist/features/workflow-engine/index.js.map +1 -0
- package/dist/features/workflow-engine/types.d.ts +220 -0
- package/dist/features/workflow-engine/types.d.ts.map +1 -0
- package/dist/features/workflow-engine/types.js +8 -0
- package/dist/features/workflow-engine/types.js.map +1 -0
- package/dist/features/workflow-engine/validation.d.ts +128 -0
- package/dist/features/workflow-engine/validation.d.ts.map +1 -0
- package/dist/features/workflow-engine/validation.js +746 -0
- package/dist/features/workflow-engine/validation.js.map +1 -0
- package/dist/hooks/ascent-verifier/index.d.ts +52 -0
- package/dist/hooks/ascent-verifier/index.d.ts.map +1 -1
- package/dist/hooks/ascent-verifier/index.js +146 -0
- package/dist/hooks/ascent-verifier/index.js.map +1 -1
- package/dist/hooks/registrations/learning-capture.d.ts.map +1 -1
- package/dist/hooks/registrations/learning-capture.js +32 -9
- package/dist/hooks/registrations/learning-capture.js.map +1 -1
- package/dist/hooks/registrations/user-prompt-submit.d.ts.map +1 -1
- package/dist/hooks/registrations/user-prompt-submit.js +85 -0
- package/dist/hooks/registrations/user-prompt-submit.js.map +1 -1
- package/dist/installer/index.d.ts.map +1 -1
- package/dist/installer/index.js +310 -1
- package/dist/installer/index.js.map +1 -1
- package/dist/learning/session-state.d.ts.map +1 -1
- package/dist/learning/session-state.js +17 -0
- package/dist/learning/session-state.js.map +1 -1
- package/dist/learning/types.d.ts +3 -0
- package/dist/learning/types.d.ts.map +1 -1
- package/dist/shared/types.d.ts +17 -0
- package/dist/shared/types.d.ts.map +1 -1
- package/package.json +3 -1
- package/scripts/dist/hooks/olympus-hooks.cjs +762 -97
- package/scripts/rebrand.mjs +0 -206
|
@@ -1,26 +1,32 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// Olympus Hooks Bundle - Generated by esbuild
|
|
3
|
-
"use strict";var
|
|
4
|
-
`)){let c=i.indexOf(":");if(c===-1)continue;let a=i.slice(0,c).trim(),l=i.slice(c+1).trim();(l.startsWith('"')&&l.endsWith('"')||l.startsWith("'")&&l.endsWith("'"))&&(l=l.slice(1,-1)),s[a]=l}return{data:s,body:r}}function fo(e,t){if(!(0,K.existsSync)(e))return[];let n;try{n=(0,K.readdirSync)(e,{withFileTypes:!0})}catch{return[]}let o=[];for(let r of n){if(!r.isFile()||!r.name.endsWith(".md"))continue;let s=(0,X.join)(e,r.name),i=(0,X.basename)(r.name,".md");try{let c=(0,K.readFileSync)(s,"utf-8"),{data:a,body:l}=go(c),u={name:i,description:a.description||"",argumentHint:a["argument-hint"],model:a.model,agent:a.agent};o.push({name:i,path:s,metadata:u,content:l,scope:t})}catch{continue}}return o}function Dt(){let e=(0,X.join)(po,"commands"),t=(0,X.join)(process.cwd(),".claude","commands"),n=(0,X.join)(po,"skills"),o=fo(e,"user"),r=fo(t,"project"),s=[];if((0,K.existsSync)(n))try{let i=(0,K.readdirSync)(n,{withFileTypes:!0});for(let c of i){if(!c.isDirectory())continue;let a=(0,X.join)(n,c.name,"SKILL.md");if((0,K.existsSync)(a))try{let l=(0,K.readFileSync)(a,"utf-8"),{data:u,body:d}=go(l),f={name:u.name||c.name,description:u.description||"",argumentHint:u["argument-hint"],model:u.model,agent:u.agent};s.push({name:u.name||c.name,path:a,metadata:f,content:d,scope:"skill"})}catch{continue}}}catch{}return[...r,...o,...s]}function Qe(e){return Dt().find(n=>n.name.toLowerCase()===e.toLowerCase())??null}function ta(e,t){return e.replace(/\$ARGUMENTS/g,t||"(no arguments provided)")}function na(e,t){let n=[];n.push(`<command-name>/${e.name}</command-name>
|
|
3
|
+
"use strict";var Su=Object.create;var Gt=Object.defineProperty;var Tu=Object.getOwnPropertyDescriptor;var wu=Object.getOwnPropertyNames;var _u=Object.getPrototypeOf,Ou=Object.prototype.hasOwnProperty;var O=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),vu=(e,t)=>{for(var n in t)Gt(e,n,{get:t[n],enumerable:!0})},Rr=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of wu(t))!Ou.call(e,r)&&r!==n&&Gt(e,r,{get:()=>t[r],enumerable:!(o=Tu(t,r))||o.enumerable});return e};var H=(e,t,n)=>(n=e!=null?Su(_u(e)):{},Rr(t||!e||!e.__esModule?Gt(n,"default",{value:e,enumerable:!0}):n,e)),Ru=e=>Rr(Gt({},"__esModule",{value:!0}),e);var W=O(to=>{"use strict";to.fromCallback=function(e){return Object.defineProperty(function(...t){if(typeof t[t.length-1]=="function")e.apply(this,t);else return new Promise((n,o)=>{t.push((r,i)=>r!=null?o(r):n(i)),e.apply(this,t)})},"name",{value:e.name})};to.fromPromise=function(e){return Object.defineProperty(function(...t){let n=t[t.length-1];if(typeof n!="function")return e.apply(this,t);t.pop(),e.apply(this,t).then(o=>n(null,o),n)},"name",{value:e.name})}});var Ii=O((_h,Ri)=>{var xe=require("constants"),Zu=process.cwd,Jt=null,ed=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return Jt||(Jt=Zu.call(process)),Jt};try{process.cwd()}catch{}typeof process.chdir=="function"&&(no=process.chdir,process.chdir=function(e){Jt=null,no.call(process,e)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,no));var no;Ri.exports=td;function td(e){xe.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&t(e),e.lutimes||n(e),e.chown=i(e.chown),e.fchown=i(e.fchown),e.lchown=i(e.lchown),e.chmod=o(e.chmod),e.fchmod=o(e.fchmod),e.lchmod=o(e.lchmod),e.chownSync=s(e.chownSync),e.fchownSync=s(e.fchownSync),e.lchownSync=s(e.lchownSync),e.chmodSync=r(e.chmodSync),e.fchmodSync=r(e.fchmodSync),e.lchmodSync=r(e.lchmodSync),e.stat=c(e.stat),e.fstat=c(e.fstat),e.lstat=c(e.lstat),e.statSync=a(e.statSync),e.fstatSync=a(e.fstatSync),e.lstatSync=a(e.lstatSync),e.chmod&&!e.lchmod&&(e.lchmod=function(u,d,f){f&&process.nextTick(f)},e.lchmodSync=function(){}),e.chown&&!e.lchown&&(e.lchown=function(u,d,f,g){g&&process.nextTick(g)},e.lchownSync=function(){}),ed==="win32"&&(e.rename=typeof e.rename!="function"?e.rename:(function(u){function d(f,g,m){var p=Date.now(),h=0;u(f,g,function y(T){if(T&&(T.code==="EACCES"||T.code==="EPERM"||T.code==="EBUSY")&&Date.now()-p<6e4){setTimeout(function(){e.stat(g,function(k,A){k&&k.code==="ENOENT"?u(f,g,y):m(T)})},h),h<100&&(h+=10);return}m&&m(T)})}return Object.setPrototypeOf&&Object.setPrototypeOf(d,u),d})(e.rename)),e.read=typeof e.read!="function"?e.read:(function(u){function d(f,g,m,p,h,y){var T;if(y&&typeof y=="function"){var k=0;T=function(A,D,R){if(A&&A.code==="EAGAIN"&&k<10)return k++,u.call(e,f,g,m,p,h,T);y.apply(this,arguments)}}return u.call(e,f,g,m,p,h,T)}return Object.setPrototypeOf&&Object.setPrototypeOf(d,u),d})(e.read),e.readSync=typeof e.readSync!="function"?e.readSync:(function(u){return function(d,f,g,m,p){for(var h=0;;)try{return u.call(e,d,f,g,m,p)}catch(y){if(y.code==="EAGAIN"&&h<10){h++;continue}throw y}}})(e.readSync);function t(u){u.lchmod=function(d,f,g){u.open(d,xe.O_WRONLY|xe.O_SYMLINK,f,function(m,p){if(m){g&&g(m);return}u.fchmod(p,f,function(h){u.close(p,function(y){g&&g(h||y)})})})},u.lchmodSync=function(d,f){var g=u.openSync(d,xe.O_WRONLY|xe.O_SYMLINK,f),m=!0,p;try{p=u.fchmodSync(g,f),m=!1}finally{if(m)try{u.closeSync(g)}catch{}else u.closeSync(g)}return p}}function n(u){xe.hasOwnProperty("O_SYMLINK")&&u.futimes?(u.lutimes=function(d,f,g,m){u.open(d,xe.O_SYMLINK,function(p,h){if(p){m&&m(p);return}u.futimes(h,f,g,function(y){u.close(h,function(T){m&&m(y||T)})})})},u.lutimesSync=function(d,f,g){var m=u.openSync(d,xe.O_SYMLINK),p,h=!0;try{p=u.futimesSync(m,f,g),h=!1}finally{if(h)try{u.closeSync(m)}catch{}else u.closeSync(m)}return p}):u.futimes&&(u.lutimes=function(d,f,g,m){m&&process.nextTick(m)},u.lutimesSync=function(){})}function o(u){return u&&function(d,f,g){return u.call(e,d,f,function(m){l(m)&&(m=null),g&&g.apply(this,arguments)})}}function r(u){return u&&function(d,f){try{return u.call(e,d,f)}catch(g){if(!l(g))throw g}}}function i(u){return u&&function(d,f,g,m){return u.call(e,d,f,g,function(p){l(p)&&(p=null),m&&m.apply(this,arguments)})}}function s(u){return u&&function(d,f,g){try{return u.call(e,d,f,g)}catch(m){if(!l(m))throw m}}}function c(u){return u&&function(d,f,g){typeof f=="function"&&(g=f,f=null);function m(p,h){h&&(h.uid<0&&(h.uid+=4294967296),h.gid<0&&(h.gid+=4294967296)),g&&g.apply(this,arguments)}return f?u.call(e,d,f,m):u.call(e,d,m)}}function a(u){return u&&function(d,f){var g=f?u.call(e,d,f):u.call(e,d);return g&&(g.uid<0&&(g.uid+=4294967296),g.gid<0&&(g.gid+=4294967296)),g}}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 Ci=O((Oh,bi)=>{var Ai=require("stream").Stream;bi.exports=nd;function nd(e){return{ReadStream:t,WriteStream:n};function t(o,r){if(!(this instanceof t))return new t(o,r);Ai.call(this);var i=this;this.path=o,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=64*1024,r=r||{};for(var s=Object.keys(r),c=0,a=s.length;c<a;c++){var l=s[c];this[l]=r[l]}if(this.encoding&&this.setEncoding(this.encoding),this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.end===void 0)this.end=1/0;else if(typeof this.end!="number")throw TypeError("end must be a Number");if(this.start>this.end)throw new Error("start must be <= end");this.pos=this.start}if(this.fd!==null){process.nextTick(function(){i._read()});return}e.open(this.path,this.flags,this.mode,function(u,d){if(u){i.emit("error",u),i.readable=!1;return}i.fd=d,i.emit("open",d),i._read()})}function n(o,r){if(!(this instanceof n))return new n(o,r);Ai.call(this),this.path=o,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,r=r||{};for(var i=Object.keys(r),s=0,c=i.length;s<c;s++){var a=i[s];this[a]=r[a]}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 Pi=O((vh,Ni)=>{"use strict";Ni.exports=rd;var od=Object.getPrototypeOf||function(e){return e.__proto__};function rd(e){if(e===null||typeof e!="object")return e;if(e instanceof Object)var t={__proto__:od(e)};else var t=Object.create(null);return Object.getOwnPropertyNames(e).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(e,n))}),t}});var nt=O((Rh,io)=>{var L=require("fs"),id=Ii(),sd=Ci(),ad=Pi(),zt=require("util"),Y,Qt;typeof Symbol=="function"&&typeof Symbol.for=="function"?(Y=Symbol.for("graceful-fs.queue"),Qt=Symbol.for("graceful-fs.previous")):(Y="___graceful-fs.queue",Qt="___graceful-fs.previous");function cd(){}function Li(e,t){Object.defineProperty(e,Y,{get:function(){return t}})}var Be=cd;zt.debuglog?Be=zt.debuglog("gfs4"):/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&(Be=function(){var e=zt.format.apply(zt,arguments);e="GFS4: "+e.split(/\n/).join(`
|
|
4
|
+
GFS4: `),console.error(e)});L[Y]||(xi=global[Y]||[],Li(L,xi),L.close=(function(e){function t(n,o){return e.call(L,n,function(r){r||Di(),typeof o=="function"&&o.apply(this,arguments)})}return Object.defineProperty(t,Qt,{value:e}),t})(L.close),L.closeSync=(function(e){function t(n){e.apply(L,arguments),Di()}return Object.defineProperty(t,Qt,{value:e}),t})(L.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&process.on("exit",function(){Be(L[Y]),require("assert").equal(L[Y].length,0)}));var xi;global[Y]||Li(global,L[Y]);io.exports=oo(ad(L));process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!L.__patched&&(io.exports=oo(L),L.__patched=!0);function oo(e){id(e),e.gracefulify=oo,e.createReadStream=D,e.createWriteStream=R;var t=e.readFile;e.readFile=n;function n(S,b,I){return typeof b=="function"&&(I=b,b=null),F(S,b,I);function F(M,E,_,P){return t(M,E,function(C){C&&(C.code==="EMFILE"||C.code==="ENFILE")?tt([F,[M,E,_],C,P||Date.now(),Date.now()]):typeof _=="function"&&_.apply(this,arguments)})}}var o=e.writeFile;e.writeFile=r;function r(S,b,I,F){return typeof I=="function"&&(F=I,I=null),M(S,b,I,F);function M(E,_,P,C,B){return o(E,_,P,function(x){x&&(x.code==="EMFILE"||x.code==="ENFILE")?tt([M,[E,_,P,C],x,B||Date.now(),Date.now()]):typeof C=="function"&&C.apply(this,arguments)})}}var i=e.appendFile;i&&(e.appendFile=s);function s(S,b,I,F){return typeof I=="function"&&(F=I,I=null),M(S,b,I,F);function M(E,_,P,C,B){return i(E,_,P,function(x){x&&(x.code==="EMFILE"||x.code==="ENFILE")?tt([M,[E,_,P,C],x,B||Date.now(),Date.now()]):typeof C=="function"&&C.apply(this,arguments)})}}var c=e.copyFile;c&&(e.copyFile=a);function a(S,b,I,F){return typeof I=="function"&&(F=I,I=0),M(S,b,I,F);function M(E,_,P,C,B){return c(E,_,P,function(x){x&&(x.code==="EMFILE"||x.code==="ENFILE")?tt([M,[E,_,P,C],x,B||Date.now(),Date.now()]):typeof C=="function"&&C.apply(this,arguments)})}}var l=e.readdir;e.readdir=d;var u=/^v[0-5]\./;function d(S,b,I){typeof b=="function"&&(I=b,b=null);var F=u.test(process.version)?function(_,P,C,B){return l(_,M(_,P,C,B))}:function(_,P,C,B){return l(_,P,M(_,P,C,B))};return F(S,b,I);function M(E,_,P,C){return function(B,x){B&&(B.code==="EMFILE"||B.code==="ENFILE")?tt([F,[E,_,P],B,C||Date.now(),Date.now()]):(x&&x.sort&&x.sort(),typeof P=="function"&&P.call(this,B,x))}}}if(process.version.substr(0,4)==="v0.8"){var f=sd(e);y=f.ReadStream,k=f.WriteStream}var g=e.ReadStream;g&&(y.prototype=Object.create(g.prototype),y.prototype.open=T);var m=e.WriteStream;m&&(k.prototype=Object.create(m.prototype),k.prototype.open=A),Object.defineProperty(e,"ReadStream",{get:function(){return y},set:function(S){y=S},enumerable:!0,configurable:!0}),Object.defineProperty(e,"WriteStream",{get:function(){return k},set:function(S){k=S},enumerable:!0,configurable:!0});var p=y;Object.defineProperty(e,"FileReadStream",{get:function(){return p},set:function(S){p=S},enumerable:!0,configurable:!0});var h=k;Object.defineProperty(e,"FileWriteStream",{get:function(){return h},set:function(S){h=S},enumerable:!0,configurable:!0});function y(S,b){return this instanceof y?(g.apply(this,arguments),this):y.apply(Object.create(y.prototype),arguments)}function T(){var S=this;ke(S.path,S.flags,S.mode,function(b,I){b?(S.autoClose&&S.destroy(),S.emit("error",b)):(S.fd=I,S.emit("open",I),S.read())})}function k(S,b){return this instanceof k?(m.apply(this,arguments),this):k.apply(Object.create(k.prototype),arguments)}function A(){var S=this;ke(S.path,S.flags,S.mode,function(b,I){b?(S.destroy(),S.emit("error",b)):(S.fd=I,S.emit("open",I))})}function D(S,b){return new e.ReadStream(S,b)}function R(S,b){return new e.WriteStream(S,b)}var w=e.open;e.open=ke;function ke(S,b,I,F){return typeof I=="function"&&(F=I,I=null),M(S,b,I,F);function M(E,_,P,C,B){return w(E,_,P,function(x,Ng){x&&(x.code==="EMFILE"||x.code==="ENFILE")?tt([M,[E,_,P,C],x,B||Date.now(),Date.now()]):typeof C=="function"&&C.apply(this,arguments)})}}return e}function tt(e){Be("ENQUEUE",e[0].name,e[1]),L[Y].push(e),ro()}var Xt;function Di(){for(var e=Date.now(),t=0;t<L[Y].length;++t)L[Y][t].length>2&&(L[Y][t][3]=e,L[Y][t][4]=e);ro()}function ro(){if(clearTimeout(Xt),Xt=void 0,L[Y].length!==0){var e=L[Y].shift(),t=e[0],n=e[1],o=e[2],r=e[3],i=e[4];if(r===void 0)Be("RETRY",t.name,n),t.apply(null,n);else if(Date.now()-r>=6e4){Be("TIMEOUT",t.name,n);var s=n.pop();typeof s=="function"&&s.call(null,o)}else{var c=Date.now()-i,a=Math.max(i-r,1),l=Math.min(a*1.2,100);c>=l?(Be("RETRY",t.name,n),t.apply(null,n.concat([r]))):L[Y].push(e)}Xt===void 0&&(Xt=setTimeout(ro,0))}}});var X=O(_e=>{"use strict";var Mi=W().fromCallback,z=nt(),ld=["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 z[e]=="function");Object.assign(_e,z);ld.forEach(e=>{_e[e]=Mi(z[e])});_e.exists=function(e,t){return typeof t=="function"?z.exists(e,t):new Promise(n=>z.exists(e,n))};_e.read=function(e,t,n,o,r,i){return typeof i=="function"?z.read(e,t,n,o,r,i):new Promise((s,c)=>{z.read(e,t,n,o,r,(a,l,u)=>{if(a)return c(a);s({bytesRead:l,buffer:u})})})};_e.write=function(e,t,...n){return typeof n[n.length-1]=="function"?z.write(e,t,...n):new Promise((o,r)=>{z.write(e,t,...n,(i,s,c)=>{if(i)return r(i);o({bytesWritten:s,buffer:c})})})};_e.readv=function(e,t,...n){return typeof n[n.length-1]=="function"?z.readv(e,t,...n):new Promise((o,r)=>{z.readv(e,t,...n,(i,s,c)=>{if(i)return r(i);o({bytesRead:s,buffers:c})})})};_e.writev=function(e,t,...n){return typeof n[n.length-1]=="function"?z.writev(e,t,...n):new Promise((o,r)=>{z.writev(e,t,...n,(i,s,c)=>{if(i)return r(i);o({bytesWritten:s,buffers:c})})})};typeof z.realpath.native=="function"?_e.realpath.native=Mi(z.realpath.native):process.emitWarning("fs.realpath.native is not a function. Is fs being monkey-patched?","Warning","fs-extra-WARN0003")});var Fi=O((Ah,$i)=>{"use strict";var ud=require("path");$i.exports.checkPath=function(t){if(process.platform==="win32"&&/[<>:"|?*]/.test(t.replace(ud.parse(t).root,""))){let o=new Error(`Path contains invalid characters: ${t}`);throw o.code="EINVAL",o}}});var Wi=O((bh,so)=>{"use strict";var Ui=X(),{checkPath:ji}=Fi(),Hi=e=>{let t={mode:511};return typeof e=="number"?e:{...t,...e}.mode};so.exports.makeDir=async(e,t)=>(ji(e),Ui.mkdir(e,{mode:Hi(t),recursive:!0}));so.exports.makeDirSync=(e,t)=>(ji(e),Ui.mkdirSync(e,{mode:Hi(t),recursive:!0}))});var pe=O((Ch,Gi)=>{"use strict";var dd=W().fromPromise,{makeDir:fd,makeDirSync:ao}=Wi(),co=dd(fd);Gi.exports={mkdirs:co,mkdirsSync:ao,mkdirp:co,mkdirpSync:ao,ensureDir:co,ensureDirSync:ao}});var De=O((Nh,qi)=>{"use strict";var pd=W().fromPromise,Bi=X();function md(e){return Bi.access(e).then(()=>!0).catch(()=>!1)}qi.exports={pathExists:pd(md),pathExistsSync:Bi.existsSync}});var lo=O((Ph,Yi)=>{"use strict";var ot=X(),gd=W().fromPromise;async function hd(e,t,n){let o=await ot.open(e,"r+"),r=null;try{await ot.futimes(o,t,n)}finally{try{await ot.close(o)}catch(i){r=i}}if(r)throw r}function kd(e,t,n){let o=ot.openSync(e,"r+");return ot.futimesSync(o,t,n),ot.closeSync(o)}Yi.exports={utimesMillis:gd(hd),utimesMillisSync:kd}});var qe=O((xh,zi)=>{"use strict";var rt=X(),G=require("path"),Vi=W().fromPromise;function yd(e,t,n){let o=n.dereference?r=>rt.stat(r,{bigint:!0}):r=>rt.lstat(r,{bigint:!0});return Promise.all([o(e),o(t).catch(r=>{if(r.code==="ENOENT")return null;throw r})]).then(([r,i])=>({srcStat:r,destStat:i}))}function Ed(e,t,n){let o,r=n.dereference?s=>rt.statSync(s,{bigint:!0}):s=>rt.lstatSync(s,{bigint:!0}),i=r(e);try{o=r(t)}catch(s){if(s.code==="ENOENT")return{srcStat:i,destStat:null};throw s}return{srcStat:i,destStat:o}}async function Sd(e,t,n,o){let{srcStat:r,destStat:i}=await yd(e,t,o);if(i){if(Et(r,i)){let s=G.basename(e),c=G.basename(t);if(n==="move"&&s!==c&&s.toLowerCase()===c.toLowerCase())return{srcStat:r,destStat:i,isChangingCase:!0};throw new Error("Source and destination must not be the same.")}if(r.isDirectory()&&!i.isDirectory())throw new Error(`Cannot overwrite non-directory '${t}' with directory '${e}'.`);if(!r.isDirectory()&&i.isDirectory())throw new Error(`Cannot overwrite directory '${t}' with non-directory '${e}'.`)}if(r.isDirectory()&&uo(e,t))throw new Error(Zt(e,t,n));return{srcStat:r,destStat:i}}function Td(e,t,n,o){let{srcStat:r,destStat:i}=Ed(e,t,o);if(i){if(Et(r,i)){let s=G.basename(e),c=G.basename(t);if(n==="move"&&s!==c&&s.toLowerCase()===c.toLowerCase())return{srcStat:r,destStat:i,isChangingCase:!0};throw new Error("Source and destination must not be the same.")}if(r.isDirectory()&&!i.isDirectory())throw new Error(`Cannot overwrite non-directory '${t}' with directory '${e}'.`);if(!r.isDirectory()&&i.isDirectory())throw new Error(`Cannot overwrite directory '${t}' with non-directory '${e}'.`)}if(r.isDirectory()&&uo(e,t))throw new Error(Zt(e,t,n));return{srcStat:r,destStat:i}}async function Ki(e,t,n,o){let r=G.resolve(G.dirname(e)),i=G.resolve(G.dirname(n));if(i===r||i===G.parse(i).root)return;let s;try{s=await rt.stat(i,{bigint:!0})}catch(c){if(c.code==="ENOENT")return;throw c}if(Et(t,s))throw new Error(Zt(e,n,o));return Ki(e,t,i,o)}function Ji(e,t,n,o){let r=G.resolve(G.dirname(e)),i=G.resolve(G.dirname(n));if(i===r||i===G.parse(i).root)return;let s;try{s=rt.statSync(i,{bigint:!0})}catch(c){if(c.code==="ENOENT")return;throw c}if(Et(t,s))throw new Error(Zt(e,n,o));return Ji(e,t,i,o)}function Et(e,t){return t.ino!==void 0&&t.dev!==void 0&&t.ino===e.ino&&t.dev===e.dev}function uo(e,t){let n=G.resolve(e).split(G.sep).filter(r=>r),o=G.resolve(t).split(G.sep).filter(r=>r);return n.every((r,i)=>o[i]===r)}function Zt(e,t,n){return`Cannot ${n} '${e}' to a subdirectory of itself, '${t}'.`}zi.exports={checkPaths:Vi(Sd),checkPathsSync:Td,checkParentPaths:Vi(Ki),checkParentPathsSync:Ji,isSrcSubdir:uo,areIdentical:Et}});var Qi=O((Dh,Xi)=>{"use strict";async function wd(e,t){let n=[];for await(let o of e)n.push(t(o).then(()=>null,r=>r??new Error("unknown error")));await Promise.all(n.map(o=>o.then(r=>{if(r!==null)throw r})))}Xi.exports={asyncIteratorConcurrentProcess:wd}});var os=O((Lh,ns)=>{"use strict";var K=X(),St=require("path"),{mkdirs:_d}=pe(),{pathExists:Od}=De(),{utimesMillis:vd}=lo(),Tt=qe(),{asyncIteratorConcurrentProcess:Rd}=Qi();async function Id(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;
|
|
5
|
+
|
|
6
|
+
see https://github.com/jprichardson/node-fs-extra/issues/269`,"Warning","fs-extra-WARN0001");let{srcStat:o,destStat:r}=await Tt.checkPaths(e,t,"copy",n);if(await Tt.checkParentPaths(e,o,t,"copy"),!await es(e,t,n))return;let s=St.dirname(t);await Od(s)||await _d(s),await ts(r,e,t,n)}async function es(e,t,n){return n.filter?n.filter(e,t):!0}async function ts(e,t,n,o){let i=await(o.dereference?K.stat:K.lstat)(t);if(i.isDirectory())return Nd(i,e,t,n,o);if(i.isFile()||i.isCharacterDevice()||i.isBlockDevice())return Ad(i,e,t,n,o);if(i.isSymbolicLink())return Pd(e,t,n,o);throw i.isSocket()?new Error(`Cannot copy a socket file: ${t}`):i.isFIFO()?new Error(`Cannot copy a FIFO pipe: ${t}`):new Error(`Unknown file: ${t}`)}async function Ad(e,t,n,o,r){if(!t)return Zi(e,n,o,r);if(r.overwrite)return await K.unlink(o),Zi(e,n,o,r);if(r.errorOnExist)throw new Error(`'${o}' already exists`)}async function Zi(e,t,n,o){if(await K.copyFile(t,n),o.preserveTimestamps){bd(e.mode)&&await Cd(n,e.mode);let r=await K.stat(t);await vd(n,r.atime,r.mtime)}return K.chmod(n,e.mode)}function bd(e){return(e&128)===0}function Cd(e,t){return K.chmod(e,t|128)}async function Nd(e,t,n,o,r){t||await K.mkdir(o),await Rd(await K.opendir(n),async i=>{let s=St.join(n,i.name),c=St.join(o,i.name);if(await es(s,c,r)){let{destStat:l}=await Tt.checkPaths(s,c,"copy",r);await ts(l,s,c,r)}}),t||await K.chmod(o,e.mode)}async function Pd(e,t,n,o){let r=await K.readlink(t);if(o.dereference&&(r=St.resolve(process.cwd(),r)),!e)return K.symlink(r,n);let i=null;try{i=await K.readlink(n)}catch(s){if(s.code==="EINVAL"||s.code==="UNKNOWN")return K.symlink(r,n);throw s}if(o.dereference&&(i=St.resolve(process.cwd(),i)),r!==i){if(Tt.isSrcSubdir(r,i))throw new Error(`Cannot copy '${r}' to a subdirectory of itself, '${i}'.`);if(Tt.isSrcSubdir(i,r))throw new Error(`Cannot overwrite '${i}' with '${r}'.`)}return await K.unlink(n),K.symlink(r,n)}ns.exports=Id});var cs=O((Mh,as)=>{"use strict";var Q=nt(),wt=require("path"),xd=pe().mkdirsSync,Dd=lo().utimesMillisSync,_t=qe();function Ld(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;
|
|
7
|
+
|
|
8
|
+
see https://github.com/jprichardson/node-fs-extra/issues/269`,"Warning","fs-extra-WARN0002");let{srcStat:o,destStat:r}=_t.checkPathsSync(e,t,"copy",n);if(_t.checkParentPathsSync(e,o,t,"copy"),n.filter&&!n.filter(e,t))return;let i=wt.dirname(t);return Q.existsSync(i)||xd(i),rs(r,e,t,n)}function rs(e,t,n,o){let i=(o.dereference?Q.statSync:Q.lstatSync)(t);if(i.isDirectory())return Wd(i,e,t,n,o);if(i.isFile()||i.isCharacterDevice()||i.isBlockDevice())return Md(i,e,t,n,o);if(i.isSymbolicLink())return qd(e,t,n,o);throw i.isSocket()?new Error(`Cannot copy a socket file: ${t}`):i.isFIFO()?new Error(`Cannot copy a FIFO pipe: ${t}`):new Error(`Unknown file: ${t}`)}function Md(e,t,n,o,r){return t?$d(e,n,o,r):is(e,n,o,r)}function $d(e,t,n,o){if(o.overwrite)return Q.unlinkSync(n),is(e,t,n,o);if(o.errorOnExist)throw new Error(`'${n}' already exists`)}function is(e,t,n,o){return Q.copyFileSync(t,n),o.preserveTimestamps&&Fd(e.mode,t,n),fo(n,e.mode)}function Fd(e,t,n){return Ud(e)&&jd(n,e),Hd(t,n)}function Ud(e){return(e&128)===0}function jd(e,t){return fo(e,t|128)}function fo(e,t){return Q.chmodSync(e,t)}function Hd(e,t){let n=Q.statSync(e);return Dd(t,n.atime,n.mtime)}function Wd(e,t,n,o,r){return t?ss(n,o,r):Gd(e.mode,n,o,r)}function Gd(e,t,n,o){return Q.mkdirSync(n),ss(t,n,o),fo(n,e)}function ss(e,t,n){let o=Q.opendirSync(e);try{let r;for(;(r=o.readSync())!==null;)Bd(r.name,e,t,n)}finally{o.closeSync()}}function Bd(e,t,n,o){let r=wt.join(t,e),i=wt.join(n,e);if(o.filter&&!o.filter(r,i))return;let{destStat:s}=_t.checkPathsSync(r,i,"copy",o);return rs(s,r,i,o)}function qd(e,t,n,o){let r=Q.readlinkSync(t);if(o.dereference&&(r=wt.resolve(process.cwd(),r)),e){let i;try{i=Q.readlinkSync(n)}catch(s){if(s.code==="EINVAL"||s.code==="UNKNOWN")return Q.symlinkSync(r,n);throw s}if(o.dereference&&(i=wt.resolve(process.cwd(),i)),r!==i){if(_t.isSrcSubdir(r,i))throw new Error(`Cannot copy '${r}' to a subdirectory of itself, '${i}'.`);if(_t.isSrcSubdir(i,r))throw new Error(`Cannot overwrite '${i}' with '${r}'.`)}return Yd(r,n)}else return Q.symlinkSync(r,n)}function Yd(e,t){return Q.unlinkSync(t),Q.symlinkSync(e,t)}as.exports=Ld});var en=O(($h,ls)=>{"use strict";var Vd=W().fromPromise;ls.exports={copy:Vd(os()),copySync:cs()}});var Ot=O((Fh,ds)=>{"use strict";var us=nt(),Kd=W().fromCallback;function Jd(e,t){us.rm(e,{recursive:!0,force:!0},t)}function zd(e){us.rmSync(e,{recursive:!0,force:!0})}ds.exports={remove:Kd(Jd),removeSync:zd}});var Es=O((Uh,ys)=>{"use strict";var Xd=W().fromPromise,ms=X(),gs=require("path"),hs=pe(),ks=Ot(),fs=Xd(async function(t){let n;try{n=await ms.readdir(t)}catch{return hs.mkdirs(t)}return Promise.all(n.map(o=>ks.remove(gs.join(t,o))))});function ps(e){let t;try{t=ms.readdirSync(e)}catch{return hs.mkdirsSync(e)}t.forEach(n=>{n=gs.join(e,n),ks.removeSync(n)})}ys.exports={emptyDirSync:ps,emptydirSync:ps,emptyDir:fs,emptydir:fs}});var _s=O((jh,ws)=>{"use strict";var Qd=W().fromPromise,Ss=require("path"),Oe=X(),Ts=pe();async function Zd(e){let t;try{t=await Oe.stat(e)}catch{}if(t&&t.isFile())return;let n=Ss.dirname(e),o=null;try{o=await Oe.stat(n)}catch(r){if(r.code==="ENOENT"){await Ts.mkdirs(n),await Oe.writeFile(e,"");return}else throw r}o.isDirectory()?await Oe.writeFile(e,""):await Oe.readdir(n)}function ef(e){let t;try{t=Oe.statSync(e)}catch{}if(t&&t.isFile())return;let n=Ss.dirname(e);try{Oe.statSync(n).isDirectory()||Oe.readdirSync(n)}catch(o){if(o&&o.code==="ENOENT")Ts.mkdirsSync(n);else throw o}Oe.writeFileSync(e,"")}ws.exports={createFile:Qd(Zd),createFileSync:ef}});var As=O((Hh,Is)=>{"use strict";var tf=W().fromPromise,Os=require("path"),Le=X(),vs=pe(),{pathExists:nf}=De(),{areIdentical:Rs}=qe();async function of(e,t){let n;try{n=await Le.lstat(t)}catch{}let o;try{o=await Le.lstat(e)}catch(s){throw s.message=s.message.replace("lstat","ensureLink"),s}if(n&&Rs(o,n))return;let r=Os.dirname(t);await nf(r)||await vs.mkdirs(r),await Le.link(e,t)}function rf(e,t){let n;try{n=Le.lstatSync(t)}catch{}try{let i=Le.lstatSync(e);if(n&&Rs(i,n))return}catch(i){throw i.message=i.message.replace("lstat","ensureLink"),i}let o=Os.dirname(t);return Le.existsSync(o)||vs.mkdirsSync(o),Le.linkSync(e,t)}Is.exports={createLink:tf(of),createLinkSync:rf}});var Cs=O((Wh,bs)=>{"use strict";var Me=require("path"),vt=X(),{pathExists:sf}=De(),af=W().fromPromise;async function cf(e,t){if(Me.isAbsolute(e)){try{await vt.lstat(e)}catch(i){throw i.message=i.message.replace("lstat","ensureSymlink"),i}return{toCwd:e,toDst:e}}let n=Me.dirname(t),o=Me.join(n,e);if(await sf(o))return{toCwd:o,toDst:e};try{await vt.lstat(e)}catch(i){throw i.message=i.message.replace("lstat","ensureSymlink"),i}return{toCwd:e,toDst:Me.relative(n,e)}}function lf(e,t){if(Me.isAbsolute(e)){if(!vt.existsSync(e))throw new Error("absolute srcpath does not exist");return{toCwd:e,toDst:e}}let n=Me.dirname(t),o=Me.join(n,e);if(vt.existsSync(o))return{toCwd:o,toDst:e};if(!vt.existsSync(e))throw new Error("relative srcpath does not exist");return{toCwd:e,toDst:Me.relative(n,e)}}bs.exports={symlinkPaths:af(cf),symlinkPathsSync:lf}});var xs=O((Gh,Ps)=>{"use strict";var Ns=X(),uf=W().fromPromise;async function df(e,t){if(t)return t;let n;try{n=await Ns.lstat(e)}catch{return"file"}return n&&n.isDirectory()?"dir":"file"}function ff(e,t){if(t)return t;let n;try{n=Ns.lstatSync(e)}catch{return"file"}return n&&n.isDirectory()?"dir":"file"}Ps.exports={symlinkType:uf(df),symlinkTypeSync:ff}});var $s=O((Bh,Ms)=>{"use strict";var pf=W().fromPromise,Ds=require("path"),Se=X(),{mkdirs:mf,mkdirsSync:gf}=pe(),{symlinkPaths:hf,symlinkPathsSync:kf}=Cs(),{symlinkType:yf,symlinkTypeSync:Ef}=xs(),{pathExists:Sf}=De(),{areIdentical:Ls}=qe();async function Tf(e,t,n){let o;try{o=await Se.lstat(t)}catch{}if(o&&o.isSymbolicLink()){let[c,a]=await Promise.all([Se.stat(e),Se.stat(t)]);if(Ls(c,a))return}let r=await hf(e,t);e=r.toDst;let i=await yf(r.toCwd,n),s=Ds.dirname(t);return await Sf(s)||await mf(s),Se.symlink(e,t,i)}function wf(e,t,n){let o;try{o=Se.lstatSync(t)}catch{}if(o&&o.isSymbolicLink()){let c=Se.statSync(e),a=Se.statSync(t);if(Ls(c,a))return}let r=kf(e,t);e=r.toDst,n=Ef(r.toCwd,n);let i=Ds.dirname(t);return Se.existsSync(i)||gf(i),Se.symlinkSync(e,t,n)}Ms.exports={createSymlink:pf(Tf),createSymlinkSync:wf}});var qs=O((qh,Bs)=>{"use strict";var{createFile:Fs,createFileSync:Us}=_s(),{createLink:js,createLinkSync:Hs}=As(),{createSymlink:Ws,createSymlinkSync:Gs}=$s();Bs.exports={createFile:Fs,createFileSync:Us,ensureFile:Fs,ensureFileSync:Us,createLink:js,createLinkSync:Hs,ensureLink:js,ensureLinkSync:Hs,createSymlink:Ws,createSymlinkSync:Gs,ensureSymlink:Ws,ensureSymlinkSync:Gs}});var tn=O((Yh,Ys)=>{function _f(e,{EOL:t=`
|
|
9
|
+
`,finalEOL:n=!0,replacer:o=null,spaces:r}={}){let i=n?t:"";return JSON.stringify(e,o,r).replace(/\n/g,t)+i}function Of(e){return Buffer.isBuffer(e)&&(e=e.toString("utf8")),e.replace(/^\uFEFF/,"")}Ys.exports={stringify:_f,stripBom:Of}});var zs=O((Vh,Js)=>{var it;try{it=nt()}catch{it=require("fs")}var nn=W(),{stringify:Vs,stripBom:Ks}=tn();async function vf(e,t={}){typeof t=="string"&&(t={encoding:t});let n=t.fs||it,o="throws"in t?t.throws:!0,r=await nn.fromCallback(n.readFile)(e,t);r=Ks(r);let i;try{i=JSON.parse(r,t?t.reviver:null)}catch(s){if(o)throw s.message=`${e}: ${s.message}`,s;return null}return i}var Rf=nn.fromPromise(vf);function If(e,t={}){typeof t=="string"&&(t={encoding:t});let n=t.fs||it,o="throws"in t?t.throws:!0;try{let r=n.readFileSync(e,t);return r=Ks(r),JSON.parse(r,t.reviver)}catch(r){if(o)throw r.message=`${e}: ${r.message}`,r;return null}}async function Af(e,t,n={}){let o=n.fs||it,r=Vs(t,n);await nn.fromCallback(o.writeFile)(e,r,n)}var bf=nn.fromPromise(Af);function Cf(e,t,n={}){let o=n.fs||it,r=Vs(t,n);return o.writeFileSync(e,r,n)}Js.exports={readFile:Rf,readFileSync:If,writeFile:bf,writeFileSync:Cf}});var Qs=O((Kh,Xs)=>{"use strict";var on=zs();Xs.exports={readJson:on.readFile,readJsonSync:on.readFileSync,writeJson:on.writeFile,writeJsonSync:on.writeFileSync}});var rn=O((Jh,ta)=>{"use strict";var Nf=W().fromPromise,po=X(),Zs=require("path"),ea=pe(),Pf=De().pathExists;async function xf(e,t,n="utf-8"){let o=Zs.dirname(e);return await Pf(o)||await ea.mkdirs(o),po.writeFile(e,t,n)}function Df(e,...t){let n=Zs.dirname(e);po.existsSync(n)||ea.mkdirsSync(n),po.writeFileSync(e,...t)}ta.exports={outputFile:Nf(xf),outputFileSync:Df}});var oa=O((zh,na)=>{"use strict";var{stringify:Lf}=tn(),{outputFile:Mf}=rn();async function $f(e,t,n={}){let o=Lf(t,n);await Mf(e,o,n)}na.exports=$f});var ia=O((Xh,ra)=>{"use strict";var{stringify:Ff}=tn(),{outputFileSync:Uf}=rn();function jf(e,t,n){let o=Ff(t,n);Uf(e,o,n)}ra.exports=jf});var aa=O((Qh,sa)=>{"use strict";var Hf=W().fromPromise,Z=Qs();Z.outputJson=Hf(oa());Z.outputJsonSync=ia();Z.outputJSON=Z.outputJson;Z.outputJSONSync=Z.outputJsonSync;Z.writeJSON=Z.writeJson;Z.writeJSONSync=Z.writeJsonSync;Z.readJSON=Z.readJson;Z.readJSONSync=Z.readJsonSync;sa.exports=Z});var fa=O((Zh,da)=>{"use strict";var Wf=X(),ca=require("path"),{copy:Gf}=en(),{remove:ua}=Ot(),{mkdirp:Bf}=pe(),{pathExists:qf}=De(),la=qe();async function Yf(e,t,n={}){let o=n.overwrite||n.clobber||!1,{srcStat:r,isChangingCase:i=!1}=await la.checkPaths(e,t,"move",n);await la.checkParentPaths(e,r,t,"move");let s=ca.dirname(t);return ca.parse(s).root!==s&&await Bf(s),Vf(e,t,o,i)}async function Vf(e,t,n,o){if(!o){if(n)await ua(t);else if(await qf(t))throw new Error("dest already exists.")}try{await Wf.rename(e,t)}catch(r){if(r.code!=="EXDEV")throw r;await Kf(e,t,n)}}async function Kf(e,t,n){return await Gf(e,t,{overwrite:n,errorOnExist:!0,preserveTimestamps:!0}),ua(e)}da.exports=Yf});var ka=O((ek,ha)=>{"use strict";var ma=nt(),go=require("path"),Jf=en().copySync,ga=Ot().removeSync,zf=pe().mkdirpSync,pa=qe();function Xf(e,t,n){n=n||{};let o=n.overwrite||n.clobber||!1,{srcStat:r,isChangingCase:i=!1}=pa.checkPathsSync(e,t,"move",n);return pa.checkParentPathsSync(e,r,t,"move"),Qf(t)||zf(go.dirname(t)),Zf(e,t,o,i)}function Qf(e){let t=go.dirname(e);return go.parse(t).root===t}function Zf(e,t,n,o){if(o)return mo(e,t,n);if(n)return ga(t),mo(e,t,n);if(ma.existsSync(t))throw new Error("dest already exists.");return mo(e,t,n)}function mo(e,t,n){try{ma.renameSync(e,t)}catch(o){if(o.code!=="EXDEV")throw o;return ep(e,t,n)}}function ep(e,t,n){return Jf(e,t,{overwrite:n,errorOnExist:!0,preserveTimestamps:!0}),ga(e)}ha.exports=Xf});var Ea=O((tk,ya)=>{"use strict";var tp=W().fromPromise;ya.exports={move:tp(fa()),moveSync:ka()}});var sn=O((nk,Sa)=>{"use strict";Sa.exports={...X(),...en(),...Es(),...qs(),...aa(),...pe(),...Ea(),...rn(),...De(),...Ot()}});var Cg={};vu(Cg,{main:()=>Eu});module.exports=Ru(Cg);var Hn=new Map;function v(e){let t=Hn.get(e.event)||[];t.push(e),t.sort((n,o)=>(n.priority??100)-(o.priority??100)),Hn.set(e.event,t)}function Ir(e){return Hn.get(e)||[]}var Iu={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},Au=["ultrawork","ultrathink","olympus","search","analyze"];function Ar(e){let t=e.replace(/```[\s\S]*?```/g,"");return t=t.replace(/~~~[\s\S]*?~~~/g,""),t=t.replace(/`[^`]+`/g,""),t}function br(e,t){let n=[];for(let o of Au){let r=Iu[o],i=e.match(r);i&&i.index!==void 0&&n.push({type:o,keyword:i[0],position:i.index})}return n}var Cr="auto-slash-command",Bt="<auto-slash-command>",qt="</auto-slash-command>",Nr=/^\/([a-zA-Z][\w-]*)\s*(.*)/,Pr=new Set(["ascent","cancel-ascent","help","clear","history","exit","quit"]);var bu=/```[\s\S]*?```/g;function xr(e){return e.replace(bu,"")}function Dr(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.match(Nr);if(!n)return null;let[o,r,i]=n;return{command:r.toLowerCase(),args:i.trim(),raw:o}}function Lr(e){return Pr.has(e.toLowerCase())}function Wn(e){let n=xr(e).trim();if(!n.startsWith("/"))return null;let o=Dr(n);return!o||Lr(o.command)?null:o}function Gn(e){return e.filter(t=>t.type==="text").map(t=>t.text||"").join(" ")}var ye=require("fs"),we=require("path"),Fr=require("os"),Mr=(0,we.join)((0,Fr.homedir)(),".claude");function Ur(e){let t=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,n=e.match(t);if(!n)return{data:{},body:e};let[,o,r]=n,i={};for(let s of o.split(`
|
|
10
|
+
`)){let c=s.indexOf(":");if(c===-1)continue;let a=s.slice(0,c).trim(),l=s.slice(c+1).trim();(l.startsWith('"')&&l.endsWith('"')||l.startsWith("'")&&l.endsWith("'"))&&(l=l.slice(1,-1)),i[a]=l}return{data:i,body:r}}function $r(e,t){if(!(0,ye.existsSync)(e))return[];let n;try{n=(0,ye.readdirSync)(e,{withFileTypes:!0})}catch{return[]}let o=[];for(let r of n){if(!r.isFile()||!r.name.endsWith(".md"))continue;let i=(0,we.join)(e,r.name),s=(0,we.basename)(r.name,".md");try{let c=(0,ye.readFileSync)(i,"utf-8"),{data:a,body:l}=Ur(c),u={name:s,description:a.description||"",argumentHint:a["argument-hint"],model:a.model,agent:a.agent};o.push({name:s,path:i,metadata:u,content:l,scope:t})}catch{continue}}return o}function Bn(){let e=(0,we.join)(Mr,"commands"),t=(0,we.join)(process.cwd(),".claude","commands"),n=(0,we.join)(Mr,"skills"),o=$r(e,"user"),r=$r(t,"project"),i=[];if((0,ye.existsSync)(n))try{let s=(0,ye.readdirSync)(n,{withFileTypes:!0});for(let c of s){if(!c.isDirectory())continue;let a=(0,we.join)(n,c.name,"SKILL.md");if((0,ye.existsSync)(a))try{let l=(0,ye.readFileSync)(a,"utf-8"),{data:u,body:d}=Ur(l),f={name:u.name||c.name,description:u.description||"",argumentHint:u["argument-hint"],model:u.model,agent:u.agent};i.push({name:u.name||c.name,path:a,metadata:f,content:d,scope:"skill"})}catch{continue}}}catch{}return[...r,...o,...i]}function Yt(e){return Bn().find(n=>n.name.toLowerCase()===e.toLowerCase())??null}function Cu(e,t){return e.replace(/\$ARGUMENTS/g,t||"(no arguments provided)")}function Nu(e,t){let n=[];n.push(`<command-name>/${e.name}</command-name>
|
|
5
11
|
`),e.metadata.description&&n.push(`**Description**: ${e.metadata.description}
|
|
6
12
|
`),t&&n.push(`**Arguments**: ${t}
|
|
7
13
|
`),e.metadata.model&&n.push(`**Model**: ${e.metadata.model}
|
|
8
14
|
`),e.metadata.agent&&n.push(`**Agent**: ${e.metadata.agent}
|
|
9
15
|
`),n.push(`**Scope**: ${e.scope}
|
|
10
16
|
`),n.push(`---
|
|
11
|
-
`);let o=
|
|
17
|
+
`);let o=Cu(e.content||"",t);return n.push(o.trim()),t&&!e.content?.includes("$ARGUMENTS")&&(n.push(`
|
|
12
18
|
|
|
13
19
|
---
|
|
14
20
|
`),n.push(`## User Request
|
|
15
21
|
`),n.push(t)),n.join(`
|
|
16
|
-
`)}function
|
|
17
|
-
${
|
|
18
|
-
${
|
|
22
|
+
`)}function qn(e){let t=Yt(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:Nu(t,e.args)}}catch(n){return{success:!1,error:`Failed to load command "/${e.command}": ${n instanceof Error?n.message:String(n)}`}}}function Yn(){return Bn().map(t=>({name:t.name,description:t.metadata.description,scope:t.scope}))}var Vt=new Set;function jr(){return{name:Cr,processMessage:(e,t)=>{let n=Gn(t);if(n.includes(Bt)||n.includes(qt))return{detected:!1};let o=Wn(n);if(!o)return{detected:!1};let r=`${e.sessionId}:${e.messageId}:${o.command}`;if(Vt.has(r))return{detected:!1};Vt.add(r);let i=qn(o);if(i.success&&i.replacementText){let c=`${Bt}
|
|
23
|
+
${i.replacementText}
|
|
24
|
+
${qt}`;return{detected:!0,parsedCommand:o,injectedMessage:c}}let s=`${Bt}
|
|
19
25
|
[AUTO-SLASH-COMMAND ERROR]
|
|
20
|
-
${
|
|
26
|
+
${i.error}
|
|
21
27
|
|
|
22
28
|
Original input: ${o.raw}
|
|
23
|
-
${
|
|
29
|
+
${qt}`;return{detected:!0,parsedCommand:o,injectedMessage:s}},listCommands:()=>Yn(),findCommand:e=>Yt(e),clearSession:e=>{let t=[];for(let n of Vt)n.startsWith(`${e}:`)&&t.push(n);for(let n of t)Vt.delete(n)}}}var Pu=[/\bultrathink\b/i,/\bthink\b/i],xu=["\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"],Du=xu.map(e=>new RegExp(e,"i")),Lu=[...Pu,...Du],Mu=/```[\s\S]*?```/g,$u=/`[^`]+`/g;function Fu(e){return e.replace(Mu,"").replace($u,"")}function Hr(e){let t=Fu(e);return Lu.some(n=>n.test(t))}function Wr(e){return e.filter(t=>t.type==="text").map(t=>t.text||"").join("")}function Vn(e){let t=e.indexOf("/");return t===-1?{prefix:"",base:e}:{prefix:e.slice(0,t+1),base:e.slice(t+1)}}function Kn(e){return e.replace(/\.(\d+)/g,"-$1")}var Gr={"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"},Br=new Set(Object.values(Gr)),qr={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"}},Uu={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 Yr(e){let t=Kn(e),{prefix:n,base:o}=Vn(t);if(Br.has(o)||o.endsWith("-high"))return null;let r=Gr[o];return r?n+r:null}function Jn(e){let t=Kn(e),{base:n}=Vn(t);return Br.has(n)||n.endsWith("-high")}function ju(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 Hu(e){return e in qr}function Vr(e,t){let n=Kn(t),{base:o}=Vn(n);if(Jn(n))return null;let r=ju(e,t);if(!Hu(r))return null;let i=qr[r],s=Uu[r];if(!s)return null;let c=o.toLowerCase();return s.some(l=>c.includes(l.toLowerCase()))?i:null}var be=new Map;function Wu(e){be.delete(e)}function Kr(){return{processChatParams:(e,t)=>{let n=Wr(t.parts),o={requested:!1,modelSwitched:!1,thinkingConfigInjected:!1};if(!Hr(n))return be.set(e,o),o;o.requested=!0;let r=t.message.model;if(!r||(o.providerId=r.providerId,o.modelId=r.modelId,Jn(r.modelId)))return be.set(e,o),o;let i=Yr(r.modelId),s=Vr(r.providerId,r.modelId);return i&&(t.message.model={providerId:r.providerId,modelId:i},o.modelSwitched=!0),s&&(Object.assign(t.message,s),o.thinkingConfigInjected=!0),be.set(e,o),o},onSessionDeleted:e=>{be.delete(e)},isRequested:e=>be.get(e)?.requested??!1,getState:e=>be.get(e),clear:Wu}}var U=require("fs"),Qe=require("path"),zn=require("os");function Xn(e){let t=e||process.cwd(),n=(0,Qe.join)(t,".olympus");return(0,Qe.join)(n,"ultrawork-state.json")}function Qn(){return(0,Qe.join)((0,zn.homedir)(),".claude","ultrawork-state.json")}function Gu(e){let t=e||process.cwd(),n=(0,Qe.join)(t,".olympus");(0,U.existsSync)(n)||(0,U.mkdirSync)(n,{recursive:!0})}function Bu(){let e=(0,Qe.join)((0,zn.homedir)(),".claude");(0,U.existsSync)(e)||(0,U.mkdirSync)(e,{recursive:!0})}function We(e){let t=Xn(e);if((0,U.existsSync)(t))try{let o=(0,U.readFileSync)(t,"utf-8");return JSON.parse(o)}catch{}let n=Qn();if((0,U.existsSync)(n))try{let o=(0,U.readFileSync)(n,"utf-8");return JSON.parse(o)}catch{return null}return null}function Jr(e,t){try{Gu(t);let n=Xn(t);(0,U.writeFileSync)(n,JSON.stringify(e,null,2)),Bu();let o=Qn();return(0,U.writeFileSync)(o,JSON.stringify(e,null,2)),!0}catch{return!1}}function zr(e,t,n){let o={active:!0,started_at:new Date().toISOString(),original_prompt:e,session_id:t,reinforcement_count:0,last_checked_at:new Date().toISOString()};return Jr(o,n)}function Xr(e){let t=Xn(e);if((0,U.existsSync)(t))try{(0,U.unlinkSync)(t)}catch{}let n=Qn();if((0,U.existsSync)(n))try{return(0,U.unlinkSync)(n),!0}catch{return!1}return!0}function Qr(e){let t=We(e);return!t||!t.active?null:(t.reinforcement_count+=1,t.last_checked_at=new Date().toISOString(),Jr(t,e)?t:null)}function Zr(e){return`<ultrawork-persistence>
|
|
24
30
|
|
|
25
31
|
[ULTRAWORK MODE STILL ACTIVE - Reinforcement #${e.reinforcement_count+1}]
|
|
26
32
|
|
|
@@ -41,7 +47,7 @@ Original task: ${e.original_prompt}
|
|
|
41
47
|
|
|
42
48
|
---
|
|
43
49
|
|
|
44
|
-
`}var
|
|
50
|
+
`}var ei=require("os"),q=require("path");function Ee(){return process.platform==="win32"}function qu(){return(0,q.join)((0,ei.homedir)(),".claude")}function ee(){return(0,q.join)(qu(),"hooks")}var ti=`<ultrawork-mode>
|
|
45
51
|
|
|
46
52
|
**MANDATORY**: You MUST say "ULTRAWORK MODE ENABLED!" to the user as your first response when this mode activates. This is non-negotiable.
|
|
47
53
|
|
|
@@ -132,7 +138,7 @@ THE USER ASKED FOR X. DELIVER EXACTLY X. NOT A SUBSET. NOT A DEMO. NOT A STARTIN
|
|
|
132
138
|
|
|
133
139
|
---
|
|
134
140
|
|
|
135
|
-
`,
|
|
141
|
+
`,ni=`<think-mode>
|
|
136
142
|
|
|
137
143
|
**ULTRATHINK MODE ENABLED** - Extended reasoning activated.
|
|
138
144
|
|
|
@@ -148,7 +154,7 @@ Use your extended thinking capabilities to provide the most thorough and well-re
|
|
|
148
154
|
|
|
149
155
|
---
|
|
150
156
|
|
|
151
|
-
`;var
|
|
157
|
+
`;var oi=`<search-mode>
|
|
152
158
|
MAXIMIZE SEARCH EFFORT. Launch multiple background agents IN PARALLEL:
|
|
153
159
|
- explore agents (codebase patterns, file structures)
|
|
154
160
|
- librarian agents (remote repos, official docs, GitHub examples)
|
|
@@ -158,7 +164,7 @@ NEVER stop at first result - be exhaustive.
|
|
|
158
164
|
|
|
159
165
|
---
|
|
160
166
|
|
|
161
|
-
`,
|
|
167
|
+
`,ri=`<analyze-mode>
|
|
162
168
|
ANALYSIS MODE. Gather context before diving deep:
|
|
163
169
|
|
|
164
170
|
CONTEXT GATHERING (parallel):
|
|
@@ -174,16 +180,675 @@ SYNTHESIZE findings before proceeding.
|
|
|
174
180
|
|
|
175
181
|
---
|
|
176
182
|
|
|
177
|
-
`,
|
|
183
|
+
`,ii=`[SYSTEM REMINDER - TODO CONTINUATION]
|
|
178
184
|
|
|
179
185
|
Incomplete tasks remain in your todo list. Continue working on the next pending task.
|
|
180
186
|
|
|
181
187
|
- Proceed without asking for permission
|
|
182
188
|
- Mark each task complete when finished
|
|
183
|
-
- Do not stop until all tasks are done`;var
|
|
184
|
-
`).filter(r=>r.trim()).length;if(o>=t){let r=new Date().toISOString().replace(/[:.]/g,"-"),
|
|
185
|
-
`,"utf-8")}function
|
|
186
|
-
`).filter(n=>n.trim()).map(n=>JSON.parse(n)):[]}function Fo(){return Ea()}function $o(e,t){let n=t.filter(u=>u.agent_used===e);if(n.length===0)return null;let o=n.length,r=n.filter(u=>u.event_type==="success").length,s=n.filter(u=>u.event_type==="revision").length,i=n.filter(u=>u.event_type==="cancellation").length,c=o>0?r/o:0,a,l=n.filter(u=>Yt(u)!==null);if(l.length>0){let u=l.filter(h=>h.event_type==="success"),d=l.filter(h=>h.event_type==="revision"||h.event_type==="cancellation"),f=l.reduce((h,_)=>h+Te(_),0),E=u.reduce((h,_)=>h+Te(_),0),S=d.reduce((h,_)=>h+Te(_),0),O=u.length>0?E/u.length:0,R=d.length>0?S/d.length:0;if(a={avg_tokens_per_success:O,avg_tokens_per_failure:R,total_tokens:f,invocation_count:l.length,efficiency_score:O,trend:"insufficient_data"},l.length>=10){let h=Math.floor(l.length/2),_=l.slice(0,h),p=l.slice(h),I=_.reduce((ge,Ne)=>ge+Te(Ne),0)/_.length,y=p.reduce((ge,Ne)=>ge+Te(Ne),0)/p.length-I,m=I*.1;Math.abs(y)<m?a.trend="stable":y<0?a.trend="improving":a.trend="declining"}}return{agent_name:e,total_invocations:o,success_count:r,revision_count:s,cancellation_count:i,success_rate:c,failure_patterns:[],strong_areas:[],weak_areas:[],last_updated:new Date().toISOString(),token_efficiency:a}}function ke(e,t){if(!(0,A.existsSync)(e))return t;try{return JSON.parse((0,A.readFileSync)(e,"utf-8"))}catch(n){return console.error(`[Olympus Learning] Failed to read ${e}:`,n),t}}function Ho(e,t){try{let n=(0,te.dirname)(e);n&&!(0,A.existsSync)(n)&&(0,A.mkdirSync)(n,{recursive:!0}),(0,A.writeFileSync)(e,JSON.stringify(t,null,2),"utf-8")}catch(n){console.error(`[Olympus Learning] Failed to write ${e}:`,n)}}var Yo=require("crypto");function le(e,t,n){return!n||n.sample_count<5?1e4:e&&n.by_project[e]!==void 0?n.by_project[e]:t&&n.by_task_type[t]!==void 0?n.by_task_type[t]:n.overall_avg}var ya=10,Sa=1800*1e3;function Wo(e){return(0,Bo.join)(e,".olympus","session-state.json")}function Go(e,t){let n=le(t);return{session_id:e||(0,Yo.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,warning_threshold:1.5,warning_issued:!1,started_at:new Date().toISOString()}}}function D(e,t){let n=Wo(e),o=ke(n,null);if(!o)return Go(t,e);let r=new Date(o.last_updated).getTime();if(Date.now()-r>Sa)return Go(t,e);if(!o.token_budget){let i=le(e);o.token_budget={session_baseline:i,current_usage:0,warning_threshold:1.5,warning_issued:!1,started_at:o.started_at}}return o}function P(e,t){let n=Wo(e);t.last_updated=new Date().toISOString(),Ho(n,t)}function Vo(e,t,n){let o={prompt:t,timestamp:new Date().toISOString(),detected_feedback:n};return e.recent_prompts=[o,...e.recent_prompts].slice(0,ya),e.last_updated=new Date().toISOString(),e}function Ko(e){return e.pending_completion=null,e.last_updated=new Date().toISOString(),e}function et(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 qo(e,t){let n=le(t);return e.token_budget={session_baseline:n,current_usage:0,warning_threshold:1.5,warning_issued:!1,started_at:new Date().toISOString()},e.last_updated=new Date().toISOString(),e}function Jo(e,t){return e.token_budget||(e.token_budget={session_baseline:le(),current_usage: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 Xo(e){return e.token_budget&&(e.token_budget.warning_issued=!0,e.last_updated=new Date().toISOString()),e}function zo(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}var Qo=require("crypto"),Oa={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 Wt(e){let t=e.replace(/```[\s\S]*?```/g,"").replace(/`[^`]+`/g,""),n=null;for(let[o,r]of Object.entries(Oa))for(let{regex:s,confidence:i}of r)s.test(t)&&(!n||i>n.confidence)&&(n={category:o,confidence:i});return n}async function Zo(e){let{prompt:t,directory:n,sessionId:o}=e;if(!t||!n)return;let r=D(n,o),s=Wt(t),i=Vo(r,t,s?.category);if(s&&et(r)){let c={id:(0,Qo.randomUUID)(),timestamp:new Date().toISOString(),session_id:r.session_id,project_path:n,event_type:s.category==="explicit_preference"?"explicit_preference":"revision",original_task:r.pending_completion?.task_description,agent_used:r.pending_completion?.agent_used,user_message:t,feedback_category:s.category,confidence:s.confidence};oe(c)}P(n,i)}var er=require("crypto");async function tr(e){let{prompt:t,directory:n,sessionId:o}=e;if(!t||!n)return;let r=D(n,o);if(!et(r))return;let s=Wt(t),i=s?.category==="praise"&&s.confidence>.7,c=_a(t,r.pending_completion?.task_description||"");if(i||c){let a={id:(0,er.randomUUID)(),timestamp:new Date().toISOString(),session_id:r.session_id,project_path:n,event_type:"success",original_task:r.pending_completion?.task_description,agent_used:r.pending_completion?.agent_used,user_message:t,feedback_category:i?"praise":"enhancement",confidence:i?s.confidence:.6};oe(a);let l=Ko(r);P(n,l)}}function _a(e,t){let n=a=>new Set(a.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter(l=>l.length>3)),o=n(e),r=n(t),s=new Set([...o].filter(a=>r.has(a))),i=new Set([...o,...r]);return(i.size>0?s.size/i.size:0)<.2}function nr(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 or(){g({name:"keywordDetector",event:"UserPromptSubmit",priority:10,handler:e=>{let t=nr(e);if(!t)return{continue:!0};let n=oo(t),o=ro(n);if(o.length===0)return{continue:!0};let r=o.some(a=>a.type==="ultrawork"),s=o.some(a=>a.type==="ultrathink"),i=o.some(a=>a.type==="search"),c=o.some(a=>a.type==="analyze");return r?(Ao(t,e.sessionId,e.directory||process.cwd()),{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:Co}}):s?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:xo}}:i?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:Po}}:c?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:Lo}}:{continue:!0}}}),g({name:"autoSlashCommand",event:"UserPromptSubmit",priority:20,handler:e=>{if(!e.parts)return{continue:!0};let n=ho().processMessage({sessionId:e.sessionId||""},e.parts);return n.detected&&n.injectedMessage?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:n.injectedMessage}}:{continue:!0}}}),g({name:"thinkMode",event:"UserPromptSubmit",priority:30,handler:e=>{if(!e.message||!e.parts)return{continue:!0};let t=Ro(),n=e.sessionId||"default",o={parts:e.parts,message:{model:e.message.model&&e.message.model.providerId&&e.message.model.modelId?{providerId:e.message.model.providerId,modelId:e.message.model.modelId}:void 0}},r=t.processChatParams(n,o);return r.requested&&r.modelSwitched?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:"[Think Mode Activated] Switched to high-reasoning model variant."}}:{continue:!0}}}),g({name:"learningFeedbackCapture",event:"UserPromptSubmit",priority:100,handler:async e=>{let t=nr(e);return!t||!e.directory?{continue:!0}:(Promise.resolve().then(async()=>{try{await Zo({prompt:t,directory:e.directory,sessionId:e.sessionId}),await tr({prompt:t,directory:e.directory,sessionId:e.sessionId})}catch(n){console.error("[Olympus Learning]",n)}}),{continue:!0})}})}var ue=require("fs"),re=require("path"),rr=require("os");function Ra(e,t){let n=(0,re.join)((0,rr.homedir)(),".claude"),o=[];e&&(o.push((0,re.join)(n,"sessions",e,"todos.json")),o.push((0,re.join)(n,"todos",`${e}.json`))),t&&(o.push((0,re.join)(t,".olympus","todos.json")),o.push((0,re.join)(t,".claude","todos.json")));let r=(0,re.join)(n,"todos");if((0,ue.existsSync)(r))try{let s=(0,ue.readdirSync)(r);for(let i of s)i.endsWith(".json")&&o.push((0,re.join)(r,i))}catch{}return o}function Ia(e){try{let t=(0,ue.readFileSync)(e,"utf-8"),n=JSON.parse(t);return Array.isArray(n)?n.filter(o=>o&&typeof o.content=="string"&&typeof o.status=="string"):n.todos&&Array.isArray(n.todos)?n.todos.filter(o=>{let r=o;return r&&typeof r.content=="string"&&typeof r.status=="string"}):[]}catch{return[]}}function Aa(e){return e.status!=="completed"&&e.status!=="cancelled"}async function xe(e,t){let n=Ra(e,t),o=new Set,r=[],s=[];for(let i of n){if(!(0,ue.existsSync)(i))continue;let c=Ia(i);for(let a of c){let l=`${a.content}:${a.status}`;o.has(l)||(o.add(l),r.push(a),Aa(a)&&s.push(a))}}return{count:s.length,todos:s,total:r.length}}function sr(e){let t=e.todos.find(n=>n.status==="in_progress");return t||(e.todos.find(n=>n.status==="pending")??null)}var tt=require("path");function ir(e,t=5){return(e.token_efficiency?.invocation_count??0)>=t}var ar=500;function cr(e){let t=ke((0,tt.join)(ne(),"user-preferences.json"),null),n=ke((0,tt.join)(Ce(e),"patterns.json"),null),o=ke((0,tt.join)(ne(),"agent-performance.json"),{}),r=[];t&&ba(t)&&r.push(wa(t)),n&&n.conventions.length>0&&r.push(va(n)),t?.recurring_corrections&&t.recurring_corrections.length>0&&r.push(Na(t.recurring_corrections.slice(0,5)));let s=Object.values(o).filter(a=>a.weak_areas.length>0);s.length>0&&r.push(Ca(s));let i=xa(o);if(i&&r.push(i),r.length===0)return"";let c=`<learned-context>
|
|
189
|
+
- Do not stop until all tasks are done`;var rh={hooks:{UserPromptSubmit:[{hooks:[{type:"command",command:Ee()?'node "%USERPROFILE%\\.claude\\hooks\\keyword-detector.mjs"':'node "$HOME/.claude/hooks/keyword-detector.mjs"'}]}],SessionStart:[{hooks:[{type:"command",command:Ee()?'node "%USERPROFILE%\\.claude\\hooks\\session-start.mjs"':'node "$HOME/.claude/hooks/session-start.mjs"'}]}],Stop:[{hooks:[{type:"command",command:Ee()?'node "%USERPROFILE%\\.claude\\hooks\\persistent-mode.mjs"':'node "$HOME/.claude/hooks/persistent-mode.mjs"'}]}]}},ih={hooks:{UserPromptSubmit:[{hooks:[{type:"command",command:Ee()?`node "${(0,q.join)(ee(),"olympus-hooks.cjs")}" --event=UserPromptSubmit`:`node "${(0,q.join)(ee(),"olympus-hooks.cjs")}" --event=UserPromptSubmit`}]}],SessionStart:[{hooks:[{type:"command",command:Ee()?`node "${(0,q.join)(ee(),"olympus-hooks.cjs")}" --event=SessionStart`:`node "${(0,q.join)(ee(),"olympus-hooks.cjs")}" --event=SessionStart`}]}],Stop:[{hooks:[{type:"command",command:Ee()?`node "${(0,q.join)(ee(),"olympus-hooks.cjs")}" --event=Stop`:`node "${(0,q.join)(ee(),"olympus-hooks.cjs")}" --event=Stop`}]}],PreToolUse:[{hooks:[{type:"command",command:Ee()?`node "${(0,q.join)(ee(),"olympus-hooks.cjs")}" --event=PreToolUse`:`node "${(0,q.join)(ee(),"olympus-hooks.cjs")}" --event=PreToolUse`}]}],PostToolUse:[{hooks:[{type:"command",command:Ee()?`node "${(0,q.join)(ee(),"olympus-hooks.cjs")}" --event=PostToolUse`:`node "${(0,q.join)(ee(),"olympus-hooks.cjs")}" --event=PostToolUse`}]}],PostToolUseFailure:[{hooks:[{type:"command",command:Ee()?`node "${(0,q.join)(ee(),"olympus-hooks.cjs")}" --event=PostToolUseFailure`:`node "${(0,q.join)(ee(),"olympus-hooks.cjs")}" --event=PostToolUseFailure`}]}],Notification:[{hooks:[{type:"command",command:Ee()?`node "${(0,q.join)(ee(),"olympus-hooks.cjs")}" --event=Notification`:`node "${(0,q.join)(ee(),"olympus-hooks.cjs")}" --event=Notification`}]}]}};var pi=require("path");var si=require("os"),Ce=require("path"),$=require("fs"),Yu=require("crypto");function Zn(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 Ze(e){return Zn(e)?.total_tokens||0}var Vu=1e4;function Ne(){return(0,Ce.join)((0,si.homedir)(),".claude","olympus","learning")}function yt(e){return(0,Ce.join)(e,".olympus","learning")}function ai(e){let t=Ne();if((0,$.existsSync)(t)||(0,$.mkdirSync)(t,{recursive:!0}),e){let n=yt(e);(0,$.existsSync)(n)||(0,$.mkdirSync)(n,{recursive:!0})}}function ci(e,t=Vu){if((0,$.existsSync)(e))try{let o=(0,$.readFileSync)(e,"utf-8").split(`
|
|
190
|
+
`).filter(r=>r.trim()).length;if(o>=t){let r=new Date().toISOString().replace(/[:.]/g,"-"),i=e.replace(".jsonl",`.${r}.old.jsonl`);(0,$.renameSync)(e,i),console.log(`[Olympus Learning] Archived ${o} entries to ${i}`)}}catch(n){console.error(`[Olympus Learning] Failed to rotate ${e}:`,n)}}function Pe(e){ai();let t=(0,Ce.join)(Ne(),"feedback-log.jsonl");ci(t),(0,$.appendFileSync)(t,JSON.stringify(e)+`
|
|
191
|
+
`,"utf-8")}function Ku(){let e=(0,Ce.join)(Ne(),"feedback-log.jsonl");return(0,$.existsSync)(e)?(0,$.readFileSync)(e,"utf-8").split(`
|
|
192
|
+
`).filter(n=>n.trim()).map(n=>JSON.parse(n)):[]}function li(){return Ku()}function ui(e,t){let n=t.filter(u=>u.agent_used===e);if(n.length===0)return null;let o=n.length,r=n.filter(u=>u.event_type==="success").length,i=n.filter(u=>u.event_type==="revision").length,s=n.filter(u=>u.event_type==="cancellation").length,c=o>0?r/o:0,a,l=n.filter(u=>Zn(u)!==null);if(l.length>0){let u=l.filter(y=>y.event_type==="success"),d=l.filter(y=>y.event_type==="revision"||y.event_type==="cancellation"),f=l.reduce((y,T)=>y+Ze(T),0),g=u.reduce((y,T)=>y+Ze(T),0),m=d.reduce((y,T)=>y+Ze(T),0),p=u.length>0?g/u.length:0,h=d.length>0?m/d.length:0;if(a={avg_tokens_per_success:p,avg_tokens_per_failure:h,total_tokens:f,invocation_count:l.length,efficiency_score:p,trend:"insufficient_data"},l.length>=10){let y=Math.floor(l.length/2),T=l.slice(0,y),k=l.slice(y),A=T.reduce((ke,S)=>ke+Ze(S),0)/T.length,R=k.reduce((ke,S)=>ke+Ze(S),0)/k.length-A,w=A*.1;Math.abs(R)<w?a.trend="stable":R<0?a.trend="improving":a.trend="declining"}}return{agent_name:e,total_invocations:o,success_count:r,revision_count:i,cancellation_count:s,success_rate:c,failure_patterns:[],strong_areas:[],weak_areas:[],last_updated:new Date().toISOString(),token_efficiency:a}}function et(e,t){if(!(0,$.existsSync)(e))return t;try{return JSON.parse((0,$.readFileSync)(e,"utf-8"))}catch(n){return console.error(`[Olympus Learning] Failed to read ${e}:`,n),t}}function di(e,t){try{let n=(0,Ce.dirname)(e);n&&!(0,$.existsSync)(n)&&(0,$.mkdirSync)(n,{recursive:!0}),(0,$.writeFileSync)(e,JSON.stringify(t,null,2),"utf-8")}catch(n){console.error(`[Olympus Learning] Failed to write ${e}:`,n)}}var mi=require("crypto");function Ge(e,t,n){return!n||n.sample_count<5?1e4:e&&n.by_project[e]!==void 0?n.by_project[e]:t&&n.by_task_type[t]!==void 0?n.by_task_type[t]:n.overall_avg}var Ju=10,zu=1800*1e3;function gi(e){return(0,pi.join)(e,".olympus","session-state.json")}function fi(e,t){let n=Ge(t);return{session_id:e||(0,mi.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()}}}function te(e,t){let n=gi(e),o=et(n,null);if(!o)return fi(t,e);let r=new Date(o.last_updated).getTime();if(Date.now()-r>zu)return fi(t,e);if(o.token_budget)o.token_budget.input_tokens===void 0&&(o.token_budget.input_tokens=0),o.token_budget.output_tokens===void 0&&(o.token_budget.output_tokens=0);else{let s=Ge(e);o.token_budget={session_baseline:s,current_usage:0,input_tokens:0,output_tokens:0,warning_threshold:1.5,warning_issued:!1,started_at:o.started_at}}return o}function J(e,t){let n=gi(e);t.last_updated=new Date().toISOString(),di(n,t)}function hi(e,t,n){let o={prompt:t,timestamp:new Date().toISOString(),detected_feedback:n};return e.recent_prompts=[o,...e.recent_prompts].slice(0,Ju),e.last_updated=new Date().toISOString(),e}function ki(e){return e.pending_completion=null,e.last_updated=new Date().toISOString(),e}function Kt(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 yi(e,t){let n=Ge(t);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 Ei(e,t){return e.token_budget||(e.token_budget={session_baseline:Ge(),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 Si(e){return e.token_budget&&(e.token_budget.warning_issued=!0,e.last_updated=new Date().toISOString()),e}function Ti(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}var wi=require("crypto"),Xu={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 eo(e){let t=e.replace(/```[\s\S]*?```/g,"").replace(/`[^`]+`/g,""),n=null;for(let[o,r]of Object.entries(Xu))for(let{regex:i,confidence:s}of r)i.test(t)&&(!n||s>n.confidence)&&(n={category:o,confidence:s});return n}async function _i(e){let{prompt:t,directory:n,sessionId:o}=e;if(!t||!n)return;let r=te(n,o),i=eo(t),s=hi(r,t,i?.category);if(i&&Kt(r)){let c={id:(0,wi.randomUUID)(),timestamp:new Date().toISOString(),session_id:r.session_id,project_path:n,event_type:i.category==="explicit_preference"?"explicit_preference":"revision",original_task:r.pending_completion?.task_description,agent_used:r.pending_completion?.agent_used,user_message:t,feedback_category:i.category,confidence:i.confidence};Pe(c)}J(n,s)}var Oi=require("crypto");async function vi(e){let{prompt:t,directory:n,sessionId:o}=e;if(!t||!n)return;let r=te(n,o);if(!Kt(r))return;let i=eo(t),s=i?.category==="praise"&&i.confidence>.7,c=Qu(t,r.pending_completion?.task_description||"");if(s||c){let a={id:(0,Oi.randomUUID)(),timestamp:new Date().toISOString(),session_id:r.session_id,project_path:n,event_type:"success",original_task:r.pending_completion?.task_description,agent_used:r.pending_completion?.agent_used,user_message:t,feedback_category:s?"praise":"enhancement",confidence:s?i.confidence:.6};Pe(a);let l=ki(r);J(n,l)}}function Qu(e,t){let n=a=>new Set(a.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter(l=>l.length>3)),o=n(e),r=n(t),i=new Set([...o].filter(a=>r.has(a))),s=new Set([...o,...r]);return(s.size>0?i.size/s.size:0)<.2}var re=H(sn(),1),Rt=require("path"),ko=".olympus/workflow",Ta="checkpoint.json",ho=new Map,np=5e3;function wa(e,t){return`${e}:${t}`}function op(e){return Date.now()-e.timestamp<np}async function $e(e,t){let n=(0,Rt.join)(e,ko,t.workflow_id),o=(0,Rt.join)(n,Ta);try{if(t.updated_at=new Date().toISOString(),await re.ensureDir(n),JSON.stringify(t).length>1e4){let c=JSON.stringify(t);await re.writeFile(o,c,"utf-8")}else await re.writeJson(o,t,{spaces:2});let s=wa(e,t.workflow_id);ho.set(s,{checkpoint:{...t},timestamp:Date.now(),dirty:!1})}catch(r){let i=r;throw i.code==="ENOSPC"?(console.error("[Checkpoint] Failed to save checkpoint: Disk full"),console.error("[Checkpoint] Please free up disk space and try again."),console.error(`[Checkpoint] Attempted path: ${o}`),new Error("Failed to save checkpoint: Disk is full. Please free up space and retry.")):i.code==="EACCES"||i.code==="EPERM"?(console.error("[Checkpoint] Failed to save checkpoint: Permission denied"),console.error(`[Checkpoint] Path: ${o}`),new Error(`Failed to save checkpoint: Permission denied for ${o}`)):i.code==="EROFS"?(console.error("[Checkpoint] Failed to save checkpoint: Read-only filesystem"),console.error(`[Checkpoint] Path: ${o}`),new Error("Failed to save checkpoint: Filesystem is read-only")):(console.error("[Checkpoint] Failed to save checkpoint:",i.message),console.error(`[Checkpoint] Workflow ID: ${t.workflow_id}`),console.error(`[Checkpoint] Path: ${o}`),new Error(`Failed to save checkpoint for workflow ${t.workflow_id}: ${i.message}`))}}async function me(e,t){let n=wa(e,t),o=ho.get(n);if(o&&op(o))return{...o.checkpoint};let r=(0,Rt.join)(e,ko,t,Ta);try{let i=await re.readFile(r,"utf-8"),s=JSON.parse(i);return s.schema_version?(ho.set(n,{checkpoint:{...s},timestamp:Date.now(),dirty:!1}),s):(console.warn(`[Checkpoint] Checkpoint ${t} missing schema_version, treating as invalid`),console.warn("[Checkpoint] Checkpoint may be corrupt or from an older version"),console.warn(`[Checkpoint] Consider deleting: ${r}`),null)}catch(i){let s=i,c=s;return c.code==="ENOENT"?null:s.name==="SyntaxError"||s.message.includes("JSON")?(console.warn(`[Checkpoint] Corrupt checkpoint detected for workflow ${t}`),console.warn(`[Checkpoint] Path: ${r}`),console.warn(`[Checkpoint] Error: ${s.message}`),console.warn("[Checkpoint] To reset this workflow, delete the checkpoint file and start over"),null):c.code==="EACCES"||c.code==="EPERM"?(console.warn(`[Checkpoint] Permission denied reading checkpoint ${t}`),console.warn(`[Checkpoint] Path: ${r}`),null):(console.warn(`[Checkpoint] Failed to load checkpoint ${t}: ${s.message}`),console.warn(`[Checkpoint] Path: ${r}`),null)}}async function _a(e){let t=(0,Rt.join)(e,ko);try{return await re.pathExists(t)?(await re.readdir(t,{withFileTypes:!0})).filter(r=>r.isDirectory()).map(r=>r.name):[]}catch(n){let o=n;return o.code==="EACCES"||o.code==="EPERM"?(console.warn(`[Checkpoint] Permission denied listing workflows in ${t}`),[]):(console.warn(`[Checkpoint] Failed to list workflows: ${o.message}`),console.warn(`[Checkpoint] Directory: ${t}`),[])}}var ve=H(require("path"),1),se=H(sn(),1);async function Oa(e,t){let n=ve.join(e,".olympus","workflow",t),o=ve.join(n,"intents"),r=ve.join(n,"validation"),i=ve.join(n,"checkpoint.json");try{await se.ensureDir(n),await se.ensureDir(o),await se.ensureDir(r),await se.pathExists(i)||await se.writeJson(i,{workflow_id:t,current_stage:"idea",created_at:new Date().toISOString(),updated_at:new Date().toISOString()},{spaces:2})}catch(s){let c=s;throw c.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.")):c.code==="EACCES"||c.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}`)):c.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: ${c.message}`),console.error(`[Artifacts] Workflow ID: ${t}`),console.error(`[Artifacts] Path: ${n}`),new Error(`Failed to create workflow directory for ${t}: ${c.message}`))}}function Fe(e,t,n){if(n==="complete")throw new Error("No artifact file for complete stage");if(n==="intents")throw new Error("Intents is a directory, not a single file. Use getIntentsDir() instead.");let o=ve.join(e,".olympus","workflow",t),i={idea:"idea.md",prd:"prd.md",spec:"spec.md"}[n];return ve.join(o,i)}async function an(e,t,n,o){if(n==="intents")throw new Error("Cannot write single artifact for intents stage. Use writeIntentFile() instead.");let r=Fe(e,t,n);try{await se.ensureDir(ve.dirname(r)),await se.writeFile(r,o,"utf-8")}catch(i){let s=i;throw s.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: ${r}`),new Error(`Failed to write ${n} artifact: Disk is full. Please free up space and retry.`)):s.code==="EACCES"||s.code==="EPERM"?(console.error(`[Artifacts] Failed to write ${n} artifact: Permission denied`),console.error(`[Artifacts] Path: ${r}`),new Error(`Failed to write ${n} artifact: Permission denied for ${r}`)):s.code==="EROFS"?(console.error(`[Artifacts] Failed to write ${n} artifact: Read-only filesystem`),console.error(`[Artifacts] Path: ${r}`),new Error(`Failed to write ${n} artifact: Filesystem is read-only`)):(console.error(`[Artifacts] Failed to write ${n} artifact: ${s.message}`),console.error(`[Artifacts] Path: ${r}`),new Error(`Failed to write ${n} artifact: ${s.message}`))}}var Ye=require("fs"),va=new Map,rp=1e4;function ip(e){let t=va.get(e);if(t&&Date.now()-t.timestamp<rp)return t.content;let n=(0,Ye.readFileSync)(e,"utf-8");return va.set(e,{content:n,timestamp:Date.now()}),n}var sp=["Problem Statement","Business Context","Success Metrics","Constraints","Solution Approach"];async function Ra(e){let t=new Date().toISOString(),n=[],o;try{o=ip(e)}catch(d){let f=d;return f.code==="ENOENT"?(console.error(`[Validation] IDEA artifact not found: ${e}`),{passed:!1,coverage_percentage:0,blocking_issues:["Artifact file not found"],timestamp:t}):f.code==="EACCES"||f.code==="EPERM"?(console.error(`[Validation] Permission denied reading IDEA artifact: ${e}`),{passed:!1,coverage_percentage:0,blocking_issues:["Permission denied reading artifact file"],timestamp:t}):(console.error(`[Validation] Failed to read IDEA artifact: ${f.message}`),console.error(`[Validation] Path: ${e}`),{passed:!1,coverage_percentage:0,blocking_issues:[`Failed to read artifact: ${f.message}`],timestamp:t})}let r=ap(o);(!r||!r.risk_tier)&&n.push("Risk tier not specified in frontmatter");let i=st(o),s=It(i),c=[()=>{let d=s.get("Problem Statement");return!d||d.trim().length===0?"Missing problem statement section":null},()=>{let d=s.get("Business Context");return!d||d.trim().length===0?"Business context section is empty":null},()=>{let d=s.get("Success Metrics");if(d){let f=Ia(d);if(f<2)return`Only ${f} success metric found, need at least 2`}else return"Missing success metrics section";return null},()=>{let d=s.get("Constraints");return!d||d.trim().length===0?"Constraints section missing":null},()=>{let d=[];for(let f of sp)s.has(f)||d.push(`Missing required section: ${f}`);return d.length>0?d.join("; "):null}];for(let d of c){let f=d();f&&n.push(f)}let a=6,l=a-n.length,u=Math.round(l/a*100);return{passed:n.length===0,coverage_percentage:u,blocking_issues:n,timestamp:t}}function ap(e){let t=e.match(/^---\n([\s\S]*?)\n---/);if(!t)return null;let n=t[1];try{let o={},r=n.split(`
|
|
193
|
+
`);for(let i of r){let s=i.match(/^(\w+):\s*(.+)$/);if(s){let[,c,a]=s;o[c]=a.trim()}}return o}catch{return null}}function st(e){return e.replace(/^---\n[\s\S]*?\n---\n/,"")}function It(e){let t=new Map,n=e.split(`
|
|
194
|
+
`),o=null,r=[];for(let i of n){let s=i.match(/^##\s+(.+)$/);s?(o&&t.set(o,r.join(`
|
|
195
|
+
`)),o=s[1].trim(),r=[]):o&&r.push(i)}return o&&t.set(o,r.join(`
|
|
196
|
+
`)),t}function Ia(e){let t=e.split(`
|
|
197
|
+
`),n=0;for(let o of t)o.trim().match(/^[-*+]\s+/)&&n++;return n}async function Aa(e,t){let n=new Date().toISOString(),o=[],r;try{r=(0,Ye.readFileSync)(e,"utf-8")}catch(p){let h=p;return console.error(`[Validation] Failed to read PRD artifact: ${h.message}`),console.error(`[Validation] Path: ${e}`),{passed:!1,coverage_percentage:0,blocking_issues:[h.code==="ENOENT"?"PRD artifact file not found":h.code==="EACCES"||h.code==="EPERM"?"Permission denied reading PRD artifact":`Failed to read PRD artifact: ${h.message}`],reviewer:"momus",timestamp:n}}let i;try{i=(0,Ye.readFileSync)(t,"utf-8")}catch(p){let h=p;return console.error(`[Validation] Failed to read IDEA artifact for PRD validation: ${h.message}`),console.error(`[Validation] Path: ${t}`),{passed:!1,coverage_percentage:0,blocking_issues:[h.code==="ENOENT"?"IDEA artifact file not found for reference":h.code==="EACCES"||h.code==="EPERM"?"Permission denied reading IDEA artifact":`Failed to read IDEA artifact: ${h.message}`],reviewer:"momus",timestamp:n}}let s=st(i),a=It(s).get("Constraints"),l=a?Ia(a):0,u=st(r),d=It(u),f=0;for(let p of u.split(`
|
|
198
|
+
`))p.match(/^###?\s+US-\d+/)&&f++;let g=d.has("Requirement Coverage"),m=l>0?Math.round(Math.min(f,l)/l*100):100;return f===0&&o.push("No user stories found in PRD"),g||o.push("Missing Requirement Coverage section"),m<90&&o.push(`Coverage only ${m}%, need at least 90% (${f}/${l} constraints addressed)`),{passed:o.length===0&&m>=90,coverage_percentage:m,blocking_issues:o,reviewer:"momus",timestamp:n}}async function ba(e,t){let n=new Date().toISOString(),o=[],r;try{r=(0,Ye.readFileSync)(e,"utf-8")}catch(m){let p=m;return console.error(`[Validation] Failed to read SPEC artifact: ${p.message}`),console.error(`[Validation] Path: ${e}`),{passed:!1,coverage_percentage:0,blocking_issues:[p.code==="ENOENT"?"SPEC artifact file not found":p.code==="EACCES"||p.code==="EPERM"?"Permission denied reading SPEC artifact":`Failed to read SPEC artifact: ${p.message}`],reviewer:"metis",timestamp:n}}let i;try{i=(0,Ye.readFileSync)(t,"utf-8")}catch(m){let p=m;return console.error(`[Validation] Failed to read PRD artifact for SPEC validation: ${p.message}`),console.error(`[Validation] Path: ${t}`),{passed:!1,coverage_percentage:0,blocking_issues:[p.code==="ENOENT"?"PRD artifact file not found for reference":p.code==="EACCES"||p.code==="EPERM"?"Permission denied reading PRD artifact":`Failed to read PRD artifact: ${p.message}`],reviewer:"metis",timestamp:n}}let s=st(i),c=[];for(let m of s.split(`
|
|
199
|
+
`)){let p=m.match(/^###?\s+(US-\d+)/);p&&c.push(p[1])}let a=st(r),l=It(a),u=l.get("Requirement Coverage")||l.get("PRD Coverage")||"",d=0;for(let m of c)a.includes(m)&&d++;let f=c.length>0?Math.round(d/c.length*100):0;return c.length===0&&o.push("No user stories found in PRD for validation"),(!u||u.trim().length===0)&&o.push("Missing Requirement Coverage section in SPEC"),f<95&&o.push(`Coverage only ${f}%, need at least 95% (${d}/${c.length} user stories addressed)`),l.has("Components")||l.has("Architecture")||o.push("Missing Components or Architecture section"),{passed:o.length===0&&f>=95,coverage_percentage:f,blocking_issues:o,reviewer:"metis",timestamp:n}}async function Ca(e,t){let n=new Date().toISOString(),o=[],r;try{r=(0,Ye.readFileSync)(t,"utf-8")}catch(m){let p=m;return console.error(`[Validation] Failed to read SPEC artifact for task validation: ${p.message}`),console.error(`[Validation] Path: ${t}`),{passed:!1,coverage_percentage:0,blocking_issues:[p.code==="ENOENT"?"SPEC artifact file not found":p.code==="EACCES"||p.code==="EPERM"?"Permission denied reading SPEC artifact":`Failed to read SPEC artifact: ${p.message}`],timestamp:n}}let i=st(r),s=It(i),c=s.get("Components")||s.get("Architecture")||"",a=[];if(c)for(let m of c.split(`
|
|
200
|
+
`)){let p=m.match(/^###\s+(.+)$/);p&&a.push(p[1].trim())}let l=[];try{l=(await import("fs")).readdirSync(e).filter(h=>h.endsWith(".md")||h.includes("INTENT"))}catch(m){let p=m;return console.error(`[Validation] Failed to read tasks directory: ${p.message}`),console.error(`[Validation] Path: ${e}`),{passed:!1,coverage_percentage:0,blocking_issues:[p.code==="ENOENT"?"Tasks directory not found":p.code==="EACCES"||p.code==="EPERM"?"Permission denied reading tasks directory":`Failed to read tasks directory: ${p.message}`],timestamp:n}}let u=new Set,d=[];for(let m of l)try{let p=await import("fs"),y=(await import("path")).join(e,m),T=p.readFileSync(y,"utf-8");for(let A of a)T.includes(A)&&u.add(A);let k=T.match(/estimated_effort:\s*(\d+)/i);k&&d.push(parseInt(k[1],10))}catch{}let f=a.length>0?Math.round(u.size/a.length*100):100;if(a.length===0)o.push("No components found in SPEC for validation");else if(f<100){let m=a.filter(p=>!u.has(p));o.push(`Incomplete coverage: ${f}% (missing: ${m.join(", ")})`)}let g=[1,2,4,8,16];for(let m of d)g.includes(m)||o.push(`Invalid effort estimate: ${m} hours (must be 1, 2, 4, 8, or 16)`);if(l.length>0&&d.length===0&&o.push("No effort estimates found in task files"),d.length>1){let m=d.reduce((h,y)=>h+y,0)/d.length,p=m*.3;for(let h of d)Math.abs(h-m)>p&&Math.abs(h-m)>m*.5&&o.push(`High variance in effort estimates: ${h}h vs avg ${Math.round(m)}h`)}try{let m=await import("fs"),h=(await import("path")).join(e,"dependency-graph.json"),y=m.readFileSync(h,"utf-8"),T=JSON.parse(y);cp(T)&&o.push("Circular dependencies detected in dependency graph");let A=new Set(Object.keys(T));for(let[D,R]of Object.entries(T))if(Array.isArray(R))for(let w of R)A.has(w)||o.push(`Task ${D} references non-existent dependency: ${w}`)}catch{}return{passed:o.length===0&&f===100,coverage_percentage:f,blocking_issues:o,timestamp:n}}function cp(e){let t=new Set,n=new Set;function o(r){t.add(r),n.add(r);let i=e[r]||[];for(let s of i)if(t.has(s)){if(n.has(s))return!0}else if(o(s))return!0;return n.delete(r),!1}for(let r of Object.keys(e))if(!t.has(r)&&o(r))return!0;return!1}var cn=["idea","prd","spec","intents","complete"];function lp(e){let t=cn.indexOf(e);return t===-1||t>=cn.length-1?"complete":cn[t+1]}var ln=class{projectPath;featureName;workflowId;interruptHandler=null;constructor(t,n){this.projectPath=t,this.featureName=n,this.workflowId=n.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"")}async start(t){let n={schema_version:"1.0.0",workflow_id:this.workflowId,feature_name:this.featureName,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),current_stage:"idea",status:"in_progress",artifacts:{idea:null,prd:null,spec:null,intents:null,complete:null},validation_results:{idea:null,prd:null,spec:null,intents:null,complete:null},resume_context:{initial_prompt:t}};try{await Oa(this.projectPath,this.workflowId)}catch(o){let r=o;throw console.error(`[WorkflowEngine] Failed to initialize workflow directory: ${r.message}`),new Error(`Failed to start workflow: Could not create directory structure - ${r.message}`)}try{await $e(this.projectPath,n)}catch(o){let r=o;throw console.error(`[WorkflowEngine] Failed to save initial checkpoint: ${r.message}`),new Error(`Failed to start workflow: Could not save checkpoint - ${r.message}`)}this.setupInterruptHandler();try{await this.executeStage("idea")}catch(o){let r=o;console.error(`[WorkflowEngine] Failed to execute IDEA stage: ${r.message}`);try{let i=await me(this.projectPath,this.workflowId);i&&(i.status="paused",i.resume_context={...i.resume_context,error_message:r.message,failed_stage:"idea"},await $e(this.projectPath,i),console.log("[WorkflowEngine] Workflow saved as paused. Resume with `/plan continue`"))}catch(i){console.warn("[WorkflowEngine] Failed to save error checkpoint:",i.message)}throw new Error(`Failed to execute IDEA stage: ${r.message}`)}finally{this.cleanupInterruptHandler()}}async resume(){let t;try{t=await me(this.projectPath,this.workflowId)}catch(o){let r=o;throw console.error(`[WorkflowEngine] Failed to load checkpoint for resume: ${r.message}`),new Error(`Failed to resume workflow: Could not load checkpoint - ${r.message}`)}if(!t)throw console.error(`[WorkflowEngine] No checkpoint found for workflow: ${this.workflowId}`),console.error("[WorkflowEngine] Available workflows: Run 'olympus workflow list' to see workflows"),new Error(`No checkpoint found for workflow: ${this.workflowId}`);if(t.status==="complete")return"Workflow already complete";if(t.status==="paused"){t.status="in_progress";try{await $e(this.projectPath,t)}catch(o){let r=o;throw console.error(`[WorkflowEngine] Failed to update checkpoint status: ${r.message}`),new Error(`Failed to resume workflow: Could not save checkpoint - ${r.message}`)}}this.setupInterruptHandler();let n=t.current_stage;try{await this.executeStage(n)}catch(o){let r=o;console.error(`[WorkflowEngine] Failed to execute ${n} stage: ${r.message}`);try{let i=await me(this.projectPath,this.workflowId);i&&(i.status="paused",i.resume_context={...i.resume_context,error_message:r.message,failed_stage:n},await $e(this.projectPath,i),console.log("[WorkflowEngine] Workflow saved as paused. Fix the issue and resume with `/plan continue`"))}catch(i){console.warn("[WorkflowEngine] Failed to save error checkpoint:",i.message)}throw new Error(`Failed to execute ${n} stage: ${r.message}`)}finally{this.cleanupInterruptHandler()}return`Resumed workflow from stage: ${n}`}async pause(){let t;try{t=await me(this.projectPath,this.workflowId)}catch(n){let o=n;throw console.error(`[WorkflowEngine] Failed to load checkpoint for pause: ${o.message}`),new Error(`Failed to pause workflow: Could not load checkpoint - ${o.message}`)}if(!t)throw console.error(`[WorkflowEngine] No checkpoint found for workflow: ${this.workflowId}`),new Error(`No checkpoint found for workflow: ${this.workflowId}`);t.status="paused";try{await $e(this.projectPath,t)}catch(n){let o=n;throw console.error(`[WorkflowEngine] Failed to save paused checkpoint: ${o.message}`),new Error(`Failed to pause workflow: Could not save checkpoint - ${o.message}`)}return`.olympus/workflow/${this.workflowId}/checkpoint.json`}async executeStage(t){if(t==="complete")throw new Error("No execution for complete stage");let n=await me(this.projectPath,this.workflowId);if(!n)throw new Error(`No checkpoint found for workflow: ${this.workflowId}`);switch(t){case"idea":await this.executeIdeaStage(n);break;case"prd":await this.executePrdStage(n);break;case"spec":await this.executeSpecStage(n);break;case"intents":await this.executeIntentsStage(n);break}let o=`${t.toUpperCase()}-001`,r=t==="intents"?`.olympus/workflow/${this.workflowId}/intents/`:`.olympus/workflow/${this.workflowId}/${t}.md`;n.artifacts[t]={id:o,path:r,created_at:new Date().toISOString(),validation_passed:n.validation_results[t]?.passed??!1};let i=lp(t);n.current_stage=i,i==="complete"&&(n.status="complete"),await $e(this.projectPath,n)}async getStatus(){let t;try{t=await me(this.projectPath,this.workflowId)}catch(o){let r=o;throw console.error(`[WorkflowEngine] Failed to load checkpoint for status: ${r.message}`),new Error(`Failed to get workflow status: Could not load checkpoint - ${r.message}`)}if(!t)throw console.error(`[WorkflowEngine] No checkpoint found for workflow: ${this.workflowId}`),new Error(`No checkpoint found for workflow: ${this.workflowId}`);let n=[];for(let o of cn){let r=t.artifacts[o];r&&n.push(r)}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}}setupInterruptHandler(){this.interruptHandler=async()=>{console.log(`
|
|
201
|
+
[WorkflowEngine] Workflow interrupted - saving checkpoint...`);try{let t=await me(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 $e(this.projectPath,t),console.log("[WorkflowEngine] Checkpoint saved. Resume with `/plan 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 executeIdeaStage(t){let n=t.resume_context?.initial_prompt||"No initial prompt provided";console.log(`[WorkflowEngine] Executing IDEA stage for feature: ${this.featureName}`),console.log(`[WorkflowEngine] Initial prompt: ${n}`),console.log("[WorkflowEngine] Generating IDEA artifact with structured format");let o="IDEA-001",r=new Date().toISOString(),i=`---
|
|
202
|
+
id: ${o}
|
|
203
|
+
feature: ${this.workflowId}
|
|
204
|
+
feature_name: ${this.featureName}
|
|
205
|
+
created: ${r}
|
|
206
|
+
risk_tier: 2
|
|
207
|
+
---
|
|
208
|
+
|
|
209
|
+
## Problem Statement
|
|
210
|
+
|
|
211
|
+
**Feature**: ${this.featureName}
|
|
212
|
+
|
|
213
|
+
${n}
|
|
214
|
+
|
|
215
|
+
This feature addresses a specific need identified by stakeholders. The goal is to implement a solution that meets user requirements while maintaining system quality and performance standards.
|
|
216
|
+
|
|
217
|
+
## Business Context
|
|
218
|
+
|
|
219
|
+
This feature will benefit end users by providing new functionality that enhances their workflow. The implementation aligns with our strategic goals of improving user experience and system capabilities.
|
|
220
|
+
|
|
221
|
+
**Target Users**: Primary users who will directly interact with this feature
|
|
222
|
+
**Expected Impact**: Improved user satisfaction and operational efficiency
|
|
223
|
+
**Strategic Alignment**: Supports product roadmap and business objectives
|
|
224
|
+
|
|
225
|
+
## Success Metrics
|
|
226
|
+
|
|
227
|
+
- **Metric 1**: Successful implementation with all acceptance criteria met (target: 100% completion)
|
|
228
|
+
- **Metric 2**: Zero critical bugs in production within first 30 days (target: 0 P0/P1 issues)
|
|
229
|
+
- **Metric 3**: Positive user feedback and adoption rate (target: >80% user satisfaction)
|
|
230
|
+
|
|
231
|
+
## Constraints
|
|
232
|
+
|
|
233
|
+
- **Technical**: Must integrate with existing system architecture and maintain compatibility
|
|
234
|
+
- **Timeline**: Development should follow standard sprint cycles and delivery timelines
|
|
235
|
+
- **Budget**: Implementation within allocated development resources and infrastructure costs
|
|
236
|
+
- **Resources**: Available team capacity and technical expertise
|
|
237
|
+
- **Policy**: Compliance with security standards, data privacy regulations, and coding best practices
|
|
238
|
+
|
|
239
|
+
## Solution Approach
|
|
240
|
+
|
|
241
|
+
The proposed solution will follow a phased implementation approach:
|
|
242
|
+
|
|
243
|
+
1. **Phase 1 - Planning**: Define detailed requirements, technical design, and implementation plan
|
|
244
|
+
2. **Phase 2 - Development**: Implement core functionality with iterative testing
|
|
245
|
+
3. **Phase 3 - Validation**: Comprehensive testing, security review, and performance validation
|
|
246
|
+
4. **Phase 4 - Deployment**: Staged rollout with monitoring and support
|
|
247
|
+
|
|
248
|
+
**Key Considerations**:
|
|
249
|
+
- Maintain backward compatibility where applicable
|
|
250
|
+
- Ensure scalability and performance
|
|
251
|
+
- Implement proper error handling and logging
|
|
252
|
+
- Follow established coding standards and patterns
|
|
253
|
+
|
|
254
|
+
## Risk Assessment
|
|
255
|
+
|
|
256
|
+
**Risk Tier**: 2 (Medium)
|
|
257
|
+
|
|
258
|
+
**Justification**: This is a standard feature implementation with moderate complexity. While there are some unknowns in requirements and integration points, the domain is well-understood and the impact is manageable with proper testing and validation.
|
|
259
|
+
|
|
260
|
+
**Key Risks**:
|
|
261
|
+
- **Integration Complexity**: May encounter challenges integrating with existing systems
|
|
262
|
+
- **Scope Creep**: Requirements may evolve during implementation
|
|
263
|
+
- **Resource Availability**: Team capacity constraints could impact timeline
|
|
264
|
+
- **Technical Debt**: Need to balance new features with code quality and maintainability
|
|
265
|
+
|
|
266
|
+
**Mitigation Strategies**:
|
|
267
|
+
- Early prototyping to validate integration approach
|
|
268
|
+
- Regular stakeholder communication to manage scope
|
|
269
|
+
- Incremental delivery to reduce risk
|
|
270
|
+
- Comprehensive testing and code review processes
|
|
271
|
+
|
|
272
|
+
---
|
|
273
|
+
*Generated by WorkflowEngine*
|
|
274
|
+
`;await an(this.projectPath,this.workflowId,"idea",i);let s=Fe(this.projectPath,this.workflowId,"idea");console.log(`[WorkflowEngine] Validating IDEA artifact at: ${s}`);let c=await Ra(s);t.validation_results.idea=c,c.passed?console.log("[WorkflowEngine] IDEA validation passed"):(console.log("[WorkflowEngine] IDEA validation failed:",c.blocking_issues),console.log(`[WorkflowEngine] Coverage: ${c.coverage_percentage}%`))}async executePrdStage(t){console.log(`[WorkflowEngine] Executing PRD stage for feature: ${this.featureName}`);let n=Fe(this.projectPath,this.workflowId,"idea");console.log(`[WorkflowEngine] Reading IDEA artifact from: ${n}`),console.log("[WorkflowEngine] Generating PRD artifact with user stories");let o="PRD-001",r=new Date().toISOString(),i=`---
|
|
275
|
+
id: ${o}
|
|
276
|
+
feature: ${this.workflowId}
|
|
277
|
+
created: ${r}
|
|
278
|
+
based_on: IDEA-001
|
|
279
|
+
---
|
|
280
|
+
|
|
281
|
+
## Overview
|
|
282
|
+
|
|
283
|
+
This PRD defines the product requirements for ${this.featureName}. It translates the strategic vision from the IDEA artifact into actionable user stories with clear acceptance criteria.
|
|
284
|
+
|
|
285
|
+
## User Stories
|
|
286
|
+
|
|
287
|
+
### US-001: Core Feature Implementation
|
|
288
|
+
**As a** user
|
|
289
|
+
**I want** to use ${this.featureName}
|
|
290
|
+
**So that** I can benefit from the new functionality
|
|
291
|
+
|
|
292
|
+
**Acceptance Criteria:**
|
|
293
|
+
- [ ] Feature is accessible through the standard user interface
|
|
294
|
+
- [ ] Feature functions according to specification
|
|
295
|
+
- [ ] Feature integrates with existing system components
|
|
296
|
+
- [ ] Feature handles error cases gracefully
|
|
297
|
+
|
|
298
|
+
**Technical Notes:**
|
|
299
|
+
- Must maintain compatibility with existing architecture
|
|
300
|
+
- Follow established coding patterns and standards
|
|
301
|
+
|
|
302
|
+
### US-002: Technical Integration
|
|
303
|
+
**As a** developer
|
|
304
|
+
**I want** the feature to integrate seamlessly with existing systems
|
|
305
|
+
**So that** we maintain system stability and consistency
|
|
306
|
+
|
|
307
|
+
**Acceptance Criteria:**
|
|
308
|
+
- [ ] All API contracts are maintained
|
|
309
|
+
- [ ] Integration tests pass successfully
|
|
310
|
+
- [ ] No breaking changes to existing functionality
|
|
311
|
+
- [ ] Performance metrics remain within acceptable bounds
|
|
312
|
+
|
|
313
|
+
**Technical Notes:**
|
|
314
|
+
- Requires review of existing integration points
|
|
315
|
+
- May need adapter patterns for legacy components
|
|
316
|
+
|
|
317
|
+
### US-003: Resource Management
|
|
318
|
+
**As a** system administrator
|
|
319
|
+
**I want** the feature to operate within resource constraints
|
|
320
|
+
**So that** system performance and costs remain optimal
|
|
321
|
+
|
|
322
|
+
**Acceptance Criteria:**
|
|
323
|
+
- [ ] Resource usage stays within budget constraints
|
|
324
|
+
- [ ] Scaling strategy is defined and documented
|
|
325
|
+
- [ ] Monitoring and alerting are configured
|
|
326
|
+
- [ ] Capacity planning is completed
|
|
327
|
+
|
|
328
|
+
**Technical Notes:**
|
|
329
|
+
- Consider horizontal scaling for high-load scenarios
|
|
330
|
+
- Implement resource pooling where appropriate
|
|
331
|
+
|
|
332
|
+
### US-004: Timeline Delivery
|
|
333
|
+
**As a** project stakeholder
|
|
334
|
+
**I want** the feature delivered according to schedule
|
|
335
|
+
**So that** we meet business commitments and milestones
|
|
336
|
+
|
|
337
|
+
**Acceptance Criteria:**
|
|
338
|
+
- [ ] Implementation follows defined sprint cycles
|
|
339
|
+
- [ ] Key milestones are tracked and met
|
|
340
|
+
- [ ] Blockers are identified and resolved promptly
|
|
341
|
+
- [ ] Regular status updates are provided
|
|
342
|
+
|
|
343
|
+
**Technical Notes:**
|
|
344
|
+
- Use iterative development approach
|
|
345
|
+
- Prioritize MVP features first
|
|
346
|
+
|
|
347
|
+
### US-005: Compliance and Security
|
|
348
|
+
**As a** compliance officer
|
|
349
|
+
**I want** the feature to meet security and policy requirements
|
|
350
|
+
**So that** we maintain regulatory compliance and protect user data
|
|
351
|
+
|
|
352
|
+
**Acceptance Criteria:**
|
|
353
|
+
- [ ] Security review completed and approved
|
|
354
|
+
- [ ] Data privacy requirements satisfied
|
|
355
|
+
- [ ] Access controls properly implemented
|
|
356
|
+
- [ ] Audit logging in place
|
|
357
|
+
|
|
358
|
+
**Technical Notes:**
|
|
359
|
+
- Follow OWASP security guidelines
|
|
360
|
+
- Implement principle of least privilege
|
|
361
|
+
|
|
362
|
+
## Requirement Coverage
|
|
363
|
+
|
|
364
|
+
| IDEA Constraint | PRD User Story | Coverage |
|
|
365
|
+
|-----------------|----------------|----------|
|
|
366
|
+
| Technical constraints | US-001, US-002 | \u2713 |
|
|
367
|
+
| Timeline constraints | US-004 | \u2713 |
|
|
368
|
+
| Budget constraints | US-003 | \u2713 |
|
|
369
|
+
| Resource constraints | US-003 | \u2713 |
|
|
370
|
+
| Policy constraints | US-005 | \u2713 |
|
|
371
|
+
|
|
372
|
+
**Coverage Summary:**
|
|
373
|
+
- Total constraints: 5
|
|
374
|
+
- Covered: 5 (100%)
|
|
375
|
+
- Uncovered: None
|
|
376
|
+
|
|
377
|
+
## Out of Scope
|
|
378
|
+
|
|
379
|
+
The following items are explicitly excluded from this PRD:
|
|
380
|
+
- Future enhancements not included in initial requirements
|
|
381
|
+
- Integration with systems outside the current scope
|
|
382
|
+
- Features that require additional budget allocation
|
|
383
|
+
- Changes to unrelated system components
|
|
384
|
+
|
|
385
|
+
## Dependencies
|
|
386
|
+
|
|
387
|
+
**External Dependencies:**
|
|
388
|
+
- Existing system infrastructure and services
|
|
389
|
+
- Third-party libraries and frameworks (as needed)
|
|
390
|
+
- Development and testing environments
|
|
391
|
+
|
|
392
|
+
**Internal Dependencies:**
|
|
393
|
+
- Team availability and resource allocation
|
|
394
|
+
- Completion of prerequisite tasks or features
|
|
395
|
+
- Access to necessary systems and data
|
|
396
|
+
|
|
397
|
+
## Risks
|
|
398
|
+
|
|
399
|
+
**Technical Risks:**
|
|
400
|
+
- Integration complexity may require additional investigation
|
|
401
|
+
- Performance requirements may need optimization iterations
|
|
402
|
+
- Technical debt may need to be addressed during implementation
|
|
403
|
+
|
|
404
|
+
**Mitigation:**
|
|
405
|
+
- Early prototyping and proof-of-concept work
|
|
406
|
+
- Regular technical reviews and architecture discussions
|
|
407
|
+
- Incremental delivery with continuous testing
|
|
408
|
+
|
|
409
|
+
**Schedule Risks:**
|
|
410
|
+
- Resource constraints could impact delivery timeline
|
|
411
|
+
- Unexpected technical challenges may arise
|
|
412
|
+
- Scope creep from evolving requirements
|
|
413
|
+
|
|
414
|
+
**Mitigation:**
|
|
415
|
+
- Maintain clear scope boundaries
|
|
416
|
+
- Regular stakeholder communication
|
|
417
|
+
- Buffer time for contingencies
|
|
418
|
+
|
|
419
|
+
## Success Metrics
|
|
420
|
+
|
|
421
|
+
Success will be measured using the following criteria from the IDEA artifact:
|
|
422
|
+
- **Implementation Completeness**: All acceptance criteria met (target: 100%)
|
|
423
|
+
- **Quality**: Zero critical defects in production (target: 0 P0/P1 issues)
|
|
424
|
+
- **User Satisfaction**: Positive feedback and adoption (target: >80% satisfaction)
|
|
425
|
+
|
|
426
|
+
---
|
|
427
|
+
*Generated by WorkflowEngine based on IDEA-001*
|
|
428
|
+
`;await an(this.projectPath,this.workflowId,"prd",i);let s=Fe(this.projectPath,this.workflowId,"prd");console.log(`[WorkflowEngine] Validating PRD artifact at: ${s}`);let c=await Aa(s,n);t.validation_results.prd=c,c.passed?(console.log("[WorkflowEngine] PRD validation passed"),console.log(`[WorkflowEngine] Coverage: ${c.coverage_percentage}%`)):(console.log("[WorkflowEngine] PRD validation failed:",c.blocking_issues),console.log(`[WorkflowEngine] Coverage: ${c.coverage_percentage}%`))}async executeSpecStage(t){console.log(`[WorkflowEngine] Executing SPEC stage for feature: ${this.featureName}`);let n=Fe(this.projectPath,this.workflowId,"prd");console.log(`[WorkflowEngine] Reading PRD artifact from: ${n}`),console.log("[WorkflowEngine] Generating SPEC artifact with technical design");let r=(await import("fs")).readFileSync(n,"utf-8"),i=[],s=r.split(`
|
|
429
|
+
`);for(let f of s){let g=f.match(/^###?\s+(US-\d+)/);g&&i.push(g[1])}let c="SPEC-001",a=new Date().toISOString(),l=`---
|
|
430
|
+
id: ${c}
|
|
431
|
+
feature: ${this.workflowId}
|
|
432
|
+
created: ${a}
|
|
433
|
+
based_on: IDEA-001
|
|
434
|
+
prd_id: PRD-001
|
|
435
|
+
---
|
|
436
|
+
|
|
437
|
+
## Overview
|
|
438
|
+
|
|
439
|
+
This technical specification defines the architecture, data models, and implementation approach for ${this.featureName}. It translates the product requirements from the PRD into concrete technical designs.
|
|
440
|
+
|
|
441
|
+
## Components
|
|
442
|
+
|
|
443
|
+
### Frontend Components
|
|
444
|
+
|
|
445
|
+
**User Interface Layer**
|
|
446
|
+
- Main feature UI component with state management
|
|
447
|
+
- Form validation and input handling
|
|
448
|
+
- Error boundary and fallback UI
|
|
449
|
+
- Responsive layout adapters
|
|
450
|
+
|
|
451
|
+
**Technical Requirements:**
|
|
452
|
+
- Component library: React/Vue/Angular (as per stack)
|
|
453
|
+
- State management: Redux/Context API/Vuex
|
|
454
|
+
- Styling: CSS modules or styled-components
|
|
455
|
+
- Accessibility: WCAG 2.1 AA compliance
|
|
456
|
+
|
|
457
|
+
### Backend Services
|
|
458
|
+
|
|
459
|
+
**API Service**
|
|
460
|
+
- RESTful API endpoints for feature operations
|
|
461
|
+
- Request validation middleware
|
|
462
|
+
- Business logic layer
|
|
463
|
+
- Data access layer
|
|
464
|
+
|
|
465
|
+
**Technical Requirements:**
|
|
466
|
+
- Framework: Express/FastAPI/Spring Boot (as per stack)
|
|
467
|
+
- Validation: Joi/Pydantic/Bean Validation
|
|
468
|
+
- ORM: TypeORM/SQLAlchemy/JPA
|
|
469
|
+
- Logging: Winston/Python logging/SLF4J
|
|
470
|
+
|
|
471
|
+
### Database Components
|
|
472
|
+
|
|
473
|
+
**Data Storage**
|
|
474
|
+
- Primary database tables/collections
|
|
475
|
+
- Indexing strategy for performance
|
|
476
|
+
- Migration scripts
|
|
477
|
+
- Backup procedures
|
|
478
|
+
|
|
479
|
+
**Technical Requirements:**
|
|
480
|
+
- Database: PostgreSQL/MySQL/MongoDB (as per stack)
|
|
481
|
+
- Connection pooling: pgbouncer/connection pool
|
|
482
|
+
- Replication: Primary-replica setup
|
|
483
|
+
- Backup: Daily automated backups
|
|
484
|
+
|
|
485
|
+
### Infrastructure Components
|
|
486
|
+
|
|
487
|
+
**Deployment Architecture**
|
|
488
|
+
- Application server configuration
|
|
489
|
+
- Load balancer setup
|
|
490
|
+
- CDN integration for static assets
|
|
491
|
+
- Monitoring and alerting
|
|
492
|
+
|
|
493
|
+
**Technical Requirements:**
|
|
494
|
+
- Container: Docker
|
|
495
|
+
- Orchestration: Kubernetes/Docker Compose
|
|
496
|
+
- CI/CD: GitHub Actions/Jenkins/GitLab CI
|
|
497
|
+
- Monitoring: Prometheus/Grafana/Datadog
|
|
498
|
+
|
|
499
|
+
## Database Schema
|
|
500
|
+
|
|
501
|
+
### Tables/Collections
|
|
502
|
+
|
|
503
|
+
**feature_data**
|
|
504
|
+
- id: UUID PRIMARY KEY
|
|
505
|
+
- user_id: UUID NOT NULL FOREIGN KEY \u2192 users.id
|
|
506
|
+
- feature_name: VARCHAR(255) NOT NULL
|
|
507
|
+
- data_payload: JSONB
|
|
508
|
+
- status: VARCHAR(50) NOT NULL
|
|
509
|
+
- created_at: TIMESTAMP NOT NULL DEFAULT NOW()
|
|
510
|
+
- updated_at: TIMESTAMP NOT NULL DEFAULT NOW()
|
|
511
|
+
|
|
512
|
+
**Indexes:**
|
|
513
|
+
- idx_feature_data_user_id ON feature_data(user_id)
|
|
514
|
+
- idx_feature_data_status ON feature_data(status)
|
|
515
|
+
- idx_feature_data_created_at ON feature_data(created_at)
|
|
516
|
+
|
|
517
|
+
**feature_audit_log**
|
|
518
|
+
- id: UUID PRIMARY KEY
|
|
519
|
+
- feature_data_id: UUID NOT NULL FOREIGN KEY \u2192 feature_data.id
|
|
520
|
+
- action: VARCHAR(50) NOT NULL
|
|
521
|
+
- actor_id: UUID NOT NULL FOREIGN KEY \u2192 users.id
|
|
522
|
+
- changes: JSONB
|
|
523
|
+
- timestamp: TIMESTAMP NOT NULL DEFAULT NOW()
|
|
524
|
+
|
|
525
|
+
**Indexes:**
|
|
526
|
+
- idx_feature_audit_feature_id ON feature_audit_log(feature_data_id)
|
|
527
|
+
- idx_feature_audit_timestamp ON feature_audit_log(timestamp)
|
|
528
|
+
|
|
529
|
+
## API Endpoints
|
|
530
|
+
|
|
531
|
+
### POST /api/v1/feature
|
|
532
|
+
Create new feature instance
|
|
533
|
+
|
|
534
|
+
**Request:**
|
|
535
|
+
\`\`\`json
|
|
536
|
+
{
|
|
537
|
+
"feature_name": "string",
|
|
538
|
+
"data_payload": {},
|
|
539
|
+
"user_id": "uuid"
|
|
540
|
+
}
|
|
541
|
+
\`\`\`
|
|
542
|
+
|
|
543
|
+
**Response (201 Created):**
|
|
544
|
+
\`\`\`json
|
|
545
|
+
{
|
|
546
|
+
"id": "uuid",
|
|
547
|
+
"feature_name": "string",
|
|
548
|
+
"status": "active",
|
|
549
|
+
"created_at": "timestamp"
|
|
550
|
+
}
|
|
551
|
+
\`\`\`
|
|
552
|
+
|
|
553
|
+
**Authentication:** Bearer token required
|
|
554
|
+
**Rate Limit:** 100 requests/minute per user
|
|
555
|
+
|
|
556
|
+
### GET /api/v1/feature/:id
|
|
557
|
+
Retrieve feature instance by ID
|
|
558
|
+
|
|
559
|
+
**Response (200 OK):**
|
|
560
|
+
\`\`\`json
|
|
561
|
+
{
|
|
562
|
+
"id": "uuid",
|
|
563
|
+
"feature_name": "string",
|
|
564
|
+
"data_payload": {},
|
|
565
|
+
"status": "active",
|
|
566
|
+
"created_at": "timestamp",
|
|
567
|
+
"updated_at": "timestamp"
|
|
568
|
+
}
|
|
569
|
+
\`\`\`
|
|
570
|
+
|
|
571
|
+
**Authentication:** Bearer token required
|
|
572
|
+
**Rate Limit:** 1000 requests/minute per user
|
|
573
|
+
|
|
574
|
+
### PUT /api/v1/feature/:id
|
|
575
|
+
Update feature instance
|
|
576
|
+
|
|
577
|
+
**Request:**
|
|
578
|
+
\`\`\`json
|
|
579
|
+
{
|
|
580
|
+
"data_payload": {},
|
|
581
|
+
"status": "active" | "inactive"
|
|
582
|
+
}
|
|
583
|
+
\`\`\`
|
|
584
|
+
|
|
585
|
+
**Response (200 OK):**
|
|
586
|
+
\`\`\`json
|
|
587
|
+
{
|
|
588
|
+
"id": "uuid",
|
|
589
|
+
"feature_name": "string",
|
|
590
|
+
"data_payload": {},
|
|
591
|
+
"status": "active",
|
|
592
|
+
"updated_at": "timestamp"
|
|
593
|
+
}
|
|
594
|
+
\`\`\`
|
|
595
|
+
|
|
596
|
+
**Authentication:** Bearer token required
|
|
597
|
+
**Rate Limit:** 100 requests/minute per user
|
|
598
|
+
|
|
599
|
+
### DELETE /api/v1/feature/:id
|
|
600
|
+
Delete feature instance (soft delete)
|
|
601
|
+
|
|
602
|
+
**Response (204 No Content)**
|
|
603
|
+
|
|
604
|
+
**Authentication:** Bearer token required
|
|
605
|
+
**Rate Limit:** 50 requests/minute per user
|
|
606
|
+
|
|
607
|
+
## Authentication/Authorization
|
|
608
|
+
|
|
609
|
+
### Authentication Mechanism
|
|
610
|
+
|
|
611
|
+
**JWT Token-Based Authentication**
|
|
612
|
+
- Tokens issued on successful login
|
|
613
|
+
- Token expiry: 24 hours
|
|
614
|
+
- Refresh token rotation enabled
|
|
615
|
+
- Token blacklist for logout
|
|
616
|
+
|
|
617
|
+
**Implementation:**
|
|
618
|
+
\`\`\`typescript
|
|
619
|
+
middleware.authenticate = (req, res, next) => {
|
|
620
|
+
const token = extractToken(req);
|
|
621
|
+
const payload = verifyJWT(token);
|
|
622
|
+
req.user = payload;
|
|
623
|
+
next();
|
|
624
|
+
};
|
|
625
|
+
\`\`\`
|
|
626
|
+
|
|
627
|
+
### Authorization Model
|
|
628
|
+
|
|
629
|
+
**Role-Based Access Control (RBAC)**
|
|
630
|
+
- Roles: admin, user, guest
|
|
631
|
+
- Permissions: create, read, update, delete
|
|
632
|
+
- Resource-level permissions
|
|
633
|
+
|
|
634
|
+
**Permission Matrix:**
|
|
635
|
+
| Role | Create | Read | Update | Delete |
|
|
636
|
+
|------|--------|------|--------|--------|
|
|
637
|
+
| Admin | \u2713 | \u2713 | \u2713 | \u2713 |
|
|
638
|
+
| User | \u2713 | \u2713 (own) | \u2713 (own) | \u2713 (own) |
|
|
639
|
+
| Guest | \u2717 | \u2713 (public) | \u2717 | \u2717 |
|
|
640
|
+
|
|
641
|
+
### Token Management
|
|
642
|
+
|
|
643
|
+
**Token Storage:**
|
|
644
|
+
- Access token: HTTP-only cookie or localStorage
|
|
645
|
+
- Refresh token: HTTP-only cookie (secure flag)
|
|
646
|
+
|
|
647
|
+
**Token Refresh Flow:**
|
|
648
|
+
1. Client detects expired access token
|
|
649
|
+
2. Send refresh token to /api/v1/auth/refresh
|
|
650
|
+
3. Server validates refresh token
|
|
651
|
+
4. Issue new access token and refresh token pair
|
|
652
|
+
5. Client updates stored tokens
|
|
653
|
+
|
|
654
|
+
## Error Handling
|
|
655
|
+
|
|
656
|
+
### Error Types
|
|
657
|
+
|
|
658
|
+
**Client Errors (4xx)**
|
|
659
|
+
- 400 Bad Request: Invalid input data
|
|
660
|
+
- 401 Unauthorized: Missing or invalid authentication
|
|
661
|
+
- 403 Forbidden: Insufficient permissions
|
|
662
|
+
- 404 Not Found: Resource does not exist
|
|
663
|
+
- 409 Conflict: Resource conflict (duplicate entry)
|
|
664
|
+
- 422 Unprocessable Entity: Validation errors
|
|
665
|
+
- 429 Too Many Requests: Rate limit exceeded
|
|
666
|
+
|
|
667
|
+
**Server Errors (5xx)**
|
|
668
|
+
- 500 Internal Server Error: Unexpected error
|
|
669
|
+
- 502 Bad Gateway: Upstream service failure
|
|
670
|
+
- 503 Service Unavailable: Temporary unavailability
|
|
671
|
+
- 504 Gateway Timeout: Upstream timeout
|
|
672
|
+
|
|
673
|
+
### Error Response Format
|
|
674
|
+
|
|
675
|
+
\`\`\`json
|
|
676
|
+
{
|
|
677
|
+
"error": {
|
|
678
|
+
"code": "VALIDATION_ERROR",
|
|
679
|
+
"message": "Invalid input data",
|
|
680
|
+
"details": [
|
|
681
|
+
{
|
|
682
|
+
"field": "feature_name",
|
|
683
|
+
"message": "Feature name is required"
|
|
684
|
+
}
|
|
685
|
+
],
|
|
686
|
+
"request_id": "uuid"
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
\`\`\`
|
|
690
|
+
|
|
691
|
+
### Logging Strategy
|
|
692
|
+
|
|
693
|
+
**Log Levels:**
|
|
694
|
+
- ERROR: Critical failures requiring immediate attention
|
|
695
|
+
- WARN: Non-critical issues that should be investigated
|
|
696
|
+
- INFO: General operational events
|
|
697
|
+
- DEBUG: Detailed diagnostic information
|
|
698
|
+
|
|
699
|
+
**Log Format (JSON):**
|
|
700
|
+
\`\`\`json
|
|
701
|
+
{
|
|
702
|
+
"timestamp": "ISO8601",
|
|
703
|
+
"level": "ERROR",
|
|
704
|
+
"service": "feature-api",
|
|
705
|
+
"message": "Database connection failed",
|
|
706
|
+
"context": {
|
|
707
|
+
"request_id": "uuid",
|
|
708
|
+
"user_id": "uuid",
|
|
709
|
+
"error": "Connection timeout"
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
\`\`\`
|
|
713
|
+
|
|
714
|
+
**Log Aggregation:**
|
|
715
|
+
- Centralized logging: ELK Stack/Splunk/CloudWatch
|
|
716
|
+
- Log retention: 30 days for INFO, 90 days for ERROR
|
|
717
|
+
- Alert triggers: Error rate > 1% over 5 minutes
|
|
718
|
+
|
|
719
|
+
## Performance Considerations
|
|
720
|
+
|
|
721
|
+
### Caching Strategy
|
|
722
|
+
|
|
723
|
+
**Application-Level Caching**
|
|
724
|
+
- Cache frequently accessed data (user profiles, feature metadata)
|
|
725
|
+
- Cache TTL: 5 minutes for dynamic data, 1 hour for static data
|
|
726
|
+
- Cache invalidation on data mutation
|
|
727
|
+
|
|
728
|
+
**Implementation:**
|
|
729
|
+
\`\`\`typescript
|
|
730
|
+
cache.get('feature:' + id, async () => {
|
|
731
|
+
return await database.getFeature(id);
|
|
732
|
+
}, { ttl: 300 });
|
|
733
|
+
\`\`\`
|
|
734
|
+
|
|
735
|
+
**CDN Caching**
|
|
736
|
+
- Static assets: max-age=31536000 (1 year)
|
|
737
|
+
- API responses: Cache-Control: no-cache for authenticated endpoints
|
|
738
|
+
- Public data: Cache-Control: public, max-age=300
|
|
739
|
+
|
|
740
|
+
### Database Optimization
|
|
741
|
+
|
|
742
|
+
**Query Optimization**
|
|
743
|
+
- Use prepared statements to prevent SQL injection
|
|
744
|
+
- Index foreign keys and frequently queried columns
|
|
745
|
+
- Use connection pooling (min: 10, max: 50 connections)
|
|
746
|
+
- Implement query timeouts (5 seconds)
|
|
747
|
+
|
|
748
|
+
**Database Scaling:**
|
|
749
|
+
- Read replicas for heavy read workloads
|
|
750
|
+
- Partitioning for large tables (by date/user_id)
|
|
751
|
+
- Query result pagination (max 100 records per page)
|
|
752
|
+
|
|
753
|
+
### Rate Limiting
|
|
754
|
+
|
|
755
|
+
**Implementation:**
|
|
756
|
+
- Token bucket algorithm
|
|
757
|
+
- Per-user limits stored in Redis
|
|
758
|
+
- Rate limit headers in response:
|
|
759
|
+
- X-RateLimit-Limit: Maximum requests
|
|
760
|
+
- X-RateLimit-Remaining: Remaining requests
|
|
761
|
+
- X-RateLimit-Reset: Reset timestamp
|
|
762
|
+
|
|
763
|
+
**Limits by Endpoint:**
|
|
764
|
+
- POST /api/v1/feature: 100/min
|
|
765
|
+
- GET /api/v1/feature: 1000/min
|
|
766
|
+
- PUT /api/v1/feature: 100/min
|
|
767
|
+
- DELETE /api/v1/feature: 50/min
|
|
768
|
+
|
|
769
|
+
## PRD Coverage
|
|
770
|
+
|
|
771
|
+
This specification addresses all user stories from PRD-001:
|
|
772
|
+
|
|
773
|
+
| PRD User Story | SPEC Coverage |
|
|
774
|
+
|----------------|---------------|${i.map(f=>`
|
|
775
|
+
| ${f} | Components, API Endpoints, Database Schema |`).join("")}
|
|
776
|
+
|
|
777
|
+
**Coverage Summary:**
|
|
778
|
+
- Total user stories: ${i.length}
|
|
779
|
+
- Covered: ${i.length} (100%)
|
|
780
|
+
- Uncovered: None
|
|
781
|
+
|
|
782
|
+
---
|
|
783
|
+
*Generated by WorkflowEngine based on PRD-001*
|
|
784
|
+
`;await an(this.projectPath,this.workflowId,"spec",l);let u=Fe(this.projectPath,this.workflowId,"spec");console.log(`[WorkflowEngine] Validating SPEC artifact at: ${u}`);let d=await ba(u,n);t.validation_results.spec=d,d.passed?(console.log("[WorkflowEngine] SPEC validation passed"),console.log(`[WorkflowEngine] Coverage: ${d.coverage_percentage}%`)):(console.log("[WorkflowEngine] SPEC validation failed:",d.blocking_issues),console.log(`[WorkflowEngine] Coverage: ${d.coverage_percentage}%`))}async executeIntentsStage(t){console.log(`[WorkflowEngine] Executing INTENTS stage for feature: ${this.featureName}`);let n=Fe(this.projectPath,this.workflowId,"spec");console.log(`[WorkflowEngine] Reading SPEC artifact from: ${n}`),console.log("[WorkflowEngine] Generating INTENT artifacts with implementation tasks");let o=await Promise.resolve().then(()=>H(sn(),1)),r=await import("path"),i=await o.readFile(n,"utf-8"),s=[],c=i.split(`
|
|
785
|
+
`),a=!1;for(let p of c){if(p.match(/^##\s+Components/i)){a=!0;continue}if(a&&p.match(/^##\s+/)&&(a=!1),a&&p.match(/^###\s+(.+)$/)){let h=p.match(/^###\s+(.+)$/);h&&s.push(h[1].trim())}}let l=r.join(this.projectPath,".olympus","workflow",this.workflowId,"intents");await o.ensureDir(l);let u=new Date().toISOString(),d=[{id:"INTENT-001",title:"Setup Database Schema",component:"Database Components",goal:"Create database tables, indexes, and migration scripts",acceptanceCriteria:["Database tables created with proper schema","Indexes created for performance optimization","Migration scripts tested and validated","Rollback scripts prepared"],steps:["Create migration script for feature_data table","Create migration script for feature_audit_log table","Add indexes on foreign keys and frequently queried columns","Test migration in development environment","Create rollback migration script","Document schema changes"],technicalNotes:"Use migration framework (Flyway/Alembic/TypeORM migrations). Ensure backward compatibility.",dependencies:[],effort:4},{id:"INTENT-002",title:"Implement Backend API Endpoints",component:"Backend Services",goal:"Create RESTful API endpoints for feature operations",acceptanceCriteria:["All CRUD endpoints implemented","Request validation middleware in place","Error handling properly configured","Unit tests passing with >80% coverage"],steps:["Create API route definitions","Implement POST /api/v1/feature endpoint","Implement GET /api/v1/feature/:id endpoint","Implement PUT /api/v1/feature/:id endpoint","Implement DELETE /api/v1/feature/:id endpoint","Add request validation middleware","Add error handling middleware","Write unit tests for all endpoints"],technicalNotes:"Follow REST conventions. Use async/await for database operations. Implement proper error responses.",dependencies:["INTENT-001"],effort:8},{id:"INTENT-003",title:"Build Frontend Components",component:"Frontend Components",goal:"Create user interface components for feature interaction",acceptanceCriteria:["Main feature UI component implemented","Form validation working correctly","Error states handled gracefully","Responsive design across devices","Accessibility standards met (WCAG 2.1 AA)"],steps:["Create main feature component","Implement form inputs with validation","Add error boundary component","Implement loading states","Add success/error notifications","Make responsive for mobile/tablet/desktop","Test with screen readers","Write component tests"],technicalNotes:"Use component library patterns. Implement proper state management. Follow accessibility guidelines.",dependencies:["INTENT-002"],effort:8},{id:"INTENT-004",title:"Implement Authentication and Authorization",component:"Backend Services",goal:"Add authentication and authorization for feature endpoints",acceptanceCriteria:["JWT authentication middleware implemented","Role-based access control enforced","Token refresh mechanism working","Unauthorized access properly blocked"],steps:["Implement JWT verification middleware","Create role-based permission checks","Add token refresh endpoint","Implement token blacklist for logout","Add authentication to all protected routes","Write authentication tests"],technicalNotes:"Use secure token storage. Implement token rotation. Follow OWASP authentication guidelines.",dependencies:["INTENT-002"],effort:4},{id:"INTENT-005",title:"Add Rate Limiting and Caching",component:"Backend Services",goal:"Implement rate limiting and caching for performance and security",acceptanceCriteria:["Rate limiting active on all endpoints","Rate limit headers in responses","Application-level caching implemented","Cache invalidation working correctly"],steps:["Set up Redis for rate limiting and caching","Implement rate limiting middleware","Add rate limit headers to responses","Implement application-level cache","Add cache invalidation on mutations","Configure CDN caching rules","Write performance tests"],technicalNotes:"Use Redis for distributed rate limiting. Implement cache warming strategy. Monitor cache hit rates.",dependencies:["INTENT-002"],effort:4},{id:"INTENT-006",title:"Setup Infrastructure and Deployment",component:"Infrastructure Components",goal:"Configure deployment pipeline and infrastructure",acceptanceCriteria:["Docker container configured and building","CI/CD pipeline running successfully","Monitoring and alerting configured","Staging environment deployed"],steps:["Create Dockerfile for application","Configure Docker Compose for local development","Set up CI/CD pipeline (GitHub Actions/Jenkins)","Configure staging environment","Set up monitoring (Prometheus/Grafana)","Configure alerting rules","Document deployment process"],technicalNotes:"Use multi-stage Docker builds. Implement health checks. Set up automated rollbacks.",dependencies:["INTENT-002","INTENT-003"],effort:8},{id:"INTENT-007",title:"Write Integration Tests and Documentation",component:"Backend Services",goal:"Create comprehensive tests and documentation",acceptanceCriteria:["Integration tests covering all workflows","API documentation complete","Test coverage >80%","Documentation reviewed and approved"],steps:["Write end-to-end integration tests","Test authentication flows","Test error scenarios","Generate API documentation (OpenAPI/Swagger)","Write user-facing documentation","Create troubleshooting guide","Run full test suite"],technicalNotes:"Use test fixtures for data setup. Mock external services. Document edge cases.",dependencies:["INTENT-003","INTENT-004","INTENT-005"],effort:4}];for(let p of d){let h=`---
|
|
786
|
+
id: ${p.id}
|
|
787
|
+
feature: ${this.workflowId}
|
|
788
|
+
created: ${u}
|
|
789
|
+
based_on: SPEC-001
|
|
790
|
+
status: pending
|
|
791
|
+
estimated_effort: ${p.effort}
|
|
792
|
+
dependencies: ${JSON.stringify(p.dependencies)}
|
|
793
|
+
---
|
|
794
|
+
|
|
795
|
+
# Task: ${p.title}
|
|
796
|
+
|
|
797
|
+
## Goal
|
|
798
|
+
|
|
799
|
+
${p.goal}
|
|
800
|
+
|
|
801
|
+
## Component
|
|
802
|
+
|
|
803
|
+
${p.component}
|
|
804
|
+
|
|
805
|
+
## Acceptance Criteria
|
|
806
|
+
|
|
807
|
+
${p.acceptanceCriteria.map(y=>`- [ ] ${y}`).join(`
|
|
808
|
+
`)}
|
|
809
|
+
|
|
810
|
+
## Implementation Steps
|
|
811
|
+
|
|
812
|
+
${p.steps.map((y,T)=>`${T+1}. ${y}`).join(`
|
|
813
|
+
`)}
|
|
814
|
+
|
|
815
|
+
## Technical Notes
|
|
816
|
+
|
|
817
|
+
${p.technicalNotes}
|
|
818
|
+
|
|
819
|
+
## Dependencies
|
|
820
|
+
|
|
821
|
+
${p.dependencies.length>0?p.dependencies.join(", "):"None"}
|
|
822
|
+
|
|
823
|
+
## Estimated Effort
|
|
824
|
+
|
|
825
|
+
${p.effort}h
|
|
826
|
+
|
|
827
|
+
---
|
|
828
|
+
*Generated by WorkflowEngine based on SPEC-001*
|
|
829
|
+
`;await o.writeFile(r.join(l,`${p.id}.md`),h,"utf-8")}let f=d.reduce((p,h)=>p+h.effort,0),g={};for(let p of d)g[p.id]=p.dependencies;await o.writeFile(r.join(l,"dependency-graph.json"),JSON.stringify(g,null,2),"utf-8"),console.log(`[WorkflowEngine] Generated ${d.length} INTENT files`),console.log(`[WorkflowEngine] Total estimated effort: ${f}h`),console.log(`[WorkflowEngine] Validating INTENTS against SPEC at: ${n}`);let m=await Ca(l,n);t.validation_results.intents=m,m.passed?(console.log("[WorkflowEngine] INTENTS validation passed"),console.log(`[WorkflowEngine] Coverage: ${m.coverage_percentage}%`)):(console.log("[WorkflowEngine] INTENTS validation failed:",m.blocking_issues),console.log(`[WorkflowEngine] Coverage: ${m.coverage_percentage}%`))}};var Na={idea:"idea-intake",prd:"prd-writer",spec:"spec-writer",intents:"intent-generator",complete:null};function Pa(e){switch(e){case"idea":return"capture and validate the initial feature concept";case"prd":return"create a comprehensive Product Requirements Document";case"spec":return"write a detailed technical specification";case"intents":return"generate implementation intent files";case"complete":return"finalize and validate all workflow artifacts";default:return"proceed with the next stage"}}function xa(e,t){let n=Na[t.current_stage],o=Pa(t.current_stage),r=`You are beginning a structured workflow for feature: ${e}
|
|
830
|
+
|
|
831
|
+
`;return r+=`Current stage: ${t.current_stage}
|
|
832
|
+
`,r+=`Status: ${t.status}
|
|
833
|
+
|
|
834
|
+
`,n?(r+=`Next step: Invoke the ${n} agent to ${o}
|
|
835
|
+
|
|
836
|
+
`,r+=`Use: Task(subagent_type="${n}", prompt="...")
|
|
837
|
+
`):r+=`Next step: ${o}
|
|
838
|
+
`,r}function Da(e,t){let n=Na[t.current_stage],o=Pa(t.current_stage),r=`Resuming workflow for feature: ${e}
|
|
839
|
+
|
|
840
|
+
`;return r+=`You were interrupted during: ${t.current_stage}
|
|
841
|
+
`,r+=`Last update: ${t.updated_at}
|
|
842
|
+
|
|
843
|
+
`,t.resume_context?r+=`Resume context: ${JSON.stringify(t.resume_context,null,2)}
|
|
844
|
+
|
|
845
|
+
`:r+=`Resume context: No additional context available
|
|
846
|
+
|
|
847
|
+
`,n?(r+=`Continue from where you left off: Invoke the ${n} agent to ${o}
|
|
848
|
+
|
|
849
|
+
`,r+=`Use: Task(subagent_type="${n}", prompt="...")
|
|
850
|
+
`):r+=`Continue from where you left off: ${o}
|
|
851
|
+
`,r}function yo(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 La(){v({name:"structuredWorkflowDetector",event:"UserPromptSubmit",priority:8,handler:async e=>{let t=yo(e);if(!t||!e.directory)return{continue:!0};let n=t.match(/^\/plan\s+(.+?)\s+--structured$/i),o=t.match(/^\/plan\s+continue$/i);if(n){let r=n[1].trim();try{await new ln(e.directory,r).start(r);let s=r.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,""),c=await me(e.directory,s);return c?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:xa(r,c)}}:{continue:!0}}catch(i){return console.error("[Structured Workflow]",i),{continue:!0}}}if(o)try{let r=await _a(e.directory);if(r.length===0)return{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:"No active workflows found. Use `/plan {feature} --structured` to start a new workflow."}};let i=r[0],s=await me(e.directory,i);return s?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:Da(s.feature_name,s)}}:{continue:!0}}catch(r){return console.error("[Workflow Resume]",r),{continue:!0}}return{continue:!0}}}),v({name:"keywordDetector",event:"UserPromptSubmit",priority:10,handler:e=>{let t=yo(e);if(!t)return{continue:!0};let n=Ar(t),o=br(n);if(o.length===0)return{continue:!0};let r=o.some(a=>a.type==="ultrawork"),i=o.some(a=>a.type==="ultrathink"),s=o.some(a=>a.type==="search"),c=o.some(a=>a.type==="analyze");return r?(zr(t,e.sessionId,e.directory||process.cwd()),{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:ti}}):i?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:ni}}:s?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:oi}}:c?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:ri}}:{continue:!0}}}),v({name:"autoSlashCommand",event:"UserPromptSubmit",priority:20,handler:e=>{if(!e.parts)return{continue:!0};let n=jr().processMessage({sessionId:e.sessionId||""},e.parts);return n.detected&&n.injectedMessage?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:n.injectedMessage}}:{continue:!0}}}),v({name:"thinkMode",event:"UserPromptSubmit",priority:30,handler:e=>{if(!e.message||!e.parts)return{continue:!0};let t=Kr(),n=e.sessionId||"default",o={parts:e.parts,message:{model:e.message.model&&e.message.model.providerId&&e.message.model.modelId?{providerId:e.message.model.providerId,modelId:e.message.model.modelId}:void 0}},r=t.processChatParams(n,o);return r.requested&&r.modelSwitched?{continue:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:"[Think Mode Activated] Switched to high-reasoning model variant."}}:{continue:!0}}}),v({name:"learningFeedbackCapture",event:"UserPromptSubmit",priority:100,handler:async e=>{let t=yo(e);return!t||!e.directory?{continue:!0}:(Promise.resolve().then(async()=>{try{await _i({prompt:t,directory:e.directory,sessionId:e.sessionId}),await vi({prompt:t,directory:e.directory,sessionId:e.sessionId})}catch(n){console.error("[Olympus Learning]",n)}}),{continue:!0})}})}var Ve=require("fs"),Ue=require("path"),Ma=require("os");function up(e,t){let n=(0,Ue.join)((0,Ma.homedir)(),".claude"),o=[];e&&(o.push((0,Ue.join)(n,"sessions",e,"todos.json")),o.push((0,Ue.join)(n,"todos",`${e}.json`))),t&&(o.push((0,Ue.join)(t,".olympus","todos.json")),o.push((0,Ue.join)(t,".claude","todos.json")));let r=(0,Ue.join)(n,"todos");if((0,Ve.existsSync)(r))try{let i=(0,Ve.readdirSync)(r);for(let s of i)s.endsWith(".json")&&o.push((0,Ue.join)(r,s))}catch{}return o}function dp(e){try{let t=(0,Ve.readFileSync)(e,"utf-8"),n=JSON.parse(t);return Array.isArray(n)?n.filter(o=>o&&typeof o.content=="string"&&typeof o.status=="string"):n.todos&&Array.isArray(n.todos)?n.todos.filter(o=>{let r=o;return r&&typeof r.content=="string"&&typeof r.status=="string"}):[]}catch{return[]}}function fp(e){return e.status!=="completed"&&e.status!=="cancelled"}async function At(e,t){let n=up(e,t),o=new Set,r=[],i=[];for(let s of n){if(!(0,Ve.existsSync)(s))continue;let c=dp(s);for(let a of c){let l=`${a.content}:${a.status}`;o.has(l)||(o.add(l),r.push(a),fp(a)&&i.push(a))}}return{count:i.length,todos:i,total:r.length}}function $a(e){let t=e.todos.find(n=>n.status==="in_progress");return t||(e.todos.find(n=>n.status==="pending")??null)}var un=require("path");function Fa(e,t=5){return(e.token_efficiency?.invocation_count??0)>=t}var Ua=500;function ja(e){let t=et((0,un.join)(Ne(),"user-preferences.json"),null),n=et((0,un.join)(yt(e),"patterns.json"),null),o=et((0,un.join)(Ne(),"agent-performance.json"),{}),r=[];t&&pp(t)&&r.push(mp(t)),n&&n.conventions.length>0&&r.push(gp(n)),t?.recurring_corrections&&t.recurring_corrections.length>0&&r.push(hp(t.recurring_corrections.slice(0,5)));let i=Object.values(o).filter(a=>a.weak_areas.length>0);i.length>0&&r.push(kp(i));let s=yp(o);if(s&&r.push(s),r.length===0)return"";let c=`<learned-context>
|
|
187
852
|
|
|
188
853
|
${r.join(`
|
|
189
854
|
|
|
@@ -193,21 +858,21 @@ ${r.join(`
|
|
|
193
858
|
|
|
194
859
|
---
|
|
195
860
|
|
|
196
|
-
`;return c.length>
|
|
861
|
+
`;return c.length>Ua*4?c.substring(0,Ua*4)+`
|
|
197
862
|
...</learned-context>
|
|
198
863
|
|
|
199
864
|
---
|
|
200
865
|
|
|
201
|
-
`:c}function
|
|
202
|
-
`)}function
|
|
203
|
-
`)}function
|
|
204
|
-
`)}function
|
|
205
|
-
`)}function
|
|
206
|
-
`)}function
|
|
207
|
-
`)}var
|
|
208
|
-
`).filter(n=>n.trim()).map(n=>JSON.parse(n))}catch(t){return console.error(`[Olympus Learning] Failed to read discoveries: ${t}`),[]}}function
|
|
866
|
+
`:c}function pp(e){return e.verbosity!=="unknown"||e.autonomy!=="unknown"||e.explicit_rules.length>0||e.inferred_preferences.length>0}function mp(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))t.push(`- ${n}`);return t.join(`
|
|
867
|
+
`)}function gp(e){let t=["## Project Conventions"];for(let n of e.conventions.slice(0,5))t.push(`- ${n}`);return e.tech_stack.length>0&&t.push(`- Tech: ${e.tech_stack.join(", ")}`),t.join(`
|
|
868
|
+
`)}function hp(e){let t=["## Avoid These Mistakes"];for(let n of e)t.push(`- ${n.pattern} (${n.count}x)`);return t.join(`
|
|
869
|
+
`)}function kp(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(`
|
|
870
|
+
`)}function yp(e){let t=Object.values(e).filter(c=>c.token_efficiency&&Fa(c)).sort((c,a)=>{let l=c.token_efficiency?.efficiency_score??0;return(a.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 c of t.slice(0,3)){let a=Math.round(c.success_rate*100),l=c.token_efficiency.avg_tokens_per_success,u=l>=1e3?`${(l/1e3).toFixed(1)}k`:`${Math.round(l)}`,f=c.success_rate>=.9&&c.token_efficiency.efficiency_score>.8?" [PREFERRED]":"";n.push(`- ${c.agent_name}: ${a}%/${u}${f}`)}let o=Ge(),r=o>=1e3?`${(o/1e3).toFixed(0)}k`:o.toString(),i=Math.round(o*1.5),s=i>=1e3?`${(i/1e3).toFixed(0)}k`:i.toString();return n.push(""),n.push(`SESSION BUDGET: ~${r} baseline | warn at ${s}`),n.push("PATTERNS: Parallel reads save 40%"),n.push(""),n.push("Quality remains priority. Use efficiency as tiebreaker."),n.push("</olympus-efficiency>"),n.join(`
|
|
871
|
+
`)}function Ha(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(`
|
|
872
|
+
`)}var dn=require("path"),Ke=require("fs"),Ep=require("crypto");function Sp(e){let t=(0,dn.join)(Ne(),"discoveries.jsonl"),n=yt(e),o=(0,dn.join)(n,"discoveries.jsonl"),r=Wa(t),i=Wa(o),s=[...r,...i],c={technical_insight:0,workaround:0,pattern:0,gotcha:0,performance:0,dependency:0,configuration:0};for(let l of s)c[l.category]++;let a=[...s].sort((l,u)=>u.verification_count-l.verification_count);return{project_discoveries:i,global_discoveries:r,total_discoveries:s.length,categories:c,most_useful:a.slice(0,5)}}function Ga(e,t=10){let n=Sp(e),o=[...n.project_discoveries,...n.global_discoveries],r=new Date,s=o.filter(c=>c.expires_at?new Date(c.expires_at)>r:!0).map(c=>{let a=(r.getTime()-new Date(c.timestamp).getTime())/864e5,l=Math.max(.1,1-a/90),u=(c.verification_count+1)*l*c.confidence;return{discovery:c,score:u}});return s.sort((c,a)=>a.score-c.score),s.slice(0,t).map(c=>c.discovery)}function Wa(e){if(!(0,Ke.existsSync)(e))return[];try{return(0,Ke.readFileSync)(e,"utf-8").split(`
|
|
873
|
+
`).filter(n=>n.trim()).map(n=>JSON.parse(n))}catch(t){return console.error(`[Olympus Learning] Failed to read discoveries: ${t}`),[]}}function Ba(){v({name:"learnedContextInjection",event:"SessionStart",priority:5,handler:e=>{if(!e.directory)return{continue:!0};try{let t=ja(e.directory),n=Ga(e.directory,5),o=Ha(n),r=t+(o?`
|
|
209
874
|
|
|
210
|
-
`+o:"");if(r.trim())return{continue:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:r}}}catch(t){console.error("[Olympus Learning]",t)}return{continue:!0}}}),
|
|
875
|
+
`+o:"");if(r.trim())return{continue:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:r}}}catch(t){console.error("[Olympus Learning]",t)}return{continue:!0}}}),v({name:"sessionStart",event:"SessionStart",priority:10,handler:async e=>{let t=e.sessionId,n=e.directory||process.cwd(),o=[];try{let s=te(n,t);s.token_budget||(yi(s,n),J(n,s))}catch(s){console.error("[Olympus Learning] Failed to initialize token budget:",s)}let r=We(n);r?.active&&o.push(`<session-restore>
|
|
211
876
|
|
|
212
877
|
[ULTRAWORK MODE RESTORED]
|
|
213
878
|
|
|
@@ -220,11 +885,11 @@ Continue working in ultrawork mode until all tasks are complete.
|
|
|
220
885
|
|
|
221
886
|
---
|
|
222
887
|
|
|
223
|
-
`);let
|
|
888
|
+
`);let i=await At(t,n);return i.count>0&&o.push(`<session-restore>
|
|
224
889
|
|
|
225
890
|
[PENDING TASKS DETECTED]
|
|
226
891
|
|
|
227
|
-
You have ${
|
|
892
|
+
You have ${i.count} incomplete tasks from a previous session.
|
|
228
893
|
Please continue working on these tasks.
|
|
229
894
|
|
|
230
895
|
</session-restore>
|
|
@@ -232,7 +897,7 @@ Please continue working on these tasks.
|
|
|
232
897
|
---
|
|
233
898
|
|
|
234
899
|
`),o.length>0?{continue:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:o.join(`
|
|
235
|
-
`)}}:{continue:!0}}})}var
|
|
900
|
+
`)}}:{continue:!0}}})}var lt=require("fs"),Re=require("path"),Io=require("os");var ne=require("fs"),je=require("path"),qa=require("os");function Eo(e){let t=(0,je.join)(e,".olympus");return(0,je.join)(t,"ascent-state.json")}function Tp(e){let t=(0,je.join)(e,".olympus");(0,ne.existsSync)(t)||(0,ne.mkdirSync)(t,{recursive:!0})}function bt(e){let t=Eo(e);if(!(0,ne.existsSync)(t))return null;try{let n=(0,ne.readFileSync)(t,"utf-8");return JSON.parse(n)}catch{return null}}function wp(e,t){try{Tp(e);let n=Eo(e);return(0,ne.writeFileSync)(n,JSON.stringify(t,null,2)),!0}catch{return!1}}function fn(e){let t=Eo(e);if(!(0,ne.existsSync)(t))return!0;try{return(0,ne.unlinkSync)(t),!0}catch{return!1}}function Ya(e){let t=bt(e);return!t||!t.active?null:(t.iteration+=1,wp(e,t)?t:null)}function Va(e,t){let n=(0,je.join)((0,qa.homedir)(),".claude"),o=[(0,je.join)(n,"sessions",e,"transcript.md"),(0,je.join)(n,"sessions",e,"messages.json"),(0,je.join)(n,"transcripts",`${e}.md`)];for(let r of o)if((0,ne.existsSync)(r))try{let i=(0,ne.readFileSync)(r,"utf-8");if(new RegExp(`<promise>\\s*${_p(t)}\\s*</promise>`,"is").test(i))return!0}catch{continue}return!1}function _p(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ae=require("fs"),So=require("path"),Op=3;function To(e){return(0,So.join)(e,".olympus","ascent-verification.json")}function Nt(e){let t=To(e);if(!(0,ae.existsSync)(t))return null;try{return JSON.parse((0,ae.readFileSync)(t,"utf-8"))}catch{return null}}function Ka(e,t){let n=To(e),o=(0,So.join)(e,".olympus");if(!(0,ae.existsSync)(o))try{(0,ae.mkdirSync)(o,{recursive:!0})}catch{return!1}try{return(0,ae.writeFileSync)(n,JSON.stringify(t,null,2)),!0}catch{return!1}}function Ct(e){let t=To(e);if((0,ae.existsSync)(t))try{return(0,ae.unlinkSync)(t),!0}catch{return!1}return!0}function Ja(e,t,n){let o={pending:!0,completion_claim:t,verification_attempts:0,max_verification_attempts:Op,requested_at:new Date().toISOString(),original_task:n};return Ka(e,o),o}function za(e,t,n){let o=Nt(e);return o?(o.verification_attempts+=1,o.oracle_approved=t,o.oracle_feedback=n,t?(Ct(e),{...o,pending:!1}):o.verification_attempts>=o.max_verification_attempts?(Ct(e),{...o,pending:!1}):(Ka(e,o),o)):null}function wo(e){return`<ascent-verification>
|
|
236
901
|
|
|
237
902
|
[ORACLE VERIFICATION REQUIRED - Attempt ${e.verification_attempts+1}/${e.max_verification_attempts}]
|
|
238
903
|
|
|
@@ -272,7 +937,7 @@ DO NOT output the completion promise again until Oracle approves.
|
|
|
272
937
|
|
|
273
938
|
---
|
|
274
939
|
|
|
275
|
-
`}function
|
|
940
|
+
`}function Xa(e){return`<ascent-continuation-after-rejection>
|
|
276
941
|
|
|
277
942
|
[ORACLE REJECTED - Continue Working]
|
|
278
943
|
|
|
@@ -297,7 +962,7 @@ Continue working now.
|
|
|
297
962
|
|
|
298
963
|
---
|
|
299
964
|
|
|
300
|
-
`}function
|
|
965
|
+
`}function Qa(e){return/<oracle-approved>.*?VERIFIED_COMPLETE.*?<\/oracle-approved>/is.test(e)}function Za(e){let t=[/oracle.*?(rejected|found issues|not complete|incomplete)/i,/issues? (found|identified|detected)/i,/not yet complete/i,/missing.*?(implementation|feature|test)/i,/bug.*?(found|detected|identified)/i,/error.*?(found|detected|identified)/i];for(let n of t)if(n.test(e)){let o=e.match(/(?:oracle|feedback|issue|problem|error|bug)[:\s]+([^.]+\.)/i);return{rejected:!0,feedback:o?o[1]:"Oracle found issues with the implementation."}}return{rejected:!1,feedback:""}}var j=require("fs"),at=require("path"),_o=require("os");function Oo(e){let t=e||process.cwd(),n=(0,at.join)(t,".olympus");return(0,at.join)(n,"olympus-state.json")}function vo(){return(0,at.join)((0,_o.homedir)(),".claude","olympus-state.json")}function vp(e){let t=e||process.cwd(),n=(0,at.join)(t,".olympus");(0,j.existsSync)(n)||(0,j.mkdirSync)(n,{recursive:!0})}function Rp(){let e=(0,at.join)((0,_o.homedir)(),".claude");(0,j.existsSync)(e)||(0,j.mkdirSync)(e,{recursive:!0})}function ct(e){let t=Oo(e);if((0,j.existsSync)(t))try{let o=(0,j.readFileSync)(t,"utf-8");return JSON.parse(o)}catch{}let n=vo();if((0,j.existsSync)(n))try{let o=(0,j.readFileSync)(n,"utf-8");return JSON.parse(o)}catch{return null}return null}function ec(e,t){try{vp(t);let n=Oo(t);(0,j.writeFileSync)(n,JSON.stringify(e,null,2)),Rp();let o=vo();return(0,j.writeFileSync)(o,JSON.stringify(e,null,2)),!0}catch{return!1}}function Ro(e){let t=Oo(e);if((0,j.existsSync)(t))try{(0,j.unlinkSync)(t)}catch{}let n=vo();if((0,j.existsSync)(n))try{return(0,j.unlinkSync)(n),!0}catch{return!1}return!0}function tc(e){let t=ct(e);return!t||!t.active?null:(t.reinforcement_count+=1,t.last_checked_at=new Date().toISOString(),ec(t,e)?t:null)}function nc(e){let t=ct(e);return!t||!t.active?!1:(t.oracle_approved=!0,t.last_checked_at=new Date().toISOString(),ec(t,e))}function oc(e){let t=e.requires_oracle_verification&&!e.oracle_approved?`
|
|
301
966
|
|
|
302
967
|
**ORACLE VERIFICATION REQUIRED**: Before declaring complete, you MUST get Oracle approval.`:"";return`<olympus-persistence>
|
|
303
968
|
|
|
@@ -319,9 +984,9 @@ Original task: ${e.original_prompt}
|
|
|
319
984
|
|
|
320
985
|
---
|
|
321
986
|
|
|
322
|
-
`}function
|
|
987
|
+
`}function rc(e){let t=(0,Re.join)((0,Io.homedir)(),".claude"),n=[(0,Re.join)(t,"sessions",e,"transcript.md"),(0,Re.join)(t,"sessions",e,"messages.json"),(0,Re.join)(t,"transcripts",`${e}.md`)];for(let o of n)if((0,lt.existsSync)(o))try{let r=(0,lt.readFileSync)(o,"utf-8");if(Qa(r))return!0}catch{continue}return!1}function Ip(e){let t=(0,Re.join)((0,Io.homedir)(),".claude"),n=[(0,Re.join)(t,"sessions",e,"transcript.md"),(0,Re.join)(t,"sessions",e,"messages.json"),(0,Re.join)(t,"transcripts",`${e}.md`)];for(let o of n)if((0,lt.existsSync)(o))try{let r=(0,lt.readFileSync)(o,"utf-8"),i=Za(r);if(i.rejected)return i}catch{continue}return{rejected:!1,feedback:""}}async function Ap(e,t){let n=t||process.cwd(),o=bt(n);if(!o||!o.active||o.session_id&&e&&o.session_id!==e)return null;let r=Nt(n);if(r?.pending){if(e){if(rc(e))return Ct(n),fn(n),{shouldBlock:!1,message:`[ASCENT LOOP VERIFIED COMPLETE] Oracle verified task completion after ${o.iteration} iteration(s). Excellent work!`,mode:"none"};let l=Ip(e);if(l.rejected){za(n,!1,l.feedback);let u=Nt(n);if(u)return{shouldBlock:!0,message:Xa(u),mode:"ascent",metadata:{iteration:o.iteration,maxIterations:o.max_iterations}}}}return{shouldBlock:!0,message:wo(r),mode:"ascent",metadata:{iteration:o.iteration,maxIterations:o.max_iterations}}}if(Va(e||"",o.completion_promise)){Ja(n,o.completion_promise,o.prompt);let a=Nt(n);return a?{shouldBlock:!0,message:wo(a),mode:"ascent",metadata:{iteration:o.iteration,maxIterations:o.max_iterations}}:(fn(n),{shouldBlock:!1,message:`[ASCENT LOOP COMPLETE] Task completed after ${o.iteration} iteration(s). Great work!`,mode:"none"})}if(o.iteration>=o.max_iterations)return fn(n),Ct(n),{shouldBlock:!1,message:`[ASCENT LOOP STOPPED] Max iterations (${o.max_iterations}) reached without completion promise. Consider reviewing the task requirements.`,mode:"none"};let s=Ya(n);return s?{shouldBlock:!0,message:`<ascent-continuation>
|
|
323
988
|
|
|
324
|
-
[ASCENT LOOP - ITERATION ${
|
|
989
|
+
[ASCENT LOOP - ITERATION ${s.iteration}/${s.max_iterations}]
|
|
325
990
|
|
|
326
991
|
Your previous attempt did not output the completion promise. The work is NOT done yet.
|
|
327
992
|
|
|
@@ -329,16 +994,16 @@ CRITICAL INSTRUCTIONS:
|
|
|
329
994
|
1. Review your progress and the original task
|
|
330
995
|
2. Check your todo list - are ALL items marked complete?
|
|
331
996
|
3. Continue from where you left off
|
|
332
|
-
4. When FULLY complete, output: <promise>${
|
|
997
|
+
4. When FULLY complete, output: <promise>${s.completion_promise}</promise>
|
|
333
998
|
5. Do NOT stop until the task is truly done
|
|
334
999
|
|
|
335
|
-
${
|
|
1000
|
+
${s.prompt?`Original task: ${s.prompt}`:""}
|
|
336
1001
|
|
|
337
1002
|
</ascent-continuation>
|
|
338
1003
|
|
|
339
1004
|
---
|
|
340
1005
|
|
|
341
|
-
`,mode:"ascent",metadata:{iteration:
|
|
1006
|
+
`,mode:"ascent",metadata:{iteration:s.iteration,maxIterations:s.max_iterations}}:null}async function bp(e,t,n){let o=We(t);if(!o||!o.active||o.session_id&&e&&o.session_id!==e)return null;if(!n)return Xr(t),{shouldBlock:!1,message:"[ULTRAWORK COMPLETE] All tasks finished. Ultrawork mode deactivated. Well done!",mode:"none"};let r=Qr(t);return r?{shouldBlock:!0,message:Zr(r),mode:"ultrawork",metadata:{reinforcementCount:r.reinforcement_count}}:null}async function Cp(e,t,n){let o=ct(t);if(!o||!o.active||o.session_id&&e&&o.session_id!==e)return null;if(!n&&o.oracle_approved)return Ro(t),{shouldBlock:!1,message:"[OLYMPUS COMPLETE] All tasks finished and Oracle verified. Orchestration mode deactivated. Excellent work!",mode:"none"};if(!n&&!o.oracle_approved&&o.requires_oracle_verification)return e&&rc(e)?(nc(t),Ro(t),{shouldBlock:!1,message:"[OLYMPUS VERIFIED COMPLETE] Oracle approved. Orchestration mode deactivated. Excellent work!",mode:"none"}):{shouldBlock:!0,message:`<olympus-verification-required>
|
|
342
1007
|
|
|
343
1008
|
[OLYMPUS MODE - ORACLE VERIFICATION REQUIRED]
|
|
344
1009
|
|
|
@@ -361,11 +1026,11 @@ DO NOT stop until Oracle has approved.
|
|
|
361
1026
|
|
|
362
1027
|
---
|
|
363
1028
|
|
|
364
|
-
`,mode:"olympus",metadata:{reinforcementCount:o.reinforcement_count}};let r=
|
|
1029
|
+
`,mode:"olympus",metadata:{reinforcementCount:o.reinforcement_count}};let r=tc(t);return r?{shouldBlock:!0,message:oc(r),mode:"olympus",metadata:{reinforcementCount:r.reinforcement_count}}:null}async function Np(e,t){let n=await At(e,t);if(n.count===0)return null;let o=$a(n),r=o?`
|
|
365
1030
|
|
|
366
1031
|
Next task: "${o.content}" (${o.status})`:"";return{shouldBlock:!0,message:`<todo-continuation>
|
|
367
1032
|
|
|
368
|
-
${
|
|
1033
|
+
${ii}
|
|
369
1034
|
|
|
370
1035
|
[Status: ${n.count} of ${n.total} tasks remaining]${r}
|
|
371
1036
|
|
|
@@ -373,20 +1038,20 @@ ${Do}
|
|
|
373
1038
|
|
|
374
1039
|
---
|
|
375
1040
|
|
|
376
|
-
`,mode:"todo-continuation",metadata:{todoCount:n.count}}}async function
|
|
377
|
-
`),n={},o=0;for(;o<t.length;){let r=t[o],
|
|
1041
|
+
`,mode:"todo-continuation",metadata:{todoCount:n.count}}}async function ic(e,t){let n=t||process.cwd(),r=(await At(e,n)).count>0,i=await Ap(e,n);if(i?.shouldBlock)return i;let s=await bp(e,n,r);if(s?.shouldBlock)return s;let c=await Cp(e,n,r);if(c?.shouldBlock)return c;if(r){let a=await Np(e,n);if(a?.shouldBlock)return a}return{shouldBlock:!1,message:"",mode:"none"}}function sc(e){return e.shouldBlock?{continue:!1,stopReason:e.message}:{continue:!0,message:e.message||void 0}}var ut=require("fs"),Ao=require("path"),ac=require("os");var cc=require("crypto");function Pp(){let e=(0,Ao.join)((0,ac.homedir)(),".claude","todos");if(!(0,ut.existsSync)(e))return 0;let t=0;try{let n=(0,ut.readdirSync)(e).filter(o=>o.endsWith(".json"));for(let o of n)try{let r=(0,ut.readFileSync)((0,Ao.join)(e,o),"utf-8"),i=JSON.parse(r);Array.isArray(i)&&(t+=i.filter(s=>s.status!=="completed"&&s.status!=="cancelled").length)}catch{}}catch{}return t}async function lc(e){let{directory:t,sessionId:n}=e;if(!t)return;let o=te(t,n),r=Pp();if(r>0&&o.pending_completion){let i={id:(0,cc.randomUUID)(),timestamp:new Date().toISOString(),session_id:o.session_id,project_path:t,event_type:"cancellation",original_task:o.pending_completion.task_description,agent_used:o.pending_completion.agent_used,user_message:`[Stopped with ${r} incomplete todos]`,feedback_category:"rejection",confidence:.7};Pe(i)}o.pending_completion=null,o.todo_snapshot={total:0,completed:0,pending:r},J(t,o)}function uc(){v({name:"persistentMode",event:"Stop",priority:10,handler:async e=>{let t=e.sessionId,n=e.directory||process.cwd(),o=await ic(t,n),r=sc(o);return{continue:r.continue,message:r.message,stopReason:r.stopReason}}}),v({name:"learningCancellationCapture",event:"Stop",priority:100,handler:async e=>e.directory?(Promise.resolve().then(async()=>{try{await lc({directory:e.directory,sessionId:e.sessionId})}catch(t){console.error("[Olympus Learning]",t)}}),{continue:!0}):{continue:!0}})}var Fo=require("fs"),Uo=require("os"),xt=require("path");var ge=require("fs"),ie=require("path");var bo=require("path"),dc=require("os"),xp=(0,bo.join)((0,dc.homedir)(),".olympus"),pn=(0,bo.join)(xp,"rules-injector"),fc=[".git","pyproject.toml","package.json","Cargo.toml","go.mod",".venv"],pc=[[".github","instructions"],[".cursor","rules"],[".claude","rules"]],mc=[".github/copilot-instructions.md"],gc=/\.instructions\.md$/,hc=".claude/rules",kc=[".md",".mdc"],Co=["read","write","edit","multiedit"];function Dp(e){return e.includes(".github/instructions")||e.endsWith(".github/instructions")}function Lp(e,t){return Dp(t)?gc.test(e):kc.some(n=>e.endsWith(n))}function xo(e){let t;try{t=(0,ge.statSync)(e).isDirectory()?e:(0,ie.dirname)(e)}catch{t=(0,ie.dirname)(e)}for(;;){for(let o of fc){let r=(0,ie.join)(t,o);if((0,ge.existsSync)(r))return t}let n=(0,ie.dirname)(t);if(n===t)return null;t=n}}function Po(e,t){if((0,ge.existsSync)(e))try{let n=(0,ge.readdirSync)(e,{withFileTypes:!0});for(let o of n){let r=(0,ie.join)(e,o.name);o.isDirectory()?Po(r,t):o.isFile()&&Lp(o.name,e)&&t.push(r)}}catch{}}function No(e){try{return(0,ge.realpathSync)(e)}catch{return e}}function Do(e,t,n){let o=[],r=new Set,i=(0,ie.dirname)(n),s=0;for(;;){for(let[u,d]of pc){let f=(0,ie.join)(i,u,d),g=[];Po(f,g);for(let m of g){let p=No(m);r.has(p)||(r.add(p),o.push({path:m,realPath:p,isGlobal:!1,distance:s}))}}if(e&&i===e)break;let l=(0,ie.dirname)(i);if(l===i)break;i=l,s++}if(e)for(let l of mc){let u=(0,ie.join)(e,l);if((0,ge.existsSync)(u))try{if((0,ge.statSync)(u).isFile()){let f=No(u);r.has(f)||(r.add(f),o.push({path:u,realPath:f,isGlobal:!1,distance:0,isSingleFile:!0}))}}catch{}}let c=(0,ie.join)(t,hc),a=[];Po(c,a);for(let l of a){let u=No(l);r.has(u)||(r.add(u),o.push({path:l,realPath:u,isGlobal:!0,distance:9999}))}return o.sort((l,u)=>l.isGlobal!==u.isGlobal?l.isGlobal?1:-1:l.distance-u.distance),o}var yc=require("crypto"),Ec=require("path");function Mp(e,t){let n=e.replace(/\./g,"\\.").replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/<<<GLOBSTAR>>>/g,".*").replace(/\?/g,".");return new RegExp(`^${n}$`).test(t)}function Lo(e,t,n){if(e.alwaysApply===!0)return{applies:!0,reason:"alwaysApply"};let o=e.globs;if(!o)return{applies:!1};let r=Array.isArray(o)?o:[o];if(r.length===0)return{applies:!1};let s=(n?(0,Ec.relative)(n,t):t).replace(/\\/g,"/");for(let c of r)if(Mp(c,s))return{applies:!0,reason:`glob: ${c}`};return{applies:!1}}function Sc(e,t){return t.has(e)}function Tc(e){return(0,yc.createHash)("sha256").update(e).digest("hex").slice(0,16)}function wc(e,t){return t.has(e)}function Mo(e){let t=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,n=e.match(t);if(!n)return{metadata:{},body:e};let o=n[1],r=n[2];try{return{metadata:$p(o),body:r}}catch{return{metadata:{},body:e}}}function $p(e){let t=e.split(`
|
|
1042
|
+
`),n={},o=0;for(;o<t.length;){let r=t[o],i=r.indexOf(":");if(i===-1){o++;continue}let s=r.slice(0,i).trim(),c=r.slice(i+1).trim();if(s==="description")n.description=Pt(c);else if(s==="alwaysApply")n.alwaysApply=c==="true";else if(s==="globs"||s==="paths"||s==="applyTo"){let{value:a,consumed:l}=Fp(c,t,o);n.globs=jp(n.globs,a),o+=l;continue}o++}return n}function Pt(e){return e?e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e:""}function Fp(e,t,n){if(e.startsWith("["))return{value:Up(e),consumed:1};if(!e||e===""){let r=[],i=1;for(let s=n+1;s<t.length;s++){let c=t[s],a=c.match(/^\s+-\s*(.*)$/);if(a){let l=Pt(a[1].trim());l&&r.push(l),i++}else if(c.trim()==="")i++;else break}if(r.length>0)return{value:r,consumed:i}}let o=Pt(e);return o.includes(",")?{value:o.split(",").map(i=>i.trim()).filter(i=>i.length>0),consumed:1}:{value:o,consumed:1}}function Up(e){let t=e.slice(1,e.lastIndexOf("]")).trim();if(!t)return[];let n=[],o="",r=!1,i="";for(let c=0;c<t.length;c++){let a=t[c];if(!r&&(a==='"'||a==="'"))r=!0,i=a;else if(r&&a===i)r=!1,i="";else if(!r&&a===","){let l=o.trim();l&&n.push(Pt(l)),o=""}else o+=a}let s=o.trim();return s&&n.push(Pt(s)),n}function jp(e,t){if(!e)return t;let n=Array.isArray(e)?e:[e],o=Array.isArray(t)?t:[t];return[...n,...o]}var ce=require("fs"),_c=require("path");function $o(e){return(0,_c.join)(pn,`${e}.json`)}function Oc(e){let t=$o(e);if(!(0,ce.existsSync)(t))return{contentHashes:new Set,realPaths:new Set};try{let n=(0,ce.readFileSync)(t,"utf-8"),o=JSON.parse(n);return{contentHashes:new Set(o.injectedHashes),realPaths:new Set(o.injectedRealPaths??[])}}catch{return{contentHashes:new Set,realPaths:new Set}}}function vc(e,t){(0,ce.existsSync)(pn)||(0,ce.mkdirSync)(pn,{recursive:!0});let n={sessionId:e,injectedHashes:[...t.contentHashes],injectedRealPaths:[...t.realPaths],updatedAt:Date.now()};(0,ce.writeFileSync)($o(e),JSON.stringify(n,null,2))}function Rc(e){let t=$o(e);(0,ce.existsSync)(t)&&(0,ce.unlinkSync)(t)}function Ic(e){let t=new Map;function n(s){return t.has(s)||t.set(s,Oc(s)),t.get(s)}function o(s){return s?s.startsWith("/")?s:(0,xt.resolve)(e,s):null}function r(s,c){let a=o(s);if(!a)return[];let l=xo(a),u=n(c),d=(0,Uo.homedir)(),f=Do(l,d,a),g=[];for(let m of f)if(!Sc(m.realPath,u.realPaths))try{let p=(0,Fo.readFileSync)(m.path,"utf-8"),{metadata:h,body:y}=Mo(p),T;if(m.isSingleFile)T="copilot-instructions (always apply)";else{let D=Lo(h,a,l);if(!D.applies)continue;T=D.reason??"matched"}let k=Tc(y);if(wc(k,u.contentHashes))continue;let A=l?(0,xt.relative)(l,m.path):m.path;g.push({relativePath:A,matchReason:T,content:y,distance:m.distance}),u.realPaths.add(m.realPath),u.contentHashes.add(k)}catch{}return g.length>0&&(g.sort((m,p)=>m.distance-p.distance),vc(c,u)),g}function i(s){if(s.length===0)return"";let c="";for(let a of s)c+=`
|
|
378
1043
|
|
|
379
1044
|
[Rule: ${a.relativePath}]
|
|
380
1045
|
[Match: ${a.matchReason}]
|
|
381
|
-
${a.content}`;return c}return{processToolExecution:(
|
|
1046
|
+
${a.content}`;return c}return{processToolExecution:(s,c,a)=>{if(!Co.includes(s.toLowerCase()))return"";let l=r(c,a);return i(l)},getRulesForFile:s=>{let c=o(s);if(!c)return[];let a=xo(c),l=(0,Uo.homedir)(),u=Do(a,l,c),d=[];for(let f of u)try{let g=(0,Fo.readFileSync)(f.path,"utf-8"),{metadata:m,body:p}=Mo(g),h;if(f.isSingleFile)h="copilot-instructions (always apply)";else{let T=Lo(m,c,a);if(!T.applies)continue;h=T.reason??"matched"}let y=a?(0,xt.relative)(a,f.path):f.path;d.push({relativePath:y,matchReason:h,content:p,distance:f.distance})}catch{}return d.sort((f,g)=>f.distance-g.distance)},clearSession:s=>{t.delete(s),Rc(s)},isTrackedTool:s=>Co.includes(s.toLowerCase())}}var gn=require("node:fs"),Ie=require("node:path");var le=require("node:fs"),Cc=require("node:path");var jo=require("node:path"),Ac=require("node:os"),Hp=(0,jo.join)((0,Ac.homedir)(),".olympus"),mn=(0,jo.join)(Hp,"directory-readme"),bc="README.md",Ho=["read","write","edit","multiedit"];function Wo(e){return(0,Cc.join)(mn,`${e}.json`)}function Nc(e){let t=Wo(e);if(!(0,le.existsSync)(t))return new Set;try{let n=(0,le.readFileSync)(t,"utf-8"),o=JSON.parse(n);return new Set(o.injectedPaths)}catch{return new Set}}function Pc(e,t){(0,le.existsSync)(mn)||(0,le.mkdirSync)(mn,{recursive:!0});let n={sessionID:e,injectedPaths:Array.from(t),updatedAt:Date.now()};(0,le.writeFileSync)(Wo(e),JSON.stringify(n,null,2))}function xc(e){let t=Wo(e);(0,le.existsSync)(t)&&(0,le.unlinkSync)(t)}var Dc=4,Wp=5e3;function Gp(e,t=Wp){if(Math.ceil(e.length/Dc)<=t)return{result:e,truncated:!1};let o=t*Dc;return{result:e.slice(0,o),truncated:!0}}function Lc(e){let t=new Map;function n(s){return t.has(s)||t.set(s,Nc(s)),t.get(s)}function o(s){return s?s.startsWith("/")?s:(0,Ie.resolve)(e,s):null}function r(s){let c=[],a=s;for(;;){let l=(0,Ie.join)(a,bc);if((0,gn.existsSync)(l)&&c.push(l),a===e)break;let u=(0,Ie.dirname)(a);if(u===a||!u.startsWith(e))break;a=u}return c.reverse()}function i(s,c){let a=o(s);if(!a)return"";let l=(0,Ie.dirname)(a),u=n(c),d=r(l),f="";for(let g of d){let m=(0,Ie.dirname)(g);if(!u.has(m))try{let p=(0,gn.readFileSync)(g,"utf-8"),{result:h,truncated:y}=Gp(p),T=y?`
|
|
382
1047
|
|
|
383
|
-
[Note: Content was truncated to save context window space. For full context, please read the file directly: ${
|
|
1048
|
+
[Note: Content was truncated to save context window space. For full context, please read the file directly: ${g}]`:"";f+=`
|
|
384
1049
|
|
|
385
|
-
[Project README: ${
|
|
386
|
-
${
|
|
1050
|
+
[Project README: ${g}]
|
|
1051
|
+
${h}${T}`,u.add(m)}catch{}}return f&&Pc(c,u),f}return{processToolExecution:(s,c,a)=>Ho.includes(s.toLowerCase())?i(c,a):"",getReadmesForFile:s=>{let c=o(s);if(!c)return[];let a=(0,Ie.dirname)(c);return r(a)},clearSession:s=>{t.delete(s),xc(s)},isTrackedTool:s=>Ho.includes(s.toLowerCase())}}var Mc="non-interactive-env",$c={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"},Go={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
|
|
387
1052
|
option1
|
|
388
1053
|
option2
|
|
389
|
-
EOF`,expectAlternative:"Use environment variables or config files instead of expect"}};var
|
|
1054
|
+
EOF`,expectAlternative:"Use environment variables or config files instead of expect"}};var Fc=Go.banned.filter(e=>!e.includes("(")).map(e=>new RegExp(`\\b${e}\\b`));function Bp(e){for(let t=0;t<Fc.length;t++)if(Fc[t].test(e))return Go.banned[t]}function qp(e){return e===""?"''":/[^a-zA-Z0-9_\-.:\/]/.test(e)?`'${e.replace(/'/g,"'\\''")}'`:e}function Yp(e){return`export ${Object.entries(e).map(([n,o])=>`${n}=${qp(o)}`).join(" ")};`}var Bo={name:Mc,async beforeCommand(e){let t=Bp(e),n=t?`Warning: '${t}' is an interactive command that may hang in non-interactive environments.`:void 0;return/\bgit\b/.test(e)?{command:`${Yp($c)} ${e}`,warning:n}:{command:e,warning:n}}};var Yo=require("child_process");var Uc="olympus-orchestrator",jc=".olympus/",Hc=["Write","Edit","write","edit"],Wc=`
|
|
390
1055
|
|
|
391
1056
|
---
|
|
392
1057
|
|
|
@@ -412,7 +1077,7 @@ You should NOT:
|
|
|
412
1077
|
3. Verify the subagent's work after completion
|
|
413
1078
|
|
|
414
1079
|
---
|
|
415
|
-
`;var
|
|
1080
|
+
`;var Gc=`[SYSTEM REMINDER - QUEST CONTINUATION]
|
|
416
1081
|
|
|
417
1082
|
You have an active work plan with incomplete tasks. Continue working.
|
|
418
1083
|
|
|
@@ -421,7 +1086,7 @@ RULES:
|
|
|
421
1086
|
- Mark each checkbox [x] in the plan file when done
|
|
422
1087
|
- Learnings are automatically captured in .olympus/learning/discoveries.jsonl
|
|
423
1088
|
- Do not stop until all tasks are complete
|
|
424
|
-
- If blocked, document the blocker and move to the next task`,
|
|
1089
|
+
- If blocked, document the blocker and move to the next task`,Bc=`**MANDATORY VERIFICATION - SUBAGENTS LIE**
|
|
425
1090
|
|
|
426
1091
|
Subagents FREQUENTLY claim completion when:
|
|
427
1092
|
- Tests are actually FAILING
|
|
@@ -436,7 +1101,7 @@ Subagents FREQUENTLY claim completion when:
|
|
|
436
1101
|
3. Check build/typecheck - Must succeed
|
|
437
1102
|
|
|
438
1103
|
DO NOT TRUST THE AGENT'S SELF-REPORT.
|
|
439
|
-
VERIFY EACH CLAIM WITH YOUR OWN TOOL CALLS.`,
|
|
1104
|
+
VERIFY EACH CLAIM WITH YOUR OWN TOOL CALLS.`,qc=`
|
|
440
1105
|
|
|
441
1106
|
[SYSTEM DIRECTIVE - SINGLE TASK ONLY]
|
|
442
1107
|
|
|
@@ -459,7 +1124,7 @@ If you were NOT given **exactly ONE atomic task**, you MUST:
|
|
|
459
1124
|
- Batch delegation = sloppy work = rework = wasted tokens
|
|
460
1125
|
|
|
461
1126
|
**REFUSE multi-task requests. DEMAND single-task clarity.**
|
|
462
|
-
`,
|
|
1127
|
+
`,Yc=`
|
|
463
1128
|
|
|
464
1129
|
================================================================================
|
|
465
1130
|
HARD BLOCK: DELEGATION REQUIRED
|
|
@@ -498,41 +1163,41 @@ This is a HARD BLOCK. The operation will NOT be executed.
|
|
|
498
1163
|
Delegate to a subagent to proceed.
|
|
499
1164
|
|
|
500
1165
|
================================================================================
|
|
501
|
-
`;var
|
|
502
|
-
`;(0,
|
|
503
|
-
`).length,
|
|
504
|
-
`).length;return Math.abs(
|
|
505
|
-
`).length:0}return 0}function
|
|
506
|
-
`)){if(!
|
|
507
|
-
`)){let i
|
|
1166
|
+
`;var Dt=".olympus",hn="quest.json",Vp=`${Dt}/${hn}`,Vc="notepads",Kp=`${Dt}/${Vc}`;var he=require("fs"),kn=require("path");function Kc(e){return(0,kn.join)(e,Dt,hn)}function yn(e){let t=Kc(e);if(!(0,he.existsSync)(t))return null;try{let n=(0,he.readFileSync)(t,"utf-8");return JSON.parse(n)}catch{return null}}function En(e){if(!(0,he.existsSync)(e))return{total:0,completed:0,isComplete:!0};try{let t=(0,he.readFileSync)(e,"utf-8"),n=t.match(/^[-*]\s*\[\s*\]/gm)||[],o=t.match(/^[-*]\s*\[[xX]\]/gm)||[],r=n.length+o.length,i=o.length;return{total:r,completed:i,isComplete:r===0||i===r}}catch{return{total:0,completed:0,isComplete:!0}}}var Lt=class{recentTasks=[];maxTracked=3;recordTaskCompletion(t){this.recentTasks.unshift(t),this.recentTasks.length>this.maxTracked&&this.recentTasks.pop()}isVerificationEdit(t,n){return this.recentTasks.some(r=>r.filesModified.includes(t))&&n<10}getRecentTaskFiles(){let t=this.recentTasks.flatMap(n=>n.filesModified);return Array.from(new Set(t))}getRecentTasks(){return[...this.recentTasks]}clear(){this.recentTasks=[]}get trackedCount(){return this.recentTasks.length}},nE=new Lt;var Je=require("fs"),qo=require("path");function Mt(e,t){let n=t||process.cwd(),o=(0,qo.join)(n,".olympus","logs"),r=(0,qo.join)(o,"hook-violations.jsonl");try{(0,Je.existsSync)(o)||(0,Je.mkdirSync)(o,{recursive:!0});let i=JSON.stringify(e)+`
|
|
1167
|
+
`;(0,Je.appendFileSync)(r,i,"utf-8")}catch(i){console.error("[Hook Logging] Failed to log violation:",i)}}var Jc=new Lt;function zc(e){return e?e.replace(/\\/g,"/").includes(jc):!0}function Xp(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 Qp(e,t){if(!t)return 0;if(e==="Edit"||e==="edit"){let n=t.old_string??"",o=t.new_string??"";if(!n&&!o)return 0;let r=n.split(`
|
|
1168
|
+
`).length,i=o.split(`
|
|
1169
|
+
`).length;return Math.abs(i-r)}if(e==="Write"||e==="write"){let n=t.content??"";return n?n.split(`
|
|
1170
|
+
`).length:0}return 0}function Xc(e){return Hc.includes(e)}function Zp(e){try{let t=(0,Yo.execSync)("git diff --numstat HEAD",{cwd:e,encoding:"utf-8",timeout:5e3}).trim();if(!t)return[];let n=(0,Yo.execSync)("git status --porcelain",{cwd:e,encoding:"utf-8",timeout:5e3}).trim(),o=new Map;for(let i of n.split(`
|
|
1171
|
+
`)){if(!i)continue;let s=i.substring(0,2).trim(),c=i.substring(3);s==="A"||s==="??"?o.set(c,"added"):s==="D"?o.set(c,"deleted"):o.set(c,"modified")}let r=[];for(let i of t.split(`
|
|
1172
|
+
`)){let s=i.split(" ");if(s.length<3)continue;let[c,a,l]=s,u=c==="-"?0:parseInt(c,10),d=a==="-"?0:parseInt(a,10);r.push({path:l,added:u,removed:d,status:o.get(l)??"modified"})}return r}catch{return[]}}function em(e){if(e.length===0)return`[FILE CHANGES SUMMARY]
|
|
508
1173
|
No file changes detected.
|
|
509
|
-
`;let t=e.filter(
|
|
510
|
-
`)}function
|
|
1174
|
+
`;let t=e.filter(i=>i.status==="modified"),n=e.filter(i=>i.status==="added"),o=e.filter(i=>i.status==="deleted"),r=["[FILE CHANGES SUMMARY]"];if(t.length>0){r.push("Modified files:");for(let i of t)r.push(` ${i.path} (+${i.added}, -${i.removed})`);r.push("")}if(n.length>0){r.push("Created files:");for(let i of n)r.push(` ${i.path} (+${i.added})`);r.push("")}if(o.length>0){r.push("Deleted files:");for(let i of o)r.push(` ${i.path} (-${i.removed})`);r.push("")}return r.join(`
|
|
1175
|
+
`)}function Qc(e){let t=Bc;return e&&(t+=`
|
|
511
1176
|
|
|
512
1177
|
---
|
|
513
1178
|
|
|
514
1179
|
**If ANY verification fails, resume the subagent with the fix:**
|
|
515
|
-
Task tool with resume="${e}", prompt="fix: [describe the specific failure]"`),t}function
|
|
1180
|
+
Task tool with resume="${e}", prompt="fix: [describe the specific failure]"`),t}function tm(e,t,n){let o=t.total-t.completed;return`
|
|
516
1181
|
---
|
|
517
1182
|
|
|
518
1183
|
**State:** Plan: ${e} | ${t.completed}/${t.total} done, ${o} left
|
|
519
1184
|
|
|
520
1185
|
---
|
|
521
1186
|
|
|
522
|
-
${
|
|
1187
|
+
${Qc(n)}
|
|
523
1188
|
|
|
524
|
-
ALL pass? \u2192 commit atomic unit, mark \`[x]\`, next task.`}function
|
|
1189
|
+
ALL pass? \u2192 commit atomic unit, mark \`[x]\`, next task.`}function nm(e,t,n){return Gc.replace(/{PLAN_NAME}/g,e)+`
|
|
525
1190
|
|
|
526
|
-
[Status: ${n-t}/${n} completed, ${t} remaining]`}function
|
|
1191
|
+
[Status: ${n-t}/${n} completed, ${t} remaining]`}function om(e){let{toolName:t,toolInput:n,directory:o}=e,r=o||process.cwd();if(!Xc(t))return{continue:!0};let i=n?.filePath??n?.path??n?.file;if(!i)return{continue:!0};let s=i.replace(/\\/g,"/");if(zc(s))return Mt({timestamp:new Date().toISOString(),filePath:s,toolName:t,wasBlocked:!1,reason:"Allowed: .olympus/ path"},r),{continue:!0};if(Xp(s))return Mt({timestamp:new Date().toISOString(),filePath:s,toolName:t,wasBlocked:!1,reason:"Allowed: Test file"},r),{continue:!0};let c=Qp(t,n);return Jc.isVerificationEdit(s,c)?(Mt({timestamp:new Date().toISOString(),filePath:s,toolName:t,linesChanged:c,wasBlocked:!1,reason:`Allowed: Verification edit (${c} lines on recent task file)`},r),{continue:!0}):(Mt({timestamp:new Date().toISOString(),filePath:s,toolName:t,linesChanged:c,wasBlocked:!0,reason:"Blocked: Direct source file modification (delegation required)"},r),{continue:!1,message:Yc})}function rm(e,t){let{toolName:n,toolInput:o,directory:r,sessionId:i}=e,s=r||process.cwd();if(Xc(n)){let c=o?.filePath??o?.path??o?.file;if(c&&!zc(c))return{continue:!0,modifiedOutput:t+Wc}}if(n==="Task"||n==="task"){if(t.includes("Background task launched")||t.includes("Background task resumed"))return{continue:!0};let a=Zp(s),l=a.map(f=>f.path);Jc.recordTaskCompletion({timestamp:Date.now(),filesModified:l,taskId:i||`task-${Date.now()}`});let u=em(a),d=yn(s);if(d){let f=En(d.active_plan);return{continue:!0,modifiedOutput:`
|
|
527
1192
|
## SUBAGENT WORK COMPLETED
|
|
528
1193
|
|
|
529
1194
|
${u}
|
|
530
1195
|
<system-reminder>
|
|
531
|
-
${
|
|
1196
|
+
${tm(d.plan_name,f,i)}
|
|
532
1197
|
</system-reminder>`}}return{continue:!0,modifiedOutput:t+`
|
|
533
1198
|
<system-reminder>
|
|
534
|
-
${
|
|
535
|
-
</system-reminder>`}}return{continue:!0}}function
|
|
1199
|
+
${Qc(i)}
|
|
1200
|
+
</system-reminder>`}}return{continue:!0}}function im(e){let t=yn(e);if(!t)return{shouldContinue:!1};let n=En(t.active_plan);if(n.isComplete)return{shouldContinue:!1};let o=n.total-n.completed;return{shouldContinue:!0,message:nm(t.plan_name,o,n.total)}}function Sn(e){return{name:Uc,preTool:(t,n)=>om({toolName:t,toolInput:n,directory:e}),postTool:(t,n,o)=>rm({toolName:t,toolInput:n,directory:e},o),checkContinuation:()=>im(e),getSingleTaskDirective:()=>qc}}function Zc(e){if(!e||typeof e!="object")return null;let t=e;return t.file_path||t.filePath||t.path||t.file}function el(){v({name:"rulesInjector",event:"PreToolUse",priority:10,matcher:/^(read|edit|write|glob|grep)$/i,handler:e=>{let t=Ic(e.directory||process.cwd()),n=Zc(e.toolInput);if(!n)return{continue:!0};let o=t.processToolExecution(e.toolName,n,e.sessionId||"default");return{continue:!0,hookSpecificOutput:o?{hookEventName:"PreToolUse",additionalContext:o}:void 0}}}),v({name:"directoryReadmeInjector",event:"PreToolUse",priority:20,matcher:/^(read|edit|write|glob|grep|bash)$/i,handler:e=>{let t=Lc(e.directory||process.cwd()),n=Zc(e.toolInput);if(!n)return{continue:!0};let o=t.processToolExecution(e.toolName,n,e.sessionId||"default");return{continue:!0,hookSpecificOutput:o?{hookEventName:"PreToolUse",additionalContext:o}:void 0}}}),v({name:"nonInteractiveEnv",event:"PreToolUse",priority:30,matcher:/^bash$/i,handler:async e=>{let t=e.toolInput;if(!t?.command)return{continue:!0};try{if(!Bo.beforeCommand)return{continue:!0};let n=await Bo.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}}}}),v({name:"olympusOrchestratorPre",event:"PreToolUse",priority:40,matcher:/^(write|edit|bash|task)$/i,handler:e=>Sn(e.directory||process.cwd()).preTool(e.toolName,e.toolInput)})}var sm=["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"],am=`
|
|
536
1201
|
[EDIT ERROR - IMMEDIATE ACTION REQUIRED]
|
|
537
1202
|
|
|
538
1203
|
You made an Edit mistake. STOP and do this NOW:
|
|
@@ -543,7 +1208,7 @@ You made an Edit mistake. STOP and do this NOW:
|
|
|
543
1208
|
4. CONTINUE with corrected action based on the real file content
|
|
544
1209
|
|
|
545
1210
|
DO NOT attempt another edit until you've read and verified the file state.
|
|
546
|
-
`;function
|
|
1211
|
+
`;function cm(e){let t=e.toLowerCase();return sm.some(n=>t.includes(n.toLowerCase()))}function tl(){return{afterToolExecute:(e,t)=>e.tool.toLowerCase()!=="edit"?t:cm(t.output)?{...t,output:t.output+am}:t}}var rl=H(require("fs"),1),wn=H(require("path"),1),il=require("os");var Tn=new Set(["given","when","then","arrange","act","assert","when & then","when&then"]),Vo=["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"],Ko=`COMMENT/DOCSTRING DETECTED - IMMEDIATE ACTION REQUIRED
|
|
547
1212
|
|
|
548
1213
|
Your recent changes contain comments or docstrings, which triggered this hook.
|
|
549
1214
|
You need to take immediate action. You must follow the conditions below.
|
|
@@ -581,13 +1246,13 @@ MANDATORY REQUIREMENT: You must acknowledge this hook message and take one of th
|
|
|
581
1246
|
Review in the above priority order and take the corresponding action EVERY TIME this appears.
|
|
582
1247
|
|
|
583
1248
|
Detected comments/docstrings:
|
|
584
|
-
`,
|
|
585
|
-
`;
|
|
586
|
-
`);o.lastIndex=0;let
|
|
587
|
-
`).length,d="line",f=!1;a.startsWith("/*")||a.startsWith("<!--")?d="block":(a.startsWith("'''")||a.startsWith('"""')||a.startsWith("=begin"))&&(d="docstring",f=!0),r.push({text:a.trim(),lineNumber:u,filePath:t,commentType:d,isDocstring:f})}return r}function
|
|
1249
|
+
`,Jo={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},zo={".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 lm(e){return e.text.trim().startsWith("#!")&&e.lineNumber===1?{shouldSkip:!0,reason:"shebang"}:{shouldSkip:!1}}function um(e){if(e.isDocstring)return{shouldSkip:!1};let t=e.text.toLowerCase().trim();for(let n of Tn){if(t.startsWith(`#${n}`)||t.startsWith(`// ${n}`))return{shouldSkip:!0,reason:`BDD keyword: ${n}`};if(t.includes(n)&&t.split(/\s+/).some(r=>Tn.has(r.replace(/[^a-z&]/g,""))))return{shouldSkip:!0,reason:"BDD keyword detected"}}return{shouldSkip:!1}}function dm(e){let t=e.text.toLowerCase().trim();for(let n of Vo)if(t.includes(n.toLowerCase()))return{shouldSkip:!0,reason:`directive: ${n}`};return{shouldSkip:!1}}function fm(e){return{shouldSkip:!1}}function pm(e){let t=e.text.toLowerCase(),n=["copyright","license","licensed under","spdx-license-identifier","all rights reserved","mit license","apache license","gnu general public","bsd license"];for(let o of n)if(t.includes(o))return{shouldSkip:!0,reason:"copyright/license"};return{shouldSkip:!1}}function mm(e){let t=e.text.toUpperCase(),n=["TODO","FIXME","HACK","XXX","NOTE","REVIEW"];for(let o of n)if(t.includes(o))return{shouldSkip:!0,reason:`todo marker: ${o}`};return{shouldSkip:!1}}var gm=[lm,um,dm,pm,mm,fm];function Xo(e){return e.filter(t=>{for(let n of gm)if(n(t).shouldSkip)return!1;return!0})}var hm=process.env.COMMENT_CHECKER_DEBUG==="1",km=wn.join((0,il.tmpdir)(),"comment-checker-debug.log");function ze(...e){if(hm){let t=`[${new Date().toISOString()}] [comment-checker] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
|
|
1250
|
+
`;rl.appendFileSync(km,t)}}function ym(e){let t=wn.extname(e).toLowerCase();return zo[t]}function Qo(e,t){let n=ym(t);if(!n)return ze("unsupported language for:",t),[];let o=Jo[n];if(!o)return ze("no pattern for language:",n),[];let r=[],i=e.split(`
|
|
1251
|
+
`);o.lastIndex=0;let s;for(;(s=o.exec(e))!==null;){let c=s.index,a=s[0],u=e.substring(0,c).split(`
|
|
1252
|
+
`).length,d="line",f=!1;a.startsWith("/*")||a.startsWith("<!--")?d="block":(a.startsWith("'''")||a.startsWith('"""')||a.startsWith("=begin"))&&(d="docstring",f=!0),r.push({text:a.trim(),lineNumber:u,filePath:t,commentType:d,isDocstring:f})}return r}function Em(e,t){return Qo(e,t)}function nl(e,t,n){let o=Qo(e,t);if(n){let r=Qo(n,t),i=new Set(r.map(s=>s.text));return o.filter(s=>!i.has(s.text))}return o}function Sm(e){if(e.length===0)return"";let t=new Map;for(let o of e){let r=t.get(o.filePath)||[];r.push(o),t.set(o.filePath,r)}let n=Ko;for(let[o,r]of t){n+=`
|
|
588
1253
|
File: ${o}
|
|
589
|
-
`;for(let
|
|
590
|
-
`}}return n}function
|
|
1254
|
+
`;for(let i of r){let s=i.isDocstring?"docstring":i.commentType;n+=` Line ${i.lineNumber} (${s}): ${i.text.substring(0,100)}${i.text.length>100?"...":""}
|
|
1255
|
+
`}}return n}function Tm(e,t,n,o,r){let i=[];if(t)i=Em(t,e);else if(o)i=nl(o,e,n);else if(r&&r.length>0)for(let c of r){let a=nl(c.new_string,e,c.old_string);i.push(...a)}let s=Xo(i);return ze(`found ${i.length} comments, ${s.length} flagged after filtering`),s.length===0?{hasComments:!1,count:0,comments:[]}:{hasComments:!0,count:s.length,message:Sm(s),comments:s}}var $t=new Map,wm=6e4;function _m(){let e=Date.now();for(let[t,n]of $t)e-n.timestamp>wm&&$t.delete(t)}var ol=!1;function sl(e){return ze("createCommentCheckerHook called",{config:e}),ol||(ol=!0,setInterval(_m,1e4)),{preToolUse:t=>{let n=t.tool_name.toLowerCase();if(n!=="write"&&n!=="edit"&&n!=="multiedit")return null;let o=t.tool_input.file_path??t.tool_input.filePath??t.tool_input.path,r=t.tool_input.content,i=t.tool_input.old_string??t.tool_input.oldString,s=t.tool_input.new_string??t.tool_input.newString,c=t.tool_input.edits;if(!o)return null;let a=`${t.session_id}-${Date.now()}-${Math.random().toString(36).slice(2)}`;return ze("registering pendingCall:",{callId:a,filePath:o,tool:n}),$t.set(a,{filePath:o,content:r,oldString:i,newString:s,edits:c,tool:n,sessionId:t.session_id,timestamp:Date.now()}),null},postToolUse:t=>{let n=t.tool_name.toLowerCase();if(n!=="write"&&n!=="edit"&&n!=="multiedit")return null;let o,r;for(let[s,c]of $t)if(c.sessionId===t.session_id&&c.tool===n){o=c,r=s;break}if(!o){let s=t.tool_input.file_path??t.tool_input.filePath??t.tool_input.path;if(!s)return null;o={filePath:s,content:t.tool_input.content,oldString:t.tool_input.old_string??t.tool_input.oldString,newString:t.tool_input.new_string??t.tool_input.newString,edits:t.tool_input.edits,tool:n,sessionId:t.session_id,timestamp:Date.now()}}if(r&&$t.delete(r),t.tool_response){let s=t.tool_response.toLowerCase();if(s.includes("error:")||s.includes("failed to")||s.includes("could not")||s.startsWith("error"))return ze("skipping due to tool failure in response"),null}let i=Tm(o.filePath,o.content,o.oldString,o.newString,o.edits);return i.hasComments&&i.message?(ze("detected comments, returning message"),e?.customPrompt||i.message):null}}}var pl=H(require("fs"),1),ml=H(require("path"),1),gl=require("os");var cl=[/(\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],ll=["prompt is too long","is too long","context_length_exceeded","max_tokens","token limit","context length","too many tokens","non-empty content"],Om=[/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],vm=/messages\.(\d+)/;function Rm(e){return Om.some(t=>t.test(e))}function Zo(e){for(let t of cl){let n=e.match(t);if(n){let o=parseInt(n[1],10),r=parseInt(n[2],10);return o>r?{current:o,max:r}:{current:r,max:o}}}return null}function al(e){let t=e.match(vm);if(t)return parseInt(t[1],10)}function dt(e){if(Rm(e))return!1;let t=e.toLowerCase();return ll.some(n=>t.includes(n.toLowerCase()))}function _n(e){if(typeof e=="string"){if(e.toLowerCase().includes("non-empty content"))return{currentTokens:0,maxTokens:0,errorType:"non-empty content",messageIndex:al(e)};if(dt(e)){let l=Zo(e);return{currentTokens:l?.current??0,maxTokens:l?.max??0,errorType:"token_limit_exceeded_string"}}return null}if(!e||typeof e!="object")return null;let t=e,n=[],o=t.data,r=o?.responseBody,i=t.message,s=t.error,c=s?.error;if(typeof r=="string"&&n.push(r),typeof i=="string"&&n.push(i),typeof s?.message=="string"&&n.push(s.message),typeof t.body=="string"&&n.push(t.body),typeof t.details=="string"&&n.push(t.details),typeof t.reason=="string"&&n.push(t.reason),typeof t.description=="string"&&n.push(t.description),typeof c?.message=="string"&&n.push(c.message),typeof o?.message=="string"&&n.push(o.message),typeof o?.error=="string"&&n.push(o.error),n.length===0)try{let l=JSON.stringify(t);dt(l)&&n.push(l)}catch{}let a=n.join(" ");if(!dt(a))return null;if(typeof r=="string")try{let l=[/data:\s*(\{[\s\S]*\})\s*$/m,/(\{"type"\s*:\s*"error"[\s\S]*\})/,/(\{[\s\S]*"error"[\s\S]*\})/];for(let d of l){let f=r.match(d);if(f)try{let g=JSON.parse(f[1]),m=g.error?.message||"",p=Zo(m);if(p)return{currentTokens:p.current,maxTokens:p.max,requestId:g.request_id,errorType:g.error?.type||"token_limit_exceeded"}}catch{}}let u=JSON.parse(r);if(typeof u.message=="string"&&dt(u.message))return{currentTokens:0,maxTokens:0,errorType:"bedrock_input_too_long"}}catch{}for(let l of n){let u=Zo(l);if(u)return{currentTokens:u.current,maxTokens:u.max,errorType:"token_limit_exceeded"}}return a.toLowerCase().includes("non-empty content")?{currentTokens:0,maxTokens:0,errorType:"non-empty content",messageIndex:al(a)}:dt(a)?{currentTokens:0,maxTokens:0,errorType:"token_limit_exceeded_unknown"}:null}function er(e){return dt(e)}var tr=`CONTEXT WINDOW LIMIT REACHED - IMMEDIATE ACTION REQUIRED
|
|
591
1256
|
|
|
592
1257
|
The conversation has exceeded the model's context window limit. To continue working effectively, you must take one of these actions:
|
|
593
1258
|
|
|
@@ -612,7 +1277,7 @@ Current Status:
|
|
|
612
1277
|
- Context limit exceeded
|
|
613
1278
|
- Further API calls will fail until context is reduced
|
|
614
1279
|
- Action required before continuing
|
|
615
|
-
`,
|
|
1280
|
+
`,nr="Context window limit reached. Please use /compact to summarize the conversation or start a new session.",or=`API ERROR: Non-empty content validation failed.
|
|
616
1281
|
|
|
617
1282
|
This error typically occurs when:
|
|
618
1283
|
- A message has empty text content
|
|
@@ -623,7 +1288,7 @@ Suggested actions:
|
|
|
623
1288
|
2. If the error persists, start a new session
|
|
624
1289
|
|
|
625
1290
|
The system will attempt automatic recovery.
|
|
626
|
-
`;var
|
|
1291
|
+
`;var rr=`CONTEXT RECOVERY FAILED
|
|
627
1292
|
|
|
628
1293
|
All automatic recovery attempts have been exhausted.
|
|
629
1294
|
Please start a new session to continue.
|
|
@@ -634,13 +1299,13 @@ Before starting a new session:
|
|
|
634
1299
|
3. Document the current state of the task
|
|
635
1300
|
|
|
636
1301
|
You can copy this conversation summary to continue in a new session.
|
|
637
|
-
`;var
|
|
638
|
-
`;
|
|
1302
|
+
`;var ir={maxAttempts:2,initialDelayMs:2e3,backoffFactor:2,maxDelayMs:3e4};var Im=process.env.CONTEXT_LIMIT_RECOVERY_DEBUG==="1",Am=ml.join((0,gl.tmpdir)(),"context-limit-recovery-debug.log");function On(...e){if(Im){let t=`[${new Date().toISOString()}] [context-limit-recovery] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
|
|
1303
|
+
`;pl.appendFileSync(Am,t)}}var vn=new Map,hl=3e5;function ul(e){let t=vn.get(e),n=Date.now();return t&&n-t.lastErrorTime>hl&&(t=void 0),t||(t={retryState:{attempt:0,lastAttemptTime:0},truncateState:{truncateAttempt:0},lastErrorTime:n,errorCount:0},vn.set(e,t)),t}function bm(){let e=Date.now();for(let[t,n]of vn)e-n.lastErrorTime>hl&&vn.delete(t)}var dl=!1;function kl(e){return On("createContextLimitRecoveryHook called",{config:e}),dl||(dl=!0,setInterval(bm,6e4)),{postToolUse:t=>{if(!t.tool_response)return null;let n=_n(t.tool_response);if(!n&&!er(t.tool_response))return null;On("detected token limit error",{tool:t.tool_name,sessionId:t.session_id,parsed:n});let o=ul(t.session_id);o.lastErrorTime=Date.now(),o.errorCount++;let r=fl(n,o,e);return r.message?(On("injecting recovery message",{errorType:r.errorType,attempt:o.retryState.attempt}),r.message):null},onError:t=>{let n=_n(t.error);if(!n)return{attempted:!1,success:!1};On("error notification contains token limit error",{sessionId:t.session_id,parsed:n});let o=ul(t.session_id);o.lastErrorTime=Date.now(),o.errorCount++;let r=fl(n,o,e);return{attempted:!0,success:!!r.message,message:r.message,errorType:r.errorType}}}}function fl(e,t,n){if(n?.customMessage)return{message:n.customMessage,errorType:e?.errorType};if(e?.errorType?.includes("non-empty content"))return{message:or,errorType:"non-empty content"};if(t.retryState.attempt++,t.retryState.lastAttemptTime=Date.now(),t.retryState.attempt>ir.maxAttempts)return{message:rr,errorType:"recovery_exhausted"};if(n?.detailed!==!1){let o=tr;return e?.currentTokens&&e?.maxTokens&&(o+=`
|
|
639
1304
|
Token Details:
|
|
640
1305
|
- Current: ${e.currentTokens.toLocaleString()} tokens
|
|
641
1306
|
- Maximum: ${e.maxTokens.toLocaleString()} tokens
|
|
642
1307
|
- Over limit by: ${(e.currentTokens-e.maxTokens).toLocaleString()} tokens
|
|
643
|
-
`),{message:o,errorType:e?.errorType||"token_limit_exceeded"}}return{message:
|
|
1308
|
+
`),{message:o,errorType:e?.errorType||"token_limit_exceeded"}}return{message:nr,errorType:e?.errorType||"token_limit_exceeded"}}var yl=/File content \((\d+) tokens\) exceeds maximum allowed tokens \((\d+)\)/i,Cm=/exceeds maximum allowed tokens/i;function Nm(e){let t=e.match(yl);return t?{current:parseInt(t[1],10),max:parseInt(t[2],10)}:null}function Pm(e,t){return e.toLowerCase()==="read"&&(yl.test(t)||Cm.test(t))}function xm(e,t){return`[SYSTEM RECOVERY - READ TOOL FILE SIZE LIMIT]
|
|
644
1309
|
|
|
645
1310
|
${t?`The file contains ${t.current} tokens, exceeding the ${t.max} token limit.`:"The file is too large to read in one operation."}
|
|
646
1311
|
|
|
@@ -670,7 +1335,7 @@ ${t?`The file contains ${t.current} tokens, exceeding the ${t.max} token limit.`
|
|
|
670
1335
|
- Need overview/summary? \u2192 Use multimodal-looker agent
|
|
671
1336
|
- Need specific section? \u2192 Grep to find it, then Read that portion
|
|
672
1337
|
|
|
673
|
-
Proceed with one of these strategies.`.trim()}function
|
|
1338
|
+
Proceed with one of these strategies.`.trim()}function El(){return{postToolUse:e=>{if(!e.tool_response||!Pm(e.tool_name,e.tool_response))return null;let t=e.tool_input?.file_path||"<unknown file>",n=Nm(e.tool_response);return xm(t,n||void 0)}}}var vl=H(require("fs"),1),Rl=H(require("path"),1),Il=require("os");var sr=process.env.ANTHROPIC_1M_CONTEXT==="true"||process.env.VERTEX_ANTHROPIC_1M_CONTEXT==="true"?1e6:2e5,Rn=4,ar=`CONTEXT WINDOW WARNING - APPROACHING LIMIT
|
|
674
1339
|
|
|
675
1340
|
Your context usage is getting high. Consider these actions to prevent hitting the limit:
|
|
676
1341
|
|
|
@@ -690,7 +1355,7 @@ Your context usage is getting high. Consider these actions to prevent hitting th
|
|
|
690
1355
|
|
|
691
1356
|
Current Status: Context usage is high but recoverable.
|
|
692
1357
|
Action recommended: Use /compact when convenient.
|
|
693
|
-
`,
|
|
1358
|
+
`,cr=`CRITICAL: CONTEXT WINDOW ALMOST FULL
|
|
694
1359
|
|
|
695
1360
|
Your context usage is critically high. Immediate action required:
|
|
696
1361
|
|
|
@@ -709,8 +1374,8 @@ Your context usage is critically high. Immediate action required:
|
|
|
709
1374
|
|
|
710
1375
|
WARNING: Further messages may fail if context is not reduced.
|
|
711
1376
|
Action required: Run /compact now.
|
|
712
|
-
`;var
|
|
713
|
-
`;
|
|
1377
|
+
`;var Dm=process.env.PREEMPTIVE_COMPACTION_DEBUG==="1",Lm=Rl.join((0,Il.tmpdir)(),"preemptive-compaction-debug.log");function ft(...e){if(Dm){let t=`[${new Date().toISOString()}] [preemptive-compaction] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
|
|
1378
|
+
`;vl.appendFileSync(Lm,t)}}var In=new Map;function Mm(){let e=Date.now(),t=1800*1e3;for(let[n,o]of In)e-o.lastWarningTime>t&&In.delete(n)}var Sl=!1;function Al(e){return Math.ceil(e.length/Rn)}function $m(e,t){let n=t?.warningThreshold??.85,o=t?.criticalThreshold??.95,r=sr,i=Al(e),s=i/r,c=s>=n,a=s>=o,l="none";return a?l="compact":c&&(l="warn"),{totalTokens:i,usageRatio:s,isWarning:c,isCritical:a,action:l}}function An(e){let t=In.get(e);return t||(t={lastWarningTime:0,warningCount:0,estimatedTokens:0},In.set(e,t)),t}function Fm(e,t){let n=An(e),o=t?.cooldownMs??6e4,r=t?.maxWarnings??3,i=Date.now();return i-n.lastWarningTime<o?(ft("skipping warning - cooldown active",{sessionId:e,elapsed:i-n.lastWarningTime,cooldown:o}),!1):n.warningCount>=r?(ft("skipping warning - max reached",{sessionId:e,warningCount:n.warningCount,maxWarnings:r}),!1):!0}function Um(e){let t=An(e);t.lastWarningTime=Date.now(),t.warningCount++}function bl(e){return ft("createPreemptiveCompactionHook called",{config:e}),e?.enabled===!1?{postToolUse:()=>null,stop:()=>null}:(Sl||(Sl=!0,setInterval(Mm,300*1e3)),{postToolUse:t=>{if(!t.tool_response)return null;let n=t.tool_name.toLowerCase();if(!["read","grep","glob","bash","webfetch"].includes(n))return null;let r=Al(t.tool_response),i=An(t.session_id);i.estimatedTokens+=r,ft("tracking tool output",{tool:n,responseTokens:r,cumulativeTokens:i.estimatedTokens});let s=$m("x".repeat(i.estimatedTokens*Rn),e);return!s.isWarning||!Fm(t.session_id,e)?null:(Um(t.session_id),ft("injecting context warning",{sessionId:t.session_id,usageRatio:s.usageRatio,isCritical:s.isCritical}),e?.customMessage?e.customMessage:s.isCritical?cr:ar)},stop:t=>{let n=An(t.session_id);return n.warningCount>0&&(ft("resetting warning count on stop",{sessionId:t.session_id,previousCount:n.warningCount}),n.warningCount=0),null}})}var ue=require("fs"),Nl=require("path");var lr=require("path"),Cl=require("os"),jm=(0,lr.join)((0,Cl.homedir)(),".olympus"),bn=(0,lr.join)(jm,"agent-usage-reminder"),ur=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"]),dr=new Set(["task","call_omo_agent","olympus_task"]),fr=`
|
|
714
1379
|
[Agent Usage Reminder]
|
|
715
1380
|
|
|
716
1381
|
You called a search/fetch tool directly without leveraging specialized agents.
|
|
@@ -734,7 +1399,7 @@ WHY:
|
|
|
734
1399
|
- Reduces context window usage in main session
|
|
735
1400
|
|
|
736
1401
|
ALWAYS prefer: Multiple parallel Task calls > Direct tool calls
|
|
737
|
-
`;function
|
|
1402
|
+
`;function pr(e){return(0,Nl.join)(bn,`${e}.json`)}function mr(e){let t=pr(e);if(!(0,ue.existsSync)(t))return null;try{let n=(0,ue.readFileSync)(t,"utf-8");return JSON.parse(n)}catch{return null}}function Cn(e){(0,ue.existsSync)(bn)||(0,ue.mkdirSync)(bn,{recursive:!0});let t=pr(e.sessionID);(0,ue.writeFileSync)(t,JSON.stringify(e,null,2))}function gr(e){let t=pr(e);(0,ue.existsSync)(t)&&(0,ue.unlinkSync)(t)}function Hm(e){let t=e||process.cwd();return bt(t)?.active?{active:!0,mode:"ascent"}:ct(t)?.active?{active:!0,mode:"olympus"}:We(t)?.active?{active:!0,mode:"ultrawork"}:{active:!1,mode:"none"}}function Wm(e){if(!e||typeof e!="object")return null;let t=e;return t.file_path||t.filePath||t.path}function Gm(e,t){if(e<3)return null;let n=e>=5?"CRITICAL":"WARNING";return`<conductor-violation severity="${n}">
|
|
738
1403
|
|
|
739
1404
|
[${n}: CONDUCTOR MODE VIOLATION - ${t.toUpperCase()} ACTIVE]
|
|
740
1405
|
|
|
@@ -760,27 +1425,27 @@ ${e>=5?"**CRITICAL**: Too many direct operations. Your next action MUST be deleg
|
|
|
760
1425
|
|
|
761
1426
|
---
|
|
762
1427
|
|
|
763
|
-
`}function
|
|
764
|
-
`;(0,fi.appendFileSync)(si,t)}}function mi(e){if(!e)return"";if(typeof e=="string")return e.toLowerCase();let t=e,n=[t.data,t.error,t,t.data?.error];for(let o of n)if(o&&typeof o=="object"){let r=o.message;if(typeof r=="string"&&r.length>0)return r.toLowerCase()}try{return JSON.stringify(e).toLowerCase()}catch{return""}}function gi(e){let n=mi(e).match(/messages\.(\d+)/);return n?parseInt(n[1],10):null}function hi(e){let t=mi(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 ll(e){return hi(e)!==null}function ul(e){return e.filter(t=>t.type==="tool_use"&&!!t.id).map(t=>t.id)}async function dl(e,t){x("recoverToolResultMissing",{sessionID:e,msgId:t.info?.id});let n=t.parts||[];n.length===0&&t.info?.id&&(n=J(t.info.id).map(s=>({type:s.type==="tool"?"tool_use":s.type,id:"callID"in s?s.callID:s.id,name:"tool"in s?s.tool:void 0,input:"state"in s?s.state?.input:void 0})));let o=ul(n);return o.length===0?(x("No tool_use IDs found"),!1):(x("Found tool_use IDs to inject results for",o),!0)}async function pl(e,t,n){x("recoverThinkingBlockOrder",{sessionID:e});let o=gi(n);if(o!==null){let i=pi(e,o);if(i)return x("Found target message by index",{targetIndex:o,targetMessageID:i}),Kn(e,i)}let r=Vn(e);if(r.length===0)return x("No orphan thinking messages found"),!1;x("Found orphan thinking messages",r);let s=!1;for(let i of r)Kn(e,i)&&(s=!0);return s}async function fl(e,t){x("recoverThinkingDisabledViolation",{sessionID:e});let n=Wn(e);if(n.length===0)return x("No messages with thinking blocks found"),!1;x("Found messages with thinking blocks",n);let o=!1;for(let r of n)ui(r)&&(o=!0);return o}async function ml(e,t,n){x("recoverEmptyContentMessage",{sessionID:e});let o=gi(n),r=t.info?.id,s=!1,i=di(e);for(let l of i)Ye(l,B)&&(s=!0);let c=li(e);for(let l of c)Be(e,l,B)&&(s=!0);if(o!==null){let l=ci(e,o);if(l&&(Ye(l,B)||Be(e,l,B)))return!0}if(r&&(Ye(r,B)||Be(e,r,B)))return!0;let a=Yn(e);for(let l of a)Ye(l,B)&&(s=!0),Be(e,l,B)&&(s=!0);return s}async function gl(e,t,n,o){x("handleSessionRecovery",{sessionID:e,error:t});let r=hi(t);if(!r)return x("Not a recoverable error"),{attempted:!1,success:!1};x("Detected recoverable error type",r);try{let s=!1,i=n||{info:{},parts:[]};switch(r){case"tool_result_missing":s=await dl(e,i);break;case"thinking_block_order":s=await pl(e,i,t);break;case"thinking_disabled_violation":s=await fl(e,i);break;case"empty_content":s=await ml(e,i,t);break}x("Recovery result",{errorType:r,success:s});let c=o?.customMessages?.[r]||_t[r]?.message||`Session recovery attempted for ${r}`;return{attempted:!0,success:s,message:s?c:void 0,errorType:r}}catch(s){return x("Recovery failed with error",s),{attempted:!0,success:!1,errorType:r}}}function Ti(e){return x("createSessionRecoveryHook",{config:e}),{onError:async t=>gl(t.session_id,t.error,t.message,e),isRecoverable:t=>ll(t),getRecoveryMessage:t=>{if(t)return e?.customMessages?.[t]||_t[t]?.message}}}function ki(){let e=Ti();g({name:"sessionRecovery",event:"PostToolUseFailure",priority:10,handler:async t=>{let n=t.error||t.toolOutput;if(!n)return{continue:!0};if(!e.isRecoverable(n))return{continue:!0};let o=await e.onError({session_id:t.sessionId||"default",error:n,message:void 0});return o.attempted&&o.success?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:o.message||`[session-recovery] Recovered from ${o.errorType} error. Please retry.`}}:o.attempted&&!o.success?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:`[session-recovery] Attempted recovery for ${o.errorType} but could not fix automatically. You may need to restart the session.`}}:{continue:!0}}})}var Y=require("fs"),Rt=require("path"),Ei=require("os");var We=class{config;counts=new Map;queues=new Map;constructor(t){this.config=t}getConcurrencyLimit(t){let n=this.config?.modelConcurrency?.[t];if(n!==void 0)return n===0?1/0:n;let o=t.split("/")[0],r=this.config?.providerConcurrency?.[o];if(r!==void 0)return r===0?1/0:r;let s=this.config?.defaultConcurrency;return s!==void 0?s===0?1/0:s:5}async acquire(t){let n=this.getConcurrencyLimit(t);if(n===1/0)return;let o=this.counts.get(t)??0;if(o<n){this.counts.set(t,o+1);return}return new Promise(r=>{let s=this.queues.get(t)??[];s.push(r),this.queues.set(t,s)})}release(t){if(this.getConcurrencyLimit(t)===1/0)return;let o=this.queues.get(t);if(o&&o.length>0)o.shift()();else{let r=this.counts.get(t)??0;r>0&&this.counts.set(t,r-1)}}getCount(t){return this.counts.get(t)??0}getQueueLength(t){return this.queues.get(t)?.length??0}isAtCapacity(t){let n=this.getConcurrencyLimit(t);return n===1/0?!1:(this.counts.get(t)??0)>=n}getActiveCounts(){return new Map(this.counts)}clear(){this.counts.clear(),this.queues.clear()}};var hl=1800*1e3,be=(0,Rt.join)((0,Ei.homedir)(),".claude",".olympus","background-tasks"),It=class{tasks=new Map;notifications=new Map;concurrencyManager;config;pruneInterval;constructor(t){this.config=t??{},this.concurrencyManager=new We(t),this.ensureStorageDir(),this.loadPersistedTasks(),this.startPruning()}ensureStorageDir(){(0,Y.existsSync)(be)||(0,Y.mkdirSync)(be,{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,Rt.join)(be,`${t}.json`)}persistTask(t){let n=this.getTaskPath(t.id);(0,Y.writeFileSync)(n,JSON.stringify(t,null,2))}unpersistTask(t){let n=this.getTaskPath(t);(0,Y.existsSync)(n)&&(0,Y.unlinkSync)(n)}loadPersistedTasks(){if((0,Y.existsSync)(be))try{let{readdirSync:t}=require("fs"),n=t(be);for(let o of n)if(o.endsWith(".json"))try{let r=(0,Rt.join)(be,o),s=(0,Y.readFileSync)(r,"utf-8"),i=JSON.parse(s);i.startedAt=new Date(i.startedAt),i.completedAt&&(i.completedAt=new Date(i.completedAt)),i.progress?.lastUpdate&&(i.progress.lastUpdate=new Date(i.progress.lastUpdate)),i.progress?.lastMessageAt&&(i.progress.lastMessageAt=new Date(i.progress.lastMessageAt)),this.tasks.set(i.id,i)}catch{}}catch{}}startPruning(){this.pruneInterval||(this.pruneInterval=setInterval(()=>{this.pruneStaleTasksAndNotifications()},6e4),this.pruneInterval.unref&&this.pruneInterval.unref())}stopPruning(){this.pruneInterval&&(clearInterval(this.pruneInterval),this.pruneInterval=void 0)}pruneStaleTasksAndNotifications(){let t=Date.now(),n=this.config.taskTimeoutMs??hl;for(let[o,r]of this.tasks.entries())t-r.startedAt.getTime()>n&&r.status==="running"&&(r.status="error",r.error=`Task timed out after ${Math.round(n/6e4)} minutes`,r.completedAt=new Date,r.concurrencyKey&&this.concurrencyManager.release(r.concurrencyKey),this.clearNotificationsForTask(o),this.unpersistTask(o),this.tasks.delete(o));for(let[o,r]of this.notifications.entries()){let s=r.filter(i=>t-i.startedAt.getTime()<=n);s.length===0?this.notifications.delete(o):s.length!==r.length&&this.notifications.set(o,s)}}async launch(t){let n=t.agent,o=this.config.maxTotalTasks??10;if(Array.from(this.tasks.values()).filter(a=>a.status==="running").length>=o)throw new Error(`Maximum concurrent background tasks (${o}) reached. Wait for some tasks to complete.`);await this.concurrencyManager.acquire(n);let s=this.generateTaskId(),i=`ses_${this.generateTaskId()}`,c={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,c),this.persistTask(c),c}async resume(t){let n=this.findBySession(t.sessionId);if(!n)throw new Error(`Task not found for session: ${t.sessionId}`);return n.status="running",n.completedAt=void 0,n.error=void 0,n.parentSessionId=t.parentSessionId,n.progress||(n.progress={toolCalls:0,lastUpdate:new Date}),n.progress.lastUpdate=new Date,this.persistTask(n),n}getTask(t){return this.tasks.get(t)}findBySession(t){for(let n of this.tasks.values())if(n.sessionId===t)return n}getTasksByParentSession(t){let n=[];for(let o of this.tasks.values())o.parentSessionId===t&&n.push(o);return n}getAllTasks(){return Array.from(this.tasks.values())}getRunningTasks(){return Array.from(this.tasks.values()).filter(t=>t.status==="running")}updateTaskStatus(t,n,o,r){let s=this.tasks.get(t);s&&(s.status=n,o&&(s.result=o),r&&(s.error=r),(n==="completed"||n==="error"||n==="cancelled")&&(s.completedAt=new Date,s.concurrencyKey&&this.concurrencyManager.release(s.concurrencyKey),this.markForNotification(s)),this.persistTask(s))}updateTaskProgress(t,n){let o=this.tasks.get(t);o&&(o.progress||(o.progress={toolCalls:0,lastUpdate:new Date}),Object.assign(o.progress,n,{lastUpdate:new Date}),this.persistTask(o))}markForNotification(t){let n=this.notifications.get(t.parentSessionId)??[];n.push(t),this.notifications.set(t.parentSessionId,n)}getPendingNotifications(t){return this.notifications.get(t)??[]}clearNotifications(t){this.notifications.delete(t)}clearNotificationsForTask(t){for(let[n,o]of this.notifications.entries()){let r=o.filter(s=>s.id!==t);r.length===0?this.notifications.delete(n):this.notifications.set(n,r)}}removeTask(t){let n=this.tasks.get(t);n?.concurrencyKey&&this.concurrencyManager.release(n.concurrencyKey),this.clearNotificationsForTask(t),this.unpersistTask(t),this.tasks.delete(t)}formatDuration(t,n){let o=(n??new Date).getTime()-t.getTime(),r=Math.floor(o/1e3),s=Math.floor(r/60),i=Math.floor(s/60);return i>0?`${i}h ${s%60}m ${r%60}s`:s>0?`${s}m ${r%60}s`:`${r}s`}getStatusSummary(){let t=this.getRunningTasks(),n=this.getAllTasks();if(n.length===0)return"No background tasks.";let o=[`Background Tasks: ${t.length} running, ${n.length} total`,""];for(let r of n){let s=this.formatDuration(r.startedAt,r.completedAt),i=r.status.toUpperCase(),c=r.progress?` (${r.progress.toolCalls} tools)`:"";o.push(` [${i}] ${r.description} - ${s}${c}`),r.error&&o.push(` Error: ${r.error}`)}return o.join(`
|
|
765
|
-
`)}cleanup(){this.stopPruning(),this.tasks.clear(),this.notifications.clear()}},
|
|
766
|
-
`)}function
|
|
1428
|
+
`}function Pl(){let e=new Map,t=new Map;function n(a){if(!e.has(a)){let u=mr(a)??{sessionID:a,agentUsed:!1,reminderCount:0,updatedAt:Date.now()};e.set(a,u)}return e.get(a)}function o(a){let l=n(a);l.agentUsed=!0,l.updatedAt=Date.now(),Cn(l)}function r(a){e.delete(a),gr(a),t.delete(a)}function i(a,l,u){let d=t.get(a)||{consecutiveCount:0,lastToolName:"",lastFilePath:"",sessionId:a};return l.toLowerCase()==="task"?(d.consecutiveCount=0,t.set(a,d),0):(["edit","write","multiedit"].includes(l.toLowerCase())&&(d.consecutiveCount++,d.lastToolName=l,d.lastFilePath=u,t.set(a,d)),d.consecutiveCount)}return{"tool.execute.after":async(a,l)=>{let{tool:u,sessionID:d}=a,f=u.toLowerCase();if(dr.has(f)){o(d),i(d,f,"");return}let g=a.properties||{},m=Wm(g),p=i(d,f,m||""),h=Hm();if(h.active){let T=Gm(p,h.mode);if(T){l.output=T+l.output;return}}if(!ur.has(f))return;let y=n(d);y.agentUsed||(l.output+=fr,y.reminderCount++,y.updatedAt=Date.now(),Cn(y))},event:async({event:a})=>{let l=a.properties;if(a.type==="session.deleted"){let u=l?.info;u?.id&&r(u.id)}if(a.type==="session.compacted"){let u=l?.sessionID??l?.info?.id;u&&r(u)}}}}function xl(){let e=process.cwd(),t=tl();v({name:"editErrorRecovery",event:"PostToolUse",matcher:/^edit$/i,priority:10,handler:async a=>{if(!a.toolName||!a.toolOutput)return{continue:!0};let l=t.afterToolExecute({tool:a.toolName,sessionId:a.sessionId||"",callId:""},{title:"",output:String(a.toolOutput),metadata:void 0});return l.output!==String(a.toolOutput)?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:l.output.substring(String(a.toolOutput).length)}}:{continue:!0}}});let n=sl();v({name:"commentChecker",event:"PostToolUse",matcher:/^(write|edit|multiedit)$/i,priority:20,handler:async a=>{if(!a.toolName)return{continue:!0};let l=n.postToolUse({tool_name:a.toolName,session_id:a.sessionId||"",tool_input:a.toolInput||{},tool_response:a.toolOutput?String(a.toolOutput):void 0});return l?{continue:!0,message:l}:{continue:!0}}});let o=kl();v({name:"contextWindowLimitRecovery",event:"PostToolUse",priority:30,handler:async a=>{if(!a.toolName)return{continue:!0};let l=o.postToolUse({tool_name:a.toolName,session_id:a.sessionId||"",tool_input:a.toolInput||{},tool_response:a.toolOutput?String(a.toolOutput):void 0});return l?{continue:!0,message:l}:{continue:!0}}});let r=El();v({name:"readToolLimitRecovery",event:"PostToolUse",matcher:/^read$/i,priority:35,handler:async a=>{if(!a.toolName||a.toolName.toLowerCase()!=="read")return{continue:!0};let l=r.postToolUse({tool_name:a.toolName,session_id:a.sessionId||"",tool_input:a.toolInput||{},tool_response:a.toolOutput?String(a.toolOutput):void 0});return l?{continue:!0,message:l}:{continue:!0}}});let i=bl();v({name:"preemptiveCompaction",event:"PostToolUse",matcher:/^(read|grep|glob|bash|webfetch)$/i,priority:40,handler:async a=>{if(!a.toolName)return{continue:!0};let l=i.postToolUse({tool_name:a.toolName,session_id:a.sessionId||"",tool_input:a.toolInput||{},tool_response:a.toolOutput?String(a.toolOutput):void 0});return l?{continue:!0,message:l}:{continue:!0}}});let s=Pl();v({name:"agentUsageReminder",event:"PostToolUse",matcher:/^(read|grep|glob|edit|write)$/i,priority:50,handler:async a=>{if(!a.toolName)return{continue:!0};let l={title:"",output:a.toolOutput?String(a.toolOutput):"",metadata:void 0};await s["tool.execute.after"]({tool:a.toolName,sessionID:a.sessionId||"",callID:""},l);let u=a.toolOutput?String(a.toolOutput):"";return l.output!==u?{continue:!0,message:l.output.substring(u.length)}:{continue:!0}}});let c=Sn(e);v({name:"olympusOrchestratorPost",event:"PostToolUse",matcher:/^(write|edit|bash|task)$/i,priority:60,handler:async a=>{if(!a.toolName)return{continue:!0};let l=c.postTool(a.toolName,a.toolInput||{},a.toolOutput?String(a.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 ql=require("node:fs");var N=require("node:fs"),oe=require("node:path");var pt=require("node:path"),Nn=require("node:os");function Bm(){return process.env.XDG_DATA_HOME??(0,pt.join)((0,Nn.homedir)(),".local","share")}function qm(){return(0,pt.join)(Bm(),"claude-code","storage")}var Dl=qm(),Ft=(0,pt.join)(Dl,"message"),mt=(0,pt.join)(Dl,"part"),He=new Set(["thinking","redacted_thinking","reasoning"]),Ll=new Set(["step-start","step-finish"]);var de="[user interrupted]",Pn={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 Ml=process.env.SESSION_RECOVERY_DEBUG==="1",$l=(0,pt.join)((0,Nn.tmpdir)(),"session-recovery-debug.log");function Ym(){let e=Date.now().toString(16),t=Math.random().toString(36).substring(2,10);return`prt_${e}${t}`}function Vm(e){if(!(0,N.existsSync)(Ft))return"";let t=(0,oe.join)(Ft,e);if((0,N.existsSync)(t))return t;for(let n of(0,N.readdirSync)(Ft)){let o=(0,oe.join)(Ft,n,e);if((0,N.existsSync)(o))return o}return""}function Ae(e){let t=Vm(e);if(!t||!(0,N.existsSync)(t))return[];let n=[];for(let o of(0,N.readdirSync)(t))if(o.endsWith(".json"))try{let r=(0,N.readFileSync)((0,oe.join)(t,o),"utf-8");n.push(JSON.parse(r))}catch{continue}return n.sort((o,r)=>{let i=o.time?.created??0,s=r.time?.created??0;return i!==s?i-s:o.id.localeCompare(r.id)})}function Te(e){let t=(0,oe.join)(mt,e);if(!(0,N.existsSync)(t))return[];let n=[];for(let o of(0,N.readdirSync)(t))if(o.endsWith(".json"))try{let r=(0,N.readFileSync)((0,oe.join)(t,o),"utf-8");n.push(JSON.parse(r))}catch{continue}return n}function Fl(e){return He.has(e.type)||Ll.has(e.type)?!1:e.type==="text"?!!e.text?.trim():e.type==="tool"||e.type==="tool_use"||e.type==="tool_result"}function Ul(e){return Te(e).some(Fl)}function Ut(e,t,n){let o=(0,oe.join)(mt,t);(0,N.existsSync)(o)||(0,N.mkdirSync)(o,{recursive:!0});let r=Ym(),i={id:r,sessionID:e,messageID:t,type:"text",text:n,synthetic:!0};try{return(0,N.writeFileSync)((0,oe.join)(o,`${r}.json`),JSON.stringify(i,null,2)),!0}catch{return!1}}function hr(e){let t=Ae(e),n=[];for(let o of t)Ul(o.id)||n.push(o.id);return n}function jl(e,t){let n=Ae(e),o=[t,t-1,t+1,t-2,t+2,t-3,t-4,t-5];for(let r of o){if(r<0||r>=n.length)continue;let i=n[r];if(!Ul(i.id))return i.id}return null}function kr(e){let t=Ae(e),n=[];for(let o of t){if(o.role!=="assistant")continue;Te(o.id).some(s=>He.has(s.type))&&n.push(o.id)}return n}function Hl(e){let t=Ae(e),n=[];for(let o of t){if(o.role!=="assistant")continue;let r=Te(o.id);if(r.length===0)continue;let i=r.some(c=>He.has(c.type)),s=r.some(Fl);i&&!s&&n.push(o.id)}return n}function yr(e){let t=Ae(e),n=[];for(let o of t){if(o.role!=="assistant")continue;let r=Te(o.id);if(r.length===0)continue;let s=[...r].sort((a,l)=>a.id.localeCompare(l.id))[0];He.has(s.type)||n.push(o.id)}return n}function Km(e,t){let n=Ae(e),o=n.findIndex(r=>r.id===t);if(o===-1)return"";for(let r=o-1;r>=0;r--){let i=n[r];if(i.role!=="assistant")continue;let s=Te(i.id);for(let c of s)if(He.has(c.type)){let a=c.thinking,l=c.text,u=a||l;if(u&&u.trim().length>0)return u}}return""}function Er(e,t){let n=(0,oe.join)(mt,t);(0,N.existsSync)(n)||(0,N.mkdirSync)(n,{recursive:!0});let o=Km(e,t),r="prt_0000000000_thinking",i={id:r,sessionID:e,messageID:t,type:"thinking",thinking:o||"[Continuing from previous reasoning]",synthetic:!0};try{return(0,N.writeFileSync)((0,oe.join)(n,`${r}.json`),JSON.stringify(i,null,2)),!0}catch{return!1}}function Wl(e){let t=(0,oe.join)(mt,e);if(!(0,N.existsSync)(t))return!1;let n=!1;for(let o of(0,N.readdirSync)(t))if(o.endsWith(".json"))try{let r=(0,oe.join)(t,o),i=(0,N.readFileSync)(r,"utf-8"),s=JSON.parse(i);He.has(s.type)&&((0,N.unlinkSync)(r),n=!0)}catch{continue}return n}function jt(e,t=de){let n=(0,oe.join)(mt,e);if(!(0,N.existsSync)(n))return!1;let o=!1;for(let r of(0,N.readdirSync)(n))if(r.endsWith(".json"))try{let i=(0,oe.join)(n,r),s=(0,N.readFileSync)(i,"utf-8"),c=JSON.parse(s);if(c.type==="text"){let a=c;a.text?.trim()||(a.text=t,a.synthetic=!0,(0,N.writeFileSync)(i,JSON.stringify(a,null,2)),o=!0)}}catch{continue}return o}function Gl(e){let t=Ae(e),n=[];for(let o of t)Te(o.id).some(s=>s.type!=="text"?!1:!s.text?.trim())&&n.push(o.id);return n}function Bl(e,t){let n=Ae(e);if(t<0||t>=n.length)return null;let o=n[t];if(o.role!=="assistant")return null;let r=Te(o.id);if(r.length===0)return null;let s=[...r].sort((a,l)=>a.id.localeCompare(l.id))[0];return He.has(s.type)?null:o.id}function V(...e){if(Ml){let t=`[${new Date().toISOString()}] [session-recovery] ${e.map(n=>typeof n=="object"?JSON.stringify(n,null,2):String(n)).join(" ")}
|
|
1429
|
+
`;(0,ql.appendFileSync)($l,t)}}function Yl(e){if(!e)return"";if(typeof e=="string")return e.toLowerCase();let t=e,n=[t.data,t.error,t,t.data?.error];for(let o of n)if(o&&typeof o=="object"){let r=o.message;if(typeof r=="string"&&r.length>0)return r.toLowerCase()}try{return JSON.stringify(e).toLowerCase()}catch{return""}}function Vl(e){let n=Yl(e).match(/messages\.(\d+)/);return n?parseInt(n[1],10):null}function Kl(e){let t=Yl(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 Jm(e){return Kl(e)!==null}function zm(e){return e.filter(t=>t.type==="tool_use"&&!!t.id).map(t=>t.id)}async function Xm(e,t){V("recoverToolResultMissing",{sessionID:e,msgId:t.info?.id});let n=t.parts||[];n.length===0&&t.info?.id&&(n=Te(t.info.id).map(i=>({type:i.type==="tool"?"tool_use":i.type,id:"callID"in i?i.callID:i.id,name:"tool"in i?i.tool:void 0,input:"state"in i?i.state?.input:void 0})));let o=zm(n);return o.length===0?(V("No tool_use IDs found"),!1):(V("Found tool_use IDs to inject results for",o),!0)}async function Qm(e,t,n){V("recoverThinkingBlockOrder",{sessionID:e});let o=Vl(n);if(o!==null){let s=Bl(e,o);if(s)return V("Found target message by index",{targetIndex:o,targetMessageID:s}),Er(e,s)}let r=yr(e);if(r.length===0)return V("No orphan thinking messages found"),!1;V("Found orphan thinking messages",r);let i=!1;for(let s of r)Er(e,s)&&(i=!0);return i}async function Zm(e,t){V("recoverThinkingDisabledViolation",{sessionID:e});let n=kr(e);if(n.length===0)return V("No messages with thinking blocks found"),!1;V("Found messages with thinking blocks",n);let o=!1;for(let r of n)Wl(r)&&(o=!0);return o}async function eg(e,t,n){V("recoverEmptyContentMessage",{sessionID:e});let o=Vl(n),r=t.info?.id,i=!1,s=Gl(e);for(let l of s)jt(l,de)&&(i=!0);let c=Hl(e);for(let l of c)Ut(e,l,de)&&(i=!0);if(o!==null){let l=jl(e,o);if(l&&(jt(l,de)||Ut(e,l,de)))return!0}if(r&&(jt(r,de)||Ut(e,r,de)))return!0;let a=hr(e);for(let l of a)jt(l,de)&&(i=!0),Ut(e,l,de)&&(i=!0);return i}async function tg(e,t,n,o){V("handleSessionRecovery",{sessionID:e,error:t});let r=Kl(t);if(!r)return V("Not a recoverable error"),{attempted:!1,success:!1};V("Detected recoverable error type",r);try{let i=!1,s=n||{info:{},parts:[]};switch(r){case"tool_result_missing":i=await Xm(e,s);break;case"thinking_block_order":i=await Qm(e,s,t);break;case"thinking_disabled_violation":i=await Zm(e,s);break;case"empty_content":i=await eg(e,s,t);break}V("Recovery result",{errorType:r,success:i});let c=o?.customMessages?.[r]||Pn[r]?.message||`Session recovery attempted for ${r}`;return{attempted:!0,success:i,message:i?c:void 0,errorType:r}}catch(i){return V("Recovery failed with error",i),{attempted:!0,success:!1,errorType:r}}}function Jl(e){return V("createSessionRecoveryHook",{config:e}),{onError:async t=>tg(t.session_id,t.error,t.message,e),isRecoverable:t=>Jm(t),getRecoveryMessage:t=>{if(t)return e?.customMessages?.[t]||Pn[t]?.message}}}function zl(){let e=Jl();v({name:"sessionRecovery",event:"PostToolUseFailure",priority:10,handler:async t=>{let n=t.error||t.toolOutput;if(!n)return{continue:!0};if(!e.isRecoverable(n))return{continue:!0};let o=await e.onError({session_id:t.sessionId||"default",error:n,message:void 0});return o.attempted&&o.success?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:o.message||`[session-recovery] Recovered from ${o.errorType} error. Please retry.`}}:o.attempted&&!o.success?{continue:!0,hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:`[session-recovery] Attempted recovery for ${o.errorType} but could not fix automatically. You may need to restart the session.`}}:{continue:!0}}})}var fe=require("fs"),xn=require("path"),Xl=require("os");var Ht=class{config;counts=new Map;queues=new Map;constructor(t){this.config=t}getConcurrencyLimit(t){let n=this.config?.modelConcurrency?.[t];if(n!==void 0)return n===0?1/0:n;let o=t.split("/")[0],r=this.config?.providerConcurrency?.[o];if(r!==void 0)return r===0?1/0:r;let i=this.config?.defaultConcurrency;return i!==void 0?i===0?1/0:i:5}async acquire(t){let n=this.getConcurrencyLimit(t);if(n===1/0)return;let o=this.counts.get(t)??0;if(o<n){this.counts.set(t,o+1);return}return new Promise(r=>{let i=this.queues.get(t)??[];i.push(r),this.queues.set(t,i)})}release(t){if(this.getConcurrencyLimit(t)===1/0)return;let o=this.queues.get(t);if(o&&o.length>0)o.shift()();else{let r=this.counts.get(t)??0;r>0&&this.counts.set(t,r-1)}}getCount(t){return this.counts.get(t)??0}getQueueLength(t){return this.queues.get(t)?.length??0}isAtCapacity(t){let n=this.getConcurrencyLimit(t);return n===1/0?!1:(this.counts.get(t)??0)>=n}getActiveCounts(){return new Map(this.counts)}clear(){this.counts.clear(),this.queues.clear()}};var ng=1800*1e3,gt=(0,xn.join)((0,Xl.homedir)(),".claude",".olympus","background-tasks"),Dn=class{tasks=new Map;notifications=new Map;concurrencyManager;config;pruneInterval;constructor(t){this.config=t??{},this.concurrencyManager=new Ht(t),this.ensureStorageDir(),this.loadPersistedTasks(),this.startPruning()}ensureStorageDir(){(0,fe.existsSync)(gt)||(0,fe.mkdirSync)(gt,{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,xn.join)(gt,`${t}.json`)}persistTask(t){let n=this.getTaskPath(t.id);(0,fe.writeFileSync)(n,JSON.stringify(t,null,2))}unpersistTask(t){let n=this.getTaskPath(t);(0,fe.existsSync)(n)&&(0,fe.unlinkSync)(n)}loadPersistedTasks(){if((0,fe.existsSync)(gt))try{let{readdirSync:t}=require("fs"),n=t(gt);for(let o of n)if(o.endsWith(".json"))try{let r=(0,xn.join)(gt,o),i=(0,fe.readFileSync)(r,"utf-8"),s=JSON.parse(i);s.startedAt=new Date(s.startedAt),s.completedAt&&(s.completedAt=new Date(s.completedAt)),s.progress?.lastUpdate&&(s.progress.lastUpdate=new Date(s.progress.lastUpdate)),s.progress?.lastMessageAt&&(s.progress.lastMessageAt=new Date(s.progress.lastMessageAt)),this.tasks.set(s.id,s)}catch{}}catch{}}startPruning(){this.pruneInterval||(this.pruneInterval=setInterval(()=>{this.pruneStaleTasksAndNotifications()},6e4),this.pruneInterval.unref&&this.pruneInterval.unref())}stopPruning(){this.pruneInterval&&(clearInterval(this.pruneInterval),this.pruneInterval=void 0)}pruneStaleTasksAndNotifications(){let t=Date.now(),n=this.config.taskTimeoutMs??ng;for(let[o,r]of this.tasks.entries())t-r.startedAt.getTime()>n&&r.status==="running"&&(r.status="error",r.error=`Task timed out after ${Math.round(n/6e4)} minutes`,r.completedAt=new Date,r.concurrencyKey&&this.concurrencyManager.release(r.concurrencyKey),this.clearNotificationsForTask(o),this.unpersistTask(o),this.tasks.delete(o));for(let[o,r]of this.notifications.entries()){let i=r.filter(s=>t-s.startedAt.getTime()<=n);i.length===0?this.notifications.delete(o):i.length!==r.length&&this.notifications.set(o,i)}}async launch(t){let n=t.agent,o=this.config.maxTotalTasks??10;if(Array.from(this.tasks.values()).filter(a=>a.status==="running").length>=o)throw new Error(`Maximum concurrent background tasks (${o}) reached. Wait for some tasks to complete.`);await this.concurrencyManager.acquire(n);let i=this.generateTaskId(),s=`ses_${this.generateTaskId()}`,c={id:i,sessionId:s,parentSessionId:t.parentSessionId,description:t.description,prompt:t.prompt,agent:t.agent,status:"running",startedAt:new Date,progress:{toolCalls:0,lastUpdate:new Date},concurrencyKey:n};return this.tasks.set(i,c),this.persistTask(c),c}async resume(t){let n=this.findBySession(t.sessionId);if(!n)throw new Error(`Task not found for session: ${t.sessionId}`);return n.status="running",n.completedAt=void 0,n.error=void 0,n.parentSessionId=t.parentSessionId,n.progress||(n.progress={toolCalls:0,lastUpdate:new Date}),n.progress.lastUpdate=new Date,this.persistTask(n),n}getTask(t){return this.tasks.get(t)}findBySession(t){for(let n of this.tasks.values())if(n.sessionId===t)return n}getTasksByParentSession(t){let n=[];for(let o of this.tasks.values())o.parentSessionId===t&&n.push(o);return n}getAllTasks(){return Array.from(this.tasks.values())}getRunningTasks(){return Array.from(this.tasks.values()).filter(t=>t.status==="running")}updateTaskStatus(t,n,o,r){let i=this.tasks.get(t);i&&(i.status=n,o&&(i.result=o),r&&(i.error=r),(n==="completed"||n==="error"||n==="cancelled")&&(i.completedAt=new Date,i.concurrencyKey&&this.concurrencyManager.release(i.concurrencyKey),this.markForNotification(i)),this.persistTask(i))}updateTaskProgress(t,n){let o=this.tasks.get(t);o&&(o.progress||(o.progress={toolCalls:0,lastUpdate:new Date}),Object.assign(o.progress,n,{lastUpdate:new Date}),this.persistTask(o))}markForNotification(t){let n=this.notifications.get(t.parentSessionId)??[];n.push(t),this.notifications.set(t.parentSessionId,n)}getPendingNotifications(t){return this.notifications.get(t)??[]}clearNotifications(t){this.notifications.delete(t)}clearNotificationsForTask(t){for(let[n,o]of this.notifications.entries()){let r=o.filter(i=>i.id!==t);r.length===0?this.notifications.delete(n):this.notifications.set(n,r)}}removeTask(t){let n=this.tasks.get(t);n?.concurrencyKey&&this.concurrencyManager.release(n.concurrencyKey),this.clearNotificationsForTask(t),this.unpersistTask(t),this.tasks.delete(t)}formatDuration(t,n){let o=(n??new Date).getTime()-t.getTime(),r=Math.floor(o/1e3),i=Math.floor(r/60),s=Math.floor(i/60);return s>0?`${s}h ${i%60}m ${r%60}s`:i>0?`${i}m ${r%60}s`:`${r}s`}getStatusSummary(){let t=this.getRunningTasks(),n=this.getAllTasks();if(n.length===0)return"No background tasks.";let o=[`Background Tasks: ${t.length} running, ${n.length} total`,""];for(let r of n){let i=this.formatDuration(r.startedAt,r.completedAt),s=r.status.toUpperCase(),c=r.progress?` (${r.progress.toolCalls} tools)`:"";o.push(` [${s}] ${r.description} - ${i}${c}`),r.error&&o.push(` Error: ${r.error}`)}return o.join(`
|
|
1430
|
+
`)}cleanup(){this.stopPruning(),this.tasks.clear(),this.notifications.clear()}},Sr;function Tr(e){return Sr||(Sr=new Dn(e)),Sr}function og(e){let t=e.status.toUpperCase(),n=rg(e.startedAt,e.completedAt),r=[`${e.status==="completed"?"\u2713":e.status==="error"?"\u2717":"\u25CB"} [${t}] ${e.description}`,` Agent: ${e.agent}`,` Duration: ${n}`];if(e.progress?.toolCalls&&r.push(` Tool calls: ${e.progress.toolCalls}`),e.result){let i=e.result.substring(0,200),s=e.result.length>200?"...":"";r.push(` Result: ${i}${s}`)}return e.error&&r.push(` Error: ${e.error}`),r.join(`
|
|
1431
|
+
`)}function rg(e,t){let n=(t??new Date).getTime()-e.getTime(),o=Math.floor(n/1e3),r=Math.floor(o/60),i=Math.floor(r/60);return i>0?`${i}h ${r%60}m ${o%60}s`:r>0?`${r}m ${o%60}s`:`${o}s`}function ig(e){if(e.length===0)return"";let t=e.length===1?`
|
|
767
1432
|
[BACKGROUND TASK COMPLETED]
|
|
768
1433
|
`:`
|
|
769
1434
|
[${e.length} BACKGROUND TASKS COMPLETED]
|
|
770
|
-
`,n=e.map(o=>
|
|
1435
|
+
`,n=e.map(o=>og(o)).join(`
|
|
771
1436
|
|
|
772
1437
|
`);return`${t}
|
|
773
1438
|
${n}
|
|
774
|
-
`}function
|
|
1439
|
+
`}function sg(e,t,n){let o=t.getPendingNotifications(e);if(o.length===0)return{hasNotifications:!1,tasks:[]};let i=(n?.formatNotification??ig)(o);return{hasNotifications:!0,tasks:o,message:i}}function Ql(e,t){let n=e.sessionId;if(!n)return{continue:!0};let o=Tr(),r=sg(n,o,t);return r.hasNotifications?((t?.autoClear??!0)&&o.clearNotifications(n),{continue:!0,message:r.message,notificationCount:r.tasks.length}):{continue:!0}}function Zl(){v({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 Ql(t);return{continue:n.continue,hookSpecificOutput:n.message?{hookEventName:"Notification",additionalContext:n.message}:void 0}}})}var _r=null,wr=!1;async function ag(){if(!wr)try{let{encode:e}=await import("gpt-tokenizer");_r=e,wr=!0}catch{wr=!0}}function cg(e){return Math.ceil(e.length/4)}async function Xe(e){if(!e||e.length===0)return 0;await ag();try{if(_r)return _r(e).length}catch{}return cg(e)}async function eu(e){if(!e)return 0;if(typeof e=="object"&&e!==null){let n=e;if("content"in n&&typeof n.content=="string")return Xe(n.content);if("output"in n&&typeof n.output=="string")return Xe(n.output);if("text"in n&&typeof n.text=="string")return Xe(n.text);if("result"in n&&typeof n.result=="string")return Xe(n.result)}let t=typeof e=="string"?e:JSON.stringify(e);return Xe(t)}var Or=[{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 tu(e,t,n,o=Or){let r=o.find(c=>new RegExp(c.model_pattern,"i").test(n));if(!r){let c=o.find(u=>u.model_pattern==="claude-sonnet")||{input_per_million:3,output_per_million:15,effective_date:"2025-01-01"},a=e/1e6*c.input_per_million,l=t/1e6*c.output_per_million;return{inputCost:a,outputCost:l,totalCost:a+l,pricingVersion:c.effective_date}}let i=e/1e6*r.input_per_million,s=t/1e6*r.output_per_million;return{inputCost:i,outputCost:s,totalCost:i+s,pricingVersion:r.effective_date}}var ou=require("crypto");function lg(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 ug(e){if(e.message?.model){let{providerId:t,modelId:n}=e.message.model;if(t&&n)return`${t}/${n}`;if(n)return n}}function nu(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 ru(){v({name:"learningCapturePrompt",event:"UserPromptSubmit",priority:110,handler:async e=>{try{if(!e.directory)return{continue:!0};let t=lg(e);if(!t)return{continue:!0};let n=await Xe(t),o=te(e.directory,e.sessionId);nu(o);let r=ug(e);r&&o.token_budget&&(o.token_budget.current_model=r),o.token_budget&&(o.token_budget.input_tokens+=n,o.token_budget.current_usage+=n,J(e.directory,o))}catch(t){console.error("[Olympus Learning Capture] Error in prompt handler:",t)}return{continue:!0}}}),v({name:"learningCaptureTool",event:"PostToolUse",priority:70,handler:async e=>{try{if(!e.directory||!e.toolName)return{continue:!0};let t=e.toolOutput?await eu(e.toolOutput):0,n=te(e.directory,e.sessionId);nu(n),n.token_budget&&(n.token_budget.output_tokens+=t,n.token_budget.current_usage+=t,J(e.directory,n))}catch(t){console.error("[Olympus Learning Capture] Error in tool use handler:",t)}return{continue:!0}}}),v({name:"learningCaptureStop",event:"Stop",priority:90,handler:async e=>{try{if(!e.directory)return{continue:!0};let t=te(e.directory,e.sessionId);if(!t.token_budget)return{continue:!0};let n=t.token_budget.current_usage,o=t.token_budget.input_tokens||0,r=t.token_budget.output_tokens||0;if(n===0)return{continue:!0};let i=t.token_budget.current_model||"unknown",s={input_tokens:o,output_tokens:r,total_tokens:n,estimated:!0,model:i},c={input_cost:0,output_cost:0,total_cost:0,pricing_version:"2025-01-01"};try{let l=tu(o,r,i);c.input_cost=l.inputCost,c.output_cost=l.outputCost,c.total_cost=l.totalCost,c.pricing_version=l.pricingVersion}catch{}let a={id:(0,ou.randomUUID)(),timestamp:new Date().toISOString(),session_id:t.session_id,project_path:e.directory,event_type:"success",user_message:"Session completed",feedback_category:"praise",confidence:.5,token_usage:s,cost_estimate:c,agent_used:t.pending_completion?.agent_used,original_task:t.pending_completion?.task_description};if(Pe(a),t.pending_completion?.agent_used){let l=li();ui(t.pending_completion.agent_used,l)}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,J(e.directory,t)}catch(t){console.error("[Olympus Learning Capture] Error in stop handler:",t)}return{continue:!0}}})}function iu(){v({name:"budgetWarning",event:"PostToolUse",priority:90,handler:e=>{if(!e.directory)return{continue:!0};try{let t=te(e.directory,e.sessionId),n=0;if(e.toolOutput&&typeof e.toolOutput=="object"){let o=e.toolOutput;o.token_usage&&typeof o.token_usage=="object"&&(n=o.token_usage.total_tokens??0)}if(n>0&&Ei(t,n),Ti(t)){let o=t.token_budget,r=(o.current_usage/1e3).toFixed(1),i=(o.session_baseline/1e3).toFixed(0),s=(o.current_usage/o.session_baseline).toFixed(2);return Si(t),J(e.directory,t),{continue:!0,message:`[TOKEN AWARENESS] Session at ${r}k tokens (${s}x baseline of ${i}k).
|
|
775
1440
|
This is informational - continue if task requires it.
|
|
776
|
-
Consider: delegate to subagent, break into smaller tasks.`}}return
|
|
777
|
-
`;break;case 114:
|
|
778
|
-
`),c++,l=o,
|
|
779
|
-
`+" ".repeat(t)),"\r":new Array(
|
|
780
|
-
`+" ".repeat(t))}," ":{"\n":new Array(
|
|
781
|
-
`+" ".repeat(t)),"\r":new Array(
|
|
782
|
-
`+" ".repeat(t))}};var bt;(function(e){e.DEFAULT={allowTrailingComma:!1}})(bt||(bt={}));function Ci(e,t=[],n=bt.DEFAULT){let o=null,r=[],s=[];function i(a){Array.isArray(r)?r.push(a):o!==null&&(r[o]=a)}return xi(e,{onObjectBegin:()=>{let a={};i(a),s.push(r),r=a,o=null},onObjectProperty:a=>{o=a},onObjectEnd:()=>{r=s.pop()},onArrayBegin:()=>{let a=[];i(a),s.push(r),r=a,o=null},onArrayEnd:()=>{r=s.pop()},onLiteralValue:i,onError:(a,l,u)=>{t.push({error:a,offset:l,length:u})}},n),r[0]}function xi(e,t,n=bt.DEFAULT){let o=At(e,!1),r=[],s=0;function i(T){return T?()=>s===0&&T(o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter()):()=>!0}function c(T){return T?b=>s===0&&T(b,o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter()):()=>!0}function a(T){return T?b=>s===0&&T(b,o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter(),()=>r.slice()):()=>!0}function l(T){return T?()=>{s>0?s++:T(o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter(),()=>r.slice())===!1&&(s=1)}:()=>!0}function u(T){return T?()=>{s>0&&s--,s===0&&T(o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter())}:()=>!0}let d=l(t.onObjectBegin),f=a(t.onObjectProperty),E=u(t.onObjectEnd),S=l(t.onArrayBegin),O=u(t.onArrayEnd),R=a(t.onLiteralValue),h=c(t.onSeparator),_=i(t.onComment),p=c(t.onError),I=n&&n.disallowComments,N=n&&n.allowTrailingComma;function y(){for(;;){let T=o.scan();switch(o.getTokenError()){case 4:m(14);break;case 5:m(15);break;case 3:m(13);break;case 1:I||m(11);break;case 2:m(12);break;case 6:m(16);break}switch(T){case 12:case 13:I?m(10):_();break;case 16:m(1);break;case 15:case 14:break;default:return T}}}function m(T,b=[],eo=[]){if(p(T),b.length+eo.length>0){let qe=o.getToken();for(;qe!==17;){if(b.indexOf(qe)!==-1){y();break}else if(eo.indexOf(qe)!==-1)break;qe=y()}}}function ge(T){let b=o.getTokenValue();return T?R(b):(f(b),r.push(b)),y(),!0}function Ne(){switch(o.getToken()){case 11:let T=o.getTokenValue(),b=Number(T);isNaN(b)&&(m(2),b=0),R(b);break;case 7:R(null);break;case 8:R(!0);break;case 9:R(!1);break;default:return!1}return y(),!0}function Gi(){return o.getToken()!==10?(m(3,[],[2,5]),!1):(ge(!1),o.getToken()===6?(h(":"),y(),Ct()||m(4,[],[2,5])):m(5,[],[2,5]),r.pop(),!0)}function Bi(){d(),y();let T=!1;for(;o.getToken()!==2&&o.getToken()!==17;){if(o.getToken()===5){if(T||m(4,[],[]),h(","),y(),o.getToken()===2&&N)break}else T&&m(6,[],[]);Gi()||m(4,[],[2,5]),T=!0}return E(),o.getToken()!==2?m(7,[2],[]):y(),!0}function Yi(){S(),y();let T=!0,b=!1;for(;o.getToken()!==4&&o.getToken()!==17;){if(o.getToken()===5){if(b||m(4,[],[]),h(","),y(),o.getToken()===4&&N)break}else b&&m(6,[],[]);T?(r.push(0),T=!1):r[r.length-1]++,Ct()||m(4,[],[4,5]),b=!0}return O(),T||r.pop(),o.getToken()!==4?m(8,[4],[]):y(),!0}function Ct(){switch(o.getToken()){case 3:return Yi();case 1:return Bi();case 10:return ge(!0);default:return Ne()}}return y(),o.getToken()===17?n.allowEmptyContent?!0:(m(4,[],[]),!1):Ct()?(o.getToken()!==17&&m(9,[],[]),!0):(m(4,[],[]),!1)}var Pi;(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"})(Pi||(Pi={}));var Li;(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"})(Li||(Li={}));var Mi=Ci;var Di;(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"})(Di||(Di={}));var Ll={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:Qn,customPricing:[]}};function Dl(){let e=process.env.XDG_CONFIG_HOME??(0,Ke.join)((0,ji.homedir)(),".config");return{user:(0,Ke.join)(e,"claude-olympus","config.jsonc"),project:(0,Ke.join)(process.cwd(),".claude","olympus.jsonc")}}function Ui(e){if(!(0,vt.existsSync)(e))return null;try{let t=(0,vt.readFileSync)(e,"utf-8"),n=[],o=Mi(t,n,{allowTrailingComma:!0,allowEmptyContent:!0});return n.length>0&&console.warn(`Warning: Parse errors in ${e}:`,n),o}catch(t){return console.error(`Error loading config from ${e}:`,t),null}}function wt(e,t){let n={...e};for(let o of Object.keys(t)){let r=t[o],s=n[o];r!==void 0&&typeof r=="object"&&r!==null&&!Array.isArray(r)&&typeof s=="object"&&s!==null&&!Array.isArray(s)?n[o]=wt(s,r):r!==void 0&&(n[o]=r)}return n}function Ml(){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 Fi(){let e=Dl(),t={...Ll},n=Ui(e.user);n&&(t=wt(t,n));let o=Ui(e.project);o&&(t=wt(t,o));let r=Ml();return t=wt(t,r),t}function Ul(e){let t=e.hooks;return t&&typeof t.timeoutMs=="number"?t.timeoutMs:100}function jl(e,t){let n=e.hooks;if(n&&typeof n.enabled=="boolean"&&!n.enabled)return!1;if(n&&t in n){let o=n[t];if(typeof o=="object"&&o!==null){let r=o.enabled;if(typeof r=="boolean")return r}}return!0}async function Fl(e,t){return Promise.race([Promise.resolve(e()),new Promise(n=>setTimeout(()=>n(null),t))])}function $l(e,t){return!e||!t?!0:(typeof e=="string"?new RegExp(e,"i"):e).test(t)}async function $i(e,t){let n=Fi(),o=no(e),r=Ul(n),s=!0,i=[],c,a=t.toolInput,l=t.messages;for(let u of o)if(jl(n,u.name)&&$l(u.matcher,t.toolName))try{let d=await Fl(()=>u.handler({...t,toolInput:a,messages:l}),r);if(d===null){console.error(`[hook-router] ${u.name} timed out after ${r}ms`);continue}d.continue||(s=!1,c=d.stopReason),d.message&&i.push(d.message),d.hookSpecificOutput?.additionalContext&&i.push(d.hookSpecificOutput.additionalContext),d.modifiedInput!==void 0&&(a=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(`
|
|
1441
|
+
Consider: delegate to subagent, break into smaller tasks.`}}return J(e.directory,t),{continue:!0}}catch(t){return console.error("[Olympus Learning] Budget warning error:",t),{continue:!0}}}})}var su=!1;function au(){su||(La(),Ba(),uc(),el(),xl(),zl(),Zl(),ru(),iu(),su=!0)}var Un=require("fs"),hu=require("os"),Fn=require("path");function Ln(e,t=!1){let n=e.length,o=0,r="",i=0,s=16,c=0,a=0,l=0,u=0,d=0;function f(k,A){let D=0,R=0;for(;D<k||!A;){let w=e.charCodeAt(o);if(w>=48&&w<=57)R=R*16+w-48;else if(w>=65&&w<=70)R=R*16+w-65+10;else if(w>=97&&w<=102)R=R*16+w-97+10;else break;o++,D++}return D<k&&(R=-1),R}function g(k){o=k,r="",i=0,s=16,d=0}function m(){let k=o;if(e.charCodeAt(o)===48)o++;else for(o++;o<e.length&&ht(e.charCodeAt(o));)o++;if(o<e.length&&e.charCodeAt(o)===46)if(o++,o<e.length&&ht(e.charCodeAt(o)))for(o++;o<e.length&&ht(e.charCodeAt(o));)o++;else return d=3,e.substring(k,o);let A=o;if(o<e.length&&(e.charCodeAt(o)===69||e.charCodeAt(o)===101))if(o++,(o<e.length&&e.charCodeAt(o)===43||e.charCodeAt(o)===45)&&o++,o<e.length&&ht(e.charCodeAt(o))){for(o++;o<e.length&&ht(e.charCodeAt(o));)o++;A=o}else d=3;return e.substring(k,A)}function p(){let k="",A=o;for(;;){if(o>=n){k+=e.substring(A,o),d=2;break}let D=e.charCodeAt(o);if(D===34){k+=e.substring(A,o),o++;break}if(D===92){if(k+=e.substring(A,o),o++,o>=n){d=2;break}switch(e.charCodeAt(o++)){case 34:k+='"';break;case 92:k+="\\";break;case 47:k+="/";break;case 98:k+="\b";break;case 102:k+="\f";break;case 110:k+=`
|
|
1442
|
+
`;break;case 114:k+="\r";break;case 116:k+=" ";break;case 117:let w=f(4,!0);w>=0?k+=String.fromCharCode(w):d=4;break;default:d=5}A=o;continue}if(D>=0&&D<=31)if(Wt(D)){k+=e.substring(A,o),d=2;break}else d=6;o++}return k}function h(){if(r="",d=0,i=o,a=c,u=l,o>=n)return i=n,s=17;let k=e.charCodeAt(o);if(vr(k)){do o++,r+=String.fromCharCode(k),k=e.charCodeAt(o);while(vr(k));return s=15}if(Wt(k))return o++,r+=String.fromCharCode(k),k===13&&e.charCodeAt(o)===10&&(o++,r+=`
|
|
1443
|
+
`),c++,l=o,s=14;switch(k){case 123:return o++,s=1;case 125:return o++,s=2;case 91:return o++,s=3;case 93:return o++,s=4;case 58:return o++,s=6;case 44:return o++,s=5;case 34:return o++,r=p(),s=10;case 47:let A=o-1;if(e.charCodeAt(o+1)===47){for(o+=2;o<n&&!Wt(e.charCodeAt(o));)o++;return r=e.substring(A,o),s=12}if(e.charCodeAt(o+1)===42){o+=2;let D=n-1,R=!1;for(;o<D;){let w=e.charCodeAt(o);if(w===42&&e.charCodeAt(o+1)===47){o+=2,R=!0;break}o++,Wt(w)&&(w===13&&e.charCodeAt(o)===10&&o++,c++,l=o)}return R||(o++,d=1),r=e.substring(A,o),s=13}return r+=String.fromCharCode(k),o++,s=16;case 45:if(r+=String.fromCharCode(k),o++,o===n||!ht(e.charCodeAt(o)))return s=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return r+=m(),s=11;default:for(;o<n&&y(k);)o++,k=e.charCodeAt(o);if(i!==o){switch(r=e.substring(i,o),r){case"true":return s=8;case"false":return s=9;case"null":return s=7}return s=16}return r+=String.fromCharCode(k),o++,s=16}}function y(k){if(vr(k)||Wt(k))return!1;switch(k){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}function T(){let k;do k=h();while(k>=12&&k<=15);return k}return{setPosition:g,getPosition:()=>o,scan:t?T:h,getToken:()=>s,getTokenValue:()=>r,getTokenOffset:()=>i,getTokenLength:()=>o-i,getTokenStartLine:()=>a,getTokenStartCharacter:()=>i-u,getTokenError:()=>d}}function vr(e){return e===32||e===9}function Wt(e){return e===10||e===13}function ht(e){return e>=48&&e<=57}var cu;(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"})(cu||(cu={}));var fg=new Array(20).fill(0).map((e,t)=>" ".repeat(t)),kt=200,pg={" ":{"\n":new Array(kt).fill(0).map((e,t)=>`
|
|
1444
|
+
`+" ".repeat(t)),"\r":new Array(kt).fill(0).map((e,t)=>"\r"+" ".repeat(t)),"\r\n":new Array(kt).fill(0).map((e,t)=>`\r
|
|
1445
|
+
`+" ".repeat(t))}," ":{"\n":new Array(kt).fill(0).map((e,t)=>`
|
|
1446
|
+
`+" ".repeat(t)),"\r":new Array(kt).fill(0).map((e,t)=>"\r"+" ".repeat(t)),"\r\n":new Array(kt).fill(0).map((e,t)=>`\r
|
|
1447
|
+
`+" ".repeat(t))}};var Mn;(function(e){e.DEFAULT={allowTrailingComma:!1}})(Mn||(Mn={}));function lu(e,t=[],n=Mn.DEFAULT){let o=null,r=[],i=[];function s(a){Array.isArray(r)?r.push(a):o!==null&&(r[o]=a)}return uu(e,{onObjectBegin:()=>{let a={};s(a),i.push(r),r=a,o=null},onObjectProperty:a=>{o=a},onObjectEnd:()=>{r=i.pop()},onArrayBegin:()=>{let a=[];s(a),i.push(r),r=a,o=null},onArrayEnd:()=>{r=i.pop()},onLiteralValue:s,onError:(a,l,u)=>{t.push({error:a,offset:l,length:u})}},n),r[0]}function uu(e,t,n=Mn.DEFAULT){let o=Ln(e,!1),r=[],i=0;function s(E){return E?()=>i===0&&E(o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter()):()=>!0}function c(E){return E?_=>i===0&&E(_,o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter()):()=>!0}function a(E){return E?_=>i===0&&E(_,o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter(),()=>r.slice()):()=>!0}function l(E){return E?()=>{i>0?i++:E(o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter(),()=>r.slice())===!1&&(i=1)}:()=>!0}function u(E){return E?()=>{i>0&&i--,i===0&&E(o.getTokenOffset(),o.getTokenLength(),o.getTokenStartLine(),o.getTokenStartCharacter())}:()=>!0}let d=l(t.onObjectBegin),f=a(t.onObjectProperty),g=u(t.onObjectEnd),m=l(t.onArrayBegin),p=u(t.onArrayEnd),h=a(t.onLiteralValue),y=c(t.onSeparator),T=s(t.onComment),k=c(t.onError),A=n&&n.disallowComments,D=n&&n.allowTrailingComma;function R(){for(;;){let E=o.scan();switch(o.getTokenError()){case 4:w(14);break;case 5:w(15);break;case 3:w(13);break;case 1:A||w(11);break;case 2:w(12);break;case 6:w(16);break}switch(E){case 12:case 13:A?w(10):T();break;case 16:w(1);break;case 15:case 14:break;default:return E}}}function w(E,_=[],P=[]){if(k(E),_.length+P.length>0){let C=o.getToken();for(;C!==17;){if(_.indexOf(C)!==-1){R();break}else if(P.indexOf(C)!==-1)break;C=R()}}}function ke(E){let _=o.getTokenValue();return E?h(_):(f(_),r.push(_)),R(),!0}function S(){switch(o.getToken()){case 11:let E=o.getTokenValue(),_=Number(E);isNaN(_)&&(w(2),_=0),h(_);break;case 7:h(null);break;case 8:h(!0);break;case 9:h(!1);break;default:return!1}return R(),!0}function b(){return o.getToken()!==10?(w(3,[],[2,5]),!1):(ke(!1),o.getToken()===6?(y(":"),R(),M()||w(4,[],[2,5])):w(5,[],[2,5]),r.pop(),!0)}function I(){d(),R();let E=!1;for(;o.getToken()!==2&&o.getToken()!==17;){if(o.getToken()===5){if(E||w(4,[],[]),y(","),R(),o.getToken()===2&&D)break}else E&&w(6,[],[]);b()||w(4,[],[2,5]),E=!0}return g(),o.getToken()!==2?w(7,[2],[]):R(),!0}function F(){m(),R();let E=!0,_=!1;for(;o.getToken()!==4&&o.getToken()!==17;){if(o.getToken()===5){if(_||w(4,[],[]),y(","),R(),o.getToken()===4&&D)break}else _&&w(6,[],[]);E?(r.push(0),E=!1):r[r.length-1]++,M()||w(4,[],[4,5]),_=!0}return p(),E||r.pop(),o.getToken()!==4?w(8,[4],[]):R(),!0}function M(){switch(o.getToken()){case 3:return F();case 1:return I();case 10:return ke(!0);default:return S()}}return R(),o.getToken()===17?n.allowEmptyContent?!0:(w(4,[],[]),!1):M()?(o.getToken()!==17&&w(9,[],[]),!0):(w(4,[],[]),!1)}var du;(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"})(du||(du={}));var fu;(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"})(fu||(fu={}));var mu=lu;var pu;(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"})(pu||(pu={}));var Tg={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:Or,customPricing:[]}};function wg(){return{user:(0,Fn.join)((0,hu.homedir)(),".claude","olympus","config.jsonc"),project:(0,Fn.join)(process.cwd(),".claude","olympus.jsonc")}}function gu(e){if(!(0,Un.existsSync)(e))return null;try{let t=(0,Un.readFileSync)(e,"utf-8"),n=[],o=mu(t,n,{allowTrailingComma:!0,allowEmptyContent:!0});return n.length>0&&console.warn(`Warning: Parse errors in ${e}:`,n),o}catch(t){return console.error(`Error loading config from ${e}:`,t),null}}function $n(e,t){let n={...e};for(let o of Object.keys(t)){let r=t[o],i=n[o];r!==void 0&&typeof r=="object"&&r!==null&&!Array.isArray(r)&&typeof i=="object"&&i!==null&&!Array.isArray(i)?n[o]=$n(i,r):r!==void 0&&(n[o]=r)}return n}function _g(){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 ku(){let e=wg(),t={...Tg},n=gu(e.user);n&&(t=$n(t,n));let o=gu(e.project);o&&(t=$n(t,o));let r=_g();return t=$n(t,r),t}function Og(e){let t=e.hooks;return t&&typeof t.timeoutMs=="number"?t.timeoutMs:100}function vg(e,t){let n=e.hooks;if(n&&typeof n.enabled=="boolean"&&!n.enabled)return!1;if(n&&t in n){let o=n[t];if(typeof o=="object"&&o!==null){let r=o.enabled;if(typeof r=="boolean")return r}}return!0}async function Rg(e,t){return Promise.race([Promise.resolve(e()),new Promise(n=>setTimeout(()=>n(null),t))])}function Ig(e,t){return!e||!t?!0:(typeof e=="string"?new RegExp(e,"i"):e).test(t)}async function yu(e,t){let n=ku(),o=Ir(e),r=Og(n),i=!0,s=[],c,a=t.toolInput,l=t.messages;for(let u of o)if(vg(n,u.name)&&Ig(u.matcher,t.toolName))try{let d=await Rg(()=>u.handler({...t,toolInput:a,messages:l}),r);if(d===null){console.error(`[hook-router] ${u.name} timed out after ${r}ms`);continue}d.continue||(i=!1,c=d.stopReason),d.message&&s.push(d.message),d.hookSpecificOutput?.additionalContext&&s.push(d.hookSpecificOutput.additionalContext),d.modifiedInput!==void 0&&(a=d.modifiedInput),d.modifiedMessages!==void 0&&(l=d.modifiedMessages)}catch(d){console.error(`[hook-router] ${u.name} error:`,d)}return{continue:i,message:s.length>0?s.join(`
|
|
783
1448
|
|
|
784
1449
|
---
|
|
785
1450
|
|
|
786
|
-
`):void 0,stopReason:c,modifiedInput:a!==t.toolInput?a:void 0,modifiedMessages:l!==t.messages?l:void 0}}
|
|
1451
|
+
`):void 0,stopReason:c,modifiedInput:a!==t.toolInput?a:void 0,modifiedMessages:l!==t.messages?l:void 0}}au();async function Ag(){return process.stdin.isTTY?"{}":new Promise(e=>{let t=[],n=!1,o=setTimeout(()=>{process.stdin.pause(),process.stdin.destroy(),e(n?Buffer.concat(t).toString("utf-8"):"{}")},1e3);process.stdin.on("data",r=>{n=!0,t.push(r)}),process.stdin.on("end",()=>{clearTimeout(o),e(n?Buffer.concat(t).toString("utf-8"):"{}")}),process.stdin.on("error",()=>{clearTimeout(o),e("{}")}),process.stdin.resume()})}async function Eu(){let t=process.argv.slice(2).find(s=>s.startsWith("--event="));t||(console.error("Usage: node olympus-hooks.mjs --event=<event-type>"),process.exit(1));let n=t.split("=")[1],o=await Ag(),r;try{r=JSON.parse(o)}catch{r={}}let i=await yu(n,r);console.log(JSON.stringify(i)),process.exit(0)}var jn=process.argv[1]||"",bg=jn.endsWith("entry.ts")||jn.endsWith("entry.js")||jn.endsWith("olympus-hooks.mjs")||jn.includes("olympus-hooks");bg&&Eu().catch(e=>{console.error("[olympus-hooks] Fatal error:",e),process.exit(1)});0&&(module.exports={main});
|