prjct-cli 1.50.0 → 1.50.2
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/CHANGELOG.md +12 -0
- package/dist/bin/prjct-core.mjs +4 -4
- package/dist/daemon/entry.mjs +3 -3
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [1.50.2] - 2026-03-03
|
|
4
|
+
|
|
5
|
+
### Bug Fixes
|
|
6
|
+
|
|
7
|
+
- guard against undefined decision.contexts in pattern-store (#230)
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
## [1.50.1] - 2026-03-02
|
|
11
|
+
|
|
12
|
+
### Fixed
|
|
13
|
+
- Fix crash in pattern-store when decision.contexts is undefined (legacy data)
|
|
14
|
+
|
|
3
15
|
## [1.50.0] - 2026-02-27
|
|
4
16
|
|
|
5
17
|
### Features
|
package/dist/bin/prjct-core.mjs
CHANGED
|
@@ -363,7 +363,7 @@ ${ce.dim(`...${o} more lines`)}`}function PS(n){let e=ii();if(Kn==="silent")retu
|
|
|
363
363
|
`),s=Math.max(n.length,...t.map(o=>o.length)),r="\u2500".repeat(s+2);console.log(ce.dim(`\u250C${r}\u2510`)),console.log(`${ce.dim("\u2502")} ${ce.bold(n.padEnd(s))} ${ce.dim("\u2502")}`),console.log(ce.dim(`\u251C${r}\u2524`));for(let o of t)console.log(`${ce.dim("\u2502")} ${o.padEnd(s)} ${ce.dim("\u2502")}`);return console.log(ce.dim(`\u2514${r}\u2518`)),this},section(n){return this.stop(),Pt?this:(console.log(`
|
|
364
364
|
${ce.bold(n)}`),console.log(ce.dim("\u2500".repeat(n.length))),this)},stop(){return qn&&(clearInterval(qn),qn=null,ES()),this},step(n,e,t){if(Pt)return this;this.stop();let s=ce.dim(`[${n}/${e}]`);return process.stdout.isTTY?(qn=setInterval(()=>{process.stdout.write(`\r${Xt.cli.spin(Rc++,`${s} ${Bt(t,Vt.STEP_MSG)}`)}`)},jc),this):(process.stdout.write(`${Xt.cli.spin(0,`${s} ${Bt(t,Vt.STEP_MSG)}`)}
|
|
365
365
|
`),this)},progress(n,e,t){if(Pt)return this;this.stop();let s=Math.round(n/e*100),r=Math.round(s/10),o=10-r,i=ce.cyan("\u2588".repeat(r))+ce.dim("\u2591".repeat(o)),a=t?` ${Bt(t,Vt.PROGRESS_TEXT)}`:"";return process.stdout.isTTY?(qn=setInterval(()=>{process.stdout.write(`\r${Xt.cli.spin(Rc++,`[${i}] ${s}%${a}`)}`)},jc),this):(process.stdout.write(`${Xt.cli.spin(0,`[${i}] ${s}%${a}`)}
|
|
366
|
-
`),this)}},f=xS});var Vp={};Ce(Vp,{default:()=>RS,sessionTracker:()=>Us});var Gp,Wp,Ac,Us,RS,ai=w(()=>{"use strict";zr();de();ln();ae();Gp=50,Wp=200,Ac=class{static{l(this,"SessionTracker")}async read(e){try{return j.getDoc(e,"session-tracker")??this.getDefault()}catch{return this.getDefault()}}async write(e,t){j.setDoc(e,"session-tracker",t)}getDefault(){return{current:null,config:{idleTimeoutMs:18e5}}}isExpired(e,t){return Ms(e.lastActivity,t)}async touch(e){let t=await this.read(e),s=T();if(t.current&&!this.isExpired(t.current,t.config.idleTimeoutMs))return t.current.lastActivity=s,await this.write(e,t),t.current;let r={id:crypto.randomUUID(),projectId:e,status:"active",createdAt:s,lastActivity:s,commands:[],files:[]};return t.current=r,await this.write(e,t),r}async trackCommand(e,t,s){let r=await this.read(e);if(!r.current)return;let o=T();r.current.lastActivity=o,r.current.commands.push({command:t,timestamp:o,durationMs:s}),r.current.commands.length>Gp&&(r.current.commands=r.current.commands.slice(-Gp)),await this.write(e,r)}async trackFile(e,t,s){let r=await this.read(e);if(!r.current)return;let o=T();r.current.lastActivity=o,r.current.files.push({path:t,operation:s,timestamp:o}),r.current.files.length>Wp&&(r.current.files=r.current.files.slice(-Wp)),await this.write(e,r)}async getInfo(e){let t=await this.read(e);if(!t.current||this.isExpired(t.current,t.config.idleTimeoutMs))return{active:!1,id:null,duration:null,idleSince:null,idleMs:0,expiresIn:null,commandCount:0,commands:[],filesRead:0,filesWritten:0};let s=t.current,r=Date.now(),o=new Date(s.createdAt).getTime(),i=new Date(s.lastActivity).getTime(),a=r-i,c=t.config.idleTimeoutMs,u=Math.max(0,c-a),p=s.commands.map(g=>g.command),m=new Set(s.files.filter(g=>g.operation==="read").map(g=>g.path)).size,d=new Set(s.files.filter(g=>g.operation==="write").map(g=>g.path)).size;return{active:!0,id:s.id,duration:Rt(r-o),idleSince:s.lastActivity,idleMs:a,expiresIn:Rt(u),commandCount:s.commands.length,commands:p,filesRead:m,filesWritten:d}}async expire(e){let t=await this.read(e);t.current&&(t.current.status="expired",t.current=null,await this.write(e,t))}async expireIfStale(e){let t=await this.read(e);return t.current&&this.isExpired(t.current,t.config.idleTimeoutMs)?(t.current=null,await this.write(e,t),!0):!1}},Us=new Ac,RS=Us});var zp={};Ce(zp,{default:()=>kn,performanceTracker:()=>Bp});var AS,Dc,Bp,kn,ci=w(()=>{"use strict";de();AS=BigInt(300*1e9),Dc=class{static{l(this,"PerformanceTracker")}marks=new Map;markStart(e){this.pruneStaleMarks(),this.marks.set(e,process.hrtime.bigint())}markEnd(e){let t=this.marks.get(e);if(t===void 0)return null;let s=process.hrtime.bigint();return this.marks.delete(e),Number(s-t)/1e6}pruneStaleMarks(){if(this.marks.size<10)return;let e=process.hrtime.bigint();for(let[t,s]of this.marks)e-s>AS&&this.marks.delete(t)}recordTiming(e,t,s,r){H.appendEvent(e,`perf.${t}`,{metric:t,value:Math.round(s*100)/100,unit:"ms",context:r})}snapshotMemory(){let e=process.memoryUsage();return{heapUsed:e.heapUsed,heapTotal:e.heapTotal,rss:e.rss,external:e.external}}recordMemory(e,t){let s=this.snapshotMemory(),r=[{metric:"heap_used",value:s.heapUsed,unit:"bytes"},{metric:"heap_total",value:s.heapTotal,unit:"bytes"},{metric:"rss",value:s.rss,unit:"bytes"},{metric:"external_memory",value:s.external,unit:"bytes"}];for(let o of r)H.appendEvent(e,`perf.${o.metric}`,{metric:o.metric,value:o.value,unit:o.unit,context:t});return s}recordContextCorrectness(e,t){H.appendEvent(e,"perf.context_correctness",{metric:"context_correctness",...t})}recordSubtaskHandoff(e,t){H.appendEvent(e,"perf.subtask_handoff",{metric:"subtask_handoff",...t})}getMetrics(e,t){t||(t=new Date,t.setDate(t.getDate()-7));let s=t.toISOString();return H.query(e,"SELECT data, timestamp FROM events WHERE type LIKE ? AND timestamp >= ? ORDER BY id DESC","perf.%",s).map(o=>({...JSON.parse(o.data),timestamp:o.timestamp}))}getReport(e,t=7){let s=new Date;s.setDate(s.getDate()-t),s.setHours(0,0,0,0);let r=this.getMetrics(e,s),o={period:`${t}d`},i=r.filter(d=>"metric"in d&&d.metric==="startup_time");if(i.length>0){let d=i.map(g=>g.value);o.startup={avg:Math.round(d.reduce((g,h)=>g+h,0)/d.length),min:Math.min(...d),max:Math.max(...d),count:d.length,unit:"ms"}}let a=r.filter(d=>"metric"in d&&d.metric==="heap_used"),c=r.filter(d=>"metric"in d&&d.metric==="rss");if(a.length>0){let d=l(k=>Math.round(k/1048576*10)/10,"toMB"),g=a.map(k=>k.value),h=c.map(k=>k.value);o.memory={avgHeapMB:d(g.reduce((k,S)=>k+S,0)/g.length),peakHeapMB:d(Math.max(...g)),avgRssMB:h.length>0?d(h.reduce((k,S)=>k+S,0)/h.length):0}}let u=r.filter(d=>"metric"in d&&d.metric==="context_correctness");if(u.length>0){let d=u.filter(g=>g.receivedSync).length;o.contextCorrectness={total:u.length,receivedSync:d,rate:Math.round(d/u.length*100)}}let p=r.filter(d=>"metric"in d&&d.metric==="subtask_handoff");if(p.length>0){let d=p.filter(g=>g.outputPopulated).length;o.subtaskHandoff={total:p.length,outputPopulated:d,rate:Math.round(d/p.length*100)}}let m=r.filter(d=>"metric"in d&&d.metric==="command_duration");if(m.length>0){let d={};for(let g of m){let h=g.context?.command||"unknown";d[h]||(d[h]=[]),d[h].push(g.value)}o.commandDurations={};for(let[g,h]of Object.entries(d))o.commandDurations[g]={avg:Math.round(h.reduce((k,S)=>k+S,0)/h.length),min:Math.min(...h),max:Math.max(...h),count:h.length,unit:"ms"}}return o}},Bp=new Dc,kn=Bp});function li(n,e=!1){return e||n>=6?"high":n>=3?"medium":"low"}var V,to=w(()=>{"use strict";V={CODE_STYLE:"code_style",NAMING_CONVENTION:"naming_convention",FILE_STRUCTURE:"file_structure",COMMIT_STYLE:"commit_style",BRANCH_NAMING:"branch_naming",TEST_BEHAVIOR:"test_behavior",SHIP_WORKFLOW:"ship_workflow",TECH_STACK:"tech_stack",ARCHITECTURE:"architecture",DEPENDENCIES:"dependencies",OUTPUT_VERBOSITY:"output_verbosity",CONFIRMATION_LEVEL:"confirmation_level",AGENT_PREFERENCE:"agent_preference"};l(li,"calculateConfidence")});var Sn,so,no,ro=w(()=>{"use strict";de();to();ae();Sn=class{static{l(this,"CachedStore")}_data=null;_loaded=!1;_projectId=null;getSubdirectory(){return null}getStoreKey(){let e=this.getFilename().replace(".json",""),t=this.getSubdirectory();return t?`memory:${t}:${e}`:`memory:${e}`}async load(e){if(this._loaded&&this._data&&this._projectId===e)return this._data;let t=this.getStoreKey(),s=H.getDoc(e,t);return s!==null?(this._data=s,this.afterLoad(this._data)):this._data=this.getDefault(),this._loaded=!0,this._projectId=e,this._data}afterLoad(e){}async save(e){if(!this._data)return;let t=this.getStoreKey();H.setDoc(e,t,this._data)}getData(){return this._data}setData(e){this._data=e}async update(e,t){let s=await this.load(e),r=t(s);return this._data=r,await this.save(e),r}isLoaded(e){return e?this._loaded&&this._projectId===e:this._loaded}reset(){this._data=null,this._loaded=!1,this._projectId=null}},so=class{static{l(this,"SessionStore")}_sessionMemory=new Map;setSession(e,t){this._sessionMemory.set(e,{value:t,timestamp:Date.now()})}getSession(e){return this._sessionMemory.get(e)?.value}clearSession(){this._sessionMemory.clear()}},no=class{static{l(this,"HistoryStore")}async appendHistory(e,t){let s={ts:T(),...t,type:t.type};H.appendEvent(e,`history.${t.type}`,s)}async getRecentHistory(e,t=20){return H.query(e,"SELECT data, timestamp FROM events WHERE type LIKE 'history.%' ORDER BY id DESC LIMIT ?",t).reverse().map(r=>JSON.parse(r.data))}}});var oo,Ic=w(()=>{"use strict";de();to();ae();ro();oo=class n extends Sn{static{l(this,"PatternStore")}static MAX_CONTEXTS=20;static ARCHIVE_AGE_DAYS=90;getFilename(){return"patterns.json"}getDefault(){return{version:1,decisions:{},preferences:{},workflows:{},counters:{}}}afterLoad(e){for(let t of Object.values(e.decisions))t.contexts.length>n.MAX_CONTEXTS&&(t.contexts=t.contexts.slice(-n.MAX_CONTEXTS))}async loadPatterns(e){return this.load(e)}async savePatterns(e){return this.save(e)}async recordDecision(e,t,s,r="",o={}){let i=await this.load(e),a=T();if(!i.decisions[t])i.decisions[t]={value:s,count:1,firstSeen:a,lastSeen:a,confidence:o.userConfirmed?"high":"low",contexts:[r].filter(Boolean),userConfirmed:o.userConfirmed||!1};else{let c=i.decisions[t];c.value===s?(c.count++,c.lastSeen=a,r&&!c.contexts.includes(r)&&(c.contexts.push(r),c.contexts.length>n.MAX_CONTEXTS&&(c.contexts=c.contexts.slice(-n.MAX_CONTEXTS))),o.userConfirmed&&(c.userConfirmed=!0),c.confidence=li(c.count,c.userConfirmed)):(c.value=s,c.count=1,c.lastSeen=a,c.userConfirmed=o.userConfirmed||!1,c.confidence=o.userConfirmed?"high":"low")}await this.save(e)}async confirmDecision(e,t){let r=(await this.load(e)).decisions[t];return r?(r.userConfirmed=!0,r.confidence="high",r.lastSeen=T(),await this.save(e),!0):!1}async getDecision(e,t){let r=(await this.load(e)).decisions[t];return!r||r.confidence==="low"?null:{value:r.value,confidence:r.confidence}}async hasPattern(e,t){return await this.getDecision(e,t)!==null}async recordWorkflow(e,t,s){let r=await this.load(e),o=T();if(!r.workflows[t])r.workflows[t]={...s,count:1,firstSeen:o,lastSeen:o,confidence:"low",userConfirmed:!1};else{let i=r.workflows[t];i.count++,i.lastSeen=o,i.confidence=li(i.count,i.userConfirmed)}await this.save(e)}async confirmWorkflow(e,t){let r=(await this.load(e)).workflows[t];return r?(r.userConfirmed=!0,r.confidence="high",r.lastSeen=T(),await this.save(e),!0):!1}async getWorkflow(e,t){let r=(await this.load(e)).workflows[t];return!r||r.count<3?null:r}async setPreference(e,t,s,r={}){let o=await this.load(e),i=o.preferences[t],a=i?i.observationCount+1:1,c=r.userConfirmed||i?.userConfirmed||!1;o.preferences[t]={value:s,updatedAt:T(),confidence:li(a,c),observationCount:a,userConfirmed:c},await this.save(e)}async confirmPreference(e,t){let r=(await this.load(e)).preferences[t];return r?(r.userConfirmed=!0,r.confidence="high",r.updatedAt=T(),await this.save(e),!0):!1}async getPreference(e,t,s=null){return(await this.load(e)).preferences[t]?.value??s}async getPatternsSummary(e){let t=await this.load(e);return{decisions:Object.keys(t.decisions).length,learnedDecisions:Object.values(t.decisions).filter(s=>s.confidence!=="low").length,workflows:Object.keys(t.workflows).length,preferences:Object.keys(t.preferences).length}}async archiveStaleDecisions(e){let t=await this.load(e),s=Date.now(),r=n.ARCHIVE_AGE_DAYS*24*60*60*1e3,o=[];for(let[a,c]of Object.entries(t.decisions)){let u=new Date(c.lastSeen).getTime();s-u>r&&o.push(a)}if(o.length===0)return 0;let i=H.getDoc(e,"memory:patterns-archive")??{};for(let a of o)i[a]=t.decisions[a],delete t.decisions[a];return H.setDoc(e,"memory:patterns-archive",i),await this.save(e),o.length}}});var bn,$c=w(()=>{"use strict";Gt();to();ae();ro();bn=class extends Sn{static{l(this,"SemanticMemories")}getFilename(){return"memories.json"}getDefault(){return{version:1,memories:[],index:this._createEmptyIndex()}}afterLoad(e){this._normalizeIndex(e)}_createEmptyIndex(){let e=Object.values(V),t={};for(let s of e)t[s]=[];return t}_normalizeIndex(e){let t=Object.values(V);for(let s of t)e.index[s]||(e.index[s]=[])}_coerceTags(e){let t=new Set(Object.values(V));return e.filter(s=>t.has(s))}async loadMemories(e){return this.load(e)}async saveMemories(e){return this.save(e)}async createMemory(e,{title:t,content:s,tags:r=[],userTriggered:o=!1}){let i=await this.load(e),a=this._coerceTags(r),c=T(),u={id:ve(),title:t,content:s,tags:a,userTriggered:o,createdAt:c,updatedAt:c};i.memories.push(u);for(let p of a)i.index[p].push(u.id);return await this.save(e),u.id}async updateMemory(e,t,s){let r=await this.load(e),o=r.memories.findIndex(c=>c.id===t);if(o===-1)return!1;let i=r.memories[o],a=i.tags||[];if(s.title&&(i.title=s.title),s.content&&(i.content=s.content),s.tags){let c=this._coerceTags(s.tags);for(let u of a)r.index[u]=r.index[u].filter(p=>p!==t);for(let u of c)r.index[u].push(t);i.tags=c}return i.updatedAt=T(),await this.save(e),!0}async deleteMemory(e,t){let s=await this.load(e),r=s.memories.findIndex(i=>i.id===t);if(r===-1)return!1;let o=s.memories[r];for(let i of o.tags||[])s.index[i]&&(s.index[i]=s.index[i].filter(a=>a!==t));return s.memories.splice(r,1),await this.save(e),!0}async findByTags(e,t,s=!1){let r=await this.load(e),o=this._coerceTags(t);if(s)return r.memories.filter(i=>o.every(a=>(i.tags||[]).includes(a)));{let i=new Set;for(let a of o){let c=r.index[a];for(let u of c)i.add(u)}return r.memories.filter(a=>i.has(a.id))}}async searchMemories(e,t){let s=await this.load(e),r=t.toLowerCase();return s.memories.filter(o=>o.title.toLowerCase().includes(r)||o.content.toLowerCase().includes(r))}async getRelevantMemories(e,t,s=5){return(await this.load(e)).memories.map(i=>{let a=0,c=this._extractContextTags(t);for(let d of i.tags||[])c.includes(d)&&(a+=10);let p=(Date.now()-new Date(i.updatedAt).getTime())/(1e3*60*60*24);a+=Math.max(0,5-p),i.userTriggered&&(a+=5);let m=this._extractKeywords(t);for(let d of m)i.content.toLowerCase().includes(d)&&(a+=2),i.title.toLowerCase().includes(d)&&(a+=3);return{...i,_score:a}}).filter(i=>i._score>0).sort((i,a)=>a._score-i._score).slice(0,s).map(({_score:i,...a})=>a)}async getRelevantMemoriesWithMetrics(e,t){let s=await this.load(e),r=s.memories.length;if(r===0)return{memories:[],metrics:{totalMemories:0,memoriesConsidered:0,memoriesReturned:0,filteringRatio:0,avgRelevanceScore:0}};let o=t.maxResults??10,i=t.minRelevance??10,c=s.memories.map(d=>{let g={domainMatch:0,tagMatch:0,recency:0,confidence:0,keywords:0,userTriggered:0};if(t.taskDomain&&(g.domainMatch=this._getSemanticDomainScore(t.taskDomain,d.tags||[])),t.commandName){let E=this._getCommandTags(t.commandName),b=(d.tags||[]).filter(x=>E.includes(x));g.tagMatch=Math.min(20,b.length*8)}let k=(Date.now()-new Date(d.updatedAt).getTime())/(1e3*60*60*24);if(g.recency=Math.max(0,Math.round(15-k*.5)),d.confidence?g.confidence=d.confidence==="high"?20:d.confidence==="medium"?12:5:d.observationCount&&(g.confidence=Math.min(20,d.observationCount*3)),t.taskDescription){let E=this._extractKeywordsFromText(t.taskDescription),b=0;for(let x of E)d.content.toLowerCase().includes(x)&&(b+=2),d.title.toLowerCase().includes(x)&&(b+=3);g.keywords=Math.min(15,b)}d.userTriggered&&(g.userTriggered=5);let S=g.domainMatch+g.tagMatch+g.recency+g.confidence+g.keywords+g.userTriggered;return{...d,relevanceScore:S,scoreBreakdown:g}}).filter(d=>d.relevanceScore>=i),p=c.sort((d,g)=>g.relevanceScore-d.relevanceScore).slice(0,o),m=p.length>0?Math.round(p.reduce((d,g)=>d+g.relevanceScore,0)/p.length):0;return{memories:p,metrics:{totalMemories:r,memoriesConsidered:c.length,memoriesReturned:p.length,filteringRatio:r>0?p.length/r:0,avgRelevanceScore:m}}}_getSemanticDomainScore(e,t){return 0}_getCommandTags(e){return{ship:[V.COMMIT_STYLE,V.SHIP_WORKFLOW,V.TEST_BEHAVIOR],feature:[V.ARCHITECTURE,V.CODE_STYLE],done:[V.SHIP_WORKFLOW],analyze:[V.TECH_STACK,V.ARCHITECTURE],spec:[V.ARCHITECTURE,V.CODE_STYLE],task:[V.BRANCH_NAMING,V.CODE_STYLE],sync:[V.TECH_STACK,V.ARCHITECTURE,V.DEPENDENCIES],test:[V.TEST_BEHAVIOR],bug:[V.CODE_STYLE,V.TEST_BEHAVIOR]}[e]||[]}_extractKeywordsFromText(e){let t=e.toLowerCase().split(/\s+/),s=new Set(["the","a","an","is","are","to","for","and","or","in","on","at","by","with","from","as","it","this","that","be","have","has"]);return t.filter(r=>r.length>2&&!s.has(r))}_extractContextTags(e){let t=[],s={ship:[V.COMMIT_STYLE,V.SHIP_WORKFLOW,V.TEST_BEHAVIOR],feature:[V.ARCHITECTURE,V.CODE_STYLE],done:[V.SHIP_WORKFLOW],analyze:[V.TECH_STACK,V.ARCHITECTURE],spec:[V.ARCHITECTURE,V.CODE_STYLE]};return e.commandName&&s[e.commandName]&&t.push(...s[e.commandName]),t}_extractKeywords(e){let t=[];e.params?.description&&t.push(...e.params.description.toLowerCase().split(/\s+/)),e.params?.feature&&t.push(...e.params.feature.toLowerCase().split(/\s+/));let s=["the","a","an","is","are","to","for","and","or","in"];return t.filter(r=>r.length>2&&!s.includes(r))}async autoRemember(e,t,s,r=""){let i={commit_footer:[V.COMMIT_STYLE],branch_naming:[V.BRANCH_NAMING],test_before_ship:[V.TEST_BEHAVIOR,V.SHIP_WORKFLOW],preferred_agent:[V.AGENT_PREFERENCE],code_style:[V.CODE_STYLE],verbosity:[V.OUTPUT_VERBOSITY]}[t]||[],a=await this.searchMemories(e,t);a.length>0?await this.updateMemory(e,a[0].id,{content:`${t}: ${s}`,tags:i}):await this.createMemory(e,{title:`Preference: ${t}`,content:`${t}: ${s}${r?`
|
|
366
|
+
`),this)}},f=xS});var Vp={};Ce(Vp,{default:()=>RS,sessionTracker:()=>Us});var Gp,Wp,Ac,Us,RS,ai=w(()=>{"use strict";zr();de();ln();ae();Gp=50,Wp=200,Ac=class{static{l(this,"SessionTracker")}async read(e){try{return j.getDoc(e,"session-tracker")??this.getDefault()}catch{return this.getDefault()}}async write(e,t){j.setDoc(e,"session-tracker",t)}getDefault(){return{current:null,config:{idleTimeoutMs:18e5}}}isExpired(e,t){return Ms(e.lastActivity,t)}async touch(e){let t=await this.read(e),s=T();if(t.current&&!this.isExpired(t.current,t.config.idleTimeoutMs))return t.current.lastActivity=s,await this.write(e,t),t.current;let r={id:crypto.randomUUID(),projectId:e,status:"active",createdAt:s,lastActivity:s,commands:[],files:[]};return t.current=r,await this.write(e,t),r}async trackCommand(e,t,s){let r=await this.read(e);if(!r.current)return;let o=T();r.current.lastActivity=o,r.current.commands.push({command:t,timestamp:o,durationMs:s}),r.current.commands.length>Gp&&(r.current.commands=r.current.commands.slice(-Gp)),await this.write(e,r)}async trackFile(e,t,s){let r=await this.read(e);if(!r.current)return;let o=T();r.current.lastActivity=o,r.current.files.push({path:t,operation:s,timestamp:o}),r.current.files.length>Wp&&(r.current.files=r.current.files.slice(-Wp)),await this.write(e,r)}async getInfo(e){let t=await this.read(e);if(!t.current||this.isExpired(t.current,t.config.idleTimeoutMs))return{active:!1,id:null,duration:null,idleSince:null,idleMs:0,expiresIn:null,commandCount:0,commands:[],filesRead:0,filesWritten:0};let s=t.current,r=Date.now(),o=new Date(s.createdAt).getTime(),i=new Date(s.lastActivity).getTime(),a=r-i,c=t.config.idleTimeoutMs,u=Math.max(0,c-a),p=s.commands.map(g=>g.command),m=new Set(s.files.filter(g=>g.operation==="read").map(g=>g.path)).size,d=new Set(s.files.filter(g=>g.operation==="write").map(g=>g.path)).size;return{active:!0,id:s.id,duration:Rt(r-o),idleSince:s.lastActivity,idleMs:a,expiresIn:Rt(u),commandCount:s.commands.length,commands:p,filesRead:m,filesWritten:d}}async expire(e){let t=await this.read(e);t.current&&(t.current.status="expired",t.current=null,await this.write(e,t))}async expireIfStale(e){let t=await this.read(e);return t.current&&this.isExpired(t.current,t.config.idleTimeoutMs)?(t.current=null,await this.write(e,t),!0):!1}},Us=new Ac,RS=Us});var zp={};Ce(zp,{default:()=>kn,performanceTracker:()=>Bp});var AS,Dc,Bp,kn,ci=w(()=>{"use strict";de();AS=BigInt(300*1e9),Dc=class{static{l(this,"PerformanceTracker")}marks=new Map;markStart(e){this.pruneStaleMarks(),this.marks.set(e,process.hrtime.bigint())}markEnd(e){let t=this.marks.get(e);if(t===void 0)return null;let s=process.hrtime.bigint();return this.marks.delete(e),Number(s-t)/1e6}pruneStaleMarks(){if(this.marks.size<10)return;let e=process.hrtime.bigint();for(let[t,s]of this.marks)e-s>AS&&this.marks.delete(t)}recordTiming(e,t,s,r){H.appendEvent(e,`perf.${t}`,{metric:t,value:Math.round(s*100)/100,unit:"ms",context:r})}snapshotMemory(){let e=process.memoryUsage();return{heapUsed:e.heapUsed,heapTotal:e.heapTotal,rss:e.rss,external:e.external}}recordMemory(e,t){let s=this.snapshotMemory(),r=[{metric:"heap_used",value:s.heapUsed,unit:"bytes"},{metric:"heap_total",value:s.heapTotal,unit:"bytes"},{metric:"rss",value:s.rss,unit:"bytes"},{metric:"external_memory",value:s.external,unit:"bytes"}];for(let o of r)H.appendEvent(e,`perf.${o.metric}`,{metric:o.metric,value:o.value,unit:o.unit,context:t});return s}recordContextCorrectness(e,t){H.appendEvent(e,"perf.context_correctness",{metric:"context_correctness",...t})}recordSubtaskHandoff(e,t){H.appendEvent(e,"perf.subtask_handoff",{metric:"subtask_handoff",...t})}getMetrics(e,t){t||(t=new Date,t.setDate(t.getDate()-7));let s=t.toISOString();return H.query(e,"SELECT data, timestamp FROM events WHERE type LIKE ? AND timestamp >= ? ORDER BY id DESC","perf.%",s).map(o=>({...JSON.parse(o.data),timestamp:o.timestamp}))}getReport(e,t=7){let s=new Date;s.setDate(s.getDate()-t),s.setHours(0,0,0,0);let r=this.getMetrics(e,s),o={period:`${t}d`},i=r.filter(d=>"metric"in d&&d.metric==="startup_time");if(i.length>0){let d=i.map(g=>g.value);o.startup={avg:Math.round(d.reduce((g,h)=>g+h,0)/d.length),min:Math.min(...d),max:Math.max(...d),count:d.length,unit:"ms"}}let a=r.filter(d=>"metric"in d&&d.metric==="heap_used"),c=r.filter(d=>"metric"in d&&d.metric==="rss");if(a.length>0){let d=l(k=>Math.round(k/1048576*10)/10,"toMB"),g=a.map(k=>k.value),h=c.map(k=>k.value);o.memory={avgHeapMB:d(g.reduce((k,S)=>k+S,0)/g.length),peakHeapMB:d(Math.max(...g)),avgRssMB:h.length>0?d(h.reduce((k,S)=>k+S,0)/h.length):0}}let u=r.filter(d=>"metric"in d&&d.metric==="context_correctness");if(u.length>0){let d=u.filter(g=>g.receivedSync).length;o.contextCorrectness={total:u.length,receivedSync:d,rate:Math.round(d/u.length*100)}}let p=r.filter(d=>"metric"in d&&d.metric==="subtask_handoff");if(p.length>0){let d=p.filter(g=>g.outputPopulated).length;o.subtaskHandoff={total:p.length,outputPopulated:d,rate:Math.round(d/p.length*100)}}let m=r.filter(d=>"metric"in d&&d.metric==="command_duration");if(m.length>0){let d={};for(let g of m){let h=g.context?.command||"unknown";d[h]||(d[h]=[]),d[h].push(g.value)}o.commandDurations={};for(let[g,h]of Object.entries(d))o.commandDurations[g]={avg:Math.round(h.reduce((k,S)=>k+S,0)/h.length),min:Math.min(...h),max:Math.max(...h),count:h.length,unit:"ms"}}return o}},Bp=new Dc,kn=Bp});function li(n,e=!1){return e||n>=6?"high":n>=3?"medium":"low"}var V,to=w(()=>{"use strict";V={CODE_STYLE:"code_style",NAMING_CONVENTION:"naming_convention",FILE_STRUCTURE:"file_structure",COMMIT_STYLE:"commit_style",BRANCH_NAMING:"branch_naming",TEST_BEHAVIOR:"test_behavior",SHIP_WORKFLOW:"ship_workflow",TECH_STACK:"tech_stack",ARCHITECTURE:"architecture",DEPENDENCIES:"dependencies",OUTPUT_VERBOSITY:"output_verbosity",CONFIRMATION_LEVEL:"confirmation_level",AGENT_PREFERENCE:"agent_preference"};l(li,"calculateConfidence")});var Sn,so,no,ro=w(()=>{"use strict";de();to();ae();Sn=class{static{l(this,"CachedStore")}_data=null;_loaded=!1;_projectId=null;getSubdirectory(){return null}getStoreKey(){let e=this.getFilename().replace(".json",""),t=this.getSubdirectory();return t?`memory:${t}:${e}`:`memory:${e}`}async load(e){if(this._loaded&&this._data&&this._projectId===e)return this._data;let t=this.getStoreKey(),s=H.getDoc(e,t);return s!==null?(this._data=s,this.afterLoad(this._data)):this._data=this.getDefault(),this._loaded=!0,this._projectId=e,this._data}afterLoad(e){}async save(e){if(!this._data)return;let t=this.getStoreKey();H.setDoc(e,t,this._data)}getData(){return this._data}setData(e){this._data=e}async update(e,t){let s=await this.load(e),r=t(s);return this._data=r,await this.save(e),r}isLoaded(e){return e?this._loaded&&this._projectId===e:this._loaded}reset(){this._data=null,this._loaded=!1,this._projectId=null}},so=class{static{l(this,"SessionStore")}_sessionMemory=new Map;setSession(e,t){this._sessionMemory.set(e,{value:t,timestamp:Date.now()})}getSession(e){return this._sessionMemory.get(e)?.value}clearSession(){this._sessionMemory.clear()}},no=class{static{l(this,"HistoryStore")}async appendHistory(e,t){let s={ts:T(),...t,type:t.type};H.appendEvent(e,`history.${t.type}`,s)}async getRecentHistory(e,t=20){return H.query(e,"SELECT data, timestamp FROM events WHERE type LIKE 'history.%' ORDER BY id DESC LIMIT ?",t).reverse().map(r=>JSON.parse(r.data))}}});var oo,Ic=w(()=>{"use strict";de();to();ae();ro();oo=class n extends Sn{static{l(this,"PatternStore")}static MAX_CONTEXTS=20;static ARCHIVE_AGE_DAYS=90;getFilename(){return"patterns.json"}getDefault(){return{version:1,decisions:{},preferences:{},workflows:{},counters:{}}}afterLoad(e){for(let t of Object.values(e.decisions))Array.isArray(t.contexts)||(t.contexts=[]),t.contexts.length>n.MAX_CONTEXTS&&(t.contexts=t.contexts.slice(-n.MAX_CONTEXTS))}async loadPatterns(e){return this.load(e)}async savePatterns(e){return this.save(e)}async recordDecision(e,t,s,r="",o={}){let i=await this.load(e),a=T();if(!i.decisions[t])i.decisions[t]={value:s,count:1,firstSeen:a,lastSeen:a,confidence:o.userConfirmed?"high":"low",contexts:[r].filter(Boolean),userConfirmed:o.userConfirmed||!1};else{let c=i.decisions[t];c.value===s?(c.count++,c.lastSeen=a,r&&!c.contexts.includes(r)&&(c.contexts.push(r),c.contexts.length>n.MAX_CONTEXTS&&(c.contexts=c.contexts.slice(-n.MAX_CONTEXTS))),o.userConfirmed&&(c.userConfirmed=!0),c.confidence=li(c.count,c.userConfirmed)):(c.value=s,c.count=1,c.lastSeen=a,c.userConfirmed=o.userConfirmed||!1,c.confidence=o.userConfirmed?"high":"low")}await this.save(e)}async confirmDecision(e,t){let r=(await this.load(e)).decisions[t];return r?(r.userConfirmed=!0,r.confidence="high",r.lastSeen=T(),await this.save(e),!0):!1}async getDecision(e,t){let r=(await this.load(e)).decisions[t];return!r||r.confidence==="low"?null:{value:r.value,confidence:r.confidence}}async hasPattern(e,t){return await this.getDecision(e,t)!==null}async recordWorkflow(e,t,s){let r=await this.load(e),o=T();if(!r.workflows[t])r.workflows[t]={...s,count:1,firstSeen:o,lastSeen:o,confidence:"low",userConfirmed:!1};else{let i=r.workflows[t];i.count++,i.lastSeen=o,i.confidence=li(i.count,i.userConfirmed)}await this.save(e)}async confirmWorkflow(e,t){let r=(await this.load(e)).workflows[t];return r?(r.userConfirmed=!0,r.confidence="high",r.lastSeen=T(),await this.save(e),!0):!1}async getWorkflow(e,t){let r=(await this.load(e)).workflows[t];return!r||r.count<3?null:r}async setPreference(e,t,s,r={}){let o=await this.load(e),i=o.preferences[t],a=i?i.observationCount+1:1,c=r.userConfirmed||i?.userConfirmed||!1;o.preferences[t]={value:s,updatedAt:T(),confidence:li(a,c),observationCount:a,userConfirmed:c},await this.save(e)}async confirmPreference(e,t){let r=(await this.load(e)).preferences[t];return r?(r.userConfirmed=!0,r.confidence="high",r.updatedAt=T(),await this.save(e),!0):!1}async getPreference(e,t,s=null){return(await this.load(e)).preferences[t]?.value??s}async getPatternsSummary(e){let t=await this.load(e);return{decisions:Object.keys(t.decisions).length,learnedDecisions:Object.values(t.decisions).filter(s=>s.confidence!=="low").length,workflows:Object.keys(t.workflows).length,preferences:Object.keys(t.preferences).length}}async archiveStaleDecisions(e){let t=await this.load(e),s=Date.now(),r=n.ARCHIVE_AGE_DAYS*24*60*60*1e3,o=[];for(let[a,c]of Object.entries(t.decisions)){let u=new Date(c.lastSeen).getTime();s-u>r&&o.push(a)}if(o.length===0)return 0;let i=H.getDoc(e,"memory:patterns-archive")??{};for(let a of o)i[a]=t.decisions[a],delete t.decisions[a];return H.setDoc(e,"memory:patterns-archive",i),await this.save(e),o.length}}});var bn,$c=w(()=>{"use strict";Gt();to();ae();ro();bn=class extends Sn{static{l(this,"SemanticMemories")}getFilename(){return"memories.json"}getDefault(){return{version:1,memories:[],index:this._createEmptyIndex()}}afterLoad(e){this._normalizeIndex(e)}_createEmptyIndex(){let e=Object.values(V),t={};for(let s of e)t[s]=[];return t}_normalizeIndex(e){let t=Object.values(V);for(let s of t)e.index[s]||(e.index[s]=[])}_coerceTags(e){let t=new Set(Object.values(V));return e.filter(s=>t.has(s))}async loadMemories(e){return this.load(e)}async saveMemories(e){return this.save(e)}async createMemory(e,{title:t,content:s,tags:r=[],userTriggered:o=!1}){let i=await this.load(e),a=this._coerceTags(r),c=T(),u={id:ve(),title:t,content:s,tags:a,userTriggered:o,createdAt:c,updatedAt:c};i.memories.push(u);for(let p of a)i.index[p].push(u.id);return await this.save(e),u.id}async updateMemory(e,t,s){let r=await this.load(e),o=r.memories.findIndex(c=>c.id===t);if(o===-1)return!1;let i=r.memories[o],a=i.tags||[];if(s.title&&(i.title=s.title),s.content&&(i.content=s.content),s.tags){let c=this._coerceTags(s.tags);for(let u of a)r.index[u]=r.index[u].filter(p=>p!==t);for(let u of c)r.index[u].push(t);i.tags=c}return i.updatedAt=T(),await this.save(e),!0}async deleteMemory(e,t){let s=await this.load(e),r=s.memories.findIndex(i=>i.id===t);if(r===-1)return!1;let o=s.memories[r];for(let i of o.tags||[])s.index[i]&&(s.index[i]=s.index[i].filter(a=>a!==t));return s.memories.splice(r,1),await this.save(e),!0}async findByTags(e,t,s=!1){let r=await this.load(e),o=this._coerceTags(t);if(s)return r.memories.filter(i=>o.every(a=>(i.tags||[]).includes(a)));{let i=new Set;for(let a of o){let c=r.index[a];for(let u of c)i.add(u)}return r.memories.filter(a=>i.has(a.id))}}async searchMemories(e,t){let s=await this.load(e),r=t.toLowerCase();return s.memories.filter(o=>o.title.toLowerCase().includes(r)||o.content.toLowerCase().includes(r))}async getRelevantMemories(e,t,s=5){return(await this.load(e)).memories.map(i=>{let a=0,c=this._extractContextTags(t);for(let d of i.tags||[])c.includes(d)&&(a+=10);let p=(Date.now()-new Date(i.updatedAt).getTime())/(1e3*60*60*24);a+=Math.max(0,5-p),i.userTriggered&&(a+=5);let m=this._extractKeywords(t);for(let d of m)i.content.toLowerCase().includes(d)&&(a+=2),i.title.toLowerCase().includes(d)&&(a+=3);return{...i,_score:a}}).filter(i=>i._score>0).sort((i,a)=>a._score-i._score).slice(0,s).map(({_score:i,...a})=>a)}async getRelevantMemoriesWithMetrics(e,t){let s=await this.load(e),r=s.memories.length;if(r===0)return{memories:[],metrics:{totalMemories:0,memoriesConsidered:0,memoriesReturned:0,filteringRatio:0,avgRelevanceScore:0}};let o=t.maxResults??10,i=t.minRelevance??10,c=s.memories.map(d=>{let g={domainMatch:0,tagMatch:0,recency:0,confidence:0,keywords:0,userTriggered:0};if(t.taskDomain&&(g.domainMatch=this._getSemanticDomainScore(t.taskDomain,d.tags||[])),t.commandName){let E=this._getCommandTags(t.commandName),b=(d.tags||[]).filter(x=>E.includes(x));g.tagMatch=Math.min(20,b.length*8)}let k=(Date.now()-new Date(d.updatedAt).getTime())/(1e3*60*60*24);if(g.recency=Math.max(0,Math.round(15-k*.5)),d.confidence?g.confidence=d.confidence==="high"?20:d.confidence==="medium"?12:5:d.observationCount&&(g.confidence=Math.min(20,d.observationCount*3)),t.taskDescription){let E=this._extractKeywordsFromText(t.taskDescription),b=0;for(let x of E)d.content.toLowerCase().includes(x)&&(b+=2),d.title.toLowerCase().includes(x)&&(b+=3);g.keywords=Math.min(15,b)}d.userTriggered&&(g.userTriggered=5);let S=g.domainMatch+g.tagMatch+g.recency+g.confidence+g.keywords+g.userTriggered;return{...d,relevanceScore:S,scoreBreakdown:g}}).filter(d=>d.relevanceScore>=i),p=c.sort((d,g)=>g.relevanceScore-d.relevanceScore).slice(0,o),m=p.length>0?Math.round(p.reduce((d,g)=>d+g.relevanceScore,0)/p.length):0;return{memories:p,metrics:{totalMemories:r,memoriesConsidered:c.length,memoriesReturned:p.length,filteringRatio:r>0?p.length/r:0,avgRelevanceScore:m}}}_getSemanticDomainScore(e,t){return 0}_getCommandTags(e){return{ship:[V.COMMIT_STYLE,V.SHIP_WORKFLOW,V.TEST_BEHAVIOR],feature:[V.ARCHITECTURE,V.CODE_STYLE],done:[V.SHIP_WORKFLOW],analyze:[V.TECH_STACK,V.ARCHITECTURE],spec:[V.ARCHITECTURE,V.CODE_STYLE],task:[V.BRANCH_NAMING,V.CODE_STYLE],sync:[V.TECH_STACK,V.ARCHITECTURE,V.DEPENDENCIES],test:[V.TEST_BEHAVIOR],bug:[V.CODE_STYLE,V.TEST_BEHAVIOR]}[e]||[]}_extractKeywordsFromText(e){let t=e.toLowerCase().split(/\s+/),s=new Set(["the","a","an","is","are","to","for","and","or","in","on","at","by","with","from","as","it","this","that","be","have","has"]);return t.filter(r=>r.length>2&&!s.has(r))}_extractContextTags(e){let t=[],s={ship:[V.COMMIT_STYLE,V.SHIP_WORKFLOW,V.TEST_BEHAVIOR],feature:[V.ARCHITECTURE,V.CODE_STYLE],done:[V.SHIP_WORKFLOW],analyze:[V.TECH_STACK,V.ARCHITECTURE],spec:[V.ARCHITECTURE,V.CODE_STYLE]};return e.commandName&&s[e.commandName]&&t.push(...s[e.commandName]),t}_extractKeywords(e){let t=[];e.params?.description&&t.push(...e.params.description.toLowerCase().split(/\s+/)),e.params?.feature&&t.push(...e.params.feature.toLowerCase().split(/\s+/));let s=["the","a","an","is","are","to","for","and","or","in"];return t.filter(r=>r.length>2&&!s.includes(r))}async autoRemember(e,t,s,r=""){let i={commit_footer:[V.COMMIT_STYLE],branch_naming:[V.BRANCH_NAMING],test_before_ship:[V.TEST_BEHAVIOR,V.SHIP_WORKFLOW],preferred_agent:[V.AGENT_PREFERENCE],code_style:[V.CODE_STYLE],verbosity:[V.OUTPUT_VERBOSITY]}[t]||[],a=await this.searchMemories(e,t);a.length>0?await this.updateMemory(e,a[0].id,{content:`${t}: ${s}`,tags:i}):await this.createMemory(e,{title:`Preference: ${t}`,content:`${t}: ${s}${r?`
|
|
367
367
|
Context: ${r}`:""}`,tags:i,userTriggered:!0})}async getAllMemories(e){return(await this.load(e)).memories}async getMemoryStats(e){let t=await this.load(e),s={};for(let[r,o]of Object.entries(t.index))s[r]=o.length;return{totalMemories:t.memories.length,userTriggered:t.memories.filter(r=>r.userTriggered).length,tagCounts:s,oldestMemory:t.memories[0]?.createdAt,newestMemory:t.memories[t.memories.length-1]?.createdAt}}}});var Mc,DS,kt,io=w(()=>{"use strict";ro();Ic();$c();ro();Ic();$c();Mc=class{static{l(this,"MemorySystem")}_semanticMemories;_patternStore;_historyStore;_sessionStore;constructor(){this._semanticMemories=new bn,this._patternStore=new oo,this._historyStore=new no,this._sessionStore=new so}loadMemories(e){return this._semanticMemories.loadMemories(e)}saveMemories(e){return this._semanticMemories.saveMemories(e)}createMemory(e,t){return this._semanticMemories.createMemory(e,t)}updateMemory(e,t,s){return this._semanticMemories.updateMemory(e,t,s)}deleteMemory(e,t){return this._semanticMemories.deleteMemory(e,t)}findByTags(e,t,s){return this._semanticMemories.findByTags(e,t,s)}searchMemories(e,t){return this._semanticMemories.searchMemories(e,t)}getRelevantMemories(e,t,s){return this._semanticMemories.getRelevantMemories(e,t,s)}autoRemember(e,t,s,r){return this._semanticMemories.autoRemember(e,t,s,r)}getAllMemories(e){return this._semanticMemories.getAllMemories(e)}getMemoryStats(e){return this._semanticMemories.getMemoryStats(e)}getRelevantMemoriesWithMetrics(e,t){return this._semanticMemories.getRelevantMemoriesWithMetrics(e,t)}setSession(e,t){this._sessionStore.setSession(e,t)}getSession(e){return this._sessionStore.getSession(e)}clearSession(){this._sessionStore.clearSession()}loadPatterns(e){return this._patternStore.loadPatterns(e)}savePatterns(e){return this._patternStore.savePatterns(e)}recordDecision(e,t,s,r){return this._patternStore.recordDecision(e,t,s,r)}getDecision(e,t){return this._patternStore.getDecision(e,t)}hasPattern(e,t){return this._patternStore.hasPattern(e,t)}recordWorkflow(e,t,s){return this._patternStore.recordWorkflow(e,t,s)}getWorkflow(e,t){return this._patternStore.getWorkflow(e,t)}setPreference(e,t,s,r){return this._patternStore.setPreference(e,t,s,r)}getPreference(e,t,s){return this._patternStore.getPreference(e,t,s)}confirmPreference(e,t){return this._patternStore.confirmPreference(e,t)}confirmDecision(e,t){return this._patternStore.confirmDecision(e,t)}confirmWorkflow(e,t){return this._patternStore.confirmWorkflow(e,t)}getPatternsSummary(e){return this._patternStore.getPatternsSummary(e)}archiveStaleDecisions(e){return this._patternStore.archiveStaleDecisions(e)}appendHistory(e,t){return this._historyStore.appendHistory(e,t)}getRecentHistory(e,t){return this._historyStore.getRecentHistory(e,t)}async getSmartDecision(e,t){let s=this.getSession(`decision:${t}`);if(s!==void 0)return s;let r=await this.getDecision(e,t);return r?r.value:null}async learnDecision(e,t,s,r=""){this.setSession(`decision:${t}`,s),await this.recordDecision(e,t,s,r),await this.appendHistory(e,{type:"decision",key:t,value:s,context:r})}resetState(){this._sessionStore.clearSession(),this._semanticMemories.reset(),this._patternStore.reset()}},DS=new Mc,kt=DS});import Jt from"node:fs/promises";import Yt from"node:path";var Oc,IS,it,Jp=w(()=>{"use strict";U();We();J();Oc=class{static{l(this,"CodebaseAnalyzer")}projectPath=null;init(e=process.cwd()){this.projectPath=e}async readPackageJson(){try{let e=Yt.join(this.projectPath,"package.json"),t=await Jt.readFile(e,"utf-8");return JSON.parse(t)}catch(e){if(D(e)||e instanceof SyntaxError)return null;throw e}}async readCargoToml(){try{let e=Yt.join(this.projectPath,"Cargo.toml");return await Jt.readFile(e,"utf-8")}catch(e){if(D(e))return null;throw e}}async readRequirements(){try{let e=Yt.join(this.projectPath,"requirements.txt");return await Jt.readFile(e,"utf-8")}catch(e){if(D(e))return null;throw e}}async readGoMod(){try{let e=Yt.join(this.projectPath,"go.mod");return await Jt.readFile(e,"utf-8")}catch(e){if(D(e))return null;throw e}}async readGemfile(){try{let e=Yt.join(this.projectPath,"Gemfile");return await Jt.readFile(e,"utf-8")}catch(e){if(D(e))return null;throw e}}async readMixExs(){try{let e=Yt.join(this.projectPath,"mix.exs");return await Jt.readFile(e,"utf-8")}catch(e){if(D(e))return null;throw e}}async readPomXml(){try{let e=Yt.join(this.projectPath,"pom.xml");return await Jt.readFile(e,"utf-8")}catch(e){if(D(e))return null;throw e}}async readComposerJson(){try{let e=Yt.join(this.projectPath,"composer.json"),t=await Jt.readFile(e,"utf-8");return JSON.parse(t)}catch(e){if(D(e)||e instanceof SyntaxError)return null;throw e}}async readPyprojectToml(){try{let e=Yt.join(this.projectPath,"pyproject.toml");return await Jt.readFile(e,"utf-8")}catch(e){if(D(e))return null;throw e}}async getFileExtensions(){try{let{stdout:e}=await L('find . -type f ! -path "*/node_modules/*" ! -path "*/.git/*" ! -path "*/dist/*" ! -path "*/.next/*" | sed "s/.*\\./\\./" | sort | uniq -c | sort -rn',{cwd:this.projectPath}),t={};return e.trim().split(`
|
|
368
368
|
`).filter(Boolean).forEach(s=>{let r=s.trim().match(/^\s*(\d+)\s+(\.\w+)$/);r&&(t[r[2]]=parseInt(r[1],10))}),t}catch{return{}}}async listConfigFiles(){try{let e=await Jt.readdir(this.projectPath),t=[/^package\.json$/,/^Cargo\.toml$/,/^go\.mod$/,/^requirements\.txt$/,/^Gemfile$/,/^mix\.exs$/,/^pom\.xml$/,/^composer\.json$/,/^pyproject\.toml$/,/^tsconfig.*\.json$/,/^\..*rc(\.json|\.js|\.cjs)?$/,/^Dockerfile$/,/^docker-compose.*\.ya?ml$/,/^\.env.*$/];return e.filter(s=>t.some(r=>r.test(s)))}catch(e){if(D(e))return[];throw e}}async listDirectories(){try{return(await Jt.readdir(this.projectPath,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name).filter(t=>!t.startsWith(".")&&t!=="node_modules")}catch(e){if(D(e))return[];throw e}}async getGitLog(e=50){try{let{stdout:t}=await L(`git log -n ${e} --pretty=format:"%h|%an|%ar|%s"`,{cwd:this.projectPath});return t}catch{return""}}async getGitStats(){try{let{stdout:e}=await L("git rev-list --count HEAD",{cwd:this.projectPath}),{stdout:t}=await L('git log --format="%an" | sort -u | wc -l',{cwd:this.projectPath}),{stdout:s}=await L('git log --reverse --pretty=format:"%ar" | head -1',{cwd:this.projectPath});return{totalCommits:parseInt(e.trim(),10)||0,contributors:parseInt(t.trim(),10)||0,age:s.trim()||"unknown"}}catch{return{totalCommits:0,contributors:0,age:"unknown"}}}async countFiles(){try{let{stdout:e}=await L('find . -type f ! -path "*/node_modules/*" ! -path "*/.git/*" ! -path "*/dist/*" | wc -l',{cwd:this.projectPath});return parseInt(e.trim(),10)||0}catch{return 0}}async fileExists(e){return v(Yt.join(this.projectPath,e))}async readFile(e){try{let t=Yt.join(this.projectPath,e);return await Jt.readFile(t,"utf-8")}catch(t){if(D(t))return null;throw t}}async findFiles(e){try{let{stdout:t}=await L(`find . -type f -name "${e}" ! -path "*/node_modules/*" ! -path "*/.git/*"`,{cwd:this.projectPath});return t.trim().split(`
|
|
369
369
|
`).filter(Boolean)}catch{return[]}}},IS=new Oc,it=IS});import Nc from"node:fs";import $S from"node:fs/promises";import ui from"node:path";function Lc(){if(qp)return _c;qp=!0;let n=ui.join(ut,"dist","templates.json");try{let e=Nc.readFileSync(n,"utf-8");return _c=JSON.parse(e),_c}catch{return null}}function OS(n){let e=vn.indexOf(n);e>-1&&vn.splice(e,1),vn.push(n)}function _S(){for(;Xn.size>=MS&&vn.length>0;){let n=vn.shift();n&&Xn.delete(n)}}function Kp(n){let e=/^---\n([\s\S]+?)\n---\n([\s\S]*)$/,t=n.match(e);if(!t)return{frontmatter:{},content:n.trim()};let[,s,r]=t,o={};return s.split(`
|
|
@@ -714,8 +714,8 @@ ${e.example}
|
|
|
714
714
|
|
|
715
715
|
Fields:
|
|
716
716
|
${fT(e.schema)}`:null}function fT(n){if(n instanceof lt.ZodObject){let e=n.shape;return Object.entries(e).map(([t,s])=>`- \`${t}\`: ${Kf(s)}`).join(`
|
|
717
|
-
`)}return"(see example above)"}function Kf(n){return n instanceof lt.ZodString?"string":n instanceof lt.ZodNumber?"number":n instanceof lt.ZodEnum?`one of: ${n.options.join(", ")}`:n instanceof lt.ZodArray?`array of ${Kf(n.element)}`:n instanceof lt.ZodObject?"object":"any"}var zf,Jf,qf,Yf=w(()=>{"use strict";Vi();Vi();zf=lt.object({agentName:lt.string(),reasoning:lt.string(),confidence:lt.number().min(0).max(1)}),Jf=lt.object({subtasks:lt.array(lt.object({description:lt.string(),domain:Wi,agent:lt.string(),dependsOn:lt.array(lt.number())})),effort:lt.enum(["low","medium","high"])}),qf={classification:{schema:dr,example:JSON.stringify({primaryDomain:"backend",secondaryDomains:["database"],confidence:.9,filePatterns:["src/api/**"],relevantAgents:["backend.md"]},null,2)},agentAssignment:{schema:zf,example:JSON.stringify({agentName:"backend.md",reasoning:"Task involves API endpoint creation",confidence:.85},null,2)},subtaskBreakdown:{schema:Jf,example:JSON.stringify({subtasks:[{description:"Add schema validation",domain:"backend",agent:"backend.md",dependsOn:[]},{description:"Add unit tests",domain:"testing",agent:"testing.md",dependsOn:[0]}],effort:"medium"},null,2)}};l(gT,"renderSchemaForPrompt");l(fT,"describeSchema");l(Kf,"describeField")});import Qf from"node:fs/promises";import Pn from"node:path";var au,hT,Zf,eh=w(()=>{"use strict";ls();Dt();U();J();et();Rf();Df();Uf();Gf();Bf();ru();Gs();au=class{static{l(this,"PromptBuilder")}_checklistsCache=null;_checklistsCacheTime=0;_checklistRoutingCache=null;_checklistRoutingCacheTime=0;_stateCache=new Map;_stateCacheTTL=5e3;_templateCache=new Map;TEMPLATE_CACHE_TTL_MS=6e4;
|
|
718
|
-
`);return Co(r,this.getEffectiveBudgets().autoContext)}calculateElapsed(e){let t=new Date(e).getTime(),r=Date.now()-t,o=Math.floor(r/6e4),i=Math.floor(o/60),a=Math.floor(i/24);return a>0?`${a}d ${i%24}h`:i>0?`${i}h ${o%60}m`:`${o}m`}async loadChecklistRouting(){let e=Date.now();if(this._checklistRoutingCache&&e-this._checklistRoutingCacheTime<this.TEMPLATE_CACHE_TTL_MS)return this._checklistRoutingCache;let t=Pn.join(__dirname,"..","..","templates","agentic","checklist-routing.md"),s=await this.getTemplate(t);return s&&(this._checklistRoutingCache=s,this._checklistRoutingCacheTime=e),this._checklistRoutingCache||null}async buildWithInjection(e,t,s,r=null,o=null,i=null,a=null,c=null){let u=[];if(t.projectId){let m=await this.buildInjectedContext(t.projectId);m&&u.push(m)}let p=await this.build(e,t,s,r,o,i,a,c);return u.push(p),u.join("")}async build(e,t,s,r=null,o=null,i=null,a=null,c=null,u=null,p){let m=p?.skipNativeContext??!1,d=[]
|
|
717
|
+
`)}return"(see example above)"}function Kf(n){return n instanceof lt.ZodString?"string":n instanceof lt.ZodNumber?"number":n instanceof lt.ZodEnum?`one of: ${n.options.join(", ")}`:n instanceof lt.ZodArray?`array of ${Kf(n.element)}`:n instanceof lt.ZodObject?"object":"any"}var zf,Jf,qf,Yf=w(()=>{"use strict";Vi();Vi();zf=lt.object({agentName:lt.string(),reasoning:lt.string(),confidence:lt.number().min(0).max(1)}),Jf=lt.object({subtasks:lt.array(lt.object({description:lt.string(),domain:Wi,agent:lt.string(),dependsOn:lt.array(lt.number())})),effort:lt.enum(["low","medium","high"])}),qf={classification:{schema:dr,example:JSON.stringify({primaryDomain:"backend",secondaryDomains:["database"],confidence:.9,filePatterns:["src/api/**"],relevantAgents:["backend.md"]},null,2)},agentAssignment:{schema:zf,example:JSON.stringify({agentName:"backend.md",reasoning:"Task involves API endpoint creation",confidence:.85},null,2)},subtaskBreakdown:{schema:Jf,example:JSON.stringify({subtasks:[{description:"Add schema validation",domain:"backend",agent:"backend.md",dependsOn:[]},{description:"Add unit tests",domain:"testing",agent:"testing.md",dependsOn:[0]}],effort:"medium"},null,2)}};l(gT,"renderSchemaForPrompt");l(fT,"describeSchema");l(Kf,"describeField")});import Qf from"node:fs/promises";import Pn from"node:path";var au,hT,Zf,eh=w(()=>{"use strict";ls();Dt();U();J();et();Rf();Df();Uf();Gf();Bf();ru();Gs();au=class{static{l(this,"PromptBuilder")}_checklistsCache=null;_checklistsCacheTime=0;_checklistRoutingCache=null;_checklistRoutingCacheTime=0;_stateCache=new Map;_stateCacheTTL=5e3;_templateCache=new Map;TEMPLATE_CACHE_TTL_MS=6e4;_coordinator=null;async getTemplate(e){let t=this._templateCache.get(e),s=Date.now();if(t&&s-t.loadedAt<this.TEMPLATE_CACHE_TTL_MS)return t.content;try{if(await v(e)){let r=await Qf.readFile(e,"utf-8");return this._templateCache.set(e,{content:r,loadedAt:s}),r}}catch(r){D(r)||console.error(`Template loading warning: ${y(r)}`)}return null}clearTemplateCache(){this._templateCache.clear(),this._checklistsCache=null,this._checklistsCacheTime=0,this._checklistRoutingCache=null,this._checklistRoutingCacheTime=0}setCoordinator(e){this._coordinator=e}getCoordinator(){return this._coordinator}getEffectiveBudgets(){return this._coordinator?Vf(this._coordinator):qi}resetContext(){}setContext(e){}async loadModule(e){let t=St(`global/modules/${e}`);if(t)return t;let s=Pn.join(ut,"templates/global/modules",e);return this.getTemplate(s)}getModulesForCommand(e,t){return t?t.modules:[]}async loadChecklists(){let e=Date.now();if(this._checklistsCache&&e-this._checklistsCacheTime<this.TEMPLATE_CACHE_TTL_MS)return this._checklistsCache;let t={};try{let s=Hs("checklists/");if(s.length>0){for(let r of s)if(r.endsWith(".md")){let o=St(r);if(o){let i=Pn.basename(r,".md");t[i]=o}}}else{let r=Pn.join(ut,"templates","checklists");if(await v(r)){let o=(await Qf.readdir(r)).filter(i=>i.endsWith(".md"));for(let i of o){let a=i.replace(".md",""),c=Pn.join(r,i),u=await this.getTemplate(c);u&&(t[a]=u)}}}}catch(s){D(s)||console.error(`Checklist loading warning: ${y(s)}`)}return this._checklistsCache=t,this._checklistsCacheTime=e,t}async getProjectState(e){if(!e)return null;let t=this._stateCache.get(e);if(t&&Date.now()-t.timestamp<this._stateCacheTTL)return t.state;try{let[s,r]=await Promise.all([N.read(e),xe.read(e)]),o={projectId:e,currentTask:s.currentTask,queue:r.tasks};return this._stateCache.set(e,{state:o,timestamp:Date.now()}),o}catch(s){if(D(s)||s instanceof SyntaxError)return null;throw s}}async buildInjectedContext(e){if(!e)return null;let t=await this.getProjectState(e);if(!t)return null;let s=[];if(s.push("## AUTO-INJECTED CONTEXT"),s.push(""),t.currentTask){let o=this.calculateElapsed(t.currentTask.startedAt);s.push(`**Current Task**: ${t.currentTask.description}`),s.push(`- Started: ${o} ago`)}else s.push("**Current Task**: None");if(s.push(""),t.queue.length>0){s.push(`**Queue**: ${t.queue.length} tasks pending`);let o=t.queue.slice(0,3);for(let i of o)s.push(`- [${i.priority}] ${i.description}`);t.queue.length>3&&s.push(`- ... and ${t.queue.length-3} more`)}s.push("");try{let o=await jf.detectPatterns(e);if(o.length>0){s.push("**Project Conventions**");for(let i of o.slice(0,3))s.push(`- ${i.description}`),i.suggestedAction&&s.push(` \u2192 ${i.suggestedAction}`);s.push("")}}catch(o){!D(o)&&!(o instanceof SyntaxError)&&console.error(`Outcome detection warning: ${y(o)}`)}s.push("---"),s.push("");let r=s.join(`
|
|
718
|
+
`);return Co(r,this.getEffectiveBudgets().autoContext)}calculateElapsed(e){let t=new Date(e).getTime(),r=Date.now()-t,o=Math.floor(r/6e4),i=Math.floor(o/60),a=Math.floor(i/24);return a>0?`${a}d ${i%24}h`:i>0?`${i}h ${o%60}m`:`${o}m`}async loadChecklistRouting(){let e=Date.now();if(this._checklistRoutingCache&&e-this._checklistRoutingCacheTime<this.TEMPLATE_CACHE_TTL_MS)return this._checklistRoutingCache;let t=Pn.join(__dirname,"..","..","templates","agentic","checklist-routing.md"),s=await this.getTemplate(t);return s&&(this._checklistRoutingCache=s,this._checklistRoutingCacheTime=e),this._checklistRoutingCache||null}async buildWithInjection(e,t,s,r=null,o=null,i=null,a=null,c=null){let u=[];if(t.projectId){let m=await this.buildInjectedContext(t.projectId);m&&u.push(m)}let p=await this.build(e,t,s,r,o,i,a,c);return u.push(p),u.join("")}async build(e,t,s,r=null,o=null,i=null,a=null,c=null,u=null,p){let m=p?.skipNativeContext??!1,d=[],g=e.frontmatter?.name?.replace("p:","")||"",h;try{let C=await Nf();h=Ff(C,g,e).entry}catch{h={agents:!0,patterns:!0,checklist:!1,modules:[]}}let k=h.agents;r&&k&&(d.push(`# AGENT: ${r.name}
|
|
719
719
|
`),r.role&&d.push(`Role: ${r.role}
|
|
720
720
|
`),r.skills?.length&&d.push(`Skills: ${r.skills.join(", ")}
|
|
721
721
|
`),d.push(`
|
|
@@ -1676,7 +1676,7 @@ ${Q.yellow(`Command '${n}' not found.`)}
|
|
|
1676
1676
|
|
|
1677
1677
|
Run 'prjct help' to see all available commands.
|
|
1678
1678
|
`}function ew(){let n=[];n.push(""),n.push(Q.cyan.bold("All Commands")),n.push("");let e=Object.entries($o).sort((t,s)=>t[1].order-s[1].order);for(let[t,s]of e){let r=Dr.filter(o=>o.group===t);if(r.length!==0){n.push(`${Q.bold(s.title)} ${Q.dim(`(${r.length} commands)`)}`),n.push(Q.dim(s.description)),n.push("");for(let o of r){let i=`p. ${o.name}`.padEnd(18),a=o.description.length>45?`${o.description.slice(0,42)}...`:o.description;n.push(` ${i} ${a}`)}n.push("")}}return n.push(Q.dim("Run 'prjct help <command>' for detailed help on a specific command.")),n.push(""),n.join(`
|
|
1679
|
-
`)}function GE(n){return n?n==="commands"||n==="all"?ew():Zy(n):Xy()}var Ky,HE,sw=w(()=>{"use strict";vd();et();Ky=[{name:"start",description:"First-time setup wizard",example:"prjct start"},{name:"init",description:"Initialize project in current directory",example:"prjct init"},{name:"sync",description:"Sync project state and update context files",example:"prjct sync"},{name:"watch",description:"Auto-sync on file changes",example:"prjct watch",options:["--verbose","--debounce=<ms>","--interval=<sec>"]},{name:"hooks",description:"Manage git hooks for auto-sync",example:"prjct hooks install",subcommands:["install","uninstall","status"]},{name:"doctor",description:"Check system health and dependencies",example:"prjct doctor"},{name:"serve",description:"Start web dashboard server",example:"prjct serve [port]"},{name:"context",description:"Smart context filtering tools for AI",example:'prjct context files "add auth"',subcommands:["files","signatures","imports","recent","summary"]},{name:"enrich",description:"Prepare issue enrichment context from local code",example:'prjct enrich "PROJ-123 improve auth flow" --md'},{name:"linear",description:"Linear issue tracker MCP gateway",example:"prjct linear setup",subcommands:["setup","status","sync","list","get","create","update","start","done","comment"]},{name:"jira",description:"Jira issue tracker MCP gateway",example:"prjct jira setup",subcommands:["setup","status","sync","list","get","create","update","start","done","transition","comment"]},{name:"stop",description:"Stop the background daemon",example:"prjct stop",options:["--force"]},{name:"restart",description:"Restart the background daemon",example:"prjct restart"},{name:"uninstall",description:"Complete system removal of prjct",example:"prjct uninstall --backup",options:["--force","--backup","--dry-run","--keep-package"]}],HE=[{flag:"-q, --quiet",description:"Suppress all output (errors to stderr only)"},{flag:"-v, --version",description:"Show version and provider status"},{flag:"-h, --help",description:"Show this help message"}];l(Xy,"formatMainHelp");l(Yy,"formatTerminalCommandHelp");l(Qy,"formatAgentCommandHelp");l(Zy,"formatCommandHelp");l(ew,"formatCommandList");l(GE,"getHelp")});var nw=dw((sJ,WE)=>{WE.exports={name:"prjct-cli",version:"1.50.0",description:"Context layer for AI agents. Project context for Claude Code, Gemini CLI, and more.",main:"dist/bin/prjct.mjs",bin:{prjct:"bin/prjct"},publishConfig:{access:"public",registry:"https://registry.npmjs.org"},scripts:{build:"node scripts/build.js","build:node":"node scripts/build.js",release:"node scripts/release.js","release:patch":"node scripts/release.js patch","release:minor":"node scripts/release.js minor","release:major":"node scripts/release.js major",postinstall:"node scripts/postinstall.js",prepare:"lefthook install","update-commands":`bun -e "const installer = require('./core/infrastructure/command-installer'); installer.syncCommands().then(r => console.log('Commands updated:', r)).catch(e => console.error('Error:', e.message))"`,"install-global":"./scripts/install.sh",update:"./scripts/update.sh",test:"bun test","test:watch":"bun test --watch","test:coverage":"bun test --coverage",typecheck:"tsc --noEmit -p core/tsconfig.json","typecheck:watch":"tsc --noEmit -p core/tsconfig.json --watch",validate:"bun scripts/validate-commands.js",lint:"biome lint .","lint:fix":"biome lint --write .","lint:meta":"bun core/cli/lint-meta-commentary.ts",format:"biome format --write .","format:check":"biome format .",check:"biome check .","check:fix":"biome check --write ."},keywords:["claude-code","gemini-cli","ai-agents","context-layer","developer-tools","ai-assistant","productivity","mcp","llm","coding-agents"],author:"prjct.app",license:"MIT",dependencies:{"@clack/prompts":"^1.0.0","@hono/node-server":"^1.13.7","better-sqlite3":"^12.6.2",chalk:"^4.1.2",chokidar:"^5.0.0","date-fns":"^4.1.0",glob:"^13.0.1",hono:"^4.11.3","jsonc-parser":"^3.3.1",zod:"^3.24.1"},devDependencies:{"@biomejs/biome":"^2.3.13","@types/better-sqlite3":"^7.6.13","@types/bun":"latest","@types/chokidar":"^2.1.7",esbuild:"^0.25.0",lefthook:"^2.1.0",typescript:"^5.9.3"},repository:{type:"git",url:"git+https://github.com/jlopezlira/prjct-cli.git"},bugs:{url:"https://github.com/jlopezlira/prjct-cli/issues"},homepage:"https://prjct.app",packageManager:"bun@1.2.23",engines:{bun:">=1.0.0",node:">=18.0.0"},files:["assets/","bin/prjct","dist/","templates/","scripts/postinstall.js","scripts/ensure-bun.sh","scripts/install.sh","LICENSE","README.md","CHANGELOG.md"],prepublishOnly:"node scripts/build.js",trustedDependencies:["chalk"]}});var YE={};import rw from"node:os";import $a from"node:path";import Ge from"chalk";async function VE(){let[n,...e]=process.argv.slice(2);if(["-v","--version","version"].includes(n)){let t=await Promise.resolve().then(()=>pw(nw()));await KE(t.version),process.exit(0)}["-h","--help",void 0].includes(n)&&(XE(),process.exit(0)),f.start();try{let t=W.getByName(n);if(!t){let m=zE(n),d=m?`Did you mean 'prjct ${m}'? Run 'prjct --help' for all commands`:"Run 'prjct --help' to see available commands";f.failWithHint(wn("UNKNOWN_COMMAND",{message:`Unknown command: ${n}`,hint:d})),f.end(),process.exit(1)}if(t.deprecated){let m=t.replacedBy?`Use 'prjct ${t.replacedBy}' instead`:"Run 'prjct --help' to see available commands";f.failWithHint({message:`Command '${n}' is deprecated`,hint:m}),f.end(),process.exit(1)}t.implemented||(f.failWithHint({message:`Command '${n}' is not yet implemented`,hint:"Run 'prjct --help' to see available commands",docs:"https://github.com/jlopezlira/prjct-cli"}),f.end(),process.exit(1));let{parsedArgs:s,options:r}=qE(t,e),o=!process.stdin.isTTY||r.md===!0||r.json===!0;t.requiresLlm&&!o&&(f.failWithHint({message:`'prjct ${n}' requires an AI agent to process its output`,hint:`Use 'p. ${n}' inside Claude/Cursor, or add --md flag`}),f.end(),process.exit(1));let i=BE(t,s);i&&(f.failWithHint(i),f.end(),process.exit(1));let a=null,c=Date.now();try{a=await M.getProjectId(process.cwd()),a&&(await Us.expireIfStale(a),await Us.touch(a))}catch{}let u=new en,p;if(n==="design"){let m=s.join(" ");p=await u.design(m,r)}else if(n==="analyze")p=await u.analyze(r);else if(n==="cleanup")p=await u.cleanup(r);else if(n==="cleanup-projects")p=await u.cleanupProjects({dryRun:r["dry-run"]===!0,md:r.md===!0});else if(n==="setup")p=await u.setup(r);else if(n==="update")p=await u.update(r);else{let m=s.join(" ")||null,d=r.md===!0,h={task:l(k=>u.task(k,process.cwd(),{md:d}),"task"),done:l(()=>u.done(process.cwd(),{md:d}),"done"),next:l(()=>u.next(process.cwd(),{md:d}),"next"),pause:l(k=>u.pause(k||"",process.cwd(),{md:d}),"pause"),resume:l(k=>u.resume(k,process.cwd(),{md:d}),"resume"),init:l(k=>u.init(k),"init"),bug:l(k=>u.bug(k||"",process.cwd(),{md:d}),"bug"),idea:l(k=>u.idea(k||"",process.cwd(),{md:d}),"idea"),spec:l(k=>u.spec(k),"spec"),ship:l(k=>u.ship(k,process.cwd(),{md:d}),"ship"),workflow:l(k=>u.workflowPrefs(k,process.cwd(),{md:d}),"workflow"),sessions:l(()=>u.sessions(process.cwd(),{md:d,cleanup:r.cleanup===!0}),"sessions"),dash:l(k=>u.dash(k||"default",process.cwd(),{md:d}),"dash"),stats:l(()=>u.stats(process.cwd(),{json:r.json===!0,export:r.export===!0}),"stats"),status:l(()=>u.status(process.cwd(),{json:r.json===!0,md:d}),"status"),help:l(k=>u.help(k||""),"help"),perf:l(k=>u.perf(k||"7"),"perf"),velocity:l(k=>u.velocity(k||"0"),"velocity"),recover:l(()=>u.recover(),"recover"),undo:l(()=>u.undo(),"undo"),redo:l(()=>u.redo(),"redo"),history:l(()=>u.history(),"history"),enrich:l(k=>u.enrich(k,process.cwd(),{md:d,json:r.json===!0}),"enrich"),sync:l(()=>u.sync(process.cwd(),{preview:r.preview===!0||r["dry-run"]===!0,yes:r.yes===!0,json:r.json===!0,md:d,package:r.package?String(r.package):void 0,full:r.full===!0}),"sync"),diff:l(()=>u.diff(process.cwd(),{json:r.json===!0,md:d}),"diff"),seal:l(()=>u.seal(process.cwd(),{json:r.json===!0}),"seal"),rollback:l(()=>u.rollback(process.cwd(),{json:r.json===!0,md:d}),"rollback"),verify:l(()=>u.verify(process.cwd(),{json:r.json===!0,semantic:r.semantic===!0}),"verify"),"analysis-payload":l(()=>u.analysisPayload(process.cwd(),{json:r.json===!0,md:d}),"analysis-payload"),"analysis-save-llm":l(k=>u.saveLlmAnalysis(k||"",process.cwd(),{md:d}),"analysis-save-llm"),"analysis-llm":l(()=>u.getLlmAnalysis(process.cwd(),{json:r.json===!0,md:d}),"analysis-llm"),start:l(()=>u.start(),"start"),context:l(k=>u.context(k),"context"),login:l(()=>u.login({md:d,url:r.url?String(r.url):void 0}),"login"),logout:l(()=>u.logout(),"logout"),auth:l(k=>u.auth(k,{md:d}),"auth")}[n];if(h)p=await h(m);else throw new Error(`Command '${n}' has no handler`)}if(a){let m=Date.now()-c;try{await Us.trackCommand(a,n,m)}catch{}try{await kn.recordTiming(a,"command_duration",m,{command:n});let d=globalThis.__perfStartNs;if(d){let g=Number(process.hrtime.bigint()-d)/1e6;await kn.recordTiming(a,"startup_time",g)}await kn.recordMemory(a,{command:n})}catch{}}p?.message&&console.log(p.message),f.end(),process.exit(p?.success?0:1)}catch(t){console.error("Error:",y(t)),process.env.DEBUG&&console.error(Wa(t)),f.end(),process.exit(1)}}function BE(n,e){if(!n.params)return null;let t=n.params.match(/<[^>]+>/g);if(!t||t.length===0)return null;if(e.length<t.length){let s=t.map(o=>o.slice(1,-1)).join(", "),r=n.usage.terminal||`prjct ${n.name} ${n.params}`;return wn("MISSING_PARAM",{message:`Missing required parameter: ${s}`,hint:`Usage: ${r}`})}return null}function zE(n){let e=W.getAll().map(r=>r.name),t=null,s=1/0;for(let r of e){let o=JE(n.toLowerCase(),r.toLowerCase());o<s&&(s=o,t=r)}return s<=2?t:null}function JE(n,e){let t=n.length,s=e.length,r=Array.from({length:t+1},()=>Array(s+1).fill(0));for(let o=0;o<=t;o++)r[o][0]=o;for(let o=0;o<=s;o++)r[0][o]=o;for(let o=1;o<=t;o++)for(let i=1;i<=s;i++)r[o][i]=n[o-1]===e[i-1]?r[o-1][i-1]:1+Math.min(r[o-1][i],r[o][i-1],r[o-1][i-1]);return r[t][s]}function qE(n,e){let t=[],s={};for(let r=0;r<e.length;r++){let o=e[r];if(o.startsWith("--")){let i=o.slice(2);r+1<e.length&&!e[r+1].startsWith("--")?s[i]=e[++r]:s[i]=!0}else t.push(o)}return{parsedArgs:t,options:s}}async function KE(n){let e=await bs(),t=$a.join(rw.homedir(),".claude","commands","p.md"),s=$a.join(rw.homedir(),".gemini","commands","p.toml"),[r,o,i,a]=await Promise.all([v(t),v(s),v($a.join(process.cwd(),".cursor","commands","sync.md")),v($a.join(process.cwd(),".cursor"))]),c=await Ln();if(console.log(`
|
|
1679
|
+
`)}function GE(n){return n?n==="commands"||n==="all"?ew():Zy(n):Xy()}var Ky,HE,sw=w(()=>{"use strict";vd();et();Ky=[{name:"start",description:"First-time setup wizard",example:"prjct start"},{name:"init",description:"Initialize project in current directory",example:"prjct init"},{name:"sync",description:"Sync project state and update context files",example:"prjct sync"},{name:"watch",description:"Auto-sync on file changes",example:"prjct watch",options:["--verbose","--debounce=<ms>","--interval=<sec>"]},{name:"hooks",description:"Manage git hooks for auto-sync",example:"prjct hooks install",subcommands:["install","uninstall","status"]},{name:"doctor",description:"Check system health and dependencies",example:"prjct doctor"},{name:"serve",description:"Start web dashboard server",example:"prjct serve [port]"},{name:"context",description:"Smart context filtering tools for AI",example:'prjct context files "add auth"',subcommands:["files","signatures","imports","recent","summary"]},{name:"enrich",description:"Prepare issue enrichment context from local code",example:'prjct enrich "PROJ-123 improve auth flow" --md'},{name:"linear",description:"Linear issue tracker MCP gateway",example:"prjct linear setup",subcommands:["setup","status","sync","list","get","create","update","start","done","comment"]},{name:"jira",description:"Jira issue tracker MCP gateway",example:"prjct jira setup",subcommands:["setup","status","sync","list","get","create","update","start","done","transition","comment"]},{name:"stop",description:"Stop the background daemon",example:"prjct stop",options:["--force"]},{name:"restart",description:"Restart the background daemon",example:"prjct restart"},{name:"uninstall",description:"Complete system removal of prjct",example:"prjct uninstall --backup",options:["--force","--backup","--dry-run","--keep-package"]}],HE=[{flag:"-q, --quiet",description:"Suppress all output (errors to stderr only)"},{flag:"-v, --version",description:"Show version and provider status"},{flag:"-h, --help",description:"Show this help message"}];l(Xy,"formatMainHelp");l(Yy,"formatTerminalCommandHelp");l(Qy,"formatAgentCommandHelp");l(Zy,"formatCommandHelp");l(ew,"formatCommandList");l(GE,"getHelp")});var nw=dw((sJ,WE)=>{WE.exports={name:"prjct-cli",version:"1.50.2",description:"Context layer for AI agents. Project context for Claude Code, Gemini CLI, and more.",main:"dist/bin/prjct.mjs",bin:{prjct:"bin/prjct"},publishConfig:{access:"public",registry:"https://registry.npmjs.org"},scripts:{build:"node scripts/build.js","build:node":"node scripts/build.js",release:"node scripts/release.js","release:patch":"node scripts/release.js patch","release:minor":"node scripts/release.js minor","release:major":"node scripts/release.js major",postinstall:"node scripts/postinstall.js",prepare:"lefthook install","update-commands":`bun -e "const installer = require('./core/infrastructure/command-installer'); installer.syncCommands().then(r => console.log('Commands updated:', r)).catch(e => console.error('Error:', e.message))"`,"install-global":"./scripts/install.sh",update:"./scripts/update.sh",test:"bun test","test:watch":"bun test --watch","test:coverage":"bun test --coverage",typecheck:"tsc --noEmit -p core/tsconfig.json","typecheck:watch":"tsc --noEmit -p core/tsconfig.json --watch",validate:"bun scripts/validate-commands.js",lint:"biome lint .","lint:fix":"biome lint --write .","lint:meta":"bun core/cli/lint-meta-commentary.ts",format:"biome format --write .","format:check":"biome format .",check:"biome check .","check:fix":"biome check --write ."},keywords:["claude-code","gemini-cli","ai-agents","context-layer","developer-tools","ai-assistant","productivity","mcp","llm","coding-agents"],author:"prjct.app",license:"MIT",dependencies:{"@clack/prompts":"^1.0.0","@hono/node-server":"^1.13.7","better-sqlite3":"^12.6.2",chalk:"^4.1.2",chokidar:"^5.0.0","date-fns":"^4.1.0",glob:"^13.0.1",hono:"^4.11.3","jsonc-parser":"^3.3.1",zod:"^3.24.1"},devDependencies:{"@biomejs/biome":"^2.3.13","@types/better-sqlite3":"^7.6.13","@types/bun":"latest","@types/chokidar":"^2.1.7",esbuild:"^0.25.0",lefthook:"^2.1.0",typescript:"^5.9.3"},repository:{type:"git",url:"git+https://github.com/jlopezlira/prjct-cli.git"},bugs:{url:"https://github.com/jlopezlira/prjct-cli/issues"},homepage:"https://prjct.app",packageManager:"bun@1.2.23",engines:{bun:">=1.0.0",node:">=18.0.0"},files:["assets/","bin/prjct","dist/","templates/","scripts/postinstall.js","scripts/ensure-bun.sh","scripts/install.sh","LICENSE","README.md","CHANGELOG.md"],prepublishOnly:"node scripts/build.js",trustedDependencies:["chalk"]}});var YE={};import rw from"node:os";import $a from"node:path";import Ge from"chalk";async function VE(){let[n,...e]=process.argv.slice(2);if(["-v","--version","version"].includes(n)){let t=await Promise.resolve().then(()=>pw(nw()));await KE(t.version),process.exit(0)}["-h","--help",void 0].includes(n)&&(XE(),process.exit(0)),f.start();try{let t=W.getByName(n);if(!t){let m=zE(n),d=m?`Did you mean 'prjct ${m}'? Run 'prjct --help' for all commands`:"Run 'prjct --help' to see available commands";f.failWithHint(wn("UNKNOWN_COMMAND",{message:`Unknown command: ${n}`,hint:d})),f.end(),process.exit(1)}if(t.deprecated){let m=t.replacedBy?`Use 'prjct ${t.replacedBy}' instead`:"Run 'prjct --help' to see available commands";f.failWithHint({message:`Command '${n}' is deprecated`,hint:m}),f.end(),process.exit(1)}t.implemented||(f.failWithHint({message:`Command '${n}' is not yet implemented`,hint:"Run 'prjct --help' to see available commands",docs:"https://github.com/jlopezlira/prjct-cli"}),f.end(),process.exit(1));let{parsedArgs:s,options:r}=qE(t,e),o=!process.stdin.isTTY||r.md===!0||r.json===!0;t.requiresLlm&&!o&&(f.failWithHint({message:`'prjct ${n}' requires an AI agent to process its output`,hint:`Use 'p. ${n}' inside Claude/Cursor, or add --md flag`}),f.end(),process.exit(1));let i=BE(t,s);i&&(f.failWithHint(i),f.end(),process.exit(1));let a=null,c=Date.now();try{a=await M.getProjectId(process.cwd()),a&&(await Us.expireIfStale(a),await Us.touch(a))}catch{}let u=new en,p;if(n==="design"){let m=s.join(" ");p=await u.design(m,r)}else if(n==="analyze")p=await u.analyze(r);else if(n==="cleanup")p=await u.cleanup(r);else if(n==="cleanup-projects")p=await u.cleanupProjects({dryRun:r["dry-run"]===!0,md:r.md===!0});else if(n==="setup")p=await u.setup(r);else if(n==="update")p=await u.update(r);else{let m=s.join(" ")||null,d=r.md===!0,h={task:l(k=>u.task(k,process.cwd(),{md:d}),"task"),done:l(()=>u.done(process.cwd(),{md:d}),"done"),next:l(()=>u.next(process.cwd(),{md:d}),"next"),pause:l(k=>u.pause(k||"",process.cwd(),{md:d}),"pause"),resume:l(k=>u.resume(k,process.cwd(),{md:d}),"resume"),init:l(k=>u.init(k),"init"),bug:l(k=>u.bug(k||"",process.cwd(),{md:d}),"bug"),idea:l(k=>u.idea(k||"",process.cwd(),{md:d}),"idea"),spec:l(k=>u.spec(k),"spec"),ship:l(k=>u.ship(k,process.cwd(),{md:d}),"ship"),workflow:l(k=>u.workflowPrefs(k,process.cwd(),{md:d}),"workflow"),sessions:l(()=>u.sessions(process.cwd(),{md:d,cleanup:r.cleanup===!0}),"sessions"),dash:l(k=>u.dash(k||"default",process.cwd(),{md:d}),"dash"),stats:l(()=>u.stats(process.cwd(),{json:r.json===!0,export:r.export===!0}),"stats"),status:l(()=>u.status(process.cwd(),{json:r.json===!0,md:d}),"status"),help:l(k=>u.help(k||""),"help"),perf:l(k=>u.perf(k||"7"),"perf"),velocity:l(k=>u.velocity(k||"0"),"velocity"),recover:l(()=>u.recover(),"recover"),undo:l(()=>u.undo(),"undo"),redo:l(()=>u.redo(),"redo"),history:l(()=>u.history(),"history"),enrich:l(k=>u.enrich(k,process.cwd(),{md:d,json:r.json===!0}),"enrich"),sync:l(()=>u.sync(process.cwd(),{preview:r.preview===!0||r["dry-run"]===!0,yes:r.yes===!0,json:r.json===!0,md:d,package:r.package?String(r.package):void 0,full:r.full===!0}),"sync"),diff:l(()=>u.diff(process.cwd(),{json:r.json===!0,md:d}),"diff"),seal:l(()=>u.seal(process.cwd(),{json:r.json===!0}),"seal"),rollback:l(()=>u.rollback(process.cwd(),{json:r.json===!0,md:d}),"rollback"),verify:l(()=>u.verify(process.cwd(),{json:r.json===!0,semantic:r.semantic===!0}),"verify"),"analysis-payload":l(()=>u.analysisPayload(process.cwd(),{json:r.json===!0,md:d}),"analysis-payload"),"analysis-save-llm":l(k=>u.saveLlmAnalysis(k||"",process.cwd(),{md:d}),"analysis-save-llm"),"analysis-llm":l(()=>u.getLlmAnalysis(process.cwd(),{json:r.json===!0,md:d}),"analysis-llm"),start:l(()=>u.start(),"start"),context:l(k=>u.context(k),"context"),login:l(()=>u.login({md:d,url:r.url?String(r.url):void 0}),"login"),logout:l(()=>u.logout(),"logout"),auth:l(k=>u.auth(k,{md:d}),"auth")}[n];if(h)p=await h(m);else throw new Error(`Command '${n}' has no handler`)}if(a){let m=Date.now()-c;try{await Us.trackCommand(a,n,m)}catch{}try{await kn.recordTiming(a,"command_duration",m,{command:n});let d=globalThis.__perfStartNs;if(d){let g=Number(process.hrtime.bigint()-d)/1e6;await kn.recordTiming(a,"startup_time",g)}await kn.recordMemory(a,{command:n})}catch{}}p?.message&&console.log(p.message),f.end(),process.exit(p?.success?0:1)}catch(t){console.error("Error:",y(t)),process.env.DEBUG&&console.error(Wa(t)),f.end(),process.exit(1)}}function BE(n,e){if(!n.params)return null;let t=n.params.match(/<[^>]+>/g);if(!t||t.length===0)return null;if(e.length<t.length){let s=t.map(o=>o.slice(1,-1)).join(", "),r=n.usage.terminal||`prjct ${n.name} ${n.params}`;return wn("MISSING_PARAM",{message:`Missing required parameter: ${s}`,hint:`Usage: ${r}`})}return null}function zE(n){let e=W.getAll().map(r=>r.name),t=null,s=1/0;for(let r of e){let o=JE(n.toLowerCase(),r.toLowerCase());o<s&&(s=o,t=r)}return s<=2?t:null}function JE(n,e){let t=n.length,s=e.length,r=Array.from({length:t+1},()=>Array(s+1).fill(0));for(let o=0;o<=t;o++)r[o][0]=o;for(let o=0;o<=s;o++)r[0][o]=o;for(let o=1;o<=t;o++)for(let i=1;i<=s;i++)r[o][i]=n[o-1]===e[i-1]?r[o-1][i-1]:1+Math.min(r[o-1][i],r[o][i-1],r[o-1][i-1]);return r[t][s]}function qE(n,e){let t=[],s={};for(let r=0;r<e.length;r++){let o=e[r];if(o.startsWith("--")){let i=o.slice(2);r+1<e.length&&!e[r+1].startsWith("--")?s[i]=e[++r]:s[i]=!0}else t.push(o)}return{parsedArgs:t,options:s}}async function KE(n){let e=await bs(),t=$a.join(rw.homedir(),".claude","commands","p.md"),s=$a.join(rw.homedir(),".gemini","commands","p.toml"),[r,o,i,a]=await Promise.all([v(t),v(s),v($a.join(process.cwd(),".cursor","commands","sync.md")),v($a.join(process.cwd(),".cursor"))]),c=await Ln();if(console.log(`
|
|
1680
1680
|
${Ge.cyan("p/")} prjct v${n}
|
|
1681
1681
|
${Ge.dim("Context layer for AI coding agents")}
|
|
1682
1682
|
|
package/dist/daemon/entry.mjs
CHANGED
|
@@ -349,7 +349,7 @@ var Wr=Object.defineProperty;var Rf=Object.getOwnPropertyDescriptor;var Af=Objec
|
|
|
349
349
|
name TEXT NOT NULL,
|
|
350
350
|
applied_at TEXT NOT NULL
|
|
351
351
|
)
|
|
352
|
-
`);let t=new Set(e.prepare("SELECT version FROM _migrations").all().map(s=>s.version));for(let s of xh)t.has(s.version)||e.transaction(()=>{s.up(e),e.prepare("INSERT INTO _migrations (version, name, applied_at) VALUES (?, ?, ?)").run(s.version,s.name,new Date().toISOString())})()}getMigrations(e){return this.getDb(e).prepare("SELECT * FROM _migrations ORDER BY version").all()}getSchemaVersion(e){return this.getDb(e).prepare("SELECT MAX(version) as version FROM _migrations").get()?.version??0}},P=new Bi,F=P});function Xr(r,e=!1){return e||r>=6?"high":r>=3?"medium":"low"}var H,cr=S(()=>{"use strict";H={CODE_STYLE:"code_style",NAMING_CONVENTION:"naming_convention",FILE_STRUCTURE:"file_structure",COMMIT_STYLE:"commit_style",BRANCH_NAMING:"branch_naming",TEST_BEHAVIOR:"test_behavior",SHIP_WORKFLOW:"ship_workflow",TECH_STACK:"tech_stack",ARCHITECTURE:"architecture",DEPENDENCIES:"dependencies",OUTPUT_VERBOSITY:"output_verbosity",CONFIRMATION_LEVEL:"confirmation_level",AGENT_PREFERENCE:"agent_preference"};l(Xr,"calculateConfidence")});var Ns,lr,ur,dr=S(()=>{"use strict";ce();cr();oe();Ns=class{static{l(this,"CachedStore")}_data=null;_loaded=!1;_projectId=null;getSubdirectory(){return null}getStoreKey(){let e=this.getFilename().replace(".json",""),t=this.getSubdirectory();return t?`memory:${t}:${e}`:`memory:${e}`}async load(e){if(this._loaded&&this._data&&this._projectId===e)return this._data;let t=this.getStoreKey(),s=F.getDoc(e,t);return s!==null?(this._data=s,this.afterLoad(this._data)):this._data=this.getDefault(),this._loaded=!0,this._projectId=e,this._data}afterLoad(e){}async save(e){if(!this._data)return;let t=this.getStoreKey();F.setDoc(e,t,this._data)}getData(){return this._data}setData(e){this._data=e}async update(e,t){let s=await this.load(e),n=t(s);return this._data=n,await this.save(e),n}isLoaded(e){return e?this._loaded&&this._projectId===e:this._loaded}reset(){this._data=null,this._loaded=!1,this._projectId=null}},lr=class{static{l(this,"SessionStore")}_sessionMemory=new Map;setSession(e,t){this._sessionMemory.set(e,{value:t,timestamp:Date.now()})}getSession(e){return this._sessionMemory.get(e)?.value}clearSession(){this._sessionMemory.clear()}},ur=class{static{l(this,"HistoryStore")}async appendHistory(e,t){let s={ts:v(),...t,type:t.type};F.appendEvent(e,`history.${t.type}`,s)}async getRecentHistory(e,t=20){return F.query(e,"SELECT data, timestamp FROM events WHERE type LIKE 'history.%' ORDER BY id DESC LIMIT ?",t).reverse().map(n=>JSON.parse(n.data))}}});var pr,Ji=S(()=>{"use strict";ce();cr();oe();dr();pr=class r extends Ns{static{l(this,"PatternStore")}static MAX_CONTEXTS=20;static ARCHIVE_AGE_DAYS=90;getFilename(){return"patterns.json"}getDefault(){return{version:1,decisions:{},preferences:{},workflows:{},counters:{}}}afterLoad(e){for(let t of Object.values(e.decisions))t.contexts.length>r.MAX_CONTEXTS&&(t.contexts=t.contexts.slice(-r.MAX_CONTEXTS))}async loadPatterns(e){return this.load(e)}async savePatterns(e){return this.save(e)}async recordDecision(e,t,s,n="",o={}){let i=await this.load(e),a=v();if(!i.decisions[t])i.decisions[t]={value:s,count:1,firstSeen:a,lastSeen:a,confidence:o.userConfirmed?"high":"low",contexts:[n].filter(Boolean),userConfirmed:o.userConfirmed||!1};else{let c=i.decisions[t];c.value===s?(c.count++,c.lastSeen=a,n&&!c.contexts.includes(n)&&(c.contexts.push(n),c.contexts.length>r.MAX_CONTEXTS&&(c.contexts=c.contexts.slice(-r.MAX_CONTEXTS))),o.userConfirmed&&(c.userConfirmed=!0),c.confidence=Xr(c.count,c.userConfirmed)):(c.value=s,c.count=1,c.lastSeen=a,c.userConfirmed=o.userConfirmed||!1,c.confidence=o.userConfirmed?"high":"low")}await this.save(e)}async confirmDecision(e,t){let n=(await this.load(e)).decisions[t];return n?(n.userConfirmed=!0,n.confidence="high",n.lastSeen=v(),await this.save(e),!0):!1}async getDecision(e,t){let n=(await this.load(e)).decisions[t];return!n||n.confidence==="low"?null:{value:n.value,confidence:n.confidence}}async hasPattern(e,t){return await this.getDecision(e,t)!==null}async recordWorkflow(e,t,s){let n=await this.load(e),o=v();if(!n.workflows[t])n.workflows[t]={...s,count:1,firstSeen:o,lastSeen:o,confidence:"low",userConfirmed:!1};else{let i=n.workflows[t];i.count++,i.lastSeen=o,i.confidence=Xr(i.count,i.userConfirmed)}await this.save(e)}async confirmWorkflow(e,t){let n=(await this.load(e)).workflows[t];return n?(n.userConfirmed=!0,n.confidence="high",n.lastSeen=v(),await this.save(e),!0):!1}async getWorkflow(e,t){let n=(await this.load(e)).workflows[t];return!n||n.count<3?null:n}async setPreference(e,t,s,n={}){let o=await this.load(e),i=o.preferences[t],a=i?i.observationCount+1:1,c=n.userConfirmed||i?.userConfirmed||!1;o.preferences[t]={value:s,updatedAt:v(),confidence:Xr(a,c),observationCount:a,userConfirmed:c},await this.save(e)}async confirmPreference(e,t){let n=(await this.load(e)).preferences[t];return n?(n.userConfirmed=!0,n.confidence="high",n.updatedAt=v(),await this.save(e),!0):!1}async getPreference(e,t,s=null){return(await this.load(e)).preferences[t]?.value??s}async getPatternsSummary(e){let t=await this.load(e);return{decisions:Object.keys(t.decisions).length,learnedDecisions:Object.values(t.decisions).filter(s=>s.confidence!=="low").length,workflows:Object.keys(t.workflows).length,preferences:Object.keys(t.preferences).length}}async archiveStaleDecisions(e){let t=await this.load(e),s=Date.now(),n=r.ARCHIVE_AGE_DAYS*24*60*60*1e3,o=[];for(let[a,c]of Object.entries(t.decisions)){let u=new Date(c.lastSeen).getTime();s-u>n&&o.push(a)}if(o.length===0)return 0;let i=F.getDoc(e,"memory:patterns-archive")??{};for(let a of o)i[a]=t.decisions[a],delete t.decisions[a];return F.setDoc(e,"memory:patterns-archive",i),await this.save(e),o.length}}});import Ah from"node:crypto";import{homedir as Dh}from"node:os";import{join as jh}from"node:path";function ye(){return Ah.randomUUID()}var FC,It=S(()=>{"use strict";l(ye,"generateUUID");FC=jh(Dh(),".prjct-cli","projects")});var Ls,zi=S(()=>{"use strict";It();cr();oe();dr();Ls=class extends Ns{static{l(this,"SemanticMemories")}getFilename(){return"memories.json"}getDefault(){return{version:1,memories:[],index:this._createEmptyIndex()}}afterLoad(e){this._normalizeIndex(e)}_createEmptyIndex(){let e=Object.values(H),t={};for(let s of e)t[s]=[];return t}_normalizeIndex(e){let t=Object.values(H);for(let s of t)e.index[s]||(e.index[s]=[])}_coerceTags(e){let t=new Set(Object.values(H));return e.filter(s=>t.has(s))}async loadMemories(e){return this.load(e)}async saveMemories(e){return this.save(e)}async createMemory(e,{title:t,content:s,tags:n=[],userTriggered:o=!1}){let i=await this.load(e),a=this._coerceTags(n),c=v(),u={id:ye(),title:t,content:s,tags:a,userTriggered:o,createdAt:c,updatedAt:c};i.memories.push(u);for(let p of a)i.index[p].push(u.id);return await this.save(e),u.id}async updateMemory(e,t,s){let n=await this.load(e),o=n.memories.findIndex(c=>c.id===t);if(o===-1)return!1;let i=n.memories[o],a=i.tags||[];if(s.title&&(i.title=s.title),s.content&&(i.content=s.content),s.tags){let c=this._coerceTags(s.tags);for(let u of a)n.index[u]=n.index[u].filter(p=>p!==t);for(let u of c)n.index[u].push(t);i.tags=c}return i.updatedAt=v(),await this.save(e),!0}async deleteMemory(e,t){let s=await this.load(e),n=s.memories.findIndex(i=>i.id===t);if(n===-1)return!1;let o=s.memories[n];for(let i of o.tags||[])s.index[i]&&(s.index[i]=s.index[i].filter(a=>a!==t));return s.memories.splice(n,1),await this.save(e),!0}async findByTags(e,t,s=!1){let n=await this.load(e),o=this._coerceTags(t);if(s)return n.memories.filter(i=>o.every(a=>(i.tags||[]).includes(a)));{let i=new Set;for(let a of o){let c=n.index[a];for(let u of c)i.add(u)}return n.memories.filter(a=>i.has(a.id))}}async searchMemories(e,t){let s=await this.load(e),n=t.toLowerCase();return s.memories.filter(o=>o.title.toLowerCase().includes(n)||o.content.toLowerCase().includes(n))}async getRelevantMemories(e,t,s=5){return(await this.load(e)).memories.map(i=>{let a=0,c=this._extractContextTags(t);for(let d of i.tags||[])c.includes(d)&&(a+=10);let p=(Date.now()-new Date(i.updatedAt).getTime())/(1e3*60*60*24);a+=Math.max(0,5-p),i.userTriggered&&(a+=5);let m=this._extractKeywords(t);for(let d of m)i.content.toLowerCase().includes(d)&&(a+=2),i.title.toLowerCase().includes(d)&&(a+=3);return{...i,_score:a}}).filter(i=>i._score>0).sort((i,a)=>a._score-i._score).slice(0,s).map(({_score:i,...a})=>a)}async getRelevantMemoriesWithMetrics(e,t){let s=await this.load(e),n=s.memories.length;if(n===0)return{memories:[],metrics:{totalMemories:0,memoriesConsidered:0,memoriesReturned:0,filteringRatio:0,avgRelevanceScore:0}};let o=t.maxResults??10,i=t.minRelevance??10,c=s.memories.map(d=>{let g={domainMatch:0,tagMatch:0,recency:0,confidence:0,keywords:0,userTriggered:0};if(t.taskDomain&&(g.domainMatch=this._getSemanticDomainScore(t.taskDomain,d.tags||[])),t.commandName){let T=this._getCommandTags(t.commandName),E=(d.tags||[]).filter(M=>T.includes(M));g.tagMatch=Math.min(20,E.length*8)}let k=(Date.now()-new Date(d.updatedAt).getTime())/(1e3*60*60*24);if(g.recency=Math.max(0,Math.round(15-k*.5)),d.confidence?g.confidence=d.confidence==="high"?20:d.confidence==="medium"?12:5:d.observationCount&&(g.confidence=Math.min(20,d.observationCount*3)),t.taskDescription){let T=this._extractKeywordsFromText(t.taskDescription),E=0;for(let M of T)d.content.toLowerCase().includes(M)&&(E+=2),d.title.toLowerCase().includes(M)&&(E+=3);g.keywords=Math.min(15,E)}d.userTriggered&&(g.userTriggered=5);let w=g.domainMatch+g.tagMatch+g.recency+g.confidence+g.keywords+g.userTriggered;return{...d,relevanceScore:w,scoreBreakdown:g}}).filter(d=>d.relevanceScore>=i),p=c.sort((d,g)=>g.relevanceScore-d.relevanceScore).slice(0,o),m=p.length>0?Math.round(p.reduce((d,g)=>d+g.relevanceScore,0)/p.length):0;return{memories:p,metrics:{totalMemories:n,memoriesConsidered:c.length,memoriesReturned:p.length,filteringRatio:n>0?p.length/n:0,avgRelevanceScore:m}}}_getSemanticDomainScore(e,t){return 0}_getCommandTags(e){return{ship:[H.COMMIT_STYLE,H.SHIP_WORKFLOW,H.TEST_BEHAVIOR],feature:[H.ARCHITECTURE,H.CODE_STYLE],done:[H.SHIP_WORKFLOW],analyze:[H.TECH_STACK,H.ARCHITECTURE],spec:[H.ARCHITECTURE,H.CODE_STYLE],task:[H.BRANCH_NAMING,H.CODE_STYLE],sync:[H.TECH_STACK,H.ARCHITECTURE,H.DEPENDENCIES],test:[H.TEST_BEHAVIOR],bug:[H.CODE_STYLE,H.TEST_BEHAVIOR]}[e]||[]}_extractKeywordsFromText(e){let t=e.toLowerCase().split(/\s+/),s=new Set(["the","a","an","is","are","to","for","and","or","in","on","at","by","with","from","as","it","this","that","be","have","has"]);return t.filter(n=>n.length>2&&!s.has(n))}_extractContextTags(e){let t=[],s={ship:[H.COMMIT_STYLE,H.SHIP_WORKFLOW,H.TEST_BEHAVIOR],feature:[H.ARCHITECTURE,H.CODE_STYLE],done:[H.SHIP_WORKFLOW],analyze:[H.TECH_STACK,H.ARCHITECTURE],spec:[H.ARCHITECTURE,H.CODE_STYLE]};return e.commandName&&s[e.commandName]&&t.push(...s[e.commandName]),t}_extractKeywords(e){let t=[];e.params?.description&&t.push(...e.params.description.toLowerCase().split(/\s+/)),e.params?.feature&&t.push(...e.params.feature.toLowerCase().split(/\s+/));let s=["the","a","an","is","are","to","for","and","or","in"];return t.filter(n=>n.length>2&&!s.includes(n))}async autoRemember(e,t,s,n=""){let i={commit_footer:[H.COMMIT_STYLE],branch_naming:[H.BRANCH_NAMING],test_before_ship:[H.TEST_BEHAVIOR,H.SHIP_WORKFLOW],preferred_agent:[H.AGENT_PREFERENCE],code_style:[H.CODE_STYLE],verbosity:[H.OUTPUT_VERBOSITY]}[t]||[],a=await this.searchMemories(e,t);a.length>0?await this.updateMemory(e,a[0].id,{content:`${t}: ${s}`,tags:i}):await this.createMemory(e,{title:`Preference: ${t}`,content:`${t}: ${s}${n?`
|
|
352
|
+
`);let t=new Set(e.prepare("SELECT version FROM _migrations").all().map(s=>s.version));for(let s of xh)t.has(s.version)||e.transaction(()=>{s.up(e),e.prepare("INSERT INTO _migrations (version, name, applied_at) VALUES (?, ?, ?)").run(s.version,s.name,new Date().toISOString())})()}getMigrations(e){return this.getDb(e).prepare("SELECT * FROM _migrations ORDER BY version").all()}getSchemaVersion(e){return this.getDb(e).prepare("SELECT MAX(version) as version FROM _migrations").get()?.version??0}},P=new Bi,F=P});function Xr(r,e=!1){return e||r>=6?"high":r>=3?"medium":"low"}var H,cr=S(()=>{"use strict";H={CODE_STYLE:"code_style",NAMING_CONVENTION:"naming_convention",FILE_STRUCTURE:"file_structure",COMMIT_STYLE:"commit_style",BRANCH_NAMING:"branch_naming",TEST_BEHAVIOR:"test_behavior",SHIP_WORKFLOW:"ship_workflow",TECH_STACK:"tech_stack",ARCHITECTURE:"architecture",DEPENDENCIES:"dependencies",OUTPUT_VERBOSITY:"output_verbosity",CONFIRMATION_LEVEL:"confirmation_level",AGENT_PREFERENCE:"agent_preference"};l(Xr,"calculateConfidence")});var Ns,lr,ur,dr=S(()=>{"use strict";ce();cr();oe();Ns=class{static{l(this,"CachedStore")}_data=null;_loaded=!1;_projectId=null;getSubdirectory(){return null}getStoreKey(){let e=this.getFilename().replace(".json",""),t=this.getSubdirectory();return t?`memory:${t}:${e}`:`memory:${e}`}async load(e){if(this._loaded&&this._data&&this._projectId===e)return this._data;let t=this.getStoreKey(),s=F.getDoc(e,t);return s!==null?(this._data=s,this.afterLoad(this._data)):this._data=this.getDefault(),this._loaded=!0,this._projectId=e,this._data}afterLoad(e){}async save(e){if(!this._data)return;let t=this.getStoreKey();F.setDoc(e,t,this._data)}getData(){return this._data}setData(e){this._data=e}async update(e,t){let s=await this.load(e),n=t(s);return this._data=n,await this.save(e),n}isLoaded(e){return e?this._loaded&&this._projectId===e:this._loaded}reset(){this._data=null,this._loaded=!1,this._projectId=null}},lr=class{static{l(this,"SessionStore")}_sessionMemory=new Map;setSession(e,t){this._sessionMemory.set(e,{value:t,timestamp:Date.now()})}getSession(e){return this._sessionMemory.get(e)?.value}clearSession(){this._sessionMemory.clear()}},ur=class{static{l(this,"HistoryStore")}async appendHistory(e,t){let s={ts:v(),...t,type:t.type};F.appendEvent(e,`history.${t.type}`,s)}async getRecentHistory(e,t=20){return F.query(e,"SELECT data, timestamp FROM events WHERE type LIKE 'history.%' ORDER BY id DESC LIMIT ?",t).reverse().map(n=>JSON.parse(n.data))}}});var pr,Ji=S(()=>{"use strict";ce();cr();oe();dr();pr=class r extends Ns{static{l(this,"PatternStore")}static MAX_CONTEXTS=20;static ARCHIVE_AGE_DAYS=90;getFilename(){return"patterns.json"}getDefault(){return{version:1,decisions:{},preferences:{},workflows:{},counters:{}}}afterLoad(e){for(let t of Object.values(e.decisions))Array.isArray(t.contexts)||(t.contexts=[]),t.contexts.length>r.MAX_CONTEXTS&&(t.contexts=t.contexts.slice(-r.MAX_CONTEXTS))}async loadPatterns(e){return this.load(e)}async savePatterns(e){return this.save(e)}async recordDecision(e,t,s,n="",o={}){let i=await this.load(e),a=v();if(!i.decisions[t])i.decisions[t]={value:s,count:1,firstSeen:a,lastSeen:a,confidence:o.userConfirmed?"high":"low",contexts:[n].filter(Boolean),userConfirmed:o.userConfirmed||!1};else{let c=i.decisions[t];c.value===s?(c.count++,c.lastSeen=a,n&&!c.contexts.includes(n)&&(c.contexts.push(n),c.contexts.length>r.MAX_CONTEXTS&&(c.contexts=c.contexts.slice(-r.MAX_CONTEXTS))),o.userConfirmed&&(c.userConfirmed=!0),c.confidence=Xr(c.count,c.userConfirmed)):(c.value=s,c.count=1,c.lastSeen=a,c.userConfirmed=o.userConfirmed||!1,c.confidence=o.userConfirmed?"high":"low")}await this.save(e)}async confirmDecision(e,t){let n=(await this.load(e)).decisions[t];return n?(n.userConfirmed=!0,n.confidence="high",n.lastSeen=v(),await this.save(e),!0):!1}async getDecision(e,t){let n=(await this.load(e)).decisions[t];return!n||n.confidence==="low"?null:{value:n.value,confidence:n.confidence}}async hasPattern(e,t){return await this.getDecision(e,t)!==null}async recordWorkflow(e,t,s){let n=await this.load(e),o=v();if(!n.workflows[t])n.workflows[t]={...s,count:1,firstSeen:o,lastSeen:o,confidence:"low",userConfirmed:!1};else{let i=n.workflows[t];i.count++,i.lastSeen=o,i.confidence=Xr(i.count,i.userConfirmed)}await this.save(e)}async confirmWorkflow(e,t){let n=(await this.load(e)).workflows[t];return n?(n.userConfirmed=!0,n.confidence="high",n.lastSeen=v(),await this.save(e),!0):!1}async getWorkflow(e,t){let n=(await this.load(e)).workflows[t];return!n||n.count<3?null:n}async setPreference(e,t,s,n={}){let o=await this.load(e),i=o.preferences[t],a=i?i.observationCount+1:1,c=n.userConfirmed||i?.userConfirmed||!1;o.preferences[t]={value:s,updatedAt:v(),confidence:Xr(a,c),observationCount:a,userConfirmed:c},await this.save(e)}async confirmPreference(e,t){let n=(await this.load(e)).preferences[t];return n?(n.userConfirmed=!0,n.confidence="high",n.updatedAt=v(),await this.save(e),!0):!1}async getPreference(e,t,s=null){return(await this.load(e)).preferences[t]?.value??s}async getPatternsSummary(e){let t=await this.load(e);return{decisions:Object.keys(t.decisions).length,learnedDecisions:Object.values(t.decisions).filter(s=>s.confidence!=="low").length,workflows:Object.keys(t.workflows).length,preferences:Object.keys(t.preferences).length}}async archiveStaleDecisions(e){let t=await this.load(e),s=Date.now(),n=r.ARCHIVE_AGE_DAYS*24*60*60*1e3,o=[];for(let[a,c]of Object.entries(t.decisions)){let u=new Date(c.lastSeen).getTime();s-u>n&&o.push(a)}if(o.length===0)return 0;let i=F.getDoc(e,"memory:patterns-archive")??{};for(let a of o)i[a]=t.decisions[a],delete t.decisions[a];return F.setDoc(e,"memory:patterns-archive",i),await this.save(e),o.length}}});import Ah from"node:crypto";import{homedir as Dh}from"node:os";import{join as jh}from"node:path";function ye(){return Ah.randomUUID()}var FC,It=S(()=>{"use strict";l(ye,"generateUUID");FC=jh(Dh(),".prjct-cli","projects")});var Ls,zi=S(()=>{"use strict";It();cr();oe();dr();Ls=class extends Ns{static{l(this,"SemanticMemories")}getFilename(){return"memories.json"}getDefault(){return{version:1,memories:[],index:this._createEmptyIndex()}}afterLoad(e){this._normalizeIndex(e)}_createEmptyIndex(){let e=Object.values(H),t={};for(let s of e)t[s]=[];return t}_normalizeIndex(e){let t=Object.values(H);for(let s of t)e.index[s]||(e.index[s]=[])}_coerceTags(e){let t=new Set(Object.values(H));return e.filter(s=>t.has(s))}async loadMemories(e){return this.load(e)}async saveMemories(e){return this.save(e)}async createMemory(e,{title:t,content:s,tags:n=[],userTriggered:o=!1}){let i=await this.load(e),a=this._coerceTags(n),c=v(),u={id:ye(),title:t,content:s,tags:a,userTriggered:o,createdAt:c,updatedAt:c};i.memories.push(u);for(let p of a)i.index[p].push(u.id);return await this.save(e),u.id}async updateMemory(e,t,s){let n=await this.load(e),o=n.memories.findIndex(c=>c.id===t);if(o===-1)return!1;let i=n.memories[o],a=i.tags||[];if(s.title&&(i.title=s.title),s.content&&(i.content=s.content),s.tags){let c=this._coerceTags(s.tags);for(let u of a)n.index[u]=n.index[u].filter(p=>p!==t);for(let u of c)n.index[u].push(t);i.tags=c}return i.updatedAt=v(),await this.save(e),!0}async deleteMemory(e,t){let s=await this.load(e),n=s.memories.findIndex(i=>i.id===t);if(n===-1)return!1;let o=s.memories[n];for(let i of o.tags||[])s.index[i]&&(s.index[i]=s.index[i].filter(a=>a!==t));return s.memories.splice(n,1),await this.save(e),!0}async findByTags(e,t,s=!1){let n=await this.load(e),o=this._coerceTags(t);if(s)return n.memories.filter(i=>o.every(a=>(i.tags||[]).includes(a)));{let i=new Set;for(let a of o){let c=n.index[a];for(let u of c)i.add(u)}return n.memories.filter(a=>i.has(a.id))}}async searchMemories(e,t){let s=await this.load(e),n=t.toLowerCase();return s.memories.filter(o=>o.title.toLowerCase().includes(n)||o.content.toLowerCase().includes(n))}async getRelevantMemories(e,t,s=5){return(await this.load(e)).memories.map(i=>{let a=0,c=this._extractContextTags(t);for(let d of i.tags||[])c.includes(d)&&(a+=10);let p=(Date.now()-new Date(i.updatedAt).getTime())/(1e3*60*60*24);a+=Math.max(0,5-p),i.userTriggered&&(a+=5);let m=this._extractKeywords(t);for(let d of m)i.content.toLowerCase().includes(d)&&(a+=2),i.title.toLowerCase().includes(d)&&(a+=3);return{...i,_score:a}}).filter(i=>i._score>0).sort((i,a)=>a._score-i._score).slice(0,s).map(({_score:i,...a})=>a)}async getRelevantMemoriesWithMetrics(e,t){let s=await this.load(e),n=s.memories.length;if(n===0)return{memories:[],metrics:{totalMemories:0,memoriesConsidered:0,memoriesReturned:0,filteringRatio:0,avgRelevanceScore:0}};let o=t.maxResults??10,i=t.minRelevance??10,c=s.memories.map(d=>{let g={domainMatch:0,tagMatch:0,recency:0,confidence:0,keywords:0,userTriggered:0};if(t.taskDomain&&(g.domainMatch=this._getSemanticDomainScore(t.taskDomain,d.tags||[])),t.commandName){let T=this._getCommandTags(t.commandName),E=(d.tags||[]).filter(M=>T.includes(M));g.tagMatch=Math.min(20,E.length*8)}let k=(Date.now()-new Date(d.updatedAt).getTime())/(1e3*60*60*24);if(g.recency=Math.max(0,Math.round(15-k*.5)),d.confidence?g.confidence=d.confidence==="high"?20:d.confidence==="medium"?12:5:d.observationCount&&(g.confidence=Math.min(20,d.observationCount*3)),t.taskDescription){let T=this._extractKeywordsFromText(t.taskDescription),E=0;for(let M of T)d.content.toLowerCase().includes(M)&&(E+=2),d.title.toLowerCase().includes(M)&&(E+=3);g.keywords=Math.min(15,E)}d.userTriggered&&(g.userTriggered=5);let w=g.domainMatch+g.tagMatch+g.recency+g.confidence+g.keywords+g.userTriggered;return{...d,relevanceScore:w,scoreBreakdown:g}}).filter(d=>d.relevanceScore>=i),p=c.sort((d,g)=>g.relevanceScore-d.relevanceScore).slice(0,o),m=p.length>0?Math.round(p.reduce((d,g)=>d+g.relevanceScore,0)/p.length):0;return{memories:p,metrics:{totalMemories:n,memoriesConsidered:c.length,memoriesReturned:p.length,filteringRatio:n>0?p.length/n:0,avgRelevanceScore:m}}}_getSemanticDomainScore(e,t){return 0}_getCommandTags(e){return{ship:[H.COMMIT_STYLE,H.SHIP_WORKFLOW,H.TEST_BEHAVIOR],feature:[H.ARCHITECTURE,H.CODE_STYLE],done:[H.SHIP_WORKFLOW],analyze:[H.TECH_STACK,H.ARCHITECTURE],spec:[H.ARCHITECTURE,H.CODE_STYLE],task:[H.BRANCH_NAMING,H.CODE_STYLE],sync:[H.TECH_STACK,H.ARCHITECTURE,H.DEPENDENCIES],test:[H.TEST_BEHAVIOR],bug:[H.CODE_STYLE,H.TEST_BEHAVIOR]}[e]||[]}_extractKeywordsFromText(e){let t=e.toLowerCase().split(/\s+/),s=new Set(["the","a","an","is","are","to","for","and","or","in","on","at","by","with","from","as","it","this","that","be","have","has"]);return t.filter(n=>n.length>2&&!s.has(n))}_extractContextTags(e){let t=[],s={ship:[H.COMMIT_STYLE,H.SHIP_WORKFLOW,H.TEST_BEHAVIOR],feature:[H.ARCHITECTURE,H.CODE_STYLE],done:[H.SHIP_WORKFLOW],analyze:[H.TECH_STACK,H.ARCHITECTURE],spec:[H.ARCHITECTURE,H.CODE_STYLE]};return e.commandName&&s[e.commandName]&&t.push(...s[e.commandName]),t}_extractKeywords(e){let t=[];e.params?.description&&t.push(...e.params.description.toLowerCase().split(/\s+/)),e.params?.feature&&t.push(...e.params.feature.toLowerCase().split(/\s+/));let s=["the","a","an","is","are","to","for","and","or","in"];return t.filter(n=>n.length>2&&!s.includes(n))}async autoRemember(e,t,s,n=""){let i={commit_footer:[H.COMMIT_STYLE],branch_naming:[H.BRANCH_NAMING],test_before_ship:[H.TEST_BEHAVIOR,H.SHIP_WORKFLOW],preferred_agent:[H.AGENT_PREFERENCE],code_style:[H.CODE_STYLE],verbosity:[H.OUTPUT_VERBOSITY]}[t]||[],a=await this.searchMemories(e,t);a.length>0?await this.updateMemory(e,a[0].id,{content:`${t}: ${s}`,tags:i}):await this.createMemory(e,{title:`Preference: ${t}`,content:`${t}: ${s}${n?`
|
|
353
353
|
Context: ${n}`:""}`,tags:i,userTriggered:!0})}async getAllMemories(e){return(await this.load(e)).memories}async getMemoryStats(e){let t=await this.load(e),s={};for(let[n,o]of Object.entries(t.index))s[n]=o.length;return{totalMemories:t.memories.length,userTriggered:t.memories.filter(n=>n.userTriggered).length,tagCounts:s,oldestMemory:t.memories[0]?.createdAt,newestMemory:t.memories[t.memories.length-1]?.createdAt}}}});var qi,Ih,at,mr=S(()=>{"use strict";dr();Ji();zi();dr();Ji();zi();qi=class{static{l(this,"MemorySystem")}_semanticMemories;_patternStore;_historyStore;_sessionStore;constructor(){this._semanticMemories=new Ls,this._patternStore=new pr,this._historyStore=new ur,this._sessionStore=new lr}loadMemories(e){return this._semanticMemories.loadMemories(e)}saveMemories(e){return this._semanticMemories.saveMemories(e)}createMemory(e,t){return this._semanticMemories.createMemory(e,t)}updateMemory(e,t,s){return this._semanticMemories.updateMemory(e,t,s)}deleteMemory(e,t){return this._semanticMemories.deleteMemory(e,t)}findByTags(e,t,s){return this._semanticMemories.findByTags(e,t,s)}searchMemories(e,t){return this._semanticMemories.searchMemories(e,t)}getRelevantMemories(e,t,s){return this._semanticMemories.getRelevantMemories(e,t,s)}autoRemember(e,t,s,n){return this._semanticMemories.autoRemember(e,t,s,n)}getAllMemories(e){return this._semanticMemories.getAllMemories(e)}getMemoryStats(e){return this._semanticMemories.getMemoryStats(e)}getRelevantMemoriesWithMetrics(e,t){return this._semanticMemories.getRelevantMemoriesWithMetrics(e,t)}setSession(e,t){this._sessionStore.setSession(e,t)}getSession(e){return this._sessionStore.getSession(e)}clearSession(){this._sessionStore.clearSession()}loadPatterns(e){return this._patternStore.loadPatterns(e)}savePatterns(e){return this._patternStore.savePatterns(e)}recordDecision(e,t,s,n){return this._patternStore.recordDecision(e,t,s,n)}getDecision(e,t){return this._patternStore.getDecision(e,t)}hasPattern(e,t){return this._patternStore.hasPattern(e,t)}recordWorkflow(e,t,s){return this._patternStore.recordWorkflow(e,t,s)}getWorkflow(e,t){return this._patternStore.getWorkflow(e,t)}setPreference(e,t,s,n){return this._patternStore.setPreference(e,t,s,n)}getPreference(e,t,s){return this._patternStore.getPreference(e,t,s)}confirmPreference(e,t){return this._patternStore.confirmPreference(e,t)}confirmDecision(e,t){return this._patternStore.confirmDecision(e,t)}confirmWorkflow(e,t){return this._patternStore.confirmWorkflow(e,t)}getPatternsSummary(e){return this._patternStore.getPatternsSummary(e)}archiveStaleDecisions(e){return this._patternStore.archiveStaleDecisions(e)}appendHistory(e,t){return this._historyStore.appendHistory(e,t)}getRecentHistory(e,t){return this._historyStore.getRecentHistory(e,t)}async getSmartDecision(e,t){let s=this.getSession(`decision:${t}`);if(s!==void 0)return s;let n=await this.getDecision(e,t);return n?n.value:null}async learnDecision(e,t,s,n=""){this.setSession(`decision:${t}`,s),await this.recordDecision(e,t,s,n),await this.appendHistory(e,{type:"decision",key:t,value:s,context:n})}resetState(){this._sessionStore.clearSession(),this._semanticMemories.reset(),this._patternStore.reset()}},Ih=new qi,at=Ih});import $t from"node:fs/promises";import _t from"node:path";var Ki,$h,Je,vu=S(()=>{"use strict";V();Ue();q();Ki=class{static{l(this,"CodebaseAnalyzer")}projectPath=null;init(e=process.cwd()){this.projectPath=e}async readPackageJson(){try{let e=_t.join(this.projectPath,"package.json"),t=await $t.readFile(e,"utf-8");return JSON.parse(t)}catch(e){if(R(e)||e instanceof SyntaxError)return null;throw e}}async readCargoToml(){try{let e=_t.join(this.projectPath,"Cargo.toml");return await $t.readFile(e,"utf-8")}catch(e){if(R(e))return null;throw e}}async readRequirements(){try{let e=_t.join(this.projectPath,"requirements.txt");return await $t.readFile(e,"utf-8")}catch(e){if(R(e))return null;throw e}}async readGoMod(){try{let e=_t.join(this.projectPath,"go.mod");return await $t.readFile(e,"utf-8")}catch(e){if(R(e))return null;throw e}}async readGemfile(){try{let e=_t.join(this.projectPath,"Gemfile");return await $t.readFile(e,"utf-8")}catch(e){if(R(e))return null;throw e}}async readMixExs(){try{let e=_t.join(this.projectPath,"mix.exs");return await $t.readFile(e,"utf-8")}catch(e){if(R(e))return null;throw e}}async readPomXml(){try{let e=_t.join(this.projectPath,"pom.xml");return await $t.readFile(e,"utf-8")}catch(e){if(R(e))return null;throw e}}async readComposerJson(){try{let e=_t.join(this.projectPath,"composer.json"),t=await $t.readFile(e,"utf-8");return JSON.parse(t)}catch(e){if(R(e)||e instanceof SyntaxError)return null;throw e}}async readPyprojectToml(){try{let e=_t.join(this.projectPath,"pyproject.toml");return await $t.readFile(e,"utf-8")}catch(e){if(R(e))return null;throw e}}async getFileExtensions(){try{let{stdout:e}=await N('find . -type f ! -path "*/node_modules/*" ! -path "*/.git/*" ! -path "*/dist/*" ! -path "*/.next/*" | sed "s/.*\\./\\./" | sort | uniq -c | sort -rn',{cwd:this.projectPath}),t={};return e.trim().split(`
|
|
354
354
|
`).filter(Boolean).forEach(s=>{let n=s.trim().match(/^\s*(\d+)\s+(\.\w+)$/);n&&(t[n[2]]=parseInt(n[1],10))}),t}catch{return{}}}async listConfigFiles(){try{let e=await $t.readdir(this.projectPath),t=[/^package\.json$/,/^Cargo\.toml$/,/^go\.mod$/,/^requirements\.txt$/,/^Gemfile$/,/^mix\.exs$/,/^pom\.xml$/,/^composer\.json$/,/^pyproject\.toml$/,/^tsconfig.*\.json$/,/^\..*rc(\.json|\.js|\.cjs)?$/,/^Dockerfile$/,/^docker-compose.*\.ya?ml$/,/^\.env.*$/];return e.filter(s=>t.some(n=>n.test(s)))}catch(e){if(R(e))return[];throw e}}async listDirectories(){try{return(await $t.readdir(this.projectPath,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name).filter(t=>!t.startsWith(".")&&t!=="node_modules")}catch(e){if(R(e))return[];throw e}}async getGitLog(e=50){try{let{stdout:t}=await N(`git log -n ${e} --pretty=format:"%h|%an|%ar|%s"`,{cwd:this.projectPath});return t}catch{return""}}async getGitStats(){try{let{stdout:e}=await N("git rev-list --count HEAD",{cwd:this.projectPath}),{stdout:t}=await N('git log --format="%an" | sort -u | wc -l',{cwd:this.projectPath}),{stdout:s}=await N('git log --reverse --pretty=format:"%ar" | head -1',{cwd:this.projectPath});return{totalCommits:parseInt(e.trim(),10)||0,contributors:parseInt(t.trim(),10)||0,age:s.trim()||"unknown"}}catch{return{totalCommits:0,contributors:0,age:"unknown"}}}async countFiles(){try{let{stdout:e}=await N('find . -type f ! -path "*/node_modules/*" ! -path "*/.git/*" ! -path "*/dist/*" | wc -l',{cwd:this.projectPath});return parseInt(e.trim(),10)||0}catch{return 0}}async fileExists(e){return C(_t.join(this.projectPath,e))}async readFile(e){try{let t=_t.join(this.projectPath,e);return await $t.readFile(t,"utf-8")}catch(t){if(R(t))return null;throw t}}async findFiles(e){try{let{stdout:t}=await N(`find . -type f -name "${e}" ! -path "*/node_modules/*" ! -path "*/.git/*"`,{cwd:this.projectPath});return t.trim().split(`
|
|
355
355
|
`).filter(Boolean)}catch{return[]}}},$h=new Ki,Je=$h});import{z as Te}from"zod";function Mh(r){return r instanceof dn}function ue(r){return Mh(r)||r instanceof Error?r.message:typeof r=="string"?r:"Unknown error"}var pn,dP,pP,mP,gP,fP,hP,dn,Yr,Qr,gr,ss=S(()=>{"use strict";pn={create(r,e){class t extends Error{static{l(this,"TypedError")}errorName;data;isOperational=!0;constructor(n){let o=e.parse(n);super(`${r}: ${JSON.stringify(o)}`),this.name=r,this.errorName=r,this.data=o,Error.captureStackTrace?.(this,this.constructor)}static throw(n){throw new t(n)}static is(n){return n instanceof t&&n.errorName===r}static create(n){return new t(n)}}return t}},dP=pn.create("FileError",Te.object({path:Te.string(),operation:Te.enum(["read","write","delete","create","copy"]),reason:Te.string().optional()})),pP=pn.create("ValidationError",Te.object({field:Te.string(),expected:Te.string(),received:Te.string().optional(),message:Te.string().optional()})),mP=pn.create("PermissionError",Te.object({action:Te.string(),resource:Te.string(),reason:Te.string().optional()})),gP=pn.create("TaskError",Te.object({taskId:Te.string().optional(),operation:Te.enum(["create","update","complete","pause","resume","delete"]),reason:Te.string()})),fP=pn.create("SessionError",Te.object({sessionId:Te.string().optional(),reason:Te.string()})),hP=pn.create("SyncError",Te.object({projectId:Te.string().optional(),operation:Te.enum(["push","pull","auth","connect"]),reason:Te.string()})),dn=class extends Error{static{l(this,"PrjctError")}code;isOperational;constructor(e,t="PRJCT_ERROR"){super(e),this.name="PrjctError",this.code=t,this.isOperational=!0,Error.captureStackTrace?.(this,this.constructor)}},Yr=class r extends dn{static{l(this,"ProjectError")}constructor(e,t="PROJECT_ERROR"){super(e,t),this.name="ProjectError"}static notInitialized(){return new r("Project not initialized. Run /p:init first.","PROJECT_NOT_INIT")}static notFound(e){return new r(`Project not found: ${e}`,"PROJECT_NOT_FOUND")}static invalidId(e){return new r(`Invalid project ID: ${e}`,"PROJECT_INVALID_ID")}},Qr=class r extends dn{static{l(this,"TemplateError")}constructor(e,t="TEMPLATE_ERROR"){super(e,t),this.name="TemplateError"}static notFound(e){return new r(`Template not found: ${e}.md`,"TEMPLATE_NOT_FOUND")}static parseFailed(e){return new r(`Failed to parse template: ${e}`,"TEMPLATE_PARSE_ERROR")}},gr=class r extends dn{static{l(this,"AgentError")}constructor(e,t="AGENT_ERROR"){super(e,t),this.name="AgentError"}static notSupported(e){return new r(`Unsupported agent type: ${e}`,"AGENT_NOT_SUPPORTED")}static initFailed(e){return new r(`Agent initialization failed: ${e}`,"AGENT_INIT_FAILED")}};l(Mh,"isPrjctError");l(ue,"getErrorMessage")});var Zi={};Bt(Zi,{PACKAGE_ROOT:()=>Qe,VERSION:()=>Ae,compareVersions:()=>Tu,getPackageInfo:()=>Oh,getPackageRoot:()=>Qi,getVersion:()=>Fs,isCompatible:()=>_h,needsMigration:()=>Nh});import Xi from"node:fs";import eo from"node:path";function Qi(){if(fr)return fr;let r=__dirname;for(let e=0;e<5;e++){let t=eo.join(r,"package.json");if(Xi.existsSync(t))try{if(JSON.parse(Xi.readFileSync(t,"utf-8")).name==="prjct-cli")return fr=r,r}catch{}r=eo.dirname(r)}return fr=eo.join(__dirname,"..","..",".."),fr}function Fs(){if(Zr)return Zr;try{let r=eo.join(Qi(),"package.json"),e=JSON.parse(Xi.readFileSync(r,"utf-8"));return Zr=e.version,Yi=e,Zr}catch(r){return console.error("Failed to read version from package.json:",y(r)),"0.0.0"}}function Oh(){return Yi||Fs(),Yi}function Tu(r,e){let t=r.split(".").map(Number),s=e.split(".").map(Number);for(let n=0;n<Math.max(t.length,s.length);n++){let o=t[n]||0,i=s[n]||0;if(o>i)return 1;if(o<i)return-1}return 0}function _h(r){let e=Fs(),[t,s]=e.split(".").map(Number),[n,o]=r.split(".").map(Number);return t===n&&s===o}function Nh(r,e=null){let t=e||Fs();return Tu(r,t)<0}var Zr,Yi,fr,Ae,Qe,Ct=S(()=>{"use strict";V();Zr=null,Yi=null,fr=null;l(Qi,"getPackageRoot");l(Fs,"getVersion");l(Oh,"getPackageInfo");l(Tu,"compareVersions");l(_h,"isCompatible");l(Nh,"needsMigration");Ae=Fs(),Qe=Qi()});import ta from"node:fs";import Lh from"node:fs/promises";import to from"node:path";function sa(){if(Cu)return ea;Cu=!0;let r=to.join(Qe,"dist","templates.json");try{let e=ta.readFileSync(r,"utf-8");return ea=JSON.parse(e),ea}catch{return null}}function Uh(r){let e=Us.indexOf(r);e>-1&&Us.splice(e,1),Us.push(r)}function Hh(){for(;mn.size>=Fh&&Us.length>0;){let r=Us.shift();r&&mn.delete(r)}}function Pu(r){let e=/^---\n([\s\S]+?)\n---\n([\s\S]*)$/,t=r.match(e);if(!t)return{frontmatter:{},content:r.trim()};let[,s,n]=t,o={};return s.split(`
|
|
@@ -707,8 +707,8 @@ ${e.example}
|
|
|
707
707
|
|
|
708
708
|
Fields:
|
|
709
709
|
${mb(e.schema)}`:null}function mb(r){if(r instanceof Xe.ZodObject){let e=r.shape;return Object.entries(e).map(([t,s])=>`- \`${t}\`: ${tg(s)}`).join(`
|
|
710
|
-
`)}return"(see example above)"}function tg(r){return r instanceof Xe.ZodString?"string":r instanceof Xe.ZodNumber?"number":r instanceof Xe.ZodEnum?`one of: ${r.options.join(", ")}`:r instanceof Xe.ZodArray?`array of ${tg(r.element)}`:r instanceof Xe.ZodObject?"object":"any"}var Qm,Zm,eg,ng=S(()=>{"use strict";Wo();Wo();Qm=Xe.object({agentName:Xe.string(),reasoning:Xe.string(),confidence:Xe.number().min(0).max(1)}),Zm=Xe.object({subtasks:Xe.array(Xe.object({description:Xe.string(),domain:Vo,agent:Xe.string(),dependsOn:Xe.array(Xe.number())})),effort:Xe.enum(["low","medium","high"])}),eg={classification:{schema:jn,example:JSON.stringify({primaryDomain:"backend",secondaryDomains:["database"],confidence:.9,filePatterns:["src/api/**"],relevantAgents:["backend.md"]},null,2)},agentAssignment:{schema:Qm,example:JSON.stringify({agentName:"backend.md",reasoning:"Task involves API endpoint creation",confidence:.85},null,2)},subtaskBreakdown:{schema:Zm,example:JSON.stringify({subtasks:[{description:"Add schema validation",domain:"backend",agent:"backend.md",dependsOn:[]},{description:"Add unit tests",domain:"testing",agent:"testing.md",dependsOn:[0]}],effort:"medium"},null,2)}};l(pb,"renderSchemaForPrompt");l(mb,"describeSchema");l(tg,"describeField")});import rg from"node:fs/promises";import Ys from"node:path";var Xc,gb,og,ig=S(()=>{"use strict";Xt();Pt();V();q();Ct();Om();Nm();Jm();qm();Ym();zc();Hs();Xc=class{static{l(this,"PromptBuilder")}_checklistsCache=null;_checklistsCacheTime=0;_checklistRoutingCache=null;_checklistRoutingCacheTime=0;_stateCache=new Map;_stateCacheTTL=5e3;_templateCache=new Map;TEMPLATE_CACHE_TTL_MS=6e4;
|
|
711
|
-
`);return Ir(n,this.getEffectiveBudgets().autoContext)}calculateElapsed(e){let t=new Date(e).getTime(),n=Date.now()-t,o=Math.floor(n/6e4),i=Math.floor(o/60),a=Math.floor(i/24);return a>0?`${a}d ${i%24}h`:i>0?`${i}h ${o%60}m`:`${o}m`}async loadChecklistRouting(){let e=Date.now();if(this._checklistRoutingCache&&e-this._checklistRoutingCacheTime<this.TEMPLATE_CACHE_TTL_MS)return this._checklistRoutingCache;let t=Ys.join(__dirname,"..","..","templates","agentic","checklist-routing.md"),s=await this.getTemplate(t);return s&&(this._checklistRoutingCache=s,this._checklistRoutingCacheTime=e),this._checklistRoutingCache||null}async buildWithInjection(e,t,s,n=null,o=null,i=null,a=null,c=null){let u=[];if(t.projectId){let m=await this.buildInjectedContext(t.projectId);m&&u.push(m)}let p=await this.build(e,t,s,n,o,i,a,c);return u.push(p),u.join("")}async build(e,t,s,n=null,o=null,i=null,a=null,c=null,u=null,p){let m=p?.skipNativeContext??!1,d=[]
|
|
710
|
+
`)}return"(see example above)"}function tg(r){return r instanceof Xe.ZodString?"string":r instanceof Xe.ZodNumber?"number":r instanceof Xe.ZodEnum?`one of: ${r.options.join(", ")}`:r instanceof Xe.ZodArray?`array of ${tg(r.element)}`:r instanceof Xe.ZodObject?"object":"any"}var Qm,Zm,eg,ng=S(()=>{"use strict";Wo();Wo();Qm=Xe.object({agentName:Xe.string(),reasoning:Xe.string(),confidence:Xe.number().min(0).max(1)}),Zm=Xe.object({subtasks:Xe.array(Xe.object({description:Xe.string(),domain:Vo,agent:Xe.string(),dependsOn:Xe.array(Xe.number())})),effort:Xe.enum(["low","medium","high"])}),eg={classification:{schema:jn,example:JSON.stringify({primaryDomain:"backend",secondaryDomains:["database"],confidence:.9,filePatterns:["src/api/**"],relevantAgents:["backend.md"]},null,2)},agentAssignment:{schema:Qm,example:JSON.stringify({agentName:"backend.md",reasoning:"Task involves API endpoint creation",confidence:.85},null,2)},subtaskBreakdown:{schema:Zm,example:JSON.stringify({subtasks:[{description:"Add schema validation",domain:"backend",agent:"backend.md",dependsOn:[]},{description:"Add unit tests",domain:"testing",agent:"testing.md",dependsOn:[0]}],effort:"medium"},null,2)}};l(pb,"renderSchemaForPrompt");l(mb,"describeSchema");l(tg,"describeField")});import rg from"node:fs/promises";import Ys from"node:path";var Xc,gb,og,ig=S(()=>{"use strict";Xt();Pt();V();q();Ct();Om();Nm();Jm();qm();Ym();zc();Hs();Xc=class{static{l(this,"PromptBuilder")}_checklistsCache=null;_checklistsCacheTime=0;_checklistRoutingCache=null;_checklistRoutingCacheTime=0;_stateCache=new Map;_stateCacheTTL=5e3;_templateCache=new Map;TEMPLATE_CACHE_TTL_MS=6e4;_coordinator=null;async getTemplate(e){let t=this._templateCache.get(e),s=Date.now();if(t&&s-t.loadedAt<this.TEMPLATE_CACHE_TTL_MS)return t.content;try{if(await C(e)){let n=await rg.readFile(e,"utf-8");return this._templateCache.set(e,{content:n,loadedAt:s}),n}}catch(n){R(n)||console.error(`Template loading warning: ${y(n)}`)}return null}clearTemplateCache(){this._templateCache.clear(),this._checklistsCache=null,this._checklistsCacheTime=0,this._checklistRoutingCache=null,this._checklistRoutingCacheTime=0}setCoordinator(e){this._coordinator=e}getCoordinator(){return this._coordinator}getEffectiveBudgets(){return this._coordinator?Xm(this._coordinator):qo}resetContext(){}setContext(e){}async loadModule(e){let t=yt(`global/modules/${e}`);if(t)return t;let s=Ys.join(Qe,"templates/global/modules",e);return this.getTemplate(s)}getModulesForCommand(e,t){return t?t.modules:[]}async loadChecklists(){let e=Date.now();if(this._checklistsCache&&e-this._checklistsCacheTime<this.TEMPLATE_CACHE_TTL_MS)return this._checklistsCache;let t={};try{let s=gn("checklists/");if(s.length>0){for(let n of s)if(n.endsWith(".md")){let o=yt(n);if(o){let i=Ys.basename(n,".md");t[i]=o}}}else{let n=Ys.join(Qe,"templates","checklists");if(await C(n)){let o=(await rg.readdir(n)).filter(i=>i.endsWith(".md"));for(let i of o){let a=i.replace(".md",""),c=Ys.join(n,i),u=await this.getTemplate(c);u&&(t[a]=u)}}}}catch(s){R(s)||console.error(`Checklist loading warning: ${y(s)}`)}return this._checklistsCache=t,this._checklistsCacheTime=e,t}async getProjectState(e){if(!e)return null;let t=this._stateCache.get(e);if(t&&Date.now()-t.timestamp<this._stateCacheTTL)return t.state;try{let[s,n]=await Promise.all([_.read(e),be.read(e)]),o={projectId:e,currentTask:s.currentTask,queue:n.tasks};return this._stateCache.set(e,{state:o,timestamp:Date.now()}),o}catch(s){if(R(s)||s instanceof SyntaxError)return null;throw s}}async buildInjectedContext(e){if(!e)return null;let t=await this.getProjectState(e);if(!t)return null;let s=[];if(s.push("## AUTO-INJECTED CONTEXT"),s.push(""),t.currentTask){let o=this.calculateElapsed(t.currentTask.startedAt);s.push(`**Current Task**: ${t.currentTask.description}`),s.push(`- Started: ${o} ago`)}else s.push("**Current Task**: None");if(s.push(""),t.queue.length>0){s.push(`**Queue**: ${t.queue.length} tasks pending`);let o=t.queue.slice(0,3);for(let i of o)s.push(`- [${i.priority}] ${i.description}`);t.queue.length>3&&s.push(`- ... and ${t.queue.length-3} more`)}s.push("");try{let o=await Mm.detectPatterns(e);if(o.length>0){s.push("**Project Conventions**");for(let i of o.slice(0,3))s.push(`- ${i.description}`),i.suggestedAction&&s.push(` \u2192 ${i.suggestedAction}`);s.push("")}}catch(o){!R(o)&&!(o instanceof SyntaxError)&&console.error(`Outcome detection warning: ${y(o)}`)}s.push("---"),s.push("");let n=s.join(`
|
|
711
|
+
`);return Ir(n,this.getEffectiveBudgets().autoContext)}calculateElapsed(e){let t=new Date(e).getTime(),n=Date.now()-t,o=Math.floor(n/6e4),i=Math.floor(o/60),a=Math.floor(i/24);return a>0?`${a}d ${i%24}h`:i>0?`${i}h ${o%60}m`:`${o}m`}async loadChecklistRouting(){let e=Date.now();if(this._checklistRoutingCache&&e-this._checklistRoutingCacheTime<this.TEMPLATE_CACHE_TTL_MS)return this._checklistRoutingCache;let t=Ys.join(__dirname,"..","..","templates","agentic","checklist-routing.md"),s=await this.getTemplate(t);return s&&(this._checklistRoutingCache=s,this._checklistRoutingCacheTime=e),this._checklistRoutingCache||null}async buildWithInjection(e,t,s,n=null,o=null,i=null,a=null,c=null){let u=[];if(t.projectId){let m=await this.buildInjectedContext(t.projectId);m&&u.push(m)}let p=await this.build(e,t,s,n,o,i,a,c);return u.push(p),u.join("")}async build(e,t,s,n=null,o=null,i=null,a=null,c=null,u=null,p){let m=p?.skipNativeContext??!1,d=[],g=e.frontmatter?.name?.replace("p:","")||"",h;try{let D=await Vm();h=Bm(D,g,e).entry}catch{h={agents:!0,patterns:!0,checklist:!1,modules:[]}}let k=h.agents;n&&k&&(d.push(`# AGENT: ${n.name}
|
|
712
712
|
`),n.role&&d.push(`Role: ${n.role}
|
|
713
713
|
`),n.skills?.length&&d.push(`Skills: ${n.skills.join(", ")}
|
|
714
714
|
`),d.push(`
|