prjct-cli 2.0.0-alpha.12 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.1.0] - 2026-04-22
4
+
5
+ ### Features
6
+
7
+ - current work
8
+
9
+
3
10
  ## [2.0.0-alpha.12] - 2026-04-21
4
11
 
5
12
  Summary of the alpha.6 → alpha.12 arc and the dead-code / harness sweep
@@ -491,7 +491,7 @@ var gf=Object.create;var zn=Object.defineProperty;var ff=Object.getOwnPropertyDe
491
491
  name TEXT NOT NULL,
492
492
  applied_at TEXT NOT NULL
493
493
  )
494
- `);let t=new Set(e.prepare("SELECT version FROM _migrations").all().map(s=>s.version));for(let s of Eh)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}},E=new Zr,O=E});import{z as L}from"zod";var Ph,jh,ou,xh,Rh,Ah,Ih,Dh,iu,sC,au=y(()=>{"use strict";Ph=L.enum(["low","medium","high"]),jh=L.enum(["pending","converted","completed","archived","dormant"]),ou=L.enum(["high","medium","low"]),xh=L.object({impact:ou,effort:ou}),Rh=L.object({frontend:L.string().optional(),backend:L.string().optional(),payments:L.string().optional(),ai:L.string().optional(),deploy:L.string().optional(),other:L.array(L.string()).optional()}),Ah=L.object({name:L.string(),description:L.string()}),Ih=L.object({name:L.string(),description:L.string().optional()}),Dh=L.object({id:L.string(),text:L.string(),details:L.string().optional(),priority:Ph,status:jh,tags:L.array(L.string()),addedAt:L.string(),completedAt:L.string().optional(),convertedTo:L.string().optional(),source:L.string().optional(),sourceFiles:L.array(L.string()).optional(),painPoints:L.array(L.string()).optional(),solutions:L.array(L.string()).optional(),filesAffected:L.array(L.string()).optional(),impactEffort:xh.optional(),implementationNotes:L.string().optional(),stack:Rh.optional(),modules:L.array(Ah).optional(),roles:L.array(Ih).optional(),risks:L.array(L.string()).optional(),risksCount:L.number().optional()}),iu=L.object({ideas:L.array(Dh),lastUpdated:L.string()}),sC={priority:"medium",status:"pending",tags:[],addedAt:new Date().toISOString()}});import $h from"node:crypto";import{homedir as Mh}from"node:os";import{join as Nh}from"node:path";function Ze(){return $h.randomUUID()}var cC,Ds=y(()=>{"use strict";c(Ze,"generateUUID");cC=Nh(Mh(),".prjct-cli","projects")});var Bt,Ui,et,ls=y(()=>{"use strict";Ds();be();ae();Bt={SHIPPED_RETENTION_DAYS:90,IDEA_DORMANT_DAYS:180,QUEUE_COMPLETED_DAYS:7,PAUSED_TASK_DAYS:30,MEMORY_MAX_ENTRIES:500},Ui=class{static{c(this,"ArchiveStorage")}archive(e,t){let s=Ze(),r=C();return E.run(e,"INSERT INTO archives (id, entity_type, entity_id, entity_data, summary, archived_at, reason) VALUES (?, ?, ?, ?, ?, ?, ?)",s,t.entityType,t.entityId,JSON.stringify(t.entityData),t.summary??null,r,t.reason),s}archiveMany(e,t){if(t.length===0)return 0;let s=C();return E.transaction(e,r=>{let o=r.prepare("INSERT INTO archives (id, entity_type, entity_id, entity_data, summary, archived_at, reason) VALUES (?, ?, ?, ?, ?, ?, ?)");for(let i of t)o.run(Ze(),i.entityType,i.entityId,JSON.stringify(i.entityData),i.summary??null,s,i.reason)}),t.length}getArchived(e,t,s=50){return t?E.query(e,"SELECT * FROM archives WHERE entity_type = ? ORDER BY archived_at DESC LIMIT ?",t,s):E.query(e,"SELECT * FROM archives ORDER BY archived_at DESC LIMIT ?",s)}getStats(e){let t=E.query(e,"SELECT entity_type, COUNT(*) as count FROM archives GROUP BY entity_type"),s={shipped:0,idea:0,queue_task:0,paused_task:0,memory_entry:0,total:0};for(let r of t){let o=r.entity_type;o in s&&(s[o]=r.count),s.total+=r.count}return s}restore(e,t){let s=E.get(e,"SELECT * FROM archives WHERE id = ?",t);return s?(E.run(e,"DELETE FROM archives WHERE id = ?",t),JSON.parse(s.entity_data)):null}pruneOldArchives(e,t){let s=new Date(Date.now()-t*24*60*60*1e3).toISOString(),r=this.getTotalCount(e);E.run(e,"DELETE FROM archives WHERE archived_at < ?",s);let o=this.getTotalCount(e);return r-o}getTotalCount(e){return E.get(e,"SELECT COUNT(*) as count FROM archives")?.count??0}},et=new Ui});var Hi,us,Wi=y(()=>{"use strict";Me();be();J();Hi=class{static{c(this,"SyncEventBus")}async publish(e){let t=D.getSyncPendingPath(e.projectId),s=await Se(t,[])??[],r=Array.isArray(s)?s:[];r.push(e),await ne(t,r)}async getPending(e){let t=D.getSyncPendingPath(e),s=await Se(t,[])??[];return Array.isArray(s)?s:[]}async clearPending(e){let t=D.getSyncPendingPath(e);await ne(t,[])}async updateLastSync(e){let t=D.getLastSyncPath(e),s={timestamp:C(),success:!0};await ne(t,s)}async getLastSync(e){let t=D.getLastSyncPath(e);return await Se(t,null)}},us=new Hi});var Xe,ds=y(()=>{"use strict";Wi();Yn();be();ae();Xe=class{static{c(this,"StorageManager")}filename;cache;constructor(e,t){this.filename=e,this.cache=new Ur({ttl:5e3,maxSize:50})}getStoreKey(){return this.filename.replace(".json","")}async read(e){let t=this.cache.get(e);if(t!==null)return t;try{let s=E.getDoc(e,this.getStoreKey());if(s!==null)return this.cache.set(e,s),s}catch{}return this.getDefault()}async write(e,t){E.setDoc(e,this.getStoreKey(),t),this.cache.set(e,t)}async update(e,t){let s=await this.read(e),r=t(s);return await this.write(e,r),r}async publishEvent(e,t,s){let r={type:t,path:[this.filename.replace(".json","")],data:s,timestamp:C(),projectId:e};await us.publish(r)}async publishEntityEvent(e,t,s,r){let o=`${t}.${s}`,i={...r,timestamp:C()};await this.publishEvent(e,o,i)}async exists(e){try{return E.hasDoc(e,this.getStoreKey())}catch{return!1}}clearCache(e){e?this.cache.delete(e):this.cache.clear()}getCacheStats(){return this.cache.stats()}}});var Gi,Fe,sr=y(()=>{"use strict";au();Ds();be();ls();ds();Gi=class extends Xe{static{c(this,"IdeasStorage")}constructor(){super("ideas.json",iu)}getDefault(){return{ideas:[],lastUpdated:""}}getEventType(e){return`ideas.${e}d`}async getAll(e){return(await this.read(e)).ideas}async getPending(e){return(await this.read(e)).ideas.filter(s=>s.status==="pending")}async addIdea(e,t,s={}){let r={id:Ze(),text:t,status:"pending",priority:s.priority||"medium",tags:s.tags||[],addedAt:C()};return await this.update(e,o=>({ideas:[r,...o.ideas],lastUpdated:C()})),await this.publishEvent(e,"idea.created",{ideaId:r.id,text:r.text,priority:r.priority}),r}async getById(e,t){return(await this.read(e)).ideas.find(r=>r.id===t)}async convertToFeature(e,t,s){await this.update(e,r=>({ideas:r.ideas.map(o=>o.id===t?{...o,status:"converted",convertedTo:s}:o),lastUpdated:C()})),await this.publishEvent(e,"idea.converted",{ideaId:t,featureId:s})}async archive(e,t){await this.update(e,s=>({ideas:s.ideas.map(r=>r.id===t?{...r,status:"archived"}:r),lastUpdated:C()})),await this.publishEvent(e,"idea.archived",{ideaId:t})}async setPriority(e,t,s){await this.update(e,r=>({ideas:r.ideas.map(o=>o.id===t?{...o,priority:s}:o),lastUpdated:C()}))}async addTags(e,t,s){await this.update(e,r=>({ideas:r.ideas.map(o=>o.id===t?{...o,tags:[...new Set([...o.tags,...s])]}:o),lastUpdated:C()}))}async removeIdea(e,t){await this.update(e,s=>({ideas:s.ideas.filter(r=>r.id!==t),lastUpdated:C()}))}async getCounts(e){let t=await this.read(e);return{pending:t.ideas.filter(s=>s.status==="pending").length,converted:t.ideas.filter(s=>s.status==="converted").length,archived:t.ideas.filter(s=>s.status==="archived").length}}async cleanup(e){let s=(await this.read(e)).ideas.filter(a=>a.status==="archived");if(s.length<=50)return{removed:0};let r=s.sort((a,l)=>new Date(l.addedAt).getTime()-new Date(a.addedAt).getTime()),o=new Set(r.slice(50).map(a=>a.id)),i=o.size;return await this.update(e,a=>({ideas:a.ideas.filter(l=>!o.has(l.id)),lastUpdated:C()})),{removed:i}}async markDormantIdeas(e){let t=await this.read(e),s=rn(Bt.IDEA_DORMANT_DAYS),r=t.ideas.filter(i=>i.status==="pending"&&new Date(i.addedAt)<s);if(r.length===0)return 0;et.archiveMany(e,r.map(i=>({entityType:"idea",entityId:i.id,entityData:i,summary:i.text,reason:"dormant"})));let o=new Set(r.map(i=>i.id));return await this.update(e,i=>({ideas:i.ideas.map(a=>o.has(a.id)?{...a,status:"dormant"}:a),lastUpdated:C()})),await this.publishEvent(e,"ideas.dormant",{count:r.length}),r.length}},Fe=new Gi});import{z as k}from"zod";var _h,eo,Oh,Lh,Fh,qi,lu,uu,du,Vi,cu,Uh,Hh,Wh,pu,mu,gu,Gh,qh,NC,Bi=y(()=>{"use strict";Fr();_h=k.enum(["low","medium","high","critical"]),eo=k.enum(["feature","bug","improvement","chore"]),Oh=k.enum(["active","backlog","previously_active"]),Lh=k.enum(["pending","in_progress","completed","blocked","paused","failed","skipped"]),Fh=k.enum(["task_completed","feature_shipped","idea_captured","session_started"]),qi=k.object({title:k.string(),description:k.string(),filesChanged:k.array(k.object({path:k.string(),action:k.enum(["created","modified","deleted"])})),whatWasDone:k.array(k.string()).min(1),outputForNextAgent:k.string().min(1),notes:k.string().optional()}),lu=k.object({output:k.string().min(1,"Subtask output is required"),summary:qi}),uu=k.object({id:k.string(),description:k.string(),domain:k.string(),agent:k.string(),status:Lh,dependsOn:k.array(k.string()),startedAt:k.string().optional(),completedAt:k.string().optional(),output:k.string().optional(),summary:qi.optional(),skipReason:k.string().optional(),blockReason:k.string().optional(),estimatedPoints:k.number().optional(),estimatedMinutes:k.number().optional()}),du=k.object({completed:k.number(),total:k.number(),percentage:k.number()}),Vi=k.object({id:k.string(),description:k.string(),type:eo.optional(),startedAt:k.string(),sessionId:k.string(),featureId:k.string().optional(),subtasks:k.array(uu).optional(),currentSubtaskIndex:k.number().optional(),subtaskProgress:du.optional(),linearId:k.string().optional(),linearUuid:k.string().optional(),estimatedPoints:k.number().optional(),estimatedMinutes:k.number().optional(),modelMetadata:Zs.optional(),tokensIn:k.number().optional(),tokensOut:k.number().optional(),parentDescription:k.string().optional(),branch:k.string().optional(),prUrl:k.string().optional()}),cu=k.object({id:k.string(),description:k.string(),status:k.literal("paused"),startedAt:k.string(),pausedAt:k.string(),pauseReason:k.string().optional(),type:eo.optional(),sessionId:k.string().optional(),featureId:k.string().optional(),subtasks:k.array(uu).optional(),currentSubtaskIndex:k.number().optional(),subtaskProgress:du.optional(),linearId:k.string().optional(),linearUuid:k.string().optional(),estimatedPoints:k.number().optional(),estimatedMinutes:k.number().optional(),modelMetadata:Zs.optional(),tokensIn:k.number().optional(),tokensOut:k.number().optional()}),Uh=k.object({stackConfirmed:k.array(k.string()).optional(),patternsDiscovered:k.array(k.string()).optional(),agentAccuracy:k.array(k.object({agent:k.string(),rating:k.enum(["helpful","neutral","inaccurate"]),note:k.string().optional()})).optional(),issuesEncountered:k.array(k.string()).optional()}),Hh=k.object({taskId:k.string(),title:k.string(),classification:eo,startedAt:k.string(),completedAt:k.string(),subtaskCount:k.number(),subtaskSummaries:k.array(qi),outcome:k.string(),branchName:k.string(),linearId:k.string().optional(),linearUuid:k.string().optional(),prUrl:k.string().optional(),feedback:Uh.optional(),tokensIn:k.number().optional(),tokensOut:k.number().optional()}),Wh=Vi.extend({workspaceId:k.string(),worktreePath:k.string().optional(),agentSessionId:k.string().optional(),jiraId:k.string().optional(),jiraUuid:k.string().optional(),dispatchedFrom:k.string().optional()}),pu=k.object({currentTask:Vi.nullable(),previousTask:cu.nullable().optional(),pausedTasks:k.array(cu).optional(),taskHistory:k.array(Hh).optional(),activeTasks:k.array(Wh).optional(),lastUpdated:k.string()}),mu=k.object({id:k.string(),description:k.string(),body:k.string().optional(),priority:_h,type:eo,featureId:k.string().optional(),originFeature:k.string().optional(),completed:k.boolean(),completedAt:k.string().optional(),createdAt:k.string(),section:Oh,agent:k.string().optional(),groupName:k.string().optional(),groupId:k.string().optional()}),gu=k.object({tasks:k.array(mu),lastUpdated:k.string()}),Gh=k.object({tasksToday:k.number(),tasksThisWeek:k.number(),streak:k.number(),velocity:k.string(),avgDuration:k.string()}),qh=k.object({type:Fh,description:k.string(),timestamp:k.string(),duration:k.string().optional()}),NC=k.object({projectId:k.string(),currentTask:Vi.nullable(),queue:k.array(mu),stats:Gh,recentActivity:k.array(qh),lastSync:k.string()})});function yu(n){return[...n].sort((e,t)=>{let s=hu[e.section]-hu[t.section];return s!==0?s:fu[e.priority]-fu[t.priority]})}function Ji(n,e){let t=new Set;return n.filter(s=>{let r=e(s);return t.has(r)?!1:(t.add(r),!0)})}var fu,hu,zi=y(()=>{"use strict";fu={critical:0,high:1,medium:2,low:3},hu={active:0,previously_active:1,backlog:2};c(yu,"sortBySectionAndPriority");c(Ji,"uniqueBy")});var Xi,Ue,nr=y(()=>{"use strict";Ds();Bi();zi();be();ls();ds();Xi=class extends Xe{static{c(this,"QueueStorage")}constructor(){super("queue.json",gu)}getDefault(){return{tasks:[],lastUpdated:""}}getEventType(e){return`queue.${e}d`}async getTasks(e){return(await this.read(e)).tasks}async getActiveTasks(e){return(await this.read(e)).tasks.filter(s=>s.section==="active"&&!s.completed)}async getBacklog(e){return(await this.read(e)).tasks.filter(s=>s.section==="backlog"&&!s.completed)}async getNextTask(e){let t=await this.getActiveTasks(e);return yu(t)[0]||null}async addTask(e,t){let s={...t,id:Ze(),createdAt:C(),completed:!1};return await this.update(e,r=>({tasks:[...r.tasks,s],lastUpdated:C()})),await this.publishEvent(e,"queue.task_added",{taskId:s.id,description:s.description,priority:s.priority,section:s.section}),s}async addTasks(e,t){let s=C(),r=t.map(o=>({...o,id:Ze(),createdAt:s,completed:!1}));return await this.update(e,o=>({tasks:[...o.tasks,...r],lastUpdated:s})),await this.publishEvent(e,"queue.tasks_added",{count:r.length,tasks:r.map(o=>({id:o.id,description:o.description}))}),r}async removeTask(e,t){await this.update(e,s=>({tasks:s.tasks.filter(r=>r.id!==t),lastUpdated:C()})),await this.publishEvent(e,"queue.task_removed",{taskId:t})}async completeTask(e,t){let s=null;if(await this.update(e,r=>({tasks:r.tasks.map(i=>i.id===t?(s={...i,completed:!0,completedAt:C()},s):i),lastUpdated:C()})),s){let r=s;await this.publishEvent(e,"queue.task_completed",{taskId:t,description:r.description,completedAt:r.completedAt})}return s}async moveToSection(e,t,s){await this.update(e,r=>({tasks:r.tasks.map(o=>o.id===t?{...o,section:s}:o),lastUpdated:C()}))}async setPriority(e,t,s){await this.update(e,r=>({tasks:r.tasks.map(o=>o.id===t?{...o,priority:s}:o),lastUpdated:C()}))}async getTask(e,t){return(await this.read(e)).tasks.find(r=>r.id===t)||null}async updateTask(e,t,s){let r=null;return await this.update(e,o=>({tasks:o.tasks.map(i=>i.id===t?(r={...i,...s},r):i),lastUpdated:C()})),r&&await this.publishEvent(e,"queue.task_updated",{taskId:t}),r}async clearCompleted(e){let s=(await this.read(e)).tasks.filter(r=>r.completed).length;return await this.update(e,r=>({tasks:r.tasks.filter(o=>!o.completed),lastUpdated:C()})),s}async removeStaleCompleted(e){let t=await this.read(e),s=rn(Bt.QUEUE_COMPLETED_DAYS),r=t.tasks.filter(i=>i.completed&&i.completedAt&&new Date(i.completedAt)<s);if(r.length===0)return 0;et.archiveMany(e,r.map(i=>({entityType:"queue_task",entityId:i.id,entityData:i,summary:i.description,reason:"age"})));let o=new Set(r.map(i=>i.id));return await this.update(e,i=>({tasks:i.tasks.filter(a=>!o.has(a.id)),lastUpdated:C()})),await this.publishEvent(e,"queue.stale_removed",{count:r.length}),r.length}},Ue=new Xi});import{z as K}from"zod";var Vh,wu,Bh,Jh,zh,Xh,Kh,Yh,Qh,ku,Su=y(()=>{"use strict";Vh=K.enum(["feature","fix","improvement","refactor"]),wu=K.enum(["pass","warning","fail","skipped"]),Bh=K.enum(["added","changed","fixed","removed"]),Jh=K.object({hours:K.number(),minutes:K.number(),totalMinutes:K.number()}),zh=K.object({filesChanged:K.number().nullable().optional(),linesAdded:K.number().nullable().optional(),linesRemoved:K.number().nullable().optional(),commits:K.number().nullable().optional()}),Xh=K.object({description:K.string(),type:Bh.optional()}),Kh=K.object({lintStatus:wu.nullable().optional(),lintDetails:K.string().optional(),testStatus:wu.nullable().optional(),testDetails:K.string().optional()}),Yh=K.object({hash:K.string().optional(),message:K.string().optional(),branch:K.string().optional()}),Qh=K.object({id:K.string(),name:K.string(),version:K.string().nullable().optional(),type:Vh,agent:K.string().optional(),description:K.string().optional(),changes:K.array(Xh).optional(),codeSnippets:K.array(K.string()).optional(),commit:Yh.optional(),codeMetrics:zh.optional(),qualityMetrics:Kh.optional(),quantitativeImpact:K.string().optional(),duration:Jh.optional(),tasksCompleted:K.number().nullable().optional(),shippedAt:K.string(),featureId:K.string().optional()}),ku=K.object({shipped:K.array(Qh),lastUpdated:K.string()})});var Ki,Ke,bu,$s=y(()=>{"use strict";Ds();Su();be();ls();ds();Ki=class extends Xe{static{c(this,"ShippedStorage")}constructor(){super("shipped.json",ku)}getDefault(){return{shipped:[],lastUpdated:""}}getEventType(e){return`shipped.${e}d`}async getAll(e){return(await this.read(e)).shipped}async getRecent(e,t=5){return(await this.read(e)).shipped.sort((r,o)=>new Date(o.shippedAt).getTime()-new Date(r.shippedAt).getTime()).slice(0,t)}async addShipped(e,t){let s={...t,id:Ze(),shippedAt:C()};return await this.update(e,r=>({shipped:[s,...Array.isArray(r.shipped)?r.shipped:[]],lastUpdated:C()})),await this.publishEvent(e,"feature.shipped",{shipId:s.id,name:s.name,version:s.version,shippedAt:s.shippedAt}),s}async getByVersion(e,t){return(await this.read(e)).shipped.find(r=>r.version===t)}async getCount(e){return(await this.read(e)).shipped.length}async getByDateRange(e,t,s){return(await this.read(e)).shipped.filter(o=>{let i=new Date(o.shippedAt);return i>=t&&i<=s})}async getStats(e,t="month"){let s=new Date,r;switch(t){case"week":r=new Date(s.getTime()-7*24*60*60*1e3);break;case"month":r=new Date(s.getFullYear(),s.getMonth(),1);break;case"year":r=new Date(s.getFullYear(),0,1);break}return{count:(await this.getByDateRange(e,r,s)).length,period:t}}async archiveOldShipped(e){let t=await this.read(e),s=rn(Bt.SHIPPED_RETENTION_DAYS),r=t.shipped.filter(i=>new Date(i.shippedAt)<s);if(r.length===0)return 0;et.archiveMany(e,r.map(i=>({entityType:"shipped",entityId:i.id,entityData:i,summary:`${i.name} v${i.version}`,reason:"age"})));let o=new Set(t.shipped.filter(i=>new Date(i.shippedAt)>=s).map(i=>i.id));return await this.update(e,i=>({shipped:i.shipped.filter(a=>o.has(a.id)),lastUpdated:C()})),await this.publishEvent(e,"shipped.archived",{count:r.length,oldestShippedAt:r[r.length-1]?.shippedAt}),r.length}},Ke=new Ki,bu=Ke});var rr,Yi,Ms,Qi=y(()=>{"use strict";rr={idle:{transitions:["task","next"],prompt:"p. task <description> Start working",description:"No active task"},working:{transitions:["done","pause"],prompt:"p. done Complete task | p. pause Switch context",description:"Task in progress"},paused:{transitions:["resume","task","ship"],prompt:"p. resume Continue | p. task <new> Start different | p. ship Ship directly",description:"Task paused"},completed:{transitions:["ship","task","next","pause","reopen"],prompt:"p. ship Ship it | p. task <next> Start next | p. reopen Reopen for rework",description:"Task completed"},shipped:{transitions:["task","next"],prompt:"p. task <description> Start new task",description:"Feature shipped"}},Yi=class{static{c(this,"WorkflowStateMachine")}getCurrentState(e,t){let s=null;if(t&&e?.activeTasks?.length&&(s=e.activeTasks.find(o=>o.workspaceId===t)),s||(s=e?.currentTask),!s)return(e?.pausedTasks?.length||0)>0||e?.previousTask?.status==="paused"?"paused":"idle";switch((typeof s.status=="string"?s.status:"").toLowerCase()){case"in_progress":case"working":return"working";case"paused":return"paused";case"completed":case"done":return"completed";case"shipped":return"shipped";default:return s?"working":"idle"}}canTransition(e,t){let s=rr[e];if(s.transitions.includes(t))return{valid:!0};let r=s.transitions.map(o=>`p. ${o}`).join(", ");return{valid:!1,error:`Cannot run 'p. ${t}' in ${e} state`,suggestion:`Valid commands: ${r}`}}getNextState(e,t){switch(t){case"task":return"working";case"done":return"completed";case"pause":return"paused";case"resume":return"working";case"ship":return"shipped";case"reopen":return"working";case"next":return e;default:return e}}getStateInfo(e){return rr[e]}getPrompt(e){return rr[e].prompt}getValidCommands(e){return rr[e].transitions}formatNextSteps(e){return rr[e].transitions.map(s=>{switch(s){case"task":return"p. task <desc> Start new task";case"done":return"p. done Complete current task";case"pause":return"p. pause Pause and switch context";case"resume":return"p. resume Continue paused task";case"ship":return"p. ship Ship the feature";case"reopen":return"p. reopen Reopen for rework";case"next":return"p. next View task queue";default:return`p. ${s}`}})}},Ms=new Yi});var Zi,_,it=y(()=>{"use strict";Ds();Bi();be();Qi();ls();ds();Zi=class extends Xe{static{c(this,"StateStorage")}constructor(){super("state.json",pu)}getDefault(){return{currentTask:null,previousTask:null,pausedTasks:[],taskHistory:[],activeTasks:[],lastUpdated:""}}getEventType(e){return`state.${e}d`}validateTransition(e,t){let s=Ms.getCurrentState(e),r=Ms.canTransition(s,t);if(!r.valid)throw new Error(`${r.error}. ${r.suggestion||""}`.trim())}async getCurrentTask(e){return(await this.read(e)).currentTask}async startTask(e,t){let s=await this.read(e);this.validateTransition(s,"task");let r={...t,startedAt:C()};return await this.update(e,o=>({...o,currentTask:r,lastUpdated:C()})),await this.publishEvent(e,"task.started",{taskId:r.id,description:r.description,startedAt:r.startedAt,sessionId:r.sessionId}),r}async updateCurrentTask(e,t){let s=await this.read(e);if(!s.currentTask)return null;let r={...s.currentTask,...t};return await this.update(e,o=>({...o,currentTask:r,lastUpdated:C()})),r}async completeTask(e,t){let s=await this.read(e),r=s.currentTask;if(!r)return null;this.validateTransition(s,"done");let o=C(),i=this.createTaskHistoryEntry(r,o,t),a=this.getTaskHistoryFromState(s),l=[i,...a].slice(0,this.maxTaskHistory);return await this.update(e,u=>({...u,currentTask:null,previousTask:null,taskHistory:l,lastUpdated:o})),await this.publishEvent(e,"task.completed",{taskId:r.id,description:r.description,startedAt:r.startedAt,completedAt:o}),r}createTaskHistoryEntry(e,t,s){let r=(e.subtasks||[]).filter(a=>a.status==="completed"&&a.summary).map(a=>a.summary),o=r.length>0?r.map(a=>a.title).join(", "):"Task completed",i={taskId:e.id,title:e.parentDescription||e.description,classification:e.type||"improvement",startedAt:e.startedAt,completedAt:t,subtaskCount:e.subtasks?.length||0,subtaskSummaries:r,outcome:o,branchName:e.branch||"unknown",linearId:e.linearId,linearUuid:e.linearUuid,prUrl:e.prUrl};return s&&(i.feedback=s),e.tokensIn&&(i.tokensIn=e.tokensIn),e.tokensOut&&(i.tokensOut=e.tokensOut),i}maxPausedTasks=5;maxTaskHistory=20;stalenessThresholdDays=30;async pauseTask(e,t){let s=await this.read(e);if(!s.currentTask)return null;this.validateTransition(s,"pause");let r={...s.currentTask,status:"paused",pausedAt:C(),pauseReason:t},o=this.getPausedTasksFromState(s),i=[r,...o].slice(0,this.maxPausedTasks);return await this.update(e,a=>({...a,currentTask:null,previousTask:null,pausedTasks:i,lastUpdated:C()})),await this.publishEvent(e,"task.paused",{taskId:r.id,description:r.description,pausedAt:r.pausedAt,reason:t,pausedCount:i.length}),r}async resumeTask(e,t){let s=await this.read(e),r=this.getPausedTasksFromState(s);if(r.length===0)return null;this.validateTransition(s,"resume");let o=0;if(t&&(o=r.findIndex(f=>f.id===t),o===-1))return null;let i=r[o],a=r.filter((f,T)=>T!==o),{status:l,pausedAt:u,pauseReason:d,...m}=i,p={...m,startedAt:C(),sessionId:i.sessionId??Ze()};return await this.update(e,f=>({...f,currentTask:p,previousTask:null,pausedTasks:a,lastUpdated:C()})),await this.publishEvent(e,"task.resumed",{taskId:p.id,description:p.description,resumedAt:p.startedAt,remainingPaused:a.length}),p}getPausedTasksFromState(e){return Array.isArray(e.pausedTasks)&&e.pausedTasks.length>0?e.pausedTasks:e.previousTask?[e.previousTask]:[]}getTaskHistoryFromState(e){return e.taskHistory||[]}async getStalePausedTasks(e){let t=await this.read(e),s=this.getPausedTasksFromState(t),r=Date.now()-this.stalenessThresholdDays*24*60*60*1e3;return s.filter(o=>new Date(o.pausedAt).getTime()<r)}async archiveStalePausedTasks(e){let t=await this.read(e),s=this.getPausedTasksFromState(t),r=Date.now()-this.stalenessThresholdDays*24*60*60*1e3,o=s.filter(a=>new Date(a.pausedAt).getTime()<r),i=s.filter(a=>new Date(a.pausedAt).getTime()>=r);if(o.length===0)return[];et.archiveMany(e,o.map(a=>({entityType:"paused_task",entityId:a.id,entityData:a,summary:a.description,reason:"staleness"}))),await this.update(e,a=>({...a,pausedTasks:i,previousTask:null,lastUpdated:C()}));for(let a of o)await this.publishEvent(e,"task.archived",{taskId:a.id,description:a.description,pausedAt:a.pausedAt,reason:"staleness"});return o}async clearTask(e){await this.update(e,()=>({currentTask:null,previousTask:null,pausedTasks:[],activeTasks:[],lastUpdated:C()}))}async hasTask(e){let t=await this.read(e),s=this.getPausedTasksFromState(t);return t.currentTask!==null||s.length>0}async getPausedTask(e){let t=await this.read(e);return this.getPausedTasksFromState(t)[0]||null}async getAllPausedTasks(e){let t=await this.read(e);return this.getPausedTasksFromState(t)}async getTaskHistory(e){let t=await this.read(e);return this.getTaskHistoryFromState(t)}async getMostRecentTask(e){let t=await this.read(e);return this.getTaskHistoryFromState(t)[0]||null}async getTaskHistoryByType(e,t){let s=await this.read(e);return this.getTaskHistoryFromState(s).filter(o=>o.classification===t)}async getAggregatedFeedback(e){let s=(await this.getTaskHistory(e)).filter(p=>p.feedback),r=[],o=[],i=[],a=[];for(let p of s){let f=p.feedback;Array.isArray(f.stackConfirmed)&&r.push(...f.stackConfirmed),Array.isArray(f.patternsDiscovered)&&o.push(...f.patternsDiscovered),Array.isArray(f.agentAccuracy)&&i.push(...f.agentAccuracy),Array.isArray(f.issuesEncountered)&&a.push(...f.issuesEncountered)}let l=[...new Set(r)],u=[...new Set(o)],d=new Map;for(let p of a)d.set(p,(d.get(p)||0)+1);let m=[...d.entries()].filter(([p,f])=>f>=2).map(([p])=>p);return{stackConfirmed:l,patternsDiscovered:u,agentAccuracy:i,issuesEncountered:[...new Set(a)],knownGotchas:m}}async startTaskInWorkspace(e,t,s){let r={...t,workspaceId:s,startedAt:C()};return await this.update(e,o=>({...o,activeTasks:[...o.activeTasks||[],r],lastUpdated:C()})),await this.publishEvent(e,"task.started",{taskId:r.id,description:r.description,startedAt:r.startedAt,sessionId:r.sessionId,workspaceId:s}),r}async getCurrentTaskForWorkspace(e,t){return((await this.read(e)).activeTasks||[]).find(r=>r.workspaceId===t)??null}async completeTaskInWorkspace(e,t,s){let r=await this.read(e),i=(r.activeTasks||[]).find(m=>m.workspaceId===t);if(!i)return null;let a=C(),l=this.createTaskHistoryEntry(i,a,s),u=this.getTaskHistoryFromState(r),d=[l,...u].slice(0,this.maxTaskHistory);return await this.update(e,m=>({...m,activeTasks:(m.activeTasks||[]).filter(p=>p.workspaceId!==t),taskHistory:d,lastUpdated:a})),await this.publishEvent(e,"task.completed",{taskId:i.id,description:i.description,startedAt:i.startedAt,completedAt:a,workspaceId:t}),i}async getActiveTasks(e){return(await this.read(e)).activeTasks||[]}async getActiveTaskCount(e){return((await this.read(e)).activeTasks||[]).length}async updateWorkspaceTask(e,t,s){let o=(await this.read(e)).activeTasks||[],i=o.findIndex(l=>l.workspaceId===t);if(i===-1)return null;let a={...o[i],...s,workspaceId:t};return await this.update(e,l=>{let u=[...l.activeTasks||[]];return u[i]=a,{...l,activeTasks:u,lastUpdated:C()}}),a}async addTokens(e,t,s){let r=await this.read(e);if(!r.currentTask)return null;let o=(r.currentTask.tokensIn||0)+t,i=(r.currentTask.tokensOut||0)+s;return await this.update(e,a=>({...a,currentTask:{...a.currentTask,tokensIn:o,tokensOut:i},lastUpdated:C()})),{tokensIn:o,tokensOut:i}}async createSubtasks(e,t){let s=await this.read(e);if(!s.currentTask)return;let r=t.map((o,i)=>({...o,status:i===0?"in_progress":"pending",startedAt:i===0?C():void 0,dependsOn:o.dependsOn||[]}));await this.update(e,o=>({...o,currentTask:{...o.currentTask,subtasks:r,currentSubtaskIndex:0,subtaskProgress:{completed:0,total:r.length,percentage:0}},lastUpdated:C()})),await this.publishEvent(e,"subtasks.created",{taskId:s.currentTask.id,subtaskCount:r.length,subtasks:r.map(o=>({id:o.id,description:o.description,domain:o.domain}))})}async completeSubtask(e,t){let s=lu.safeParse(t);if(!s.success){let T=s.error.issues.map(j=>`${j.path.join(".")}: ${j.message}`);throw new Error(`Subtask completion requires handoff data:
494
+ `);let t=new Set(e.prepare("SELECT version FROM _migrations").all().map(s=>s.version));for(let s of Eh)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}},E=new Zr,O=E});import{z as L}from"zod";var Ph,jh,ou,xh,Rh,Ah,Ih,Dh,iu,sC,au=y(()=>{"use strict";Ph=L.enum(["low","medium","high"]),jh=L.enum(["pending","converted","completed","archived","dormant"]),ou=L.enum(["high","medium","low"]),xh=L.object({impact:ou,effort:ou}),Rh=L.object({frontend:L.string().optional(),backend:L.string().optional(),payments:L.string().optional(),ai:L.string().optional(),deploy:L.string().optional(),other:L.array(L.string()).optional()}),Ah=L.object({name:L.string(),description:L.string()}),Ih=L.object({name:L.string(),description:L.string().optional()}),Dh=L.object({id:L.string(),text:L.string(),details:L.string().optional(),priority:Ph,status:jh,tags:L.array(L.string()),addedAt:L.string(),completedAt:L.string().optional(),convertedTo:L.string().optional(),source:L.string().optional(),sourceFiles:L.array(L.string()).optional(),painPoints:L.array(L.string()).optional(),solutions:L.array(L.string()).optional(),filesAffected:L.array(L.string()).optional(),impactEffort:xh.optional(),implementationNotes:L.string().optional(),stack:Rh.optional(),modules:L.array(Ah).optional(),roles:L.array(Ih).optional(),risks:L.array(L.string()).optional(),risksCount:L.number().optional()}),iu=L.object({ideas:L.array(Dh),lastUpdated:L.string()}),sC={priority:"medium",status:"pending",tags:[],addedAt:new Date().toISOString()}});import $h from"node:crypto";import{homedir as Mh}from"node:os";import{join as Nh}from"node:path";function Ze(){return $h.randomUUID()}var cC,Ds=y(()=>{"use strict";c(Ze,"generateUUID");cC=Nh(Mh(),".prjct-cli","projects")});var Bt,Ui,et,ls=y(()=>{"use strict";Ds();be();ae();Bt={SHIPPED_RETENTION_DAYS:90,IDEA_DORMANT_DAYS:180,QUEUE_COMPLETED_DAYS:7,PAUSED_TASK_DAYS:30,MEMORY_MAX_ENTRIES:500},Ui=class{static{c(this,"ArchiveStorage")}archive(e,t){let s=Ze(),r=C();return E.run(e,"INSERT INTO archives (id, entity_type, entity_id, entity_data, summary, archived_at, reason) VALUES (?, ?, ?, ?, ?, ?, ?)",s,t.entityType,t.entityId,JSON.stringify(t.entityData),t.summary??null,r,t.reason),s}archiveMany(e,t){if(t.length===0)return 0;let s=C();return E.transaction(e,r=>{let o=r.prepare("INSERT INTO archives (id, entity_type, entity_id, entity_data, summary, archived_at, reason) VALUES (?, ?, ?, ?, ?, ?, ?)");for(let i of t)o.run(Ze(),i.entityType,i.entityId,JSON.stringify(i.entityData),i.summary??null,s,i.reason)}),t.length}getArchived(e,t,s=50){return t?E.query(e,"SELECT * FROM archives WHERE entity_type = ? ORDER BY archived_at DESC LIMIT ?",t,s):E.query(e,"SELECT * FROM archives ORDER BY archived_at DESC LIMIT ?",s)}getStats(e){let t=E.query(e,"SELECT entity_type, COUNT(*) as count FROM archives GROUP BY entity_type"),s={shipped:0,idea:0,queue_task:0,paused_task:0,memory_entry:0,total:0};for(let r of t){let o=r.entity_type;o in s&&(s[o]=r.count),s.total+=r.count}return s}restore(e,t){let s=E.get(e,"SELECT * FROM archives WHERE id = ?",t);return s?(E.run(e,"DELETE FROM archives WHERE id = ?",t),JSON.parse(s.entity_data)):null}pruneOldArchives(e,t){let s=new Date(Date.now()-t*24*60*60*1e3).toISOString(),r=this.getTotalCount(e);E.run(e,"DELETE FROM archives WHERE archived_at < ?",s);let o=this.getTotalCount(e);return r-o}getTotalCount(e){return E.get(e,"SELECT COUNT(*) as count FROM archives")?.count??0}},et=new Ui});var Hi,us,Wi=y(()=>{"use strict";Me();be();J();Hi=class{static{c(this,"SyncEventBus")}async publish(e){let t=D.getSyncPendingPath(e.projectId),s=await Se(t,[])??[],r=Array.isArray(s)?s:[];r.push(e),await ne(t,r)}async getPending(e){let t=D.getSyncPendingPath(e),s=await Se(t,[])??[];return Array.isArray(s)?s:[]}async clearPending(e){let t=D.getSyncPendingPath(e);await ne(t,[])}async updateLastSync(e){let t=D.getLastSyncPath(e),s={timestamp:C(),success:!0};await ne(t,s)}async getLastSync(e){let t=D.getLastSyncPath(e);return await Se(t,null)}},us=new Hi});var Xe,ds=y(()=>{"use strict";Wi();Yn();be();ae();Xe=class{static{c(this,"StorageManager")}filename;cache;constructor(e,t){this.filename=e,this.cache=new Ur({ttl:5e3,maxSize:50})}getStoreKey(){return this.filename.replace(".json","")}async read(e){let t=this.cache.get(e);if(t!==null)return t;try{let s=E.getDoc(e,this.getStoreKey());if(s!==null)return this.cache.set(e,s),s}catch{}return this.getDefault()}async write(e,t){E.setDoc(e,this.getStoreKey(),t),this.cache.set(e,t)}async update(e,t){let s=await this.read(e),r=t(s);return await this.write(e,r),r}async publishEvent(e,t,s){let r={type:t,path:[this.filename.replace(".json","")],data:s,timestamp:C(),projectId:e};await us.publish(r)}async publishEntityEvent(e,t,s,r){let o=`${t}.${s}`,i={...r,timestamp:C()};await this.publishEvent(e,o,i)}async exists(e){try{return E.hasDoc(e,this.getStoreKey())}catch{return!1}}clearCache(e){e?this.cache.delete(e):this.cache.clear()}getCacheStats(){return this.cache.stats()}}});var Gi,Fe,sr=y(()=>{"use strict";au();Ds();be();ls();ds();Gi=class extends Xe{static{c(this,"IdeasStorage")}constructor(){super("ideas.json",iu)}getDefault(){return{ideas:[],lastUpdated:""}}getEventType(e){return`ideas.${e}d`}async getAll(e){return(await this.read(e)).ideas}async getPending(e){return(await this.read(e)).ideas.filter(s=>s.status==="pending")}async addIdea(e,t,s={}){let r={id:Ze(),text:t,status:"pending",priority:s.priority||"medium",tags:s.tags||[],addedAt:C()};return await this.update(e,o=>({ideas:[r,...o.ideas],lastUpdated:C()})),await this.publishEvent(e,"idea.created",{ideaId:r.id,text:r.text,priority:r.priority}),r}async getById(e,t){return(await this.read(e)).ideas.find(r=>r.id===t)}async convertToFeature(e,t,s){await this.update(e,r=>({ideas:r.ideas.map(o=>o.id===t?{...o,status:"converted",convertedTo:s}:o),lastUpdated:C()})),await this.publishEvent(e,"idea.converted",{ideaId:t,featureId:s})}async archive(e,t){await this.update(e,s=>({ideas:s.ideas.map(r=>r.id===t?{...r,status:"archived"}:r),lastUpdated:C()})),await this.publishEvent(e,"idea.archived",{ideaId:t})}async setPriority(e,t,s){await this.update(e,r=>({ideas:r.ideas.map(o=>o.id===t?{...o,priority:s}:o),lastUpdated:C()}))}async addTags(e,t,s){await this.update(e,r=>({ideas:r.ideas.map(o=>o.id===t?{...o,tags:[...new Set([...o.tags,...s])]}:o),lastUpdated:C()}))}async removeIdea(e,t){await this.update(e,s=>({ideas:s.ideas.filter(r=>r.id!==t),lastUpdated:C()}))}async getCounts(e){let t=await this.read(e);return{pending:t.ideas.filter(s=>s.status==="pending").length,converted:t.ideas.filter(s=>s.status==="converted").length,archived:t.ideas.filter(s=>s.status==="archived").length}}async cleanup(e){let s=(await this.read(e)).ideas.filter(a=>a.status==="archived");if(s.length<=50)return{removed:0};let r=s.sort((a,l)=>new Date(l.addedAt).getTime()-new Date(a.addedAt).getTime()),o=new Set(r.slice(50).map(a=>a.id)),i=o.size;return await this.update(e,a=>({ideas:a.ideas.filter(l=>!o.has(l.id)),lastUpdated:C()})),{removed:i}}async markDormantIdeas(e){let t=await this.read(e),s=rn(Bt.IDEA_DORMANT_DAYS),r=t.ideas.filter(i=>i.status==="pending"&&new Date(i.addedAt)<s);if(r.length===0)return 0;et.archiveMany(e,r.map(i=>({entityType:"idea",entityId:i.id,entityData:i,summary:i.text,reason:"dormant"})));let o=new Set(r.map(i=>i.id));return await this.update(e,i=>({ideas:i.ideas.map(a=>o.has(a.id)?{...a,status:"dormant"}:a),lastUpdated:C()})),await this.publishEvent(e,"ideas.dormant",{count:r.length}),r.length}},Fe=new Gi});import{z as k}from"zod";var _h,eo,Oh,Lh,Fh,qi,lu,uu,du,Vi,cu,Uh,Hh,Wh,pu,mu,gu,Gh,qh,NC,Bi=y(()=>{"use strict";Fr();_h=k.enum(["low","medium","high","critical"]),eo=k.enum(["feature","bug","improvement","chore"]),Oh=k.enum(["active","backlog","previously_active"]),Lh=k.enum(["pending","in_progress","completed","blocked","paused","failed","skipped"]),Fh=k.enum(["task_completed","feature_shipped","idea_captured","session_started"]),qi=k.object({title:k.string(),description:k.string(),filesChanged:k.array(k.object({path:k.string(),action:k.enum(["created","modified","deleted"])})),whatWasDone:k.array(k.string()).min(1),outputForNextAgent:k.string().min(1),notes:k.string().optional()}),lu=k.object({output:k.string().min(1,"Subtask output is required"),summary:qi}),uu=k.object({id:k.string(),description:k.string(),domain:k.string(),agent:k.string(),status:Lh,dependsOn:k.array(k.string()),startedAt:k.string().optional(),completedAt:k.string().optional(),output:k.string().optional(),summary:qi.optional(),skipReason:k.string().optional(),blockReason:k.string().optional(),estimatedPoints:k.number().optional(),estimatedMinutes:k.number().optional()}),du=k.object({completed:k.number(),total:k.number(),percentage:k.number()}),Vi=k.object({id:k.string(),description:k.string(),type:eo.optional(),startedAt:k.string(),sessionId:k.string(),featureId:k.string().optional(),subtasks:k.array(uu).optional(),currentSubtaskIndex:k.number().optional(),subtaskProgress:du.optional(),linearId:k.string().optional(),linearUuid:k.string().optional(),estimatedPoints:k.number().optional(),estimatedMinutes:k.number().optional(),modelMetadata:Zs.optional(),tokensIn:k.number().optional(),tokensOut:k.number().optional(),parentDescription:k.string().optional(),branch:k.string().optional(),prUrl:k.string().optional()}),cu=k.object({id:k.string(),description:k.string(),status:k.literal("paused"),startedAt:k.string(),pausedAt:k.string(),pauseReason:k.string().optional(),type:eo.optional(),sessionId:k.string().optional(),featureId:k.string().optional(),subtasks:k.array(uu).optional(),currentSubtaskIndex:k.number().optional(),subtaskProgress:du.optional(),linearId:k.string().optional(),linearUuid:k.string().optional(),estimatedPoints:k.number().optional(),estimatedMinutes:k.number().optional(),modelMetadata:Zs.optional(),tokensIn:k.number().optional(),tokensOut:k.number().optional()}),Uh=k.object({stackConfirmed:k.array(k.string()).optional(),patternsDiscovered:k.array(k.string()).optional(),agentAccuracy:k.array(k.object({agent:k.string(),rating:k.enum(["helpful","neutral","inaccurate"]),note:k.string().optional()})).optional(),issuesEncountered:k.array(k.string()).optional()}),Hh=k.object({taskId:k.string(),title:k.string(),classification:eo,startedAt:k.string(),completedAt:k.string(),subtaskCount:k.number(),subtaskSummaries:k.array(qi),outcome:k.string(),branchName:k.string(),linearId:k.string().optional(),linearUuid:k.string().optional(),prUrl:k.string().optional(),feedback:Uh.optional(),tokensIn:k.number().optional(),tokensOut:k.number().optional()}),Wh=Vi.extend({workspaceId:k.string(),worktreePath:k.string().optional(),agentSessionId:k.string().optional(),jiraId:k.string().optional(),jiraUuid:k.string().optional(),dispatchedFrom:k.string().optional()}),pu=k.object({currentTask:Vi.nullable(),previousTask:cu.nullable().optional(),pausedTasks:k.array(cu).optional(),taskHistory:k.array(Hh).optional(),activeTasks:k.array(Wh).optional(),lastUpdated:k.string()}),mu=k.object({id:k.string(),description:k.string(),body:k.string().optional(),priority:_h,type:eo,featureId:k.string().optional(),originFeature:k.string().optional(),completed:k.boolean(),completedAt:k.string().optional(),createdAt:k.string(),section:Oh,agent:k.string().optional(),groupName:k.string().optional(),groupId:k.string().optional()}),gu=k.object({tasks:k.array(mu),lastUpdated:k.string()}),Gh=k.object({tasksToday:k.number(),tasksThisWeek:k.number(),streak:k.number(),velocity:k.string(),avgDuration:k.string()}),qh=k.object({type:Fh,description:k.string(),timestamp:k.string(),duration:k.string().optional()}),NC=k.object({projectId:k.string(),currentTask:Vi.nullable(),queue:k.array(mu),stats:Gh,recentActivity:k.array(qh),lastSync:k.string()})});function yu(n){return[...n].sort((e,t)=>{let s=hu[e.section]-hu[t.section];return s!==0?s:fu[e.priority]-fu[t.priority]})}function Ji(n,e){let t=new Set;return n.filter(s=>{let r=e(s);return t.has(r)?!1:(t.add(r),!0)})}var fu,hu,zi=y(()=>{"use strict";fu={critical:0,high:1,medium:2,low:3},hu={active:0,previously_active:1,backlog:2};c(yu,"sortBySectionAndPriority");c(Ji,"uniqueBy")});var Xi,Ue,nr=y(()=>{"use strict";Ds();Bi();zi();be();ls();ds();Xi=class extends Xe{static{c(this,"QueueStorage")}constructor(){super("queue.json",gu)}getDefault(){return{tasks:[],lastUpdated:""}}getEventType(e){return`queue.${e}d`}async getTasks(e){return(await this.read(e)).tasks}async getActiveTasks(e){return(await this.read(e)).tasks.filter(s=>s.section==="active"&&!s.completed)}async getBacklog(e){return(await this.read(e)).tasks.filter(s=>s.section==="backlog"&&!s.completed)}async getNextTask(e){let t=await this.getActiveTasks(e);return yu(t)[0]||null}async addTask(e,t){let s={...t,id:Ze(),createdAt:C(),completed:!1};return await this.update(e,r=>({tasks:[...r.tasks,s],lastUpdated:C()})),await this.publishEvent(e,"queue.task_added",{taskId:s.id,description:s.description,priority:s.priority,section:s.section}),s}async addTasks(e,t){let s=C(),r=t.map(o=>({...o,id:Ze(),createdAt:s,completed:!1}));return await this.update(e,o=>({tasks:[...o.tasks,...r],lastUpdated:s})),await this.publishEvent(e,"queue.tasks_added",{count:r.length,tasks:r.map(o=>({id:o.id,description:o.description}))}),r}async removeTask(e,t){await this.update(e,s=>({tasks:s.tasks.filter(r=>r.id!==t),lastUpdated:C()})),await this.publishEvent(e,"queue.task_removed",{taskId:t})}async completeTask(e,t){let s=null;if(await this.update(e,r=>({tasks:r.tasks.map(i=>i.id===t?(s={...i,completed:!0,completedAt:C()},s):i),lastUpdated:C()})),s){let r=s;await this.publishEvent(e,"queue.task_completed",{taskId:t,description:r.description,completedAt:r.completedAt})}return s}async moveToSection(e,t,s){await this.update(e,r=>({tasks:r.tasks.map(o=>o.id===t?{...o,section:s}:o),lastUpdated:C()}))}async setPriority(e,t,s){await this.update(e,r=>({tasks:r.tasks.map(o=>o.id===t?{...o,priority:s}:o),lastUpdated:C()}))}async getTask(e,t){return(await this.read(e)).tasks.find(r=>r.id===t)||null}async updateTask(e,t,s){let r=null;return await this.update(e,o=>({tasks:o.tasks.map(i=>i.id===t?(r={...i,...s},r):i),lastUpdated:C()})),r&&await this.publishEvent(e,"queue.task_updated",{taskId:t}),r}async clearCompleted(e){let s=(await this.read(e)).tasks.filter(r=>r.completed).length;return await this.update(e,r=>({tasks:r.tasks.filter(o=>!o.completed),lastUpdated:C()})),s}async removeStaleCompleted(e){let t=await this.read(e),s=rn(Bt.QUEUE_COMPLETED_DAYS),r=t.tasks.filter(i=>i.completed&&i.completedAt&&new Date(i.completedAt)<s);if(r.length===0)return 0;et.archiveMany(e,r.map(i=>({entityType:"queue_task",entityId:i.id,entityData:i,summary:i.description,reason:"age"})));let o=new Set(r.map(i=>i.id));return await this.update(e,i=>({tasks:i.tasks.filter(a=>!o.has(a.id)),lastUpdated:C()})),await this.publishEvent(e,"queue.stale_removed",{count:r.length}),r.length}},Ue=new Xi});import{z as K}from"zod";var Vh,wu,Bh,Jh,zh,Xh,Kh,Yh,Qh,ku,Su=y(()=>{"use strict";Vh=K.enum(["feature","fix","improvement","refactor"]),wu=K.enum(["pass","warning","fail","skipped"]),Bh=K.enum(["added","changed","fixed","removed"]),Jh=K.object({hours:K.number(),minutes:K.number(),totalMinutes:K.number()}),zh=K.object({filesChanged:K.number().nullable().optional(),linesAdded:K.number().nullable().optional(),linesRemoved:K.number().nullable().optional(),commits:K.number().nullable().optional()}),Xh=K.object({description:K.string(),type:Bh.optional()}),Kh=K.object({lintStatus:wu.nullable().optional(),lintDetails:K.string().optional(),testStatus:wu.nullable().optional(),testDetails:K.string().optional()}),Yh=K.object({hash:K.string().optional(),message:K.string().optional(),branch:K.string().optional()}),Qh=K.object({id:K.string(),name:K.string(),version:K.string().nullable().optional(),type:Vh,agent:K.string().optional(),description:K.string().optional(),changes:K.array(Xh).optional(),codeSnippets:K.array(K.string()).optional(),commit:Yh.optional(),codeMetrics:zh.optional(),qualityMetrics:Kh.optional(),quantitativeImpact:K.string().optional(),duration:Jh.optional(),tasksCompleted:K.number().nullable().optional(),shippedAt:K.string(),featureId:K.string().optional()}),ku=K.object({shipped:K.array(Qh),lastUpdated:K.string()})});var Ki,Ke,bu,$s=y(()=>{"use strict";Ds();Su();be();ls();ds();Ki=class extends Xe{static{c(this,"ShippedStorage")}constructor(){super("shipped.json",ku)}getDefault(){return{shipped:[],lastUpdated:""}}getEventType(e){return`shipped.${e}d`}async getAll(e){return(await this.read(e)).shipped}async getRecent(e,t=5){return(await this.read(e)).shipped.sort((r,o)=>new Date(o.shippedAt).getTime()-new Date(r.shippedAt).getTime()).slice(0,t)}async addShipped(e,t){let s={...t,id:Ze(),shippedAt:C()};return await this.update(e,r=>({shipped:[s,...Array.isArray(r.shipped)?r.shipped:[]],lastUpdated:C()})),await this.publishEvent(e,"feature.shipped",{shipId:s.id,name:s.name,version:s.version,shippedAt:s.shippedAt}),s}async getByVersion(e,t){return(await this.read(e)).shipped.find(r=>r.version===t)}async getCount(e){return(await this.read(e)).shipped.length}async getByDateRange(e,t,s){return(await this.read(e)).shipped.filter(o=>{let i=new Date(o.shippedAt);return i>=t&&i<=s})}async getStats(e,t="month"){let s=new Date,r;switch(t){case"week":r=new Date(s.getTime()-7*24*60*60*1e3);break;case"month":r=new Date(s.getFullYear(),s.getMonth(),1);break;case"year":r=new Date(s.getFullYear(),0,1);break}return{count:(await this.getByDateRange(e,r,s)).length,period:t}}async archiveOldShipped(e){let t=await this.read(e),s=rn(Bt.SHIPPED_RETENTION_DAYS),r=t.shipped.filter(i=>new Date(i.shippedAt)<s);if(r.length===0)return 0;et.archiveMany(e,r.map(i=>({entityType:"shipped",entityId:i.id,entityData:i,summary:`${i.name} v${i.version}`,reason:"age"})));let o=new Set(t.shipped.filter(i=>new Date(i.shippedAt)>=s).map(i=>i.id));return await this.update(e,i=>({shipped:i.shipped.filter(a=>o.has(a.id)),lastUpdated:C()})),await this.publishEvent(e,"shipped.archived",{count:r.length,oldestShippedAt:r[r.length-1]?.shippedAt}),r.length}},Ke=new Ki,bu=Ke});var rr,Yi,Ms,Qi=y(()=>{"use strict";rr={idle:{transitions:["task","next"],prompt:"p. task <description> Start working",description:"No active task"},working:{transitions:["done","pause"],prompt:"p. done Complete task | p. pause Switch context",description:"Task in progress"},paused:{transitions:["resume","task","ship"],prompt:"p. resume Continue | p. task <new> Start different | p. ship Ship directly",description:"Task paused"},completed:{transitions:["ship","task","next","pause","reopen"],prompt:"p. ship Ship it | p. task <next> Start next | p. reopen Reopen for rework",description:"Task completed"},shipped:{transitions:["task","next"],prompt:"p. task <description> Start new task",description:"Feature shipped"}},Yi=class{static{c(this,"WorkflowStateMachine")}getCurrentState(e,t){let s=null;if(t&&e?.activeTasks?.length&&(s=e.activeTasks.find(o=>o.workspaceId===t)),s||(s=e?.currentTask),!s)return(e?.pausedTasks?.length||0)>0||e?.previousTask?.status==="paused"?"paused":"idle";switch((typeof s.status=="string"?s.status:"").toLowerCase()){case"in_progress":case"working":return"working";case"paused":return"paused";case"completed":case"done":return"completed";case"shipped":return"shipped";default:return s?"working":"idle"}}canTransition(e,t){let s=rr[e];if(s.transitions.includes(t))return{valid:!0};let r=s.transitions.map(o=>`prjct ${o}`).join(", ");return{valid:!1,error:`Cannot run 'prjct ${t}' in ${e} state`,suggestion:`Valid commands: ${r}`}}getNextState(e,t){switch(t){case"task":return"working";case"done":return"completed";case"pause":return"paused";case"resume":return"working";case"ship":return"shipped";case"reopen":return"working";case"next":return e;default:return e}}getStateInfo(e){return rr[e]}getPrompt(e){return rr[e].prompt}getValidCommands(e){return rr[e].transitions}formatNextSteps(e){return rr[e].transitions.map(s=>{switch(s){case"task":return"p. task <desc> Start new task";case"done":return"p. done Complete current task";case"pause":return"p. pause Pause and switch context";case"resume":return"p. resume Continue paused task";case"ship":return"p. ship Ship the feature";case"reopen":return"p. reopen Reopen for rework";case"next":return"p. next View task queue";default:return`p. ${s}`}})}},Ms=new Yi});var Zi,_,it=y(()=>{"use strict";Ds();Bi();be();Qi();ls();ds();Zi=class extends Xe{static{c(this,"StateStorage")}constructor(){super("state.json",pu)}getDefault(){return{currentTask:null,previousTask:null,pausedTasks:[],taskHistory:[],activeTasks:[],lastUpdated:""}}getEventType(e){return`state.${e}d`}validateTransition(e,t){let s=Ms.getCurrentState(e),r=Ms.canTransition(s,t);if(!r.valid)throw new Error(`${r.error}. ${r.suggestion||""}`.trim())}async getCurrentTask(e){return(await this.read(e)).currentTask}async startTask(e,t){let s=await this.read(e);this.validateTransition(s,"task");let r={...t,startedAt:C()};return await this.update(e,o=>({...o,currentTask:r,lastUpdated:C()})),await this.publishEvent(e,"task.started",{taskId:r.id,description:r.description,startedAt:r.startedAt,sessionId:r.sessionId}),r}async updateCurrentTask(e,t){let s=await this.read(e);if(!s.currentTask)return null;let r={...s.currentTask,...t};return await this.update(e,o=>({...o,currentTask:r,lastUpdated:C()})),r}async completeTask(e,t){let s=await this.read(e),r=s.currentTask;if(!r)return null;this.validateTransition(s,"done");let o=C(),i=this.createTaskHistoryEntry(r,o,t),a=this.getTaskHistoryFromState(s),l=[i,...a].slice(0,this.maxTaskHistory);return await this.update(e,u=>({...u,currentTask:null,previousTask:null,taskHistory:l,lastUpdated:o})),await this.publishEvent(e,"task.completed",{taskId:r.id,description:r.description,startedAt:r.startedAt,completedAt:o}),r}createTaskHistoryEntry(e,t,s){let r=(e.subtasks||[]).filter(a=>a.status==="completed"&&a.summary).map(a=>a.summary),o=r.length>0?r.map(a=>a.title).join(", "):"Task completed",i={taskId:e.id,title:e.parentDescription||e.description,classification:e.type||"improvement",startedAt:e.startedAt,completedAt:t,subtaskCount:e.subtasks?.length||0,subtaskSummaries:r,outcome:o,branchName:e.branch||"unknown",linearId:e.linearId,linearUuid:e.linearUuid,prUrl:e.prUrl};return s&&(i.feedback=s),e.tokensIn&&(i.tokensIn=e.tokensIn),e.tokensOut&&(i.tokensOut=e.tokensOut),i}maxPausedTasks=5;maxTaskHistory=20;stalenessThresholdDays=30;async pauseTask(e,t){let s=await this.read(e);if(!s.currentTask)return null;this.validateTransition(s,"pause");let r={...s.currentTask,status:"paused",pausedAt:C(),pauseReason:t},o=this.getPausedTasksFromState(s),i=[r,...o].slice(0,this.maxPausedTasks);return await this.update(e,a=>({...a,currentTask:null,previousTask:null,pausedTasks:i,lastUpdated:C()})),await this.publishEvent(e,"task.paused",{taskId:r.id,description:r.description,pausedAt:r.pausedAt,reason:t,pausedCount:i.length}),r}async resumeTask(e,t){let s=await this.read(e),r=this.getPausedTasksFromState(s);if(r.length===0)return null;this.validateTransition(s,"resume");let o=0;if(t&&(o=r.findIndex(f=>f.id===t),o===-1))return null;let i=r[o],a=r.filter((f,T)=>T!==o),{status:l,pausedAt:u,pauseReason:d,...m}=i,p={...m,startedAt:C(),sessionId:i.sessionId??Ze()};return await this.update(e,f=>({...f,currentTask:p,previousTask:null,pausedTasks:a,lastUpdated:C()})),await this.publishEvent(e,"task.resumed",{taskId:p.id,description:p.description,resumedAt:p.startedAt,remainingPaused:a.length}),p}getPausedTasksFromState(e){return Array.isArray(e.pausedTasks)&&e.pausedTasks.length>0?e.pausedTasks:e.previousTask?[e.previousTask]:[]}getTaskHistoryFromState(e){return e.taskHistory||[]}async getStalePausedTasks(e){let t=await this.read(e),s=this.getPausedTasksFromState(t),r=Date.now()-this.stalenessThresholdDays*24*60*60*1e3;return s.filter(o=>new Date(o.pausedAt).getTime()<r)}async archiveStalePausedTasks(e){let t=await this.read(e),s=this.getPausedTasksFromState(t),r=Date.now()-this.stalenessThresholdDays*24*60*60*1e3,o=s.filter(a=>new Date(a.pausedAt).getTime()<r),i=s.filter(a=>new Date(a.pausedAt).getTime()>=r);if(o.length===0)return[];et.archiveMany(e,o.map(a=>({entityType:"paused_task",entityId:a.id,entityData:a,summary:a.description,reason:"staleness"}))),await this.update(e,a=>({...a,pausedTasks:i,previousTask:null,lastUpdated:C()}));for(let a of o)await this.publishEvent(e,"task.archived",{taskId:a.id,description:a.description,pausedAt:a.pausedAt,reason:"staleness"});return o}async clearTask(e){await this.update(e,()=>({currentTask:null,previousTask:null,pausedTasks:[],activeTasks:[],lastUpdated:C()}))}async hasTask(e){let t=await this.read(e),s=this.getPausedTasksFromState(t);return t.currentTask!==null||s.length>0}async getPausedTask(e){let t=await this.read(e);return this.getPausedTasksFromState(t)[0]||null}async getAllPausedTasks(e){let t=await this.read(e);return this.getPausedTasksFromState(t)}async getTaskHistory(e){let t=await this.read(e);return this.getTaskHistoryFromState(t)}async getMostRecentTask(e){let t=await this.read(e);return this.getTaskHistoryFromState(t)[0]||null}async getTaskHistoryByType(e,t){let s=await this.read(e);return this.getTaskHistoryFromState(s).filter(o=>o.classification===t)}async getAggregatedFeedback(e){let s=(await this.getTaskHistory(e)).filter(p=>p.feedback),r=[],o=[],i=[],a=[];for(let p of s){let f=p.feedback;Array.isArray(f.stackConfirmed)&&r.push(...f.stackConfirmed),Array.isArray(f.patternsDiscovered)&&o.push(...f.patternsDiscovered),Array.isArray(f.agentAccuracy)&&i.push(...f.agentAccuracy),Array.isArray(f.issuesEncountered)&&a.push(...f.issuesEncountered)}let l=[...new Set(r)],u=[...new Set(o)],d=new Map;for(let p of a)d.set(p,(d.get(p)||0)+1);let m=[...d.entries()].filter(([p,f])=>f>=2).map(([p])=>p);return{stackConfirmed:l,patternsDiscovered:u,agentAccuracy:i,issuesEncountered:[...new Set(a)],knownGotchas:m}}async startTaskInWorkspace(e,t,s){let r={...t,workspaceId:s,startedAt:C()};return await this.update(e,o=>({...o,activeTasks:[...o.activeTasks||[],r],lastUpdated:C()})),await this.publishEvent(e,"task.started",{taskId:r.id,description:r.description,startedAt:r.startedAt,sessionId:r.sessionId,workspaceId:s}),r}async getCurrentTaskForWorkspace(e,t){return((await this.read(e)).activeTasks||[]).find(r=>r.workspaceId===t)??null}async completeTaskInWorkspace(e,t,s){let r=await this.read(e),i=(r.activeTasks||[]).find(m=>m.workspaceId===t);if(!i)return null;let a=C(),l=this.createTaskHistoryEntry(i,a,s),u=this.getTaskHistoryFromState(r),d=[l,...u].slice(0,this.maxTaskHistory);return await this.update(e,m=>({...m,activeTasks:(m.activeTasks||[]).filter(p=>p.workspaceId!==t),taskHistory:d,lastUpdated:a})),await this.publishEvent(e,"task.completed",{taskId:i.id,description:i.description,startedAt:i.startedAt,completedAt:a,workspaceId:t}),i}async getActiveTasks(e){return(await this.read(e)).activeTasks||[]}async getActiveTaskCount(e){return((await this.read(e)).activeTasks||[]).length}async updateWorkspaceTask(e,t,s){let o=(await this.read(e)).activeTasks||[],i=o.findIndex(l=>l.workspaceId===t);if(i===-1)return null;let a={...o[i],...s,workspaceId:t};return await this.update(e,l=>{let u=[...l.activeTasks||[]];return u[i]=a,{...l,activeTasks:u,lastUpdated:C()}}),a}async addTokens(e,t,s){let r=await this.read(e);if(!r.currentTask)return null;let o=(r.currentTask.tokensIn||0)+t,i=(r.currentTask.tokensOut||0)+s;return await this.update(e,a=>({...a,currentTask:{...a.currentTask,tokensIn:o,tokensOut:i},lastUpdated:C()})),{tokensIn:o,tokensOut:i}}async createSubtasks(e,t){let s=await this.read(e);if(!s.currentTask)return;let r=t.map((o,i)=>({...o,status:i===0?"in_progress":"pending",startedAt:i===0?C():void 0,dependsOn:o.dependsOn||[]}));await this.update(e,o=>({...o,currentTask:{...o.currentTask,subtasks:r,currentSubtaskIndex:0,subtaskProgress:{completed:0,total:r.length,percentage:0}},lastUpdated:C()})),await this.publishEvent(e,"subtasks.created",{taskId:s.currentTask.id,subtaskCount:r.length,subtasks:r.map(o=>({id:o.id,description:o.description,domain:o.domain}))})}async completeSubtask(e,t){let s=lu.safeParse(t);if(!s.success){let T=s.error.issues.map(j=>`${j.path.join(".")}: ${j.message}`);throw new Error(`Subtask completion requires handoff data:
495
495
  ${T.join(`
496
496
  `)}`)}let{output:r,summary:o}=s.data,i=await this.read(e);if(!i.currentTask?.subtasks)return null;let a=i.currentTask.currentSubtaskIndex||0,l=i.currentTask.subtasks[a];if(!l)return null;let u=[...i.currentTask.subtasks];u[a]={...l,status:"completed",completedAt:C(),output:r,summary:o};let d=u.filter(T=>T.status==="completed").length,m=u.length,p=Math.round(d/m*100),f=a+1;return f<u.length&&(u[f]={...u[f],status:"in_progress",startedAt:C()}),await this.update(e,T=>({...T,currentTask:{...T.currentTask,subtasks:u,currentSubtaskIndex:f<m?f:a,subtaskProgress:{completed:d,total:m,percentage:p}},lastUpdated:C()})),await this.publishEvent(e,"subtask.completed",{taskId:i.currentTask.id,subtaskId:l.id,description:l.description,output:r,handoff:o.outputForNextAgent,filesChanged:o.filesChanged.length,progress:{completed:d,total:m,percentage:p}}),f<m?u[f]:null}async getCurrentSubtask(e){let t=await this.read(e);if(!t.currentTask?.subtasks)return null;let s=t.currentTask.currentSubtaskIndex||0;return t.currentTask.subtasks[s]||null}async getNextSubtask(e){let t=await this.read(e);if(!t.currentTask?.subtasks)return null;let s=(t.currentTask.currentSubtaskIndex||0)+1;return t.currentTask.subtasks[s]||null}async getPreviousSubtask(e){let t=await this.read(e);if(!t.currentTask?.subtasks)return null;let s=(t.currentTask.currentSubtaskIndex||0)-1;return s<0?null:t.currentTask.subtasks[s]||null}async getPreviousHandoff(e){let t=await this.getPreviousSubtask(e);return t?.summary?.outputForNextAgent?{fromSubtask:t.description,outputForNextAgent:t.summary.outputForNextAgent,filesChanged:t.summary.filesChanged,whatWasDone:t.summary.whatWasDone}:null}async getSubtasks(e){return(await this.read(e)).currentTask?.subtasks||[]}async getSubtaskProgress(e){return(await this.read(e)).currentTask?.subtaskProgress||null}async hasSubtasks(e){return((await this.read(e)).currentTask?.subtasks?.length||0)>0}async areAllSubtasksComplete(e){let t=await this.read(e);return t.currentTask?.subtasks?t.currentTask.subtasks.every(s=>s.status==="completed"||s.status==="failed"||s.status==="skipped"):!0}async failSubtask(e,t){let s=await this.read(e);if(!s.currentTask?.subtasks)return null;let r=s.currentTask.currentSubtaskIndex||0,o=s.currentTask.subtasks[r];if(!o)return null;let i=[...s.currentTask.subtasks];i[r]={...o,status:"failed",completedAt:C(),output:`Failed: ${t}`};let a=r+1,l=i.length;a<l&&(i[a]={...i[a],status:"in_progress",startedAt:C()});let u=i.filter(m=>m.status==="completed"||m.status==="failed"||m.status==="skipped").length,d=Math.round(u/l*100);return await this.update(e,m=>({...m,currentTask:{...m.currentTask,subtasks:i,currentSubtaskIndex:a<l?a:r,subtaskProgress:{completed:u,total:l,percentage:d}},lastUpdated:C()})),await this.publishEvent(e,"subtask.failed",{taskId:s.currentTask.id,subtaskId:o.id,description:o.description,error:t}),a<l?i[a]:null}async skipSubtask(e,t){let s=await this.read(e);if(!s.currentTask?.subtasks)return null;let r=s.currentTask.currentSubtaskIndex||0,o=s.currentTask.subtasks[r];if(!o)return null;let i=[...s.currentTask.subtasks];i[r]={...o,status:"skipped",completedAt:C(),output:`Skipped: ${t}`,skipReason:t};let a=r+1,l=i.length;a<l&&(i[a]={...i[a],status:"in_progress",startedAt:C()});let u=i.filter(m=>m.status==="completed"||m.status==="failed"||m.status==="skipped").length,d=Math.round(u/l*100);return await this.update(e,m=>({...m,currentTask:{...m.currentTask,subtasks:i,currentSubtaskIndex:a<l?a:r,subtaskProgress:{completed:u,total:l,percentage:d}},lastUpdated:C()})),await this.publishEvent(e,"subtask.skipped",{taskId:s.currentTask.id,subtaskId:o.id,description:o.description,reason:t}),a<l?i[a]:null}async blockSubtask(e,t){let s=await this.read(e);if(!s.currentTask?.subtasks)return null;let r=s.currentTask.currentSubtaskIndex||0,o=s.currentTask.subtasks[r];if(!o)return null;let i=[...s.currentTask.subtasks];i[r]={...o,status:"blocked",output:`Blocked: ${t}`,blockReason:t};let a=r+1,l=i.length;return a<l&&(i[a]={...i[a],status:"in_progress",startedAt:C()}),await this.update(e,u=>({...u,currentTask:{...u.currentTask,subtasks:i,currentSubtaskIndex:a<l?a:r},lastUpdated:C()})),await this.publishEvent(e,"subtask.blocked",{taskId:s.currentTask.id,subtaskId:o.id,description:o.description,blocker:t}),a<l?i[a]:null}},_=new Zi});function ey(){let n=process.env.PRJCT_DEBUG||process.env.DEBUG||"";if(!n)return{level:-1,name:"disabled"};if(Zh.has(n)||n.includes("prjct"))return{level:ln.debug,name:"debug"};let e=ln[n]??-1,t=e>=0?n:"disabled";return{level:e,name:t}}function to(n,e,t){return vu>=n?(...s)=>console[t](e,...s):sy}var ln,Zh,vu,ty,sy,ny,V,ps=y(()=>{"use strict";ln={error:0,warn:1,info:2,debug:3},Zh=new Set(["1","true","*"]);c(ey,"getLogLevel");({level:vu,name:ty}=ey()),sy=c(()=>{},"noop");c(to,"createLogMethod");ny={error:to(ln.error,"[prjct:error]","error"),warn:to(ln.warn,"[prjct:warn]","warn"),info:to(ln.info,"[prjct:info]","log"),debug:to(ln.debug,"[prjct:debug]","log"),isEnabled:c(()=>vu>=0,"isEnabled"),level:c(()=>ty,"level")},V=ny});import ry from"node:fs/promises";import oy from"node:path";import{Hono as iy}from"hono";function ay(n){return D.getGlobalProjectPath(n)}function Tu(n,e){let t=new iy,s=ay(n);return t.get("/state",async r=>{let o=await _.read(n);return r.json(o)}),t.get("/queue",async r=>{let o=await Ue.read(n);return r.json(o)}),t.get("/ideas",async r=>{let o=await Fe.read(n);return r.json(o)}),t.get("/roadmap",async r=>{let o=E.getDoc(n,"roadmap");return o?r.json(o):r.json({features:[],backlog:[],lastUpdated:""})}),t.get("/shipped",async r=>{let o=await Ke.read(n);return r.json(o)}),t.get("/dashboard",async r=>{let[o,i,a,l]=await Promise.all([_.read(n),Ue.read(n),Fe.read(n),Ke.read(n)]),u=E.getDoc(n,"roadmap");return r.json({projectId:n,state:o,queue:i,ideas:a,roadmap:u||{features:[],backlog:[],lastUpdated:""},shipped:l,timestamp:new Date().toISOString()})}),t.post("/state",async r=>{try{let o=await r.req.json();if(!o||typeof o!="object"||Array.isArray(o))return r.json({success:!1,error:"Invalid state object"},400);let i=["currentTask","previousTask","lastUpdated"],a={};for(let l of i)l in o&&(a[l]=o[l]);return await _.write(n,a),r.json({success:!0})}catch{return r.json({success:!1,error:"Internal server error"},400)}}),t.get("/context/:name",async r=>{let o=r.req.param("name");if(!["now","next","ideas","shipped"].includes(o))return r.json({error:"Invalid context file"},400);try{let a=oy.join(s,"context",`${o}.md`),l=await ry.readFile(a,"utf-8");return r.text(l,200,{"Content-Type":"text/markdown"})}catch(a){return $(a)||V.error(`Context read error: ${S(a)}`),r.text("",200,{"Content-Type":"text/markdown"})}}),t}var Eu=y(()=>{"use strict";Me();ae();sr();nr();$s();it();q();ps();c(ay,"getProjectDataPath");c(Tu,"createRoutes")});function cy(n){return{id:n.id,taskId:n.task_id,author:n.author,content:n.content,createdAt:n.created_at,updatedAt:n.updated_at}}function ly(){return`cmt_${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`}var ea,or,Cu=y(()=>{"use strict";ae();c(cy,"rowToComment");c(ly,"generateId");ea=class{static{c(this,"CommentStorage")}addComment(e,t,s,r="user"){let o=ly(),i=new Date().toISOString();return E.run(e,`INSERT INTO queue_task_comments (id, task_id, author, content, created_at, updated_at)
497
497
  VALUES (?, ?, ?, ?, ?, ?)`,o,t,r,s,i,i),{id:o,taskId:t,author:r,content:s,createdAt:i,updatedAt:i}}getComments(e,t){return E.query(e,"SELECT * FROM queue_task_comments WHERE task_id = ? ORDER BY created_at ASC",t).map(cy)}updateComment(e,t,s){return E.get(e,"SELECT id FROM queue_task_comments WHERE id = ?",t)?(E.run(e,"UPDATE queue_task_comments SET content = ?, updated_at = ? WHERE id = ?",s,new Date().toISOString(),t),!0):!1}deleteComment(e,t){return E.get(e,"SELECT id FROM queue_task_comments WHERE id = ?",t)?(E.run(e,"DELETE FROM queue_task_comments WHERE id = ?",t),!0):!1}},or=new ea});var ta,sa,Pu=y(()=>{"use strict";ae();ta=class{static{c(this,"ContextZoneStorage")}recordTransition(e,t,s){E.run(e,`INSERT INTO context_zone_events (project_id, session_id, zone_from, zone_to, usage_percent, action, timestamp)
@@ -1313,7 +1313,7 @@ ${B.yellow(`Command '${n}' not found.`)}
1313
1313
 
1314
1314
  Run 'prjct help' to see all available commands.
1315
1315
  `}function Qv(){let n=[];n.push(""),n.push(B.cyan.bold("All Commands")),n.push("");let e=Object.entries(Ir).sort((t,s)=>t[1].order-s[1].order);for(let[t,s]of e){let r=Un.filter(o=>o.group===t);if(r.length!==0){n.push(`${B.bold(s.title)} ${B.dim(`(${r.length} commands)`)}`),n.push(B.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(B.dim("Run 'prjct help <command>' for detailed help on a specific command.")),n.push(""),n.join(`
1316
- `)}function Zv(n){return n?n==="commands"||n==="all"?Qv():Yv(n):zv()}var Qg,Jv,ef=y(()=>{"use strict";ul();qe();Qg=[{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:"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"]}],Jv=[{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"}];c(zv,"formatMainHelp");c(Xv,"formatTerminalCommandHelp");c(Kv,"formatAgentCommandHelp");c(Yv,"formatCommandHelp");c(Qv,"formatCommandList");c(Zv,"getHelp")});var tf=kf((MF,eT)=>{eT.exports={name:"prjct-cli",version:"2.0.0-alpha.12",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 .",knip:"knip","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.19.14","@modelcontextprotocol/sdk":"1.28.0","better-sqlite3":"12.6.2",chalk:"4.1.2",chokidar:"5.0.0","date-fns":"4.1.0",glob:"13.0.1",hono:"4.12.14","jsonc-parser":"3.3.1",zod:"3.24.1"},overrides:{"path-to-regexp":"8.4.0","brace-expansion":"5.0.5",hono:"4.12.14","@hono/node-server":"1.19.14"},devDependencies:{"@biomejs/biome":"2.3.13","@types/better-sqlite3":"7.6.13","@types/bun":"latest","@types/chokidar":"2.1.7",esbuild:"0.25.0",knip:"6.3.1",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:">=22.22.2"},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 aT={};import sf from"node:os";import pi from"node:path";import je from"chalk";async function tT(){let[n,...e]=process.argv.slice(2);if(["-v","--version","version"].includes(n)){let s=await Promise.resolve().then(()=>Sf(tf()));await oT(s.version),process.exit(0)}if(["-h","--help",void 0].includes(n)&&(iT(),process.exit(0)),n&&!ie.getByName(n)&&!(e.length===0&&nf(n)!==null)){let r=[n,...e.filter(i=>!i.startsWith("-"))].join(" "),o=e.filter(i=>i.startsWith("-"));n="capture",e=[r,...o]}let t=e.includes("--md");t||g.start();try{let s=ie.getByName(n);if(!s){let p=nf(n),f=p?`Did you mean 'prjct ${p}'? Run 'prjct --help' for all commands`:"Run 'prjct --help' to see available commands";g.failWithHint(pr("UNKNOWN_COMMAND",{message:`Unknown command: ${n}`,hint:f})),t||g.end(),process.exit(1)}if(s.deprecated){let p=s.replacedBy?`Use 'prjct ${s.replacedBy}' instead`:"Run 'prjct --help' to see available commands";g.failWithHint({message:`Command '${n}' is deprecated`,hint:p}),t||g.end(),process.exit(1)}s.implemented||(g.failWithHint({message:`Command '${n}' is not yet implemented`,hint:"Run 'prjct --help' to see available commands",docs:"https://github.com/jlopezlira/prjct-cli"}),t||g.end(),process.exit(1));let{parsedArgs:r,options:o}=rT(s,e),i=!process.stdin.isTTY||o.md===!0||o.json===!0;s.requiresLlm&&!i&&(g.failWithHint({message:`'prjct ${n}' requires an AI agent to process its output`,hint:`Use 'p. ${n}' inside Claude/Cursor, or add --md flag`}),t||g.end(),process.exit(1));let a=sT(s,r);a&&(g.failWithHint(a),t||g.end(),process.exit(1));let l=null,u=Date.now();try{l=await I.getProjectId(process.cwd()),l&&(await fn.expireIfStale(l),await fn.touch(l))}catch{}let d=new vs,m;if(n==="analyze")m=await d.analyze(o);else if(n==="setup")m=await d.setup(o);else if(n==="update")m=await d.update(o);else{let p=r.join(" ")||null,f=o.md===!0,j={task:c(v=>d.task(v,process.cwd(),{md:f}),"task"),init:c(v=>d.init({idea:v,yes:o.yes===!0,pack:o.pack?String(o.pack):void 0,persona:o.persona?String(o.persona):void 0}),"init"),ship:c(v=>d.ship(v,process.cwd(),{md:f}),"ship"),workflow:c(v=>d.workflowPrefs(v,process.cwd(),{md:f}),"workflow"),sync:c(()=>d.sync(process.cwd(),{preview:o.preview===!0||o["dry-run"]===!0,yes:o.yes===!0,json:o.json===!0,md:f,package:o.package?String(o.package):void 0,full:o.full===!0}),"sync"),start:c(()=>d.start(),"start"),context:c(v=>d.context(v),"context"),status:c(v=>d.status(v,process.cwd(),{md:f}),"status"),tag:c(v=>d.tag(v,process.cwd(),{md:f}),"tag"),remember:c(v=>d.remember(v,process.cwd(),{md:f,tags:o.tags?String(o.tags):void 0}),"remember"),login:c(()=>d.login({md:f,url:o.url?String(o.url):void 0}),"login"),logout:c(()=>d.logout(),"logout"),auth:c(v=>d.auth(v,{md:f}),"auth"),seed:c(v=>d.seed(v,process.cwd(),{md:f}),"seed"),install:c(()=>d.install(null,process.cwd(),{md:f}),"install"),capture:c(v=>d.capture(v,process.cwd(),{md:f,tags:o.tags?String(o.tags):void 0,force:o.force===!0}),"capture")}[n];if(j)m=await j(p);else throw new Error(`Command '${n}' has no handler`)}if(l){let p=Date.now()-u;try{await fn.trackCommand(l,n,p)}catch{}try{await mr.recordTiming(l,"command_duration",p,{command:n});let f=globalThis.__perfStartNs;if(f){let T=Number(process.hrtime.bigint()-f)/1e6;await mr.recordTiming(l,"startup_time",T)}await mr.recordMemory(l,{command:n})}catch{}}m?.message&&console.log(m.message),t||g.end(),process.exit(m?.success?0:1)}catch(s){console.error("Error:",S(s)),process.env.DEBUG&&console.error(wi(s)),t||g.end(),process.exit(1)}}function sT(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 pr("MISSING_PARAM",{message:`Missing required parameter: ${s}`,hint:`Usage: ${r}`})}return null}function nf(n){let e=ie.getAll().map(r=>r.name),t=null,s=1/0;for(let r of e){let o=nT(n.toLowerCase(),r.toLowerCase());o<s&&(s=o,t=r)}return s<=2?t:null}function nT(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 rT(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 oT(n){let e=await Vt(),t=pi.join(sf.homedir(),".claude","commands","p.md"),s=pi.join(sf.homedir(),".gemini","commands","p.toml"),[r,o,i,a]=await Promise.all([b(t),b(s),b(pi.join(process.cwd(),".cursor","commands","sync.md")),b(pi.join(process.cwd(),".cursor"))]),l=await tn();if(console.log(`
1316
+ `)}function Zv(n){return n?n==="commands"||n==="all"?Qv():Yv(n):zv()}var Qg,Jv,ef=y(()=>{"use strict";ul();qe();Qg=[{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:"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"]}],Jv=[{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"}];c(zv,"formatMainHelp");c(Xv,"formatTerminalCommandHelp");c(Kv,"formatAgentCommandHelp");c(Yv,"formatCommandHelp");c(Qv,"formatCommandList");c(Zv,"getHelp")});var tf=kf((MF,eT)=>{eT.exports={name:"prjct-cli",version:"2.1.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 .",knip:"knip","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.19.14","@modelcontextprotocol/sdk":"1.28.0","better-sqlite3":"12.6.2",chalk:"4.1.2",chokidar:"5.0.0","date-fns":"4.1.0",glob:"13.0.1",hono:"4.12.14","jsonc-parser":"3.3.1",zod:"3.24.1"},overrides:{"path-to-regexp":"8.4.0","brace-expansion":"5.0.5",hono:"4.12.14","@hono/node-server":"1.19.14"},devDependencies:{"@biomejs/biome":"2.3.13","@types/better-sqlite3":"7.6.13","@types/bun":"latest","@types/chokidar":"2.1.7",esbuild:"0.25.0",knip:"6.3.1",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:">=22.22.2"},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 aT={};import sf from"node:os";import pi from"node:path";import je from"chalk";async function tT(){let[n,...e]=process.argv.slice(2);if(["-v","--version","version"].includes(n)){let s=await Promise.resolve().then(()=>Sf(tf()));await oT(s.version),process.exit(0)}if(["-h","--help",void 0].includes(n)&&(iT(),process.exit(0)),n&&!ie.getByName(n)&&!(e.length===0&&nf(n)!==null)){let r=[n,...e.filter(i=>!i.startsWith("-"))].join(" "),o=e.filter(i=>i.startsWith("-"));n="capture",e=[r,...o]}let t=e.includes("--md");t||g.start();try{let s=ie.getByName(n);if(!s){let p=nf(n),f=p?`Did you mean 'prjct ${p}'? Run 'prjct --help' for all commands`:"Run 'prjct --help' to see available commands";g.failWithHint(pr("UNKNOWN_COMMAND",{message:`Unknown command: ${n}`,hint:f})),t||g.end(),process.exit(1)}if(s.deprecated){let p=s.replacedBy?`Use 'prjct ${s.replacedBy}' instead`:"Run 'prjct --help' to see available commands";g.failWithHint({message:`Command '${n}' is deprecated`,hint:p}),t||g.end(),process.exit(1)}s.implemented||(g.failWithHint({message:`Command '${n}' is not yet implemented`,hint:"Run 'prjct --help' to see available commands",docs:"https://github.com/jlopezlira/prjct-cli"}),t||g.end(),process.exit(1));let{parsedArgs:r,options:o}=rT(s,e),i=!process.stdin.isTTY||o.md===!0||o.json===!0;s.requiresLlm&&!i&&(g.failWithHint({message:`'prjct ${n}' requires an AI agent to process its output`,hint:`Use 'p. ${n}' inside Claude/Cursor, or add --md flag`}),t||g.end(),process.exit(1));let a=sT(s,r);a&&(g.failWithHint(a),t||g.end(),process.exit(1));let l=null,u=Date.now();try{l=await I.getProjectId(process.cwd()),l&&(await fn.expireIfStale(l),await fn.touch(l))}catch{}let d=new vs,m;if(n==="analyze")m=await d.analyze(o);else if(n==="setup")m=await d.setup(o);else if(n==="update")m=await d.update(o);else{let p=r.join(" ")||null,f=o.md===!0,j={task:c(v=>d.task(v,process.cwd(),{md:f}),"task"),init:c(v=>d.init({idea:v,yes:o.yes===!0,pack:o.pack?String(o.pack):void 0,persona:o.persona?String(o.persona):void 0}),"init"),ship:c(v=>d.ship(v,process.cwd(),{md:f}),"ship"),workflow:c(v=>d.workflowPrefs(v,process.cwd(),{md:f}),"workflow"),sync:c(()=>d.sync(process.cwd(),{preview:o.preview===!0||o["dry-run"]===!0,yes:o.yes===!0,json:o.json===!0,md:f,package:o.package?String(o.package):void 0,full:o.full===!0}),"sync"),start:c(()=>d.start(),"start"),context:c(v=>d.context(v),"context"),status:c(v=>d.status(v,process.cwd(),{md:f}),"status"),tag:c(v=>d.tag(v,process.cwd(),{md:f}),"tag"),remember:c(v=>d.remember(v,process.cwd(),{md:f,tags:o.tags?String(o.tags):void 0}),"remember"),login:c(()=>d.login({md:f,url:o.url?String(o.url):void 0}),"login"),logout:c(()=>d.logout(),"logout"),auth:c(v=>d.auth(v,{md:f}),"auth"),seed:c(v=>d.seed(v,process.cwd(),{md:f}),"seed"),install:c(()=>d.install(null,process.cwd(),{md:f}),"install"),capture:c(v=>d.capture(v,process.cwd(),{md:f,tags:o.tags?String(o.tags):void 0,force:o.force===!0}),"capture")}[n];if(j)m=await j(p);else throw new Error(`Command '${n}' has no handler`)}if(l){let p=Date.now()-u;try{await fn.trackCommand(l,n,p)}catch{}try{await mr.recordTiming(l,"command_duration",p,{command:n});let f=globalThis.__perfStartNs;if(f){let T=Number(process.hrtime.bigint()-f)/1e6;await mr.recordTiming(l,"startup_time",T)}await mr.recordMemory(l,{command:n})}catch{}}m?.message&&console.log(m.message),t||g.end(),process.exit(m?.success?0:1)}catch(s){console.error("Error:",S(s)),process.env.DEBUG&&console.error(wi(s)),t||g.end(),process.exit(1)}}function sT(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 pr("MISSING_PARAM",{message:`Missing required parameter: ${s}`,hint:`Usage: ${r}`})}return null}function nf(n){let e=ie.getAll().map(r=>r.name),t=null,s=1/0;for(let r of e){let o=nT(n.toLowerCase(),r.toLowerCase());o<s&&(s=o,t=r)}return s<=2?t:null}function nT(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 rT(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 oT(n){let e=await Vt(),t=pi.join(sf.homedir(),".claude","commands","p.md"),s=pi.join(sf.homedir(),".gemini","commands","p.toml"),[r,o,i,a]=await Promise.all([b(t),b(s),b(pi.join(process.cwd(),".cursor","commands","sync.md")),b(pi.join(process.cwd(),".cursor"))]),l=await tn();if(console.log(`
1317
1317
  ${je.cyan("p/")} prjct v${n}
1318
1318
  ${je.dim("Context layer for AI coding agents")}
1319
1319
 
@@ -515,7 +515,7 @@ No changes between runs.`;let e=[];e.push("## Analysis Diff"),(n.beforeCommit||n
515
515
  name TEXT NOT NULL,
516
516
  applied_at TEXT NOT NULL
517
517
  )
518
- `);let t=new Set(e.prepare("SELECT version FROM _migrations").all().map(r=>r.version));for(let r of Rm)t.has(r.version)||e.transaction(()=>{r.up(e),e.prepare("INSERT INTO _migrations (version, name, applied_at) VALUES (?, ?, ?)").run(r.version,r.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}},w=new dn,F=w});import Im from"node:fs/promises";import Dm from"node:path";function xr(n){return n.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").replace(/[-_./]/g," ").toLowerCase().split(/\s+/).filter(e=>e.length>1)}function $m(n,e){let t=[],r=e.replace(/\.[^.]+$/,"").split(/[/\\]/).filter(Boolean);for(let m of r)t.push(...xr(m));let s=[/export\s+(?:async\s+)?function\s+(\w+)/g,/export\s+class\s+(\w+)/g,/export\s+interface\s+(\w+)/g,/export\s+type\s+(\w+)/g,/export\s+(?:const|let|var)\s+(\w+)/g,/export\s+default\s+(?:class|function)\s+(\w+)/g];for(let m of s){let f;for(;(f=m.exec(n))!==null;)f[1]&&t.push(...xr(f[1]))}let o=[/(?:async\s+)?function\s+(\w+)/g,/class\s+(\w+)/g,/interface\s+(\w+)/g,/type\s+(\w+)\s*=/g];for(let m of o){let f;for(;(f=m.exec(n))!==null;)f[1]&&t.push(...xr(f[1]))}let i=/(?:from|import)\s+['"]([^'"]+)['"]/g,a;for(;(a=i.exec(n))!==null;){let m=a[1];if(m.startsWith(".")||m.startsWith("@/"))t.push(...xr(m));else{let f=m.startsWith("@")?m.split("/").slice(0,2).join("/"):m.split("/")[0];t.push(...xr(f))}}let c=/\/\/\s*(.+)/g,u;for(;(u=c.exec(n))!==null;){let m=u[1].toLowerCase().split(/\s+/).filter(f=>f.length>2);t.push(...m)}let d=/\/\*\*?([\s\S]*?)\*\//g,p;for(;(p=d.exec(n))!==null;){let m=p[1].replace(/@\w+/g,"").replace(/\*/g,"").toLowerCase().split(/\s+/).filter(f=>f.length>2&&/^[a-z]+$/.test(f));t.push(...m)}return t.filter(m=>m.length>1&&!qc.has(m)&&/^[a-z][a-z0-9]*$/.test(m))}function Nm(n){return n.split(/\s+/).flatMap(e=>xr(e)).filter(e=>e.length>1&&!qc.has(e)&&/^[a-z][a-z0-9]*$/.test(e))}async function _m(n){let e=await yr(n),t={},r={},s=0,o=await wr(e,50,async a=>{try{let c=await Im.readFile(Dm.join(n,a),"utf-8"),u=$m(c,a);return u.length>0?{filePath:a,tokens:u}:null}catch{return null}});for(let{filePath:a,tokens:c}of o){t[a]={tokens:c,length:c.length},s+=c.length;let u=new Map;for(let d of c)u.set(d,(u.get(d)||0)+1);for(let[d,p]of u)r[d]||(r[d]=[]),r[d].push({path:a,tf:p})}let i=Object.keys(t).length;return{documents:t,invertedIndex:r,avgDocLength:i>0?s/i:0,totalDocs:i,builtAt:new Date().toISOString()}}function Om(n,e){return Math.log((e-n+.5)/(n+.5)+1)}function Mm(n,e){let t=Nm(n);if(t.length===0)return[];let r=new Map;for(let s of t){let o=e.invertedIndex[s];if(!o)continue;let i=Om(o.length,e.totalDocs);for(let{path:a,tf:c}of o){let u=e.documents[a];if(!u)continue;let d=c*(1.2+1),p=c+1.2*(1-.75+.75*(u.length/e.avgDocLength)),m=i*(d/p);r.set(a,(r.get(a)||0)+m)}}return Array.from(r.entries()).map(([s,o])=>({path:s,score:o})).sort((s,o)=>o.score-s.score)}function Lm(n,e){let t={invertedIndex:e.invertedIndex,avgDocLength:e.avgDocLength,totalDocs:e.totalDocs,builtAt:e.builtAt,docLengths:Object.fromEntries(Object.entries(e.documents).map(([r,s])=>[r,s.length]))};F.setDoc(n,Bc,t)}function pn(n){let e=F.getDoc(n,Bc);if(!e)return null;let t={};for(let[r,s]of Object.entries(e.docLengths))t[r]={tokens:[],length:s};return{documents:t,invertedIndex:e.invertedIndex,avgDocLength:e.avgDocLength,totalDocs:e.totalDocs,builtAt:e.builtAt}}async function Jc(n,e){let t=await _m(n);return Lm(e,t),t}function zc(n,e,t=15){let r=pn(n);return r?Mm(e,r).slice(0,t):[]}var qc,Bc,Uo=v(()=>{"use strict";Mo();ae();J();qc=new Set(["the","a","an","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","shall","can","of","in","to","for","with","on","at","from","by","as","or","and","but","if","not","no","so","up","out","this","that","it","its","all","any","import","export","default","const","let","var","function","class","interface","type","return","new","true","false","null","undefined","void","async","await","static","public","private","protected","readonly","string","number","boolean","object","array"]);l(xr,"splitIdentifier");l($m,"tokenizeFile");l(Nm,"tokenizeQuery");l(_m,"buildIndex");l(Om,"idf");l(Mm,"score");Bc="bm25-index";l(Lm,"saveIndex");l(pn,"loadIndex");l(Jc,"indexProject");l(zc,"queryFiles")});import Ho from"node:fs/promises";import $t from"node:path";import{z as U}from"zod";async function Gm(n,e){let t=Date.now();if(n.frameworks.length===0)return{name:"Framework verification",passed:!0,output:"No frameworks declared (skipped)",durationMs:Date.now()-t};try{let r=$t.join(e,"package.json"),s=await Ho.readFile(r,"utf-8"),o=JSON.parse(s),i={...o.dependencies,...o.devDependencies},a=[],c=[];for(let u of n.frameworks){let d=u.toLowerCase();Object.keys(i).some(m=>m.toLowerCase().includes(d))?c.push(u):a.push(u)}return a.length===0?{name:"Framework verification",passed:!0,output:`${c.length} framework(s) verified in dependencies`,durationMs:Date.now()-t}:{name:"Framework verification",passed:!1,error:`Frameworks not found in dependencies: ${a.join(", ")}`,durationMs:Date.now()-t}}catch(r){return A(r)?{name:"Framework verification",passed:!1,error:"package.json not found (cannot verify frameworks)",durationMs:Date.now()-t}:{name:"Framework verification",passed:!1,error:`Failed to read package.json: ${r instanceof Error?r.message:"unknown error"}`,durationMs:Date.now()-t}}}async function Vm(n,e){let t=Date.now();if(n.languages.length===0)return{name:"Language verification",passed:!0,output:"No languages declared (skipped)",durationMs:Date.now()-t};try{let r=await zm(e),s=new Set(r),o=[],i=[];for(let a of n.languages){let c=Wm[a];if(!c)continue;c.some(d=>s.has(d))?o.push(a):i.push(a)}return i.length===0?{name:"Language verification",passed:!0,output:`${o.length} language(s) verified with matching files`,durationMs:Date.now()-t}:{name:"Language verification",passed:!1,error:`Languages without matching files: ${i.join(", ")}`,durationMs:Date.now()-t}}catch(r){return{name:"Language verification",passed:!1,error:`Failed to scan project files: ${r instanceof Error?r.message:"unknown error"}`,durationMs:Date.now()-t}}}async function qm(n,e){let t=Date.now(),r=n.patterns.filter(i=>i.location);if(r.length===0)return{name:"Pattern location verification",passed:!0,output:"No pattern locations specified (skipped)",durationMs:Date.now()-t};let s=[],o=[];for(let i of r){let a=i.location,c=$t.join(e,a);await b(c)?o.push(a):s.push(`${i.name} (${a})`)}return s.length===0?{name:"Pattern location verification",passed:!0,output:`${o.length} pattern location(s) verified`,durationMs:Date.now()-t}:{name:"Pattern location verification",passed:!1,error:`Pattern locations not found: ${s.join(", ")}`,durationMs:Date.now()-t}}async function Bm(n,e){let t=Date.now();try{let r=await Xm(e),s=n.fileCount,o=.1,i=Math.abs(r-s),a=s*o;return i<=a?{name:"File count verification",passed:!0,output:`File count accurate (declared: ${s}, actual: ${r})`,durationMs:Date.now()-t}:{name:"File count verification",passed:!1,error:`File count mismatch: declared ${s}, actual ${r} (diff: ${i})`,durationMs:Date.now()-t}}catch(r){return{name:"File count verification",passed:!1,error:`Failed to count files: ${r instanceof Error?r.message:"unknown error"}`,durationMs:Date.now()-t}}}async function Jm(n,e){let t=Date.now();if(n.antiPatterns.length===0)return{name:"Anti-pattern file verification",passed:!0,output:"No anti-patterns declared (skipped)",durationMs:Date.now()-t};let r=[],s=[];for(let o of n.antiPatterns){let i=$t.join(e,o.file);await b(i)?s.push(o.file):r.push(`${o.issue} (${o.file})`)}return r.length===0?{name:"Anti-pattern file verification",passed:!0,output:`${s.length} anti-pattern file(s) verified`,durationMs:Date.now()-t}:{name:"Anti-pattern file verification",passed:!1,error:`Anti-pattern files not found: ${r.join(", ")}`,durationMs:Date.now()-t}}async function Xc(n,e){let t=Date.now(),r=await Promise.all([Gm(n,e),Vm(n,e),qm(n,e),Bm(n,e),Jm(n,e)]),s=r.filter(i=>!i.passed).length,o=r.filter(i=>i.passed).length;return{passed:s===0,checks:r,totalMs:Date.now()-t,failedCount:s,passedCount:o}}async function zm(n){let e=new Set,t=[/node_modules/,/\.git/,/dist/,/build/,/\.next/,/\.turbo/,/coverage/];async function r(s){try{let o=await Ho.readdir(s,{withFileTypes:!0});for(let i of o){let a=$t.join(s,i.name),c=$t.relative(n,a);if(!t.some(u=>u.test(c))){if(i.isDirectory())await r(a);else if(i.isFile()){let u=$t.extname(i.name);u&&e.add(u)}}}}catch{}}return l(r,"scanDir"),await r(n),Array.from(e)}async function Xm(n){let e=0,t=[/node_modules/,/\.git/,/dist/,/build/,/\.next/,/\.turbo/,/coverage/];async function r(s){try{let o=await Ho.readdir(s,{withFileTypes:!0});for(let i of o){let a=$t.join(s,i.name),c=$t.relative(n,a);t.some(u=>u.test(c))||(i.isDirectory()?await r(a):i.isFile()&&e++)}}catch{}}return l(r,"scanDir"),await r(n),e}var Fm,Um,Hm,Wo,kT,Wm,Kc=v(()=>{"use strict";q();J();Ks();Fm=U.enum(["draft","verified","sealed"]),Um=U.object({name:U.string(),description:U.string(),location:U.string().optional(),severity:U.enum(["low","medium","high"]).optional(),language:U.string().optional(),framework:U.string().optional(),source:U.enum(["baseline","repo","context7","feedback"]).optional(),confidence:U.number().min(0).max(1).optional()}),Hm=U.object({issue:U.string(),file:U.string(),suggestion:U.string(),severity:U.enum(["low","medium","high"]).optional(),language:U.string().optional(),framework:U.string().optional(),source:U.enum(["baseline","repo","context7","feedback"]).optional(),confidence:U.number().min(0).max(1).optional()}),Wo=U.object({projectId:U.string(),languages:U.array(U.string()),frameworks:U.array(U.string()),packageManager:U.string().optional(),sourceDir:U.string().optional(),testDir:U.string().optional(),configFiles:U.array(U.string()),fileCount:U.number(),patterns:U.array(Um),antiPatterns:U.array(Hm),analyzedAt:U.string(),modelMetadata:Er.optional(),status:Fm.default("draft"),commitHash:U.string().optional(),signature:U.string().optional(),sealedAt:U.string().optional(),verifiedAt:U.string().optional()}),kT={languages:[],frameworks:[],configFiles:[],fileCount:0,patterns:[],antiPatterns:[],analyzedAt:new Date().toISOString(),status:"draft"},Wm={TypeScript:[".ts",".tsx",".mts",".cts"],JavaScript:[".js",".jsx",".mjs",".cjs"],Python:[".py",".pyw"],Java:[".java"],Go:[".go"],Rust:[".rs"],Ruby:[".rb"],PHP:[".php"],Swift:[".swift"],Kotlin:[".kt",".kts"],"C++":[".cpp",".cc",".cxx",".hpp",".h"],C:[".c",".h"],"C#":[".cs"],Elixir:[".ex",".exs"],Scala:[".scala"]};l(Gm,"verifyFrameworks");l(Vm,"verifyLanguages");l(qm,"verifyPatternLocations");l(Bm,"verifyFileCount");l(Jm,"verifyAntiPatternFiles");l(Xc,"semanticVerify");l(zm,"getProjectExtensions");l(Xm,"countProjectFiles")});import{createHash as Yc}from"node:crypto";function ls(n){return Yc("sha256").update(n).digest("hex")}function Qc(n){return ls(n).slice(0,16)}function Zc(n){return Yc("md5").update(n).digest("hex")}var us=v(()=>{"use strict";l(ls,"sha256");l(Qc,"sha256Short");l(Zc,"md5")});var Go,Nt,Vo=v(()=>{"use strict";Ee();ye();J();Go=class{static{l(this,"SyncEventBus")}async publish(e){let t=R.getSyncPendingPath(e.projectId),r=await me(t,[])??[],s=Array.isArray(r)?r:[];s.push(e),await te(t,s)}async getPending(e){let t=R.getSyncPendingPath(e),r=await me(t,[])??[];return Array.isArray(r)?r:[]}async clearPending(e){let t=R.getSyncPendingPath(e);await te(t,[])}async updateLastSync(e){let t=R.getLastSyncPath(e),r={timestamp:E(),success:!0};await te(t,r)}async getLastSync(e){let t=R.getLastSyncPath(e);return await me(t,null)}},Nt=new Go});var De,_t=v(()=>{"use strict";Vo();Zs();ye();ae();De=class{static{l(this,"StorageManager")}filename;cache;constructor(e,t){this.filename=e,this.cache=new Ys({ttl:5e3,maxSize:50})}getStoreKey(){return this.filename.replace(".json","")}async read(e){let t=this.cache.get(e);if(t!==null)return t;try{let r=w.getDoc(e,this.getStoreKey());if(r!==null)return this.cache.set(e,r),r}catch{}return this.getDefault()}async write(e,t){w.setDoc(e,this.getStoreKey(),t),this.cache.set(e,t)}async update(e,t){let r=await this.read(e),s=t(r);return await this.write(e,s),s}async publishEvent(e,t,r){let s={type:t,path:[this.filename.replace(".json","")],data:r,timestamp:E(),projectId:e};await Nt.publish(s)}async publishEntityEvent(e,t,r,s){let o=`${t}.${r}`,i={...s,timestamp:E()};await this.publishEvent(e,o,i)}async exists(e){try{return w.hasDoc(e,this.getStoreKey())}catch{return!1}}clearCache(e){e?this.cache.delete(e):this.cache.clear()}getCacheStats(){return this.cache.stats()}}});var qo,Me,ds=v(()=>{"use strict";Kc();Oo();ye();us();_t();qo=class extends De{static{l(this,"AnalysisStorage")}constructor(){super("analysis.json")}getDefault(){return{draft:null,sealed:null,previousSealed:null,lastUpdated:""}}getEventType(e){return`analysis.${e}d`}async saveDraft(e,t){let r={...t,status:"draft"};Wo.parse(r),await this.update(e,s=>({...s,draft:r,lastUpdated:E()})),await this.publishEntityEvent(e,"analysis","drafted",{commitHash:r.commitHash,fileCount:r.fileCount})}async seal(e){let t=await this.read(e);if(!t.draft)return{success:!1,error:"No draft analysis to seal. Run `p. sync` first."};if(t.draft.status==="sealed")return{success:!1,error:"Draft is already sealed."};let r=this.computeSignature(t.draft),s=E(),o={...t.draft,status:"sealed",signature:r,sealedAt:s};return Wo.parse(o),await this.write(e,{draft:null,sealed:o,previousSealed:t.sealed,lastUpdated:s}),await this.publishEntityEvent(e,"analysis","sealed",{commitHash:o.commitHash,signature:r}),{success:!0,signature:r}}async getSealed(e){return(await this.read(e)).sealed}async getDraft(e){return(await this.read(e)).draft}async getActive(e){let t=await this.read(e);return t.sealed??t.draft}async getStatus(e){let t=await this.read(e);return{hasSealed:t.sealed!==null,hasDraft:t.draft!==null,hasPreviousSealed:t.previousSealed!==null,sealedCommit:t.sealed?.commitHash??null,draftCommit:t.draft?.commitHash??null,previousSealedCommit:t.previousSealed?.commitHash??null,sealedAt:t.sealed?.sealedAt??null}}async rollback(e){let t=await this.read(e);if(!t.previousSealed)return{success:!1,error:"No previous sealed version to rollback to."};let r=E();return await this.write(e,{draft:t.sealed,sealed:t.previousSealed,previousSealed:null,lastUpdated:r}),await this.publishEntityEvent(e,"analysis","rolled_back",{restoredCommit:t.previousSealed.commitHash,restoredSignature:t.previousSealed.signature}),{success:!0,restoredSignature:t.previousSealed.signature}}async diff(e){let t=await this.read(e);return!t.sealed||!t.draft?null:Lc(t.sealed,t.draft)}checkStaleness(e,t){return e?t?e!==t?{isStale:!0,sealedCommit:e,currentCommit:t,message:`Analysis is stale: sealed at ${e}, HEAD is ${t}. Run \`p. sync\` + \`p. seal\` to update.`}:{isStale:!1,sealedCommit:e,currentCommit:t,message:"Analysis is current."}:{isStale:!0,sealedCommit:e,currentCommit:null,message:"Cannot determine current commit. Analysis may be stale."}:{isStale:!1,sealedCommit:null,currentCommit:t,message:"No sealed analysis. Run `p. sync` then `p. seal`."}}async verify(e){let t=await this.read(e);if(!t.sealed)return{valid:!1,message:"No sealed analysis to verify."};if(!t.sealed.signature)return{valid:!1,message:"Sealed analysis has no signature."};let r=this.computeSignature({...t.sealed,signature:void 0,sealedAt:void 0});return r===t.sealed.signature?{valid:!0,message:"Signature verified. Analysis integrity confirmed."}:{valid:!1,message:`Signature mismatch. Expected ${r}, got ${t.sealed.signature}. Analysis may have been modified.`}}async semanticVerify(e,t){let r=await this.read(e),s=r.sealed??r.draft;return s?await Xc(s,t):{passed:!1,checks:[{name:"Analysis availability",passed:!1,error:"No analysis available. Run `p. sync` to generate.",durationMs:0}],totalMs:0,failedCount:1,passedCount:0}}computeSignature(e){let t={projectId:e.projectId,languages:e.languages,frameworks:e.frameworks,packageManager:e.packageManager,sourceDir:e.sourceDir,testDir:e.testDir,configFiles:e.configFiles,fileCount:e.fileCount,patterns:e.patterns,antiPatterns:e.antiPatterns,analyzedAt:e.analyzedAt,commitHash:e.commitHash};return ls(JSON.stringify(t))}},Me=new qo});var Bo,mn,Tt,ps=v(()=>{"use strict";ye();ae();Bo=class{static{l(this,"LLMAnalysisStorage")}save(e,t){let r=w.getDb(e),s=E();r.transaction(()=>{r.prepare("UPDATE llm_analysis SET status = 'superseded', superseded_at = ? WHERE status = 'active'").run(s),r.prepare("INSERT INTO llm_analysis (commit_hash, status, analysis, analyzed_at) VALUES (?, ?, ?, ?)").run(t.commitHash??null,"active",JSON.stringify(t),t.analyzedAt)})()}getActive(e){let t=w.get(e,"SELECT analysis FROM llm_analysis WHERE status = 'active' LIMIT 1");return t?JSON.parse(t.analysis):null}getActiveSummary(e){let t=this.getActive(e);return t?{commitHash:t.commitHash,architectureStyle:t.architecture.style,patternCount:t.patterns.length,antiPatternCount:t.antiPatterns.length,analyzedAt:t.analyzedAt}:null}isCurrent(e,t){return t?w.get(e,"SELECT commit_hash FROM llm_analysis WHERE status = 'active' LIMIT 1")?.commit_hash===t:!1}getHistory(e,t=10){return w.query(e,"SELECT id, commit_hash, status, analyzed_at, analysis FROM llm_analysis ORDER BY id DESC LIMIT ?",t).map(s=>{let o=JSON.parse(s.analysis);return{id:s.id,commitHash:s.commit_hash,status:s.status,analyzedAt:s.analyzed_at,patternCount:o.patterns.length}})}},mn=new Bo,Tt=mn});import Km from"node:crypto";import{homedir as Ym}from"node:os";import{join as Qm}from"node:path";function Le(){return Km.randomUUID()}var XT,Qt=v(()=>{"use strict";l(Le,"generateUUID");XT=Qm(Ym(),".prjct-cli","projects")});import{z as h}from"zod";var Zm,gn,eg,tg,rg,Jo,tl,rl,sl,zo,el,sg,ng,og,nl,ol,il,ig,ag,ev,Xo=v(()=>{"use strict";Ks();Zm=h.enum(["low","medium","high","critical"]),gn=h.enum(["feature","bug","improvement","chore"]),eg=h.enum(["active","backlog","previously_active"]),tg=h.enum(["pending","in_progress","completed","blocked","paused","failed","skipped"]),rg=h.enum(["task_completed","feature_shipped","idea_captured","session_started"]),Jo=h.object({title:h.string(),description:h.string(),filesChanged:h.array(h.object({path:h.string(),action:h.enum(["created","modified","deleted"])})),whatWasDone:h.array(h.string()).min(1),outputForNextAgent:h.string().min(1),notes:h.string().optional()}),tl=h.object({output:h.string().min(1,"Subtask output is required"),summary:Jo}),rl=h.object({id:h.string(),description:h.string(),domain:h.string(),agent:h.string(),status:tg,dependsOn:h.array(h.string()),startedAt:h.string().optional(),completedAt:h.string().optional(),output:h.string().optional(),summary:Jo.optional(),skipReason:h.string().optional(),blockReason:h.string().optional(),estimatedPoints:h.number().optional(),estimatedMinutes:h.number().optional()}),sl=h.object({completed:h.number(),total:h.number(),percentage:h.number()}),zo=h.object({id:h.string(),description:h.string(),type:gn.optional(),startedAt:h.string(),sessionId:h.string(),featureId:h.string().optional(),subtasks:h.array(rl).optional(),currentSubtaskIndex:h.number().optional(),subtaskProgress:sl.optional(),linearId:h.string().optional(),linearUuid:h.string().optional(),estimatedPoints:h.number().optional(),estimatedMinutes:h.number().optional(),modelMetadata:Er.optional(),tokensIn:h.number().optional(),tokensOut:h.number().optional(),parentDescription:h.string().optional(),branch:h.string().optional(),prUrl:h.string().optional()}),el=h.object({id:h.string(),description:h.string(),status:h.literal("paused"),startedAt:h.string(),pausedAt:h.string(),pauseReason:h.string().optional(),type:gn.optional(),sessionId:h.string().optional(),featureId:h.string().optional(),subtasks:h.array(rl).optional(),currentSubtaskIndex:h.number().optional(),subtaskProgress:sl.optional(),linearId:h.string().optional(),linearUuid:h.string().optional(),estimatedPoints:h.number().optional(),estimatedMinutes:h.number().optional(),modelMetadata:Er.optional(),tokensIn:h.number().optional(),tokensOut:h.number().optional()}),sg=h.object({stackConfirmed:h.array(h.string()).optional(),patternsDiscovered:h.array(h.string()).optional(),agentAccuracy:h.array(h.object({agent:h.string(),rating:h.enum(["helpful","neutral","inaccurate"]),note:h.string().optional()})).optional(),issuesEncountered:h.array(h.string()).optional()}),ng=h.object({taskId:h.string(),title:h.string(),classification:gn,startedAt:h.string(),completedAt:h.string(),subtaskCount:h.number(),subtaskSummaries:h.array(Jo),outcome:h.string(),branchName:h.string(),linearId:h.string().optional(),linearUuid:h.string().optional(),prUrl:h.string().optional(),feedback:sg.optional(),tokensIn:h.number().optional(),tokensOut:h.number().optional()}),og=zo.extend({workspaceId:h.string(),worktreePath:h.string().optional(),agentSessionId:h.string().optional(),jiraId:h.string().optional(),jiraUuid:h.string().optional(),dispatchedFrom:h.string().optional()}),nl=h.object({currentTask:zo.nullable(),previousTask:el.nullable().optional(),pausedTasks:h.array(el).optional(),taskHistory:h.array(ng).optional(),activeTasks:h.array(og).optional(),lastUpdated:h.string()}),ol=h.object({id:h.string(),description:h.string(),body:h.string().optional(),priority:Zm,type:gn,featureId:h.string().optional(),originFeature:h.string().optional(),completed:h.boolean(),completedAt:h.string().optional(),createdAt:h.string(),section:eg,agent:h.string().optional(),groupName:h.string().optional(),groupId:h.string().optional()}),il=h.object({tasks:h.array(ol),lastUpdated:h.string()}),ig=h.object({tasksToday:h.number(),tasksThisWeek:h.number(),streak:h.number(),velocity:h.string(),avgDuration:h.string()}),ag=h.object({type:rg,description:h.string(),timestamp:h.string(),duration:h.string().optional()}),ev=h.object({projectId:h.string(),currentTask:zo.nullable(),queue:h.array(ol),stats:ig,recentActivity:h.array(ag),lastSync:h.string()})});var ms,Ko,Zt,Yo=v(()=>{"use strict";ms={idle:{transitions:["task","next"],prompt:"p. task <description> Start working",description:"No active task"},working:{transitions:["done","pause"],prompt:"p. done Complete task | p. pause Switch context",description:"Task in progress"},paused:{transitions:["resume","task","ship"],prompt:"p. resume Continue | p. task <new> Start different | p. ship Ship directly",description:"Task paused"},completed:{transitions:["ship","task","next","pause","reopen"],prompt:"p. ship Ship it | p. task <next> Start next | p. reopen Reopen for rework",description:"Task completed"},shipped:{transitions:["task","next"],prompt:"p. task <description> Start new task",description:"Feature shipped"}},Ko=class{static{l(this,"WorkflowStateMachine")}getCurrentState(e,t){let r=null;if(t&&e?.activeTasks?.length&&(r=e.activeTasks.find(o=>o.workspaceId===t)),r||(r=e?.currentTask),!r)return(e?.pausedTasks?.length||0)>0||e?.previousTask?.status==="paused"?"paused":"idle";switch((typeof r.status=="string"?r.status:"").toLowerCase()){case"in_progress":case"working":return"working";case"paused":return"paused";case"completed":case"done":return"completed";case"shipped":return"shipped";default:return r?"working":"idle"}}canTransition(e,t){let r=ms[e];if(r.transitions.includes(t))return{valid:!0};let s=r.transitions.map(o=>`p. ${o}`).join(", ");return{valid:!1,error:`Cannot run 'p. ${t}' in ${e} state`,suggestion:`Valid commands: ${s}`}}getNextState(e,t){switch(t){case"task":return"working";case"done":return"completed";case"pause":return"paused";case"resume":return"working";case"ship":return"shipped";case"reopen":return"working";case"next":return e;default:return e}}getStateInfo(e){return ms[e]}getPrompt(e){return ms[e].prompt}getValidCommands(e){return ms[e].transitions}formatNextSteps(e){return ms[e].transitions.map(r=>{switch(r){case"task":return"p. task <desc> Start new task";case"done":return"p. done Complete current task";case"pause":return"p. pause Pause and switch context";case"resume":return"p. resume Continue paused task";case"ship":return"p. ship Ship the feature";case"reopen":return"p. reopen Reopen for rework";case"next":return"p. next View task queue";default:return`p. ${r}`}})}},Zt=new Ko});var vt,Qo,Fe,Ot=v(()=>{"use strict";Qt();ye();ae();vt={SHIPPED_RETENTION_DAYS:90,IDEA_DORMANT_DAYS:180,QUEUE_COMPLETED_DAYS:7,PAUSED_TASK_DAYS:30,MEMORY_MAX_ENTRIES:500},Qo=class{static{l(this,"ArchiveStorage")}archive(e,t){let r=Le(),s=E();return w.run(e,"INSERT INTO archives (id, entity_type, entity_id, entity_data, summary, archived_at, reason) VALUES (?, ?, ?, ?, ?, ?, ?)",r,t.entityType,t.entityId,JSON.stringify(t.entityData),t.summary??null,s,t.reason),r}archiveMany(e,t){if(t.length===0)return 0;let r=E();return w.transaction(e,s=>{let o=s.prepare("INSERT INTO archives (id, entity_type, entity_id, entity_data, summary, archived_at, reason) VALUES (?, ?, ?, ?, ?, ?, ?)");for(let i of t)o.run(Le(),i.entityType,i.entityId,JSON.stringify(i.entityData),i.summary??null,r,i.reason)}),t.length}getArchived(e,t,r=50){return t?w.query(e,"SELECT * FROM archives WHERE entity_type = ? ORDER BY archived_at DESC LIMIT ?",t,r):w.query(e,"SELECT * FROM archives ORDER BY archived_at DESC LIMIT ?",r)}getStats(e){let t=w.query(e,"SELECT entity_type, COUNT(*) as count FROM archives GROUP BY entity_type"),r={shipped:0,idea:0,queue_task:0,paused_task:0,memory_entry:0,total:0};for(let s of t){let o=s.entity_type;o in r&&(r[o]=s.count),r.total+=s.count}return r}restore(e,t){let r=w.get(e,"SELECT * FROM archives WHERE id = ?",t);return r?(w.run(e,"DELETE FROM archives WHERE id = ?",t),JSON.parse(r.entity_data)):null}pruneOldArchives(e,t){let r=new Date(Date.now()-t*24*60*60*1e3).toISOString(),s=this.getTotalCount(e);w.run(e,"DELETE FROM archives WHERE archived_at < ?",r);let o=this.getTotalCount(e);return s-o}getTotalCount(e){return w.get(e,"SELECT COUNT(*) as count FROM archives")?.count??0}},Fe=new Qo});var Zo,$,qe=v(()=>{"use strict";Qt();Xo();ye();Yo();Ot();_t();Zo=class extends De{static{l(this,"StateStorage")}constructor(){super("state.json",nl)}getDefault(){return{currentTask:null,previousTask:null,pausedTasks:[],taskHistory:[],activeTasks:[],lastUpdated:""}}getEventType(e){return`state.${e}d`}validateTransition(e,t){let r=Zt.getCurrentState(e),s=Zt.canTransition(r,t);if(!s.valid)throw new Error(`${s.error}. ${s.suggestion||""}`.trim())}async getCurrentTask(e){return(await this.read(e)).currentTask}async startTask(e,t){let r=await this.read(e);this.validateTransition(r,"task");let s={...t,startedAt:E()};return await this.update(e,o=>({...o,currentTask:s,lastUpdated:E()})),await this.publishEvent(e,"task.started",{taskId:s.id,description:s.description,startedAt:s.startedAt,sessionId:s.sessionId}),s}async updateCurrentTask(e,t){let r=await this.read(e);if(!r.currentTask)return null;let s={...r.currentTask,...t};return await this.update(e,o=>({...o,currentTask:s,lastUpdated:E()})),s}async completeTask(e,t){let r=await this.read(e),s=r.currentTask;if(!s)return null;this.validateTransition(r,"done");let o=E(),i=this.createTaskHistoryEntry(s,o,t),a=this.getTaskHistoryFromState(r),c=[i,...a].slice(0,this.maxTaskHistory);return await this.update(e,u=>({...u,currentTask:null,previousTask:null,taskHistory:c,lastUpdated:o})),await this.publishEvent(e,"task.completed",{taskId:s.id,description:s.description,startedAt:s.startedAt,completedAt:o}),s}createTaskHistoryEntry(e,t,r){let s=(e.subtasks||[]).filter(a=>a.status==="completed"&&a.summary).map(a=>a.summary),o=s.length>0?s.map(a=>a.title).join(", "):"Task completed",i={taskId:e.id,title:e.parentDescription||e.description,classification:e.type||"improvement",startedAt:e.startedAt,completedAt:t,subtaskCount:e.subtasks?.length||0,subtaskSummaries:s,outcome:o,branchName:e.branch||"unknown",linearId:e.linearId,linearUuid:e.linearUuid,prUrl:e.prUrl};return r&&(i.feedback=r),e.tokensIn&&(i.tokensIn=e.tokensIn),e.tokensOut&&(i.tokensOut=e.tokensOut),i}maxPausedTasks=5;maxTaskHistory=20;stalenessThresholdDays=30;async pauseTask(e,t){let r=await this.read(e);if(!r.currentTask)return null;this.validateTransition(r,"pause");let s={...r.currentTask,status:"paused",pausedAt:E(),pauseReason:t},o=this.getPausedTasksFromState(r),i=[s,...o].slice(0,this.maxPausedTasks);return await this.update(e,a=>({...a,currentTask:null,previousTask:null,pausedTasks:i,lastUpdated:E()})),await this.publishEvent(e,"task.paused",{taskId:s.id,description:s.description,pausedAt:s.pausedAt,reason:t,pausedCount:i.length}),s}async resumeTask(e,t){let r=await this.read(e),s=this.getPausedTasksFromState(r);if(s.length===0)return null;this.validateTransition(r,"resume");let o=0;if(t&&(o=s.findIndex(f=>f.id===t),o===-1))return null;let i=s[o],a=s.filter((f,S)=>S!==o),{status:c,pausedAt:u,pauseReason:d,...p}=i,m={...p,startedAt:E(),sessionId:i.sessionId??Le()};return await this.update(e,f=>({...f,currentTask:m,previousTask:null,pausedTasks:a,lastUpdated:E()})),await this.publishEvent(e,"task.resumed",{taskId:m.id,description:m.description,resumedAt:m.startedAt,remainingPaused:a.length}),m}getPausedTasksFromState(e){return Array.isArray(e.pausedTasks)&&e.pausedTasks.length>0?e.pausedTasks:e.previousTask?[e.previousTask]:[]}getTaskHistoryFromState(e){return e.taskHistory||[]}async getStalePausedTasks(e){let t=await this.read(e),r=this.getPausedTasksFromState(t),s=Date.now()-this.stalenessThresholdDays*24*60*60*1e3;return r.filter(o=>new Date(o.pausedAt).getTime()<s)}async archiveStalePausedTasks(e){let t=await this.read(e),r=this.getPausedTasksFromState(t),s=Date.now()-this.stalenessThresholdDays*24*60*60*1e3,o=r.filter(a=>new Date(a.pausedAt).getTime()<s),i=r.filter(a=>new Date(a.pausedAt).getTime()>=s);if(o.length===0)return[];Fe.archiveMany(e,o.map(a=>({entityType:"paused_task",entityId:a.id,entityData:a,summary:a.description,reason:"staleness"}))),await this.update(e,a=>({...a,pausedTasks:i,previousTask:null,lastUpdated:E()}));for(let a of o)await this.publishEvent(e,"task.archived",{taskId:a.id,description:a.description,pausedAt:a.pausedAt,reason:"staleness"});return o}async clearTask(e){await this.update(e,()=>({currentTask:null,previousTask:null,pausedTasks:[],activeTasks:[],lastUpdated:E()}))}async hasTask(e){let t=await this.read(e),r=this.getPausedTasksFromState(t);return t.currentTask!==null||r.length>0}async getPausedTask(e){let t=await this.read(e);return this.getPausedTasksFromState(t)[0]||null}async getAllPausedTasks(e){let t=await this.read(e);return this.getPausedTasksFromState(t)}async getTaskHistory(e){let t=await this.read(e);return this.getTaskHistoryFromState(t)}async getMostRecentTask(e){let t=await this.read(e);return this.getTaskHistoryFromState(t)[0]||null}async getTaskHistoryByType(e,t){let r=await this.read(e);return this.getTaskHistoryFromState(r).filter(o=>o.classification===t)}async getAggregatedFeedback(e){let r=(await this.getTaskHistory(e)).filter(m=>m.feedback),s=[],o=[],i=[],a=[];for(let m of r){let f=m.feedback;Array.isArray(f.stackConfirmed)&&s.push(...f.stackConfirmed),Array.isArray(f.patternsDiscovered)&&o.push(...f.patternsDiscovered),Array.isArray(f.agentAccuracy)&&i.push(...f.agentAccuracy),Array.isArray(f.issuesEncountered)&&a.push(...f.issuesEncountered)}let c=[...new Set(s)],u=[...new Set(o)],d=new Map;for(let m of a)d.set(m,(d.get(m)||0)+1);let p=[...d.entries()].filter(([m,f])=>f>=2).map(([m])=>m);return{stackConfirmed:c,patternsDiscovered:u,agentAccuracy:i,issuesEncountered:[...new Set(a)],knownGotchas:p}}async startTaskInWorkspace(e,t,r){let s={...t,workspaceId:r,startedAt:E()};return await this.update(e,o=>({...o,activeTasks:[...o.activeTasks||[],s],lastUpdated:E()})),await this.publishEvent(e,"task.started",{taskId:s.id,description:s.description,startedAt:s.startedAt,sessionId:s.sessionId,workspaceId:r}),s}async getCurrentTaskForWorkspace(e,t){return((await this.read(e)).activeTasks||[]).find(s=>s.workspaceId===t)??null}async completeTaskInWorkspace(e,t,r){let s=await this.read(e),i=(s.activeTasks||[]).find(p=>p.workspaceId===t);if(!i)return null;let a=E(),c=this.createTaskHistoryEntry(i,a,r),u=this.getTaskHistoryFromState(s),d=[c,...u].slice(0,this.maxTaskHistory);return await this.update(e,p=>({...p,activeTasks:(p.activeTasks||[]).filter(m=>m.workspaceId!==t),taskHistory:d,lastUpdated:a})),await this.publishEvent(e,"task.completed",{taskId:i.id,description:i.description,startedAt:i.startedAt,completedAt:a,workspaceId:t}),i}async getActiveTasks(e){return(await this.read(e)).activeTasks||[]}async getActiveTaskCount(e){return((await this.read(e)).activeTasks||[]).length}async updateWorkspaceTask(e,t,r){let o=(await this.read(e)).activeTasks||[],i=o.findIndex(c=>c.workspaceId===t);if(i===-1)return null;let a={...o[i],...r,workspaceId:t};return await this.update(e,c=>{let u=[...c.activeTasks||[]];return u[i]=a,{...c,activeTasks:u,lastUpdated:E()}}),a}async addTokens(e,t,r){let s=await this.read(e);if(!s.currentTask)return null;let o=(s.currentTask.tokensIn||0)+t,i=(s.currentTask.tokensOut||0)+r;return await this.update(e,a=>({...a,currentTask:{...a.currentTask,tokensIn:o,tokensOut:i},lastUpdated:E()})),{tokensIn:o,tokensOut:i}}async createSubtasks(e,t){let r=await this.read(e);if(!r.currentTask)return;let s=t.map((o,i)=>({...o,status:i===0?"in_progress":"pending",startedAt:i===0?E():void 0,dependsOn:o.dependsOn||[]}));await this.update(e,o=>({...o,currentTask:{...o.currentTask,subtasks:s,currentSubtaskIndex:0,subtaskProgress:{completed:0,total:s.length,percentage:0}},lastUpdated:E()})),await this.publishEvent(e,"subtasks.created",{taskId:r.currentTask.id,subtaskCount:s.length,subtasks:s.map(o=>({id:o.id,description:o.description,domain:o.domain}))})}async completeSubtask(e,t){let r=tl.safeParse(t);if(!r.success){let S=r.error.issues.map(x=>`${x.path.join(".")}: ${x.message}`);throw new Error(`Subtask completion requires handoff data:
518
+ `);let t=new Set(e.prepare("SELECT version FROM _migrations").all().map(r=>r.version));for(let r of Rm)t.has(r.version)||e.transaction(()=>{r.up(e),e.prepare("INSERT INTO _migrations (version, name, applied_at) VALUES (?, ?, ?)").run(r.version,r.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}},w=new dn,F=w});import Im from"node:fs/promises";import Dm from"node:path";function xr(n){return n.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").replace(/[-_./]/g," ").toLowerCase().split(/\s+/).filter(e=>e.length>1)}function $m(n,e){let t=[],r=e.replace(/\.[^.]+$/,"").split(/[/\\]/).filter(Boolean);for(let m of r)t.push(...xr(m));let s=[/export\s+(?:async\s+)?function\s+(\w+)/g,/export\s+class\s+(\w+)/g,/export\s+interface\s+(\w+)/g,/export\s+type\s+(\w+)/g,/export\s+(?:const|let|var)\s+(\w+)/g,/export\s+default\s+(?:class|function)\s+(\w+)/g];for(let m of s){let f;for(;(f=m.exec(n))!==null;)f[1]&&t.push(...xr(f[1]))}let o=[/(?:async\s+)?function\s+(\w+)/g,/class\s+(\w+)/g,/interface\s+(\w+)/g,/type\s+(\w+)\s*=/g];for(let m of o){let f;for(;(f=m.exec(n))!==null;)f[1]&&t.push(...xr(f[1]))}let i=/(?:from|import)\s+['"]([^'"]+)['"]/g,a;for(;(a=i.exec(n))!==null;){let m=a[1];if(m.startsWith(".")||m.startsWith("@/"))t.push(...xr(m));else{let f=m.startsWith("@")?m.split("/").slice(0,2).join("/"):m.split("/")[0];t.push(...xr(f))}}let c=/\/\/\s*(.+)/g,u;for(;(u=c.exec(n))!==null;){let m=u[1].toLowerCase().split(/\s+/).filter(f=>f.length>2);t.push(...m)}let d=/\/\*\*?([\s\S]*?)\*\//g,p;for(;(p=d.exec(n))!==null;){let m=p[1].replace(/@\w+/g,"").replace(/\*/g,"").toLowerCase().split(/\s+/).filter(f=>f.length>2&&/^[a-z]+$/.test(f));t.push(...m)}return t.filter(m=>m.length>1&&!qc.has(m)&&/^[a-z][a-z0-9]*$/.test(m))}function Nm(n){return n.split(/\s+/).flatMap(e=>xr(e)).filter(e=>e.length>1&&!qc.has(e)&&/^[a-z][a-z0-9]*$/.test(e))}async function _m(n){let e=await yr(n),t={},r={},s=0,o=await wr(e,50,async a=>{try{let c=await Im.readFile(Dm.join(n,a),"utf-8"),u=$m(c,a);return u.length>0?{filePath:a,tokens:u}:null}catch{return null}});for(let{filePath:a,tokens:c}of o){t[a]={tokens:c,length:c.length},s+=c.length;let u=new Map;for(let d of c)u.set(d,(u.get(d)||0)+1);for(let[d,p]of u)r[d]||(r[d]=[]),r[d].push({path:a,tf:p})}let i=Object.keys(t).length;return{documents:t,invertedIndex:r,avgDocLength:i>0?s/i:0,totalDocs:i,builtAt:new Date().toISOString()}}function Om(n,e){return Math.log((e-n+.5)/(n+.5)+1)}function Mm(n,e){let t=Nm(n);if(t.length===0)return[];let r=new Map;for(let s of t){let o=e.invertedIndex[s];if(!o)continue;let i=Om(o.length,e.totalDocs);for(let{path:a,tf:c}of o){let u=e.documents[a];if(!u)continue;let d=c*(1.2+1),p=c+1.2*(1-.75+.75*(u.length/e.avgDocLength)),m=i*(d/p);r.set(a,(r.get(a)||0)+m)}}return Array.from(r.entries()).map(([s,o])=>({path:s,score:o})).sort((s,o)=>o.score-s.score)}function Lm(n,e){let t={invertedIndex:e.invertedIndex,avgDocLength:e.avgDocLength,totalDocs:e.totalDocs,builtAt:e.builtAt,docLengths:Object.fromEntries(Object.entries(e.documents).map(([r,s])=>[r,s.length]))};F.setDoc(n,Bc,t)}function pn(n){let e=F.getDoc(n,Bc);if(!e)return null;let t={};for(let[r,s]of Object.entries(e.docLengths))t[r]={tokens:[],length:s};return{documents:t,invertedIndex:e.invertedIndex,avgDocLength:e.avgDocLength,totalDocs:e.totalDocs,builtAt:e.builtAt}}async function Jc(n,e){let t=await _m(n);return Lm(e,t),t}function zc(n,e,t=15){let r=pn(n);return r?Mm(e,r).slice(0,t):[]}var qc,Bc,Uo=v(()=>{"use strict";Mo();ae();J();qc=new Set(["the","a","an","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","shall","can","of","in","to","for","with","on","at","from","by","as","or","and","but","if","not","no","so","up","out","this","that","it","its","all","any","import","export","default","const","let","var","function","class","interface","type","return","new","true","false","null","undefined","void","async","await","static","public","private","protected","readonly","string","number","boolean","object","array"]);l(xr,"splitIdentifier");l($m,"tokenizeFile");l(Nm,"tokenizeQuery");l(_m,"buildIndex");l(Om,"idf");l(Mm,"score");Bc="bm25-index";l(Lm,"saveIndex");l(pn,"loadIndex");l(Jc,"indexProject");l(zc,"queryFiles")});import Ho from"node:fs/promises";import $t from"node:path";import{z as U}from"zod";async function Gm(n,e){let t=Date.now();if(n.frameworks.length===0)return{name:"Framework verification",passed:!0,output:"No frameworks declared (skipped)",durationMs:Date.now()-t};try{let r=$t.join(e,"package.json"),s=await Ho.readFile(r,"utf-8"),o=JSON.parse(s),i={...o.dependencies,...o.devDependencies},a=[],c=[];for(let u of n.frameworks){let d=u.toLowerCase();Object.keys(i).some(m=>m.toLowerCase().includes(d))?c.push(u):a.push(u)}return a.length===0?{name:"Framework verification",passed:!0,output:`${c.length} framework(s) verified in dependencies`,durationMs:Date.now()-t}:{name:"Framework verification",passed:!1,error:`Frameworks not found in dependencies: ${a.join(", ")}`,durationMs:Date.now()-t}}catch(r){return A(r)?{name:"Framework verification",passed:!1,error:"package.json not found (cannot verify frameworks)",durationMs:Date.now()-t}:{name:"Framework verification",passed:!1,error:`Failed to read package.json: ${r instanceof Error?r.message:"unknown error"}`,durationMs:Date.now()-t}}}async function Vm(n,e){let t=Date.now();if(n.languages.length===0)return{name:"Language verification",passed:!0,output:"No languages declared (skipped)",durationMs:Date.now()-t};try{let r=await zm(e),s=new Set(r),o=[],i=[];for(let a of n.languages){let c=Wm[a];if(!c)continue;c.some(d=>s.has(d))?o.push(a):i.push(a)}return i.length===0?{name:"Language verification",passed:!0,output:`${o.length} language(s) verified with matching files`,durationMs:Date.now()-t}:{name:"Language verification",passed:!1,error:`Languages without matching files: ${i.join(", ")}`,durationMs:Date.now()-t}}catch(r){return{name:"Language verification",passed:!1,error:`Failed to scan project files: ${r instanceof Error?r.message:"unknown error"}`,durationMs:Date.now()-t}}}async function qm(n,e){let t=Date.now(),r=n.patterns.filter(i=>i.location);if(r.length===0)return{name:"Pattern location verification",passed:!0,output:"No pattern locations specified (skipped)",durationMs:Date.now()-t};let s=[],o=[];for(let i of r){let a=i.location,c=$t.join(e,a);await b(c)?o.push(a):s.push(`${i.name} (${a})`)}return s.length===0?{name:"Pattern location verification",passed:!0,output:`${o.length} pattern location(s) verified`,durationMs:Date.now()-t}:{name:"Pattern location verification",passed:!1,error:`Pattern locations not found: ${s.join(", ")}`,durationMs:Date.now()-t}}async function Bm(n,e){let t=Date.now();try{let r=await Xm(e),s=n.fileCount,o=.1,i=Math.abs(r-s),a=s*o;return i<=a?{name:"File count verification",passed:!0,output:`File count accurate (declared: ${s}, actual: ${r})`,durationMs:Date.now()-t}:{name:"File count verification",passed:!1,error:`File count mismatch: declared ${s}, actual ${r} (diff: ${i})`,durationMs:Date.now()-t}}catch(r){return{name:"File count verification",passed:!1,error:`Failed to count files: ${r instanceof Error?r.message:"unknown error"}`,durationMs:Date.now()-t}}}async function Jm(n,e){let t=Date.now();if(n.antiPatterns.length===0)return{name:"Anti-pattern file verification",passed:!0,output:"No anti-patterns declared (skipped)",durationMs:Date.now()-t};let r=[],s=[];for(let o of n.antiPatterns){let i=$t.join(e,o.file);await b(i)?s.push(o.file):r.push(`${o.issue} (${o.file})`)}return r.length===0?{name:"Anti-pattern file verification",passed:!0,output:`${s.length} anti-pattern file(s) verified`,durationMs:Date.now()-t}:{name:"Anti-pattern file verification",passed:!1,error:`Anti-pattern files not found: ${r.join(", ")}`,durationMs:Date.now()-t}}async function Xc(n,e){let t=Date.now(),r=await Promise.all([Gm(n,e),Vm(n,e),qm(n,e),Bm(n,e),Jm(n,e)]),s=r.filter(i=>!i.passed).length,o=r.filter(i=>i.passed).length;return{passed:s===0,checks:r,totalMs:Date.now()-t,failedCount:s,passedCount:o}}async function zm(n){let e=new Set,t=[/node_modules/,/\.git/,/dist/,/build/,/\.next/,/\.turbo/,/coverage/];async function r(s){try{let o=await Ho.readdir(s,{withFileTypes:!0});for(let i of o){let a=$t.join(s,i.name),c=$t.relative(n,a);if(!t.some(u=>u.test(c))){if(i.isDirectory())await r(a);else if(i.isFile()){let u=$t.extname(i.name);u&&e.add(u)}}}}catch{}}return l(r,"scanDir"),await r(n),Array.from(e)}async function Xm(n){let e=0,t=[/node_modules/,/\.git/,/dist/,/build/,/\.next/,/\.turbo/,/coverage/];async function r(s){try{let o=await Ho.readdir(s,{withFileTypes:!0});for(let i of o){let a=$t.join(s,i.name),c=$t.relative(n,a);t.some(u=>u.test(c))||(i.isDirectory()?await r(a):i.isFile()&&e++)}}catch{}}return l(r,"scanDir"),await r(n),e}var Fm,Um,Hm,Wo,kT,Wm,Kc=v(()=>{"use strict";q();J();Ks();Fm=U.enum(["draft","verified","sealed"]),Um=U.object({name:U.string(),description:U.string(),location:U.string().optional(),severity:U.enum(["low","medium","high"]).optional(),language:U.string().optional(),framework:U.string().optional(),source:U.enum(["baseline","repo","context7","feedback"]).optional(),confidence:U.number().min(0).max(1).optional()}),Hm=U.object({issue:U.string(),file:U.string(),suggestion:U.string(),severity:U.enum(["low","medium","high"]).optional(),language:U.string().optional(),framework:U.string().optional(),source:U.enum(["baseline","repo","context7","feedback"]).optional(),confidence:U.number().min(0).max(1).optional()}),Wo=U.object({projectId:U.string(),languages:U.array(U.string()),frameworks:U.array(U.string()),packageManager:U.string().optional(),sourceDir:U.string().optional(),testDir:U.string().optional(),configFiles:U.array(U.string()),fileCount:U.number(),patterns:U.array(Um),antiPatterns:U.array(Hm),analyzedAt:U.string(),modelMetadata:Er.optional(),status:Fm.default("draft"),commitHash:U.string().optional(),signature:U.string().optional(),sealedAt:U.string().optional(),verifiedAt:U.string().optional()}),kT={languages:[],frameworks:[],configFiles:[],fileCount:0,patterns:[],antiPatterns:[],analyzedAt:new Date().toISOString(),status:"draft"},Wm={TypeScript:[".ts",".tsx",".mts",".cts"],JavaScript:[".js",".jsx",".mjs",".cjs"],Python:[".py",".pyw"],Java:[".java"],Go:[".go"],Rust:[".rs"],Ruby:[".rb"],PHP:[".php"],Swift:[".swift"],Kotlin:[".kt",".kts"],"C++":[".cpp",".cc",".cxx",".hpp",".h"],C:[".c",".h"],"C#":[".cs"],Elixir:[".ex",".exs"],Scala:[".scala"]};l(Gm,"verifyFrameworks");l(Vm,"verifyLanguages");l(qm,"verifyPatternLocations");l(Bm,"verifyFileCount");l(Jm,"verifyAntiPatternFiles");l(Xc,"semanticVerify");l(zm,"getProjectExtensions");l(Xm,"countProjectFiles")});import{createHash as Yc}from"node:crypto";function ls(n){return Yc("sha256").update(n).digest("hex")}function Qc(n){return ls(n).slice(0,16)}function Zc(n){return Yc("md5").update(n).digest("hex")}var us=v(()=>{"use strict";l(ls,"sha256");l(Qc,"sha256Short");l(Zc,"md5")});var Go,Nt,Vo=v(()=>{"use strict";Ee();ye();J();Go=class{static{l(this,"SyncEventBus")}async publish(e){let t=R.getSyncPendingPath(e.projectId),r=await me(t,[])??[],s=Array.isArray(r)?r:[];s.push(e),await te(t,s)}async getPending(e){let t=R.getSyncPendingPath(e),r=await me(t,[])??[];return Array.isArray(r)?r:[]}async clearPending(e){let t=R.getSyncPendingPath(e);await te(t,[])}async updateLastSync(e){let t=R.getLastSyncPath(e),r={timestamp:E(),success:!0};await te(t,r)}async getLastSync(e){let t=R.getLastSyncPath(e);return await me(t,null)}},Nt=new Go});var De,_t=v(()=>{"use strict";Vo();Zs();ye();ae();De=class{static{l(this,"StorageManager")}filename;cache;constructor(e,t){this.filename=e,this.cache=new Ys({ttl:5e3,maxSize:50})}getStoreKey(){return this.filename.replace(".json","")}async read(e){let t=this.cache.get(e);if(t!==null)return t;try{let r=w.getDoc(e,this.getStoreKey());if(r!==null)return this.cache.set(e,r),r}catch{}return this.getDefault()}async write(e,t){w.setDoc(e,this.getStoreKey(),t),this.cache.set(e,t)}async update(e,t){let r=await this.read(e),s=t(r);return await this.write(e,s),s}async publishEvent(e,t,r){let s={type:t,path:[this.filename.replace(".json","")],data:r,timestamp:E(),projectId:e};await Nt.publish(s)}async publishEntityEvent(e,t,r,s){let o=`${t}.${r}`,i={...s,timestamp:E()};await this.publishEvent(e,o,i)}async exists(e){try{return w.hasDoc(e,this.getStoreKey())}catch{return!1}}clearCache(e){e?this.cache.delete(e):this.cache.clear()}getCacheStats(){return this.cache.stats()}}});var qo,Me,ds=v(()=>{"use strict";Kc();Oo();ye();us();_t();qo=class extends De{static{l(this,"AnalysisStorage")}constructor(){super("analysis.json")}getDefault(){return{draft:null,sealed:null,previousSealed:null,lastUpdated:""}}getEventType(e){return`analysis.${e}d`}async saveDraft(e,t){let r={...t,status:"draft"};Wo.parse(r),await this.update(e,s=>({...s,draft:r,lastUpdated:E()})),await this.publishEntityEvent(e,"analysis","drafted",{commitHash:r.commitHash,fileCount:r.fileCount})}async seal(e){let t=await this.read(e);if(!t.draft)return{success:!1,error:"No draft analysis to seal. Run `p. sync` first."};if(t.draft.status==="sealed")return{success:!1,error:"Draft is already sealed."};let r=this.computeSignature(t.draft),s=E(),o={...t.draft,status:"sealed",signature:r,sealedAt:s};return Wo.parse(o),await this.write(e,{draft:null,sealed:o,previousSealed:t.sealed,lastUpdated:s}),await this.publishEntityEvent(e,"analysis","sealed",{commitHash:o.commitHash,signature:r}),{success:!0,signature:r}}async getSealed(e){return(await this.read(e)).sealed}async getDraft(e){return(await this.read(e)).draft}async getActive(e){let t=await this.read(e);return t.sealed??t.draft}async getStatus(e){let t=await this.read(e);return{hasSealed:t.sealed!==null,hasDraft:t.draft!==null,hasPreviousSealed:t.previousSealed!==null,sealedCommit:t.sealed?.commitHash??null,draftCommit:t.draft?.commitHash??null,previousSealedCommit:t.previousSealed?.commitHash??null,sealedAt:t.sealed?.sealedAt??null}}async rollback(e){let t=await this.read(e);if(!t.previousSealed)return{success:!1,error:"No previous sealed version to rollback to."};let r=E();return await this.write(e,{draft:t.sealed,sealed:t.previousSealed,previousSealed:null,lastUpdated:r}),await this.publishEntityEvent(e,"analysis","rolled_back",{restoredCommit:t.previousSealed.commitHash,restoredSignature:t.previousSealed.signature}),{success:!0,restoredSignature:t.previousSealed.signature}}async diff(e){let t=await this.read(e);return!t.sealed||!t.draft?null:Lc(t.sealed,t.draft)}checkStaleness(e,t){return e?t?e!==t?{isStale:!0,sealedCommit:e,currentCommit:t,message:`Analysis is stale: sealed at ${e}, HEAD is ${t}. Run \`p. sync\` + \`p. seal\` to update.`}:{isStale:!1,sealedCommit:e,currentCommit:t,message:"Analysis is current."}:{isStale:!0,sealedCommit:e,currentCommit:null,message:"Cannot determine current commit. Analysis may be stale."}:{isStale:!1,sealedCommit:null,currentCommit:t,message:"No sealed analysis. Run `p. sync` then `p. seal`."}}async verify(e){let t=await this.read(e);if(!t.sealed)return{valid:!1,message:"No sealed analysis to verify."};if(!t.sealed.signature)return{valid:!1,message:"Sealed analysis has no signature."};let r=this.computeSignature({...t.sealed,signature:void 0,sealedAt:void 0});return r===t.sealed.signature?{valid:!0,message:"Signature verified. Analysis integrity confirmed."}:{valid:!1,message:`Signature mismatch. Expected ${r}, got ${t.sealed.signature}. Analysis may have been modified.`}}async semanticVerify(e,t){let r=await this.read(e),s=r.sealed??r.draft;return s?await Xc(s,t):{passed:!1,checks:[{name:"Analysis availability",passed:!1,error:"No analysis available. Run `p. sync` to generate.",durationMs:0}],totalMs:0,failedCount:1,passedCount:0}}computeSignature(e){let t={projectId:e.projectId,languages:e.languages,frameworks:e.frameworks,packageManager:e.packageManager,sourceDir:e.sourceDir,testDir:e.testDir,configFiles:e.configFiles,fileCount:e.fileCount,patterns:e.patterns,antiPatterns:e.antiPatterns,analyzedAt:e.analyzedAt,commitHash:e.commitHash};return ls(JSON.stringify(t))}},Me=new qo});var Bo,mn,Tt,ps=v(()=>{"use strict";ye();ae();Bo=class{static{l(this,"LLMAnalysisStorage")}save(e,t){let r=w.getDb(e),s=E();r.transaction(()=>{r.prepare("UPDATE llm_analysis SET status = 'superseded', superseded_at = ? WHERE status = 'active'").run(s),r.prepare("INSERT INTO llm_analysis (commit_hash, status, analysis, analyzed_at) VALUES (?, ?, ?, ?)").run(t.commitHash??null,"active",JSON.stringify(t),t.analyzedAt)})()}getActive(e){let t=w.get(e,"SELECT analysis FROM llm_analysis WHERE status = 'active' LIMIT 1");return t?JSON.parse(t.analysis):null}getActiveSummary(e){let t=this.getActive(e);return t?{commitHash:t.commitHash,architectureStyle:t.architecture.style,patternCount:t.patterns.length,antiPatternCount:t.antiPatterns.length,analyzedAt:t.analyzedAt}:null}isCurrent(e,t){return t?w.get(e,"SELECT commit_hash FROM llm_analysis WHERE status = 'active' LIMIT 1")?.commit_hash===t:!1}getHistory(e,t=10){return w.query(e,"SELECT id, commit_hash, status, analyzed_at, analysis FROM llm_analysis ORDER BY id DESC LIMIT ?",t).map(s=>{let o=JSON.parse(s.analysis);return{id:s.id,commitHash:s.commit_hash,status:s.status,analyzedAt:s.analyzed_at,patternCount:o.patterns.length}})}},mn=new Bo,Tt=mn});import Km from"node:crypto";import{homedir as Ym}from"node:os";import{join as Qm}from"node:path";function Le(){return Km.randomUUID()}var XT,Qt=v(()=>{"use strict";l(Le,"generateUUID");XT=Qm(Ym(),".prjct-cli","projects")});import{z as h}from"zod";var Zm,gn,eg,tg,rg,Jo,tl,rl,sl,zo,el,sg,ng,og,nl,ol,il,ig,ag,ev,Xo=v(()=>{"use strict";Ks();Zm=h.enum(["low","medium","high","critical"]),gn=h.enum(["feature","bug","improvement","chore"]),eg=h.enum(["active","backlog","previously_active"]),tg=h.enum(["pending","in_progress","completed","blocked","paused","failed","skipped"]),rg=h.enum(["task_completed","feature_shipped","idea_captured","session_started"]),Jo=h.object({title:h.string(),description:h.string(),filesChanged:h.array(h.object({path:h.string(),action:h.enum(["created","modified","deleted"])})),whatWasDone:h.array(h.string()).min(1),outputForNextAgent:h.string().min(1),notes:h.string().optional()}),tl=h.object({output:h.string().min(1,"Subtask output is required"),summary:Jo}),rl=h.object({id:h.string(),description:h.string(),domain:h.string(),agent:h.string(),status:tg,dependsOn:h.array(h.string()),startedAt:h.string().optional(),completedAt:h.string().optional(),output:h.string().optional(),summary:Jo.optional(),skipReason:h.string().optional(),blockReason:h.string().optional(),estimatedPoints:h.number().optional(),estimatedMinutes:h.number().optional()}),sl=h.object({completed:h.number(),total:h.number(),percentage:h.number()}),zo=h.object({id:h.string(),description:h.string(),type:gn.optional(),startedAt:h.string(),sessionId:h.string(),featureId:h.string().optional(),subtasks:h.array(rl).optional(),currentSubtaskIndex:h.number().optional(),subtaskProgress:sl.optional(),linearId:h.string().optional(),linearUuid:h.string().optional(),estimatedPoints:h.number().optional(),estimatedMinutes:h.number().optional(),modelMetadata:Er.optional(),tokensIn:h.number().optional(),tokensOut:h.number().optional(),parentDescription:h.string().optional(),branch:h.string().optional(),prUrl:h.string().optional()}),el=h.object({id:h.string(),description:h.string(),status:h.literal("paused"),startedAt:h.string(),pausedAt:h.string(),pauseReason:h.string().optional(),type:gn.optional(),sessionId:h.string().optional(),featureId:h.string().optional(),subtasks:h.array(rl).optional(),currentSubtaskIndex:h.number().optional(),subtaskProgress:sl.optional(),linearId:h.string().optional(),linearUuid:h.string().optional(),estimatedPoints:h.number().optional(),estimatedMinutes:h.number().optional(),modelMetadata:Er.optional(),tokensIn:h.number().optional(),tokensOut:h.number().optional()}),sg=h.object({stackConfirmed:h.array(h.string()).optional(),patternsDiscovered:h.array(h.string()).optional(),agentAccuracy:h.array(h.object({agent:h.string(),rating:h.enum(["helpful","neutral","inaccurate"]),note:h.string().optional()})).optional(),issuesEncountered:h.array(h.string()).optional()}),ng=h.object({taskId:h.string(),title:h.string(),classification:gn,startedAt:h.string(),completedAt:h.string(),subtaskCount:h.number(),subtaskSummaries:h.array(Jo),outcome:h.string(),branchName:h.string(),linearId:h.string().optional(),linearUuid:h.string().optional(),prUrl:h.string().optional(),feedback:sg.optional(),tokensIn:h.number().optional(),tokensOut:h.number().optional()}),og=zo.extend({workspaceId:h.string(),worktreePath:h.string().optional(),agentSessionId:h.string().optional(),jiraId:h.string().optional(),jiraUuid:h.string().optional(),dispatchedFrom:h.string().optional()}),nl=h.object({currentTask:zo.nullable(),previousTask:el.nullable().optional(),pausedTasks:h.array(el).optional(),taskHistory:h.array(ng).optional(),activeTasks:h.array(og).optional(),lastUpdated:h.string()}),ol=h.object({id:h.string(),description:h.string(),body:h.string().optional(),priority:Zm,type:gn,featureId:h.string().optional(),originFeature:h.string().optional(),completed:h.boolean(),completedAt:h.string().optional(),createdAt:h.string(),section:eg,agent:h.string().optional(),groupName:h.string().optional(),groupId:h.string().optional()}),il=h.object({tasks:h.array(ol),lastUpdated:h.string()}),ig=h.object({tasksToday:h.number(),tasksThisWeek:h.number(),streak:h.number(),velocity:h.string(),avgDuration:h.string()}),ag=h.object({type:rg,description:h.string(),timestamp:h.string(),duration:h.string().optional()}),ev=h.object({projectId:h.string(),currentTask:zo.nullable(),queue:h.array(ol),stats:ig,recentActivity:h.array(ag),lastSync:h.string()})});var ms,Ko,Zt,Yo=v(()=>{"use strict";ms={idle:{transitions:["task","next"],prompt:"p. task <description> Start working",description:"No active task"},working:{transitions:["done","pause"],prompt:"p. done Complete task | p. pause Switch context",description:"Task in progress"},paused:{transitions:["resume","task","ship"],prompt:"p. resume Continue | p. task <new> Start different | p. ship Ship directly",description:"Task paused"},completed:{transitions:["ship","task","next","pause","reopen"],prompt:"p. ship Ship it | p. task <next> Start next | p. reopen Reopen for rework",description:"Task completed"},shipped:{transitions:["task","next"],prompt:"p. task <description> Start new task",description:"Feature shipped"}},Ko=class{static{l(this,"WorkflowStateMachine")}getCurrentState(e,t){let r=null;if(t&&e?.activeTasks?.length&&(r=e.activeTasks.find(o=>o.workspaceId===t)),r||(r=e?.currentTask),!r)return(e?.pausedTasks?.length||0)>0||e?.previousTask?.status==="paused"?"paused":"idle";switch((typeof r.status=="string"?r.status:"").toLowerCase()){case"in_progress":case"working":return"working";case"paused":return"paused";case"completed":case"done":return"completed";case"shipped":return"shipped";default:return r?"working":"idle"}}canTransition(e,t){let r=ms[e];if(r.transitions.includes(t))return{valid:!0};let s=r.transitions.map(o=>`prjct ${o}`).join(", ");return{valid:!1,error:`Cannot run 'prjct ${t}' in ${e} state`,suggestion:`Valid commands: ${s}`}}getNextState(e,t){switch(t){case"task":return"working";case"done":return"completed";case"pause":return"paused";case"resume":return"working";case"ship":return"shipped";case"reopen":return"working";case"next":return e;default:return e}}getStateInfo(e){return ms[e]}getPrompt(e){return ms[e].prompt}getValidCommands(e){return ms[e].transitions}formatNextSteps(e){return ms[e].transitions.map(r=>{switch(r){case"task":return"p. task <desc> Start new task";case"done":return"p. done Complete current task";case"pause":return"p. pause Pause and switch context";case"resume":return"p. resume Continue paused task";case"ship":return"p. ship Ship the feature";case"reopen":return"p. reopen Reopen for rework";case"next":return"p. next View task queue";default:return`p. ${r}`}})}},Zt=new Ko});var vt,Qo,Fe,Ot=v(()=>{"use strict";Qt();ye();ae();vt={SHIPPED_RETENTION_DAYS:90,IDEA_DORMANT_DAYS:180,QUEUE_COMPLETED_DAYS:7,PAUSED_TASK_DAYS:30,MEMORY_MAX_ENTRIES:500},Qo=class{static{l(this,"ArchiveStorage")}archive(e,t){let r=Le(),s=E();return w.run(e,"INSERT INTO archives (id, entity_type, entity_id, entity_data, summary, archived_at, reason) VALUES (?, ?, ?, ?, ?, ?, ?)",r,t.entityType,t.entityId,JSON.stringify(t.entityData),t.summary??null,s,t.reason),r}archiveMany(e,t){if(t.length===0)return 0;let r=E();return w.transaction(e,s=>{let o=s.prepare("INSERT INTO archives (id, entity_type, entity_id, entity_data, summary, archived_at, reason) VALUES (?, ?, ?, ?, ?, ?, ?)");for(let i of t)o.run(Le(),i.entityType,i.entityId,JSON.stringify(i.entityData),i.summary??null,r,i.reason)}),t.length}getArchived(e,t,r=50){return t?w.query(e,"SELECT * FROM archives WHERE entity_type = ? ORDER BY archived_at DESC LIMIT ?",t,r):w.query(e,"SELECT * FROM archives ORDER BY archived_at DESC LIMIT ?",r)}getStats(e){let t=w.query(e,"SELECT entity_type, COUNT(*) as count FROM archives GROUP BY entity_type"),r={shipped:0,idea:0,queue_task:0,paused_task:0,memory_entry:0,total:0};for(let s of t){let o=s.entity_type;o in r&&(r[o]=s.count),r.total+=s.count}return r}restore(e,t){let r=w.get(e,"SELECT * FROM archives WHERE id = ?",t);return r?(w.run(e,"DELETE FROM archives WHERE id = ?",t),JSON.parse(r.entity_data)):null}pruneOldArchives(e,t){let r=new Date(Date.now()-t*24*60*60*1e3).toISOString(),s=this.getTotalCount(e);w.run(e,"DELETE FROM archives WHERE archived_at < ?",r);let o=this.getTotalCount(e);return s-o}getTotalCount(e){return w.get(e,"SELECT COUNT(*) as count FROM archives")?.count??0}},Fe=new Qo});var Zo,$,qe=v(()=>{"use strict";Qt();Xo();ye();Yo();Ot();_t();Zo=class extends De{static{l(this,"StateStorage")}constructor(){super("state.json",nl)}getDefault(){return{currentTask:null,previousTask:null,pausedTasks:[],taskHistory:[],activeTasks:[],lastUpdated:""}}getEventType(e){return`state.${e}d`}validateTransition(e,t){let r=Zt.getCurrentState(e),s=Zt.canTransition(r,t);if(!s.valid)throw new Error(`${s.error}. ${s.suggestion||""}`.trim())}async getCurrentTask(e){return(await this.read(e)).currentTask}async startTask(e,t){let r=await this.read(e);this.validateTransition(r,"task");let s={...t,startedAt:E()};return await this.update(e,o=>({...o,currentTask:s,lastUpdated:E()})),await this.publishEvent(e,"task.started",{taskId:s.id,description:s.description,startedAt:s.startedAt,sessionId:s.sessionId}),s}async updateCurrentTask(e,t){let r=await this.read(e);if(!r.currentTask)return null;let s={...r.currentTask,...t};return await this.update(e,o=>({...o,currentTask:s,lastUpdated:E()})),s}async completeTask(e,t){let r=await this.read(e),s=r.currentTask;if(!s)return null;this.validateTransition(r,"done");let o=E(),i=this.createTaskHistoryEntry(s,o,t),a=this.getTaskHistoryFromState(r),c=[i,...a].slice(0,this.maxTaskHistory);return await this.update(e,u=>({...u,currentTask:null,previousTask:null,taskHistory:c,lastUpdated:o})),await this.publishEvent(e,"task.completed",{taskId:s.id,description:s.description,startedAt:s.startedAt,completedAt:o}),s}createTaskHistoryEntry(e,t,r){let s=(e.subtasks||[]).filter(a=>a.status==="completed"&&a.summary).map(a=>a.summary),o=s.length>0?s.map(a=>a.title).join(", "):"Task completed",i={taskId:e.id,title:e.parentDescription||e.description,classification:e.type||"improvement",startedAt:e.startedAt,completedAt:t,subtaskCount:e.subtasks?.length||0,subtaskSummaries:s,outcome:o,branchName:e.branch||"unknown",linearId:e.linearId,linearUuid:e.linearUuid,prUrl:e.prUrl};return r&&(i.feedback=r),e.tokensIn&&(i.tokensIn=e.tokensIn),e.tokensOut&&(i.tokensOut=e.tokensOut),i}maxPausedTasks=5;maxTaskHistory=20;stalenessThresholdDays=30;async pauseTask(e,t){let r=await this.read(e);if(!r.currentTask)return null;this.validateTransition(r,"pause");let s={...r.currentTask,status:"paused",pausedAt:E(),pauseReason:t},o=this.getPausedTasksFromState(r),i=[s,...o].slice(0,this.maxPausedTasks);return await this.update(e,a=>({...a,currentTask:null,previousTask:null,pausedTasks:i,lastUpdated:E()})),await this.publishEvent(e,"task.paused",{taskId:s.id,description:s.description,pausedAt:s.pausedAt,reason:t,pausedCount:i.length}),s}async resumeTask(e,t){let r=await this.read(e),s=this.getPausedTasksFromState(r);if(s.length===0)return null;this.validateTransition(r,"resume");let o=0;if(t&&(o=s.findIndex(f=>f.id===t),o===-1))return null;let i=s[o],a=s.filter((f,S)=>S!==o),{status:c,pausedAt:u,pauseReason:d,...p}=i,m={...p,startedAt:E(),sessionId:i.sessionId??Le()};return await this.update(e,f=>({...f,currentTask:m,previousTask:null,pausedTasks:a,lastUpdated:E()})),await this.publishEvent(e,"task.resumed",{taskId:m.id,description:m.description,resumedAt:m.startedAt,remainingPaused:a.length}),m}getPausedTasksFromState(e){return Array.isArray(e.pausedTasks)&&e.pausedTasks.length>0?e.pausedTasks:e.previousTask?[e.previousTask]:[]}getTaskHistoryFromState(e){return e.taskHistory||[]}async getStalePausedTasks(e){let t=await this.read(e),r=this.getPausedTasksFromState(t),s=Date.now()-this.stalenessThresholdDays*24*60*60*1e3;return r.filter(o=>new Date(o.pausedAt).getTime()<s)}async archiveStalePausedTasks(e){let t=await this.read(e),r=this.getPausedTasksFromState(t),s=Date.now()-this.stalenessThresholdDays*24*60*60*1e3,o=r.filter(a=>new Date(a.pausedAt).getTime()<s),i=r.filter(a=>new Date(a.pausedAt).getTime()>=s);if(o.length===0)return[];Fe.archiveMany(e,o.map(a=>({entityType:"paused_task",entityId:a.id,entityData:a,summary:a.description,reason:"staleness"}))),await this.update(e,a=>({...a,pausedTasks:i,previousTask:null,lastUpdated:E()}));for(let a of o)await this.publishEvent(e,"task.archived",{taskId:a.id,description:a.description,pausedAt:a.pausedAt,reason:"staleness"});return o}async clearTask(e){await this.update(e,()=>({currentTask:null,previousTask:null,pausedTasks:[],activeTasks:[],lastUpdated:E()}))}async hasTask(e){let t=await this.read(e),r=this.getPausedTasksFromState(t);return t.currentTask!==null||r.length>0}async getPausedTask(e){let t=await this.read(e);return this.getPausedTasksFromState(t)[0]||null}async getAllPausedTasks(e){let t=await this.read(e);return this.getPausedTasksFromState(t)}async getTaskHistory(e){let t=await this.read(e);return this.getTaskHistoryFromState(t)}async getMostRecentTask(e){let t=await this.read(e);return this.getTaskHistoryFromState(t)[0]||null}async getTaskHistoryByType(e,t){let r=await this.read(e);return this.getTaskHistoryFromState(r).filter(o=>o.classification===t)}async getAggregatedFeedback(e){let r=(await this.getTaskHistory(e)).filter(m=>m.feedback),s=[],o=[],i=[],a=[];for(let m of r){let f=m.feedback;Array.isArray(f.stackConfirmed)&&s.push(...f.stackConfirmed),Array.isArray(f.patternsDiscovered)&&o.push(...f.patternsDiscovered),Array.isArray(f.agentAccuracy)&&i.push(...f.agentAccuracy),Array.isArray(f.issuesEncountered)&&a.push(...f.issuesEncountered)}let c=[...new Set(s)],u=[...new Set(o)],d=new Map;for(let m of a)d.set(m,(d.get(m)||0)+1);let p=[...d.entries()].filter(([m,f])=>f>=2).map(([m])=>m);return{stackConfirmed:c,patternsDiscovered:u,agentAccuracy:i,issuesEncountered:[...new Set(a)],knownGotchas:p}}async startTaskInWorkspace(e,t,r){let s={...t,workspaceId:r,startedAt:E()};return await this.update(e,o=>({...o,activeTasks:[...o.activeTasks||[],s],lastUpdated:E()})),await this.publishEvent(e,"task.started",{taskId:s.id,description:s.description,startedAt:s.startedAt,sessionId:s.sessionId,workspaceId:r}),s}async getCurrentTaskForWorkspace(e,t){return((await this.read(e)).activeTasks||[]).find(s=>s.workspaceId===t)??null}async completeTaskInWorkspace(e,t,r){let s=await this.read(e),i=(s.activeTasks||[]).find(p=>p.workspaceId===t);if(!i)return null;let a=E(),c=this.createTaskHistoryEntry(i,a,r),u=this.getTaskHistoryFromState(s),d=[c,...u].slice(0,this.maxTaskHistory);return await this.update(e,p=>({...p,activeTasks:(p.activeTasks||[]).filter(m=>m.workspaceId!==t),taskHistory:d,lastUpdated:a})),await this.publishEvent(e,"task.completed",{taskId:i.id,description:i.description,startedAt:i.startedAt,completedAt:a,workspaceId:t}),i}async getActiveTasks(e){return(await this.read(e)).activeTasks||[]}async getActiveTaskCount(e){return((await this.read(e)).activeTasks||[]).length}async updateWorkspaceTask(e,t,r){let o=(await this.read(e)).activeTasks||[],i=o.findIndex(c=>c.workspaceId===t);if(i===-1)return null;let a={...o[i],...r,workspaceId:t};return await this.update(e,c=>{let u=[...c.activeTasks||[]];return u[i]=a,{...c,activeTasks:u,lastUpdated:E()}}),a}async addTokens(e,t,r){let s=await this.read(e);if(!s.currentTask)return null;let o=(s.currentTask.tokensIn||0)+t,i=(s.currentTask.tokensOut||0)+r;return await this.update(e,a=>({...a,currentTask:{...a.currentTask,tokensIn:o,tokensOut:i},lastUpdated:E()})),{tokensIn:o,tokensOut:i}}async createSubtasks(e,t){let r=await this.read(e);if(!r.currentTask)return;let s=t.map((o,i)=>({...o,status:i===0?"in_progress":"pending",startedAt:i===0?E():void 0,dependsOn:o.dependsOn||[]}));await this.update(e,o=>({...o,currentTask:{...o.currentTask,subtasks:s,currentSubtaskIndex:0,subtaskProgress:{completed:0,total:s.length,percentage:0}},lastUpdated:E()})),await this.publishEvent(e,"subtasks.created",{taskId:r.currentTask.id,subtaskCount:s.length,subtasks:s.map(o=>({id:o.id,description:o.description,domain:o.domain}))})}async completeSubtask(e,t){let r=tl.safeParse(t);if(!r.success){let S=r.error.issues.map(x=>`${x.path.join(".")}: ${x.message}`);throw new Error(`Subtask completion requires handoff data:
519
519
  ${S.join(`
520
520
  `)}`)}let{output:s,summary:o}=r.data,i=await this.read(e);if(!i.currentTask?.subtasks)return null;let a=i.currentTask.currentSubtaskIndex||0,c=i.currentTask.subtasks[a];if(!c)return null;let u=[...i.currentTask.subtasks];u[a]={...c,status:"completed",completedAt:E(),output:s,summary:o};let d=u.filter(S=>S.status==="completed").length,p=u.length,m=Math.round(d/p*100),f=a+1;return f<u.length&&(u[f]={...u[f],status:"in_progress",startedAt:E()}),await this.update(e,S=>({...S,currentTask:{...S.currentTask,subtasks:u,currentSubtaskIndex:f<p?f:a,subtaskProgress:{completed:d,total:p,percentage:m}},lastUpdated:E()})),await this.publishEvent(e,"subtask.completed",{taskId:i.currentTask.id,subtaskId:c.id,description:c.description,output:s,handoff:o.outputForNextAgent,filesChanged:o.filesChanged.length,progress:{completed:d,total:p,percentage:m}}),f<p?u[f]:null}async getCurrentSubtask(e){let t=await this.read(e);if(!t.currentTask?.subtasks)return null;let r=t.currentTask.currentSubtaskIndex||0;return t.currentTask.subtasks[r]||null}async getNextSubtask(e){let t=await this.read(e);if(!t.currentTask?.subtasks)return null;let r=(t.currentTask.currentSubtaskIndex||0)+1;return t.currentTask.subtasks[r]||null}async getPreviousSubtask(e){let t=await this.read(e);if(!t.currentTask?.subtasks)return null;let r=(t.currentTask.currentSubtaskIndex||0)-1;return r<0?null:t.currentTask.subtasks[r]||null}async getPreviousHandoff(e){let t=await this.getPreviousSubtask(e);return t?.summary?.outputForNextAgent?{fromSubtask:t.description,outputForNextAgent:t.summary.outputForNextAgent,filesChanged:t.summary.filesChanged,whatWasDone:t.summary.whatWasDone}:null}async getSubtasks(e){return(await this.read(e)).currentTask?.subtasks||[]}async getSubtaskProgress(e){return(await this.read(e)).currentTask?.subtaskProgress||null}async hasSubtasks(e){return((await this.read(e)).currentTask?.subtasks?.length||0)>0}async areAllSubtasksComplete(e){let t=await this.read(e);return t.currentTask?.subtasks?t.currentTask.subtasks.every(r=>r.status==="completed"||r.status==="failed"||r.status==="skipped"):!0}async failSubtask(e,t){let r=await this.read(e);if(!r.currentTask?.subtasks)return null;let s=r.currentTask.currentSubtaskIndex||0,o=r.currentTask.subtasks[s];if(!o)return null;let i=[...r.currentTask.subtasks];i[s]={...o,status:"failed",completedAt:E(),output:`Failed: ${t}`};let a=s+1,c=i.length;a<c&&(i[a]={...i[a],status:"in_progress",startedAt:E()});let u=i.filter(p=>p.status==="completed"||p.status==="failed"||p.status==="skipped").length,d=Math.round(u/c*100);return await this.update(e,p=>({...p,currentTask:{...p.currentTask,subtasks:i,currentSubtaskIndex:a<c?a:s,subtaskProgress:{completed:u,total:c,percentage:d}},lastUpdated:E()})),await this.publishEvent(e,"subtask.failed",{taskId:r.currentTask.id,subtaskId:o.id,description:o.description,error:t}),a<c?i[a]:null}async skipSubtask(e,t){let r=await this.read(e);if(!r.currentTask?.subtasks)return null;let s=r.currentTask.currentSubtaskIndex||0,o=r.currentTask.subtasks[s];if(!o)return null;let i=[...r.currentTask.subtasks];i[s]={...o,status:"skipped",completedAt:E(),output:`Skipped: ${t}`,skipReason:t};let a=s+1,c=i.length;a<c&&(i[a]={...i[a],status:"in_progress",startedAt:E()});let u=i.filter(p=>p.status==="completed"||p.status==="failed"||p.status==="skipped").length,d=Math.round(u/c*100);return await this.update(e,p=>({...p,currentTask:{...p.currentTask,subtasks:i,currentSubtaskIndex:a<c?a:s,subtaskProgress:{completed:u,total:c,percentage:d}},lastUpdated:E()})),await this.publishEvent(e,"subtask.skipped",{taskId:r.currentTask.id,subtaskId:o.id,description:o.description,reason:t}),a<c?i[a]:null}async blockSubtask(e,t){let r=await this.read(e);if(!r.currentTask?.subtasks)return null;let s=r.currentTask.currentSubtaskIndex||0,o=r.currentTask.subtasks[s];if(!o)return null;let i=[...r.currentTask.subtasks];i[s]={...o,status:"blocked",output:`Blocked: ${t}`,blockReason:t};let a=s+1,c=i.length;return a<c&&(i[a]={...i[a],status:"in_progress",startedAt:E()}),await this.update(e,u=>({...u,currentTask:{...u.currentTask,subtasks:i,currentSubtaskIndex:a<c?a:s},lastUpdated:E()})),await this.publishEvent(e,"subtask.blocked",{taskId:r.currentTask.id,subtaskId:o.id,description:o.description,blocker:t}),a<c?i[a]:null}},$=new Zo});import al from"node:fs/promises";import cl from"node:path";async function ti(n,e,t,r){let[s,o,i,a]=await Promise.all([ug(n,e,r),dg(n),pg(n),mg(n)]);return{project:{name:r.name,ecosystem:r.ecosystem,languages:r.languages,frameworks:r.frameworks,fileCount:r.fileCount,projectType:r.projectType},git:{branch:t.branch,recentCommits:t.recentCommits.slice(0,cg).map(c=>({message:c.message,date:c.date})),hasChanges:t.hasChanges,weeklyCommits:t.weeklyCommits},codeSamples:s,existingPatterns:o,taskHistory:i,previousAnalysis:a??void 0}}async function ug(n,e,t){let r=[],s=[...t.frameworks.map(a=>a.toLowerCase()),"config","router","middleware","service","model","schema","database","api","auth"].join(" "),o=zc(n,s,ei*2);for(let a of o){if(r.length>=ei)break;try{let c=cl.join(e,a.path),u=await al.readFile(c,"utf-8");u.length>fn*3?r.push({path:a.path,content:`${u.slice(0,fn)}
521
521
  // ... truncated`,reason:`BM25 score: ${a.score.toFixed(2)} (truncated, ${u.length} chars)`}):r.push({path:a.path,content:u.slice(0,fn),reason:`BM25 score: ${a.score.toFixed(2)}`})}catch{}}let i=["package.json","tsconfig.json","src/index.ts","src/main.ts","app.ts"];for(let a of i){if(r.length>=ei)break;if(!r.some(c=>c.path===a))try{let c=cl.join(e,a),u=await al.readFile(c,"utf-8");r.push({path:a,content:u.slice(0,fn),reason:"entry point"})}catch{}}return r}async function dg(n){try{let e=await Me.getActive(n);return e?{patterns:(e.patterns??[]).map(t=>({name:t.name,description:t.description})),antiPatterns:(e.antiPatterns??[]).map(t=>({issue:t.issue,file:t.file,suggestion:t.suggestion}))}:{patterns:[],antiPatterns:[]}}catch{return{patterns:[],antiPatterns:[]}}}async function pg(n){try{return(await $.getTaskHistory(n)).slice(0,lg).map(t=>({description:t.title,status:t.classification,branch:t.branchName}))}catch{return[]}}function mg(n){try{let e=Tt.getActiveSummary(n);return Promise.resolve(e)}catch(e){return L.debug("Failed to get previous LLM analysis summary",{error:e}),Promise.resolve(null)}}var fn,ei,cg,lg,ll=v(()=>{"use strict";Uo();ds();ps();qe();It();fn=800,ei=6,cg=8,lg=5;l(ti,"buildAnalysisPayload");l(ug,"selectCodeSamples");l(dg,"getExistingPatterns");l(pg,"getTaskHistory");l(mg,"getPreviousAnalysisSummary")});var ul=v(()=>{"use strict"});import bt from"chalk";function dl(n){return Math.ceil(n.length/4)}function pl(n){let e=n.split(`
@@ -499,7 +499,7 @@ Total affected: ${o.allAffected.length} files`),{content:[{type:"text",text:a.jo
499
499
  `)}]}}return{content:[{type:"text",text:["## Import Graph Stats",`Files: ${s.fileCount}`,`Edges: ${s.edgeCount}`,`Built: ${s.builtAt}`].join(`
500
500
  `)}]}})),t.tool("prjct_cochange","Files that historically change together (Jaccard similarity from git history)",{projectPath:A.string().describe("Project directory path"),seedFiles:A.array(A.string()).describe("Seed files to find co-change partners for"),rebuild:A.boolean().optional().default(!1).describe("Force rebuild the co-change matrix"),maxResults:A.number().optional().default(10).describe("Max results (default 10)")},S("prjct_cochange",async e=>{let r=await P(e.projectPath),s=e.rebuild?null:Xt(r);s||(s=await sr(e.projectPath,r));let o=Ut(e.seedFiles,s).slice(0,e.maxResults);if(o.length===0)return{content:[{type:"text",text:"No co-change partners found."}]};let i=["## Co-Change Partners",`Seeds: ${e.seedFiles.join(", ")}`,`Commits analyzed: ${s.commitsAnalyzed}`,""];for(let a of o)i.push(`- ${a.path} (similarity: ${Math.round(a.score*100)}%)`);return{content:[{type:"text",text:i.join(`
501
501
  `)}]}})),t.tool("prjct_related_context","Combined: import neighbors + co-change partners for seed files",{projectPath:A.string().describe("Project directory path"),seedFiles:A.array(A.string()).describe("Seed files to find related context for"),maxResults:A.number().optional().default(15).describe("Max results (default 15)")},S("prjct_related_context",async e=>{let r=await P(e.projectPath),s=et(r),o=s?Je(e.seedFiles,s):[],i=Xt(r),a=i?Ut(e.seedFiles,i):[],u=new Map;for(let d of o)u.set(d.path,{importScore:d.score,cochangeScore:0});for(let d of a){let g=u.get(d.path);g?g.cochangeScore=d.score:u.set(d.path,{importScore:0,cochangeScore:d.score})}let p=Array.from(u.entries()).map(([d,g])=>({path:d,combined:g.importScore*.6+g.cochangeScore*.4,importScore:g.importScore,cochangeScore:g.cochangeScore})).sort((d,g)=>g.combined-d.combined).slice(0,e.maxResults);if(p.length===0)return{content:[{type:"text",text:"No related files found. Run `prjct sync` to build indexes."}]};let m=["## Related Context",`Seeds: ${e.seedFiles.join(", ")}`,""];for(let d of p){let g=[];d.importScore>0&&g.push(`import: ${d.importScore.toFixed(2)}`),d.cochangeScore>0&&g.push(`cochange: ${Math.round(d.cochangeScore*100)}%`),m.push(`- ${d.path} (${g.join(", ")})`)}return{content:[{type:"text",text:m.join(`
502
- `)}]}}))}c(pr,"registerCodeIntelTools");import{z as H}from"zod";import qs from"node:crypto";import{homedir as zs}from"node:os";import{join as Ys}from"node:path";function $(){return qs.randomUUID()}c($,"generateUUID");var na=Ys(zs(),".prjct-cli","projects");Rt();import{z as l}from"zod";var Js=l.enum(["low","medium","high","critical"]),Tt=l.enum(["feature","bug","improvement","chore"]),Vs=l.enum(["active","backlog","previously_active"]),Ks=l.enum(["pending","in_progress","completed","blocked","paused","failed","skipped"]),Qs=l.enum(["task_completed","feature_shipped","idea_captured","session_started"]),Jt=l.object({title:l.string(),description:l.string(),filesChanged:l.array(l.object({path:l.string(),action:l.enum(["created","modified","deleted"])})),whatWasDone:l.array(l.string()).min(1),outputForNextAgent:l.string().min(1),notes:l.string().optional()}),mr=l.object({output:l.string().min(1,"Subtask output is required"),summary:Jt}),gr=l.object({id:l.string(),description:l.string(),domain:l.string(),agent:l.string(),status:Ks,dependsOn:l.array(l.string()),startedAt:l.string().optional(),completedAt:l.string().optional(),output:l.string().optional(),summary:Jt.optional(),skipReason:l.string().optional(),blockReason:l.string().optional(),estimatedPoints:l.number().optional(),estimatedMinutes:l.number().optional()}),fr=l.object({completed:l.number(),total:l.number(),percentage:l.number()}),Vt=l.object({id:l.string(),description:l.string(),type:Tt.optional(),startedAt:l.string(),sessionId:l.string(),featureId:l.string().optional(),subtasks:l.array(gr).optional(),currentSubtaskIndex:l.number().optional(),subtaskProgress:fr.optional(),linearId:l.string().optional(),linearUuid:l.string().optional(),estimatedPoints:l.number().optional(),estimatedMinutes:l.number().optional(),modelMetadata:ut.optional(),tokensIn:l.number().optional(),tokensOut:l.number().optional(),parentDescription:l.string().optional(),branch:l.string().optional(),prUrl:l.string().optional()}),dr=l.object({id:l.string(),description:l.string(),status:l.literal("paused"),startedAt:l.string(),pausedAt:l.string(),pauseReason:l.string().optional(),type:Tt.optional(),sessionId:l.string().optional(),featureId:l.string().optional(),subtasks:l.array(gr).optional(),currentSubtaskIndex:l.number().optional(),subtaskProgress:fr.optional(),linearId:l.string().optional(),linearUuid:l.string().optional(),estimatedPoints:l.number().optional(),estimatedMinutes:l.number().optional(),modelMetadata:ut.optional(),tokensIn:l.number().optional(),tokensOut:l.number().optional()}),Zs=l.object({stackConfirmed:l.array(l.string()).optional(),patternsDiscovered:l.array(l.string()).optional(),agentAccuracy:l.array(l.object({agent:l.string(),rating:l.enum(["helpful","neutral","inaccurate"]),note:l.string().optional()})).optional(),issuesEncountered:l.array(l.string()).optional()}),tn=l.object({taskId:l.string(),title:l.string(),classification:Tt,startedAt:l.string(),completedAt:l.string(),subtaskCount:l.number(),subtaskSummaries:l.array(Jt),outcome:l.string(),branchName:l.string(),linearId:l.string().optional(),linearUuid:l.string().optional(),prUrl:l.string().optional(),feedback:Zs.optional(),tokensIn:l.number().optional(),tokensOut:l.number().optional()}),en=Vt.extend({workspaceId:l.string(),worktreePath:l.string().optional(),agentSessionId:l.string().optional(),jiraId:l.string().optional(),jiraUuid:l.string().optional(),dispatchedFrom:l.string().optional()}),hr=l.object({currentTask:Vt.nullable(),previousTask:dr.nullable().optional(),pausedTasks:l.array(dr).optional(),taskHistory:l.array(tn).optional(),activeTasks:l.array(en).optional(),lastUpdated:l.string()}),yr=l.object({id:l.string(),description:l.string(),body:l.string().optional(),priority:Js,type:Tt,featureId:l.string().optional(),originFeature:l.string().optional(),completed:l.boolean(),completedAt:l.string().optional(),createdAt:l.string(),section:Vs,agent:l.string().optional(),groupName:l.string().optional(),groupId:l.string().optional()}),Tr=l.object({tasks:l.array(yr),lastUpdated:l.string()}),rn=l.object({tasksToday:l.number(),tasksThisWeek:l.number(),streak:l.number(),velocity:l.string(),avgDuration:l.string()}),sn=l.object({type:Qs,description:l.string(),timestamp:l.string(),duration:l.string().optional()}),ua=l.object({projectId:l.string(),currentTask:Vt.nullable(),queue:l.array(yr),stats:rn,recentActivity:l.array(sn),lastSync:l.string()});var st={idle:{transitions:["task","next"],prompt:"p. task <description> Start working",description:"No active task"},working:{transitions:["done","pause"],prompt:"p. done Complete task | p. pause Switch context",description:"Task in progress"},paused:{transitions:["resume","task","ship"],prompt:"p. resume Continue | p. task <new> Start different | p. ship Ship directly",description:"Task paused"},completed:{transitions:["ship","task","next","pause","reopen"],prompt:"p. ship Ship it | p. task <next> Start next | p. reopen Reopen for rework",description:"Task completed"},shipped:{transitions:["task","next"],prompt:"p. task <description> Start new task",description:"Feature shipped"}},Kt=class{static{c(this,"WorkflowStateMachine")}getCurrentState(t,e){let r=null;if(e&&t?.activeTasks?.length&&(r=t.activeTasks.find(o=>o.workspaceId===e)),r||(r=t?.currentTask),!r)return(t?.pausedTasks?.length||0)>0||t?.previousTask?.status==="paused"?"paused":"idle";switch((typeof r.status=="string"?r.status:"").toLowerCase()){case"in_progress":case"working":return"working";case"paused":return"paused";case"completed":case"done":return"completed";case"shipped":return"shipped";default:return r?"working":"idle"}}canTransition(t,e){let r=st[t];if(r.transitions.includes(e))return{valid:!0};let s=r.transitions.map(o=>`p. ${o}`).join(", ");return{valid:!1,error:`Cannot run 'p. ${e}' in ${t} state`,suggestion:`Valid commands: ${s}`}}getNextState(t,e){switch(e){case"task":return"working";case"done":return"completed";case"pause":return"paused";case"resume":return"working";case"ship":return"shipped";case"reopen":return"working";case"next":return t;default:return t}}getStateInfo(t){return st[t]}getPrompt(t){return st[t].prompt}getValidCommands(t){return st[t].transitions}formatNextSteps(t){return st[t].transitions.map(r=>{switch(r){case"task":return"p. task <desc> Start new task";case"done":return"p. done Complete current task";case"pause":return"p. pause Pause and switch context";case"resume":return"p. resume Continue paused task";case"ship":return"p. ship Ship the feature";case"reopen":return"p. reopen Reopen for rework";case"next":return"p. next View task queue";default:return`p. ${r}`}})}},Qt=new Kt;var nt={SHIPPED_RETENTION_DAYS:90,IDEA_DORMANT_DAYS:180,QUEUE_COMPLETED_DAYS:7,PAUSED_TASK_DAYS:30,MEMORY_MAX_ENTRIES:500},Zt=class{static{c(this,"ArchiveStorage")}archive(t,e){let r=$(),s=f();return T.run(t,"INSERT INTO archives (id, entity_type, entity_id, entity_data, summary, archived_at, reason) VALUES (?, ?, ?, ?, ?, ?, ?)",r,e.entityType,e.entityId,JSON.stringify(e.entityData),e.summary??null,s,e.reason),r}archiveMany(t,e){if(e.length===0)return 0;let r=f();return T.transaction(t,s=>{let o=s.prepare("INSERT INTO archives (id, entity_type, entity_id, entity_data, summary, archived_at, reason) VALUES (?, ?, ?, ?, ?, ?, ?)");for(let i of e)o.run($(),i.entityType,i.entityId,JSON.stringify(i.entityData),i.summary??null,r,i.reason)}),e.length}getArchived(t,e,r=50){return e?T.query(t,"SELECT * FROM archives WHERE entity_type = ? ORDER BY archived_at DESC LIMIT ?",e,r):T.query(t,"SELECT * FROM archives ORDER BY archived_at DESC LIMIT ?",r)}getStats(t){let e=T.query(t,"SELECT entity_type, COUNT(*) as count FROM archives GROUP BY entity_type"),r={shipped:0,idea:0,queue_task:0,paused_task:0,memory_entry:0,total:0};for(let s of e){let o=s.entity_type;o in r&&(r[o]=s.count),r.total+=s.count}return r}restore(t,e){let r=T.get(t,"SELECT * FROM archives WHERE id = ?",e);return r?(T.run(t,"DELETE FROM archives WHERE id = ?",e),JSON.parse(r.entity_data)):null}pruneOldArchives(t,e){let r=new Date(Date.now()-e*24*60*60*1e3).toISOString(),s=this.getTotalCount(t);T.run(t,"DELETE FROM archives WHERE archived_at < ?",r);let o=this.getTotalCount(t);return s-o}getTotalCount(t){return T.get(t,"SELECT COUNT(*) as count FROM archives")?.count??0}},V=new Zt;U();var te=class{static{c(this,"SyncEventBus")}async publish(t){let e=b.getSyncPendingPath(t.projectId),r=await ct(e,[])??[],s=Array.isArray(r)?r:[];s.push(t),await j(e,s)}async getPending(t){let e=b.getSyncPendingPath(t),r=await ct(e,[])??[];return Array.isArray(r)?r:[]}async clearPending(t){let e=b.getSyncPendingPath(t);await j(e,[])}async updateLastSync(t){let e=b.getLastSyncPath(t),r={timestamp:f(),success:!0};await j(e,r)}async getLastSync(t){let e=b.getLastSyncPath(t);return await ct(e,null)}},Er=new te;At();var K=class{static{c(this,"StorageManager")}filename;cache;constructor(t,e){this.filename=t,this.cache=new lt({ttl:5e3,maxSize:50})}getStoreKey(){return this.filename.replace(".json","")}async read(t){let e=this.cache.get(t);if(e!==null)return e;try{let r=T.getDoc(t,this.getStoreKey());if(r!==null)return this.cache.set(t,r),r}catch{}return this.getDefault()}async write(t,e){T.setDoc(t,this.getStoreKey(),e),this.cache.set(t,e)}async update(t,e){let r=await this.read(t),s=e(r);return await this.write(t,s),s}async publishEvent(t,e,r){let s={type:e,path:[this.filename.replace(".json","")],data:r,timestamp:f(),projectId:t};await Er.publish(s)}async publishEntityEvent(t,e,r,s){let o=`${e}.${r}`,i={...s,timestamp:f()};await this.publishEvent(t,o,i)}async exists(t){try{return T.hasDoc(t,this.getStoreKey())}catch{return!1}}clearCache(t){t?this.cache.delete(t):this.cache.clear()}getCacheStats(){return this.cache.stats()}};var ee=class extends K{static{c(this,"StateStorage")}constructor(){super("state.json",hr)}getDefault(){return{currentTask:null,previousTask:null,pausedTasks:[],taskHistory:[],activeTasks:[],lastUpdated:""}}getEventType(t){return`state.${t}d`}validateTransition(t,e){let r=Qt.getCurrentState(t),s=Qt.canTransition(r,e);if(!s.valid)throw new Error(`${s.error}. ${s.suggestion||""}`.trim())}async getCurrentTask(t){return(await this.read(t)).currentTask}async startTask(t,e){let r=await this.read(t);this.validateTransition(r,"task");let s={...e,startedAt:f()};return await this.update(t,o=>({...o,currentTask:s,lastUpdated:f()})),await this.publishEvent(t,"task.started",{taskId:s.id,description:s.description,startedAt:s.startedAt,sessionId:s.sessionId}),s}async updateCurrentTask(t,e){let r=await this.read(t);if(!r.currentTask)return null;let s={...r.currentTask,...e};return await this.update(t,o=>({...o,currentTask:s,lastUpdated:f()})),s}async completeTask(t,e){let r=await this.read(t),s=r.currentTask;if(!s)return null;this.validateTransition(r,"done");let o=f(),i=this.createTaskHistoryEntry(s,o,e),a=this.getTaskHistoryFromState(r),u=[i,...a].slice(0,this.maxTaskHistory);return await this.update(t,p=>({...p,currentTask:null,previousTask:null,taskHistory:u,lastUpdated:o})),await this.publishEvent(t,"task.completed",{taskId:s.id,description:s.description,startedAt:s.startedAt,completedAt:o}),s}createTaskHistoryEntry(t,e,r){let s=(t.subtasks||[]).filter(a=>a.status==="completed"&&a.summary).map(a=>a.summary),o=s.length>0?s.map(a=>a.title).join(", "):"Task completed",i={taskId:t.id,title:t.parentDescription||t.description,classification:t.type||"improvement",startedAt:t.startedAt,completedAt:e,subtaskCount:t.subtasks?.length||0,subtaskSummaries:s,outcome:o,branchName:t.branch||"unknown",linearId:t.linearId,linearUuid:t.linearUuid,prUrl:t.prUrl};return r&&(i.feedback=r),t.tokensIn&&(i.tokensIn=t.tokensIn),t.tokensOut&&(i.tokensOut=t.tokensOut),i}maxPausedTasks=5;maxTaskHistory=20;stalenessThresholdDays=30;async pauseTask(t,e){let r=await this.read(t);if(!r.currentTask)return null;this.validateTransition(r,"pause");let s={...r.currentTask,status:"paused",pausedAt:f(),pauseReason:e},o=this.getPausedTasksFromState(r),i=[s,...o].slice(0,this.maxPausedTasks);return await this.update(t,a=>({...a,currentTask:null,previousTask:null,pausedTasks:i,lastUpdated:f()})),await this.publishEvent(t,"task.paused",{taskId:s.id,description:s.description,pausedAt:s.pausedAt,reason:e,pausedCount:i.length}),s}async resumeTask(t,e){let r=await this.read(t),s=this.getPausedTasksFromState(r);if(s.length===0)return null;this.validateTransition(r,"resume");let o=0;if(e&&(o=s.findIndex(h=>h.id===e),o===-1))return null;let i=s[o],a=s.filter((h,M)=>M!==o),{status:u,pausedAt:p,pauseReason:m,...d}=i,g={...d,startedAt:f(),sessionId:i.sessionId??$()};return await this.update(t,h=>({...h,currentTask:g,previousTask:null,pausedTasks:a,lastUpdated:f()})),await this.publishEvent(t,"task.resumed",{taskId:g.id,description:g.description,resumedAt:g.startedAt,remainingPaused:a.length}),g}getPausedTasksFromState(t){return Array.isArray(t.pausedTasks)&&t.pausedTasks.length>0?t.pausedTasks:t.previousTask?[t.previousTask]:[]}getTaskHistoryFromState(t){return t.taskHistory||[]}async getStalePausedTasks(t){let e=await this.read(t),r=this.getPausedTasksFromState(e),s=Date.now()-this.stalenessThresholdDays*24*60*60*1e3;return r.filter(o=>new Date(o.pausedAt).getTime()<s)}async archiveStalePausedTasks(t){let e=await this.read(t),r=this.getPausedTasksFromState(e),s=Date.now()-this.stalenessThresholdDays*24*60*60*1e3,o=r.filter(a=>new Date(a.pausedAt).getTime()<s),i=r.filter(a=>new Date(a.pausedAt).getTime()>=s);if(o.length===0)return[];V.archiveMany(t,o.map(a=>({entityType:"paused_task",entityId:a.id,entityData:a,summary:a.description,reason:"staleness"}))),await this.update(t,a=>({...a,pausedTasks:i,previousTask:null,lastUpdated:f()}));for(let a of o)await this.publishEvent(t,"task.archived",{taskId:a.id,description:a.description,pausedAt:a.pausedAt,reason:"staleness"});return o}async clearTask(t){await this.update(t,()=>({currentTask:null,previousTask:null,pausedTasks:[],activeTasks:[],lastUpdated:f()}))}async hasTask(t){let e=await this.read(t),r=this.getPausedTasksFromState(e);return e.currentTask!==null||r.length>0}async getPausedTask(t){let e=await this.read(t);return this.getPausedTasksFromState(e)[0]||null}async getAllPausedTasks(t){let e=await this.read(t);return this.getPausedTasksFromState(e)}async getTaskHistory(t){let e=await this.read(t);return this.getTaskHistoryFromState(e)}async getMostRecentTask(t){let e=await this.read(t);return this.getTaskHistoryFromState(e)[0]||null}async getTaskHistoryByType(t,e){let r=await this.read(t);return this.getTaskHistoryFromState(r).filter(o=>o.classification===e)}async getAggregatedFeedback(t){let r=(await this.getTaskHistory(t)).filter(g=>g.feedback),s=[],o=[],i=[],a=[];for(let g of r){let h=g.feedback;Array.isArray(h.stackConfirmed)&&s.push(...h.stackConfirmed),Array.isArray(h.patternsDiscovered)&&o.push(...h.patternsDiscovered),Array.isArray(h.agentAccuracy)&&i.push(...h.agentAccuracy),Array.isArray(h.issuesEncountered)&&a.push(...h.issuesEncountered)}let u=[...new Set(s)],p=[...new Set(o)],m=new Map;for(let g of a)m.set(g,(m.get(g)||0)+1);let d=[...m.entries()].filter(([g,h])=>h>=2).map(([g])=>g);return{stackConfirmed:u,patternsDiscovered:p,agentAccuracy:i,issuesEncountered:[...new Set(a)],knownGotchas:d}}async startTaskInWorkspace(t,e,r){let s={...e,workspaceId:r,startedAt:f()};return await this.update(t,o=>({...o,activeTasks:[...o.activeTasks||[],s],lastUpdated:f()})),await this.publishEvent(t,"task.started",{taskId:s.id,description:s.description,startedAt:s.startedAt,sessionId:s.sessionId,workspaceId:r}),s}async getCurrentTaskForWorkspace(t,e){return((await this.read(t)).activeTasks||[]).find(s=>s.workspaceId===e)??null}async completeTaskInWorkspace(t,e,r){let s=await this.read(t),i=(s.activeTasks||[]).find(d=>d.workspaceId===e);if(!i)return null;let a=f(),u=this.createTaskHistoryEntry(i,a,r),p=this.getTaskHistoryFromState(s),m=[u,...p].slice(0,this.maxTaskHistory);return await this.update(t,d=>({...d,activeTasks:(d.activeTasks||[]).filter(g=>g.workspaceId!==e),taskHistory:m,lastUpdated:a})),await this.publishEvent(t,"task.completed",{taskId:i.id,description:i.description,startedAt:i.startedAt,completedAt:a,workspaceId:e}),i}async getActiveTasks(t){return(await this.read(t)).activeTasks||[]}async getActiveTaskCount(t){return((await this.read(t)).activeTasks||[]).length}async updateWorkspaceTask(t,e,r){let o=(await this.read(t)).activeTasks||[],i=o.findIndex(u=>u.workspaceId===e);if(i===-1)return null;let a={...o[i],...r,workspaceId:e};return await this.update(t,u=>{let p=[...u.activeTasks||[]];return p[i]=a,{...u,activeTasks:p,lastUpdated:f()}}),a}async addTokens(t,e,r){let s=await this.read(t);if(!s.currentTask)return null;let o=(s.currentTask.tokensIn||0)+e,i=(s.currentTask.tokensOut||0)+r;return await this.update(t,a=>({...a,currentTask:{...a.currentTask,tokensIn:o,tokensOut:i},lastUpdated:f()})),{tokensIn:o,tokensOut:i}}async createSubtasks(t,e){let r=await this.read(t);if(!r.currentTask)return;let s=e.map((o,i)=>({...o,status:i===0?"in_progress":"pending",startedAt:i===0?f():void 0,dependsOn:o.dependsOn||[]}));await this.update(t,o=>({...o,currentTask:{...o.currentTask,subtasks:s,currentSubtaskIndex:0,subtaskProgress:{completed:0,total:s.length,percentage:0}},lastUpdated:f()})),await this.publishEvent(t,"subtasks.created",{taskId:r.currentTask.id,subtaskCount:s.length,subtasks:s.map(o=>({id:o.id,description:o.description,domain:o.domain}))})}async completeSubtask(t,e){let r=mr.safeParse(e);if(!r.success){let M=r.error.issues.map(it=>`${it.path.join(".")}: ${it.message}`);throw new Error(`Subtask completion requires handoff data:
502
+ `)}]}}))}c(pr,"registerCodeIntelTools");import{z as H}from"zod";import qs from"node:crypto";import{homedir as zs}from"node:os";import{join as Ys}from"node:path";function $(){return qs.randomUUID()}c($,"generateUUID");var na=Ys(zs(),".prjct-cli","projects");Rt();import{z as l}from"zod";var Js=l.enum(["low","medium","high","critical"]),Tt=l.enum(["feature","bug","improvement","chore"]),Vs=l.enum(["active","backlog","previously_active"]),Ks=l.enum(["pending","in_progress","completed","blocked","paused","failed","skipped"]),Qs=l.enum(["task_completed","feature_shipped","idea_captured","session_started"]),Jt=l.object({title:l.string(),description:l.string(),filesChanged:l.array(l.object({path:l.string(),action:l.enum(["created","modified","deleted"])})),whatWasDone:l.array(l.string()).min(1),outputForNextAgent:l.string().min(1),notes:l.string().optional()}),mr=l.object({output:l.string().min(1,"Subtask output is required"),summary:Jt}),gr=l.object({id:l.string(),description:l.string(),domain:l.string(),agent:l.string(),status:Ks,dependsOn:l.array(l.string()),startedAt:l.string().optional(),completedAt:l.string().optional(),output:l.string().optional(),summary:Jt.optional(),skipReason:l.string().optional(),blockReason:l.string().optional(),estimatedPoints:l.number().optional(),estimatedMinutes:l.number().optional()}),fr=l.object({completed:l.number(),total:l.number(),percentage:l.number()}),Vt=l.object({id:l.string(),description:l.string(),type:Tt.optional(),startedAt:l.string(),sessionId:l.string(),featureId:l.string().optional(),subtasks:l.array(gr).optional(),currentSubtaskIndex:l.number().optional(),subtaskProgress:fr.optional(),linearId:l.string().optional(),linearUuid:l.string().optional(),estimatedPoints:l.number().optional(),estimatedMinutes:l.number().optional(),modelMetadata:ut.optional(),tokensIn:l.number().optional(),tokensOut:l.number().optional(),parentDescription:l.string().optional(),branch:l.string().optional(),prUrl:l.string().optional()}),dr=l.object({id:l.string(),description:l.string(),status:l.literal("paused"),startedAt:l.string(),pausedAt:l.string(),pauseReason:l.string().optional(),type:Tt.optional(),sessionId:l.string().optional(),featureId:l.string().optional(),subtasks:l.array(gr).optional(),currentSubtaskIndex:l.number().optional(),subtaskProgress:fr.optional(),linearId:l.string().optional(),linearUuid:l.string().optional(),estimatedPoints:l.number().optional(),estimatedMinutes:l.number().optional(),modelMetadata:ut.optional(),tokensIn:l.number().optional(),tokensOut:l.number().optional()}),Zs=l.object({stackConfirmed:l.array(l.string()).optional(),patternsDiscovered:l.array(l.string()).optional(),agentAccuracy:l.array(l.object({agent:l.string(),rating:l.enum(["helpful","neutral","inaccurate"]),note:l.string().optional()})).optional(),issuesEncountered:l.array(l.string()).optional()}),tn=l.object({taskId:l.string(),title:l.string(),classification:Tt,startedAt:l.string(),completedAt:l.string(),subtaskCount:l.number(),subtaskSummaries:l.array(Jt),outcome:l.string(),branchName:l.string(),linearId:l.string().optional(),linearUuid:l.string().optional(),prUrl:l.string().optional(),feedback:Zs.optional(),tokensIn:l.number().optional(),tokensOut:l.number().optional()}),en=Vt.extend({workspaceId:l.string(),worktreePath:l.string().optional(),agentSessionId:l.string().optional(),jiraId:l.string().optional(),jiraUuid:l.string().optional(),dispatchedFrom:l.string().optional()}),hr=l.object({currentTask:Vt.nullable(),previousTask:dr.nullable().optional(),pausedTasks:l.array(dr).optional(),taskHistory:l.array(tn).optional(),activeTasks:l.array(en).optional(),lastUpdated:l.string()}),yr=l.object({id:l.string(),description:l.string(),body:l.string().optional(),priority:Js,type:Tt,featureId:l.string().optional(),originFeature:l.string().optional(),completed:l.boolean(),completedAt:l.string().optional(),createdAt:l.string(),section:Vs,agent:l.string().optional(),groupName:l.string().optional(),groupId:l.string().optional()}),Tr=l.object({tasks:l.array(yr),lastUpdated:l.string()}),rn=l.object({tasksToday:l.number(),tasksThisWeek:l.number(),streak:l.number(),velocity:l.string(),avgDuration:l.string()}),sn=l.object({type:Qs,description:l.string(),timestamp:l.string(),duration:l.string().optional()}),ua=l.object({projectId:l.string(),currentTask:Vt.nullable(),queue:l.array(yr),stats:rn,recentActivity:l.array(sn),lastSync:l.string()});var st={idle:{transitions:["task","next"],prompt:"p. task <description> Start working",description:"No active task"},working:{transitions:["done","pause"],prompt:"p. done Complete task | p. pause Switch context",description:"Task in progress"},paused:{transitions:["resume","task","ship"],prompt:"p. resume Continue | p. task <new> Start different | p. ship Ship directly",description:"Task paused"},completed:{transitions:["ship","task","next","pause","reopen"],prompt:"p. ship Ship it | p. task <next> Start next | p. reopen Reopen for rework",description:"Task completed"},shipped:{transitions:["task","next"],prompt:"p. task <description> Start new task",description:"Feature shipped"}},Kt=class{static{c(this,"WorkflowStateMachine")}getCurrentState(t,e){let r=null;if(e&&t?.activeTasks?.length&&(r=t.activeTasks.find(o=>o.workspaceId===e)),r||(r=t?.currentTask),!r)return(t?.pausedTasks?.length||0)>0||t?.previousTask?.status==="paused"?"paused":"idle";switch((typeof r.status=="string"?r.status:"").toLowerCase()){case"in_progress":case"working":return"working";case"paused":return"paused";case"completed":case"done":return"completed";case"shipped":return"shipped";default:return r?"working":"idle"}}canTransition(t,e){let r=st[t];if(r.transitions.includes(e))return{valid:!0};let s=r.transitions.map(o=>`prjct ${o}`).join(", ");return{valid:!1,error:`Cannot run 'prjct ${e}' in ${t} state`,suggestion:`Valid commands: ${s}`}}getNextState(t,e){switch(e){case"task":return"working";case"done":return"completed";case"pause":return"paused";case"resume":return"working";case"ship":return"shipped";case"reopen":return"working";case"next":return t;default:return t}}getStateInfo(t){return st[t]}getPrompt(t){return st[t].prompt}getValidCommands(t){return st[t].transitions}formatNextSteps(t){return st[t].transitions.map(r=>{switch(r){case"task":return"p. task <desc> Start new task";case"done":return"p. done Complete current task";case"pause":return"p. pause Pause and switch context";case"resume":return"p. resume Continue paused task";case"ship":return"p. ship Ship the feature";case"reopen":return"p. reopen Reopen for rework";case"next":return"p. next View task queue";default:return`p. ${r}`}})}},Qt=new Kt;var nt={SHIPPED_RETENTION_DAYS:90,IDEA_DORMANT_DAYS:180,QUEUE_COMPLETED_DAYS:7,PAUSED_TASK_DAYS:30,MEMORY_MAX_ENTRIES:500},Zt=class{static{c(this,"ArchiveStorage")}archive(t,e){let r=$(),s=f();return T.run(t,"INSERT INTO archives (id, entity_type, entity_id, entity_data, summary, archived_at, reason) VALUES (?, ?, ?, ?, ?, ?, ?)",r,e.entityType,e.entityId,JSON.stringify(e.entityData),e.summary??null,s,e.reason),r}archiveMany(t,e){if(e.length===0)return 0;let r=f();return T.transaction(t,s=>{let o=s.prepare("INSERT INTO archives (id, entity_type, entity_id, entity_data, summary, archived_at, reason) VALUES (?, ?, ?, ?, ?, ?, ?)");for(let i of e)o.run($(),i.entityType,i.entityId,JSON.stringify(i.entityData),i.summary??null,r,i.reason)}),e.length}getArchived(t,e,r=50){return e?T.query(t,"SELECT * FROM archives WHERE entity_type = ? ORDER BY archived_at DESC LIMIT ?",e,r):T.query(t,"SELECT * FROM archives ORDER BY archived_at DESC LIMIT ?",r)}getStats(t){let e=T.query(t,"SELECT entity_type, COUNT(*) as count FROM archives GROUP BY entity_type"),r={shipped:0,idea:0,queue_task:0,paused_task:0,memory_entry:0,total:0};for(let s of e){let o=s.entity_type;o in r&&(r[o]=s.count),r.total+=s.count}return r}restore(t,e){let r=T.get(t,"SELECT * FROM archives WHERE id = ?",e);return r?(T.run(t,"DELETE FROM archives WHERE id = ?",e),JSON.parse(r.entity_data)):null}pruneOldArchives(t,e){let r=new Date(Date.now()-e*24*60*60*1e3).toISOString(),s=this.getTotalCount(t);T.run(t,"DELETE FROM archives WHERE archived_at < ?",r);let o=this.getTotalCount(t);return s-o}getTotalCount(t){return T.get(t,"SELECT COUNT(*) as count FROM archives")?.count??0}},V=new Zt;U();var te=class{static{c(this,"SyncEventBus")}async publish(t){let e=b.getSyncPendingPath(t.projectId),r=await ct(e,[])??[],s=Array.isArray(r)?r:[];s.push(t),await j(e,s)}async getPending(t){let e=b.getSyncPendingPath(t),r=await ct(e,[])??[];return Array.isArray(r)?r:[]}async clearPending(t){let e=b.getSyncPendingPath(t);await j(e,[])}async updateLastSync(t){let e=b.getLastSyncPath(t),r={timestamp:f(),success:!0};await j(e,r)}async getLastSync(t){let e=b.getLastSyncPath(t);return await ct(e,null)}},Er=new te;At();var K=class{static{c(this,"StorageManager")}filename;cache;constructor(t,e){this.filename=t,this.cache=new lt({ttl:5e3,maxSize:50})}getStoreKey(){return this.filename.replace(".json","")}async read(t){let e=this.cache.get(t);if(e!==null)return e;try{let r=T.getDoc(t,this.getStoreKey());if(r!==null)return this.cache.set(t,r),r}catch{}return this.getDefault()}async write(t,e){T.setDoc(t,this.getStoreKey(),e),this.cache.set(t,e)}async update(t,e){let r=await this.read(t),s=e(r);return await this.write(t,s),s}async publishEvent(t,e,r){let s={type:e,path:[this.filename.replace(".json","")],data:r,timestamp:f(),projectId:t};await Er.publish(s)}async publishEntityEvent(t,e,r,s){let o=`${e}.${r}`,i={...s,timestamp:f()};await this.publishEvent(t,o,i)}async exists(t){try{return T.hasDoc(t,this.getStoreKey())}catch{return!1}}clearCache(t){t?this.cache.delete(t):this.cache.clear()}getCacheStats(){return this.cache.stats()}};var ee=class extends K{static{c(this,"StateStorage")}constructor(){super("state.json",hr)}getDefault(){return{currentTask:null,previousTask:null,pausedTasks:[],taskHistory:[],activeTasks:[],lastUpdated:""}}getEventType(t){return`state.${t}d`}validateTransition(t,e){let r=Qt.getCurrentState(t),s=Qt.canTransition(r,e);if(!s.valid)throw new Error(`${s.error}. ${s.suggestion||""}`.trim())}async getCurrentTask(t){return(await this.read(t)).currentTask}async startTask(t,e){let r=await this.read(t);this.validateTransition(r,"task");let s={...e,startedAt:f()};return await this.update(t,o=>({...o,currentTask:s,lastUpdated:f()})),await this.publishEvent(t,"task.started",{taskId:s.id,description:s.description,startedAt:s.startedAt,sessionId:s.sessionId}),s}async updateCurrentTask(t,e){let r=await this.read(t);if(!r.currentTask)return null;let s={...r.currentTask,...e};return await this.update(t,o=>({...o,currentTask:s,lastUpdated:f()})),s}async completeTask(t,e){let r=await this.read(t),s=r.currentTask;if(!s)return null;this.validateTransition(r,"done");let o=f(),i=this.createTaskHistoryEntry(s,o,e),a=this.getTaskHistoryFromState(r),u=[i,...a].slice(0,this.maxTaskHistory);return await this.update(t,p=>({...p,currentTask:null,previousTask:null,taskHistory:u,lastUpdated:o})),await this.publishEvent(t,"task.completed",{taskId:s.id,description:s.description,startedAt:s.startedAt,completedAt:o}),s}createTaskHistoryEntry(t,e,r){let s=(t.subtasks||[]).filter(a=>a.status==="completed"&&a.summary).map(a=>a.summary),o=s.length>0?s.map(a=>a.title).join(", "):"Task completed",i={taskId:t.id,title:t.parentDescription||t.description,classification:t.type||"improvement",startedAt:t.startedAt,completedAt:e,subtaskCount:t.subtasks?.length||0,subtaskSummaries:s,outcome:o,branchName:t.branch||"unknown",linearId:t.linearId,linearUuid:t.linearUuid,prUrl:t.prUrl};return r&&(i.feedback=r),t.tokensIn&&(i.tokensIn=t.tokensIn),t.tokensOut&&(i.tokensOut=t.tokensOut),i}maxPausedTasks=5;maxTaskHistory=20;stalenessThresholdDays=30;async pauseTask(t,e){let r=await this.read(t);if(!r.currentTask)return null;this.validateTransition(r,"pause");let s={...r.currentTask,status:"paused",pausedAt:f(),pauseReason:e},o=this.getPausedTasksFromState(r),i=[s,...o].slice(0,this.maxPausedTasks);return await this.update(t,a=>({...a,currentTask:null,previousTask:null,pausedTasks:i,lastUpdated:f()})),await this.publishEvent(t,"task.paused",{taskId:s.id,description:s.description,pausedAt:s.pausedAt,reason:e,pausedCount:i.length}),s}async resumeTask(t,e){let r=await this.read(t),s=this.getPausedTasksFromState(r);if(s.length===0)return null;this.validateTransition(r,"resume");let o=0;if(e&&(o=s.findIndex(h=>h.id===e),o===-1))return null;let i=s[o],a=s.filter((h,M)=>M!==o),{status:u,pausedAt:p,pauseReason:m,...d}=i,g={...d,startedAt:f(),sessionId:i.sessionId??$()};return await this.update(t,h=>({...h,currentTask:g,previousTask:null,pausedTasks:a,lastUpdated:f()})),await this.publishEvent(t,"task.resumed",{taskId:g.id,description:g.description,resumedAt:g.startedAt,remainingPaused:a.length}),g}getPausedTasksFromState(t){return Array.isArray(t.pausedTasks)&&t.pausedTasks.length>0?t.pausedTasks:t.previousTask?[t.previousTask]:[]}getTaskHistoryFromState(t){return t.taskHistory||[]}async getStalePausedTasks(t){let e=await this.read(t),r=this.getPausedTasksFromState(e),s=Date.now()-this.stalenessThresholdDays*24*60*60*1e3;return r.filter(o=>new Date(o.pausedAt).getTime()<s)}async archiveStalePausedTasks(t){let e=await this.read(t),r=this.getPausedTasksFromState(e),s=Date.now()-this.stalenessThresholdDays*24*60*60*1e3,o=r.filter(a=>new Date(a.pausedAt).getTime()<s),i=r.filter(a=>new Date(a.pausedAt).getTime()>=s);if(o.length===0)return[];V.archiveMany(t,o.map(a=>({entityType:"paused_task",entityId:a.id,entityData:a,summary:a.description,reason:"staleness"}))),await this.update(t,a=>({...a,pausedTasks:i,previousTask:null,lastUpdated:f()}));for(let a of o)await this.publishEvent(t,"task.archived",{taskId:a.id,description:a.description,pausedAt:a.pausedAt,reason:"staleness"});return o}async clearTask(t){await this.update(t,()=>({currentTask:null,previousTask:null,pausedTasks:[],activeTasks:[],lastUpdated:f()}))}async hasTask(t){let e=await this.read(t),r=this.getPausedTasksFromState(e);return e.currentTask!==null||r.length>0}async getPausedTask(t){let e=await this.read(t);return this.getPausedTasksFromState(e)[0]||null}async getAllPausedTasks(t){let e=await this.read(t);return this.getPausedTasksFromState(e)}async getTaskHistory(t){let e=await this.read(t);return this.getTaskHistoryFromState(e)}async getMostRecentTask(t){let e=await this.read(t);return this.getTaskHistoryFromState(e)[0]||null}async getTaskHistoryByType(t,e){let r=await this.read(t);return this.getTaskHistoryFromState(r).filter(o=>o.classification===e)}async getAggregatedFeedback(t){let r=(await this.getTaskHistory(t)).filter(g=>g.feedback),s=[],o=[],i=[],a=[];for(let g of r){let h=g.feedback;Array.isArray(h.stackConfirmed)&&s.push(...h.stackConfirmed),Array.isArray(h.patternsDiscovered)&&o.push(...h.patternsDiscovered),Array.isArray(h.agentAccuracy)&&i.push(...h.agentAccuracy),Array.isArray(h.issuesEncountered)&&a.push(...h.issuesEncountered)}let u=[...new Set(s)],p=[...new Set(o)],m=new Map;for(let g of a)m.set(g,(m.get(g)||0)+1);let d=[...m.entries()].filter(([g,h])=>h>=2).map(([g])=>g);return{stackConfirmed:u,patternsDiscovered:p,agentAccuracy:i,issuesEncountered:[...new Set(a)],knownGotchas:d}}async startTaskInWorkspace(t,e,r){let s={...e,workspaceId:r,startedAt:f()};return await this.update(t,o=>({...o,activeTasks:[...o.activeTasks||[],s],lastUpdated:f()})),await this.publishEvent(t,"task.started",{taskId:s.id,description:s.description,startedAt:s.startedAt,sessionId:s.sessionId,workspaceId:r}),s}async getCurrentTaskForWorkspace(t,e){return((await this.read(t)).activeTasks||[]).find(s=>s.workspaceId===e)??null}async completeTaskInWorkspace(t,e,r){let s=await this.read(t),i=(s.activeTasks||[]).find(d=>d.workspaceId===e);if(!i)return null;let a=f(),u=this.createTaskHistoryEntry(i,a,r),p=this.getTaskHistoryFromState(s),m=[u,...p].slice(0,this.maxTaskHistory);return await this.update(t,d=>({...d,activeTasks:(d.activeTasks||[]).filter(g=>g.workspaceId!==e),taskHistory:m,lastUpdated:a})),await this.publishEvent(t,"task.completed",{taskId:i.id,description:i.description,startedAt:i.startedAt,completedAt:a,workspaceId:e}),i}async getActiveTasks(t){return(await this.read(t)).activeTasks||[]}async getActiveTaskCount(t){return((await this.read(t)).activeTasks||[]).length}async updateWorkspaceTask(t,e,r){let o=(await this.read(t)).activeTasks||[],i=o.findIndex(u=>u.workspaceId===e);if(i===-1)return null;let a={...o[i],...r,workspaceId:e};return await this.update(t,u=>{let p=[...u.activeTasks||[]];return p[i]=a,{...u,activeTasks:p,lastUpdated:f()}}),a}async addTokens(t,e,r){let s=await this.read(t);if(!s.currentTask)return null;let o=(s.currentTask.tokensIn||0)+e,i=(s.currentTask.tokensOut||0)+r;return await this.update(t,a=>({...a,currentTask:{...a.currentTask,tokensIn:o,tokensOut:i},lastUpdated:f()})),{tokensIn:o,tokensOut:i}}async createSubtasks(t,e){let r=await this.read(t);if(!r.currentTask)return;let s=e.map((o,i)=>({...o,status:i===0?"in_progress":"pending",startedAt:i===0?f():void 0,dependsOn:o.dependsOn||[]}));await this.update(t,o=>({...o,currentTask:{...o.currentTask,subtasks:s,currentSubtaskIndex:0,subtaskProgress:{completed:0,total:s.length,percentage:0}},lastUpdated:f()})),await this.publishEvent(t,"subtasks.created",{taskId:r.currentTask.id,subtaskCount:s.length,subtasks:s.map(o=>({id:o.id,description:o.description,domain:o.domain}))})}async completeSubtask(t,e){let r=mr.safeParse(e);if(!r.success){let M=r.error.issues.map(it=>`${it.path.join(".")}: ${it.message}`);throw new Error(`Subtask completion requires handoff data:
503
503
  ${M.join(`
504
504
  `)}`)}let{output:s,summary:o}=r.data,i=await this.read(t);if(!i.currentTask?.subtasks)return null;let a=i.currentTask.currentSubtaskIndex||0,u=i.currentTask.subtasks[a];if(!u)return null;let p=[...i.currentTask.subtasks];p[a]={...u,status:"completed",completedAt:f(),output:s,summary:o};let m=p.filter(M=>M.status==="completed").length,d=p.length,g=Math.round(m/d*100),h=a+1;return h<p.length&&(p[h]={...p[h],status:"in_progress",startedAt:f()}),await this.update(t,M=>({...M,currentTask:{...M.currentTask,subtasks:p,currentSubtaskIndex:h<d?h:a,subtaskProgress:{completed:m,total:d,percentage:g}},lastUpdated:f()})),await this.publishEvent(t,"subtask.completed",{taskId:i.currentTask.id,subtaskId:u.id,description:u.description,output:s,handoff:o.outputForNextAgent,filesChanged:o.filesChanged.length,progress:{completed:m,total:d,percentage:g}}),h<d?p[h]:null}async getCurrentSubtask(t){let e=await this.read(t);if(!e.currentTask?.subtasks)return null;let r=e.currentTask.currentSubtaskIndex||0;return e.currentTask.subtasks[r]||null}async getNextSubtask(t){let e=await this.read(t);if(!e.currentTask?.subtasks)return null;let r=(e.currentTask.currentSubtaskIndex||0)+1;return e.currentTask.subtasks[r]||null}async getPreviousSubtask(t){let e=await this.read(t);if(!e.currentTask?.subtasks)return null;let r=(e.currentTask.currentSubtaskIndex||0)-1;return r<0?null:e.currentTask.subtasks[r]||null}async getPreviousHandoff(t){let e=await this.getPreviousSubtask(t);return e?.summary?.outputForNextAgent?{fromSubtask:e.description,outputForNextAgent:e.summary.outputForNextAgent,filesChanged:e.summary.filesChanged,whatWasDone:e.summary.whatWasDone}:null}async getSubtasks(t){return(await this.read(t)).currentTask?.subtasks||[]}async getSubtaskProgress(t){return(await this.read(t)).currentTask?.subtaskProgress||null}async hasSubtasks(t){return((await this.read(t)).currentTask?.subtasks?.length||0)>0}async areAllSubtasksComplete(t){let e=await this.read(t);return e.currentTask?.subtasks?e.currentTask.subtasks.every(r=>r.status==="completed"||r.status==="failed"||r.status==="skipped"):!0}async failSubtask(t,e){let r=await this.read(t);if(!r.currentTask?.subtasks)return null;let s=r.currentTask.currentSubtaskIndex||0,o=r.currentTask.subtasks[s];if(!o)return null;let i=[...r.currentTask.subtasks];i[s]={...o,status:"failed",completedAt:f(),output:`Failed: ${e}`};let a=s+1,u=i.length;a<u&&(i[a]={...i[a],status:"in_progress",startedAt:f()});let p=i.filter(d=>d.status==="completed"||d.status==="failed"||d.status==="skipped").length,m=Math.round(p/u*100);return await this.update(t,d=>({...d,currentTask:{...d.currentTask,subtasks:i,currentSubtaskIndex:a<u?a:s,subtaskProgress:{completed:p,total:u,percentage:m}},lastUpdated:f()})),await this.publishEvent(t,"subtask.failed",{taskId:r.currentTask.id,subtaskId:o.id,description:o.description,error:e}),a<u?i[a]:null}async skipSubtask(t,e){let r=await this.read(t);if(!r.currentTask?.subtasks)return null;let s=r.currentTask.currentSubtaskIndex||0,o=r.currentTask.subtasks[s];if(!o)return null;let i=[...r.currentTask.subtasks];i[s]={...o,status:"skipped",completedAt:f(),output:`Skipped: ${e}`,skipReason:e};let a=s+1,u=i.length;a<u&&(i[a]={...i[a],status:"in_progress",startedAt:f()});let p=i.filter(d=>d.status==="completed"||d.status==="failed"||d.status==="skipped").length,m=Math.round(p/u*100);return await this.update(t,d=>({...d,currentTask:{...d.currentTask,subtasks:i,currentSubtaskIndex:a<u?a:s,subtaskProgress:{completed:p,total:u,percentage:m}},lastUpdated:f()})),await this.publishEvent(t,"subtask.skipped",{taskId:r.currentTask.id,subtaskId:o.id,description:o.description,reason:e}),a<u?i[a]:null}async blockSubtask(t,e){let r=await this.read(t);if(!r.currentTask?.subtasks)return null;let s=r.currentTask.currentSubtaskIndex||0,o=r.currentTask.subtasks[s];if(!o)return null;let i=[...r.currentTask.subtasks];i[s]={...o,status:"blocked",output:`Blocked: ${e}`,blockReason:e};let a=s+1,u=i.length;return a<u&&(i[a]={...i[a],status:"in_progress",startedAt:f()}),await this.update(t,p=>({...p,currentTask:{...p.currentTask,subtasks:i,currentSubtaskIndex:a<u?a:s},lastUpdated:f()})),await this.publishEvent(t,"subtask.blocked",{taskId:r.currentTask.id,subtaskId:o.id,description:o.description,blocker:e}),a<u?i[a]:null}},Q=new ee;W();z();import nn from"node:fs/promises";import Et from"node:path";var on={frontend:["component","page","view","ui","layout","style","css","scss","sass","hook","context","store","redux","zustand","react","vue","svelte","angular","next","nuxt","app","client"],backend:["api","route","controller","service","middleware","handler","resolver","schema","model","entity","repository","server","socket","graphql","rest","trpc"],database:["migration","seed","schema","model","entity","repository","prisma","drizzle","sequelize","typeorm","mongoose","knex","sql","db"],auth:["auth","login","logout","session","token","jwt","oauth","passport","credential","permission","role","user","account"],testing:["test","spec","e2e","integration","unit","mock","fixture","stub","jest","vitest","cypress","playwright"],config:["config","env","setting","constant","option","tsconfig","eslint","prettier","vite","webpack","rollup"],infra:["docker","compose","kubernetes","k8s","ci","cd","github","gitlab","jenkins","terraform","ansible","deploy"],util:["util","helper","lib","common","shared","core","base","abstract"]},an=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".go",".rs",".java",".kt",".swift",".rb",".php",".c",".cpp",".h",".hpp",".cs",".vue",".svelte"]),cn=new Set(["node_modules",".git","dist","build",".next",".nuxt",".output","coverage",".cache","__pycache__",".pytest_cache","vendor","target",".turbo",".vercel"]);async function kr(n,t,e={}){let r=Date.now(),s=e.maxFiles??30,o=e.minScore??.1,i=e.includeTests??!1,a=un(n),u=await ln(t),p=await pn(t),m=[];for(let g of u){if(!i&&mn(g))continue;let h=dn(g,a,p,e.historicalBoosts);h.score>=o&&m.push(h)}m.sort((g,h)=>h.score-g.score);let d=m.slice(0,s);return{files:d,metrics:{filesScanned:u.length,filesReturned:d.length,scanDuration:Date.now()-r}}}c(kr,"findRelevantFiles");function un(n){let t=n.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean),e=new Set(["a","an","the","and","or","but","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","must","shall","can","need","to","of","in","for","on","with","at","by","from","as","into","through","during","before","after","above","below","between","under","again","further","then","once","here","there","when","where","why","how","all","each","few","more","most","other","some","such","no","nor","not","only","own","same","so","than","too","very","just","add","create","make","implement","fix","update","change","modify","remove","delete","new"]);return t.filter(r=>!e.has(r)&&r.length>2)}c(un,"extractKeywords");async function ln(n){let t=[];async function e(r,s=""){try{let o=await nn.readdir(r,{withFileTypes:!0});for(let i of o){let a=Et.join(r,i.name),u=Et.join(s,i.name);if(i.isDirectory()){if(cn.has(i.name)||i.name.startsWith("."))continue;await e(a,u)}else if(i.isFile()){let p=Et.extname(i.name).toLowerCase();an.has(p)&&t.push(u)}}}catch(o){N(o)}}return c(e,"walk"),await e(n),t}c(ln,"getAllCodeFiles");async function pn(n){let t=new Map;try{let{stdout:e}=await k(`git log -30 --pretty=format:"%H %ct" --name-only | awk '
505
505
  /^[a-f0-9]{40}/ { commit=$1; timestamp=$2; next }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "prjct-cli",
3
- "version": "2.0.0-alpha.12",
3
+ "version": "2.1.0",
4
4
  "description": "Context layer for AI agents. Project context for Claude Code, Gemini CLI, and more.",
5
5
  "main": "dist/bin/prjct.mjs",
6
6
  "bin": {